hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 8,
"code_window": [
"import { defineNuxtConfig } from 'nuxt'\n",
"import { addComponent } from '@nuxt/kit'\n",
"\n",
"export default defineNuxtConfig({\n",
" buildDir: process.env.NITRO_BUILD_DIR,\n",
" builder: process.env.TEST_WITH_WEBPACK ? 'webpack' : 'vite',\n",
" extends: [\n",
" './extends/bar',\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" app: {\n",
" head: {\n",
" charset: 'utf-8',\n",
" link: [undefined],\n",
" meta: [{ name: 'viewport', content: 'width=1024, initial-scale=1' }, { charset: 'utf-8' }]\n",
" }\n",
" },\n"
],
"file_path": "test/fixtures/basic/nuxt.config.ts",
"type": "add",
"edit_start_line_idx": 4
}
|
import { resolve } from 'pathe'
import { withoutLeadingSlash } from 'ufo'
export default {
/**
* Configuration that will be passed directly to Vite.
*
* See https://vitejs.dev/config for more information.
* Please note that not all vite options are supported in Nuxt.
*
* @type {typeof import('../src/types/config').ViteConfig}
* @version 3
*/
vite: {
root: {
$resolve: (val, get) => val ?? get('srcDir'),
},
mode: {
$resolve: (val, get) => val ?? (get('dev') ? 'development' : 'production'),
},
logLevel: 'warn',
define: {
$resolve: (val, get) => ({
'process.dev': get('dev'),
...val || {}
})
},
resolve: {
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
},
publicDir: {
$resolve: (val, get) => val ?? resolve(get('srcDir'), get('dir').public),
},
vue: {
isProduction: {
$resolve: (val, get) => val ?? !get('dev'),
},
template: { compilerOptions: {
$resolve: (val, get) => val ?? get('vue').compilerOptions }
},
},
optimizeDeps: {
exclude: {
$resolve: (val, get) => [
...val || [],
...get('build.transpile').filter(i => typeof i === 'string'),
'vue-demi'
],
},
},
esbuild: {
jsxFactory: 'h',
jsxFragment: 'Fragment',
tsconfigRaw: '{}'
},
clearScreen: false,
build: {
assetsDir: {
$resolve: (val, get) => val ?? withoutLeadingSlash(get('app').buildAssetsDir),
},
emptyOutDir: false,
},
server: {
fs: {
strict: false,
allow: {
$resolve: (val, get) => [
get('buildDir'),
get('srcDir'),
get('rootDir'),
...get('modulesDir'),
...val ?? []
]
}
}
}
}
}
|
packages/schema/src/config/vite.ts
| 0 |
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
|
[
0.0003868618223350495,
0.0002051298797596246,
0.0001661930582486093,
0.00017205081530846655,
0.00007065283716656268
] |
{
"id": 8,
"code_window": [
"import { defineNuxtConfig } from 'nuxt'\n",
"import { addComponent } from '@nuxt/kit'\n",
"\n",
"export default defineNuxtConfig({\n",
" buildDir: process.env.NITRO_BUILD_DIR,\n",
" builder: process.env.TEST_WITH_WEBPACK ? 'webpack' : 'vite',\n",
" extends: [\n",
" './extends/bar',\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" app: {\n",
" head: {\n",
" charset: 'utf-8',\n",
" link: [undefined],\n",
" meta: [{ name: 'viewport', content: 'width=1024, initial-scale=1' }, { charset: 'utf-8' }]\n",
" }\n",
" },\n"
],
"file_path": "test/fixtures/basic/nuxt.config.ts",
"type": "add",
"edit_start_line_idx": 4
}
|
import { promises as fsp } from 'node:fs'
import { join, resolve } from 'pathe'
import { createApp, lazyHandle } from 'h3'
import { listen } from 'listhen'
import { writeTypes } from '../utils/prepare'
import { loadKit } from '../utils/kit'
import { clearDir } from '../utils/fs'
import { overrideEnv } from '../utils/env'
import { defineNuxtCommand } from './index'
export default defineNuxtCommand({
meta: {
name: 'analyze',
usage: 'npx nuxi analyze [rootDir]',
description: 'Build nuxt and analyze production bundle (experimental)'
},
async invoke (args) {
overrideEnv('production')
const rootDir = resolve(args._[0] || '.')
const statsDir = join(rootDir, '.nuxt/stats')
const { loadNuxt, buildNuxt } = await loadKit(rootDir)
const nuxt = await loadNuxt({
rootDir,
config: {
build: {
analyze: true
}
}
})
await clearDir(nuxt.options.buildDir)
await writeTypes(nuxt)
await buildNuxt(nuxt)
const app = createApp()
const serveFile = (filePath: string) => lazyHandle(async () => {
const contents = await fsp.readFile(filePath, 'utf-8')
return (_req, res) => { res.end(contents) }
})
console.warn('Do not deploy analyze results! Use `nuxi build` before deploying.')
console.info('Starting stats server...')
app.use('/client', serveFile(join(statsDir, 'client.html')))
app.use('/nitro', serveFile(join(statsDir, 'nitro.html')))
app.use(() => `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Nuxt Bundle Stats (experimental)</title>
</head>
<h1>Nuxt Bundle Stats (experimental)</h1>
<ul>
<li>
<a href="/nitro">Nitro server bundle stats</a>
</li>
<li>
<a href="/client">Client bundle stats</a>
</li>
</ul>
</html>`)
await listen(app)
return 'wait' as const
}
})
|
packages/nuxi/src/commands/analyze.ts
| 0 |
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
|
[
0.009617306292057037,
0.002451942302286625,
0.00016439301543869078,
0.00023193465312942863,
0.003639163915067911
] |
{
"id": 0,
"code_window": [
" publicBase,\n",
" assetsDir,\n",
" inlineLimit\n",
" )\n",
" assets.set(fileName, content)\n",
" debug(`${id} -> ${url}`)\n",
" return `export default ${JSON.stringify(url)}`\n",
" }\n",
" },\n",
"\n",
" generateBundle(_options, bundle) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" debug(`${id} -> ${url.startsWith('data:') ? `base64 inlined` : url}`)\n"
],
"file_path": "src/node/buildPluginAsset.ts",
"type": "replace",
"edit_start_line_idx": 79
}
|
import path from 'path'
import { Plugin } from 'rollup'
import { resolveAsset, registerAssets } from './buildPluginAsset'
import { loadPostcssConfig } from './config'
import { isExternalUrl, asyncReplace } from './utils'
const debug = require('debug')('vite:build:css')
const urlRE = /(url\(\s*['"]?)([^"')]+)(["']?\s*\))/
export const createBuildCssPlugin = (
root: string,
publicBase: string,
assetsDir: string,
cssFileName: string,
minify: boolean,
inlineLimit: number
): Plugin => {
const styles: Map<string, string> = new Map()
const assets = new Map()
return {
name: 'vite:css',
async transform(css: string, id: string) {
if (id.endsWith('.css')) {
// process url() - register referenced files as assets
// and rewrite the url to the resolved public path
if (urlRE.test(css)) {
const fileDir = path.dirname(id)
css = await asyncReplace(
css,
urlRE,
async ([matched, before, rawUrl, after]) => {
if (isExternalUrl(rawUrl)) {
return matched
}
const file = path.join(fileDir, rawUrl)
const { fileName, content, url } = await resolveAsset(
file,
publicBase,
assetsDir,
inlineLimit
)
assets.set(fileName, content)
debug(`url(${rawUrl}) -> url(${url})`)
return `${before}${url}${after}`
}
)
}
// postcss
let modules
const postcssConfig = await loadPostcssConfig(root)
const expectsModule = id.endsWith('.module.css')
if (postcssConfig || expectsModule) {
try {
const result = await require('postcss')([
...((postcssConfig && postcssConfig.plugins) || []),
...(expectsModule
? [
require('postcss-modules')({
getJSON(_: string, json: Record<string, string>) {
modules = json
}
})
]
: [])
]).process(css, {
...(postcssConfig && postcssConfig.options),
from: id
})
css = result.css
} catch (e) {
console.error(`[vite] error applying postcss transforms: `, e)
}
}
styles.set(id, css)
return modules
? `export default ${JSON.stringify(modules)}`
: '/* css extracted by vite */'
}
},
async generateBundle(_options, bundle) {
let css = ''
// finalize extracted css
styles.forEach((s) => {
css += s
})
// minify with cssnano
if (minify) {
css = (
await require('postcss')([require('cssnano')]).process(css, {
from: undefined
})
).css
}
bundle[cssFileName] = {
isAsset: true,
type: 'asset',
fileName: cssFileName,
source: css
}
registerAssets(assets, bundle)
}
}
}
|
src/node/buildPluginCss.ts
| 1 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.2605355978012085,
0.02302149124443531,
0.00016614393098279834,
0.0013598804362118244,
0.07162568718194962
] |
{
"id": 0,
"code_window": [
" publicBase,\n",
" assetsDir,\n",
" inlineLimit\n",
" )\n",
" assets.set(fileName, content)\n",
" debug(`${id} -> ${url}`)\n",
" return `export default ${JSON.stringify(url)}`\n",
" }\n",
" },\n",
"\n",
" generateBundle(_options, bundle) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" debug(`${id} -> ${url.startsWith('data:') ? `base64 inlined` : url}`)\n"
],
"file_path": "src/node/buildPluginAsset.ts",
"type": "replace",
"edit_start_line_idx": 79
}
|
import { Plugin } from './server'
import path from 'path'
import slash from 'slash'
import LRUCache from 'lru-cache'
import MagicString from 'magic-string'
import { init as initLexer, parse as parseImports } from 'es-module-lexer'
import { InternalResolver } from './resolver'
import {
debugHmr,
importerMap,
importeeMap,
ensureMapEntry,
rewriteFileWithHMR,
hmrClientPublicPath
} from './serverPluginHmr'
import { readBody, cleanUrl, queryRE, isExternalUrl } from './utils'
const debug = require('debug')('vite:rewrite')
const rewriteCache = new LRUCache({ max: 1024 })
// Plugin for rewriting served js.
// - Rewrites named module imports to `/@modules/:id` requests, e.g.
// "vue" => "/@modules/vue"
// - Rewrites HMR `hot.accept` calls to inject the file's own path. e.g.
// `hot.accept('./dep.js', cb)` -> `hot.accept('/importer.js', './dep.js', cb)`
// - Also tracks importer/importee relationship graph during the rewrite.
// The graph is used by the HMR plugin to perform analysis on file change.
export const moduleRewritePlugin: Plugin = ({ app, watcher, resolver }) => {
// bust module rewrite cache on file change
watcher.on('change', (file) => {
const publicPath = resolver.fileToRequest(file)
debug(`${publicPath}: cache busted`)
rewriteCache.del(publicPath)
})
// inject __DEV__ and process.env.NODE_ENV flags
// since some ESM builds expect these to be replaced by the bundler
const devInjectionCode =
`\n<script type="module">` +
`import "${hmrClientPublicPath}"\n` +
`window.__DEV__ = true\n` +
`window.process = { env: { NODE_ENV: 'development' }}\n` +
`</script>\n`
const scriptRE = /(<script\b[^>]*>)([\s\S]*?)<\/script>/gm
const srcRE = /\bsrc=(?:"([^"]+)"|'([^']+)'|([^'"\s]+)\b)/
app.use(async (ctx, next) => {
await next()
if (ctx.status === 304) {
return
}
if (ctx.path === '/index.html') {
const html = await readBody(ctx.body)
if (html && rewriteCache.has(html)) {
debug('/index.html: serving from cache')
ctx.body = rewriteCache.get(html)
} else if (ctx.body) {
await initLexer
let hasInjectedDevFlag = false
const importer = '/index.html'
ctx.body = html!.replace(scriptRE, (matched, openTag, script) => {
const devFlag = hasInjectedDevFlag ? `` : devInjectionCode
hasInjectedDevFlag = true
if (script) {
return `${devFlag}${openTag}${rewriteImports(
script,
importer,
resolver
)}</script>`
} else {
const srcAttr = openTag.match(srcRE)
if (srcAttr) {
// register script as a import dep for hmr
const importee = cleanUrl(slash(path.resolve('/', srcAttr[1])))
debugHmr(` ${importer} imports ${importee}`)
ensureMapEntry(importerMap, importee).add(importer)
}
return `${devFlag}${matched}`
}
})
rewriteCache.set(html, ctx.body)
return
}
}
// we are doing the js rewrite after all other middlewares have finished;
// this allows us to post-process javascript produced by user middlewares
// regardless of the extension of the original files.
if (
ctx.body &&
ctx.response.is('js') &&
!ctx.url.endsWith('.map') &&
// skip internal client
!ctx.path.startsWith(`/@hmr`) &&
// only need to rewrite for <script> part in vue files
!((ctx.path.endsWith('.vue') || ctx.vue) && ctx.query.type != null)
) {
const content = await readBody(ctx.body)
if (!ctx.query.t && rewriteCache.has(content)) {
debug(`${ctx.url}: serving from cache`)
ctx.body = rewriteCache.get(content)
} else {
await initLexer
ctx.body = rewriteImports(content!, ctx.path, resolver, ctx.query.t)
rewriteCache.set(content, ctx.body)
}
} else {
debug(`not rewriting: ${ctx.url}`)
}
})
}
function rewriteImports(
source: string,
importer: string,
resolver: InternalResolver,
timestamp?: string
) {
if (typeof source !== 'string') {
source = String(source)
}
try {
const [imports] = parseImports(source)
if (imports.length) {
debug(`${importer}: rewriting`)
const s = new MagicString(source)
let hasReplaced = false
const prevImportees = importeeMap.get(importer)
const currentImportees = new Set<string>()
importeeMap.set(importer, currentImportees)
for (let i = 0; i < imports.length; i++) {
const { s: start, e: end, d: dynamicIndex } = imports[i]
let id = source.substring(start, end)
let hasLiteralDynamicId = false
if (dynamicIndex >= 0) {
const literalIdMatch = id.match(/^(?:'([^']+)'|"([^"]+)")$/)
if (literalIdMatch) {
hasLiteralDynamicId = true
id = literalIdMatch[1] || literalIdMatch[2]
}
}
if (dynamicIndex === -1 || hasLiteralDynamicId) {
// do not rewrite external imports
if (isExternalUrl(id)) {
break
}
let resolved
if (/^[^\/\.]/.test(id)) {
resolved = resolver.idToRequest(id) || `/@modules/${id}`
if (
resolved === hmrClientPublicPath &&
!/.vue$|.vue\?type=/.test(importer)
) {
// the user explicit imports the HMR API in a js file
// making the module hot.
rewriteFileWithHMR(source, importer, s)
// we rewrite the hot.accept call
hasReplaced = true
}
} else {
let pathname = cleanUrl(id)
const queryMatch = id.match(queryRE)
let query = queryMatch ? queryMatch[0] : ''
// append .js for extension-less imports
// for now we don't attemp to resolve other extensions
if (!/\.\w+/.test(pathname)) {
const file = resolver.requestToFile(pathname)
pathname += path.extname(file)
}
// force re-fetch all imports by appending timestamp
// if this is a hmr refresh request
if (timestamp) {
query += `${query ? `&` : `?`}t=${timestamp}`
}
resolved = pathname + query
}
if (resolved !== id) {
debug(` "${id}" --> "${resolved}"`)
s.overwrite(
start,
end,
hasLiteralDynamicId ? `'${resolved}'` : resolved
)
hasReplaced = true
}
// save the import chain for hmr analysis
const importee = cleanUrl(
slash(path.resolve(path.dirname(importer), resolved))
)
currentImportees.add(importee)
debugHmr(` ${importer} imports ${importee}`)
ensureMapEntry(importerMap, importee).add(importer)
} else {
console.log(`[vite] ignored dynamic import(${id})`)
}
}
// since the importees may have changed due to edits,
// check if we need to remove this importer from certain importees
if (prevImportees) {
prevImportees.forEach((importee) => {
if (!currentImportees.has(importee)) {
const importers = importerMap.get(importee)
if (importers) {
importers.delete(importer)
}
}
})
}
if (!hasReplaced) {
debug(` no imports rewritten.`)
}
return hasReplaced ? s.toString() : source
} else {
debug(`${importer}: no imports found.`)
}
return source
} catch (e) {
console.error(
`[vite] Error: module imports rewrite failed for ${importer}.\n`,
e
)
debug(source)
return source
}
}
|
src/node/serverPluginModuleRewrite.ts
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.0007797717116773129,
0.0001983802067115903,
0.00016310566570609808,
0.00016918418987188488,
0.0001228144101332873
] |
{
"id": 0,
"code_window": [
" publicBase,\n",
" assetsDir,\n",
" inlineLimit\n",
" )\n",
" assets.set(fileName, content)\n",
" debug(`${id} -> ${url}`)\n",
" return `export default ${JSON.stringify(url)}`\n",
" }\n",
" },\n",
"\n",
" generateBundle(_options, bundle) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" debug(`${id} -> ${url.startsWith('data:') ? `base64 inlined` : url}`)\n"
],
"file_path": "src/node/buildPluginAsset.ts",
"type": "replace",
"edit_start_line_idx": 79
}
|
// How HMR works
// 1. `.vue` files are transformed into `.js` files before being served
// 2. All `.js` files, before being served, are parsed to detect their imports
// (this is done in `./serverPluginModuleRewrite.ts`) for module import rewriting.
// During this we also record the importer/importee relationships which can be used for
// HMR analysis (we do both at the same time to avoid double parse costs)
// 3. When a `.vue` file changes, we directly read, parse it again and
// send the client because Vue components are self-accepting by nature
// 4. When a js file changes, it triggers an HMR graph analysis, where we try to
// walk its importer chains and see if we reach a "HMR boundary". An HMR
// boundary is either a `.vue` file or a `.js` file that explicitly indicated
// that it accepts hot updates (by importing from the `/@hmr` special module)
// 5. If any parent chain exhausts without ever running into an HMR boundary,
// it's considered a "dead end". This causes a full page reload.
// 6. If a `.vue` boundary is encountered, we add it to the `vueImports` Set.
// 7. If a `.js` boundary is encountered, we check if the boundary's current
// child importer is in the accepted list of the boundary (see additional
// explanation below). If yes, record current child importer in the
// `jsImporters` Set.
// 8. If the graph walk finished without running into dead ends, send the
// client to update all `jsImporters` and `vueImporters`.
// How do we get a js HMR boundary's accepted list on the server
// 1. During the import rewriting, if `/@hmr` import is present in a js file,
// we will do a fullblown parse of the file to find the `hot.accept` call,
// and records the file and its accepted dependencies in a `hmrBoundariesMap`
// 2. We also inject the boundary file's full path into the `hot.accept` call
// so that on the client, the `hot.accept` call would have registered for
// updates using the full paths of the dependencies.
import { Plugin } from './server'
import WebSocket from 'ws'
import path from 'path'
import slash from 'slash'
import chalk from 'chalk'
import hash_sum from 'hash-sum'
import { SFCBlock } from '@vue/compiler-sfc'
import { parseSFC, vueCache } from './serverPluginVue'
import { cachedRead } from './utils'
import { FSWatcher } from 'chokidar'
import MagicString from 'magic-string'
import { parse } from '@babel/parser'
import { StringLiteral, Statement, Expression } from '@babel/types'
export const debugHmr = require('debug')('vite:hmr')
export type HMRWatcher = FSWatcher & {
handleVueReload: (file: string, timestamp?: number, content?: string) => void
handleJSReload: (file: string, timestamp?: number) => void
send: (payload: HMRPayload) => void
}
// while we lex the files for imports we also build a import graph
// so that we can determine what files to hot reload
type HMRStateMap = Map<string, Set<string>>
export const hmrAcceptanceMap: HMRStateMap = new Map()
export const importerMap: HMRStateMap = new Map()
export const importeeMap: HMRStateMap = new Map()
// client and node files are placed flat in the dist folder
export const hmrClientFilePath = path.resolve(__dirname, './client.js')
export const hmrClientId = '@hmr'
export const hmrClientPublicPath = `/${hmrClientId}`
interface HMRPayload {
type:
| 'vue-rerender'
| 'vue-reload'
| 'vue-style-update'
| 'js-update'
| 'style-update'
| 'style-remove'
| 'full-reload'
| 'custom'
timestamp: number
path?: string
id?: string
index?: number
customData?: any
}
export const hmrPlugin: Plugin = ({ root, app, server, watcher, resolver }) => {
app.use(async (ctx, next) => {
if (ctx.path !== hmrClientPublicPath) {
return next()
}
debugHmr('serving hmr client')
ctx.type = 'js'
await cachedRead(ctx, hmrClientFilePath)
})
// start a websocket server to send hmr notifications to the client
const wss = new WebSocket.Server({ server })
const sockets = new Set<WebSocket>()
wss.on('connection', (socket) => {
debugHmr('ws client connected')
sockets.add(socket)
socket.send(JSON.stringify({ type: 'connected' }))
socket.on('close', () => {
sockets.delete(socket)
})
})
wss.on('error', (e: Error & { code: string }) => {
if (e.code !== 'EADDRINUSE') {
console.error(chalk.red(`[vite] WebSocket server error:`))
console.error(e)
}
})
const send = (payload: HMRPayload) => {
const stringified = JSON.stringify(payload, null, 2)
debugHmr(`update: ${stringified}`)
sockets.forEach((s) => s.send(stringified))
}
watcher.handleVueReload = handleVueReload
watcher.handleJSReload = handleJSReload
watcher.send = send
watcher.on('change', async (file) => {
const timestamp = Date.now()
if (file.endsWith('.vue')) {
handleVueReload(file, timestamp)
} else if (file.endsWith('.js')) {
handleJSReload(file, timestamp)
}
})
async function handleVueReload(
file: string,
timestamp: number = Date.now(),
content?: string
) {
const publicPath = resolver.fileToRequest(file)
const cacheEntry = vueCache.get(file)
debugHmr(`busting Vue cache for ${file}`)
vueCache.del(file)
const descriptor = await parseSFC(root, file, content)
if (!descriptor) {
// read failed
return
}
const prevDescriptor = cacheEntry && cacheEntry.descriptor
if (!prevDescriptor) {
// the file has never been accessed yet
return
}
// check which part of the file changed
let needReload = false
let needRerender = false
if (!isEqual(descriptor.script, prevDescriptor.script)) {
needReload = true
}
if (!isEqual(descriptor.template, prevDescriptor.template)) {
needRerender = true
}
const styleId = hash_sum(publicPath)
const prevStyles = prevDescriptor.styles || []
const nextStyles = descriptor.styles || []
if (
(!needReload &&
prevStyles.some((s) => s.scoped) !==
nextStyles.some((s) => s.scoped)) ||
// TODO for now we force the component to reload on <style module> change
// but this should be optimizable to replace the __cssMoudles object
// on script and only trigger a rerender.
prevStyles.some((s) => s.module != null) ||
nextStyles.some((s) => s.module != null)
) {
needReload = true
}
// only need to update styles if not reloading, since reload forces
// style updates as well.
if (!needReload) {
nextStyles.forEach((_, i) => {
if (!prevStyles[i] || !isEqual(prevStyles[i], nextStyles[i])) {
send({
type: 'vue-style-update',
path: publicPath,
index: i,
id: `${styleId}-${i}`,
timestamp
})
}
})
}
// stale styles always need to be removed
prevStyles.slice(nextStyles.length).forEach((_, i) => {
send({
type: 'style-remove',
path: publicPath,
id: `${styleId}-${i + nextStyles.length}`,
timestamp
})
})
if (needReload) {
send({
type: 'vue-reload',
path: publicPath,
timestamp
})
} else if (needRerender) {
send({
type: 'vue-rerender',
path: publicPath,
timestamp
})
}
}
function handleJSReload(filePath: string, timestamp: number = Date.now()) {
// normal js file
const publicPath = resolver.fileToRequest(filePath)
const importers = importerMap.get(publicPath)
if (importers) {
const vueImporters = new Set<string>()
const jsHotImporters = new Set<string>()
const hasDeadEnd = walkImportChain(
publicPath,
importers,
vueImporters,
jsHotImporters
)
if (hasDeadEnd) {
send({
type: 'full-reload',
timestamp
})
} else {
vueImporters.forEach((vueImporter) => {
send({
type: 'vue-reload',
path: vueImporter,
timestamp
})
})
jsHotImporters.forEach((jsImporter) => {
send({
type: 'js-update',
path: jsImporter,
timestamp
})
})
}
} else {
debugHmr(`no importers for ${publicPath}.`)
}
}
}
function walkImportChain(
importee: string,
currentImporters: Set<string>,
vueImporters: Set<string>,
jsHotImporters: Set<string>
): boolean {
if (isHmrAccepted(importee, importee)) {
// self-accepting module.
jsHotImporters.add(importee)
return false
}
let hasDeadEnd = false
for (const importer of currentImporters) {
if (importer.endsWith('.vue')) {
vueImporters.add(importer)
} else if (isHmrAccepted(importer, importee)) {
jsHotImporters.add(importer)
} else {
const parentImpoters = importerMap.get(importer)
if (!parentImpoters) {
hasDeadEnd = true
} else {
hasDeadEnd = walkImportChain(
importer,
parentImpoters,
vueImporters,
jsHotImporters
)
}
}
}
return hasDeadEnd
}
function isHmrAccepted(importer: string, dep: string): boolean {
const deps = hmrAcceptanceMap.get(importer)
return deps ? deps.has(dep) : false
}
function isEqual(a: SFCBlock | null, b: SFCBlock | null) {
if (!a && !b) return true
if (!a || !b) return false
if (a.content !== b.content) return false
const keysA = Object.keys(a.attrs)
const keysB = Object.keys(b.attrs)
if (keysA.length !== keysB.length) {
return false
}
return keysA.every((key) => a.attrs[key] === b.attrs[key])
}
export function ensureMapEntry(map: HMRStateMap, key: string): Set<string> {
let entry = map.get(key)
if (!entry) {
entry = new Set<string>()
map.set(key, entry)
}
return entry
}
export function rewriteFileWithHMR(
source: string,
importer: string,
s: MagicString
) {
const ast = parse(source, {
sourceType: 'module',
plugins: [
// by default we enable proposals slated for ES2020.
// full list at https://babeljs.io/docs/en/next/babel-parser#plugins
// this should be kept in async with @vue/compiler-core's support range
'bigInt',
'optionalChaining',
'nullishCoalescingOperator'
]
}).program.body
const registerDep = (e: StringLiteral) => {
const deps = ensureMapEntry(hmrAcceptanceMap, importer)
const depPublicPath = slash(path.resolve(path.dirname(importer), e.value))
deps.add(depPublicPath)
debugHmr(` ${importer} accepts ${depPublicPath}`)
s.overwrite(e.start!, e.end!, JSON.stringify(depPublicPath))
}
const checkAcceptCall = (node: Expression) => {
if (
node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'hot' &&
node.callee.property.name === 'accept'
) {
const args = node.arguments
// inject the imports's own path so it becomes
// hot.accept('/foo.js', ['./bar.js'], () => {})
s.appendLeft(args[0].start!, JSON.stringify(importer) + ', ')
// register the accepted deps
if (args[0].type === 'ArrayExpression') {
args[0].elements.forEach((e) => {
if (e && e.type !== 'StringLiteral') {
console.error(
`[vite] HMR syntax error in ${importer}: hot.accept() deps list can only contain string literals.`
)
} else if (e) {
registerDep(e)
}
})
} else if (args[0].type === 'StringLiteral') {
registerDep(args[0])
} else if (args[0].type.endsWith('FunctionExpression')) {
// self accepting, rewrite to inject itself
// hot.accept(() => {}) --> hot.accept('/foo.js', '/foo.js', () => {})
s.appendLeft(args[0].start!, JSON.stringify(importer) + ', ')
ensureMapEntry(hmrAcceptanceMap, importer).add(importer)
} else {
console.error(
`[vite] HMR syntax error in ${importer}: ` +
`hot.accept() expects a dep string, an array of deps, or a callback.`
)
}
}
}
const checkStatements = (node: Statement) => {
if (node.type === 'ExpressionStatement') {
// top level hot.accept() call
checkAcceptCall(node.expression)
// __DEV__ && hot.accept()
if (
node.expression.type === 'LogicalExpression' &&
node.expression.operator === '&&' &&
node.expression.left.type === 'Identifier' &&
node.expression.left.name === '__DEV__'
) {
checkAcceptCall(node.expression.right)
}
}
// if (__DEV__) ...
if (
node.type === 'IfStatement' &&
node.test.type === 'Identifier' &&
node.test.name === '__DEV__'
) {
if (node.consequent.type === 'BlockStatement') {
node.consequent.body.forEach(checkStatements)
}
if (node.consequent.type === 'ExpressionStatement') {
checkAcceptCall(node.consequent.expression)
}
}
}
ast.forEach(checkStatements)
}
|
src/node/serverPluginHmr.ts
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.00019928514666389674,
0.00017226241470780224,
0.00016456427692901343,
0.00017194724932778627,
0.000004826491476705996
] |
{
"id": 0,
"code_window": [
" publicBase,\n",
" assetsDir,\n",
" inlineLimit\n",
" )\n",
" assets.set(fileName, content)\n",
" debug(`${id} -> ${url}`)\n",
" return `export default ${JSON.stringify(url)}`\n",
" }\n",
" },\n",
"\n",
" generateBundle(_options, bundle) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" debug(`${id} -> ${url.startsWith('data:') ? `base64 inlined` : url}`)\n"
],
"file_path": "src/node/buildPluginAsset.ts",
"type": "replace",
"edit_start_line_idx": 79
}
|
import path from 'path'
import resolve from 'resolve-from'
import sfcCompiler from '@vue/compiler-sfc'
import chalk from 'chalk'
interface ResolvedVuePaths {
browser: string
bundler: string
version: string
hasLocalVue: boolean
compiler: string
cdnLink: string
}
let resolved: ResolvedVuePaths | undefined = undefined
// Resolve the correct `vue` and `@vue.compiler-sfc` to use.
// If the user project has local installations of these, they should be used;
// otherwise, fallback to the dependency of Vite itself.
export function resolveVue(root: string): ResolvedVuePaths {
if (resolved) {
return resolved
}
let browserPath: string
let bundlerPath: string
let compilerPath: string
let hasLocalVue = true
let vueVersion: string
try {
// see if user has local vue installation
const userVuePkg = resolve(root, 'vue/package.json')
vueVersion = require(userVuePkg).version
browserPath = path.join(
path.dirname(userVuePkg),
'dist/vue.runtime.esm-browser.js'
)
bundlerPath = path.join(
path.dirname(userVuePkg),
'dist/vue.runtime.esm-bundler.js'
)
// also resolve matching sfc compiler
try {
const compilerPkgPath = resolve(root, '@vue/compiler-sfc/package.json')
const compilerPkg = require(compilerPkgPath)
if (compilerPkg.version !== require(userVuePkg).version) {
throw new Error()
}
compilerPath = path.join(path.dirname(compilerPkgPath), compilerPkg.main)
} catch (e) {
// user has local vue but has no compiler-sfc
console.error(
chalk.red(
`[vite] Error: a local installation of \`vue\` is detected but ` +
`no matching \`@vue/compiler-sfc\` is found. Make sure to install ` +
`both and use the same version.`
)
)
compilerPath = require.resolve('@vue/compiler-sfc')
}
} catch (e) {
// user has no local vue, use vite's dependency version
hasLocalVue = false
browserPath = require.resolve('vue/dist/vue.runtime.esm-browser.js')
bundlerPath = require.resolve('vue/dist/vue.runtime.esm-bundler.js')
vueVersion = require('vue/package.json').version
compilerPath = require.resolve('@vue/compiler-sfc')
}
resolved = {
browser: browserPath,
bundler: bundlerPath,
version: vueVersion,
hasLocalVue,
compiler: compilerPath,
cdnLink: `https://unpkg.com/vue@${vueVersion}/dist/vue.esm-browser.prod.js`
}
return resolved
}
export function resolveCompiler(cwd: string): typeof sfcCompiler {
return require(resolveVue(cwd).compiler)
}
|
src/node/vueResolver.ts
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.00017533331993035972,
0.0001731626980472356,
0.0001671263453317806,
0.0001739102299325168,
0.0000023684658572165063
] |
{
"id": 1,
"code_window": [
" css,\n",
" urlRE,\n",
" async ([matched, before, rawUrl, after]) => {\n",
" if (isExternalUrl(rawUrl)) {\n",
" return matched\n",
" }\n",
" const file = path.join(fileDir, rawUrl)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isExternalUrl(rawUrl) || rawUrl.startsWith('data:')) {\n"
],
"file_path": "src/node/buildPluginCss.ts",
"type": "replace",
"edit_start_line_idx": 33
}
|
import path from 'path'
import fs from 'fs-extra'
import { Plugin, OutputBundle } from 'rollup'
import { isStaticAsset } from './utils'
import hash_sum from 'hash-sum'
import slash from 'slash'
import mime from 'mime-types'
const debug = require('debug')('vite:build:asset')
interface AssetCacheEntry {
content: Buffer
fileName: string
url: string
}
const assetResolveCache = new Map<string, AssetCacheEntry>()
export const resolveAsset = async (
id: string,
publicBase: string,
assetsDir: string,
inlineLimit: number
): Promise<AssetCacheEntry> => {
const cached = assetResolveCache.get(id)
if (cached) {
return cached
}
const ext = path.extname(id)
const baseName = path.basename(id, ext)
const resolvedFileName = `${baseName}.${hash_sum(id)}${ext}`
let url = slash(path.join(publicBase, assetsDir, resolvedFileName))
const content = await fs.readFile(id)
if (!id.endsWith(`.svg`) && content.length < inlineLimit) {
url = `data:${mime.lookup(id)};base64,${content.toString('base64')}`
}
const resolved = {
content,
fileName: resolvedFileName,
url
}
assetResolveCache.set(id, resolved)
return resolved
}
export const registerAssets = (
assets: Map<string, string>,
bundle: OutputBundle
) => {
for (const [fileName, source] of assets) {
bundle[fileName] = {
isAsset: true,
type: 'asset',
fileName,
source
}
}
}
export const createBuildAssetPlugin = (
publicBase: string,
assetsDir: string,
inlineLimit: number
): Plugin => {
const assets = new Map()
return {
name: 'vite:asset',
async load(id) {
if (isStaticAsset(id)) {
const { fileName, content, url } = await resolveAsset(
id,
publicBase,
assetsDir,
inlineLimit
)
assets.set(fileName, content)
debug(`${id} -> ${url}`)
return `export default ${JSON.stringify(url)}`
}
},
generateBundle(_options, bundle) {
registerAssets(assets, bundle)
}
}
}
|
src/node/buildPluginAsset.ts
| 1 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.0015483807073906064,
0.00036895726225338876,
0.00016395861166529357,
0.0001687474868958816,
0.0004380164318718016
] |
{
"id": 1,
"code_window": [
" css,\n",
" urlRE,\n",
" async ([matched, before, rawUrl, after]) => {\n",
" if (isExternalUrl(rawUrl)) {\n",
" return matched\n",
" }\n",
" const file = path.join(fileDir, rawUrl)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isExternalUrl(rawUrl) || rawUrl.startsWith('data:')) {\n"
],
"file_path": "src/node/buildPluginCss.ts",
"type": "replace",
"edit_start_line_idx": 33
}
|
{
"compilerOptions": {
"sourceMap": false,
"target": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"declaration": true,
"allowJs": false,
"allowSyntheticDefaultImports": true,
"noUnusedLocals": true,
"strictNullChecks": true,
"noImplicitAny": true,
"removeComments": false
}
}
|
tsconfig.base.json
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.0001722278248053044,
0.00017127636238001287,
0.00017032491450663656,
0.00017127636238001287,
9.514551493339241e-7
] |
{
"id": 1,
"code_window": [
" css,\n",
" urlRE,\n",
" async ([matched, before, rawUrl, after]) => {\n",
" if (isExternalUrl(rawUrl)) {\n",
" return matched\n",
" }\n",
" const file = path.join(fileDir, rawUrl)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isExternalUrl(rawUrl) || rawUrl.startsWith('data:')) {\n"
],
"file_path": "src/node/buildPluginCss.ts",
"type": "replace",
"edit_start_line_idx": 33
}
|
import path from 'path'
import { Plugin } from './server'
import {
SFCDescriptor,
SFCTemplateBlock,
SFCStyleBlock,
SFCStyleCompileResults
} from '@vue/compiler-sfc'
import { resolveCompiler } from './vueResolver'
import hash_sum from 'hash-sum'
import LRUCache from 'lru-cache'
import { hmrClientId } from './serverPluginHmr'
import resolve from 'resolve-from'
import { cachedRead, genSourceMapString } from './utils'
import { loadPostcssConfig } from './config'
import { Context } from 'koa'
import { transform } from './esbuildService'
const debug = require('debug')('vite:sfc')
const getEtag = require('etag')
interface CacheEntry {
descriptor?: SFCDescriptor
template?: string
script?: string
styles: SFCStyleCompileResults[]
}
export const vueCache = new LRUCache<string, CacheEntry>({
max: 65535
})
const etagCacheCheck = (ctx: Context) => {
ctx.etag = getEtag(ctx.body)
ctx.status = ctx.etag === ctx.get('If-None-Match') ? 304 : 200
}
export const vuePlugin: Plugin = ({ root, app, resolver }) => {
app.use(async (ctx, next) => {
if (!ctx.path.endsWith('.vue') && !ctx.vue) {
return next()
}
const query = ctx.query
const publicPath = ctx.path
const filePath = resolver.requestToFile(publicPath)
// upstream plugins could've already read the file
const descriptor = await parseSFC(root, filePath, ctx.body)
if (!descriptor) {
debug(`${ctx.url} - 404`)
ctx.status = 404
return
}
if (!query.type) {
ctx.type = 'js'
ctx.body = await compileSFCMain(descriptor, filePath, publicPath)
return etagCacheCheck(ctx)
}
if (query.type === 'template') {
ctx.type = 'js'
ctx.body = compileSFCTemplate(
root,
descriptor.template!,
filePath,
publicPath,
descriptor.styles.some((s) => s.scoped)
)
return etagCacheCheck(ctx)
}
if (query.type === 'style') {
const index = Number(query.index)
const styleBlock = descriptor.styles[index]
const result = await compileSFCStyle(
root,
styleBlock,
index,
filePath,
publicPath
)
if (query.module != null) {
ctx.type = 'js'
ctx.body = `export default ${JSON.stringify(result.modules)}`
} else {
ctx.type = 'css'
ctx.body = result.code
}
return etagCacheCheck(ctx)
}
// TODO custom blocks
})
}
export async function parseSFC(
root: string,
filename: string,
content?: string | Buffer
): Promise<SFCDescriptor | undefined> {
let cached = vueCache.get(filename)
if (cached && cached.descriptor) {
debug(`${filename} parse cache hit`)
return cached.descriptor
}
if (!content) {
try {
content = await cachedRead(null, filename)
} catch (e) {
return
}
}
if (typeof content !== 'string') {
content = content.toString()
}
const start = Date.now()
const { descriptor, errors } = resolveCompiler(root).parse(content, {
filename,
sourceMap: true
})
if (errors.length) {
errors.forEach((e) => {
console.error(`[vite] SFC parse error: `, e)
})
console.error(`source:\n`, content)
}
cached = cached || { styles: [] }
cached.descriptor = descriptor
vueCache.set(filename, cached)
debug(`${filename} parsed in ${Date.now() - start}ms.`)
return descriptor
}
async function compileSFCMain(
descriptor: SFCDescriptor,
filePath: string,
publicPath: string
): Promise<string> {
let cached = vueCache.get(filePath)
if (cached && cached.script) {
return cached.script
}
let code = ''
if (descriptor.script) {
let content = descriptor.script.content
if (descriptor.script.lang === 'ts') {
content = (await transform(content, publicPath, { loader: 'ts' })).code
}
code += content.replace(`export default`, 'const __script =')
} else {
code += `const __script = {}`
}
const id = hash_sum(publicPath)
let hasScoped = false
let hasCSSModules = false
if (descriptor.styles) {
code += `\nimport { updateStyle } from "${hmrClientId}"\n`
descriptor.styles.forEach((s, i) => {
const styleRequest = publicPath + `?type=style&index=${i}`
if (s.scoped) hasScoped = true
if (s.module) {
if (!hasCSSModules) {
code += `\nconst __cssModules = __script.__cssModules = {}`
hasCSSModules = true
}
const styleVar = `__style${i}`
const moduleName = typeof s.module === 'string' ? s.module : '$style'
code += `\nimport ${styleVar} from ${JSON.stringify(
styleRequest + '&module'
)}`
code += `\n__cssModules[${JSON.stringify(moduleName)}] = ${styleVar}`
}
code += `\nupdateStyle("${id}-${i}", ${JSON.stringify(styleRequest)})`
})
if (hasScoped) {
code += `\n__script.__scopeId = "data-v-${id}"`
}
}
if (descriptor.template) {
code += `\nimport { render as __render } from ${JSON.stringify(
publicPath + `?type=template`
)}`
code += `\n__script.render = __render`
}
code += `\n__script.__hmrId = ${JSON.stringify(publicPath)}`
code += `\n__script.__file = ${JSON.stringify(filePath)}`
code += `\nexport default __script`
if (descriptor.script) {
code += genSourceMapString(descriptor.script.map)
}
cached = cached || { styles: [] }
cached.script = code
vueCache.set(filePath, cached)
return code
}
function compileSFCTemplate(
root: string,
template: SFCTemplateBlock,
filePath: string,
publicPath: string,
scoped: boolean
): string {
let cached = vueCache.get(filePath)
if (cached && cached.template) {
debug(`${publicPath} template cache hit`)
return cached.template
}
const start = Date.now()
const { code, map, errors } = resolveCompiler(root).compileTemplate({
source: template.content,
filename: filePath,
inMap: template.map,
transformAssetUrls: {
base: path.posix.dirname(publicPath)
},
compilerOptions: {
scopeId: scoped ? `data-v-${hash_sum(publicPath)}` : null,
runtimeModuleName: '/@modules/vue'
},
preprocessLang: template.lang,
preprocessCustomRequire: (id: string) => require(resolve(root, id))
})
if (errors.length) {
errors.forEach((e) => {
console.error(`[vite] SFC template compilation error: `, e)
})
console.error(`source:\n`, template.content)
}
const finalCode = code + genSourceMapString(map)
cached = cached || { styles: [] }
cached.template = finalCode
vueCache.set(filePath, cached)
debug(`${publicPath} template compiled in ${Date.now() - start}ms.`)
return finalCode
}
async function compileSFCStyle(
root: string,
style: SFCStyleBlock,
index: number,
filePath: string,
publicPath: string
): Promise<SFCStyleCompileResults> {
let cached = vueCache.get(filePath)
const cachedEntry = cached && cached.styles && cached.styles[index]
if (cachedEntry) {
debug(`${publicPath} style cache hit`)
return cachedEntry
}
const start = Date.now()
const id = hash_sum(publicPath)
const postcssConfig = await loadPostcssConfig(root)
const result = await resolveCompiler(root).compileStyleAsync({
source: style.content,
filename: filePath,
id: `data-v-${id}`,
scoped: style.scoped != null,
modules: style.module != null,
preprocessLang: style.lang as any,
preprocessCustomRequire: (id: string) => require(resolve(root, id)),
...(postcssConfig
? {
postcssOptions: postcssConfig.options,
postcssPlugins: postcssConfig.plugins
}
: {})
})
if (result.errors.length) {
result.errors.forEach((e) => {
console.error(`[vite] SFC style compilation error: `, e)
})
console.error(`source:\n`, style.content)
}
cached = cached || { styles: [] }
cached.styles[index] = result
vueCache.set(filePath, cached)
debug(`${publicPath} style compiled in ${Date.now() - start}ms`)
return result
}
|
src/node/serverPluginVue.ts
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.0014911146136000752,
0.0002125036990037188,
0.0001617620582692325,
0.00017040385864675045,
0.00023350158880930394
] |
{
"id": 1,
"code_window": [
" css,\n",
" urlRE,\n",
" async ([matched, before, rawUrl, after]) => {\n",
" if (isExternalUrl(rawUrl)) {\n",
" return matched\n",
" }\n",
" const file = path.join(fileDir, rawUrl)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isExternalUrl(rawUrl) || rawUrl.startsWith('data:')) {\n"
],
"file_path": "src/node/buildPluginCss.ts",
"type": "replace",
"edit_start_line_idx": 33
}
|
import { createApp } from 'vue'
import Comp from './Comp.vue'
import './main.css'
createApp(Comp).mount('#app')
|
test/fixtures/main.js
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.0001727317285258323,
0.0001727317285258323,
0.0001727317285258323,
0.0001727317285258323,
0
] |
{
"id": 2,
"code_window": [
" inlineLimit\n",
" )\n",
" assets.set(fileName, content)\n",
" debug(`url(${rawUrl}) -> url(${url})`)\n",
" return `${before}${url}${after}`\n",
" }\n",
" )\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" debug(\n",
" `url(${rawUrl}) -> ${\n",
" url.startsWith('data:') ? `base64 inlined` : `url(${url})`\n",
" }`\n",
" )\n"
],
"file_path": "src/node/buildPluginCss.ts",
"type": "replace",
"edit_start_line_idx": 44
}
|
import path from 'path'
import { Plugin } from 'rollup'
import { resolveAsset, registerAssets } from './buildPluginAsset'
import { loadPostcssConfig } from './config'
import { isExternalUrl, asyncReplace } from './utils'
const debug = require('debug')('vite:build:css')
const urlRE = /(url\(\s*['"]?)([^"')]+)(["']?\s*\))/
export const createBuildCssPlugin = (
root: string,
publicBase: string,
assetsDir: string,
cssFileName: string,
minify: boolean,
inlineLimit: number
): Plugin => {
const styles: Map<string, string> = new Map()
const assets = new Map()
return {
name: 'vite:css',
async transform(css: string, id: string) {
if (id.endsWith('.css')) {
// process url() - register referenced files as assets
// and rewrite the url to the resolved public path
if (urlRE.test(css)) {
const fileDir = path.dirname(id)
css = await asyncReplace(
css,
urlRE,
async ([matched, before, rawUrl, after]) => {
if (isExternalUrl(rawUrl)) {
return matched
}
const file = path.join(fileDir, rawUrl)
const { fileName, content, url } = await resolveAsset(
file,
publicBase,
assetsDir,
inlineLimit
)
assets.set(fileName, content)
debug(`url(${rawUrl}) -> url(${url})`)
return `${before}${url}${after}`
}
)
}
// postcss
let modules
const postcssConfig = await loadPostcssConfig(root)
const expectsModule = id.endsWith('.module.css')
if (postcssConfig || expectsModule) {
try {
const result = await require('postcss')([
...((postcssConfig && postcssConfig.plugins) || []),
...(expectsModule
? [
require('postcss-modules')({
getJSON(_: string, json: Record<string, string>) {
modules = json
}
})
]
: [])
]).process(css, {
...(postcssConfig && postcssConfig.options),
from: id
})
css = result.css
} catch (e) {
console.error(`[vite] error applying postcss transforms: `, e)
}
}
styles.set(id, css)
return modules
? `export default ${JSON.stringify(modules)}`
: '/* css extracted by vite */'
}
},
async generateBundle(_options, bundle) {
let css = ''
// finalize extracted css
styles.forEach((s) => {
css += s
})
// minify with cssnano
if (minify) {
css = (
await require('postcss')([require('cssnano')]).process(css, {
from: undefined
})
).css
}
bundle[cssFileName] = {
isAsset: true,
type: 'asset',
fileName: cssFileName,
source: css
}
registerAssets(assets, bundle)
}
}
}
|
src/node/buildPluginCss.ts
| 1 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.9956117868423462,
0.08353478461503983,
0.00016860515461303294,
0.00021956145064905286,
0.27500247955322266
] |
{
"id": 2,
"code_window": [
" inlineLimit\n",
" )\n",
" assets.set(fileName, content)\n",
" debug(`url(${rawUrl}) -> url(${url})`)\n",
" return `${before}${url}${after}`\n",
" }\n",
" )\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" debug(\n",
" `url(${rawUrl}) -> ${\n",
" url.startsWith('data:') ? `base64 inlined` : `url(${url})`\n",
" }`\n",
" )\n"
],
"file_path": "src/node/buildPluginCss.ts",
"type": "replace",
"edit_start_line_idx": 44
}
|
{
"greeting": "hello world"
}
|
test/fixtures/data.json
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.00016769126523286104,
0.00016769126523286104,
0.00016769126523286104,
0.00016769126523286104,
0
] |
{
"id": 2,
"code_window": [
" inlineLimit\n",
" )\n",
" assets.set(fileName, content)\n",
" debug(`url(${rawUrl}) -> url(${url})`)\n",
" return `${before}${url}${after}`\n",
" }\n",
" )\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" debug(\n",
" `url(${rawUrl}) -> ${\n",
" url.startsWith('data:') ? `base64 inlined` : `url(${url})`\n",
" }`\n",
" )\n"
],
"file_path": "src/node/buildPluginCss.ts",
"type": "replace",
"edit_start_line_idx": 44
}
|
import http, { Server } from 'http'
import Koa from 'koa'
import chokidar from 'chokidar'
import { Resolver, createResolver, InternalResolver } from './resolver'
import { moduleRewritePlugin } from './serverPluginModuleRewrite'
import { moduleResolvePlugin } from './serverPluginModuleResolve'
import { vuePlugin } from './serverPluginVue'
import { hmrPlugin, HMRWatcher } from './serverPluginHmr'
import { serveStaticPlugin } from './serverPluginServeStatic'
import { jsonPlugin } from './serverPluginJson'
import { cssPlugin } from './serverPluginCss'
import { esbuildPlugin } from './serverPluginEsbuild'
export { Resolver }
export type Plugin = (ctx: PluginContext) => void
export interface PluginContext {
root: string
app: Koa
server: Server
watcher: HMRWatcher
resolver: InternalResolver
jsxConfig: {
jsxFactory: string | undefined
jsxFragment: string | undefined
}
}
export interface ServerConfig {
root?: string
plugins?: Plugin[]
resolvers?: Resolver[]
jsx?: {
factory?: string
fragment?: string
}
}
const internalPlugins: Plugin[] = [
moduleRewritePlugin,
moduleResolvePlugin,
vuePlugin,
esbuildPlugin,
jsonPlugin,
cssPlugin,
hmrPlugin,
serveStaticPlugin
]
export function createServer(config: ServerConfig = {}): Server {
const {
root = process.cwd(),
plugins = [],
resolvers = [],
jsx = {}
} = config
const app = new Koa()
const server = http.createServer(app.callback())
const watcher = chokidar.watch(root, {
ignored: [/node_modules/]
}) as HMRWatcher
const resolver = createResolver(root, resolvers)
const context = {
root,
app,
server,
watcher,
resolver,
jsxConfig: {
jsxFactory: jsx.factory,
jsxFragment: jsx.fragment
}
}
;[...plugins, ...internalPlugins].forEach((m) => m(context))
return server
}
|
src/node/server.ts
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.0001745010813465342,
0.00017066614236682653,
0.00016841043543536216,
0.00017056509386748075,
0.0000018360535705141956
] |
{
"id": 2,
"code_window": [
" inlineLimit\n",
" )\n",
" assets.set(fileName, content)\n",
" debug(`url(${rawUrl}) -> url(${url})`)\n",
" return `${before}${url}${after}`\n",
" }\n",
" )\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" debug(\n",
" `url(${rawUrl}) -> ${\n",
" url.startsWith('data:') ? `base64 inlined` : `url(${url})`\n",
" }`\n",
" )\n"
],
"file_path": "src/node/buildPluginCss.ts",
"type": "replace",
"edit_start_line_idx": 44
}
|
MIT License
Copyright (c) 2019-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
|
LICENSE
| 0 |
https://github.com/vitejs/vite/commit/e01e26dc93070b995d75784bb48e97a024148338
|
[
0.00017514167120680213,
0.00017162477888632566,
0.0001695183600531891,
0.00017021434905473143,
0.0000025029878543136874
] |
{
"id": 0,
"code_window": [
" );\n",
"\n",
" return (\n",
" <div className={styles.cardContainer}>\n",
" <SearchCheckbox\n",
" aria-label=\"Select dashboard\"\n",
" editable={editable}\n",
" checked={isSelected}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" className={styles.checkbox}\n"
],
"file_path": "public/app/features/search/components/SearchItem.tsx",
"type": "add",
"edit_start_line_idx": 71
}
|
import { css } from '@emotion/css';
import React, { useCallback } from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { selectors as e2eSelectors } from '@grafana/e2e-selectors';
import { config } from '@grafana/runtime';
import { Card, Icon, IconName, TagList, useStyles2 } from '@grafana/ui';
import { t } from 'app/core/internationalization';
import { SEARCH_ITEM_HEIGHT } from '../constants';
import { getIconForKind } from '../service/utils';
import { DashboardViewItem, OnToggleChecked } from '../types';
import { SearchCheckbox } from './SearchCheckbox';
export interface Props {
item: DashboardViewItem;
isSelected?: boolean;
editable?: boolean;
onTagSelected: (name: string) => any;
onToggleChecked?: OnToggleChecked;
onClickItem?: (event: React.MouseEvent<HTMLElement>) => void;
}
const selectors = e2eSelectors.components.Search;
const getIconFromMeta = (meta = ''): IconName => {
const metaIconMap = new Map<string, IconName>([
['errors', 'info-circle'],
['views', 'eye'],
]);
return metaIconMap.has(meta) ? metaIconMap.get(meta)! : 'sort-amount-down';
};
/** @deprecated */
export const SearchItem = ({ item, isSelected, editable, onToggleChecked, onTagSelected, onClickItem }: Props) => {
const styles = useStyles2(getStyles);
const tagSelected = useCallback(
(tag: string, event: React.MouseEvent<HTMLElement>) => {
event.stopPropagation();
event.preventDefault();
onTagSelected(tag);
},
[onTagSelected]
);
const handleCheckboxClick = useCallback(
(ev: React.MouseEvent) => {
ev.stopPropagation();
if (onToggleChecked) {
onToggleChecked(item);
}
},
[item, onToggleChecked]
);
const description = config.featureToggles.nestedFolders ? (
<>
<Icon name={getIconForKind(item.kind)} aria-hidden /> {kindName(item.kind)}
</>
) : (
<>
<Icon name={getIconForKind(item.parentKind ?? 'folder')} aria-hidden /> {item.parentTitle || 'General'}
</>
);
return (
<div className={styles.cardContainer}>
<SearchCheckbox
aria-label="Select dashboard"
editable={editable}
checked={isSelected}
onClick={handleCheckboxClick}
/>
<Card
className={styles.card}
data-testid={selectors.dashboardItem(item.title)}
href={item.url}
style={{ minHeight: SEARCH_ITEM_HEIGHT }}
onClick={onClickItem}
>
<Card.Heading>{item.title}</Card.Heading>
<Card.Meta separator={''}>
<span className={styles.metaContainer}>{description}</span>
{item.sortMetaName && (
<span className={styles.metaContainer}>
<Icon name={getIconFromMeta(item.sortMetaName)} />
{item.sortMeta} {item.sortMetaName}
</span>
)}
</Card.Meta>
<Card.Tags>
<TagList tags={item.tags ?? []} onClick={tagSelected} getAriaLabel={(tag) => `Filter by tag "${tag}"`} />
</Card.Tags>
</Card>
</div>
);
};
function kindName(kind: DashboardViewItem['kind']) {
switch (kind) {
case 'folder':
return t('search.result-kind.folder', 'Folder');
case 'dashboard':
return t('search.result-kind.dashboard', 'Dashboard');
case 'panel':
return t('search.result-kind.panel', 'Panel');
}
}
const getStyles = (theme: GrafanaTheme2) => {
return {
cardContainer: css`
display: flex;
align-items: center;
margin-bottom: ${theme.spacing(0.75)};
`,
card: css`
padding: ${theme.spacing(1)} ${theme.spacing(2)};
margin-bottom: 0;
`,
metaContainer: css`
display: flex;
align-items: center;
margin-right: ${theme.spacing(1)};
svg {
margin-right: ${theme.spacing(0.5)};
}
`,
};
};
|
public/app/features/search/components/SearchItem.tsx
| 1 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.029764899984002113,
0.0033837154041975737,
0.00016689019685145468,
0.00044068717397749424,
0.007529612630605698
] |
{
"id": 0,
"code_window": [
" );\n",
"\n",
" return (\n",
" <div className={styles.cardContainer}>\n",
" <SearchCheckbox\n",
" aria-label=\"Select dashboard\"\n",
" editable={editable}\n",
" checked={isSelected}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" className={styles.checkbox}\n"
],
"file_path": "public/app/features/search/components/SearchItem.tsx",
"type": "add",
"edit_start_line_idx": 71
}
|
import React from 'react';
import { MenuGroup } from '../Menu/MenuGroup';
import { MenuItem } from '../Menu/MenuItem';
const menuItems = [
{
label: 'Test',
items: [
{ label: 'First', ariaLabel: 'First' },
{ label: 'Second', ariaLabel: 'Second' },
{ label: 'Third', ariaLabel: 'Third' },
{ label: 'Fourth', ariaLabel: 'Fourth' },
{ label: 'Fifth', ariaLabel: 'Fifth' },
],
},
];
export const renderMenuItems = () => {
return menuItems.map((group, index) => (
<MenuGroup key={`${group.label}${index}`} label={group.label}>
{group.items.map((item) => (
<MenuItem key={item.label} label={item.label} />
))}
</MenuGroup>
));
};
|
packages/grafana-ui/src/components/ContextMenu/ContextMenuStoryHelper.tsx
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.0001734356046654284,
0.00017235435370821506,
0.00017023106920532882,
0.00017339643090963364,
0.0000015014843484095763
] |
{
"id": 0,
"code_window": [
" );\n",
"\n",
" return (\n",
" <div className={styles.cardContainer}>\n",
" <SearchCheckbox\n",
" aria-label=\"Select dashboard\"\n",
" editable={editable}\n",
" checked={isSelected}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" className={styles.checkbox}\n"
],
"file_path": "public/app/features/search/components/SearchItem.tsx",
"type": "add",
"edit_start_line_idx": 71
}
|
package api
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/web"
)
// swagger:route GET /dashboards/uid/{uid}/permissions dashboard_permissions getDashboardPermissionsListByUID
//
// Gets all existing permissions for the given dashboard.
//
// Responses:
// 200: getDashboardPermissionsListResponse
// 401: unauthorisedError
// 403: forbiddenError
// 404: notFoundError
// 500: internalServerError
// swagger:route GET /dashboards/id/{DashboardID}/permissions dashboard_permissions getDashboardPermissionsListByID
//
// Gets all existing permissions for the given dashboard.
//
// Please refer to [updated API](#/dashboard_permissions/getDashboardPermissionsListByUID) instead
//
// Deprecated: true
//
// Responses:
// 200: getDashboardPermissionsListResponse
// 401: unauthorisedError
// 403: forbiddenError
// 404: notFoundError
// 500: internalServerError
func (hs *HTTPServer) GetDashboardPermissionList(c *contextmodel.ReqContext) response.Response {
var dashID int64
var err error
dashUID := web.Params(c.Req)[":uid"]
if dashUID == "" {
dashID, err = strconv.ParseInt(web.Params(c.Req)[":dashboardId"], 10, 64)
if err != nil {
return response.Error(http.StatusBadRequest, "dashboardId is invalid", err)
}
}
dash, rsp := hs.getDashboardHelper(c.Req.Context(), c.OrgID, dashID, dashUID)
if rsp != nil {
return rsp
}
g, err := guardian.NewByDashboard(c.Req.Context(), dash, c.OrgID, c.SignedInUser)
if err != nil {
return response.Err(err)
}
if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin {
return dashboardGuardianResponse(err)
}
acl, err := g.GetACLWithoutDuplicates()
if err != nil {
return response.Error(500, "Failed to get dashboard permissions", err)
}
filteredACLs := make([]*dashboards.DashboardACLInfoDTO, 0, len(acl))
for _, perm := range acl {
if perm.UserID > 0 && dtos.IsHiddenUser(perm.UserLogin, c.SignedInUser, hs.Cfg) {
continue
}
perm.UserAvatarURL = dtos.GetGravatarUrl(perm.UserEmail)
if perm.TeamID > 0 {
perm.TeamAvatarURL = dtos.GetGravatarUrlWithDefault(perm.TeamEmail, perm.Team)
}
if perm.Slug != "" {
perm.URL = dashboards.GetDashboardFolderURL(perm.IsFolder, perm.UID, perm.Slug)
}
filteredACLs = append(filteredACLs, perm)
}
return response.JSON(http.StatusOK, filteredACLs)
}
// swagger:route POST /dashboards/uid/{uid}/permissions dashboard_permissions updateDashboardPermissionsByUID
//
// Updates permissions for a dashboard.
//
// This operation will remove existing permissions if they’re not included in the request.
//
// Responses:
// 200: okResponse
// 400: badRequestError
// 401: unauthorisedError
// 403: forbiddenError
// 404: notFoundError
// 500: internalServerError
// swagger:route POST /dashboards/id/{DashboardID}/permissions dashboard_permissions updateDashboardPermissionsByID
//
// Updates permissions for a dashboard.
//
// Please refer to [updated API](#/dashboard_permissions/updateDashboardPermissionsByUID) instead
//
// This operation will remove existing permissions if they’re not included in the request.
//
// Deprecated: true
//
// Responses:
// 200: okResponse
// 400: badRequestError
// 401: unauthorisedError
// 403: forbiddenError
// 404: notFoundError
// 500: internalServerError
func (hs *HTTPServer) UpdateDashboardPermissions(c *contextmodel.ReqContext) response.Response {
var dashID int64
var err error
apiCmd := dtos.UpdateDashboardACLCommand{}
if err := web.Bind(c.Req, &apiCmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err)
}
if err := validatePermissionsUpdate(apiCmd); err != nil {
return response.Error(400, err.Error(), err)
}
dashUID := web.Params(c.Req)[":uid"]
if dashUID == "" {
dashID, err = strconv.ParseInt(web.Params(c.Req)[":dashboardId"], 10, 64)
if err != nil {
return response.Error(http.StatusBadRequest, "dashboardId is invalid", err)
}
}
dash, rsp := hs.getDashboardHelper(c.Req.Context(), c.OrgID, dashID, dashUID)
if rsp != nil {
return rsp
}
g, err := guardian.NewByDashboard(c.Req.Context(), dash, c.OrgID, c.SignedInUser)
if err != nil {
return response.Err(err)
}
if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin {
return dashboardGuardianResponse(err)
}
items := make([]*dashboards.DashboardACL, 0, len(apiCmd.Items))
for _, item := range apiCmd.Items {
items = append(items, &dashboards.DashboardACL{
OrgID: c.OrgID,
DashboardID: dashID,
UserID: item.UserID,
TeamID: item.TeamID,
Role: item.Role,
Permission: item.Permission,
Created: time.Now(),
Updated: time.Now(),
})
}
hiddenACL, err := g.GetHiddenACL(hs.Cfg)
if err != nil {
return response.Error(500, "Error while retrieving hidden permissions", err)
}
items = append(items, hiddenACL...)
if okToUpdate, err := g.CheckPermissionBeforeUpdate(dashboards.PERMISSION_ADMIN, items); err != nil || !okToUpdate {
if err != nil {
if errors.Is(err, guardian.ErrGuardianPermissionExists) || errors.Is(err, guardian.ErrGuardianOverride) {
return response.Error(400, err.Error(), err)
}
return response.Error(500, "Error while checking dashboard permissions", err)
}
return response.Error(403, "Cannot remove own admin permission for a folder", nil)
}
if !hs.AccessControl.IsDisabled() {
old, err := g.GetACL()
if err != nil {
return response.Error(500, "Error while checking dashboard permissions", err)
}
if err := hs.updateDashboardAccessControl(c.Req.Context(), dash.OrgID, dash.UID, false, items, old); err != nil {
return response.Error(500, "Failed to update permissions", err)
}
return response.Success("Dashboard permissions updated")
}
if err := hs.DashboardService.UpdateDashboardACL(c.Req.Context(), dashID, items); err != nil {
if errors.Is(err, dashboards.ErrDashboardACLInfoMissing) ||
errors.Is(err, dashboards.ErrDashboardPermissionDashboardEmpty) {
return response.Error(409, err.Error(), err)
}
return response.Error(500, "Failed to create permission", err)
}
return response.Success("Dashboard permissions updated")
}
// updateDashboardAccessControl is used for api backward compatibility
func (hs *HTTPServer) updateDashboardAccessControl(ctx context.Context, orgID int64, uid string, isFolder bool, items []*dashboards.DashboardACL, old []*dashboards.DashboardACLInfoDTO) error {
commands := []accesscontrol.SetResourcePermissionCommand{}
for _, item := range items {
permissions := item.Permission.String()
role := ""
if item.Role != nil {
role = string(*item.Role)
}
commands = append(commands, accesscontrol.SetResourcePermissionCommand{
UserID: item.UserID,
TeamID: item.TeamID,
BuiltinRole: role,
Permission: permissions,
})
}
for _, o := range old {
shouldRemove := true
for _, item := range items {
if item.UserID != 0 && item.UserID == o.UserID {
shouldRemove = false
break
}
if item.TeamID != 0 && item.TeamID == o.TeamID {
shouldRemove = false
break
}
if item.Role != nil && o.Role != nil && *item.Role == *o.Role {
shouldRemove = false
break
}
}
if shouldRemove {
role := ""
if o.Role != nil {
role = string(*o.Role)
}
commands = append(commands, accesscontrol.SetResourcePermissionCommand{
UserID: o.UserID,
TeamID: o.TeamID,
BuiltinRole: role,
Permission: "",
})
}
}
if isFolder {
if _, err := hs.folderPermissionsService.SetPermissions(ctx, orgID, uid, commands...); err != nil {
return err
}
return nil
}
if _, err := hs.dashboardPermissionsService.SetPermissions(ctx, orgID, uid, commands...); err != nil {
return err
}
return nil
}
func validatePermissionsUpdate(apiCmd dtos.UpdateDashboardACLCommand) error {
for _, item := range apiCmd.Items {
if item.UserID > 0 && item.TeamID > 0 {
return dashboards.ErrPermissionsWithUserAndTeamNotAllowed
}
if (item.UserID > 0 || item.TeamID > 0) && item.Role != nil {
return dashboards.ErrPermissionsWithRoleNotAllowed
}
}
return nil
}
// swagger:parameters getDashboardPermissionsListByUID
type GetDashboardPermissionsListByUIDParams struct {
// in:path
// required:true
UID string `json:"uid"`
}
// swagger:parameters getDashboardPermissionsListByID
type GetDashboardPermissionsListByIDParams struct {
// in:path
DashboardID int64
}
// swagger:parameters updateDashboardPermissionsByID
type UpdateDashboardPermissionsByIDParams struct {
// in:body
// required:true
Body dtos.UpdateDashboardACLCommand
// in:path
DashboardID int64
}
// swagger:parameters updateDashboardPermissionsByUID
type UpdateDashboardPermissionsByUIDParams struct {
// in:body
// required:true
Body dtos.UpdateDashboardACLCommand
// in:path
// required:true
// description: The dashboard UID
UID string `json:"uid"`
}
// swagger:response getDashboardPermissionsListResponse
type GetDashboardPermissionsResponse struct {
// in: body
Body []*dashboards.DashboardACLInfoDTO `json:"body"`
}
|
pkg/api/dashboard_permission.go
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.001112514641135931,
0.0003448765492066741,
0.00016521330690011382,
0.00020197340927552432,
0.00025934065342880785
] |
{
"id": 0,
"code_window": [
" );\n",
"\n",
" return (\n",
" <div className={styles.cardContainer}>\n",
" <SearchCheckbox\n",
" aria-label=\"Select dashboard\"\n",
" editable={editable}\n",
" checked={isSelected}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" className={styles.checkbox}\n"
],
"file_path": "public/app/features/search/components/SearchItem.tsx",
"type": "add",
"edit_start_line_idx": 71
}
|
import { combineReducers } from '@reduxjs/toolkit';
import { TypedVariableModel } from '@grafana/data';
import { dashboardReducer } from 'app/features/dashboard/state/reducers';
import { DashboardState, StoreState } from '../../../types';
import { VariableAdapter } from '../adapters';
import { NEW_VARIABLE_ID } from '../constants';
import {
DashboardVariableModel,
initialVariableModelState,
OrgVariableModel,
UserVariableModel,
VariableHide,
VariableModel,
} from '../types';
import { createQueryVariable } from './__tests__/fixtures';
import { keyedVariablesReducer, KeyedVariablesState } from './keyedVariablesReducer';
import { getInitialTemplatingState, TemplatingState } from './reducers';
import { VariablesState } from './types';
export const getVariableState = (
noOfVariables: number,
inEditorIndex = -1,
includeEmpty = false,
includeSystem = false
): VariablesState => {
const variables: Record<string, TypedVariableModel> = {};
if (includeSystem) {
const dashboardModel: DashboardVariableModel = {
...initialVariableModelState,
id: '__dashboard',
name: '__dashboard',
type: 'system',
index: -3,
skipUrlSync: true,
hide: VariableHide.hideVariable,
current: {
value: {
name: 'A dashboard title',
uid: 'An dashboard UID',
toString: () => 'A dashboard title',
},
},
};
const orgModel: OrgVariableModel = {
...initialVariableModelState,
id: '__org',
name: '__org',
type: 'system',
index: -2,
skipUrlSync: true,
hide: VariableHide.hideVariable,
current: {
value: {
name: 'An org name',
id: 1,
toString: () => '1',
},
},
};
const userModel: UserVariableModel = {
...initialVariableModelState,
id: '__user',
name: '__user',
type: 'system',
index: -1,
skipUrlSync: true,
hide: VariableHide.hideVariable,
current: {
value: {
login: 'admin',
id: 1,
email: 'admin@test',
toString: () => '1',
},
},
};
variables[dashboardModel.id] = dashboardModel;
variables[orgModel.id] = orgModel;
variables[userModel.id] = userModel;
}
for (let index = 0; index < noOfVariables; index++) {
variables[index] = createQueryVariable({
id: index.toString(),
name: `Name-${index}`,
label: `Label-${index}`,
index,
});
}
if (includeEmpty) {
variables[NEW_VARIABLE_ID] = createQueryVariable({
id: NEW_VARIABLE_ID,
name: `Name-${NEW_VARIABLE_ID}`,
label: `Label-${NEW_VARIABLE_ID}`,
index: noOfVariables,
});
}
return variables;
};
export const getVariableTestContext = <Model extends TypedVariableModel>(
adapter: VariableAdapter<Model>,
variableOverrides: Partial<Model> = {}
) => {
const defaults: Partial<VariableModel> = {
id: '0',
rootStateKey: 'key',
index: 0,
name: '0',
};
const defaultVariable = {
...adapter.initialState,
...defaults,
};
const initialState: VariablesState = {
'0': { ...defaultVariable, ...variableOverrides },
};
return { initialState };
};
export const getRootReducer = () =>
combineReducers({
dashboard: dashboardReducer,
templating: keyedVariablesReducer,
});
export type RootReducerType = { dashboard: DashboardState; templating: KeyedVariablesState };
export const getTemplatingRootReducer = () =>
combineReducers({
templating: keyedVariablesReducer,
});
export type TemplatingReducerType = { templating: KeyedVariablesState };
export function getPreloadedState(
key: string,
templatingState: Partial<TemplatingState>
): Pick<StoreState, 'templating'> {
return {
templating: {
lastKey: key,
keys: {
[key]: {
...getInitialTemplatingState(),
...templatingState,
},
},
},
};
}
|
public/app/features/variables/state/helpers.ts
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.00038822722854092717,
0.000185181648703292,
0.00016618498193565756,
0.0001719503488857299,
0.000051000861276406795
] |
{
"id": 1,
"code_window": [
" `,\n",
" card: css`\n",
" padding: ${theme.spacing(1)} ${theme.spacing(2)};\n",
" margin-bottom: 0;\n",
" `,\n",
" metaContainer: css`\n",
" display: flex;\n",
" align-items: center;\n",
" margin-right: ${theme.spacing(1)};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkbox: css({\n",
" marginRight: theme.spacing(1),\n",
" }),\n"
],
"file_path": "public/app/features/search/components/SearchItem.tsx",
"type": "add",
"edit_start_line_idx": 126
}
|
import { css } from '@emotion/css';
import React, { useCallback } from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { selectors as e2eSelectors } from '@grafana/e2e-selectors';
import { config } from '@grafana/runtime';
import { Card, Icon, IconName, TagList, useStyles2 } from '@grafana/ui';
import { t } from 'app/core/internationalization';
import { SEARCH_ITEM_HEIGHT } from '../constants';
import { getIconForKind } from '../service/utils';
import { DashboardViewItem, OnToggleChecked } from '../types';
import { SearchCheckbox } from './SearchCheckbox';
export interface Props {
item: DashboardViewItem;
isSelected?: boolean;
editable?: boolean;
onTagSelected: (name: string) => any;
onToggleChecked?: OnToggleChecked;
onClickItem?: (event: React.MouseEvent<HTMLElement>) => void;
}
const selectors = e2eSelectors.components.Search;
const getIconFromMeta = (meta = ''): IconName => {
const metaIconMap = new Map<string, IconName>([
['errors', 'info-circle'],
['views', 'eye'],
]);
return metaIconMap.has(meta) ? metaIconMap.get(meta)! : 'sort-amount-down';
};
/** @deprecated */
export const SearchItem = ({ item, isSelected, editable, onToggleChecked, onTagSelected, onClickItem }: Props) => {
const styles = useStyles2(getStyles);
const tagSelected = useCallback(
(tag: string, event: React.MouseEvent<HTMLElement>) => {
event.stopPropagation();
event.preventDefault();
onTagSelected(tag);
},
[onTagSelected]
);
const handleCheckboxClick = useCallback(
(ev: React.MouseEvent) => {
ev.stopPropagation();
if (onToggleChecked) {
onToggleChecked(item);
}
},
[item, onToggleChecked]
);
const description = config.featureToggles.nestedFolders ? (
<>
<Icon name={getIconForKind(item.kind)} aria-hidden /> {kindName(item.kind)}
</>
) : (
<>
<Icon name={getIconForKind(item.parentKind ?? 'folder')} aria-hidden /> {item.parentTitle || 'General'}
</>
);
return (
<div className={styles.cardContainer}>
<SearchCheckbox
aria-label="Select dashboard"
editable={editable}
checked={isSelected}
onClick={handleCheckboxClick}
/>
<Card
className={styles.card}
data-testid={selectors.dashboardItem(item.title)}
href={item.url}
style={{ minHeight: SEARCH_ITEM_HEIGHT }}
onClick={onClickItem}
>
<Card.Heading>{item.title}</Card.Heading>
<Card.Meta separator={''}>
<span className={styles.metaContainer}>{description}</span>
{item.sortMetaName && (
<span className={styles.metaContainer}>
<Icon name={getIconFromMeta(item.sortMetaName)} />
{item.sortMeta} {item.sortMetaName}
</span>
)}
</Card.Meta>
<Card.Tags>
<TagList tags={item.tags ?? []} onClick={tagSelected} getAriaLabel={(tag) => `Filter by tag "${tag}"`} />
</Card.Tags>
</Card>
</div>
);
};
function kindName(kind: DashboardViewItem['kind']) {
switch (kind) {
case 'folder':
return t('search.result-kind.folder', 'Folder');
case 'dashboard':
return t('search.result-kind.dashboard', 'Dashboard');
case 'panel':
return t('search.result-kind.panel', 'Panel');
}
}
const getStyles = (theme: GrafanaTheme2) => {
return {
cardContainer: css`
display: flex;
align-items: center;
margin-bottom: ${theme.spacing(0.75)};
`,
card: css`
padding: ${theme.spacing(1)} ${theme.spacing(2)};
margin-bottom: 0;
`,
metaContainer: css`
display: flex;
align-items: center;
margin-right: ${theme.spacing(1)};
svg {
margin-right: ${theme.spacing(0.5)};
}
`,
};
};
|
public/app/features/search/components/SearchItem.tsx
| 1 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.9976621866226196,
0.07301238924264908,
0.0001628000318305567,
0.00016783429600764066,
0.25650498270988464
] |
{
"id": 1,
"code_window": [
" `,\n",
" card: css`\n",
" padding: ${theme.spacing(1)} ${theme.spacing(2)};\n",
" margin-bottom: 0;\n",
" `,\n",
" metaContainer: css`\n",
" display: flex;\n",
" align-items: center;\n",
" margin-right: ${theme.spacing(1)};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkbox: css({\n",
" marginRight: theme.spacing(1),\n",
" }),\n"
],
"file_path": "public/app/features/search/components/SearchItem.tsx",
"type": "add",
"edit_start_line_idx": 126
}
|
package persistentcollection
import (
"context"
)
type Predicate[T any] func(item T) (bool, error)
type UpdateFn[T any] func(item T) (updated bool, updatedItem T, err error)
// PersistentCollection is a collection of items that's going to retain its state between Grafana restarts.
// The main purpose of this API is to reduce the time-to-Proof-of-Concept - this is NOT intended for production use.
//
// The item type needs to be serializable to JSON.
// @alpha -- EXPERIMENTAL
type PersistentCollection[T any] interface {
Delete(ctx context.Context, namespace string, predicate Predicate[T]) (deletedCount int, err error)
FindFirst(ctx context.Context, namespace string, predicate Predicate[T]) (T, error)
Find(ctx context.Context, namespace string, predicate Predicate[T]) ([]T, error)
Update(ctx context.Context, namespace string, updateFn UpdateFn[T]) (updatedCount int, err error)
Insert(ctx context.Context, namespace string, item T) error
}
|
pkg/infra/x/persistentcollection/model.go
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.00017547114111948758,
0.00017283820488955826,
0.00017070128524210304,
0.00017234215920325369,
0.0000019786223219853127
] |
{
"id": 1,
"code_window": [
" `,\n",
" card: css`\n",
" padding: ${theme.spacing(1)} ${theme.spacing(2)};\n",
" margin-bottom: 0;\n",
" `,\n",
" metaContainer: css`\n",
" display: flex;\n",
" align-items: center;\n",
" margin-right: ${theme.spacing(1)};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkbox: css({\n",
" marginRight: theme.spacing(1),\n",
" }),\n"
],
"file_path": "public/app/features/search/components/SearchItem.tsx",
"type": "add",
"edit_start_line_idx": 126
}
|
import { e2e } from '@grafana/e2e';
import datasetResponse from './datasets-response.json';
import fieldsResponse from './fields-response.json';
import tablesResponse from './tables-response.json';
const tableNameWithSpecialCharacter = tablesResponse.results.tables.frames[0].data.values[0][1];
const normalTableName = tablesResponse.results.tables.frames[0].data.values[0][0];
describe('MySQL datasource', () => {
it('code editor autocomplete should handle table name escaping/quoting', () => {
e2e.flows.login('admin', 'admin');
e2e().intercept(
'POST',
{
pathname: '/api/ds/query',
},
(req) => {
if (req.body.queries[0].refId === 'datasets') {
req.alias = 'datasets';
req.reply({
body: datasetResponse,
});
} else if (req.body.queries[0].refId === 'tables') {
req.alias = 'tables';
req.reply({
body: tablesResponse,
});
} else if (req.body.queries[0].refId === 'fields') {
req.alias = 'fields';
req.reply({
body: fieldsResponse,
});
}
}
);
e2e.pages.Explore.visit();
e2e.components.DataSourcePicker.container().should('be.visible').type('gdev-mysql{enter}');
e2e().get("label[for^='option-code']").should('be.visible').click();
e2e().get('textarea').type('S{downArrow}{enter}');
e2e().wait('@tables');
e2e().get('.suggest-widget').contains(tableNameWithSpecialCharacter).should('be.visible');
e2e().get('textarea').type('{enter}');
e2e().get('textarea').should('have.value', `SELECT FROM grafana.\`${tableNameWithSpecialCharacter}\``);
const deleteTimes = new Array(tableNameWithSpecialCharacter.length + 2).fill(
'{backspace}',
0,
tableNameWithSpecialCharacter.length + 2
);
e2e().get('textarea').type(deleteTimes.join(''));
e2e().get('textarea').type('{command}i');
e2e().get('.suggest-widget').contains(tableNameWithSpecialCharacter).should('be.visible');
e2e().get('textarea').type('S{downArrow}{enter}');
e2e().get('textarea').should('have.value', `SELECT FROM grafana.${normalTableName}`);
e2e().get('textarea').type('.');
e2e().get('.suggest-widget').contains('No suggestions.').should('be.visible');
});
});
|
e2e/sql-suite/mysql.spec.ts
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.00017767888493835926,
0.000175004024640657,
0.00017173685773741454,
0.00017531929188407958,
0.000002121638544849702
] |
{
"id": 1,
"code_window": [
" `,\n",
" card: css`\n",
" padding: ${theme.spacing(1)} ${theme.spacing(2)};\n",
" margin-bottom: 0;\n",
" `,\n",
" metaContainer: css`\n",
" display: flex;\n",
" align-items: center;\n",
" margin-right: ${theme.spacing(1)};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkbox: css({\n",
" marginRight: theme.spacing(1),\n",
" }),\n"
],
"file_path": "public/app/features/search/components/SearchItem.tsx",
"type": "add",
"edit_start_line_idx": 126
}
|
package database
import (
"context"
"errors"
"fmt"
"time"
"xorm.io/xorm"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/metrics"
ac "github.com/grafana/grafana/pkg/services/accesscontrol"
alertmodels "github.com/grafana/grafana/pkg/services/alerting/models"
"github.com/grafana/grafana/pkg/services/dashboards"
dashver "github.com/grafana/grafana/pkg/services/dashboardversion"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/quota"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/services/sqlstore/permissions"
"github.com/grafana/grafana/pkg/services/sqlstore/searchstore"
"github.com/grafana/grafana/pkg/services/star"
"github.com/grafana/grafana/pkg/services/store"
"github.com/grafana/grafana/pkg/services/tag"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
type dashboardStore struct {
store db.DB
cfg *setting.Cfg
log log.Logger
features featuremgmt.FeatureToggles
tagService tag.Service
}
// SQL bean helper to save tags
type dashboardTag struct {
Id int64
DashboardId int64
Term string
}
// DashboardStore implements the Store interface
var _ dashboards.Store = (*dashboardStore)(nil)
func ProvideDashboardStore(sqlStore db.DB, cfg *setting.Cfg, features featuremgmt.FeatureToggles, tagService tag.Service, quotaService quota.Service) (dashboards.Store, error) {
s := &dashboardStore{store: sqlStore, cfg: cfg, log: log.New("dashboard-store"), features: features, tagService: tagService}
defaultLimits, err := readQuotaConfig(cfg)
if err != nil {
return nil, err
}
if err := quotaService.RegisterQuotaReporter("a.NewUsageReporter{
TargetSrv: dashboards.QuotaTargetSrv,
DefaultLimits: defaultLimits,
Reporter: s.Count,
}); err != nil {
return nil, err
}
return s, nil
}
func (d *dashboardStore) emitEntityEvent() bool {
return d.features != nil && d.features.IsEnabled(featuremgmt.FlagPanelTitleSearch)
}
func (d *dashboardStore) ValidateDashboardBeforeSave(ctx context.Context, dashboard *dashboards.Dashboard, overwrite bool) (bool, error) {
isParentFolderChanged := false
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var err error
isParentFolderChanged, err = getExistingDashboardByIDOrUIDForUpdate(sess, dashboard, d.store.GetDialect(), overwrite)
if err != nil {
return err
}
isParentFolderChanged, err = getExistingDashboardByTitleAndFolder(sess, dashboard, d.store.GetDialect(), overwrite,
isParentFolderChanged)
if err != nil {
return err
}
return nil
})
if err != nil {
return false, err
}
return isParentFolderChanged, nil
}
func (d *dashboardStore) GetProvisionedDataByDashboardID(ctx context.Context, dashboardID int64) (*dashboards.DashboardProvisioning, error) {
var data dashboards.DashboardProvisioning
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
_, err := sess.Where("dashboard_id = ?", dashboardID).Get(&data)
return err
})
if data.DashboardID == 0 {
return nil, nil
}
return &data, err
}
func (d *dashboardStore) GetProvisionedDataByDashboardUID(ctx context.Context, orgID int64, dashboardUID string) (*dashboards.DashboardProvisioning, error) {
var provisionedDashboard dashboards.DashboardProvisioning
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
var dashboard dashboards.Dashboard
exists, err := sess.Where("org_id = ? AND uid = ?", orgID, dashboardUID).Get(&dashboard)
if err != nil {
return err
}
if !exists {
return dashboards.ErrDashboardNotFound
}
exists, err = sess.Where("dashboard_id = ?", dashboard.ID).Get(&provisionedDashboard)
if err != nil {
return err
}
if !exists {
return dashboards.ErrProvisionedDashboardNotFound
}
return nil
})
return &provisionedDashboard, err
}
func (d *dashboardStore) GetProvisionedDashboardData(ctx context.Context, name string) ([]*dashboards.DashboardProvisioning, error) {
var result []*dashboards.DashboardProvisioning
err := d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
return sess.Where("name = ?", name).Find(&result)
})
return result, err
}
func (d *dashboardStore) SaveProvisionedDashboard(ctx context.Context, cmd dashboards.SaveDashboardCommand, provisioning *dashboards.DashboardProvisioning) (*dashboards.Dashboard, error) {
var result *dashboards.Dashboard
var err error
err = d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
result, err = saveDashboard(sess, &cmd, d.emitEntityEvent())
if err != nil {
return err
}
if provisioning.Updated == 0 {
provisioning.Updated = result.Updated.Unix()
}
return saveProvisionedData(sess, provisioning, result)
})
return result, err
}
func (d *dashboardStore) SaveDashboard(ctx context.Context, cmd dashboards.SaveDashboardCommand) (*dashboards.Dashboard, error) {
var result *dashboards.Dashboard
var err error
err = d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
result, err = saveDashboard(sess, &cmd, d.emitEntityEvent())
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return result, err
}
func (d *dashboardStore) UpdateDashboardACL(ctx context.Context, dashboardID int64, items []*dashboards.DashboardACL) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
// delete existing items
_, err := sess.Exec("DELETE FROM dashboard_acl WHERE dashboard_id=?", dashboardID)
if err != nil {
return fmt.Errorf("deleting from dashboard_acl failed: %w", err)
}
for _, item := range items {
if item.UserID == 0 && item.TeamID == 0 && (item.Role == nil || !item.Role.IsValid()) {
return dashboards.ErrDashboardACLInfoMissing
}
if item.DashboardID == 0 {
return dashboards.ErrDashboardPermissionDashboardEmpty
}
sess.Nullable("user_id", "team_id")
if _, err := sess.Insert(item); err != nil {
return err
}
}
// Update dashboard HasACL flag
dashboard := dashboards.Dashboard{HasACL: true}
_, err = sess.Cols("has_acl").Where("id=?", dashboardID).Update(&dashboard)
return err
})
}
func (d *dashboardStore) SaveAlerts(ctx context.Context, dashID int64, alerts []*alertmodels.Alert) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
existingAlerts, err := GetAlertsByDashboardId2(dashID, sess)
if err != nil {
return err
}
if err := d.updateAlerts(ctx, existingAlerts, alerts, d.log); err != nil {
return err
}
if err := d.deleteMissingAlerts(existingAlerts, alerts, sess); err != nil {
return err
}
return nil
})
}
// UnprovisionDashboard removes row in dashboard_provisioning for the dashboard making it seem as if manually created.
// The dashboard will still have `created_by = -1` to see it was not created by any particular user.
func (d *dashboardStore) UnprovisionDashboard(ctx context.Context, id int64) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
_, err := sess.Where("dashboard_id = ?", id).Delete(&dashboards.DashboardProvisioning{})
return err
})
}
func (d *dashboardStore) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *dashboards.DeleteOrphanedProvisionedDashboardsCommand) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
var result []*dashboards.DashboardProvisioning
convertedReaderNames := make([]interface{}, len(cmd.ReaderNames))
for index, readerName := range cmd.ReaderNames {
convertedReaderNames[index] = readerName
}
err := sess.NotIn("name", convertedReaderNames...).Find(&result)
if err != nil {
return err
}
for _, deleteDashCommand := range result {
err := d.DeleteDashboard(ctx, &dashboards.DeleteDashboardCommand{ID: deleteDashCommand.DashboardID})
if err != nil && !errors.Is(err, dashboards.ErrDashboardNotFound) {
return err
}
}
return nil
})
}
func (d *dashboardStore) Count(ctx context.Context, scopeParams *quota.ScopeParameters) (*quota.Map, error) {
u := "a.Map{}
type result struct {
Count int64
}
r := result{}
if err := d.store.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
rawSQL := fmt.Sprintf("SELECT COUNT(*) AS count FROM dashboard WHERE is_folder=%s", d.store.GetDialect().BooleanStr(false))
if _, err := sess.SQL(rawSQL).Get(&r); err != nil {
return err
}
return nil
}); err != nil {
return u, err
} else {
tag, err := quota.NewTag(dashboards.QuotaTargetSrv, dashboards.QuotaTarget, quota.GlobalScope)
if err != nil {
return nil, err
}
u.Set(tag, r.Count)
}
if scopeParams != nil && scopeParams.OrgID != 0 {
if err := d.store.WithDbSession(ctx, func(sess *sqlstore.DBSession) error {
rawSQL := fmt.Sprintf("SELECT COUNT(*) AS count FROM dashboard WHERE org_id=? AND is_folder=%s", d.store.GetDialect().BooleanStr(false))
if _, err := sess.SQL(rawSQL, scopeParams.OrgID).Get(&r); err != nil {
return err
}
return nil
}); err != nil {
return u, err
} else {
tag, err := quota.NewTag(dashboards.QuotaTargetSrv, dashboards.QuotaTarget, quota.OrgScope)
if err != nil {
return nil, err
}
u.Set(tag, r.Count)
}
}
return u, nil
}
func getExistingDashboardByIDOrUIDForUpdate(sess *db.Session, dash *dashboards.Dashboard, dialect migrator.Dialect, overwrite bool) (bool, error) {
dashWithIdExists := false
isParentFolderChanged := false
var existingById dashboards.Dashboard
if dash.ID > 0 {
var err error
dashWithIdExists, err = sess.Where("id=? AND org_id=?", dash.ID, dash.OrgID).Get(&existingById)
if err != nil {
return false, fmt.Errorf("SQL query for existing dashboard by ID failed: %w", err)
}
if !dashWithIdExists {
return false, dashboards.ErrDashboardNotFound
}
if dash.UID == "" {
dash.SetUID(existingById.UID)
}
}
dashWithUidExists := false
var existingByUid dashboards.Dashboard
if dash.UID != "" {
var err error
dashWithUidExists, err = sess.Where("org_id=? AND uid=?", dash.OrgID, dash.UID).Get(&existingByUid)
if err != nil {
return false, fmt.Errorf("SQL query for existing dashboard by UID failed: %w", err)
}
}
if dash.FolderID > 0 {
var existingFolder dashboards.Dashboard
folderExists, err := sess.Where("org_id=? AND id=? AND is_folder=?", dash.OrgID, dash.FolderID,
dialect.BooleanStr(true)).Get(&existingFolder)
if err != nil {
return false, fmt.Errorf("SQL query for folder failed: %w", err)
}
if !folderExists {
return false, dashboards.ErrDashboardFolderNotFound
}
}
if !dashWithIdExists && !dashWithUidExists {
return false, nil
}
if dashWithIdExists && dashWithUidExists && existingById.ID != existingByUid.ID {
return false, dashboards.ErrDashboardWithSameUIDExists
}
existing := existingById
if !dashWithIdExists && dashWithUidExists {
dash.SetID(existingByUid.ID)
dash.SetUID(existingByUid.UID)
existing = existingByUid
}
if (existing.IsFolder && !dash.IsFolder) ||
(!existing.IsFolder && dash.IsFolder) {
return isParentFolderChanged, dashboards.ErrDashboardTypeMismatch
}
if !dash.IsFolder && dash.FolderID != existing.FolderID {
isParentFolderChanged = true
}
// check for is someone else has written in between
if dash.Version != existing.Version {
if overwrite {
dash.SetVersion(existing.Version)
} else {
return isParentFolderChanged, dashboards.ErrDashboardVersionMismatch
}
}
// do not allow plugin dashboard updates without overwrite flag
if existing.PluginID != "" && !overwrite {
return isParentFolderChanged, dashboards.UpdatePluginDashboardError{PluginId: existing.PluginID}
}
return isParentFolderChanged, nil
}
func getExistingDashboardByTitleAndFolder(sess *db.Session, dash *dashboards.Dashboard, dialect migrator.Dialect, overwrite,
isParentFolderChanged bool) (bool, error) {
var existing dashboards.Dashboard
exists, err := sess.Where("org_id=? AND slug=? AND (is_folder=? OR folder_id=?)", dash.OrgID, dash.Slug,
dialect.BooleanStr(true), dash.FolderID).Get(&existing)
if err != nil {
return isParentFolderChanged, fmt.Errorf("SQL query for existing dashboard by org ID or folder ID failed: %w", err)
}
if exists && dash.ID != existing.ID {
if existing.IsFolder && !dash.IsFolder {
return isParentFolderChanged, dashboards.ErrDashboardWithSameNameAsFolder
}
if !existing.IsFolder && dash.IsFolder {
return isParentFolderChanged, dashboards.ErrDashboardFolderWithSameNameAsDashboard
}
if !dash.IsFolder && (dash.FolderID != existing.FolderID || dash.ID == 0) {
isParentFolderChanged = true
}
if overwrite {
dash.SetID(existing.ID)
dash.SetUID(existing.UID)
dash.SetVersion(existing.Version)
} else {
return isParentFolderChanged, dashboards.ErrDashboardWithSameNameInFolderExists
}
}
return isParentFolderChanged, nil
}
func saveDashboard(sess *db.Session, cmd *dashboards.SaveDashboardCommand, emitEntityEvent bool) (*dashboards.Dashboard, error) {
dash := cmd.GetDashboardModel()
userId := cmd.UserID
if userId == 0 {
userId = -1
}
if dash.ID > 0 {
var existing dashboards.Dashboard
dashWithIdExists, err := sess.Where("id=? AND org_id=?", dash.ID, dash.OrgID).Get(&existing)
if err != nil {
return nil, err
}
if !dashWithIdExists {
return nil, dashboards.ErrDashboardNotFound
}
// check for is someone else has written in between
if dash.Version != existing.Version {
if cmd.Overwrite {
dash.SetVersion(existing.Version)
} else {
return nil, dashboards.ErrDashboardVersionMismatch
}
}
// do not allow plugin dashboard updates without overwrite flag
if existing.PluginID != "" && !cmd.Overwrite {
return nil, dashboards.UpdatePluginDashboardError{PluginId: existing.PluginID}
}
}
if dash.UID == "" {
dash.SetUID(util.GenerateShortUID())
}
parentVersion := dash.Version
var affectedRows int64
var err error
if dash.ID == 0 {
dash.SetVersion(1)
dash.Created = time.Now()
dash.CreatedBy = userId
dash.Updated = time.Now()
dash.UpdatedBy = userId
metrics.MApiDashboardInsert.Inc()
affectedRows, err = sess.Insert(dash)
} else {
dash.SetVersion(dash.Version + 1)
if !cmd.UpdatedAt.IsZero() {
dash.Updated = cmd.UpdatedAt
} else {
dash.Updated = time.Now()
}
dash.UpdatedBy = userId
affectedRows, err = sess.MustCols("folder_id").ID(dash.ID).Update(dash)
}
if err != nil {
return nil, err
}
if affectedRows == 0 {
return nil, dashboards.ErrDashboardNotFound
}
dashVersion := &dashver.DashboardVersion{
DashboardID: dash.ID,
ParentVersion: parentVersion,
RestoredFrom: cmd.RestoredFrom,
Version: dash.Version,
Created: time.Now(),
CreatedBy: dash.UpdatedBy,
Message: cmd.Message,
Data: dash.Data,
}
// insert version entry
if affectedRows, err = sess.Insert(dashVersion); err != nil {
return nil, err
} else if affectedRows == 0 {
return nil, dashboards.ErrDashboardNotFound
}
// delete existing tags
if _, err = sess.Exec("DELETE FROM dashboard_tag WHERE dashboard_id=?", dash.ID); err != nil {
return nil, err
}
// insert new tags
tags := dash.GetTags()
if len(tags) > 0 {
for _, tag := range tags {
if _, err := sess.Insert(dashboardTag{DashboardId: dash.ID, Term: tag}); err != nil {
return nil, err
}
}
}
if emitEntityEvent {
_, err := sess.Insert(createEntityEvent(dash, store.EntityEventTypeUpdate))
if err != nil {
return dash, err
}
}
return dash, nil
}
func saveProvisionedData(sess *db.Session, provisioning *dashboards.DashboardProvisioning, dashboard *dashboards.Dashboard) error {
result := &dashboards.DashboardProvisioning{}
exist, err := sess.Where("dashboard_id=? AND name = ?", dashboard.ID, provisioning.Name).Get(result)
if err != nil {
return err
}
provisioning.ID = result.ID
provisioning.DashboardID = dashboard.ID
if exist {
_, err = sess.ID(result.ID).Update(provisioning)
} else {
_, err = sess.Insert(provisioning)
}
return err
}
func GetAlertsByDashboardId2(dashboardId int64, sess *db.Session) ([]*alertmodels.Alert, error) {
alerts := make([]*alertmodels.Alert, 0)
err := sess.Where("dashboard_id = ?", dashboardId).Find(&alerts)
if err != nil {
return []*alertmodels.Alert{}, err
}
return alerts, nil
}
func (d *dashboardStore) updateAlerts(ctx context.Context, existingAlerts []*alertmodels.Alert, alertsIn []*alertmodels.Alert, log log.Logger) error {
return d.store.WithDbSession(ctx, func(sess *db.Session) error {
for _, alert := range alertsIn {
update := false
var alertToUpdate *alertmodels.Alert
for _, k := range existingAlerts {
if alert.PanelID == k.PanelID {
update = true
alert.ID = k.ID
alertToUpdate = k
break
}
}
if update {
if alertToUpdate.ContainsUpdates(alert) {
alert.Updated = time.Now()
alert.State = alertToUpdate.State
sess.MustCols("message", "for")
_, err := sess.ID(alert.ID).Update(alert)
if err != nil {
return err
}
log.Debug("Alert updated", "name", alert.Name, "id", alert.ID)
}
} else {
alert.Updated = time.Now()
alert.Created = time.Now()
alert.State = alertmodels.AlertStateUnknown
alert.NewStateDate = time.Now()
_, err := sess.Insert(alert)
if err != nil {
return err
}
log.Debug("Alert inserted", "name", alert.Name, "id", alert.ID)
}
tags := alert.GetTagsFromSettings()
if _, err := sess.Exec("DELETE FROM alert_rule_tag WHERE alert_id = ?", alert.ID); err != nil {
return err
}
if tags != nil {
tags, err := d.tagService.EnsureTagsExist(ctx, tags)
if err != nil {
return err
}
for _, tag := range tags {
if _, err := sess.Exec("INSERT INTO alert_rule_tag (alert_id, tag_id) VALUES(?,?)", alert.ID, tag.Id); err != nil {
return err
}
}
}
}
return nil
})
}
func (d *dashboardStore) deleteMissingAlerts(alerts []*alertmodels.Alert, existingAlerts []*alertmodels.Alert, sess *db.Session) error {
for _, missingAlert := range alerts {
missing := true
for _, k := range existingAlerts {
if missingAlert.PanelID == k.PanelID {
missing = false
break
}
}
if missing {
if err := d.deleteAlertByIdInternal(missingAlert.ID, "Removed from dashboard", sess); err != nil {
// No use trying to delete more, since we're in a transaction and it will be
// rolled back on error.
return err
}
}
}
return nil
}
func (d *dashboardStore) deleteAlertByIdInternal(alertId int64, reason string, sess *db.Session) error {
d.log.Debug("Deleting alert", "id", alertId, "reason", reason)
if _, err := sess.Exec("DELETE FROM alert WHERE id = ?", alertId); err != nil {
return err
}
if _, err := sess.Exec("DELETE FROM annotation WHERE alert_id = ?", alertId); err != nil {
return err
}
if _, err := sess.Exec("DELETE FROM alert_notification_state WHERE alert_id = ?", alertId); err != nil {
return err
}
if _, err := sess.Exec("DELETE FROM alert_rule_tag WHERE alert_id = ?", alertId); err != nil {
return err
}
return nil
}
func (d *dashboardStore) GetDashboardsByPluginID(ctx context.Context, query *dashboards.GetDashboardsByPluginIDQuery) ([]*dashboards.Dashboard, error) {
var dashboards = make([]*dashboards.Dashboard, 0)
err := d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
whereExpr := "org_id=? AND plugin_id=? AND is_folder=" + d.store.GetDialect().BooleanStr(false)
err := dbSession.Where(whereExpr, query.OrgID, query.PluginID).Find(&dashboards)
return err
})
if err != nil {
return nil, err
}
return dashboards, nil
}
func (d *dashboardStore) DeleteDashboard(ctx context.Context, cmd *dashboards.DeleteDashboardCommand) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
return d.deleteDashboard(cmd, sess, d.emitEntityEvent())
})
}
func (d *dashboardStore) deleteDashboard(cmd *dashboards.DeleteDashboardCommand, sess *db.Session, emitEntityEvent bool) error {
dashboard := dashboards.Dashboard{ID: cmd.ID, OrgID: cmd.OrgID}
has, err := sess.Get(&dashboard)
if err != nil {
return err
} else if !has {
return dashboards.ErrDashboardNotFound
}
deletes := []string{
"DELETE FROM dashboard_tag WHERE dashboard_id = ? ",
"DELETE FROM star WHERE dashboard_id = ? ",
"DELETE FROM dashboard WHERE id = ?",
"DELETE FROM playlist_item WHERE type = 'dashboard_by_id' AND value = ?",
"DELETE FROM dashboard_version WHERE dashboard_id = ?",
"DELETE FROM annotation WHERE dashboard_id = ?",
"DELETE FROM dashboard_provisioning WHERE dashboard_id = ?",
"DELETE FROM dashboard_acl WHERE dashboard_id = ?",
}
if dashboard.IsFolder {
deletes = append(deletes, "DELETE FROM dashboard WHERE folder_id = ?")
if err := d.deleteChildrenDashboardAssociations(sess, dashboard); err != nil {
return err
}
// remove all access control permission with folder scope
_, err = sess.Exec("DELETE FROM permission WHERE scope = ?", dashboards.ScopeFoldersProvider.GetResourceScopeUID(dashboard.UID))
if err != nil {
return err
}
if err := deleteFolderAlertRules(sess, dashboard, cmd.ForceDeleteFolderRules); err != nil {
return err
}
} else {
_, err = sess.Exec("DELETE FROM permission WHERE scope = ?", ac.GetResourceScopeUID("dashboards", dashboard.UID))
if err != nil {
return err
}
}
if err := d.deleteAlertDefinition(dashboard.ID, sess); err != nil {
return err
}
for _, sql := range deletes {
_, err := sess.Exec(sql, dashboard.ID)
if err != nil {
return err
}
}
if emitEntityEvent {
_, err := sess.Insert(createEntityEvent(&dashboard, store.EntityEventTypeDelete))
if err != nil {
return err
}
}
return nil
}
func (d *dashboardStore) deleteChildrenDashboardAssociations(sess *db.Session, dashboard dashboards.Dashboard) error {
var dashIds []struct {
Id int64
Uid string
}
err := sess.SQL("SELECT id, uid FROM dashboard WHERE folder_id = ?", dashboard.ID).Find(&dashIds)
if err != nil {
return err
}
if len(dashIds) > 0 {
for _, dash := range dashIds {
if err := d.deleteAlertDefinition(dash.Id, sess); err != nil {
return err
}
// remove all access control permission with child dashboard scopes
_, err = sess.Exec("DELETE FROM permission WHERE scope = ?", ac.GetResourceScopeUID("dashboards", dash.Uid))
if err != nil {
return err
}
}
childrenDeletes := []string{
"DELETE FROM dashboard_tag WHERE dashboard_id IN (SELECT id FROM dashboard WHERE org_id = ? AND folder_id = ?)",
"DELETE FROM star WHERE dashboard_id IN (SELECT id FROM dashboard WHERE org_id = ? AND folder_id = ?)",
"DELETE FROM dashboard_version WHERE dashboard_id IN (SELECT id FROM dashboard WHERE org_id = ? AND folder_id = ?)",
"DELETE FROM annotation WHERE dashboard_id IN (SELECT id FROM dashboard WHERE org_id = ? AND folder_id = ?)",
"DELETE FROM dashboard_provisioning WHERE dashboard_id IN (SELECT id FROM dashboard WHERE org_id = ? AND folder_id = ?)",
"DELETE FROM dashboard_acl WHERE dashboard_id IN (SELECT id FROM dashboard WHERE org_id = ? AND folder_id = ?)",
}
for _, sql := range childrenDeletes {
_, err := sess.Exec(sql, dashboard.OrgID, dashboard.ID)
if err != nil {
return err
}
}
}
return nil
}
func deleteFolderAlertRules(sess *db.Session, dashboard dashboards.Dashboard, forceDeleteFolderAlertRules bool) error {
var existingRuleID int64
exists, err := sess.Table("alert_rule").Where("namespace_uid = (SELECT uid FROM dashboard WHERE id = ?)", dashboard.ID).Cols("id").Get(&existingRuleID)
if err != nil {
return err
}
if exists {
if !forceDeleteFolderAlertRules {
return fmt.Errorf("folder cannot be deleted: %w", dashboards.ErrFolderContainsAlertRules)
}
// Delete all rules under this folder.
deleteNGAlertsByFolder := []string{
"DELETE FROM alert_rule WHERE namespace_uid = (SELECT uid FROM dashboard WHERE id = ?)",
"DELETE FROM alert_rule_version WHERE rule_namespace_uid = (SELECT uid FROM dashboard WHERE id = ?)",
}
for _, sql := range deleteNGAlertsByFolder {
_, err := sess.Exec(sql, dashboard.ID)
if err != nil {
return err
}
}
}
return nil
}
func createEntityEvent(dashboard *dashboards.Dashboard, eventType store.EntityEventType) *store.EntityEvent {
var entityEvent *store.EntityEvent
if dashboard.IsFolder {
entityEvent = &store.EntityEvent{
EventType: eventType,
EntityId: store.CreateDatabaseEntityId(dashboard.UID, dashboard.OrgID, store.EntityTypeFolder),
Created: time.Now().Unix(),
}
} else {
entityEvent = &store.EntityEvent{
EventType: eventType,
EntityId: store.CreateDatabaseEntityId(dashboard.UID, dashboard.OrgID, store.EntityTypeDashboard),
Created: time.Now().Unix(),
}
}
return entityEvent
}
func (d *dashboardStore) deleteAlertDefinition(dashboardId int64, sess *db.Session) error {
alerts := make([]*alertmodels.Alert, 0)
if err := sess.Where("dashboard_id = ?", dashboardId).Find(&alerts); err != nil {
return err
}
for _, alert := range alerts {
if err := d.deleteAlertByIdInternal(alert.ID, "Dashboard deleted", sess); err != nil {
// If we return an error, the current transaction gets rolled back, so no use
// trying to delete more
return err
}
}
return nil
}
func (d *dashboardStore) GetDashboard(ctx context.Context, query *dashboards.GetDashboardQuery) (*dashboards.Dashboard, error) {
var queryResult *dashboards.Dashboard
err := d.store.WithDbSession(ctx, func(sess *db.Session) error {
if query.ID == 0 && len(query.UID) == 0 && (query.Title == nil || query.FolderID == nil) {
return dashboards.ErrDashboardIdentifierNotSet
}
dashboard := dashboards.Dashboard{OrgID: query.OrgID, ID: query.ID, UID: query.UID}
mustCols := []string{}
if query.Title != nil {
dashboard.Title = *query.Title
mustCols = append(mustCols, "title")
}
if query.FolderID != nil {
dashboard.FolderID = *query.FolderID
mustCols = append(mustCols, "folder_id")
}
has, err := sess.MustCols(mustCols...).Get(&dashboard)
if err != nil {
return err
} else if !has {
return dashboards.ErrDashboardNotFound
}
dashboard.SetID(dashboard.ID)
dashboard.SetUID(dashboard.UID)
queryResult = &dashboard
return nil
})
return queryResult, err
}
func (d *dashboardStore) GetDashboardUIDByID(ctx context.Context, query *dashboards.GetDashboardRefByIDQuery) (*dashboards.DashboardRef, error) {
us := &dashboards.DashboardRef{}
err := d.store.WithDbSession(ctx, func(sess *db.Session) error {
var rawSQL = `SELECT uid, slug from dashboard WHERE Id=?`
exists, err := sess.SQL(rawSQL, query.ID).Get(us)
if err != nil {
return err
} else if !exists {
return dashboards.ErrDashboardNotFound
}
return nil
})
if err != nil {
return nil, err
}
return us, nil
}
func (d *dashboardStore) GetDashboards(ctx context.Context, query *dashboards.GetDashboardsQuery) ([]*dashboards.Dashboard, error) {
var dashboards = make([]*dashboards.Dashboard, 0)
err := d.store.WithDbSession(ctx, func(sess *db.Session) error {
if len(query.DashboardIDs) == 0 && len(query.DashboardUIDs) == 0 {
return star.ErrCommandValidationFailed
}
var session *xorm.Session
if len(query.DashboardIDs) > 0 {
session = sess.In("id", query.DashboardIDs)
} else {
session = sess.In("uid", query.DashboardUIDs)
}
if query.OrgID > 0 {
session = sess.Where("org_id = ?", query.OrgID)
}
err := session.Find(&dashboards)
return err
})
if err != nil {
return nil, err
}
return dashboards, nil
}
func (d *dashboardStore) FindDashboards(ctx context.Context, query *dashboards.FindPersistedDashboardsQuery) ([]dashboards.DashboardSearchProjection, error) {
filters := []interface{}{
permissions.DashboardPermissionFilter{
OrgRole: query.SignedInUser.OrgRole,
OrgId: query.SignedInUser.OrgID,
Dialect: d.store.GetDialect(),
UserId: query.SignedInUser.UserID,
PermissionLevel: query.Permission,
},
}
if !ac.IsDisabled(d.cfg) {
recursiveQueriesAreSupported, err := d.store.RecursiveQueriesAreSupported()
if err != nil {
return nil, err
}
// if access control is enabled, overwrite the filters so far
filters = []interface{}{
permissions.NewAccessControlDashboardPermissionFilter(query.SignedInUser, query.Permission, query.Type, d.features, recursiveQueriesAreSupported),
}
}
for _, filter := range query.Sort.Filter {
filters = append(filters, filter)
}
filters = append(filters, query.Filters...)
if query.OrgId != 0 {
filters = append(filters, searchstore.OrgFilter{OrgId: query.OrgId})
} else if query.SignedInUser.OrgID != 0 {
filters = append(filters, searchstore.OrgFilter{OrgId: query.SignedInUser.OrgID})
}
if len(query.Tags) > 0 {
filters = append(filters, searchstore.TagsFilter{Tags: query.Tags})
}
if len(query.DashboardUIDs) > 0 {
filters = append(filters, searchstore.DashboardFilter{UIDs: query.DashboardUIDs})
} else if len(query.DashboardIds) > 0 {
filters = append(filters, searchstore.DashboardIDFilter{IDs: query.DashboardIds})
}
if len(query.Title) > 0 {
filters = append(filters, searchstore.TitleFilter{Dialect: d.store.GetDialect(), Title: query.Title})
}
if len(query.Type) > 0 {
filters = append(filters, searchstore.TypeFilter{Dialect: d.store.GetDialect(), Type: query.Type})
}
if len(query.FolderIds) > 0 {
filters = append(filters, searchstore.FolderFilter{IDs: query.FolderIds})
}
var res []dashboards.DashboardSearchProjection
sb := &searchstore.Builder{Dialect: d.store.GetDialect(), Filters: filters}
limit := query.Limit
if limit < 1 {
limit = 1000
}
page := query.Page
if page < 1 {
page = 1
}
sql, params := sb.ToSQL(limit, page)
err := d.store.WithDbSession(ctx, func(sess *db.Session) error {
return sess.SQL(sql, params...).Find(&res)
})
if err != nil {
return nil, err
}
return res, nil
}
func (d *dashboardStore) GetDashboardTags(ctx context.Context, query *dashboards.GetDashboardTagsQuery) ([]*dashboards.DashboardTagCloudItem, error) {
queryResult := make([]*dashboards.DashboardTagCloudItem, 0)
err := d.store.WithDbSession(ctx, func(dbSession *db.Session) error {
sql := `SELECT
COUNT(*) as count,
term
FROM dashboard
INNER JOIN dashboard_tag on dashboard_tag.dashboard_id = dashboard.id
WHERE dashboard.org_id=?
GROUP BY term
ORDER BY term`
sess := dbSession.SQL(sql, query.OrgID)
err := sess.Find(&queryResult)
return err
})
if err != nil {
return nil, err
}
return queryResult, nil
}
// CountDashboardsInFolder returns a count of all dashboards associated with the
// given parent folder ID.
//
// This will be updated to take CountDashboardsInFolderQuery as an argument and
// lookup dashboards using the ParentFolderUID when dashboards are associated with a parent folder UID instead of ID.
func (d *dashboardStore) CountDashboardsInFolder(
ctx context.Context, req *dashboards.CountDashboardsInFolderRequest) (int64, error) {
var count int64
var err error
err = d.store.WithDbSession(ctx, func(sess *db.Session) error {
session := sess.In("folder_id", req.FolderID).In("org_id", req.OrgID).
In("is_folder", d.store.GetDialect().BooleanStr(false))
count, err = session.Count(&dashboards.Dashboard{})
return err
})
return count, err
}
func (d *dashboardStore) DeleteDashboardsInFolder(
ctx context.Context, req *dashboards.DeleteDashboardsInFolderRequest) error {
return d.store.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
dashboard := dashboards.Dashboard{OrgID: req.OrgID}
has, err := sess.Where("uid = ? AND org_id = ?", req.FolderUID, req.OrgID).Get(&dashboard)
if err != nil {
return err
}
if !has {
return dashboards.ErrFolderNotFound
}
if err := d.deleteChildrenDashboardAssociations(sess, dashboard); err != nil {
return err
}
_, err = sess.Where("folder_id = ? AND org_id = ? AND is_folder = ?", dashboard.ID, dashboard.OrgID, false).Delete(&dashboards.Dashboard{})
return err
})
}
func readQuotaConfig(cfg *setting.Cfg) (*quota.Map, error) {
limits := "a.Map{}
if cfg == nil {
return limits, nil
}
globalQuotaTag, err := quota.NewTag(dashboards.QuotaTargetSrv, dashboards.QuotaTarget, quota.GlobalScope)
if err != nil {
return "a.Map{}, err
}
orgQuotaTag, err := quota.NewTag(dashboards.QuotaTargetSrv, dashboards.QuotaTarget, quota.OrgScope)
if err != nil {
return "a.Map{}, err
}
limits.Set(globalQuotaTag, cfg.Quota.Global.Dashboard)
limits.Set(orgQuotaTag, cfg.Quota.Org.Dashboard)
return limits, nil
}
|
pkg/services/dashboards/database/database.go
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.00030063639860600233,
0.00017388116975780576,
0.0001619603717699647,
0.00017261994071304798,
0.000014504247701552231
] |
{
"id": 2,
"code_window": [
" <>\n",
" {selectionToggle && selection && (\n",
" <div onClick={onToggleFolder}>\n",
" <Checkbox\n",
" value={selection(section.kind, section.uid)}\n",
" aria-label={t('search.folder-view.select-folder', 'Select folder')}\n",
" />\n",
" </div>\n",
" )}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" className={styles.checkbox}\n"
],
"file_path": "public/app/features/search/page/components/FolderSection.tsx",
"type": "add",
"edit_start_line_idx": 151
}
|
import { css } from '@emotion/css';
import React, { useCallback } from 'react';
import { useAsync, useLocalStorage } from 'react-use';
import { GrafanaTheme2, toIconName } from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { Card, Checkbox, CollapsableSection, Icon, Spinner, useStyles2 } from '@grafana/ui';
import { config } from 'app/core/config';
import { t } from 'app/core/internationalization';
import { getSectionStorageKey } from 'app/features/search/utils';
import { useUniqueId } from 'app/plugins/datasource/influxdb/components/useUniqueId';
import { SearchItem } from '../..';
import { GENERAL_FOLDER_UID } from '../../constants';
import { getGrafanaSearcher } from '../../service';
import { getFolderChildren } from '../../service/folders';
import { queryResultToViewItem } from '../../service/utils';
import { DashboardViewItem } from '../../types';
import { SelectionChecker, SelectionToggle } from '../selection';
interface SectionHeaderProps {
selection?: SelectionChecker;
selectionToggle?: SelectionToggle;
onClickItem?: (e: React.MouseEvent<HTMLElement>) => void;
onTagSelected: (tag: string) => void;
section: DashboardViewItem;
renderStandaloneBody?: boolean; // render the body on its own
tags?: string[];
}
async function getChildren(section: DashboardViewItem, tags: string[] | undefined): Promise<DashboardViewItem[]> {
if (config.featureToggles.nestedFolders) {
return getFolderChildren(section.uid, section.title);
}
const query = section.itemsUIDs
? {
uid: section.itemsUIDs,
}
: {
query: '*',
kind: ['dashboard'],
location: section.uid,
sort: 'name_sort',
limit: 1000, // this component does not have infinite scroll, so we need to load everything upfront
};
const raw = await getGrafanaSearcher().search({ ...query, tags });
return raw.view.map((v) => queryResultToViewItem(v, raw.view));
}
export const FolderSection = ({
section,
selectionToggle,
onClickItem,
onTagSelected,
selection,
renderStandaloneBody,
tags,
}: SectionHeaderProps) => {
const editable = selectionToggle != null;
const styles = useStyles2(useCallback((theme: GrafanaTheme2) => getSectionHeaderStyles(theme, editable), [editable]));
const [sectionExpanded, setSectionExpanded] = useLocalStorage(getSectionStorageKey(section.title), false);
const results = useAsync(async () => {
if (!sectionExpanded && !renderStandaloneBody) {
return Promise.resolve([]);
}
const childItems = getChildren(section, tags);
return childItems;
}, [sectionExpanded, tags]);
const onSectionExpand = () => {
setSectionExpanded(!sectionExpanded);
};
const onToggleFolder = (evt: React.FormEvent) => {
evt.preventDefault();
evt.stopPropagation();
if (selectionToggle && selection) {
const checked = !selection(section.kind, section.uid);
selectionToggle(section.kind, section.uid);
const sub = results.value ?? [];
for (const item of sub) {
if (selection(item.kind, item.uid!) !== checked) {
selectionToggle(item.kind, item.uid!);
}
}
}
};
const id = useUniqueId();
const labelId = `section-header-label-${id}`;
let icon = toIconName(section.icon ?? '');
if (!icon) {
icon = sectionExpanded ? 'folder-open' : 'folder';
}
const renderResults = () => {
if (!results.value) {
return null;
} else if (results.value.length === 0 && !results.loading) {
return (
<Card>
<Card.Heading>No results found</Card.Heading>
</Card>
);
}
return results.value.map((item) => {
return (
<SearchItem
key={item.uid}
item={item}
onTagSelected={onTagSelected}
onToggleChecked={(item) => selectionToggle?.(item.kind, item.uid)}
editable={Boolean(selection != null)}
onClickItem={onClickItem}
isSelected={selection?.(item.kind, item.uid)}
/>
);
});
};
// Skip the folder wrapper
if (renderStandaloneBody) {
return (
<div className={styles.folderViewResults}>
{!results.value?.length && results.loading ? <Spinner className={styles.spinner} /> : renderResults()}
</div>
);
}
return (
<CollapsableSection
headerDataTestId={selectors.components.Search.folderHeader(section.title)}
contentDataTestId={selectors.components.Search.folderContent(section.title)}
isOpen={sectionExpanded ?? false}
onToggle={onSectionExpand}
className={styles.wrapper}
contentClassName={styles.content}
loading={results.loading}
labelId={labelId}
label={
<>
{selectionToggle && selection && (
<div onClick={onToggleFolder}>
<Checkbox
value={selection(section.kind, section.uid)}
aria-label={t('search.folder-view.select-folder', 'Select folder')}
/>
</div>
)}
<div className={styles.icon}>
<Icon name={icon} />
</div>
<div className={styles.text}>
<span id={labelId}>{section.title}</span>
{section.url && section.uid !== GENERAL_FOLDER_UID && (
<a href={section.url} className={styles.link}>
<span className={styles.separator}>|</span> <Icon name="folder-upload" />{' '}
{t('search.folder-view.go-to-folder', 'Go to folder')}
</a>
)}
</div>
</>
}
>
{results.value && <ul className={styles.sectionItems}>{renderResults()}</ul>}
</CollapsableSection>
);
};
const getSectionHeaderStyles = (theme: GrafanaTheme2, editable: boolean) => {
const sm = theme.spacing(1);
return {
wrapper: css`
align-items: center;
font-size: ${theme.typography.size.base};
padding: 12px;
border-bottom: none;
color: ${theme.colors.text.secondary};
z-index: 1;
&:hover,
&.selected {
color: ${theme.colors.text};
}
&:hover,
&:focus-visible,
&:focus-within {
a {
opacity: 1;
}
}
`,
sectionItems: css`
margin: 0 24px 0 32px;
`,
icon: css`
padding: 0 ${sm} 0 ${editable ? 0 : sm};
`,
folderViewResults: css`
overflow: auto;
`,
text: css`
flex-grow: 1;
line-height: 24px;
`,
link: css`
padding: 2px 10px 0;
color: ${theme.colors.text.secondary};
opacity: 0;
transition: opacity 150ms ease-in-out;
`,
separator: css`
margin-right: 6px;
`,
content: css`
padding-top: 0px;
padding-bottom: 0px;
`,
spinner: css`
display: grid;
place-content: center;
padding-bottom: 1rem;
`,
};
};
|
public/app/features/search/page/components/FolderSection.tsx
| 1 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.9447709321975708,
0.057894572615623474,
0.00016541585500817746,
0.00034846499329432845,
0.1979304850101471
] |
{
"id": 2,
"code_window": [
" <>\n",
" {selectionToggle && selection && (\n",
" <div onClick={onToggleFolder}>\n",
" <Checkbox\n",
" value={selection(section.kind, section.uid)}\n",
" aria-label={t('search.folder-view.select-folder', 'Select folder')}\n",
" />\n",
" </div>\n",
" )}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" className={styles.checkbox}\n"
],
"file_path": "public/app/features/search/page/components/FolderSection.tsx",
"type": "add",
"edit_start_line_idx": 151
}
|
import { IconName } from '@grafana/ui';
interface TextBreadcrumb {
text: string;
href: string;
}
interface IconBreadcrumb extends TextBreadcrumb {
icon: IconName;
}
export type Breadcrumb = TextBreadcrumb | IconBreadcrumb;
|
public/app/core/components/Breadcrumbs/types.ts
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.00016958529886323959,
0.0001671188947511837,
0.0001646524906391278,
0.0001671188947511837,
0.0000024664041120558977
] |
{
"id": 2,
"code_window": [
" <>\n",
" {selectionToggle && selection && (\n",
" <div onClick={onToggleFolder}>\n",
" <Checkbox\n",
" value={selection(section.kind, section.uid)}\n",
" aria-label={t('search.folder-view.select-folder', 'Select folder')}\n",
" />\n",
" </div>\n",
" )}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" className={styles.checkbox}\n"
],
"file_path": "public/app/features/search/page/components/FolderSection.tsx",
"type": "add",
"edit_start_line_idx": 151
}
|
package setting
import (
"github.com/grafana/grafana-azure-sdk-go/azsettings"
)
func (cfg *Cfg) readAzureSettings() {
azureSettings := &azsettings.AzureSettings{}
azureSection := cfg.Raw.Section("azure")
// Cloud
cloudName := azureSection.Key("cloud").MustString(azsettings.AzurePublic)
azureSettings.Cloud = azsettings.NormalizeAzureCloud(cloudName)
// Managed Identity authentication
azureSettings.ManagedIdentityEnabled = azureSection.Key("managed_identity_enabled").MustBool(false)
azureSettings.ManagedIdentityClientId = azureSection.Key("managed_identity_client_id").String()
// User Identity authentication
if azureSection.Key("user_identity_enabled").MustBool(false) {
azureSettings.UserIdentityEnabled = true
tokenEndpointSettings := &azsettings.TokenEndpointSettings{}
// Get token endpoint from Azure AD settings if enabled
azureAdSection := cfg.Raw.Section("auth.azuread")
if azureAdSection.Key("enabled").MustBool(false) {
tokenEndpointSettings.TokenUrl = azureAdSection.Key("token_url").String()
tokenEndpointSettings.ClientId = azureAdSection.Key("client_id").String()
tokenEndpointSettings.ClientSecret = azureAdSection.Key("client_secret").String()
}
// Override individual settings
if val := azureSection.Key("user_identity_token_url").String(); val != "" {
tokenEndpointSettings.TokenUrl = val
}
if val := azureSection.Key("user_identity_client_id").String(); val != "" {
tokenEndpointSettings.ClientId = val
tokenEndpointSettings.ClientSecret = ""
}
if val := azureSection.Key("user_identity_client_secret").String(); val != "" {
tokenEndpointSettings.ClientSecret = val
}
azureSettings.UserIdentityTokenEndpoint = tokenEndpointSettings
}
cfg.Azure = azureSettings
}
|
pkg/setting/setting_azure.go
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.000171710315044038,
0.0001697521365713328,
0.00016769686772022396,
0.00016975548351183534,
0.0000013509322798199719
] |
{
"id": 2,
"code_window": [
" <>\n",
" {selectionToggle && selection && (\n",
" <div onClick={onToggleFolder}>\n",
" <Checkbox\n",
" value={selection(section.kind, section.uid)}\n",
" aria-label={t('search.folder-view.select-folder', 'Select folder')}\n",
" />\n",
" </div>\n",
" )}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" className={styles.checkbox}\n"
],
"file_path": "public/app/features/search/page/components/FolderSection.tsx",
"type": "add",
"edit_start_line_idx": 151
}
|
import React, { FC } from 'react';
import { createFilter, GroupBase, OptionsOrGroups } from 'react-select';
import { SelectableValue } from '@grafana/data';
import { Field, Select } from '@grafana/ui';
export interface AlertLabelDropdownProps {
onChange: (newValue: SelectableValue<string>) => void;
onOpenMenu?: () => void;
options: SelectableValue[];
defaultValue?: SelectableValue;
type: 'key' | 'value';
}
const _customFilter = createFilter({ ignoreCase: false });
function customFilter(opt: SelectableValue, searchQuery: string) {
return _customFilter(
{
label: opt.label ?? '',
value: opt.value ?? '',
data: {},
},
searchQuery
);
}
const handleIsValidNewOption = (
inputValue: string,
value: SelectableValue<string> | null,
options: OptionsOrGroups<SelectableValue<string>, GroupBase<SelectableValue<string>>>
) => {
const exactValueExists = options.some((el) => el.label === inputValue);
const valueIsNotEmpty = inputValue.trim().length;
return !Boolean(exactValueExists) && Boolean(valueIsNotEmpty);
};
const AlertLabelDropdown: FC<AlertLabelDropdownProps> = React.forwardRef<HTMLDivElement, AlertLabelDropdownProps>(
function labelPicker({ onChange, options, defaultValue, type, onOpenMenu = () => {} }, ref) {
return (
<div ref={ref}>
<Field disabled={false} data-testid={`alertlabel-${type}-picker`}>
<Select<string>
placeholder={`Choose ${type}`}
width={29}
className="ds-picker select-container"
backspaceRemovesValue={false}
onChange={onChange}
onOpenMenu={onOpenMenu}
filterOption={customFilter}
isValidNewOption={handleIsValidNewOption}
options={options}
maxMenuHeight={500}
noOptionsMessage="No labels found"
defaultValue={defaultValue}
allowCustomValue
/>
</Field>
</div>
);
}
);
export default AlertLabelDropdown;
|
public/app/features/alerting/unified/components/AlertLabelDropdown.tsx
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.00018195147276856005,
0.00017191663209814578,
0.0001656630338402465,
0.00016848783707246184,
0.000005808680725749582
] |
{
"id": 3,
"code_window": [
" place-content: center;\n",
" padding-bottom: 1rem;\n",
" `,\n",
" };\n",
"};"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" checkbox: css({\n",
" marginRight: theme.spacing(1),\n",
" }),\n"
],
"file_path": "public/app/features/search/page/components/FolderSection.tsx",
"type": "add",
"edit_start_line_idx": 234
}
|
import { css } from '@emotion/css';
import React, { useCallback } from 'react';
import { useAsync, useLocalStorage } from 'react-use';
import { GrafanaTheme2, toIconName } from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { Card, Checkbox, CollapsableSection, Icon, Spinner, useStyles2 } from '@grafana/ui';
import { config } from 'app/core/config';
import { t } from 'app/core/internationalization';
import { getSectionStorageKey } from 'app/features/search/utils';
import { useUniqueId } from 'app/plugins/datasource/influxdb/components/useUniqueId';
import { SearchItem } from '../..';
import { GENERAL_FOLDER_UID } from '../../constants';
import { getGrafanaSearcher } from '../../service';
import { getFolderChildren } from '../../service/folders';
import { queryResultToViewItem } from '../../service/utils';
import { DashboardViewItem } from '../../types';
import { SelectionChecker, SelectionToggle } from '../selection';
interface SectionHeaderProps {
selection?: SelectionChecker;
selectionToggle?: SelectionToggle;
onClickItem?: (e: React.MouseEvent<HTMLElement>) => void;
onTagSelected: (tag: string) => void;
section: DashboardViewItem;
renderStandaloneBody?: boolean; // render the body on its own
tags?: string[];
}
async function getChildren(section: DashboardViewItem, tags: string[] | undefined): Promise<DashboardViewItem[]> {
if (config.featureToggles.nestedFolders) {
return getFolderChildren(section.uid, section.title);
}
const query = section.itemsUIDs
? {
uid: section.itemsUIDs,
}
: {
query: '*',
kind: ['dashboard'],
location: section.uid,
sort: 'name_sort',
limit: 1000, // this component does not have infinite scroll, so we need to load everything upfront
};
const raw = await getGrafanaSearcher().search({ ...query, tags });
return raw.view.map((v) => queryResultToViewItem(v, raw.view));
}
export const FolderSection = ({
section,
selectionToggle,
onClickItem,
onTagSelected,
selection,
renderStandaloneBody,
tags,
}: SectionHeaderProps) => {
const editable = selectionToggle != null;
const styles = useStyles2(useCallback((theme: GrafanaTheme2) => getSectionHeaderStyles(theme, editable), [editable]));
const [sectionExpanded, setSectionExpanded] = useLocalStorage(getSectionStorageKey(section.title), false);
const results = useAsync(async () => {
if (!sectionExpanded && !renderStandaloneBody) {
return Promise.resolve([]);
}
const childItems = getChildren(section, tags);
return childItems;
}, [sectionExpanded, tags]);
const onSectionExpand = () => {
setSectionExpanded(!sectionExpanded);
};
const onToggleFolder = (evt: React.FormEvent) => {
evt.preventDefault();
evt.stopPropagation();
if (selectionToggle && selection) {
const checked = !selection(section.kind, section.uid);
selectionToggle(section.kind, section.uid);
const sub = results.value ?? [];
for (const item of sub) {
if (selection(item.kind, item.uid!) !== checked) {
selectionToggle(item.kind, item.uid!);
}
}
}
};
const id = useUniqueId();
const labelId = `section-header-label-${id}`;
let icon = toIconName(section.icon ?? '');
if (!icon) {
icon = sectionExpanded ? 'folder-open' : 'folder';
}
const renderResults = () => {
if (!results.value) {
return null;
} else if (results.value.length === 0 && !results.loading) {
return (
<Card>
<Card.Heading>No results found</Card.Heading>
</Card>
);
}
return results.value.map((item) => {
return (
<SearchItem
key={item.uid}
item={item}
onTagSelected={onTagSelected}
onToggleChecked={(item) => selectionToggle?.(item.kind, item.uid)}
editable={Boolean(selection != null)}
onClickItem={onClickItem}
isSelected={selection?.(item.kind, item.uid)}
/>
);
});
};
// Skip the folder wrapper
if (renderStandaloneBody) {
return (
<div className={styles.folderViewResults}>
{!results.value?.length && results.loading ? <Spinner className={styles.spinner} /> : renderResults()}
</div>
);
}
return (
<CollapsableSection
headerDataTestId={selectors.components.Search.folderHeader(section.title)}
contentDataTestId={selectors.components.Search.folderContent(section.title)}
isOpen={sectionExpanded ?? false}
onToggle={onSectionExpand}
className={styles.wrapper}
contentClassName={styles.content}
loading={results.loading}
labelId={labelId}
label={
<>
{selectionToggle && selection && (
<div onClick={onToggleFolder}>
<Checkbox
value={selection(section.kind, section.uid)}
aria-label={t('search.folder-view.select-folder', 'Select folder')}
/>
</div>
)}
<div className={styles.icon}>
<Icon name={icon} />
</div>
<div className={styles.text}>
<span id={labelId}>{section.title}</span>
{section.url && section.uid !== GENERAL_FOLDER_UID && (
<a href={section.url} className={styles.link}>
<span className={styles.separator}>|</span> <Icon name="folder-upload" />{' '}
{t('search.folder-view.go-to-folder', 'Go to folder')}
</a>
)}
</div>
</>
}
>
{results.value && <ul className={styles.sectionItems}>{renderResults()}</ul>}
</CollapsableSection>
);
};
const getSectionHeaderStyles = (theme: GrafanaTheme2, editable: boolean) => {
const sm = theme.spacing(1);
return {
wrapper: css`
align-items: center;
font-size: ${theme.typography.size.base};
padding: 12px;
border-bottom: none;
color: ${theme.colors.text.secondary};
z-index: 1;
&:hover,
&.selected {
color: ${theme.colors.text};
}
&:hover,
&:focus-visible,
&:focus-within {
a {
opacity: 1;
}
}
`,
sectionItems: css`
margin: 0 24px 0 32px;
`,
icon: css`
padding: 0 ${sm} 0 ${editable ? 0 : sm};
`,
folderViewResults: css`
overflow: auto;
`,
text: css`
flex-grow: 1;
line-height: 24px;
`,
link: css`
padding: 2px 10px 0;
color: ${theme.colors.text.secondary};
opacity: 0;
transition: opacity 150ms ease-in-out;
`,
separator: css`
margin-right: 6px;
`,
content: css`
padding-top: 0px;
padding-bottom: 0px;
`,
spinner: css`
display: grid;
place-content: center;
padding-bottom: 1rem;
`,
};
};
|
public/app/features/search/page/components/FolderSection.tsx
| 1 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.997799813747406,
0.04188165441155434,
0.00016586836136411875,
0.00017093063797801733,
0.19932378828525543
] |
{
"id": 3,
"code_window": [
" place-content: center;\n",
" padding-bottom: 1rem;\n",
" `,\n",
" };\n",
"};"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" checkbox: css({\n",
" marginRight: theme.spacing(1),\n",
" }),\n"
],
"file_path": "public/app/features/search/page/components/FolderSection.tsx",
"type": "add",
"edit_start_line_idx": 234
}
|
package clients
import (
"context"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/util/errutil"
"github.com/grafana/grafana/pkg/web"
)
var (
errBadForm = errutil.NewBase(errutil.StatusBadRequest, "form-auth.invalid", errutil.WithPublicMessage("bad login data"))
)
var _ authn.Client = new(Form)
func ProvideForm(client authn.PasswordClient) *Form {
return &Form{client}
}
type Form struct {
client authn.PasswordClient
}
type loginForm struct {
Username string `json:"user" binding:"Required"`
Password string `json:"password" binding:"Required"`
}
func (c *Form) Name() string {
return authn.ClientForm
}
func (c *Form) Authenticate(ctx context.Context, r *authn.Request) (*authn.Identity, error) {
form := loginForm{}
if err := web.Bind(r.HTTPRequest, &form); err != nil {
return nil, errBadForm.Errorf("failed to parse request: %w", err)
}
return c.client.AuthenticatePassword(ctx, r, form.Username, form.Password)
}
|
pkg/services/authn/clients/form.go
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.00017847777053248137,
0.0001694917300483212,
0.00016346314805559814,
0.0001678152329986915,
0.00000509980418428313
] |
{
"id": 3,
"code_window": [
" place-content: center;\n",
" padding-bottom: 1rem;\n",
" `,\n",
" };\n",
"};"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" checkbox: css({\n",
" marginRight: theme.spacing(1),\n",
" }),\n"
],
"file_path": "public/app/features/search/page/components/FolderSection.tsx",
"type": "add",
"edit_start_line_idx": 234
}
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12,9a1,1,0,1,0,1,1A1,1,0,0,0,12,9Zm7-7H5A3,3,0,0,0,2,5V15a3,3,0,0,0,3,3H16.59l3.7,3.71A1,1,0,0,0,21,22a.84.84,0,0,0,.38-.08A1,1,0,0,0,22,21V5A3,3,0,0,0,19,2Zm1,16.59-2.29-2.3A1,1,0,0,0,17,16H5a1,1,0,0,1-1-1V5A1,1,0,0,1,5,4H19a1,1,0,0,1,1,1ZM8,9a1,1,0,1,0,1,1A1,1,0,0,0,8,9Zm8,0a1,1,0,1,0,1,1A1,1,0,0,0,16,9Z"/></svg>
|
public/img/icons/unicons/comment-alt-dots.svg
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.0001692050718702376,
0.0001692050718702376,
0.0001692050718702376,
0.0001692050718702376,
0
] |
{
"id": 3,
"code_window": [
" place-content: center;\n",
" padding-bottom: 1rem;\n",
" `,\n",
" };\n",
"};"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" checkbox: css({\n",
" marginRight: theme.spacing(1),\n",
" }),\n"
],
"file_path": "public/app/features/search/page/components/FolderSection.tsx",
"type": "add",
"edit_start_line_idx": 234
}
|
package main
import (
"log"
"github.com/urfave/cli/v2"
"github.com/grafana/grafana/pkg/build/config"
"github.com/grafana/grafana/pkg/build/docker"
"github.com/grafana/grafana/pkg/build/gcloud"
)
func BuildDocker(c *cli.Context) error {
if err := docker.Init(); err != nil {
return err
}
metadata, err := config.GenerateMetadata(c)
if err != nil {
return err
}
useUbuntu := c.Bool("ubuntu")
buildConfig, err := config.GetBuildConfig(metadata.ReleaseMode.Mode)
if err != nil {
return err
}
shouldSave := buildConfig.Docker.ShouldSave
if shouldSave {
if err := gcloud.ActivateServiceAccount(); err != nil {
return err
}
}
edition := config.Edition(c.String("edition"))
version := metadata.GrafanaVersion
log.Printf("Building Docker images, version %s, %s edition, Ubuntu based: %v...", version, edition,
useUbuntu)
for _, arch := range buildConfig.Docker.Architectures {
if _, err := docker.BuildImage(version, arch, ".", useUbuntu, shouldSave, edition, metadata.ReleaseMode.Mode); err != nil {
return cli.Exit(err.Error(), 1)
}
}
log.Println("Successfully built Docker images!")
return nil
}
|
pkg/build/cmd/builddocker.go
| 0 |
https://github.com/grafana/grafana/commit/d2814df8b63a83ea9bffdf063b2c3e6b25174179
|
[
0.0001786432694643736,
0.00017134797235485166,
0.00016526292893104255,
0.00017066486179828644,
0.000004583152531267842
] |
{
"id": 0,
"code_window": [
" createClient,\n",
" TypedDocumentNode,\n",
" OperationResult,\n",
" defaultExchanges,\n",
"} from \"@urql/core\"\n",
"import { devtoolsExchange } from \"@urql/devtools\"\n",
"import * as E from \"fp-ts/Either\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" OperationContext,\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "add",
"edit_start_line_idx": 14
}
|
import gql from "graphql-tag"
import { pipe } from "fp-ts/function"
import * as TE from "fp-ts/TaskEither"
import { runMutation } from "../GQLClient"
import { TeamName } from "../types/TeamName"
type DeleteTeamErrors =
| "team/not_required_role"
| "team/invalid_id"
| "team/member_not_found"
| "ea/not_invite_or_admin"
type ExitTeamErrors =
| "team/invalid_id"
| "team/member_not_found"
| "ea/not_invite_or_admin"
type CreateTeamErrors = "team/name_invalid" | "ea/not_invite_or_admin"
export const createTeam = (name: TeamName) =>
pipe(
runMutation<
{
createTeam: {
id: string
name: string
}
},
CreateTeamErrors
>(
gql`
mutation CreateTeam($name: String!) {
createTeam(name: $name) {
id
name
}
}
`,
{
name,
}
),
TE.map(({ createTeam }) => createTeam)
)
export const deleteTeam = (teamID: string) =>
runMutation<void, DeleteTeamErrors>(
gql`
mutation DeleteTeam($teamID: ID!) {
deleteTeam(teamID: $teamID)
}
`,
{
teamID,
}
)
export const leaveTeam = (teamID: string) =>
runMutation<void, ExitTeamErrors>(
gql`
mutation ExitTeam($teamID: ID!) {
leaveTeam(teamID: $teamID)
}
`,
{
teamID,
}
)
|
packages/hoppscotch-app/helpers/backend/mutations/Team.ts
| 1 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00036023114807903767,
0.0002002174878725782,
0.00016881911142263561,
0.0001736931299092248,
0.00006541307084262371
] |
{
"id": 0,
"code_window": [
" createClient,\n",
" TypedDocumentNode,\n",
" OperationResult,\n",
" defaultExchanges,\n",
"} from \"@urql/core\"\n",
"import { devtoolsExchange } from \"@urql/devtools\"\n",
"import * as E from \"fp-ts/Either\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" OperationContext,\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "add",
"edit_start_line_idx": 14
}
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path></svg>
|
packages/hoppscotch-app/assets/icons/key.svg
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017156678950414062,
0.00017156678950414062,
0.00017156678950414062,
0.00017156678950414062,
0
] |
{
"id": 0,
"code_window": [
" createClient,\n",
" TypedDocumentNode,\n",
" OperationResult,\n",
" defaultExchanges,\n",
"} from \"@urql/core\"\n",
"import { devtoolsExchange } from \"@urql/devtools\"\n",
"import * as E from \"fp-ts/Either\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" OperationContext,\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "add",
"edit_start_line_idx": 14
}
|
{
"action": {
"cancel": "İptal",
"choose_file": "Bir dosya seçin",
"clear": "Açık",
"clear_all": "Hepsini temizle",
"connect": "Bağlan",
"copy": "kopyala",
"delete": "Sil",
"disconnect": "bağlantıyı kes",
"dismiss": "Azlalt",
"download_file": "Dosyayı indir",
"edit": "Düzenle",
"go_back": "Geri git",
"label": "Etiket",
"learn_more": "Daha fazla bilgi edin",
"more": "Daha",
"new": "Yeni",
"no": "Numara",
"preserve_current": "Şimdikini koru",
"prettify": "Güzelleştir",
"remove": "Kaldır",
"replace_current": "Şimdikini değiştir",
"replace_json": "JSON ile değiştir",
"restore": "Onar",
"save": "Kaydet",
"search": "Arama",
"send": "Gönder",
"start": "Başla",
"stop": "Dur",
"turn_off": "Kapat",
"turn_on": "Aç",
"undo": "Geri al",
"yes": "Evet"
},
"add": {
"new": "Yeni ekle",
"star": "Yıldız ekle"
},
"app": {
"chat_with_us": "bizimle sohbet et",
"contact_us": "Bize Ulaşın",
"copy": "kopyala",
"documentation": "belgeler",
"github": "GitHub",
"help": "Yardım, geri bildirim ve belgeler",
"home": "Ana sayfa",
"invite": "Davet etmek",
"invite_description": "Hoppscotch'ta API'lerinizi oluşturmak ve yönetmek için basit ve sezgisel bir arayüz tasarladık. Hoppscotch, API'lerinizi oluşturmanıza, test etmenize, belgelemenize ve paylaşmanıza yardımcı olan bir araçtır.",
"invite_your_friends": "Arkadaşlarını davet et",
"join_discord_community": "Discord topluluğumuza katılın",
"keyboard_shortcuts": "Klavye kısayolları",
"name": "seksek",
"new_version_found": "Yeni sürüm bulundu. Güncellemek için yenileyin.",
"proxy_privacy_policy": "Proxy gizlilik ilkesi",
"reload": "Tekrar yükle",
"search": "Arama",
"share": "Paylaşmak",
"shortcuts": "Kısayollar",
"spotlight": "Spot ışığı",
"status": "Durum",
"terms_and_privacy": "Şartlar ve gizlilik",
"twitter": "heyecan",
"type_a_command_search": "Bir komut yazın veya arayın…",
"version": "v2.0",
"we_use_cookies": "çerez kullanıyoruz",
"whats_new": "Ne var ne yok?",
"wiki": "Wiki"
},
"auth": {
"account_exists": "Farklı kimlik bilgilerine sahip hesap var - Her iki hesabı birbirine bağlamak için giriş yapın",
"all_sign_in_options": "Tüm oturum açma seçenekleri",
"continue_with_email": "E-posta ile devam et",
"continue_with_github": "GitHub ile devam et",
"continue_with_google": "Google ile devam",
"email": "E-posta",
"logged_out": "Çıkış yapıldı",
"login": "Giriş yapmak",
"login_success": "Başarıyla giriş yapıldı",
"login_to_hoppscotch": "Hoppscotch'a giriş yapın",
"logout": "Çıkış Yap",
"re_enter_email": "E-mail adresinizi yeniden girin",
"send_magic_link": "Sihirli bir bağlantı gönder",
"sync": "senkronizasyon",
"we_sent_magic_link": "Size sihirli bir bağlantı gönderdik!",
"we_sent_magic_link_description": "Gelen kutunuzu kontrol edin - {email} adresine bir e-posta gönderdik. Giriş yapmanızı sağlayacak sihirli bir bağlantı içerir."
},
"authorization": {
"generate_token": "Jeton Oluştur",
"include_in_url": "URL'ye dahil et",
"learn": "Nasıl öğrenilir",
"password": "Parola",
"token": "Jeton",
"type": "Yetki Türü",
"username": "Kullanıcı adı"
},
"collection": {
"created": "Koleksiyon oluşturuldu",
"edit": "Koleksiyonu Düzenle",
"invalid_name": "Lütfen koleksiyon için geçerli bir ad girin",
"my_collections": "Koleksiyonlarım",
"name": "Yeni Koleksiyonum",
"new": "Yeni koleksiyon",
"renamed": "Koleksiyon yeniden adlandırıldı",
"save_as": "Farklı kaydet",
"select": "Bir Koleksiyon Seçin",
"select_location": "Konum seçin",
"select_team": "Bir takım seçin",
"team_collections": "Takım Koleksiyonları"
},
"confirm": {
"logout": "Oturumu kapatmak istediğinizden emin misiniz?",
"remove_collection": "Bu koleksiyonu kalıcı olarak silmek istediğinizden emin misiniz?",
"remove_environment": "Bu ortamı kalıcı olarak silmek istediğinizden emin misiniz?",
"remove_folder": "Bu klasörü kalıcı olarak silmek istediğinizden emin misiniz?",
"remove_history": "Tüm geçmişi kalıcı olarak silmek istediğinizden emin misiniz?",
"remove_request": "Bu isteği kalıcı olarak silmek istediğinizden emin misiniz?",
"remove_team": "Bu takımı silmek istediğinizden emin misiniz?",
"remove_telemetry": "Telemetriden çıkmak istediğinizden emin misiniz?",
"sync": "Bu çalışma alanını senkronize etmek istediğinizden emin misiniz?"
},
"count": {
"header": "Başlık {count}",
"message": "Mesaj {count}",
"parameter": "Parametre {sayım}",
"protocol": "Protokol {sayım}",
"value": "Değer {count}",
"variable": "Değişken {count}"
},
"documentation": {
"generate": "Belge oluştur",
"generate_message": "Güncel API belgelerini oluşturmak için herhangi bir Hoppscotch koleksiyonunu içe aktarın."
},
"empty": {
"authorization": "Bu istek herhangi bir yetkilendirme kullanmıyor",
"body": "Bu isteğin bir gövdesi yok",
"collection": "Koleksiyon boş",
"collections": "Koleksiyonlar boş",
"environments": "Ortamlar boş",
"folder": "Klasör boş",
"headers": "Bu isteğin herhangi bir başlığı yok",
"history": "Geçmiş boş",
"members": "Takım boş",
"parameters": "Bu isteğin herhangi bir parametresi yok",
"protocols": "Protokoller boş",
"schema": "Bir GraphQL uç noktasına bağlanma",
"team_name": "Takım adı boş",
"teams": "Takımlar boş",
"tests": "Bu istek için test yok"
},
"environment": {
"create_new": "Yeni ortam oluştur",
"edit": "Ortamı Düzenle",
"invalid_name": "Lütfen ortam için geçerli bir ad girin",
"new": "Yeni ortam",
"no_environment": "Ortam yok",
"select": "Ortam seçin",
"title": "Ortamlar",
"variable_list": "Değişken Listesi"
},
"error": {
"browser_support_sse": "Bu tarayıcıda Sunucu Gönderilen Olaylar desteği yok gibi görünüyor.",
"check_console_details": "Ayrıntılar için konsol günlüğünü kontrol edin.",
"curl_invalid_format": "cURL düzgün biçimlendirilmemiş",
"empty_req_name": "Boş İstek Adı",
"f12_details": "(Ayrıntılar için F12)",
"gql_prettify_invalid_query": "Geçersiz bir sorgu güzelleştirilemedi, sorgu sözdizimi hatalarını çözüp tekrar deneyin",
"json_prettify_invalid_body": "Geçersiz bir gövde güzelleştirilemedi, json sözdizimi hatalarını çözüp tekrar deneyin",
"network_fail": "istek gönderilemedi",
"no_duration": "Süre yok",
"something_went_wrong": "Bir şeyler yanlış gitti"
},
"export": {
"as_json": "JSON olarak dışa aktar",
"create_secret_gist": "Gizli Gist oluştur",
"gist_created": "Gist oluşturuldu",
"require_github": "Gizli Gist oluşturmak için GitHub ile giriş yapın"
},
"folder": {
"created": "Klasör oluşturuldu",
"edit": "Klasörü Düzenle",
"invalid_name": "Lütfen klasör için bir ad girin",
"new": "Yeni dosya",
"renamed": "Klasör yeniden adlandırıldı"
},
"graphql": {
"mutations": "mutasyonlar",
"schema": "Şema",
"subscriptions": "abonelikler"
},
"header": {
"account": "Hesap",
"install_pwa": "Uygulamayı yükle",
"login": "Giriş yap",
"save_workspace": "Çalışma Alanımı Kaydet"
},
"helpers": {
"authorization": "Yetkilendirme başlığı, isteği gönderdiğinizde otomatik olarak oluşturulur.",
"generate_documentation_first": "Önce belgeleri oluşturun",
"network_fail": "API uç noktasına ulaşılamıyor. Ağ bağlantınızı kontrol edin ve tekrar deneyin.",
"offline": "Çevrimdışı görünüyorsun. Bu çalışma alanındaki veriler güncel olmayabilir.",
"offline_short": "Çevrimdışı görünüyorsun.",
"post_request_tests": "Test komut dosyaları JavaScript'te yazılır ve yanıt alındıktan sonra çalıştırılır.",
"pre_request_script": "Ön istek komut dosyaları JavaScript'te yazılır ve istek gönderilmeden önce çalıştırılır.",
"tests": "Hata ayıklamayı otomatikleştirmek için bir test komut dosyası yazın."
},
"hide": {
"more": "Daha fazlasını gizle",
"preview": "Önizlemeyi Gizle",
"sidebar": "Kenar çubuğunu gizle"
},
"import": {
"collections": "Koleksiyonları içe aktar",
"curl": "cURL'yi içe aktar",
"failed": "İçe aktarılamadı",
"from_gist": "Gist'ten içe aktar",
"from_my_collections": "Koleksiyonlarımdan İçe Aktar",
"gist_url": "Gist URL'sini girin",
"json": "JSON'dan içe aktar",
"title": "İçe aktar"
},
"layout": {
"column": "Dikey görünüm",
"row": "Yatay görünüm",
"zen_mode": "Zen modu"
},
"modal": {
"collections": "Koleksiyonlar",
"confirm": "Onaylamak",
"edit_request": "İsteği Düzenle",
"import_export": "Yükleme/Dışa aktarma"
},
"mqtt": {
"communication": "İletişim",
"log": "Kayıt",
"message": "İleti",
"publish": "Yayınla",
"subscribe": "Abone",
"topic": "Başlık",
"topic_name": "Konu adı",
"topic_title": "Konuyu Yayınla / Abone Ol",
"unsubscribe": "Aboneliği iptal et",
"url": "URL"
},
"navigation": {
"doc": "Dokümanlar",
"graphql": "GraphQL",
"realtime": "Gerçek zamanlı",
"rest": "REST",
"settings": "Ayarlar"
},
"preRequest": {
"javascript_code": "JavaScript Kodu",
"learn": "Belgeleri okuyun",
"script": "Ön İstek Komut Dosyası",
"snippets": "snippet'ler"
},
"remove": {
"star": "Yıldızı kaldır"
},
"request": {
"added": "İstek eklendi",
"authorization": "yetki",
"body": "İstek Gövdesi",
"choose_language": "Dil seçiniz",
"content_type": "İçerik türü",
"copy_link": "Bağlantıyı kopyala",
"duration": "Süre",
"enter_curl": "cURL'yi girin",
"generate_code": "Kodunu oluşturun",
"generated_code": "oluşturulan kod",
"header_list": "Başlık Listesi",
"invalid_name": "Lütfen istek için bir ad girin",
"method": "Yöntem",
"name": "İstek adı",
"parameter_list": "Sorgu Parametreleri",
"parameters": "parametreler",
"payload": "yük",
"query": "Sorgu",
"raw_body": "Ham İstek Gövdesi",
"renamed": "Yeniden adlandırılmış istek",
"run": "Çalıştırmak",
"save": "Kayıt etmek",
"save_as": "Farklı kaydet",
"saved": "İstek kaydedildi",
"share": "Paylaşmak",
"title": "İstek",
"type": "İstek Türü",
"url": "URL",
"variables": "Değişkenler"
},
"response": {
"body": "Yanıt Gövdesi",
"headers": "Başlıklar",
"html": "HTML",
"image": "resim",
"json": "JSON",
"preview_html": "HTML'yi önizle",
"raw": "Çiğ",
"size": "Boy",
"status": "Durum",
"time": "Zaman",
"title": "Cevap",
"waiting_for_connection": "bağlantı için bekleniyor",
"xml": "XML"
},
"settings": {
"accent_color": "vurgu rengi",
"account": "Hesap",
"account_description": "Hesap ayarlarınızı özelleştirin.",
"account_email_description": "Birincil e-posta adresiniz.",
"account_name_description": "Bu sizin görünen adınız.",
"background": "Arka fon",
"black_mode": "Siyah",
"change_font_size": "Yazı tipi boyutunu değiştir",
"choose_language": "Dil seçiniz",
"dark_mode": "Karanlık",
"experiments": "deneyler",
"experiments_notice": "Bu, üzerinde çalıştığımız, yararlı, eğlenceli, her ikisi de ya da hiçbiri olabilecek bir deneyler koleksiyonudur. Nihai değiller ve istikrarlı olmayabilirler, bu yüzden aşırı garip bir şey olursa panik yapmayın. Sadece şu şeyi kapat. şaka bir yana,",
"extension_ver_not_reported": "Rapor edilmemiş",
"extension_version": "Uzantı Sürümü",
"extensions": "Uzantılar",
"extensions_use_toggle": "İstek göndermek için tarayıcı uzantısını kullanın (varsa)",
"font_size": "Yazı Boyutu",
"font_size_large": "Büyük",
"font_size_medium": "Orta",
"font_size_small": "Küçük",
"interceptor": "önleyici",
"interceptor_description": "Uygulama ve API'ler arasındaki ara katman yazılımı.",
"language": "Dil",
"light_mode": "Işık",
"navigation_sidebar": "Gezinme kenar çubuğu",
"official_proxy_hosting": "Resmi Proxy, Hoppscotch tarafından barındırılmaktadır.",
"proxy": "vekil",
"proxy_url": "Proxy URL'si",
"proxy_use_toggle": "İstek göndermek için proxy ara yazılımını kullanın",
"read_the": "Oku",
"reset_default": "Varsayılana sıfırla",
"sync": "senkronize et",
"sync_collections": "Koleksiyonlar",
"sync_description": "Bu ayarlar bulutla senkronize edilir.",
"sync_environments": "ortamlar",
"sync_history": "Tarih",
"system_mode": "sistem",
"telemetry": "telemetri",
"telemetry_helps_us": "Telemetri, operasyonlarımızı kişiselleştirmemize ve size en iyi deneyimi sunmamıza yardımcı olur.",
"theme": "Tema",
"theme_description": "Uygulama temanızı özelleştirin.",
"use_experimental_url_bar": "Ortam vurgulamalı deneysel URL çubuğunu kullanın",
"user": "kullanıcı"
},
"shortcut": {
"general": {
"close_current_menu": "Güncel menüyü kapat",
"command_menu": "Arama ve komut menüsü",
"help_menu": "Yardım menüsü",
"show_all": "Klavye kısayolları",
"title": "Genel"
},
"miscellaneous": {
"invite": "İnsanları Hoppscotch'a davet edin",
"title": "Çeşitli"
},
"navigation": {
"back": "Önceki sayfaya geri dön",
"documentation": "Belgeler sayfasına git",
"forward": "Sonraki sayfaya ilerle",
"graphql": "GraphQL sayfasına git",
"realtime": "Gerçek Zamanlı sayfasına git",
"rest": "REST sayfasına git",
"settings": "Ayarlar sayfasına git",
"title": "Navigasyon"
},
"request": {
"copy_request_link": "İstek Bağlantısını Kopyala",
"delete_method": "SİL yöntemini seçin",
"get_method": "GET yöntemini seçin",
"head_method": "HEAD yöntemini seçin",
"method": "Yöntem",
"next_method": "Sonraki yöntemi seçin",
"path": "Yol",
"post_method": "POST yöntemini seçin",
"previous_method": "Önceki yöntemi seçin",
"put_method": "PUT yöntemini seçin",
"reset_request": "İsteği Sıfırla",
"save_to_collections": "Koleksiyonlara Kaydet",
"send_request": "İstek gönder",
"title": "İstek"
}
},
"show": {
"code": "Kodu göster",
"more": "Daha fazla göster",
"sidebar": "Kenar çubuğunu göster"
},
"socketio": {
"communication": "İletişim",
"event_name": "Etkinlik ismi",
"events": "Olaylar",
"log": "Kayıt",
"url": "URL"
},
"sse": {
"event_type": "Etkinlik tipi",
"log": "Kayıt",
"url": "URL"
},
"state": {
"bulk_mode": "Toplu düzenleme",
"bulk_mode_placeholder": "Girişler yeni satırla ayrılır\nAnahtarlar ve değerler şu şekilde ayrılır:\nEklemek istediğiniz ancak devre dışı bırakmak istediğiniz herhangi bir satırın başına // ekleyin",
"cleared": "Temizlendi",
"connected": "bağlı",
"connected_to": "{name} ile bağlantılı",
"connecting_to": "{name} adlı kullanıcıya bağlanılıyor...",
"copied_to_clipboard": "Panoya kopyalandı",
"deleted": "silindi",
"deprecated": "KULLANIMDAN KALDIRILMIŞ",
"disabled": "Engelli",
"disconnected": "Bağlantı kesildi",
"disconnected_from": "{name} ile bağlantı kesildi",
"docs_generated": "Dokümantasyon oluşturuldu",
"download_started": "İndirme başladı",
"enabled": "Etkinleştirilmiş",
"file_imported": "Dosya içe aktarıldı",
"finished_in": "{duration} ms içinde tamamlandı",
"history_deleted": "Geçmiş silindi",
"linewrap": "Çizgileri sarın",
"loading": "Yükleniyor...",
"none": "Hiçbiri",
"nothing_found": "için hiçbir şey bulunamadı",
"waiting_send_request": "istek göndermek için bekliyorum"
},
"support": {
"changelog": "En son sürümler hakkında daha fazla bilgi edin",
"chat": "Sorun mu var? Bizle sohbet et!",
"community": "Sorular sorun ve başkalarına yardım edin",
"documentation": "Hoppscotch hakkında daha fazla bilgi edin",
"forum": "Sorular sorun ve cevaplar alın",
"shortcuts": "Uygulamaya daha hızlı göz atın",
"team": "Takımla iletişim kurun",
"title": "Destek",
"twitter": "Bizi Twitter'da takip edin"
},
"tab": {
"authorization": "yetki",
"body": "Vücut",
"collections": "Koleksiyonlar",
"documentation": "belgeler",
"headers": "Başlıklar",
"history": "Geçmiş",
"mqtt": "MQTT",
"parameters": "parametreler",
"pre_request_script": "Ön İstek Komut Dosyası",
"queries": "Sorgular",
"query": "Sorgu",
"socketio": "Soket.IO",
"sse": "SSE",
"tests": "testler",
"types": "Türler",
"variables": "Değişkenler",
"websocket": "WebSocket"
},
"team": {
"create_new": "Yeni takım oluştur",
"deleted": "Takım silindi",
"edit": "Takımı Düzenle",
"email": "e-posta",
"exit": "Takımdan Çık",
"exit_disabled": "Takımın kurucusu çıkamaz.",
"invalid_email_format": "E-posta biçimi geçersiz",
"invalid_member_permission": "Lütfen takım üyesine geçerli bir izin verin",
"join_beta": "Takımlara erişmek için beta programına katılın.",
"left": "takımdan ayrıldın",
"member_removed": "Kullanıcı kaldırıldı",
"member_role_updated": "Kullanıcı rolleri güncellendi",
"members": "Üyeler",
"name_length_insufficient": "Takım adı en az 6 karakter uzunluğunda olmalıdır",
"new": "Yeni takım",
"new_created": "Yeni takım oluşturuldu",
"new_name": "Yeni Takımım",
"no_access": "Bu koleksiyonlar için düzenleme erişiminiz yok",
"permissions": "izinler",
"saved": "Takım kaydedildi",
"title": "Başlık"
},
"test": {
"javascript_code": "JavaScript Kodu",
"learn": "Belgeleri okuyun",
"report": "Test raporu",
"results": "Test sonuçları",
"script": "Komut dosyası",
"snippets": "snippet'ler"
},
"websocket": {
"communication": "İletişim",
"log": "Kayıt",
"message": "Mesaj",
"protocols": "protokoller",
"url": "URL"
}
}
|
packages/hoppscotch-app/locales/tr.json
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017774937441572547,
0.0001731875236146152,
0.00016695861995685846,
0.00017357393517158926,
0.0000025023882699315436
] |
{
"id": 0,
"code_window": [
" createClient,\n",
" TypedDocumentNode,\n",
" OperationResult,\n",
" defaultExchanges,\n",
"} from \"@urql/core\"\n",
"import { devtoolsExchange } from \"@urql/devtools\"\n",
"import * as E from \"fp-ts/Either\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" OperationContext,\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "add",
"edit_start_line_idx": 14
}
|
<svg height="623" width="2500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0.324 1000 248.676"><path d="M0 .324v248.003L1000 249V.324H0z" fill="#1482c2"/><g fill="#fff"><path d="M399.832 59.812l-56.002 82.93c-5.825 8.777-16.043 14.082-26.737 14.082-17.415 0-31.83-14.31-31.83-31.576 0-17.521 14.415-31.804 31.952-31.804 1.738-.223 4.07-.466 5.697-.466 12.089 0 24.405 5.071 32.773 13.604l16.726-25.349c-13.01-13.355-32.301-21.903-51.598-21.903-36.022 0-69.018 29.726-69.018 65.674 0 35.736 29.514 64.99 65.547 64.99 17.425 0 34.851-7.371 46.94-19.592h38.577l.228 19.593h33.48V59.812h-36.734zm-15.321 82.013l18.348-25.555.228 25.555h-18.575zM500.709 189.993H467.24V90.21h-26.027V60.028l85.51-.218v30.4H500.71v99.783zM638.29 59.812l-33.468.008-.233 48.604h-39.515l-.25-48.614h-33.441v130.183h33.69V138.6h39.748v51.392h33.468V59.81zM906.481 59.812v60.581L860.47 59.812l-30.457.212-.23 47.48c-7.668-27.654-33.933-47.692-63.215-47.692-36.017 0-65.536 29.244-65.536 65.192 0 11.543 3.482 23.266 9.052 33.42h-33.155V59.812h-34.104v130.183h77.964v-18.216c12.317 11.3 29.048 18.216 45.78 18.216 29.28 0 55.085-19.593 63.215-47.253l.229 47.253h33.711v-63.353l45.764 63.353h30.436l.042-130.183h-33.478zm-139.913 98.384c-18.358 0-33.462-14.744-33.462-33.192 0-18.194 15.104-33.166 33.462-33.166 18.602 0 33.707 14.972 33.707 33.166 0 18.448-15.105 33.192-33.707 33.192M211.32 158.426v-18.22h35.917l-.064-31.783H211.32V91.84h39.59l-.068-32.026-76.227.212v44.709c-7.901-24.422-30.685-42.404-56.712-44.709l-57.868-.212v130.178h58.106c25.789-2.295 48.573-20.267 56.474-44.465v44.465h76.295l-.068-31.566h-39.52zm-73.66-13.599c-2.084 8.766-10.457 14.972-19.52 15.205H96.761V90.208h21.38c9.062 0 17.435 6.482 19.519 15.454 2.098 5.994 3.259 12.905 3.259 19.344 0 6.699-1.16 13.6-3.26 19.821"/></g></svg>
|
packages/hoppscotch-app/static/images/users/decathlon.svg
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.0005159040447324514,
0.0005159040447324514,
0.0005159040447324514,
0.0005159040447324514,
0
] |
{
"id": 1,
"code_window": [
" MutationReturnType = any,\n",
" MutationFailType extends string = \"\",\n",
" MutationVariables extends {} = {}\n",
">(\n",
" mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,\n",
" variables?: MutationVariables\n",
"): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n",
" pipe(\n",
" TE.tryCatch(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" variables?: MutationVariables,\n",
" additionalConfig?: Partial<OperationContext>\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "replace",
"edit_start_line_idx": 173
}
|
import {
computed,
ref,
onMounted,
onBeforeUnmount,
reactive,
Ref,
} from "@nuxtjs/composition-api"
import { DocumentNode } from "graphql/language"
import {
createClient,
TypedDocumentNode,
OperationResult,
defaultExchanges,
} from "@urql/core"
import { devtoolsExchange } from "@urql/devtools"
import * as E from "fp-ts/Either"
import * as TE from "fp-ts/TaskEither"
import { pipe, constVoid } from "fp-ts/function"
import { subscribe } from "wonka"
import clone from "lodash/clone"
import { getAuthIDToken } from "~/helpers/fb/auth"
const BACKEND_GQL_URL =
process.env.CONTEXT === "production"
? "https://api.hoppscotch.io/graphql"
: "https://api.hoppscotch.io/graphql"
const client = createClient({
url: BACKEND_GQL_URL,
fetchOptions: () => {
const token = getAuthIDToken()
return {
headers: {
authorization: token ? `Bearer ${token}` : "",
},
}
},
exchanges: [devtoolsExchange, ...defaultExchanges],
})
/**
* A wrapper type for defining errors possible in a GQL operation
*/
export type GQLError<T extends string> =
| {
type: "network_error"
error: Error
}
| {
type: "gql_error"
error: T
}
const DEFAULT_QUERY_OPTIONS = {
noPolling: false,
pause: undefined as Ref<boolean> | undefined,
}
type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS
type UseQueryLoading = {
loading: true
}
type UseQueryLoaded<
QueryFailType extends string = "",
QueryReturnType = any
> = {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
}
type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> =
| UseQueryLoading
| UseQueryLoaded<QueryFailType, QueryReturnType>
export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>(
x: UseQueryReturn<QueryFailType, QueryReturnType>
): x is {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
} {
return !x.loading
}
export function useGQLQuery<
QueryReturnType = any,
QueryFailType extends string = "",
QueryVariables extends object = {}
>(
query: string | DocumentNode | TypedDocumentNode<any, QueryVariables>,
variables?: QueryVariables,
options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS
):
| { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> }
| { loading: true } {
type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType>
const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options)
const data = ref<DataType>()
let subscription: { unsubscribe(): void } | null = null
onMounted(() => {
const gqlQuery = client.query<any, QueryVariables>(query, variables)
const processResult = (result: OperationResult<any, QueryVariables>) =>
pipe(
// The target
result.data as QueryReturnType | undefined,
// Define what happens if data does not exist (it is an error)
E.fromNullable(
pipe(
// Take the network error value
result.error?.networkError,
// If it null, set the left to the generic error name
E.fromNullable(result.error?.name),
E.match(
// The left case (network error was null)
(gqlErr) =>
<GQLError<QueryFailType>>{
type: "gql_error",
error: gqlErr as QueryFailType,
},
// The right case (it was a GraphQL Error)
(networkErr) =>
<GQLError<QueryFailType>>{
type: "network_error",
error: networkErr,
}
)
)
)
)
if (finalOptions.noPolling) {
gqlQuery.toPromise().then((result) => {
data.value = processResult(result)
})
} else {
subscription = pipe(
gqlQuery,
subscribe((result) => {
data.value = processResult(result)
})
)
}
})
onBeforeUnmount(() => {
subscription?.unsubscribe()
})
return reactive({
loading: computed(() => !data.value),
data: data!,
}) as
| {
loading: false
data: DataType
}
| { loading: true }
}
export const runMutation = <
MutationReturnType = any,
MutationFailType extends string = "",
MutationVariables extends {} = {}
>(
mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,
variables?: MutationVariables
): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>
pipe(
TE.tryCatch(
() => client.mutation<MutationReturnType>(mutation, variables).toPromise(),
() => constVoid() as never // The mutation function can never fail, so this will never be called ;)
),
TE.chainEitherK((result) =>
pipe(
result.data as MutationReturnType, // If we have the result, then okay
E.fromNullable(
// Result is null
pipe(
result.error?.networkError, // Check for network error
E.fromNullable(result.error?.name), // If it is null, then it is a GQL error
E.match(
// The left case (network error was null)
(gqlErr) =>
<GQLError<MutationFailType>>{
type: "gql_error",
error: gqlErr as MutationFailType,
},
// The right case (it was a GraphQL Error)
(networkErr) =>
<GQLError<MutationFailType>>{
type: "network_error",
error: networkErr,
}
)
)
)
)
)
)
|
packages/hoppscotch-app/helpers/backend/GQLClient.ts
| 1 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.9972872734069824,
0.10308697074651718,
0.00016443064669147134,
0.001099260407499969,
0.2905585765838623
] |
{
"id": 1,
"code_window": [
" MutationReturnType = any,\n",
" MutationFailType extends string = \"\",\n",
" MutationVariables extends {} = {}\n",
">(\n",
" mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,\n",
" variables?: MutationVariables\n",
"): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n",
" pipe(\n",
" TE.tryCatch(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" variables?: MutationVariables,\n",
" additionalConfig?: Partial<OperationContext>\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "replace",
"edit_start_line_idx": 173
}
|
import runTestScriptWithVariables from "../postwomanTesting"
/**
* @param {string} script
* @param {number} index
*/
function getTestResult(script, index) {
return runTestScriptWithVariables(script).testResults[index].result
}
/**
* @param {string} script
*/
function getErrors(script) {
return runTestScriptWithVariables(script).errors
}
describe("Error handling", () => {
test("throws error at unknown test method", () => {
const testScriptWithUnknownMethod = "pw.expect(1).toBeSomeUnknownMethod()"
expect(() => {
runTestScriptWithVariables(testScriptWithUnknownMethod)
}).toThrow()
})
test("errors array is empty on a successful test", () => {
expect(getErrors("pw.expect(1).toBe(1)")).toStrictEqual([])
})
test("throws error at a variable which is not declared", () => {
expect(() => {
runTestScriptWithVariables("someVariable")
}).toThrow()
})
})
describe("toBe", () => {
test("test for numbers", () => {
expect(getTestResult("pw.expect(1).toBe(2)", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect(1).toBe(1)", 0)).toEqual("PASS")
})
test("test for strings", () => {
expect(getTestResult("pw.expect('hello').toBe('bonjour')", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect('hi').toBe('hi')", 0)).toEqual("PASS")
})
test("test for negative assertion (.not.toBe)", () => {
expect(getTestResult("pw.expect(1).not.toBe(1)", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect(1).not.toBe(2)", 0)).toEqual("PASS")
expect(getTestResult("pw.expect('world').not.toBe('planet')", 0)).toEqual(
"PASS"
)
expect(getTestResult("pw.expect('world').not.toBe('world')", 0)).toEqual(
"FAIL"
)
})
})
describe("toHaveProperty", () => {
const dummyResponse = {
id: 843,
description: "random",
}
test("test for positive assertion (.toHaveProperty)", () => {
expect(
getTestResult(
`pw.expect(${JSON.stringify(dummyResponse)}).toHaveProperty("id")`,
0
)
).toEqual("PASS")
expect(
getTestResult(`pw.expect(${dummyResponse.id}).toBe(843)`, 0)
).toEqual("PASS")
})
test("test for negative assertion (.not.toHaveProperty)", () => {
expect(
getTestResult(
`pw.expect(${JSON.stringify(
dummyResponse
)}).not.toHaveProperty("type")`,
0
)
).toEqual("PASS")
expect(
getTestResult(
`pw.expect(${JSON.stringify(dummyResponse)}).toHaveProperty("type")`,
0
)
).toEqual("FAIL")
})
})
describe("toBeLevel2xx", () => {
test("test for numbers", () => {
expect(getTestResult("pw.expect(200).toBeLevel2xx()", 0)).toEqual("PASS")
expect(getTestResult("pw.expect(200).not.toBeLevel2xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(300).toBeLevel2xx()", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect(300).not.toBeLevel2xx()", 0)).toEqual(
"PASS"
)
})
test("test for strings", () => {
expect(getTestResult("pw.expect('200').toBeLevel2xx()", 0)).toEqual("PASS")
expect(getTestResult("pw.expect('200').not.toBeLevel2xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect('300').toBeLevel2xx()", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect('300').not.toBeLevel2xx()", 0)).toEqual(
"PASS"
)
})
test("failed to parse to integer", () => {
expect(getTestResult("pw.expect(undefined).toBeLevel2xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(null).toBeLevel2xx()", 0)).toEqual("FAIL")
expect(() => {
runTestScriptWithVariables("pw.expect(Symbol('test')).toBeLevel2xx()")
}).toThrow()
})
})
describe("toBeLevel3xx()", () => {
test("test for numbers", () => {
expect(getTestResult("pw.expect(300).toBeLevel3xx()", 0)).toEqual("PASS")
expect(getTestResult("pw.expect(300).not.toBeLevel3xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(400).toBeLevel3xx()", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect(400).not.toBeLevel3xx()", 0)).toEqual(
"PASS"
)
})
test("test for strings", () => {
expect(getTestResult("pw.expect('300').toBeLevel3xx()", 0)).toEqual("PASS")
expect(getTestResult("pw.expect('300').not.toBeLevel3xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect('400').toBeLevel3xx()", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect('400').not.toBeLevel3xx()", 0)).toEqual(
"PASS"
)
})
test("failed to parse to integer", () => {
expect(getTestResult("pw.expect(undefined).toBeLevel3xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(null).toBeLevel3xx()", 0)).toEqual("FAIL")
expect(() => {
runTestScriptWithVariables("pw.expect(Symbol('test')).toBeLevel3xx()")
}).toThrow()
})
})
describe("toBeLevel4xx()", () => {
test("test for numbers", () => {
expect(getTestResult("pw.expect(400).toBeLevel4xx()", 0)).toEqual("PASS")
expect(getTestResult("pw.expect(400).not.toBeLevel4xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(500).toBeLevel4xx()", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect(500).not.toBeLevel4xx()", 0)).toEqual(
"PASS"
)
})
test("test for strings", () => {
expect(getTestResult("pw.expect('400').toBeLevel4xx()", 0)).toEqual("PASS")
expect(getTestResult("pw.expect('400').not.toBeLevel4xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect('500').toBeLevel4xx()", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect('500').not.toBeLevel4xx()", 0)).toEqual(
"PASS"
)
})
test("failed to parse to integer", () => {
expect(getTestResult("pw.expect(undefined).toBeLevel4xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(null).toBeLevel4xx()", 0)).toEqual("FAIL")
expect(() => {
runTestScriptWithVariables("pw.expect(Symbol('test')).toBeLevel4xx()")
}).toThrow()
})
})
describe("toBeLevel5xx()", () => {
test("test for numbers", () => {
expect(getTestResult("pw.expect(500).toBeLevel5xx()", 0)).toEqual("PASS")
expect(getTestResult("pw.expect(500).not.toBeLevel5xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(200).toBeLevel5xx()", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect(200).not.toBeLevel5xx()", 0)).toEqual(
"PASS"
)
})
test("test for strings", () => {
expect(getTestResult("pw.expect('500').toBeLevel5xx()", 0)).toEqual("PASS")
expect(getTestResult("pw.expect('500').not.toBeLevel5xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect('200').toBeLevel5xx()", 0)).toEqual("FAIL")
expect(getTestResult("pw.expect('200').not.toBeLevel5xx()", 0)).toEqual(
"PASS"
)
})
test("failed to parse to integer", () => {
expect(getTestResult("pw.expect(undefined).toBeLevel5xx()", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(null).toBeLevel5xx()", 0)).toEqual("FAIL")
expect(() => {
runTestScriptWithVariables("pw.expect(Symbol('test')).toBeLevel5xx()")
}).toThrow()
})
})
describe("toHaveLength()", () => {
test("test for strings", () => {
expect(getTestResult("pw.expect('word').toHaveLength(4)", 0)).toEqual(
"PASS"
)
expect(getTestResult("pw.expect('word').toHaveLength(5)", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect('word').not.toHaveLength(4)", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect('word').not.toHaveLength(5)", 0)).toEqual(
"PASS"
)
})
test("test for arrays", () => {
const fruits =
"['apples', 'bananas', 'oranges', 'grapes', 'strawberries', 'cherries']"
expect(getTestResult(`pw.expect(${fruits}).toHaveLength(6)`, 0)).toEqual(
"PASS"
)
expect(getTestResult(`pw.expect(${fruits}).toHaveLength(7)`, 0)).toEqual(
"FAIL"
)
expect(
getTestResult(`pw.expect(${fruits}).not.toHaveLength(6)`, 0)
).toEqual("FAIL")
expect(
getTestResult(`pw.expect(${fruits}).not.toHaveLength(7)`, 0)
).toEqual("PASS")
})
})
describe("toBeType()", () => {
test("test for positive assertion", () => {
expect(getTestResult("pw.expect('random').toBeType('string')", 0)).toEqual(
"PASS"
)
expect(getTestResult("pw.expect(true).toBeType('boolean')", 0)).toEqual(
"PASS"
)
expect(getTestResult("pw.expect(5).toBeType('number')", 0)).toEqual("PASS")
expect(
getTestResult("pw.expect(new Date()).toBeType('object')", 0)
).toEqual("PASS")
expect(
getTestResult("pw.expect(undefined).toBeType('undefined')", 0)
).toEqual("PASS")
expect(
getTestResult("pw.expect(BigInt(123)).toBeType('bigint')", 0)
).toEqual("PASS")
expect(
getTestResult("pw.expect(Symbol('test')).toBeType('symbol')", 0)
).toEqual("PASS")
expect(
getTestResult("pw.expect(function() {}).toBeType('function')", 0)
).toEqual("PASS")
})
test("test for negative assertion", () => {
expect(
getTestResult("pw.expect('random').not.toBeType('string')", 0)
).toEqual("FAIL")
expect(getTestResult("pw.expect(true).not.toBeType('boolean')", 0)).toEqual(
"FAIL"
)
expect(getTestResult("pw.expect(5).not.toBeType('number')", 0)).toEqual(
"FAIL"
)
expect(
getTestResult("pw.expect(new Date()).not.toBeType('object')", 0)
).toEqual("FAIL")
expect(
getTestResult("pw.expect(undefined).not.toBeType('undefined')", 0)
).toEqual("FAIL")
expect(
getTestResult("pw.expect(BigInt(123)).not.toBeType('bigint')", 0)
).toEqual("FAIL")
expect(
getTestResult("pw.expect(Symbol('test')).not.toBeType('symbol')", 0)
).toEqual("FAIL")
expect(
getTestResult("pw.expect(function() {}).not.toBeType('function')", 0)
).toEqual("FAIL")
})
test("unexpected type", () => {
expect(getTestResult("pw.expect('random').toBeType('unknown')", 0)).toEqual(
"FAIL"
)
})
})
|
packages/hoppscotch-app/helpers/__tests__/postwomanTesting.sample
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00018121943867299706,
0.00017693283734843135,
0.00017049440066330135,
0.000177626934600994,
0.0000023460420379706193
] |
{
"id": 1,
"code_window": [
" MutationReturnType = any,\n",
" MutationFailType extends string = \"\",\n",
" MutationVariables extends {} = {}\n",
">(\n",
" mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,\n",
" variables?: MutationVariables\n",
"): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n",
" pipe(\n",
" TE.tryCatch(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" variables?: MutationVariables,\n",
" additionalConfig?: Partial<OperationContext>\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "replace",
"edit_start_line_idx": 173
}
|
<template>
<SmartLink
:to="`${/^\/(?!\/).*$/.test(to) ? localePath(to) : to}`"
:exact="exact"
:blank="blank"
class="
font-bold
py-2
transition
inline-flex
items-center
justify-center
focus:outline-none
focus-visible:bg-accentDark
"
:class="[
color
? `text-${color}-800 bg-${color}-200 hover:(text-${color}-900 bg-${color}-300) focus-visible:(text-${color}-900 bg-${color}-300)`
: `text-accentContrast bg-accent hover:bg-accentDark focus-visible:bg-accentDark`,
label ? 'px-4' : 'px-2',
rounded ? 'rounded-full' : 'rounded',
{ 'opacity-75 cursor-not-allowed': disabled },
{ 'pointer-events-none': loading },
{ 'px-6 py-4 text-lg': large },
{ 'shadow-lg hover:shadow-xl': shadow },
{
'text-white bg-gradient-to-tr from-gradientFrom via-gradientVia to-gradientTo':
gradient,
},
{
'border border-accent hover:border-accentDark focus-visible:border-accentDark':
outline,
},
]"
:disabled="disabled"
:tabindex="loading ? '-1' : '0'"
:type="type"
>
<span
v-if="!loading"
class="inline-flex items-center justify-center whitespace-nowrap"
:class="{ 'flex-row-reverse': reverse }"
>
<i
v-if="icon"
class="material-icons"
:class="[
{ '!text-2xl': large },
label ? (reverse ? 'ml-2' : 'mr-2') : '',
]"
>
{{ icon }}
</i>
<SmartIcon
v-if="svg"
:name="svg"
class="svg-icons"
:class="[
{ '!h-6 !w-6': large },
label ? (reverse ? 'ml-2' : 'mr-2') : '',
]"
/>
{{ label }}
<div v-if="shortcut.length" class="ml-2">
<kbd
v-for="(key, index) in shortcut"
:key="`key-${index}`"
class="bg-accentLight rounded ml-1 px-1 inline-flex"
>
{{ key }}
</kbd>
</div>
</span>
<SmartSpinner v-else />
</SmartLink>
</template>
<script lang="ts">
import { defineComponent } from "@nuxtjs/composition-api"
export default defineComponent({
props: {
to: {
type: String,
default: "",
},
exact: {
type: Boolean,
default: true,
},
blank: {
type: Boolean,
default: false,
},
label: {
type: String,
default: "",
},
icon: {
type: String,
default: "",
},
svg: {
type: String,
default: "",
},
color: {
type: String,
default: "",
},
disabled: {
type: Boolean,
default: false,
},
loading: {
type: Boolean,
default: false,
},
large: {
type: Boolean,
default: false,
},
shadow: {
type: Boolean,
default: false,
},
reverse: {
type: Boolean,
default: false,
},
rounded: {
type: Boolean,
default: false,
},
gradient: {
type: Boolean,
default: false,
},
outline: {
type: Boolean,
default: false,
},
shortcut: {
type: Array,
default: () => [],
},
type: {
type: String,
default: "button",
},
},
})
</script>
|
packages/hoppscotch-app/components/button/Primary.vue
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017721171025186777,
0.00017512039630673826,
0.00017170803039334714,
0.00017537488020025194,
0.0000014685638234368525
] |
{
"id": 1,
"code_window": [
" MutationReturnType = any,\n",
" MutationFailType extends string = \"\",\n",
" MutationVariables extends {} = {}\n",
">(\n",
" mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,\n",
" variables?: MutationVariables\n",
"): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n",
" pipe(\n",
" TE.tryCatch(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" variables?: MutationVariables,\n",
" additionalConfig?: Partial<OperationContext>\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "replace",
"edit_start_line_idx": 173
}
|
import { Lens } from "./lenses"
const xmlLens: Lens = {
lensName: "response.xml",
isSupportedContentType: (contentType) => /\bxml\b/i.test(contentType),
renderer: "xmlres",
rendererImport: () =>
import("~/components/lenses/renderers/XMLLensRenderer.vue"),
}
export default xmlLens
|
packages/hoppscotch-app/helpers/lenses/xmlLens.ts
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017524823488201946,
0.00017336237942799926,
0.00017147652397397906,
0.00017336237942799926,
0.0000018858554540202022
] |
{
"id": 2,
"code_window": [
"): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n",
" pipe(\n",
" TE.tryCatch(\n",
" () => client.mutation<MutationReturnType>(mutation, variables).toPromise(),\n",
" () => constVoid() as never // The mutation function can never fail, so this will never be called ;)\n",
" ),\n",
" TE.chainEitherK((result) =>\n",
" pipe(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" () =>\n",
" client\n",
" .mutation<MutationReturnType>(mutation, variables, additionalConfig)\n",
" .toPromise(),\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "replace",
"edit_start_line_idx": 177
}
|
import {
computed,
ref,
onMounted,
onBeforeUnmount,
reactive,
Ref,
} from "@nuxtjs/composition-api"
import { DocumentNode } from "graphql/language"
import {
createClient,
TypedDocumentNode,
OperationResult,
defaultExchanges,
} from "@urql/core"
import { devtoolsExchange } from "@urql/devtools"
import * as E from "fp-ts/Either"
import * as TE from "fp-ts/TaskEither"
import { pipe, constVoid } from "fp-ts/function"
import { subscribe } from "wonka"
import clone from "lodash/clone"
import { getAuthIDToken } from "~/helpers/fb/auth"
const BACKEND_GQL_URL =
process.env.CONTEXT === "production"
? "https://api.hoppscotch.io/graphql"
: "https://api.hoppscotch.io/graphql"
const client = createClient({
url: BACKEND_GQL_URL,
fetchOptions: () => {
const token = getAuthIDToken()
return {
headers: {
authorization: token ? `Bearer ${token}` : "",
},
}
},
exchanges: [devtoolsExchange, ...defaultExchanges],
})
/**
* A wrapper type for defining errors possible in a GQL operation
*/
export type GQLError<T extends string> =
| {
type: "network_error"
error: Error
}
| {
type: "gql_error"
error: T
}
const DEFAULT_QUERY_OPTIONS = {
noPolling: false,
pause: undefined as Ref<boolean> | undefined,
}
type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS
type UseQueryLoading = {
loading: true
}
type UseQueryLoaded<
QueryFailType extends string = "",
QueryReturnType = any
> = {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
}
type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> =
| UseQueryLoading
| UseQueryLoaded<QueryFailType, QueryReturnType>
export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>(
x: UseQueryReturn<QueryFailType, QueryReturnType>
): x is {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
} {
return !x.loading
}
export function useGQLQuery<
QueryReturnType = any,
QueryFailType extends string = "",
QueryVariables extends object = {}
>(
query: string | DocumentNode | TypedDocumentNode<any, QueryVariables>,
variables?: QueryVariables,
options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS
):
| { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> }
| { loading: true } {
type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType>
const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options)
const data = ref<DataType>()
let subscription: { unsubscribe(): void } | null = null
onMounted(() => {
const gqlQuery = client.query<any, QueryVariables>(query, variables)
const processResult = (result: OperationResult<any, QueryVariables>) =>
pipe(
// The target
result.data as QueryReturnType | undefined,
// Define what happens if data does not exist (it is an error)
E.fromNullable(
pipe(
// Take the network error value
result.error?.networkError,
// If it null, set the left to the generic error name
E.fromNullable(result.error?.name),
E.match(
// The left case (network error was null)
(gqlErr) =>
<GQLError<QueryFailType>>{
type: "gql_error",
error: gqlErr as QueryFailType,
},
// The right case (it was a GraphQL Error)
(networkErr) =>
<GQLError<QueryFailType>>{
type: "network_error",
error: networkErr,
}
)
)
)
)
if (finalOptions.noPolling) {
gqlQuery.toPromise().then((result) => {
data.value = processResult(result)
})
} else {
subscription = pipe(
gqlQuery,
subscribe((result) => {
data.value = processResult(result)
})
)
}
})
onBeforeUnmount(() => {
subscription?.unsubscribe()
})
return reactive({
loading: computed(() => !data.value),
data: data!,
}) as
| {
loading: false
data: DataType
}
| { loading: true }
}
export const runMutation = <
MutationReturnType = any,
MutationFailType extends string = "",
MutationVariables extends {} = {}
>(
mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,
variables?: MutationVariables
): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>
pipe(
TE.tryCatch(
() => client.mutation<MutationReturnType>(mutation, variables).toPromise(),
() => constVoid() as never // The mutation function can never fail, so this will never be called ;)
),
TE.chainEitherK((result) =>
pipe(
result.data as MutationReturnType, // If we have the result, then okay
E.fromNullable(
// Result is null
pipe(
result.error?.networkError, // Check for network error
E.fromNullable(result.error?.name), // If it is null, then it is a GQL error
E.match(
// The left case (network error was null)
(gqlErr) =>
<GQLError<MutationFailType>>{
type: "gql_error",
error: gqlErr as MutationFailType,
},
// The right case (it was a GraphQL Error)
(networkErr) =>
<GQLError<MutationFailType>>{
type: "network_error",
error: networkErr,
}
)
)
)
)
)
)
|
packages/hoppscotch-app/helpers/backend/GQLClient.ts
| 1 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.9896957874298096,
0.04783579334616661,
0.0001641809067223221,
0.0002769074635580182,
0.21060898900032043
] |
{
"id": 2,
"code_window": [
"): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n",
" pipe(\n",
" TE.tryCatch(\n",
" () => client.mutation<MutationReturnType>(mutation, variables).toPromise(),\n",
" () => constVoid() as never // The mutation function can never fail, so this will never be called ;)\n",
" ),\n",
" TE.chainEitherK((result) =>\n",
" pipe(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" () =>\n",
" client\n",
" .mutation<MutationReturnType>(mutation, variables, additionalConfig)\n",
" .toPromise(),\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "replace",
"edit_start_line_idx": 177
}
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
|
packages/hoppscotch-app/assets/icons/lock.svg
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017425564874429256,
0.00017425564874429256,
0.00017425564874429256,
0.00017425564874429256,
0
] |
{
"id": 2,
"code_window": [
"): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n",
" pipe(\n",
" TE.tryCatch(\n",
" () => client.mutation<MutationReturnType>(mutation, variables).toPromise(),\n",
" () => constVoid() as never // The mutation function can never fail, so this will never be called ;)\n",
" ),\n",
" TE.chainEitherK((result) =>\n",
" pipe(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" () =>\n",
" client\n",
" .mutation<MutationReturnType>(mutation, variables, additionalConfig)\n",
" .toPromise(),\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "replace",
"edit_start_line_idx": 177
}
|
module.exports = {
semi: false,
}
|
packages/hoppscotch-js-sandbox/.prettierrc.js
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017572597425896674,
0.00017572597425896674,
0.00017572597425896674,
0.00017572597425896674,
0
] |
{
"id": 2,
"code_window": [
"): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>\n",
" pipe(\n",
" TE.tryCatch(\n",
" () => client.mutation<MutationReturnType>(mutation, variables).toPromise(),\n",
" () => constVoid() as never // The mutation function can never fail, so this will never be called ;)\n",
" ),\n",
" TE.chainEitherK((result) =>\n",
" pipe(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" () =>\n",
" client\n",
" .mutation<MutationReturnType>(mutation, variables, additionalConfig)\n",
" .toPromise(),\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/GQLClient.ts",
"type": "replace",
"edit_start_line_idx": 177
}
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path><line x1="9" y1="14" x2="15" y2="14"></line></svg>
|
packages/hoppscotch-app/assets/icons/folder-minus.svg
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017336435848847032,
0.00017336435848847032,
0.00017336435848847032,
0.00017336435848847032,
0
] |
{
"id": 3,
"code_window": [
" }\n",
" `,\n",
" {\n",
" teamID,\n",
" }\n",
" )\n",
"\n",
"export const leaveTeam = (teamID: string) =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" additionalTypenames: [\"Team\"],\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts",
"type": "add",
"edit_start_line_idx": 54
}
|
import {
computed,
ref,
onMounted,
onBeforeUnmount,
reactive,
Ref,
} from "@nuxtjs/composition-api"
import { DocumentNode } from "graphql/language"
import {
createClient,
TypedDocumentNode,
OperationResult,
defaultExchanges,
} from "@urql/core"
import { devtoolsExchange } from "@urql/devtools"
import * as E from "fp-ts/Either"
import * as TE from "fp-ts/TaskEither"
import { pipe, constVoid } from "fp-ts/function"
import { subscribe } from "wonka"
import clone from "lodash/clone"
import { getAuthIDToken } from "~/helpers/fb/auth"
const BACKEND_GQL_URL =
process.env.CONTEXT === "production"
? "https://api.hoppscotch.io/graphql"
: "https://api.hoppscotch.io/graphql"
const client = createClient({
url: BACKEND_GQL_URL,
fetchOptions: () => {
const token = getAuthIDToken()
return {
headers: {
authorization: token ? `Bearer ${token}` : "",
},
}
},
exchanges: [devtoolsExchange, ...defaultExchanges],
})
/**
* A wrapper type for defining errors possible in a GQL operation
*/
export type GQLError<T extends string> =
| {
type: "network_error"
error: Error
}
| {
type: "gql_error"
error: T
}
const DEFAULT_QUERY_OPTIONS = {
noPolling: false,
pause: undefined as Ref<boolean> | undefined,
}
type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS
type UseQueryLoading = {
loading: true
}
type UseQueryLoaded<
QueryFailType extends string = "",
QueryReturnType = any
> = {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
}
type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> =
| UseQueryLoading
| UseQueryLoaded<QueryFailType, QueryReturnType>
export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>(
x: UseQueryReturn<QueryFailType, QueryReturnType>
): x is {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
} {
return !x.loading
}
export function useGQLQuery<
QueryReturnType = any,
QueryFailType extends string = "",
QueryVariables extends object = {}
>(
query: string | DocumentNode | TypedDocumentNode<any, QueryVariables>,
variables?: QueryVariables,
options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS
):
| { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> }
| { loading: true } {
type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType>
const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options)
const data = ref<DataType>()
let subscription: { unsubscribe(): void } | null = null
onMounted(() => {
const gqlQuery = client.query<any, QueryVariables>(query, variables)
const processResult = (result: OperationResult<any, QueryVariables>) =>
pipe(
// The target
result.data as QueryReturnType | undefined,
// Define what happens if data does not exist (it is an error)
E.fromNullable(
pipe(
// Take the network error value
result.error?.networkError,
// If it null, set the left to the generic error name
E.fromNullable(result.error?.name),
E.match(
// The left case (network error was null)
(gqlErr) =>
<GQLError<QueryFailType>>{
type: "gql_error",
error: gqlErr as QueryFailType,
},
// The right case (it was a GraphQL Error)
(networkErr) =>
<GQLError<QueryFailType>>{
type: "network_error",
error: networkErr,
}
)
)
)
)
if (finalOptions.noPolling) {
gqlQuery.toPromise().then((result) => {
data.value = processResult(result)
})
} else {
subscription = pipe(
gqlQuery,
subscribe((result) => {
data.value = processResult(result)
})
)
}
})
onBeforeUnmount(() => {
subscription?.unsubscribe()
})
return reactive({
loading: computed(() => !data.value),
data: data!,
}) as
| {
loading: false
data: DataType
}
| { loading: true }
}
export const runMutation = <
MutationReturnType = any,
MutationFailType extends string = "",
MutationVariables extends {} = {}
>(
mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,
variables?: MutationVariables
): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>
pipe(
TE.tryCatch(
() => client.mutation<MutationReturnType>(mutation, variables).toPromise(),
() => constVoid() as never // The mutation function can never fail, so this will never be called ;)
),
TE.chainEitherK((result) =>
pipe(
result.data as MutationReturnType, // If we have the result, then okay
E.fromNullable(
// Result is null
pipe(
result.error?.networkError, // Check for network error
E.fromNullable(result.error?.name), // If it is null, then it is a GQL error
E.match(
// The left case (network error was null)
(gqlErr) =>
<GQLError<MutationFailType>>{
type: "gql_error",
error: gqlErr as MutationFailType,
},
// The right case (it was a GraphQL Error)
(networkErr) =>
<GQLError<MutationFailType>>{
type: "network_error",
error: networkErr,
}
)
)
)
)
)
)
|
packages/hoppscotch-app/helpers/backend/GQLClient.ts
| 1 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.0006275124032981694,
0.00020120410772506148,
0.00016627674631308764,
0.00017068210581783205,
0.0000995105438050814
] |
{
"id": 3,
"code_window": [
" }\n",
" `,\n",
" {\n",
" teamID,\n",
" }\n",
" )\n",
"\n",
"export const leaveTeam = (teamID: string) =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" additionalTypenames: [\"Team\"],\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts",
"type": "add",
"edit_start_line_idx": 54
}
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="8.5" cy="7" r="4"></circle><line x1="20" y1="8" x2="20" y2="14"></line><line x1="23" y1="11" x2="17" y2="11"></line></svg>
|
packages/hoppscotch-app/assets/icons/user-plus.svg
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017060870595742017,
0.00017060870595742017,
0.00017060870595742017,
0.00017060870595742017,
0
] |
{
"id": 3,
"code_window": [
" }\n",
" `,\n",
" {\n",
" teamID,\n",
" }\n",
" )\n",
"\n",
"export const leaveTeam = (teamID: string) =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" additionalTypenames: [\"Team\"],\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts",
"type": "add",
"edit_start_line_idx": 54
}
|
name: "Code Scanning - Action"
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12 or JAN-DEC)
# │ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ │
# * * * * *
- cron: '0 0 * * 6'
jobs:
CodeQL-Build:
# CodeQL runs on ubuntu-latest, windows-latest, and macos-latest
runs-on: ubuntu-latest
permissions:
# required for all workflows
security-events: write
# only required for workflows in private repositories
actions: read
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below).
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following
# three lines and modify them (or add more) to build your code if your
# project uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
|
.github/workflows/codeql-analysis.yml
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.0001742975291563198,
0.0001712516968837008,
0.00016556544869672507,
0.0001718326675472781,
0.0000026213685941911535
] |
{
"id": 3,
"code_window": [
" }\n",
" `,\n",
" {\n",
" teamID,\n",
" }\n",
" )\n",
"\n",
"export const leaveTeam = (teamID: string) =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" additionalTypenames: [\"Team\"],\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts",
"type": "add",
"edit_start_line_idx": 54
}
|
# Contributing
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.
Please note we have a code of conduct, please follow it in all your interactions with the project.
## Pull Request Process
1. Ensure any install or build dependencies are removed before the end of the layer when doing a
build.
2. Update the README.md with details of changes to the interface, this includes new environment
variables, exposed ports, useful file locations and container parameters.
3. Increase the version numbers in any examples files and the README.md to the new version that this
Pull Request would represent. The versioning scheme we use is [SemVer](https://semver.org).
4. You may merge the Pull Request once you have the sign-off of two other developers, or if you
do not have permission to do that, you may request the second reviewer merge it for you.
|
CONTRIBUTING.md
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.0001749777584336698,
0.00017053550982382149,
0.00016609326121397316,
0.00017053550982382149,
0.0000044422486098483205
] |
{
"id": 4,
"code_window": [
" leaveTeam(teamID: $teamID)\n",
" }\n",
" `,\n",
" {\n",
" teamID,\n",
" }\n",
" )"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" additionalTypenames: [\"Team\"],\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts",
"type": "add",
"edit_start_line_idx": 66
}
|
import {
computed,
ref,
onMounted,
onBeforeUnmount,
reactive,
Ref,
} from "@nuxtjs/composition-api"
import { DocumentNode } from "graphql/language"
import {
createClient,
TypedDocumentNode,
OperationResult,
defaultExchanges,
} from "@urql/core"
import { devtoolsExchange } from "@urql/devtools"
import * as E from "fp-ts/Either"
import * as TE from "fp-ts/TaskEither"
import { pipe, constVoid } from "fp-ts/function"
import { subscribe } from "wonka"
import clone from "lodash/clone"
import { getAuthIDToken } from "~/helpers/fb/auth"
const BACKEND_GQL_URL =
process.env.CONTEXT === "production"
? "https://api.hoppscotch.io/graphql"
: "https://api.hoppscotch.io/graphql"
const client = createClient({
url: BACKEND_GQL_URL,
fetchOptions: () => {
const token = getAuthIDToken()
return {
headers: {
authorization: token ? `Bearer ${token}` : "",
},
}
},
exchanges: [devtoolsExchange, ...defaultExchanges],
})
/**
* A wrapper type for defining errors possible in a GQL operation
*/
export type GQLError<T extends string> =
| {
type: "network_error"
error: Error
}
| {
type: "gql_error"
error: T
}
const DEFAULT_QUERY_OPTIONS = {
noPolling: false,
pause: undefined as Ref<boolean> | undefined,
}
type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS
type UseQueryLoading = {
loading: true
}
type UseQueryLoaded<
QueryFailType extends string = "",
QueryReturnType = any
> = {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
}
type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> =
| UseQueryLoading
| UseQueryLoaded<QueryFailType, QueryReturnType>
export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>(
x: UseQueryReturn<QueryFailType, QueryReturnType>
): x is {
loading: false
data: E.Either<GQLError<QueryFailType>, QueryReturnType>
} {
return !x.loading
}
export function useGQLQuery<
QueryReturnType = any,
QueryFailType extends string = "",
QueryVariables extends object = {}
>(
query: string | DocumentNode | TypedDocumentNode<any, QueryVariables>,
variables?: QueryVariables,
options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS
):
| { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> }
| { loading: true } {
type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType>
const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options)
const data = ref<DataType>()
let subscription: { unsubscribe(): void } | null = null
onMounted(() => {
const gqlQuery = client.query<any, QueryVariables>(query, variables)
const processResult = (result: OperationResult<any, QueryVariables>) =>
pipe(
// The target
result.data as QueryReturnType | undefined,
// Define what happens if data does not exist (it is an error)
E.fromNullable(
pipe(
// Take the network error value
result.error?.networkError,
// If it null, set the left to the generic error name
E.fromNullable(result.error?.name),
E.match(
// The left case (network error was null)
(gqlErr) =>
<GQLError<QueryFailType>>{
type: "gql_error",
error: gqlErr as QueryFailType,
},
// The right case (it was a GraphQL Error)
(networkErr) =>
<GQLError<QueryFailType>>{
type: "network_error",
error: networkErr,
}
)
)
)
)
if (finalOptions.noPolling) {
gqlQuery.toPromise().then((result) => {
data.value = processResult(result)
})
} else {
subscription = pipe(
gqlQuery,
subscribe((result) => {
data.value = processResult(result)
})
)
}
})
onBeforeUnmount(() => {
subscription?.unsubscribe()
})
return reactive({
loading: computed(() => !data.value),
data: data!,
}) as
| {
loading: false
data: DataType
}
| { loading: true }
}
export const runMutation = <
MutationReturnType = any,
MutationFailType extends string = "",
MutationVariables extends {} = {}
>(
mutation: string | DocumentNode | TypedDocumentNode<any, MutationVariables>,
variables?: MutationVariables
): TE.TaskEither<GQLError<MutationFailType>, NonNullable<MutationReturnType>> =>
pipe(
TE.tryCatch(
() => client.mutation<MutationReturnType>(mutation, variables).toPromise(),
() => constVoid() as never // The mutation function can never fail, so this will never be called ;)
),
TE.chainEitherK((result) =>
pipe(
result.data as MutationReturnType, // If we have the result, then okay
E.fromNullable(
// Result is null
pipe(
result.error?.networkError, // Check for network error
E.fromNullable(result.error?.name), // If it is null, then it is a GQL error
E.match(
// The left case (network error was null)
(gqlErr) =>
<GQLError<MutationFailType>>{
type: "gql_error",
error: gqlErr as MutationFailType,
},
// The right case (it was a GraphQL Error)
(networkErr) =>
<GQLError<MutationFailType>>{
type: "network_error",
error: networkErr,
}
)
)
)
)
)
)
|
packages/hoppscotch-app/helpers/backend/GQLClient.ts
| 1 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00043376811663620174,
0.00019842323672492057,
0.00016650903853587806,
0.00016983934619929641,
0.00007302519225049764
] |
{
"id": 4,
"code_window": [
" leaveTeam(teamID: $teamID)\n",
" }\n",
" `,\n",
" {\n",
" teamID,\n",
" }\n",
" )"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" additionalTypenames: [\"Team\"],\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts",
"type": "add",
"edit_start_line_idx": 66
}
|
const sourceEmojis = {
// Source used for info messages.
info: "\tℹ️ [INFO]:\t",
// Source used for client to server messages.
client: "\t⬅️ [SENT]:\t",
// Source used for server to client messages.
server: "\t➡️ [RECEIVED]:\t",
}
export function getSourcePrefix(source: keyof typeof sourceEmojis) {
return sourceEmojis[source]
}
|
packages/hoppscotch-app/helpers/utils/string.ts
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017252597899641842,
0.00016978729399852455,
0.00016704860900063068,
0.00016978729399852455,
0.00000273868499789387
] |
{
"id": 4,
"code_window": [
" leaveTeam(teamID: $teamID)\n",
" }\n",
" `,\n",
" {\n",
" teamID,\n",
" }\n",
" )"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" additionalTypenames: [\"Team\"],\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts",
"type": "add",
"edit_start_line_idx": 66
}
|
import { Subject, BehaviorSubject } from "rxjs"
import { map } from "rxjs/operators"
import assign from "lodash/assign"
import clone from "lodash/clone"
type dispatcherFunc<StoreType> = (
currentVal: StoreType,
payload: any
) => Partial<StoreType>
/**
* Defines a dispatcher.
*
* This function exists to provide better typing for dispatch function.
* As you can see, its pretty much an identity function.
*/
export const defineDispatchers = <StoreType, T>(
// eslint-disable-next-line no-unused-vars
dispatchers: { [_ in keyof T]: dispatcherFunc<StoreType> }
) => dispatchers
type Dispatch<
StoreType,
DispatchersType extends Record<string, dispatcherFunc<StoreType>>
> = {
dispatcher: keyof DispatchersType
payload: any
}
export default class DispatchingStore<
StoreType,
DispatchersType extends Record<string, dispatcherFunc<StoreType>>
> {
#state$: BehaviorSubject<StoreType>
#dispatchers: DispatchersType
#dispatches$: Subject<Dispatch<StoreType, DispatchersType>> = new Subject()
constructor(initialValue: StoreType, dispatchers: DispatchersType) {
this.#state$ = new BehaviorSubject(initialValue)
this.#dispatchers = dispatchers
this.#dispatches$
.pipe(
map(({ dispatcher, payload }) =>
this.#dispatchers[dispatcher](this.value, payload)
)
)
.subscribe((val) => {
const data = clone(this.value)
assign(data, val)
this.#state$.next(data)
})
}
get subject$() {
return this.#state$
}
get value() {
return this.subject$.value
}
get dispatches$() {
return this.#dispatches$
}
dispatch({ dispatcher, payload }: Dispatch<StoreType, DispatchersType>) {
if (!this.#dispatchers[dispatcher])
throw new Error(`Undefined dispatch type '${dispatcher}'`)
this.#dispatches$.next({ dispatcher, payload })
}
}
|
packages/hoppscotch-app/newstore/DispatchingStore.ts
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.0004281751753296703,
0.0002015311038121581,
0.0001662471186136827,
0.00016983368550427258,
0.00008568718476453796
] |
{
"id": 4,
"code_window": [
" leaveTeam(teamID: $teamID)\n",
" }\n",
" `,\n",
" {\n",
" teamID,\n",
" }\n",
" )"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" additionalTypenames: [\"Team\"],\n"
],
"file_path": "packages/hoppscotch-app/helpers/backend/mutations/Team.ts",
"type": "add",
"edit_start_line_idx": 66
}
|
<template>
<SmartModal
v-if="show"
:title="$t('folder.edit')"
@close="$emit('hide-modal')"
>
<template #body>
<div class="flex flex-col px-2">
<input
id="selectLabelEditFolder"
v-model="name"
v-focus
class="input floating-input"
placeholder=" "
type="text"
autocomplete="off"
@keyup.enter="editFolder"
/>
<label for="selectLabelEditFolder">
{{ $t("action.label") }}
</label>
</div>
</template>
<template #footer>
<span>
<ButtonPrimary :label="$t('action.save')" @click.native="editFolder" />
<ButtonSecondary
:label="$t('action.cancel')"
@click.native="hideModal"
/>
</span>
</template>
</SmartModal>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
export default defineComponent({
props: {
show: Boolean,
},
data() {
return {
name: null,
}
},
methods: {
editFolder() {
if (!this.name) {
this.$toast.error(this.$t("folder.invalid_name"), {
icon: "error_outline",
})
return
}
this.$emit("submit", this.name)
this.hideModal()
},
hideModal() {
this.name = null
this.$emit("hide-modal")
},
},
})
</script>
|
packages/hoppscotch-app/components/collections/EditFolder.vue
| 0 |
https://github.com/hoppscotch/hoppscotch/commit/81ae70ee04c4f6f88b2b839f78173d87c6cf38a2
|
[
0.00017317369929514825,
0.00017151329666376114,
0.00016885405057109892,
0.00017172751540783793,
0.0000014528167184835183
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
"export class Conditional extends AST {\n",
" constructor(condition:AST, trueExp:AST, falseExp:AST){\n",
" this.condition = condition;\n",
" this.trueExp = trueExp;\n",
" this.falseExp = falseExp;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final condition:AST')\n",
" @FIELD('final trueExp:AST')\n",
" @FIELD('final falseExp:AST')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 23
}
|
import {FIELD, int, isBlank} from 'facade/lang';
import {ListWrapper, List} from 'facade/collection';
import {Lexer, EOF, Token, $PERIOD, $COLON, $SEMICOLON} from './lexer';
import {ClosureMap} from './closure_map';
import {
AST,
ImplicitReceiver,
FieldRead,
LiteralPrimitive,
Expression,
Binary,
PrefixNot,
Conditional,
Formatter
} from './ast';
var _implicitReceiver = new ImplicitReceiver();
export class Parser {
@FIELD('final _lexer:Lexer')
@FIELD('final _closureMap:ClosureMap')
constructor(lexer:Lexer, closureMap:ClosureMap){
this._lexer = lexer;
this._closureMap = closureMap;
}
parseAction(input:string):AST {
var tokens = this._lexer.tokenize(input);
return new _ParseAST(input, tokens, this._closureMap, true).parseChain();
}
parseBinding(input:string):AST {
var tokens = this._lexer.tokenize(input);
return new _ParseAST(input, tokens, this._closureMap, false).parseChain();
}
}
class _ParseAST {
@FIELD('final input:String')
@FIELD('final tokens:List<Token>')
@FIELD('final closureMap:ClosureMap')
@FIELD('final parseAction:boolean')
@FIELD('index:int')
constructor(input:string, tokens:List, closureMap:ClosureMap, parseAction:boolean) {
this.input = input;
this.tokens = tokens;
this.index = 0;
this.closureMap = closureMap;
this.parseAction = parseAction;
}
peek(offset:int):Token {
var i = this.index + offset;
return i < this.tokens.length ? this.tokens[i] : EOF;
}
get next():Token {
return this.peek(0);
}
get inputIndex():int {
return (this.index < this.tokens.length) ? this.next.index : this.input.length;
}
advance() {
this.index ++;
}
optionalCharacter(code:int):boolean {
if (this.next.isCharacter(code)) {
this.advance();
return true;
} else {
return false;
}
}
optionalOperator(op:string):boolean {
if (this.next.isOperator(op)) {
this.advance();
return true;
} else {
return false;
}
}
parseChain():AST {
var exprs = [];
while (this.index < this.tokens.length) {
var expr = this.parseFormatter();
ListWrapper.push(exprs, expr);
while (this.optionalCharacter($SEMICOLON)) {
if (! this.parseAction) {
this.error("Binding expression cannot contain chained expression");
}
}
}
return ListWrapper.first(exprs);
}
parseFormatter() {
var result = this.parseExpression();
while (this.optionalOperator("|")) {
if (this.parseAction) {
this.error("Cannot have a formatter in an action expression");
}
var name = this.parseIdentifier();
var args = ListWrapper.create();
while (this.optionalCharacter($COLON)) {
ListWrapper.push(args, this.parseExpression());
}
result = new Formatter(result, name, args);
}
return result;
}
parseExpression() {
return this.parseConditional();
}
parseConditional() {
var start = this.inputIndex;
var result = this.parseLogicalOr();
if (this.optionalOperator('?')) {
var yes = this.parseExpression();
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.parseExpression();
return new Conditional(result, yes, no);
} else {
return result;
}
}
parseLogicalOr() {
// '||'
var result = this.parseLogicalAnd();
while (this.optionalOperator('||')) {
result = new Binary('||', result, this.parseLogicalAnd());
}
return result;
}
parseLogicalAnd() {
// '&&'
var result = this.parseEquality();
while (this.optionalOperator('&&')) {
result = new Binary('&&', result, this.parseEquality());
}
return result;
}
parseEquality() {
// '==','!='
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 {
return result;
}
}
}
parseRelational() {
// '<', '>', '<=', '>='
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() {
// '+', '-'
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() {
// '*', '%', '/', '~/'
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());
// TODO(rado): This exists only in Dart, figure out whether to support it.
// } else if (this.optionalOperator('~/')) {
// result = new BinaryTruncatingDivide(result, this.parsePrefix());
} else {
return result;
}
}
}
parsePrefix() {
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.parseAccessOrCallMember();
}
}
parseAccessOrCallMember() {
var result = this.parsePrimary();
// TODO: add missing cases.
return result;
}
parsePrimary() {
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.next.isIdentifier()) {
return this.parseAccess();
} else if (this.next.isNumber()) {
var value = this.next.toNumber();
this.advance();
return new LiteralPrimitive(value);
} else if (this.next.isString()) {
var value = this.next.toString();
this.advance();
return new LiteralPrimitive(value);
} else if (this.index >= this.tokens.length) {
throw `Unexpected end of expression: ${this.input}`;
} else {
throw `Unexpected token ${this.next}`;
}
}
parseAccess():AST {
var result = this.parseFieldRead(_implicitReceiver);
while(this.optionalCharacter($PERIOD)) {
result = this.parseFieldRead(result);
}
return result;
}
parseFieldRead(receiver):AST {
var id = this.parseIdentifier();
return new FieldRead(receiver, id, this.closureMap.getter(id));
}
parseIdentifier():string {
var n = this.next;
if (!n.isIdentifier() && !n.isKeyword()) {
this.error(`Unexpected token ${n}, expected identifier or keyword`)
}
this.advance();
return n.toString();
}
error(message:string, index:int = 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 ParserError(`Parser Error: ${message} ${location} [${this.input}]`);
}
}
class ParserError extends Error {
constructor(message) {
this.message = message;
}
toString() {
return this.message;
}
}
|
modules/change_detection/src/parser/parser.js
| 1 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.9984496831893921,
0.1216587945818901,
0.00016543889068998396,
0.00017392117297276855,
0.31705859303474426
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
"export class Conditional extends AST {\n",
" constructor(condition:AST, trueExp:AST, falseExp:AST){\n",
" this.condition = condition;\n",
" this.trueExp = trueExp;\n",
" this.falseExp = falseExp;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final condition:AST')\n",
" @FIELD('final trueExp:AST')\n",
" @FIELD('final falseExp:AST')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 23
}
|
library element_injector_benchmark;
import './instantiate_benchmark.dart' as ib;
import './instantiate_benchmark_codegen.dart' as ibc;
import './instantiate_directive_benchmark.dart' as idb;
import 'dart:js' as js;
main () {
js.context['benchmarkSteps'].add(new js.JsObject.jsify({
"name": "ElementInjector.instantiate + instantiateDirectives",
"fn": new js.JsFunction.withThis((_) => ib.run())
}));
js.context['benchmarkSteps'].add(new js.JsObject.jsify({
"name": "ElementInjector.instantiateDirectives",
"fn": new js.JsFunction.withThis((_) => idb.run())
}));
js.context['benchmarkSteps'].add(new js.JsObject.jsify({
"name": "ElementInjector.instantiate + instantiateDirectives (codegen)",
"fn": new js.JsFunction.withThis((_) => ibc.run())
}));
}
|
modules/benchmarks/src/element_injector/benchmark.dart
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.00017606525216251612,
0.00017409170686732978,
0.0001718325074762106,
0.00017437731730751693,
0.0000017397735518898116
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
"export class Conditional extends AST {\n",
" constructor(condition:AST, trueExp:AST, falseExp:AST){\n",
" this.condition = condition;\n",
" this.trueExp = trueExp;\n",
" this.falseExp = falseExp;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final condition:AST')\n",
" @FIELD('final trueExp:AST')\n",
" @FIELD('final falseExp:AST')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 23
}
|
export var describe = window.describe;
export var xdescribe = window.xdescribe;
export var ddescribe = window.ddescribe;
export var it = window.it;
export var xit = window.xit;
export var iit = window.iit;
export var beforeEach = window.beforeEach;
export var afterEach = window.afterEach;
export var expect = window.expect;
// To make testing consistent between dart and js
window.print = function(msg) {
if (window.dump) {
window.dump(msg);
} else {
window.console.log(msg);
}
};
window.beforeEach(function() {
jasmine.addMatchers({
toBePromise: function() {
return {
compare: function (actual, expectedClass) {
var pass = typeof actual === 'object' && typeof actual.then === 'function';
return {
pass: pass,
get message() {
return 'Expected ' + actual + ' to be a promise';
}
};
}
};
},
toBeAnInstanceOf: function() {
return {
compare: function(actual, expectedClass) {
var pass = typeof actual === 'object' && actual instanceof expectedClass;
return {
pass: pass,
get message() {
return 'Expected ' + actual + ' to be an instance of ' + expectedClass;
}
};
}
};
}
});
});
|
modules/test_lib/src/test_lib.es6
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.000177560665179044,
0.000171871084603481,
0.00016749966016504914,
0.00017264638154301792,
0.0000034246315863128984
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
"export class Conditional extends AST {\n",
" constructor(condition:AST, trueExp:AST, falseExp:AST){\n",
" this.condition = condition;\n",
" this.trueExp = trueExp;\n",
" this.falseExp = falseExp;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final condition:AST')\n",
" @FIELD('final trueExp:AST')\n",
" @FIELD('final falseExp:AST')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 23
}
|
#!/bin/bash
set -e
AVAILABLE_DART_VERSION=$(curl "https://storage.googleapis.com/dart-archive/channels/$CHANNEL/release/latest/VERSION" | python -c \
'import sys, json; print(json.loads(sys.stdin.read())["version"])')
echo Fetch Dart channel: $CHANNEL
SVN_REVISION=latest
# TODO(chirayu): Remove this once issue 20896 is fixed.
# Dart 1.7.0-dev.1.0 and 1.7.0-dev.2.0 are both broken so use version
# 1.7.0-dev.0.1 instead.
if [[ "$AVAILABLE_DART_VERSION" == "1.7.0-dev.2.0" ]]; then
SVN_REVISION=39661 # Use version 1.7.0-dev.0.1
fi
URL_PREFIX=https://storage.googleapis.com/dart-archive/channels/$CHANNEL/release/$SVN_REVISION
DART_SDK_URL=$URL_PREFIX/sdk/dartsdk-linux-x64-release.zip
DARTIUM_URL=$URL_PREFIX/dartium/dartium-linux-x64-release.zip
download_and_unzip() {
ZIPFILE=${1/*\//}
curl -O -L $1 && unzip -q $ZIPFILE && rm $ZIPFILE
}
# TODO: do these downloads in parallel
download_and_unzip $DART_SDK_URL
download_and_unzip $DARTIUM_URL
echo Fetched new dart version $(<dart-sdk/version)
if [[ -n $DARTIUM_URL ]]; then
mv dartium-* chromium
fi
|
scripts/travis/install.sh
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.0001701534929452464,
0.0001681094290688634,
0.00016609895101282746,
0.00016809265071060508,
0.0000017800829255065764
] |
{
"id": 1,
"code_window": [
" }\n",
"}\n",
"\n",
"export class FieldRead extends AST {\n",
" constructor(receiver:AST, name:string, getter:Function) {\n",
" this.receiver = receiver;\n",
" this.name = name;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final receiver:AST')\n",
" @FIELD('final name:string')\n",
" @FIELD('final getter:Function')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 39
}
|
import {FIELD, int, isBlank} from 'facade/lang';
import {ListWrapper, List} from 'facade/collection';
import {Lexer, EOF, Token, $PERIOD, $COLON, $SEMICOLON} from './lexer';
import {ClosureMap} from './closure_map';
import {
AST,
ImplicitReceiver,
FieldRead,
LiteralPrimitive,
Expression,
Binary,
PrefixNot,
Conditional,
Formatter
} from './ast';
var _implicitReceiver = new ImplicitReceiver();
export class Parser {
@FIELD('final _lexer:Lexer')
@FIELD('final _closureMap:ClosureMap')
constructor(lexer:Lexer, closureMap:ClosureMap){
this._lexer = lexer;
this._closureMap = closureMap;
}
parseAction(input:string):AST {
var tokens = this._lexer.tokenize(input);
return new _ParseAST(input, tokens, this._closureMap, true).parseChain();
}
parseBinding(input:string):AST {
var tokens = this._lexer.tokenize(input);
return new _ParseAST(input, tokens, this._closureMap, false).parseChain();
}
}
class _ParseAST {
@FIELD('final input:String')
@FIELD('final tokens:List<Token>')
@FIELD('final closureMap:ClosureMap')
@FIELD('final parseAction:boolean')
@FIELD('index:int')
constructor(input:string, tokens:List, closureMap:ClosureMap, parseAction:boolean) {
this.input = input;
this.tokens = tokens;
this.index = 0;
this.closureMap = closureMap;
this.parseAction = parseAction;
}
peek(offset:int):Token {
var i = this.index + offset;
return i < this.tokens.length ? this.tokens[i] : EOF;
}
get next():Token {
return this.peek(0);
}
get inputIndex():int {
return (this.index < this.tokens.length) ? this.next.index : this.input.length;
}
advance() {
this.index ++;
}
optionalCharacter(code:int):boolean {
if (this.next.isCharacter(code)) {
this.advance();
return true;
} else {
return false;
}
}
optionalOperator(op:string):boolean {
if (this.next.isOperator(op)) {
this.advance();
return true;
} else {
return false;
}
}
parseChain():AST {
var exprs = [];
while (this.index < this.tokens.length) {
var expr = this.parseFormatter();
ListWrapper.push(exprs, expr);
while (this.optionalCharacter($SEMICOLON)) {
if (! this.parseAction) {
this.error("Binding expression cannot contain chained expression");
}
}
}
return ListWrapper.first(exprs);
}
parseFormatter() {
var result = this.parseExpression();
while (this.optionalOperator("|")) {
if (this.parseAction) {
this.error("Cannot have a formatter in an action expression");
}
var name = this.parseIdentifier();
var args = ListWrapper.create();
while (this.optionalCharacter($COLON)) {
ListWrapper.push(args, this.parseExpression());
}
result = new Formatter(result, name, args);
}
return result;
}
parseExpression() {
return this.parseConditional();
}
parseConditional() {
var start = this.inputIndex;
var result = this.parseLogicalOr();
if (this.optionalOperator('?')) {
var yes = this.parseExpression();
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.parseExpression();
return new Conditional(result, yes, no);
} else {
return result;
}
}
parseLogicalOr() {
// '||'
var result = this.parseLogicalAnd();
while (this.optionalOperator('||')) {
result = new Binary('||', result, this.parseLogicalAnd());
}
return result;
}
parseLogicalAnd() {
// '&&'
var result = this.parseEquality();
while (this.optionalOperator('&&')) {
result = new Binary('&&', result, this.parseEquality());
}
return result;
}
parseEquality() {
// '==','!='
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 {
return result;
}
}
}
parseRelational() {
// '<', '>', '<=', '>='
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() {
// '+', '-'
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() {
// '*', '%', '/', '~/'
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());
// TODO(rado): This exists only in Dart, figure out whether to support it.
// } else if (this.optionalOperator('~/')) {
// result = new BinaryTruncatingDivide(result, this.parsePrefix());
} else {
return result;
}
}
}
parsePrefix() {
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.parseAccessOrCallMember();
}
}
parseAccessOrCallMember() {
var result = this.parsePrimary();
// TODO: add missing cases.
return result;
}
parsePrimary() {
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.next.isIdentifier()) {
return this.parseAccess();
} else if (this.next.isNumber()) {
var value = this.next.toNumber();
this.advance();
return new LiteralPrimitive(value);
} else if (this.next.isString()) {
var value = this.next.toString();
this.advance();
return new LiteralPrimitive(value);
} else if (this.index >= this.tokens.length) {
throw `Unexpected end of expression: ${this.input}`;
} else {
throw `Unexpected token ${this.next}`;
}
}
parseAccess():AST {
var result = this.parseFieldRead(_implicitReceiver);
while(this.optionalCharacter($PERIOD)) {
result = this.parseFieldRead(result);
}
return result;
}
parseFieldRead(receiver):AST {
var id = this.parseIdentifier();
return new FieldRead(receiver, id, this.closureMap.getter(id));
}
parseIdentifier():string {
var n = this.next;
if (!n.isIdentifier() && !n.isKeyword()) {
this.error(`Unexpected token ${n}, expected identifier or keyword`)
}
this.advance();
return n.toString();
}
error(message:string, index:int = 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 ParserError(`Parser Error: ${message} ${location} [${this.input}]`);
}
}
class ParserError extends Error {
constructor(message) {
this.message = message;
}
toString() {
return this.message;
}
}
|
modules/change_detection/src/parser/parser.js
| 1 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.9992161989212036,
0.09684614092111588,
0.00016721530118957162,
0.0001745934278005734,
0.29512491822242737
] |
{
"id": 1,
"code_window": [
" }\n",
"}\n",
"\n",
"export class FieldRead extends AST {\n",
" constructor(receiver:AST, name:string, getter:Function) {\n",
" this.receiver = receiver;\n",
" this.name = name;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final receiver:AST')\n",
" @FIELD('final name:string')\n",
" @FIELD('final getter:Function')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 39
}
|
library element_injector_benchmark;
import './instantiate_benchmark.dart' as ib;
import './instantiate_benchmark_codegen.dart' as ibc;
import './instantiate_directive_benchmark.dart' as idb;
import 'dart:js' as js;
main () {
js.context['benchmarkSteps'].add(new js.JsObject.jsify({
"name": "ElementInjector.instantiate + instantiateDirectives",
"fn": new js.JsFunction.withThis((_) => ib.run())
}));
js.context['benchmarkSteps'].add(new js.JsObject.jsify({
"name": "ElementInjector.instantiateDirectives",
"fn": new js.JsFunction.withThis((_) => idb.run())
}));
js.context['benchmarkSteps'].add(new js.JsObject.jsify({
"name": "ElementInjector.instantiate + instantiateDirectives (codegen)",
"fn": new js.JsFunction.withThis((_) => ibc.run())
}));
}
|
modules/benchmarks/src/element_injector/benchmark.dart
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.0001758198341121897,
0.0001747963688103482,
0.00017320839106105268,
0.00017536089580971748,
0.0000011383973514966783
] |
{
"id": 1,
"code_window": [
" }\n",
"}\n",
"\n",
"export class FieldRead extends AST {\n",
" constructor(receiver:AST, name:string, getter:Function) {\n",
" this.receiver = receiver;\n",
" this.name = name;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final receiver:AST')\n",
" @FIELD('final name:string')\n",
" @FIELD('final getter:Function')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 39
}
|
{
"name": "rtts-assert",
"version": "0.0.1",
"description": "A type assertion library for Traceur.",
"main": "./dist/cjs/assert.js",
"homepage": "https://github.com/angular/assert",
"repository": {
"type": "git",
"url": "git://github.com/angular/assert.git"
},
"bugs": {
"url": "https://github.com/angular/assert/issues"
},
"dependencies": {},
"devDependencies": {
"gulp": "^3.5.6",
"gulp-connect": "~1.0.5",
"gulp-traceur": "~0.4.0",
"karma": "^0.12.1",
"karma-chrome-launcher": "^0.1.2",
"karma-jasmine": "^0.2.2",
"karma-requirejs": "^0.2.1",
"karma-traceur-preprocessor": "^0.2.2",
"pipe": "git://github.com/angular/pipe#remove-transitive-deps"
},
"scripts": {
"test": "karma start --single-run"
},
"author": "Vojta Jína <[email protected]>",
"license": "Apache-2.0"
}
|
modules/rtts_assert/package.json
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.00017844799731392413,
0.0001741339365253225,
0.0001717977866064757,
0.00017314498836640269,
0.000002556887920945883
] |
{
"id": 1,
"code_window": [
" }\n",
"}\n",
"\n",
"export class FieldRead extends AST {\n",
" constructor(receiver:AST, name:string, getter:Function) {\n",
" this.receiver = receiver;\n",
" this.name = name;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final receiver:AST')\n",
" @FIELD('final name:string')\n",
" @FIELD('final getter:Function')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 39
}
|
library core.annotations.facade;
import 'package:di/di.dart' show Module;
import '../compiler/element_module.dart' show ElementModule;
typedef DomServicesFunction(ElementModule m);
typedef ComponentServicesFunction(Module m);
|
modules/core/src/annotations/facade.dart
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.00017276334983762354,
0.00017276334983762354,
0.00017276334983762354,
0.00017276334983762354,
0
] |
{
"id": 2,
"code_window": [
"}\n",
"\n",
"export class Formatter extends AST {\n",
" constructor(exp:AST, name:string, args:List) {\n",
" this.exp = exp;\n",
" this.name = name;\n",
" this.args = args;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final exp:AST')\n",
" @FIELD('final name:string')\n",
" @FIELD('final args:List<AST>')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 55
}
|
import {FIELD, toBool, autoConvertAdd, isBlank, FunctionWrapper, BaseException} from "facade/lang";
import {List, ListWrapper} from "facade/collection";
export class AST {
eval(context) {
throw new BaseException("Not supported");
}
visit(visitor) {
}
}
export class ImplicitReceiver extends AST {
eval(context) {
return context;
}
visit(visitor) {
visitor.visitImplicitReceiver(this);
}
}
export class Conditional extends AST {
constructor(condition:AST, trueExp:AST, falseExp:AST){
this.condition = condition;
this.trueExp = trueExp;
this.falseExp = falseExp;
}
eval(context) {
if(this.condition.eval(context)) {
return this.trueExp.eval(context);
} else {
return this.falseExp.eval(context);
}
}
}
export class FieldRead extends AST {
constructor(receiver:AST, name:string, getter:Function) {
this.receiver = receiver;
this.name = name;
this.getter = getter;
}
eval(context) {
return this.getter(this.receiver.eval(context));
}
visit(visitor) {
visitor.visitFieldRead(this);
}
}
export class Formatter extends AST {
constructor(exp:AST, name:string, args:List) {
this.exp = exp;
this.name = name;
this.args = args;
this.allArgs = ListWrapper.concat([exp], args);
}
visit(visitor) {
visitor.visitFormatter(this);
}
}
export class LiteralPrimitive extends AST {
@FIELD('final value')
constructor(value) {
this.value = value;
}
eval(context) {
return this.value;
}
visit(visitor) {
visitor.visitLiteralPrimitive(this);
}
}
export class Binary extends AST {
@FIELD('final operation:string')
@FIELD('final left:AST')
@FIELD('final right:AST')
constructor(operation:string, left:AST, right:AST) {
this.operation = operation;
this.left = left;
this.right = right;
}
visit(visitor) {
visitor.visitBinary(this);
}
eval(context) {
var left = this.left.eval(context);
switch (this.operation) {
case '&&': return toBool(left) && toBool(this.right.eval(context));
case '||': return toBool(left) || toBool(this.right.eval(context));
}
var right = this.right.eval(context);
// Null check for the operations.
if (left == null || right == null) {
throw new BaseException("One of the operands is null");
}
switch (this.operation) {
case '+' : return autoConvertAdd(left, right);
case '-' : return left - right;
case '*' : return left * right;
case '/' : return left / right;
// This exists only in Dart, TODO(rado) figure out whether to support it.
// case '~/' : return left ~/ right;
case '%' : return left % right;
case '==' : return left == right;
case '!=' : return left != right;
case '<' : return left < right;
case '>' : return left > right;
case '<=' : return left <= right;
case '>=' : return left >= right;
case '^' : return left ^ right;
case '&' : return left & right;
}
throw 'Internal error [$operation] not handled';
}
}
export class PrefixNot extends AST {
@FIELD('final operation:string')
@FIELD('final expression:AST')
constructor(expression:AST) {
this.expression = expression;
}
visit(visitor) { visitor.visitPrefixNot(this); }
eval(context) {
return !toBool(this.expression.eval(context));
}
}
//INTERFACE
export class AstVisitor {
visitImplicitReceiver(ast:ImplicitReceiver) {}
visitFieldRead(ast:FieldRead) {}
visitBinary(ast:Binary) {}
visitPrefixNot(ast:PrefixNot) {}
visitLiteralPrimitive(ast:LiteralPrimitive) {}
visitFormatter(ast:Formatter) {}
}
var _evalListCache = [[],[0],[0,0],[0,0,0],[0,0,0,0],[0,0,0,0,0]];
function evalList(context, exps:List){
var length = exps.length;
var result = _evalListCache[length];
for (var i = 0; i < length; i++) {
result[i] = exps[i].eval(context);
}
return result;
}
|
modules/change_detection/src/parser/ast.js
| 1 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.9985657334327698,
0.18412505090236664,
0.00016722900909371674,
0.0003129068936686963,
0.3825169503688812
] |
{
"id": 2,
"code_window": [
"}\n",
"\n",
"export class Formatter extends AST {\n",
" constructor(exp:AST, name:string, args:List) {\n",
" this.exp = exp;\n",
" this.name = name;\n",
" this.args = args;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final exp:AST')\n",
" @FIELD('final name:string')\n",
" @FIELD('final args:List<AST>')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 55
}
|
// Asserting APIs:
// - generated by Traceur (based on type annotations)
// - can be also used in tests for instance
assert.type(something, Type);
assert.returnType(returnValue, Type);
assert.argumentTypes(firstArg, Type, secondArg, Type);
// this can be used anywhere in the code
// (useful inside test, when we don't wanna define an interface)
assert(value).is(...)
// Custom type assert:
// - i have a custom type
// - adding an assert methos
assert.define(MyUser, function(value) {
assert(value).is(Type, Type2); // or
assert(value, 'name').is(assert.string);
assert(value, 'contact').is(assert.structure({
email: assert.string,
cell: assert.string
}));
assert(value, 'contacts').is(assert.arrayOf(assert.structure({email: assert.string})));
});
// Define interface (an empty type with assert method)
// - returns an empty class with assert method
var Email = assert.define('IEmail', function(value) {
assert(value).is(String);
if (value.indexOf('@') !== -1) {
assert.fail('has to contain "@"');
}
});
// Predefined types
assert.string
assert.number
assert.boolean
assert.arrayOf(...types)
assert.structure(object)
|
modules/rtts_assert/API.md
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.0001715242542559281,
0.0001678531989455223,
0.00016202108236029744,
0.0001685926254140213,
0.0000032973191537166713
] |
{
"id": 2,
"code_window": [
"}\n",
"\n",
"export class Formatter extends AST {\n",
" constructor(exp:AST, name:string, args:List) {\n",
" this.exp = exp;\n",
" this.name = name;\n",
" this.args = args;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final exp:AST')\n",
" @FIELD('final name:string')\n",
" @FIELD('final args:List<AST>')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 55
}
|
import {Directive} from './directive';
import {ABSTRACT, CONST} from 'facade/lang';
export class Component extends Directive {
@CONST()
constructor({
selector,
lightDomServices,
implementsTypes,
template,
elementServices,
componentServices
}:{
selector:String,
template:TemplateConfig,
lightDomServices:DomServicesFunction,
shadowDomServices:DomServicesFunction,
componentServices:ComponentServicesFunction,
implementsTypes:Array<Type>
})
{
super({
selector: selector,
lightDomServices: lightDomServices,
implementsTypes: implementsTypes});
this.template = template;
this.elementServices = elementServices;
this.componentServices = componentServices;
}
}
///////////////////////////
/*
import 'package:angular/core.dart' as core;
@Component(
selector: 'example',
template: const TemplateConfig(
url: 'example.dart',
uses: const [core.CONFIG],
directives: const [CompA],
formatters: const [Stringify]
),
componentServices: Example.componentServices,
elementServices: Example.elementServices,
implementsTypes: const [App]
)
class Example implements App {
static componentServices(Module m) {
m.bind();
}
static elementServices(ElementModule m) {
m.bind();
}
}
class CompA {}
@Formatter()
class Stringify {}
<CompA>
LightDOM:
</CompA>
CompA ShadowDOM:
<div>
<CompB></CompB>
</div>
CompB SHadowDOM:
<div></div>
*/
|
modules/core/src/annotations/component.js
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.9972284436225891,
0.12511788308620453,
0.00016388889343943447,
0.00017102647689171135,
0.3296278417110443
] |
{
"id": 2,
"code_window": [
"}\n",
"\n",
"export class Formatter extends AST {\n",
" constructor(exp:AST, name:string, args:List) {\n",
" this.exp = exp;\n",
" this.name = name;\n",
" this.args = args;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final exp:AST')\n",
" @FIELD('final name:string')\n",
" @FIELD('final args:List<AST>')\n"
],
"file_path": "modules/change_detection/src/parser/ast.js",
"type": "add",
"edit_start_line_idx": 55
}
|
import {VariableStatement, VariableDeclarationList} from 'traceur/src/syntax/trees/ParseTrees';
import {ParseTreeTransformer} from './ParseTreeTransformer';
/**
* Transforms `var a, b;` to `var a; var b;`
*/
export class MultiVarTransformer extends ParseTreeTransformer {
// Individual item transformer can return an array of items.
// This is used in `transformVariableStatement`.
// Otherwise this is copy/pasted from `ParseTreeTransformer`.
transformList(list) {
var transformedList = [];
var transformedItem = null;
for (var i = 0, ii = list.length; i < ii; i++) {
transformedItem = this.transformAny(list[i]);
if (Array.isArray(transformedItem)) {
transformedList = transformedList.concat(transformedItem);
} else {
transformedList.push(transformedItem);
}
}
return transformedList;
}
/**
* @param {VariableStatement} tree
* @returns {ParseTree}
*/
transformVariableStatement(tree) {
var declarations = tree.declarations.declarations;
if (declarations.length === 1 || declarations.length === 0) {
return tree;
}
// Multiple var declaration, we will split it into multiple statements.
// TODO(vojta): We can leave the multi-definition as long as they are all the same type/untyped.
return declarations.map(function(declaration) {
return new VariableStatement(tree.location, new VariableDeclarationList(tree.location,
tree.declarations.declarationType, [declaration]));
});
}
}
|
tools/transpiler/src/codegeneration/MultiVarTransformer.js
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.0001718316925689578,
0.00017050937458407134,
0.0001678593980614096,
0.00017106726591009647,
0.0000014430783039642847
] |
{
"id": 3,
"code_window": [
" }\n",
"}\n",
"\n",
"class _ParseAST {\n",
" @FIELD('final input:String')\n",
" @FIELD('final tokens:List<Token>')\n",
" @FIELD('final closureMap:ClosureMap')\n",
" @FIELD('final parseAction:boolean')\n",
" @FIELD('index:int')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final input:string')\n"
],
"file_path": "modules/change_detection/src/parser/parser.js",
"type": "replace",
"edit_start_line_idx": 38
}
|
import {FIELD, toBool, autoConvertAdd, isBlank, FunctionWrapper, BaseException} from "facade/lang";
import {List, ListWrapper} from "facade/collection";
export class AST {
eval(context) {
throw new BaseException("Not supported");
}
visit(visitor) {
}
}
export class ImplicitReceiver extends AST {
eval(context) {
return context;
}
visit(visitor) {
visitor.visitImplicitReceiver(this);
}
}
export class Conditional extends AST {
constructor(condition:AST, trueExp:AST, falseExp:AST){
this.condition = condition;
this.trueExp = trueExp;
this.falseExp = falseExp;
}
eval(context) {
if(this.condition.eval(context)) {
return this.trueExp.eval(context);
} else {
return this.falseExp.eval(context);
}
}
}
export class FieldRead extends AST {
constructor(receiver:AST, name:string, getter:Function) {
this.receiver = receiver;
this.name = name;
this.getter = getter;
}
eval(context) {
return this.getter(this.receiver.eval(context));
}
visit(visitor) {
visitor.visitFieldRead(this);
}
}
export class Formatter extends AST {
constructor(exp:AST, name:string, args:List) {
this.exp = exp;
this.name = name;
this.args = args;
this.allArgs = ListWrapper.concat([exp], args);
}
visit(visitor) {
visitor.visitFormatter(this);
}
}
export class LiteralPrimitive extends AST {
@FIELD('final value')
constructor(value) {
this.value = value;
}
eval(context) {
return this.value;
}
visit(visitor) {
visitor.visitLiteralPrimitive(this);
}
}
export class Binary extends AST {
@FIELD('final operation:string')
@FIELD('final left:AST')
@FIELD('final right:AST')
constructor(operation:string, left:AST, right:AST) {
this.operation = operation;
this.left = left;
this.right = right;
}
visit(visitor) {
visitor.visitBinary(this);
}
eval(context) {
var left = this.left.eval(context);
switch (this.operation) {
case '&&': return toBool(left) && toBool(this.right.eval(context));
case '||': return toBool(left) || toBool(this.right.eval(context));
}
var right = this.right.eval(context);
// Null check for the operations.
if (left == null || right == null) {
throw new BaseException("One of the operands is null");
}
switch (this.operation) {
case '+' : return autoConvertAdd(left, right);
case '-' : return left - right;
case '*' : return left * right;
case '/' : return left / right;
// This exists only in Dart, TODO(rado) figure out whether to support it.
// case '~/' : return left ~/ right;
case '%' : return left % right;
case '==' : return left == right;
case '!=' : return left != right;
case '<' : return left < right;
case '>' : return left > right;
case '<=' : return left <= right;
case '>=' : return left >= right;
case '^' : return left ^ right;
case '&' : return left & right;
}
throw 'Internal error [$operation] not handled';
}
}
export class PrefixNot extends AST {
@FIELD('final operation:string')
@FIELD('final expression:AST')
constructor(expression:AST) {
this.expression = expression;
}
visit(visitor) { visitor.visitPrefixNot(this); }
eval(context) {
return !toBool(this.expression.eval(context));
}
}
//INTERFACE
export class AstVisitor {
visitImplicitReceiver(ast:ImplicitReceiver) {}
visitFieldRead(ast:FieldRead) {}
visitBinary(ast:Binary) {}
visitPrefixNot(ast:PrefixNot) {}
visitLiteralPrimitive(ast:LiteralPrimitive) {}
visitFormatter(ast:Formatter) {}
}
var _evalListCache = [[],[0],[0,0],[0,0,0],[0,0,0,0],[0,0,0,0,0]];
function evalList(context, exps:List){
var length = exps.length;
var result = _evalListCache[length];
for (var i = 0; i < length; i++) {
result[i] = exps[i].eval(context);
}
return result;
}
|
modules/change_detection/src/parser/ast.js
| 1 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.0006390619673766196,
0.0002588861098047346,
0.0001675731473369524,
0.0001756146375555545,
0.0001647590397624299
] |
{
"id": 3,
"code_window": [
" }\n",
"}\n",
"\n",
"class _ParseAST {\n",
" @FIELD('final input:String')\n",
" @FIELD('final tokens:List<Token>')\n",
" @FIELD('final closureMap:ClosureMap')\n",
" @FIELD('final parseAction:boolean')\n",
" @FIELD('index:int')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final input:string')\n"
],
"file_path": "modules/change_detection/src/parser/parser.js",
"type": "replace",
"edit_start_line_idx": 38
}
|
import {Binding, Dependency, Key, Injector} from 'di/di';
import {ProtoElementInjector} from 'core/compiler/element_injector';
var ITERATIONS = 20000;
var count = 0;
export function run () {
var appInjector = new Injector([]);
var bindings = [
new Binding(Key.get(A), () => new A(), [], false),
new Binding(Key.get(B), () => new B(), [], false),
new Binding(Key.get(C), (a,b) => new C(a,b), [
new Dependency(Key.get(A), false, false, []),
new Dependency(Key.get(B), false, false, [])
], false)];
var proto = new ProtoElementInjector(null, bindings);
for (var i = 0; i < ITERATIONS; ++i) {
var ei = proto.instantiate({view:null});
ei.instantiateDirectives(appInjector);
}
}
class A {
constructor() {
count++;
}
}
class B {
constructor() {
count++;
}
}
class C {
constructor(a:A, b:B) {
count++;
}
}
|
modules/benchmarks/src/element_injector/instantiate_benchmark_codegen.js
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.0001759662409313023,
0.00017148278129752725,
0.00016813669935800135,
0.00017151952488347888,
0.000002715065875236178
] |
{
"id": 3,
"code_window": [
" }\n",
"}\n",
"\n",
"class _ParseAST {\n",
" @FIELD('final input:String')\n",
" @FIELD('final tokens:List<Token>')\n",
" @FIELD('final closureMap:ClosureMap')\n",
" @FIELD('final parseAction:boolean')\n",
" @FIELD('index:int')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final input:string')\n"
],
"file_path": "modules/change_detection/src/parser/parser.js",
"type": "replace",
"edit_start_line_idx": 38
}
|
export var Type = Function;
export var Math = window.Math;
export class FIELD {
constructor(definition) {
this.definition = definition;
}
}
export class CONST {}
export class ABSTRACT {}
export class IMPLEMENTS {}
export function isPresent(obj):boolean {
return obj !== undefined && obj !== null;
}
export function isBlank(obj):boolean {
return obj === undefined || obj === null;
}
export function toBool(obj) {
return !!obj;
}
export function autoConvertAdd(a, b) {
return a + b;
}
export function stringify(token):string {
if (typeof token === 'string') {
return token;
}
if (token === undefined || token === null) {
return '' + token;
}
if (token.name) {
return token.name;
}
return token.toString();
}
export class StringWrapper {
static fromCharCode(code:int) {
return String.fromCharCode(code);
}
static charCodeAt(s:string, index:int) {
return s.charCodeAt(index);
}
}
export class StringJoiner {
constructor() {
this.parts = [];
}
add(part:string) {
this.parts.push(part);
}
toString():string {
return this.parts.join("");
}
}
export class NumerParseError extends Error {
constructor(message) {
this.message = message;
}
toString() {
return this.message;
}
}
export class NumberWrapper {
static parseIntAutoRadix(text:string):int {
var result:int = parseInt(text);
if (isNaN(result)) {
throw new NumerParseError("Invalid integer literal when parsing " + text);
}
return result;
}
static parseInt(text:string, radix:int):int {
if (radix == 10) {
if (/^(\-|\+)?[0-9]+$/.test(text)) {
return parseInt(text, radix);
}
} else if (radix == 16) {
if (/^(\-|\+)?[0-9ABCDEFabcdef]+$/.test(text)) {
return parseInt(text, radix);
}
} else {
var result:int = parseInt(text, radix);
if (!isNaN(result)) {
return result;
}
}
throw new NumerParseError("Invalid integer literal when parsing " + text + " in base " + radix);
}
// TODO: NaN is a valid literal but is returned by parseFloat to indicate an error.
static parseFloat(text:string):number {
return parseFloat(text);
}
}
export function int() {};
int.assert = function(value) {
return value == null || typeof value == 'number' && value === Math.floor(value);
}
export var RegExp = window.RegExp;
export class RegExpWrapper {
static create(regExpStr):RegExp {
return new RegExp(regExpStr, 'g');
}
static matcher(regExp, input) {
return {
re: regExp,
input: input
};
}
}
export class RegExpMatcherWrapper {
static next(matcher) {
return matcher.re.exec(matcher.input);
}
}
export class FunctionWrapper {
static apply(fn:Function, posArgs) {
return fn.apply(null, posArgs);
}
}
export class BaseException extends Error {
constructor(message){
this.message = message;
}
toString():String {
return this.message;
}
}
|
modules/facade/src/lang.es6
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.0013418019516393542,
0.0004287410993129015,
0.00016423540364485234,
0.00019147104467265308,
0.00038779329042881727
] |
{
"id": 3,
"code_window": [
" }\n",
"}\n",
"\n",
"class _ParseAST {\n",
" @FIELD('final input:String')\n",
" @FIELD('final tokens:List<Token>')\n",
" @FIELD('final closureMap:ClosureMap')\n",
" @FIELD('final parseAction:boolean')\n",
" @FIELD('index:int')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" @FIELD('final input:string')\n"
],
"file_path": "modules/change_detection/src/parser/parser.js",
"type": "replace",
"edit_start_line_idx": 38
}
|
import {FunctionExpression} from 'traceur/src/syntax/trees/ParseTrees';
import {ParseTreeTransformer} from 'traceur/src/codegeneration/ParseTreeTransformer';
import {FUNCTION_BODY} from 'traceur/src/syntax/trees/ParseTreeType';
import alphaRenameThisAndArguments from 'traceur/src/codegeneration/alphaRenameThisAndArguments';
import {
createFunctionBody,
createReturnStatement
} from 'traceur/src/codegeneration/ParseTreeFactory';
/**
* Transforms an arrow function expression into a function declaration by adding a function
* body and return statement if needed.
*/
export class ArrowFunctionTransformer extends ParseTreeTransformer {
transformArrowFunctionExpression(tree) {
var body = this.transformAny(tree.body);
var parameterList = this.transformAny(tree.parameterList);
if (body.type !== FUNCTION_BODY) {
body = createFunctionBody([createReturnStatement(body)]);
}
return new FunctionExpression(tree.location, null, tree.functionKind, parameterList, null, [],
body);
}
}
|
tools/transpiler/src/codegeneration/ArrowFunctionTransformer.js
| 0 |
https://github.com/angular/angular/commit/03c779321fff3f75136f60c1f0063a31666e90e0
|
[
0.00027142101316712797,
0.00020395976025611162,
0.00016696754028089345,
0.000173490698216483,
0.00004777659341925755
] |
{
"id": 0,
"code_window": [
" \"text.html.markdown\"\n",
" ],\n",
" \"embeddedLanguages\": {\n",
" \"meta.embedded.math.markdown\": \"latex\"\n",
" }\n",
" }\n",
" ],\n",
" \"notebookRenderer\": [\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"meta.embedded.math.markdown\": \"latex\",\n",
" \"punctuation.definition.math.end.markdown\": \"latex\"\n"
],
"file_path": "extensions/markdown-math/package.json",
"type": "replace",
"edit_start_line_idx": 54
}
|
{
"fileTypes": [],
"injectionSelector": "L:meta.paragraph.markdown - (comment, string, markup.math.inline.markdown, markup.fenced_code.block.markdown)",
"patterns": [
{
"include": "#math_inline_double"
},
{
"include": "#math_inline_single"
},
{
"include": "#math_inline_block"
}
],
"repository": {
"math_inline_single": {
"name": "markup.math.inline.markdown",
"match": "(?<=\\s|\\W|^)(?<!\\$)(\\$)(.+?)(\\$)(?!\\$)(?=\\s|\\W|$)",
"captures": {
"1": {
"name": "punctuation.definition.math.begin.markdown"
},
"2": {
"name": "meta.embedded.math.markdown",
"patterns": [
{
"include": "text.html.markdown.math#math"
}
]
},
"3": {
"name": "punctuation.definition.math.begin.markdown"
}
}
},
"math_inline_double": {
"name": "markup.math.inline.markdown",
"match": "(?<=\\s|\\W|^)(?<!\\$)(\\$\\$)(.+?)(\\$\\$)(?!\\$)(?=\\s|\\W|$)",
"captures": {
"1": {
"name": "punctuation.definition.math.begin.markdown"
},
"2": {
"name": "meta.embedded.math.markdown",
"patterns": [
{
"include": "text.html.markdown.math#math"
}
]
},
"3": {
"name": "punctuation.definition.math.begin.markdown"
}
}
},
"math_inline_block": {
"name": "markup.math.inline.markdown",
"contentName": "meta.embedded.math.markdown",
"begin": "(?<=\\s|^)(\\${2})",
"beginCaptures": {
"2": {
"name": "punctuation.definition.math.begin.markdown"
}
},
"end": "(\\${2})(?=\\s|$)",
"endCaptures": {
"2": {
"name": "punctuation.definition.math.end.markdown"
}
},
"patterns": [
{
"include": "text.html.markdown.math#math"
}
]
}
},
"scopeName": "markdown.math.inline"
}
|
extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json
| 1 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.004134788643568754,
0.0014120612759143114,
0.00016740370483603328,
0.0003553543356247246,
0.0016523712547495961
] |
{
"id": 0,
"code_window": [
" \"text.html.markdown\"\n",
" ],\n",
" \"embeddedLanguages\": {\n",
" \"meta.embedded.math.markdown\": \"latex\"\n",
" }\n",
" }\n",
" ],\n",
" \"notebookRenderer\": [\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"meta.embedded.math.markdown\": \"latex\",\n",
" \"punctuation.definition.math.end.markdown\": \"latex\"\n"
],
"file_path": "extensions/markdown-math/package.json",
"type": "replace",
"edit_start_line_idx": 54
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// empty placeholder declaration for the `comments/comment/editorActions` menu
|
src/vscode-dts/vscode.proposed.contribCommentEditorActionsMenu.d.ts
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.00017494922212790698,
0.00017494922212790698,
0.00017494922212790698,
0.00017494922212790698,
0
] |
{
"id": 0,
"code_window": [
" \"text.html.markdown\"\n",
" ],\n",
" \"embeddedLanguages\": {\n",
" \"meta.embedded.math.markdown\": \"latex\"\n",
" }\n",
" }\n",
" ],\n",
" \"notebookRenderer\": [\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"meta.embedded.math.markdown\": \"latex\",\n",
" \"punctuation.definition.math.end.markdown\": \"latex\"\n"
],
"file_path": "extensions/markdown-math/package.json",
"type": "replace",
"edit_start_line_idx": 54
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { TextModel } from 'vs/editor/common/model/textModel';
import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl';
import { TestConfiguration } from 'vs/editor/test/browser/config/testConfiguration';
import { MonospaceLineBreaksComputerFactory } from 'vs/editor/common/viewModel/monospaceLineBreaksComputer';
import { createTextModel } from 'vs/editor/test/common/testTextModel';
import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService';
import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';
export function testViewModel(text: string[], options: IEditorOptions, callback: (viewModel: ViewModel, model: TextModel) => void): void {
const EDITOR_ID = 1;
const configuration = new TestConfiguration(options);
const model = createTextModel(text.join('\n'));
const monospaceLineBreaksComputerFactory = MonospaceLineBreaksComputerFactory.create(configuration.options);
const viewModel = new ViewModel(EDITOR_ID, configuration, model, monospaceLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, null!, new TestLanguageConfigurationService(), new TestThemeService());
callback(viewModel, model);
viewModel.dispose();
model.dispose();
configuration.dispose();
}
|
src/vs/editor/test/browser/viewModel/testViewModel.ts
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.00017438762006349862,
0.00017355762247461826,
0.0001723357563605532,
0.00017394953465554863,
8.82316612660361e-7
] |
{
"id": 0,
"code_window": [
" \"text.html.markdown\"\n",
" ],\n",
" \"embeddedLanguages\": {\n",
" \"meta.embedded.math.markdown\": \"latex\"\n",
" }\n",
" }\n",
" ],\n",
" \"notebookRenderer\": [\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"meta.embedded.math.markdown\": \"latex\",\n",
" \"punctuation.definition.math.end.markdown\": \"latex\"\n"
],
"file_path": "extensions/markdown-math/package.json",
"type": "replace",
"edit_start_line_idx": 54
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { LifecyclePhase, ILifecycleService, StartupKind } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { language } from 'vs/base/common/platform';
import { Disposable } from 'vs/base/common/lifecycle';
import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry';
import { configurationTelemetry, TelemetryTrustedValue } from 'vs/platform/telemetry/common/telemetryUtils';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ITextFileService, ITextFileSaveEvent, ITextFileResolveEvent } from 'vs/workbench/services/textfile/common/textfiles';
import { extname, basename, isEqual, isEqualOrParent } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { getMimeTypes } from 'vs/editor/common/services/languagesAssociations';
import { hash } from 'vs/base/common/hash';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IUserDataProfileService } from 'vs/workbench/services/userDataProfile/common/userDataProfile';
type TelemetryData = {
mimeType: TelemetryTrustedValue<string>;
ext: string;
path: number;
reason?: number;
allowlistedjson?: string;
};
type FileTelemetryDataFragment = {
mimeType: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The language type of the file (for example XML).' };
ext: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The file extension of the file (for example xml).' };
path: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The path of the file as a hash.' };
reason?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The reason why a file is read or written. Allows to e.g. distinguish auto save from normal save.' };
allowlistedjson?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The name of the file but only if it matches some well known file names such as package.json or tsconfig.json.' };
};
export class TelemetryContribution extends Disposable implements IWorkbenchContribution {
private static ALLOWLIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
private static ALLOWLIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];
constructor(
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ILifecycleService lifecycleService: ILifecycleService,
@IEditorService editorService: IEditorService,
@IKeybindingService keybindingsService: IKeybindingService,
@IWorkbenchThemeService themeService: IWorkbenchThemeService,
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@IUserDataProfileService private readonly userDataProfileService: IUserDataProfileService,
@IConfigurationService configurationService: IConfigurationService,
@IPaneCompositePartService paneCompositeService: IPaneCompositePartService,
@ITextFileService textFileService: ITextFileService
) {
super();
const { filesToOpenOrCreate, filesToDiff, filesToMerge } = environmentService;
const activeViewlet = paneCompositeService.getActivePaneComposite(ViewContainerLocation.Sidebar);
type WindowSizeFragment = {
innerHeight: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The height of the current window.' };
innerWidth: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The width of the current window.' };
outerHeight: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The height of the current window with all decoration removed.' };
outerWidth: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The width of the current window with all decoration removed.' };
owner: 'bpasero';
comment: 'The size of the window.';
};
type WorkspaceLoadClassification = {
owner: 'bpasero';
emptyWorkbench: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether a folder or workspace is opened or not.' };
windowSize: WindowSizeFragment;
'workbench.filesToOpenOrCreate': { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of files that should open or be created.' };
'workbench.filesToDiff': { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of files that should be compared.' };
'workbench.filesToMerge': { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of files that should be merged.' };
customKeybindingsCount: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of custom keybindings' };
theme: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The current theme of the window.' };
language: { classification: 'SystemMetaData'; purpose: 'BusinessInsight'; comment: 'The display language of the window.' };
pinnedViewlets: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The identifiers of views that are pinned.' };
restoredViewlet?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The identifier of the view that is restored.' };
restoredEditors: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The number of editors that restored.' };
startupKind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'How the window was opened, e.g via reload or not.' };
comment: 'Metadata around the workspace that is being loaded into a window.';
};
type WorkspaceLoadEvent = {
windowSize: { innerHeight: number; innerWidth: number; outerHeight: number; outerWidth: number };
emptyWorkbench: boolean;
'workbench.filesToOpenOrCreate': number;
'workbench.filesToDiff': number;
'workbench.filesToMerge': number;
customKeybindingsCount: number;
theme: string;
language: string;
pinnedViewlets: string[];
restoredViewlet?: string;
restoredEditors: number;
startupKind: StartupKind;
};
telemetryService.publicLog2<WorkspaceLoadEvent, WorkspaceLoadClassification>('workspaceLoad', {
windowSize: { innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth },
emptyWorkbench: contextService.getWorkbenchState() === WorkbenchState.EMPTY,
'workbench.filesToOpenOrCreate': filesToOpenOrCreate && filesToOpenOrCreate.length || 0,
'workbench.filesToDiff': filesToDiff && filesToDiff.length || 0,
'workbench.filesToMerge': filesToMerge && filesToMerge.length || 0,
customKeybindingsCount: keybindingsService.customKeybindingsCount(),
theme: themeService.getColorTheme().id,
language,
pinnedViewlets: paneCompositeService.getPinnedPaneCompositeIds(ViewContainerLocation.Sidebar),
restoredViewlet: activeViewlet ? activeViewlet.getId() : undefined,
restoredEditors: editorService.visibleEditors.length,
startupKind: lifecycleService.startupKind
});
// Error Telemetry
this._register(new ErrorTelemetry(telemetryService));
// Configuration Telemetry
this._register(configurationTelemetry(telemetryService, configurationService));
// Files Telemetry
this._register(textFileService.files.onDidResolve(e => this.onTextFileModelResolved(e)));
this._register(textFileService.files.onDidSave(e => this.onTextFileModelSaved(e)));
// Lifecycle
this._register(lifecycleService.onDidShutdown(() => this.dispose()));
}
private onTextFileModelResolved(e: ITextFileResolveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsReadClassification = {
owner: 'bpasero';
settingsType: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The type of the settings file that was read.' };
comment: 'Track when a settings file was read, for example from an editor.';
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsReadClassification>('settingsRead', { settingsType }); // Do not log read to user settings.json and .vscode folder as a fileGet event as it ruins our JSON usage data
} else {
type FileGetClassification = {
owner: 'bpasero';
comment: 'Track when a file was read, for example from an editor.';
} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FileGetClassification>('fileGet', this.getTelemetryData(e.model.resource, e.reason));
}
}
private onTextFileModelSaved(e: ITextFileSaveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsWrittenClassification = {
owner: 'bpasero';
settingsType: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The type of the settings file that was written to.' };
comment: 'Track when a settings file was written to, for example from an editor.';
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsWrittenClassification>('settingsWritten', { settingsType }); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data
} else {
type FilePutClassfication = {
owner: 'bpasero';
comment: 'Track when a file was written to, for example from an editor.';
} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FilePutClassfication>('filePUT', this.getTelemetryData(e.model.resource, e.reason));
}
}
private getTypeIfSettings(resource: URI): string {
if (extname(resource) !== '.json') {
return '';
}
// Check for global settings file
if (isEqual(resource, this.userDataProfileService.currentProfile.settingsResource)) {
return 'global-settings';
}
// Check for keybindings file
if (isEqual(resource, this.userDataProfileService.currentProfile.keybindingsResource)) {
return 'keybindings';
}
// Check for snippets
if (isEqualOrParent(resource, this.userDataProfileService.currentProfile.snippetsHome)) {
return 'snippets';
}
// Check for workspace settings file
const folders = this.contextService.getWorkspace().folders;
for (const folder of folders) {
if (isEqualOrParent(resource, folder.toResource('.vscode'))) {
const filename = basename(resource);
if (TelemetryContribution.ALLOWLIST_WORKSPACE_JSON.indexOf(filename) > -1) {
return `.vscode/${filename}`;
}
}
}
return '';
}
private getTelemetryData(resource: URI, reason?: number): TelemetryData {
let ext = extname(resource);
// Remove query parameters from the resource extension
const queryStringLocation = ext.indexOf('?');
ext = queryStringLocation !== -1 ? ext.substr(0, queryStringLocation) : ext;
const fileName = basename(resource);
const path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;
const telemetryData = {
mimeType: new TelemetryTrustedValue(getMimeTypes(resource).join(', ')),
ext,
path: hash(path),
reason,
allowlistedjson: undefined as string | undefined
};
if (ext === '.json' && TelemetryContribution.ALLOWLIST_JSON.indexOf(fileName) > -1) {
telemetryData['allowlistedjson'] = fileName;
}
return telemetryData;
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(TelemetryContribution, LifecyclePhase.Restored);
|
src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.00017559649131726474,
0.00017023422697093338,
0.00016413741104770452,
0.00016986993432510644,
0.0000030086500828474527
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t\t\t\"include\": \"text.html.markdown.math#math\"\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t]\n",
"\t\t\t\t},\n",
"\t\t\t\t\"3\": {\n",
"\t\t\t\t\t\"name\": \"punctuation.definition.math.begin.markdown\"\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t},\n",
"\t\t\"math_inline_double\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\"name\": \"punctuation.definition.math.end.markdown\"\n"
],
"file_path": "extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json",
"type": "replace",
"edit_start_line_idx": 31
}
|
{
"name": "markdown-math",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"icon": "icon.png",
"publisher": "vscode",
"license": "MIT",
"aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255",
"engines": {
"vscode": "^1.54.0"
},
"categories": [
"Other"
],
"capabilities": {
"virtualWorkspaces": true,
"untrustedWorkspaces": {
"supported": true
}
},
"main": "./out/extension",
"browser": "./dist/browser/extension",
"activationEvents": [],
"contributes": {
"languages": [
{
"id": "markdown-math",
"aliases": []
}
],
"grammars": [
{
"language": "markdown-math",
"scopeName": "text.html.markdown.math",
"path": "./syntaxes/md-math.tmLanguage.json"
},
{
"scopeName": "markdown.math.block",
"path": "./syntaxes/md-math-block.tmLanguage.json",
"injectTo": [
"text.html.markdown"
],
"embeddedLanguages": {
"meta.embedded.math.markdown": "latex"
}
},
{
"scopeName": "markdown.math.inline",
"path": "./syntaxes/md-math-inline.tmLanguage.json",
"injectTo": [
"text.html.markdown"
],
"embeddedLanguages": {
"meta.embedded.math.markdown": "latex"
}
}
],
"notebookRenderer": [
{
"id": "vscode.markdown-it-katex-extension",
"displayName": "Markdown it KaTeX renderer",
"entrypoint": {
"extends": "vscode.markdown-it-renderer",
"path": "./notebook-out/katex.js"
}
}
],
"markdown.markdownItPlugins": true,
"markdown.previewStyles": [
"./notebook-out/katex.min.css",
"./preview-styles/index.css"
],
"configuration": [
{
"title": "Markdown Math",
"properties": {
"markdown.math.enabled": {
"type": "boolean",
"default": true,
"description": "%config.markdown.math.enabled%"
}
}
}
]
},
"scripts": {
"compile": "npm run build-notebook",
"watch": "npm run build-notebook",
"build-notebook": "node ./esbuild"
},
"dependencies": {
"@vscode/markdown-it-katex": "^1.0.0"
},
"devDependencies": {
"@types/markdown-it": "^0.0.0",
"@types/vscode-notebook-renderer": "^1.60.0"
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
|
extensions/markdown-math/package.json
| 1 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.0008262622868642211,
0.0002844615082722157,
0.000166977260960266,
0.0002556032850407064,
0.00018045035540126264
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t\t\t\"include\": \"text.html.markdown.math#math\"\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t]\n",
"\t\t\t\t},\n",
"\t\t\t\t\"3\": {\n",
"\t\t\t\t\t\"name\": \"punctuation.definition.math.begin.markdown\"\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t},\n",
"\t\t\"math_inline_double\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\"name\": \"punctuation.definition.math.end.markdown\"\n"
],
"file_path": "extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json",
"type": "replace",
"edit_start_line_idx": 31
}
|
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
|
extensions/lua/yarn.lock
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.0001705018657958135,
0.0001705018657958135,
0.0001705018657958135,
0.0001705018657958135,
0
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t\t\t\"include\": \"text.html.markdown.math#math\"\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t]\n",
"\t\t\t\t},\n",
"\t\t\t\t\"3\": {\n",
"\t\t\t\t\t\"name\": \"punctuation.definition.math.begin.markdown\"\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t},\n",
"\t\t\"math_inline_double\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\"name\": \"punctuation.definition.math.end.markdown\"\n"
],
"file_path": "extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json",
"type": "replace",
"edit_start_line_idx": 31
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITextMateService } from 'vs/workbench/services/textMate/browser/textMate';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { AbstractTextMateService } from 'vs/workbench/services/textMate/browser/abstractTextMateService';
import { FileAccess } from 'vs/base/common/network';
export class TextMateService extends AbstractTextMateService {
protected async _loadVSCodeOnigurumWASM(): Promise<Response | ArrayBuffer> {
const response = await fetch(FileAccess.asBrowserUri('vscode-oniguruma/../onig.wasm').toString(true));
// Using the response directly only works if the server sets the MIME type 'application/wasm'.
// Otherwise, a TypeError is thrown when using the streaming compiler.
// We therefore use the non-streaming compiler :(.
return await response.arrayBuffer();
}
}
registerSingleton(ITextMateService, TextMateService, InstantiationType.Eager);
|
src/vs/workbench/services/textMate/browser/browserTextMateService.ts
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.000173552252817899,
0.00017074048810172826,
0.00016797819989733398,
0.00017069104069378227,
0.000002275866336276522
] |
{
"id": 1,
"code_window": [
"\t\t\t\t\t\t\t\"include\": \"text.html.markdown.math#math\"\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t]\n",
"\t\t\t\t},\n",
"\t\t\t\t\"3\": {\n",
"\t\t\t\t\t\"name\": \"punctuation.definition.math.begin.markdown\"\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t},\n",
"\t\t\"math_inline_double\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\"name\": \"punctuation.definition.math.end.markdown\"\n"
],
"file_path": "extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json",
"type": "replace",
"edit_start_line_idx": 31
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { distinct } from 'vs/base/common/arrays';
import { IStringDictionary } from 'vs/base/common/collections';
import { JSONVisitor, parse, visit } from 'vs/base/common/json';
import { applyEdits, setProperty, withFormatting } from 'vs/base/common/jsonEdit';
import { Edit, FormattingOptions, getEOL } from 'vs/base/common/jsonFormatter';
import * as objects from 'vs/base/common/objects';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import * as contentUtil from 'vs/platform/userDataSync/common/content';
import { getDisallowedIgnoredSettings, IConflictSetting } from 'vs/platform/userDataSync/common/userDataSync';
export interface IMergeResult {
localContent: string | null;
remoteContent: string | null;
hasConflicts: boolean;
conflictsSettings: IConflictSetting[];
}
export function getIgnoredSettings(defaultIgnoredSettings: string[], configurationService: IConfigurationService, settingsContent?: string): string[] {
let value: ReadonlyArray<string> = [];
if (settingsContent) {
value = getIgnoredSettingsFromContent(settingsContent);
} else {
value = getIgnoredSettingsFromConfig(configurationService);
}
const added: string[] = [], removed: string[] = [...getDisallowedIgnoredSettings()];
if (Array.isArray(value)) {
for (const key of value) {
if (key.startsWith('-')) {
removed.push(key.substring(1));
} else {
added.push(key);
}
}
}
return distinct([...defaultIgnoredSettings, ...added,].filter(setting => removed.indexOf(setting) === -1));
}
function getIgnoredSettingsFromConfig(configurationService: IConfigurationService): ReadonlyArray<string> {
let userValue = configurationService.inspect<string[]>('settingsSync.ignoredSettings').userValue;
if (userValue !== undefined) {
return userValue;
}
userValue = configurationService.inspect<string[]>('sync.ignoredSettings').userValue;
if (userValue !== undefined) {
return userValue;
}
return configurationService.getValue<string[]>('settingsSync.ignoredSettings') || [];
}
function getIgnoredSettingsFromContent(settingsContent: string): string[] {
const parsed = parse(settingsContent);
return parsed ? parsed['settingsSync.ignoredSettings'] || parsed['sync.ignoredSettings'] || [] : [];
}
export function removeComments(content: string, formattingOptions: FormattingOptions): string {
const source = parse(content) || {};
let result = '{}';
for (const key of Object.keys(source)) {
const edits = setProperty(result, [key], source[key], formattingOptions);
result = applyEdits(result, edits);
}
return result;
}
export function updateIgnoredSettings(targetContent: string, sourceContent: string, ignoredSettings: string[], formattingOptions: FormattingOptions): string {
if (ignoredSettings.length) {
const sourceTree = parseSettings(sourceContent);
const source = parse(sourceContent) || {};
const target = parse(targetContent);
if (!target) {
return targetContent;
}
const settingsToAdd: INode[] = [];
for (const key of ignoredSettings) {
const sourceValue = source[key];
const targetValue = target[key];
// Remove in target
if (sourceValue === undefined) {
targetContent = contentUtil.edit(targetContent, [key], undefined, formattingOptions);
}
// Update in target
else if (targetValue !== undefined) {
targetContent = contentUtil.edit(targetContent, [key], sourceValue, formattingOptions);
}
else {
settingsToAdd.push(findSettingNode(key, sourceTree)!);
}
}
settingsToAdd.sort((a, b) => a.startOffset - b.startOffset);
settingsToAdd.forEach(s => targetContent = addSetting(s.setting!.key, sourceContent, targetContent, formattingOptions));
}
return targetContent;
}
export function merge(originalLocalContent: string, originalRemoteContent: string, baseContent: string | null, ignoredSettings: string[], resolvedConflicts: { key: string; value: any | undefined }[], formattingOptions: FormattingOptions): IMergeResult {
const localContentWithoutIgnoredSettings = updateIgnoredSettings(originalLocalContent, originalRemoteContent, ignoredSettings, formattingOptions);
const localForwarded = baseContent !== localContentWithoutIgnoredSettings;
const remoteForwarded = baseContent !== originalRemoteContent;
/* no changes */
if (!localForwarded && !remoteForwarded) {
return { conflictsSettings: [], localContent: null, remoteContent: null, hasConflicts: false };
}
/* local has changed and remote has not */
if (localForwarded && !remoteForwarded) {
return { conflictsSettings: [], localContent: null, remoteContent: localContentWithoutIgnoredSettings, hasConflicts: false };
}
/* remote has changed and local has not */
if (remoteForwarded && !localForwarded) {
return { conflictsSettings: [], localContent: updateIgnoredSettings(originalRemoteContent, originalLocalContent, ignoredSettings, formattingOptions), remoteContent: null, hasConflicts: false };
}
/* local is empty and not synced before */
if (baseContent === null && isEmpty(originalLocalContent)) {
const localContent = areSame(originalLocalContent, originalRemoteContent, ignoredSettings) ? null : updateIgnoredSettings(originalRemoteContent, originalLocalContent, ignoredSettings, formattingOptions);
return { conflictsSettings: [], localContent, remoteContent: null, hasConflicts: false };
}
/* remote and local has changed */
let localContent = originalLocalContent;
let remoteContent = originalRemoteContent;
const local = parse(originalLocalContent);
const remote = parse(originalRemoteContent);
const base = baseContent ? parse(baseContent) : null;
const ignored = ignoredSettings.reduce((set, key) => { set.add(key); return set; }, new Set<string>());
const localToRemote = compare(local, remote, ignored);
const baseToLocal = compare(base, local, ignored);
const baseToRemote = compare(base, remote, ignored);
const conflicts: Map<string, IConflictSetting> = new Map<string, IConflictSetting>();
const handledConflicts: Set<string> = new Set<string>();
const handleConflict = (conflictKey: string): void => {
handledConflicts.add(conflictKey);
const resolvedConflict = resolvedConflicts.filter(({ key }) => key === conflictKey)[0];
if (resolvedConflict) {
localContent = contentUtil.edit(localContent, [conflictKey], resolvedConflict.value, formattingOptions);
remoteContent = contentUtil.edit(remoteContent, [conflictKey], resolvedConflict.value, formattingOptions);
} else {
conflicts.set(conflictKey, { key: conflictKey, localValue: local[conflictKey], remoteValue: remote[conflictKey] });
}
};
// Removed settings in Local
for (const key of baseToLocal.removed.values()) {
// Conflict - Got updated in remote.
if (baseToRemote.updated.has(key)) {
handleConflict(key);
}
// Also remove in remote
else {
remoteContent = contentUtil.edit(remoteContent, [key], undefined, formattingOptions);
}
}
// Removed settings in Remote
for (const key of baseToRemote.removed.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Conflict - Got updated in local
if (baseToLocal.updated.has(key)) {
handleConflict(key);
}
// Also remove in locals
else {
localContent = contentUtil.edit(localContent, [key], undefined, formattingOptions);
}
}
// Updated settings in Local
for (const key of baseToLocal.updated.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Got updated in remote
if (baseToRemote.updated.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
handleConflict(key);
}
} else {
remoteContent = contentUtil.edit(remoteContent, [key], local[key], formattingOptions);
}
}
// Updated settings in Remote
for (const key of baseToRemote.updated.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Got updated in local
if (baseToLocal.updated.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
handleConflict(key);
}
} else {
localContent = contentUtil.edit(localContent, [key], remote[key], formattingOptions);
}
}
// Added settings in Local
for (const key of baseToLocal.added.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Got added in remote
if (baseToRemote.added.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
handleConflict(key);
}
} else {
remoteContent = addSetting(key, localContent, remoteContent, formattingOptions);
}
}
// Added settings in remote
for (const key of baseToRemote.added.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Got added in local
if (baseToLocal.added.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
handleConflict(key);
}
} else {
localContent = addSetting(key, remoteContent, localContent, formattingOptions);
}
}
const hasConflicts = conflicts.size > 0 || !areSame(localContent, remoteContent, ignoredSettings);
const hasLocalChanged = hasConflicts || !areSame(localContent, originalLocalContent, []);
const hasRemoteChanged = hasConflicts || !areSame(remoteContent, originalRemoteContent, []);
return { localContent: hasLocalChanged ? localContent : null, remoteContent: hasRemoteChanged ? remoteContent : null, conflictsSettings: [...conflicts.values()], hasConflicts };
}
function areSame(localContent: string, remoteContent: string, ignoredSettings: string[]): boolean {
if (localContent === remoteContent) {
return true;
}
const local = parse(localContent);
const remote = parse(remoteContent);
const ignored = ignoredSettings.reduce((set, key) => { set.add(key); return set; }, new Set<string>());
const localTree = parseSettings(localContent).filter(node => !(node.setting && ignored.has(node.setting.key)));
const remoteTree = parseSettings(remoteContent).filter(node => !(node.setting && ignored.has(node.setting.key)));
if (localTree.length !== remoteTree.length) {
return false;
}
for (let index = 0; index < localTree.length; index++) {
const localNode = localTree[index];
const remoteNode = remoteTree[index];
if (localNode.setting && remoteNode.setting) {
if (localNode.setting.key !== remoteNode.setting.key) {
return false;
}
if (!objects.equals(local[localNode.setting.key], remote[localNode.setting.key])) {
return false;
}
} else if (!localNode.setting && !remoteNode.setting) {
if (localNode.value !== remoteNode.value) {
return false;
}
} else {
return false;
}
}
return true;
}
export function isEmpty(content: string): boolean {
if (content) {
const nodes = parseSettings(content);
return nodes.length === 0;
}
return true;
}
function compare(from: IStringDictionary<any> | null, to: IStringDictionary<any>, ignored: Set<string>): { added: Set<string>; removed: Set<string>; updated: Set<string> } {
const fromKeys = from ? Object.keys(from).filter(key => !ignored.has(key)) : [];
const toKeys = Object.keys(to).filter(key => !ignored.has(key));
const added = toKeys.filter(key => fromKeys.indexOf(key) === -1).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
const removed = fromKeys.filter(key => toKeys.indexOf(key) === -1).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
const updated: Set<string> = new Set<string>();
if (from) {
for (const key of fromKeys) {
if (removed.has(key)) {
continue;
}
const value1 = from[key];
const value2 = to[key];
if (!objects.equals(value1, value2)) {
updated.add(key);
}
}
}
return { added, removed, updated };
}
export function addSetting(key: string, sourceContent: string, targetContent: string, formattingOptions: FormattingOptions): string {
const source = parse(sourceContent);
const sourceTree = parseSettings(sourceContent);
const targetTree = parseSettings(targetContent);
const insertLocation = getInsertLocation(key, sourceTree, targetTree);
return insertAtLocation(targetContent, key, source[key], insertLocation, targetTree, formattingOptions);
}
interface InsertLocation {
index: number;
insertAfter: boolean;
}
function getInsertLocation(key: string, sourceTree: INode[], targetTree: INode[]): InsertLocation {
const sourceNodeIndex = sourceTree.findIndex(node => node.setting?.key === key);
const sourcePreviousNode: INode = sourceTree[sourceNodeIndex - 1];
if (sourcePreviousNode) {
/*
Previous node in source is a setting.
Find the same setting in the target.
Insert it after that setting
*/
if (sourcePreviousNode.setting) {
const targetPreviousSetting = findSettingNode(sourcePreviousNode.setting.key, targetTree);
if (targetPreviousSetting) {
/* Insert after target's previous setting */
return { index: targetTree.indexOf(targetPreviousSetting), insertAfter: true };
}
}
/* Previous node in source is a comment */
else {
const sourcePreviousSettingNode = findPreviousSettingNode(sourceNodeIndex, sourceTree);
/*
Source has a setting defined before the setting to be added.
Find the same previous setting in the target.
If found, insert before its next setting so that comments are retrieved.
Otherwise, insert at the end.
*/
if (sourcePreviousSettingNode) {
const targetPreviousSetting = findSettingNode(sourcePreviousSettingNode.setting!.key, targetTree);
if (targetPreviousSetting) {
const targetNextSetting = findNextSettingNode(targetTree.indexOf(targetPreviousSetting), targetTree);
const sourceCommentNodes = findNodesBetween(sourceTree, sourcePreviousSettingNode, sourceTree[sourceNodeIndex]);
if (targetNextSetting) {
const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetNextSetting);
const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes, targetCommentNodes);
if (targetCommentNode) {
return { index: targetTree.indexOf(targetCommentNode), insertAfter: true }; /* Insert after comment */
} else {
return { index: targetTree.indexOf(targetNextSetting), insertAfter: false }; /* Insert before target next setting */
}
} else {
const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetTree[targetTree.length - 1]);
const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes, targetCommentNodes);
if (targetCommentNode) {
return { index: targetTree.indexOf(targetCommentNode), insertAfter: true }; /* Insert after comment */
} else {
return { index: targetTree.length - 1, insertAfter: true }; /* Insert at the end */
}
}
}
}
}
const sourceNextNode = sourceTree[sourceNodeIndex + 1];
if (sourceNextNode) {
/*
Next node in source is a setting.
Find the same setting in the target.
Insert it before that setting
*/
if (sourceNextNode.setting) {
const targetNextSetting = findSettingNode(sourceNextNode.setting.key, targetTree);
if (targetNextSetting) {
/* Insert before target's next setting */
return { index: targetTree.indexOf(targetNextSetting), insertAfter: false };
}
}
/* Next node in source is a comment */
else {
const sourceNextSettingNode = findNextSettingNode(sourceNodeIndex, sourceTree);
/*
Source has a setting defined after the setting to be added.
Find the same next setting in the target.
If found, insert after its previous setting so that comments are retrieved.
Otherwise, insert at the beginning.
*/
if (sourceNextSettingNode) {
const targetNextSetting = findSettingNode(sourceNextSettingNode.setting!.key, targetTree);
if (targetNextSetting) {
const targetPreviousSetting = findPreviousSettingNode(targetTree.indexOf(targetNextSetting), targetTree);
const sourceCommentNodes = findNodesBetween(sourceTree, sourceTree[sourceNodeIndex], sourceNextSettingNode);
if (targetPreviousSetting) {
const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetNextSetting);
const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes.reverse(), targetCommentNodes.reverse());
if (targetCommentNode) {
return { index: targetTree.indexOf(targetCommentNode), insertAfter: false }; /* Insert before comment */
} else {
return { index: targetTree.indexOf(targetPreviousSetting), insertAfter: true }; /* Insert after target previous setting */
}
} else {
const targetCommentNodes = findNodesBetween(targetTree, targetTree[0], targetNextSetting);
const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes.reverse(), targetCommentNodes.reverse());
if (targetCommentNode) {
return { index: targetTree.indexOf(targetCommentNode), insertAfter: false }; /* Insert before comment */
} else {
return { index: 0, insertAfter: false }; /* Insert at the beginning */
}
}
}
}
}
}
}
/* Insert at the end */
return { index: targetTree.length - 1, insertAfter: true };
}
function insertAtLocation(content: string, key: string, value: any, location: InsertLocation, tree: INode[], formattingOptions: FormattingOptions): string {
let edits: Edit[];
/* Insert at the end */
if (location.index === -1) {
edits = setProperty(content, [key], value, formattingOptions);
} else {
edits = getEditToInsertAtLocation(content, key, value, location, tree, formattingOptions).map(edit => withFormatting(content, edit, formattingOptions)[0]);
}
return applyEdits(content, edits);
}
function getEditToInsertAtLocation(content: string, key: string, value: any, location: InsertLocation, tree: INode[], formattingOptions: FormattingOptions): Edit[] {
const newProperty = `${JSON.stringify(key)}: ${JSON.stringify(value)}`;
const eol = getEOL(formattingOptions, content);
const node = tree[location.index];
if (location.insertAfter) {
const edits: Edit[] = [];
/* Insert after a setting */
if (node.setting) {
edits.push({ offset: node.endOffset, length: 0, content: ',' + newProperty });
}
/* Insert after a comment */
else {
const nextSettingNode = findNextSettingNode(location.index, tree);
const previousSettingNode = findPreviousSettingNode(location.index, tree);
const previousSettingCommaOffset = previousSettingNode?.setting?.commaOffset;
/* If there is a previous setting and it does not has comma then add it */
if (previousSettingNode && previousSettingCommaOffset === undefined) {
edits.push({ offset: previousSettingNode.endOffset, length: 0, content: ',' });
}
const isPreviouisSettingIncludesComment = previousSettingCommaOffset !== undefined && previousSettingCommaOffset > node.endOffset;
edits.push({
offset: isPreviouisSettingIncludesComment ? previousSettingCommaOffset! + 1 : node.endOffset,
length: 0,
content: nextSettingNode ? eol + newProperty + ',' : eol + newProperty
});
}
return edits;
}
else {
/* Insert before a setting */
if (node.setting) {
return [{ offset: node.startOffset, length: 0, content: newProperty + ',' }];
}
/* Insert before a comment */
const content = (tree[location.index - 1] && !tree[location.index - 1].setting /* previous node is comment */ ? eol : '')
+ newProperty
+ (findNextSettingNode(location.index, tree) ? ',' : '')
+ eol;
return [{ offset: node.startOffset, length: 0, content }];
}
}
function findSettingNode(key: string, tree: INode[]): INode | undefined {
return tree.filter(node => node.setting?.key === key)[0];
}
function findPreviousSettingNode(index: number, tree: INode[]): INode | undefined {
for (let i = index - 1; i >= 0; i--) {
if (tree[i].setting) {
return tree[i];
}
}
return undefined;
}
function findNextSettingNode(index: number, tree: INode[]): INode | undefined {
for (let i = index + 1; i < tree.length; i++) {
if (tree[i].setting) {
return tree[i];
}
}
return undefined;
}
function findNodesBetween(nodes: INode[], from: INode, till: INode): INode[] {
const fromIndex = nodes.indexOf(from);
const tillIndex = nodes.indexOf(till);
return nodes.filter((node, index) => fromIndex < index && index < tillIndex);
}
function findLastMatchingTargetCommentNode(sourceComments: INode[], targetComments: INode[]): INode | undefined {
if (sourceComments.length && targetComments.length) {
let index = 0;
for (; index < targetComments.length && index < sourceComments.length; index++) {
if (sourceComments[index].value !== targetComments[index].value) {
return targetComments[index - 1];
}
}
return targetComments[index - 1];
}
return undefined;
}
interface INode {
readonly startOffset: number;
readonly endOffset: number;
readonly value: string;
readonly setting?: {
readonly key: string;
readonly commaOffset: number | undefined;
};
readonly comment?: string;
}
function parseSettings(content: string): INode[] {
const nodes: INode[] = [];
let hierarchyLevel = -1;
let startOffset: number;
let key: string;
const visitor: JSONVisitor = {
onObjectBegin: (offset: number) => {
hierarchyLevel++;
},
onObjectProperty: (name: string, offset: number, length: number) => {
if (hierarchyLevel === 0) {
// this is setting key
startOffset = offset;
key = name;
}
},
onObjectEnd: (offset: number, length: number) => {
hierarchyLevel--;
if (hierarchyLevel === 0) {
nodes.push({
startOffset,
endOffset: offset + length,
value: content.substring(startOffset, offset + length),
setting: {
key,
commaOffset: undefined
}
});
}
},
onArrayBegin: (offset: number, length: number) => {
hierarchyLevel++;
},
onArrayEnd: (offset: number, length: number) => {
hierarchyLevel--;
if (hierarchyLevel === 0) {
nodes.push({
startOffset,
endOffset: offset + length,
value: content.substring(startOffset, offset + length),
setting: {
key,
commaOffset: undefined
}
});
}
},
onLiteralValue: (value: any, offset: number, length: number) => {
if (hierarchyLevel === 0) {
nodes.push({
startOffset,
endOffset: offset + length,
value: content.substring(startOffset, offset + length),
setting: {
key,
commaOffset: undefined
}
});
}
},
onSeparator: (sep: string, offset: number, length: number) => {
if (hierarchyLevel === 0) {
if (sep === ',') {
let index = nodes.length - 1;
for (; index >= 0; index--) {
if (nodes[index].setting) {
break;
}
}
const node = nodes[index];
if (node) {
nodes.splice(index, 1, {
startOffset: node.startOffset,
endOffset: node.endOffset,
value: node.value,
setting: {
key: node.setting!.key,
commaOffset: offset
}
});
}
}
}
},
onComment: (offset: number, length: number) => {
if (hierarchyLevel === 0) {
nodes.push({
startOffset: offset,
endOffset: offset + length,
value: content.substring(offset, offset + length),
});
}
}
};
visit(content, visitor);
return nodes;
}
|
src/vs/platform/userDataSync/common/settingsMerge.ts
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.00017452870088163763,
0.00017125013982877135,
0.00016308482736349106,
0.0001721204025670886,
0.000002316271547897486
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\t\t\t\"include\": \"text.html.markdown.math#math\"\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t]\n",
"\t\t\t\t},\n",
"\t\t\t\t\"3\": {\n",
"\t\t\t\t\t\"name\": \"punctuation.definition.math.begin.markdown\"\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t},\n",
"\t\t\"math_inline_block\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\"name\": \"punctuation.definition.math.end.markdown\"\n"
],
"file_path": "extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json",
"type": "replace",
"edit_start_line_idx": 51
}
|
{
"fileTypes": [],
"injectionSelector": "L:meta.paragraph.markdown - (comment, string, markup.math.inline.markdown, markup.fenced_code.block.markdown)",
"patterns": [
{
"include": "#math_inline_double"
},
{
"include": "#math_inline_single"
},
{
"include": "#math_inline_block"
}
],
"repository": {
"math_inline_single": {
"name": "markup.math.inline.markdown",
"match": "(?<=\\s|\\W|^)(?<!\\$)(\\$)(.+?)(\\$)(?!\\$)(?=\\s|\\W|$)",
"captures": {
"1": {
"name": "punctuation.definition.math.begin.markdown"
},
"2": {
"name": "meta.embedded.math.markdown",
"patterns": [
{
"include": "text.html.markdown.math#math"
}
]
},
"3": {
"name": "punctuation.definition.math.begin.markdown"
}
}
},
"math_inline_double": {
"name": "markup.math.inline.markdown",
"match": "(?<=\\s|\\W|^)(?<!\\$)(\\$\\$)(.+?)(\\$\\$)(?!\\$)(?=\\s|\\W|$)",
"captures": {
"1": {
"name": "punctuation.definition.math.begin.markdown"
},
"2": {
"name": "meta.embedded.math.markdown",
"patterns": [
{
"include": "text.html.markdown.math#math"
}
]
},
"3": {
"name": "punctuation.definition.math.begin.markdown"
}
}
},
"math_inline_block": {
"name": "markup.math.inline.markdown",
"contentName": "meta.embedded.math.markdown",
"begin": "(?<=\\s|^)(\\${2})",
"beginCaptures": {
"2": {
"name": "punctuation.definition.math.begin.markdown"
}
},
"end": "(\\${2})(?=\\s|$)",
"endCaptures": {
"2": {
"name": "punctuation.definition.math.end.markdown"
}
},
"patterns": [
{
"include": "text.html.markdown.math#math"
}
]
}
},
"scopeName": "markdown.math.inline"
}
|
extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json
| 1 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.5369300246238708,
0.07877778261899948,
0.0006925096386112273,
0.017361659556627274,
0.17342615127563477
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\t\t\t\"include\": \"text.html.markdown.math#math\"\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t]\n",
"\t\t\t\t},\n",
"\t\t\t\t\"3\": {\n",
"\t\t\t\t\t\"name\": \"punctuation.definition.math.begin.markdown\"\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t},\n",
"\t\t\"math_inline_block\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\"name\": \"punctuation.definition.math.end.markdown\"\n"
],
"file_path": "extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json",
"type": "replace",
"edit_start_line_idx": 51
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { WebContents } from 'electron';
import { Event } from 'vs/base/common/event';
import { IProcessEnvironment } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ICodeWindow } from 'vs/platform/window/electron-main/window';
import { IOpenEmptyWindowOptions, IWindowOpenable } from 'vs/platform/window/common/window';
export const IWindowsMainService = createDecorator<IWindowsMainService>('windowsMainService');
export interface IWindowsMainService {
readonly _serviceBrand: undefined;
readonly onDidChangeWindowsCount: Event<IWindowsCountChangedEvent>;
readonly onDidOpenWindow: Event<ICodeWindow>;
readonly onDidSignalReadyWindow: Event<ICodeWindow>;
readonly onDidTriggerSystemContextMenu: Event<{ window: ICodeWindow; x: number; y: number }>;
readonly onDidDestroyWindow: Event<ICodeWindow>;
open(openConfig: IOpenConfiguration): Promise<ICodeWindow[]>;
openEmptyWindow(openConfig: IOpenEmptyConfiguration, options?: IOpenEmptyWindowOptions): Promise<ICodeWindow[]>;
openExtensionDevelopmentHostWindow(extensionDevelopmentPath: string[], openConfig: IOpenConfiguration): Promise<ICodeWindow[]>;
openExistingWindow(window: ICodeWindow, openConfig: IOpenConfiguration): void;
sendToFocused(channel: string, ...args: any[]): void;
sendToAll(channel: string, payload?: any, windowIdsToIgnore?: number[]): void;
getWindows(): ICodeWindow[];
getWindowCount(): number;
getFocusedWindow(): ICodeWindow | undefined;
getLastActiveWindow(): ICodeWindow | undefined;
getWindowById(windowId: number): ICodeWindow | undefined;
getWindowByWebContents(webContents: WebContents): ICodeWindow | undefined;
}
export interface IWindowsCountChangedEvent {
readonly oldCount: number;
readonly newCount: number;
}
export const enum OpenContext {
// opening when running from the command line
CLI,
// macOS only: opening from the dock (also when opening files to a running instance from desktop)
DOCK,
// opening from the main application window
MENU,
// opening from a file or folder dialog
DIALOG,
// opening from the OS's UI
DESKTOP,
// opening through the API
API
}
export interface IBaseOpenConfiguration {
readonly context: OpenContext;
readonly contextWindowId?: number;
}
export interface IOpenConfiguration extends IBaseOpenConfiguration {
readonly cli: NativeParsedArgs;
readonly userEnv?: IProcessEnvironment;
readonly urisToOpen?: IWindowOpenable[];
readonly waitMarkerFileURI?: URI;
readonly preferNewWindow?: boolean;
readonly forceNewWindow?: boolean;
readonly forceNewTabbedWindow?: boolean;
readonly forceReuseWindow?: boolean;
readonly forceEmpty?: boolean;
readonly diffMode?: boolean;
readonly mergeMode?: boolean;
addMode?: boolean;
readonly gotoLineMode?: boolean;
readonly initialStartup?: boolean;
readonly noRecentEntry?: boolean;
/**
* The remote authority to use when windows are opened with either
* - no workspace (empty window)
* - a workspace that is neither `file://` nor `vscode-remote://`
*/
readonly remoteAuthority?: string;
readonly forceProfile?: string;
readonly forceTempProfile?: boolean;
}
export interface IOpenEmptyConfiguration extends IBaseOpenConfiguration { }
|
src/vs/platform/windows/electron-main/windows.ts
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.00017400925571564585,
0.0001702986191958189,
0.00016707424947526306,
0.00016998905630316585,
0.0000021993876089254627
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\t\t\t\"include\": \"text.html.markdown.math#math\"\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t]\n",
"\t\t\t\t},\n",
"\t\t\t\t\"3\": {\n",
"\t\t\t\t\t\"name\": \"punctuation.definition.math.begin.markdown\"\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t},\n",
"\t\t\"math_inline_block\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\"name\": \"punctuation.definition.math.end.markdown\"\n"
],
"file_path": "extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json",
"type": "replace",
"edit_start_line_idx": 51
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
/** @typedef {import('webpack').Configuration} WebpackConfig **/
'use strict';
const path = require('path');
const fs = require('fs');
const merge = require('merge-options');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { NLSBundlePlugin } = require('vscode-nls-dev/lib/webpack-bundler');
const { DefinePlugin, optimize } = require('webpack');
const tsLoaderOptions = {
compilerOptions: {
'sourceMap': true,
},
onlyCompileBundledFiles: true,
};
function withNodeDefaults(/**@type WebpackConfig*/extConfig) {
/** @type WebpackConfig */
const defaultConfig = {
mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production')
target: 'node', // extensions run in a node context
node: {
__dirname: false // leave the __dirname-behaviour intact
},
resolve: {
mainFields: ['module', 'main'],
extensions: ['.ts', '.js'] // support ts-files and js-files
},
module: {
rules: [{
test: /\.ts$/,
exclude: /node_modules/,
use: [{
// vscode-nls-dev loader:
// * rewrite nls-calls
loader: 'vscode-nls-dev/lib/webpack-loader',
options: {
base: path.join(extConfig.context, 'src')
}
}, {
// configure TypeScript loader:
// * enable sources maps for end-to-end source maps
loader: 'ts-loader',
options: tsLoaderOptions
}, {
loader: path.resolve(__dirname, 'mangle-loader.js'),
options: {
configFile: path.join(extConfig.context, 'tsconfig.json')
},
},]
}]
},
externals: {
'vscode': 'commonjs vscode', // ignored because it doesn't exist,
'applicationinsights-native-metrics': 'commonjs applicationinsights-native-metrics', // ignored because we don't ship native module
'@opentelemetry/tracing': 'commonjs @opentelemetry/tracing', // ignored because we don't ship this module
'@opentelemetry/instrumentation': 'commonjs @opentelemetry/instrumentation', // ignored because we don't ship this module
'@azure/opentelemetry-instrumentation-azure-sdk': 'commonjs @azure/opentelemetry-instrumentation-azure-sdk', // ignored because we don't ship this module
},
output: {
// all output goes into `dist`.
// packaging depends on that and this must always be like it
filename: '[name].js',
path: path.join(extConfig.context, 'dist'),
libraryTarget: 'commonjs',
},
// yes, really source maps
devtool: 'source-map',
plugins: nodePlugins(extConfig.context),
};
return merge(defaultConfig, extConfig);
}
/**
*
* @param {string} context
*/
function nodePlugins(context) {
// Need to find the top-most `package.json` file
const folderName = path.relative(__dirname, context).split(/[\\\/]/)[0];
const pkgPath = path.join(__dirname, folderName, 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const id = `${pkg.publisher}.${pkg.name}`;
return [
new CopyWebpackPlugin({
patterns: [
{ from: 'src', to: '.', globOptions: { ignore: ['**/test/**', '**/*.ts'] }, noErrorOnMissing: true }
]
}),
new NLSBundlePlugin(id)
];
}
/**
* @typedef {{
* configFile?: string
* }} AdditionalBrowserConfig
*/
function withBrowserDefaults(/**@type WebpackConfig*/extConfig, /** @type AdditionalBrowserConfig */ additionalOptions = {}) {
/** @type WebpackConfig */
const defaultConfig = {
mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production')
target: 'webworker', // extensions run in a webworker context
resolve: {
mainFields: ['browser', 'module', 'main'],
extensions: ['.ts', '.js'], // support ts-files and js-files
fallback: {
'path': require.resolve('path-browserify'),
'util': require.resolve('util')
}
},
module: {
rules: [{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
// configure TypeScript loader:
// * enable sources maps for end-to-end source maps
loader: 'ts-loader',
options: {
...tsLoaderOptions,
...(additionalOptions ? {} : { configFile: additionalOptions.configFile }),
}
},
{
loader: path.resolve(__dirname, 'mangle-loader.js'),
options: {
configFile: path.join(extConfig.context, additionalOptions?.configFile ?? 'tsconfig.json')
},
},
]
}]
},
externals: {
'vscode': 'commonjs vscode', // ignored because it doesn't exist,
'applicationinsights-native-metrics': 'commonjs applicationinsights-native-metrics', // ignored because we don't ship native module
'@opentelemetry/tracing': 'commonjs @opentelemetry/tracing', // ignored because we don't ship this module
'@opentelemetry/instrumentation': 'commonjs @opentelemetry/instrumentation', // ignored because we don't ship this module
'@azure/opentelemetry-instrumentation-azure-sdk': 'commonjs @azure/opentelemetry-instrumentation-azure-sdk', // ignored because we don't ship this module
},
performance: {
hints: false
},
output: {
// all output goes into `dist`.
// packaging depends on that and this must always be like it
filename: '[name].js',
path: path.join(extConfig.context, 'dist', 'browser'),
libraryTarget: 'commonjs',
},
// yes, really source maps
devtool: 'source-map',
plugins: browserPlugins(extConfig.context)
};
return merge(defaultConfig, extConfig);
}
/**
*
* @param {string} context
*/
function browserPlugins(context) {
// Need to find the top-most `package.json` file
// const folderName = path.relative(__dirname, context).split(/[\\\/]/)[0];
// const pkgPath = path.join(__dirname, folderName, 'package.json');
// const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
// const id = `${pkg.publisher}.${pkg.name}`;
return [
new optimize.LimitChunkCountPlugin({
maxChunks: 1
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'src', to: '.', globOptions: { ignore: ['**/test/**', '**/*.ts'] }, noErrorOnMissing: true }
]
}),
new DefinePlugin({
'process.platform': JSON.stringify('web'),
'process.env': JSON.stringify({}),
'process.env.BROWSER_ENV': JSON.stringify('true')
}),
// TODO: bring this back once vscode-nls-dev supports browser
// new NLSBundlePlugin(id)
];
}
module.exports = withNodeDefaults;
module.exports.node = withNodeDefaults;
module.exports.browser = withBrowserDefaults;
module.exports.nodePlugins = nodePlugins;
module.exports.browserPlugins = browserPlugins;
|
extensions/shared.webpack.config.js
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.0001764959015417844,
0.00017169024795293808,
0.000166206038556993,
0.000171748484717682,
0.0000022716524199495325
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\t\t\t\"include\": \"text.html.markdown.math#math\"\n",
"\t\t\t\t\t\t}\n",
"\t\t\t\t\t]\n",
"\t\t\t\t},\n",
"\t\t\t\t\"3\": {\n",
"\t\t\t\t\t\"name\": \"punctuation.definition.math.begin.markdown\"\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t},\n",
"\t\t\"math_inline_block\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\t\"name\": \"punctuation.definition.math.end.markdown\"\n"
],
"file_path": "extensions/markdown-math/syntaxes/md-math-inline.tmLanguage.json",
"type": "replace",
"edit_start_line_idx": 51
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { compareIgnoreCase, regExpLeadsToEndlessLoop } from 'vs/base/common/strings';
import { clearPlatformLanguageAssociations, getLanguageIds, registerPlatformLanguageAssociation } from 'vs/editor/common/services/languagesAssociations';
import { URI } from 'vs/base/common/uri';
import { ILanguageIdCodec } from 'vs/editor/common/languages';
import { LanguageId } from 'vs/editor/common/encodedTokenAttributes';
import { ModesRegistry, PLAINTEXT_LANGUAGE_ID } from 'vs/editor/common/languages/modesRegistry';
import { ILanguageExtensionPoint, ILanguageNameIdPair, ILanguageIcon } from 'vs/editor/common/languages/language';
import { Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { Registry } from 'vs/platform/registry/common/platform';
const hasOwnProperty = Object.prototype.hasOwnProperty;
const NULL_LANGUAGE_ID = 'vs.editor.nullLanguage';
interface IResolvedLanguage {
identifier: string;
name: string | null;
mimetypes: string[];
aliases: string[];
extensions: string[];
filenames: string[];
configurationFiles: URI[];
icons: ILanguageIcon[];
}
export class LanguageIdCodec implements ILanguageIdCodec {
private _nextLanguageId: number;
private readonly _languageIdToLanguage: string[] = [];
private readonly _languageToLanguageId = new Map<string, number>();
constructor() {
this._register(NULL_LANGUAGE_ID, LanguageId.Null);
this._register(PLAINTEXT_LANGUAGE_ID, LanguageId.PlainText);
this._nextLanguageId = 2;
}
private _register(language: string, languageId: LanguageId): void {
this._languageIdToLanguage[languageId] = language;
this._languageToLanguageId.set(language, languageId);
}
public register(language: string): void {
if (this._languageToLanguageId.has(language)) {
return;
}
const languageId = this._nextLanguageId++;
this._register(language, languageId);
}
public encodeLanguageId(languageId: string): LanguageId {
return this._languageToLanguageId.get(languageId) || LanguageId.Null;
}
public decodeLanguageId(languageId: LanguageId): string {
return this._languageIdToLanguage[languageId] || NULL_LANGUAGE_ID;
}
}
export class LanguagesRegistry extends Disposable {
static instanceCount = 0;
private readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidChange: Event<void> = this._onDidChange.event;
private readonly _warnOnOverwrite: boolean;
public readonly languageIdCodec: LanguageIdCodec;
private _dynamicLanguages: ILanguageExtensionPoint[];
private _languages: { [id: string]: IResolvedLanguage };
private _mimeTypesMap: { [mimeType: string]: string };
private _nameMap: { [name: string]: string };
private _lowercaseNameMap: { [name: string]: string };
constructor(useModesRegistry = true, warnOnOverwrite = false) {
super();
LanguagesRegistry.instanceCount++;
this._warnOnOverwrite = warnOnOverwrite;
this.languageIdCodec = new LanguageIdCodec();
this._dynamicLanguages = [];
this._languages = {};
this._mimeTypesMap = {};
this._nameMap = {};
this._lowercaseNameMap = {};
if (useModesRegistry) {
this._initializeFromRegistry();
this._register(ModesRegistry.onDidChangeLanguages((m) => {
this._initializeFromRegistry();
}));
}
}
override dispose() {
LanguagesRegistry.instanceCount--;
super.dispose();
}
public setDynamicLanguages(def: ILanguageExtensionPoint[]): void {
this._dynamicLanguages = def;
this._initializeFromRegistry();
}
private _initializeFromRegistry(): void {
this._languages = {};
this._mimeTypesMap = {};
this._nameMap = {};
this._lowercaseNameMap = {};
clearPlatformLanguageAssociations();
const desc = (<ILanguageExtensionPoint[]>[]).concat(ModesRegistry.getLanguages()).concat(this._dynamicLanguages);
this._registerLanguages(desc);
}
registerLanguage(desc: ILanguageExtensionPoint): IDisposable {
return ModesRegistry.registerLanguage(desc);
}
_registerLanguages(desc: ILanguageExtensionPoint[]): void {
for (const d of desc) {
this._registerLanguage(d);
}
// Rebuild fast path maps
this._mimeTypesMap = {};
this._nameMap = {};
this._lowercaseNameMap = {};
Object.keys(this._languages).forEach((langId) => {
const language = this._languages[langId];
if (language.name) {
this._nameMap[language.name] = language.identifier;
}
language.aliases.forEach((alias) => {
this._lowercaseNameMap[alias.toLowerCase()] = language.identifier;
});
language.mimetypes.forEach((mimetype) => {
this._mimeTypesMap[mimetype] = language.identifier;
});
});
Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerOverrideIdentifiers(this.getRegisteredLanguageIds());
this._onDidChange.fire();
}
private _registerLanguage(lang: ILanguageExtensionPoint): void {
const langId = lang.id;
let resolvedLanguage: IResolvedLanguage;
if (hasOwnProperty.call(this._languages, langId)) {
resolvedLanguage = this._languages[langId];
} else {
this.languageIdCodec.register(langId);
resolvedLanguage = {
identifier: langId,
name: null,
mimetypes: [],
aliases: [],
extensions: [],
filenames: [],
configurationFiles: [],
icons: []
};
this._languages[langId] = resolvedLanguage;
}
this._mergeLanguage(resolvedLanguage, lang);
}
private _mergeLanguage(resolvedLanguage: IResolvedLanguage, lang: ILanguageExtensionPoint): void {
const langId = lang.id;
let primaryMime: string | null = null;
if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) {
resolvedLanguage.mimetypes.push(...lang.mimetypes);
primaryMime = lang.mimetypes[0];
}
if (!primaryMime) {
primaryMime = `text/x-${langId}`;
resolvedLanguage.mimetypes.push(primaryMime);
}
if (Array.isArray(lang.extensions)) {
if (lang.configuration) {
// insert first as this appears to be the 'primary' language definition
resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions);
} else {
resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions);
}
for (const extension of lang.extensions) {
registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, extension: extension }, this._warnOnOverwrite);
}
}
if (Array.isArray(lang.filenames)) {
for (const filename of lang.filenames) {
registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, filename: filename }, this._warnOnOverwrite);
resolvedLanguage.filenames.push(filename);
}
}
if (Array.isArray(lang.filenamePatterns)) {
for (const filenamePattern of lang.filenamePatterns) {
registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite);
}
}
if (typeof lang.firstLine === 'string' && lang.firstLine.length > 0) {
let firstLineRegexStr = lang.firstLine;
if (firstLineRegexStr.charAt(0) !== '^') {
firstLineRegexStr = '^' + firstLineRegexStr;
}
try {
const firstLineRegex = new RegExp(firstLineRegexStr);
if (!regExpLeadsToEndlessLoop(firstLineRegex)) {
registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite);
}
} catch (err) {
// Most likely, the regex was bad
console.warn(`[${lang.id}]: Invalid regular expression \`${firstLineRegexStr}\`: `, err);
}
}
resolvedLanguage.aliases.push(langId);
let langAliases: Array<string | null> | null = null;
if (typeof lang.aliases !== 'undefined' && Array.isArray(lang.aliases)) {
if (lang.aliases.length === 0) {
// signal that this language should not get a name
langAliases = [null];
} else {
langAliases = lang.aliases;
}
}
if (langAliases !== null) {
for (const langAlias of langAliases) {
if (!langAlias || langAlias.length === 0) {
continue;
}
resolvedLanguage.aliases.push(langAlias);
}
}
const containsAliases = (langAliases !== null && langAliases.length > 0);
if (containsAliases && langAliases![0] === null) {
// signal that this language should not get a name
} else {
const bestName = (containsAliases ? langAliases![0] : null) || langId;
if (containsAliases || !resolvedLanguage.name) {
resolvedLanguage.name = bestName;
}
}
if (lang.configuration) {
resolvedLanguage.configurationFiles.push(lang.configuration);
}
if (lang.icon) {
resolvedLanguage.icons.push(lang.icon);
}
}
public isRegisteredLanguageId(languageId: string | null | undefined): boolean {
if (!languageId) {
return false;
}
return hasOwnProperty.call(this._languages, languageId);
}
public getRegisteredLanguageIds(): string[] {
return Object.keys(this._languages);
}
public getSortedRegisteredLanguageNames(): ILanguageNameIdPair[] {
const result: ILanguageNameIdPair[] = [];
for (const languageName in this._nameMap) {
if (hasOwnProperty.call(this._nameMap, languageName)) {
result.push({
languageName: languageName,
languageId: this._nameMap[languageName]
});
}
}
result.sort((a, b) => compareIgnoreCase(a.languageName, b.languageName));
return result;
}
public getLanguageName(languageId: string): string | null {
if (!hasOwnProperty.call(this._languages, languageId)) {
return null;
}
return this._languages[languageId].name;
}
public getMimeType(languageId: string): string | null {
if (!hasOwnProperty.call(this._languages, languageId)) {
return null;
}
const language = this._languages[languageId];
return (language.mimetypes[0] || null);
}
public getExtensions(languageId: string): ReadonlyArray<string> {
if (!hasOwnProperty.call(this._languages, languageId)) {
return [];
}
return this._languages[languageId].extensions;
}
public getFilenames(languageId: string): ReadonlyArray<string> {
if (!hasOwnProperty.call(this._languages, languageId)) {
return [];
}
return this._languages[languageId].filenames;
}
public getIcon(languageId: string): ILanguageIcon | null {
if (!hasOwnProperty.call(this._languages, languageId)) {
return null;
}
const language = this._languages[languageId];
return (language.icons[0] || null);
}
public getConfigurationFiles(languageId: string): ReadonlyArray<URI> {
if (!hasOwnProperty.call(this._languages, languageId)) {
return [];
}
return this._languages[languageId].configurationFiles || [];
}
public getLanguageIdByLanguageName(languageName: string): string | null {
const languageNameLower = languageName.toLowerCase();
if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) {
return null;
}
return this._lowercaseNameMap[languageNameLower];
}
public getLanguageIdByMimeType(mimeType: string | null | undefined): string | null {
if (!mimeType) {
return null;
}
if (hasOwnProperty.call(this._mimeTypesMap, mimeType)) {
return this._mimeTypesMap[mimeType];
}
return null;
}
public guessLanguageIdByFilepathOrFirstLine(resource: URI | null, firstLine?: string): string[] {
if (!resource && !firstLine) {
return [];
}
return getLanguageIds(resource, firstLine);
}
}
|
src/vs/editor/common/services/languagesRegistry.ts
| 0 |
https://github.com/microsoft/vscode/commit/63b07dbd7fe51b4612cac7224d9ffb6149024d4d
|
[
0.00017578880942892283,
0.00017095264047384262,
0.0001655720843700692,
0.00017087945889215916,
0.0000019685651295731077
] |
{
"id": 0,
"code_window": [
"\n",
"### Why defaultExpandAll not working on ajax data?\n",
"\n",
"`default` prefix prop only works when inited. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.\n",
"\n",
"### Virtual scroll limitation\n",
"\n",
"Virtual scroll only render items in visible region. Thus not support auto width (like long `title` with horizontal scroll).\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"`default` prefix prop only works when initializing. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.\n"
],
"file_path": "components/tree/index.en-US.md",
"type": "replace",
"edit_start_line_idx": 113
}
|
---
category: Components
type: Data Display
title: Tree
cover: https://gw.alipayobjects.com/zos/alicdn/Xh-oWqg9k/Tree.svg
---
A hierarchical list structure component.
## When To Use
Almost anything can be represented in a tree structure. Examples include directories, organization hierarchies, biological classifications, countries, etc. The `Tree` component is a way of representing the hierarchical relationship between these things. You can also expand, collapse, and select a treeNode within a `Tree`.
## API
### Tree props
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| allowDrop | Whether to allow dropping on the node | ({ dropNode, dropPosition }) => boolean | - | |
| autoExpandParent | Whether to automatically expand a parent treeNode | boolean | false | |
| blockNode | Whether treeNode fill remaining horizontal space | boolean | false | |
| checkable | Add a Checkbox before the treeNodes | boolean | false | |
| checkedKeys | (Controlled) Specifies the keys of the checked treeNodes (PS: When this specifies the key of a treeNode which is also a parent treeNode, all the children treeNodes of will be checked; and vice versa, when it specifies the key of a treeNode which is a child treeNode, its parent treeNode will also be checked. When `checkable` and `checkStrictly` is true, its object has `checked` and `halfChecked` property. Regardless of whether the child or parent treeNode is checked, they won't impact each other | string\[] \| {checked: string\[], halfChecked: string\[]} | \[] | |
| checkStrictly | Check treeNode precisely; parent treeNode and children treeNodes are not associated | boolean | false | |
| defaultCheckedKeys | Specifies the keys of the default checked treeNodes | string\[] | \[] | |
| defaultExpandAll | Whether to expand all treeNodes by default | boolean | false | |
| defaultExpandedKeys | Specify the keys of the default expanded treeNodes | string\[] | \[] | |
| defaultExpandParent | If auto expand parent treeNodes when init | boolean | true | |
| defaultSelectedKeys | Specifies the keys of the default selected treeNodes | string\[] | \[] | |
| disabled | Whether disabled the tree | boolean | false | |
| draggable | Specifies whether this Tree or the node is draggable. Use `icon: false` to disable drag handler icon | boolean \| ((node: DataNode) => boolean) \| { icon?: React.ReactNode \| false, nodeDraggable?: (node: DataNode) => boolean } | false | `config`: 4.17.0 |
| expandedKeys | (Controlled) Specifies the keys of the expanded treeNodes | string\[] | \[] | |
| fieldNames | Customize node title, key, children field name | object | { title: `title`, key: `key`, children: `children` } | 4.17.0 |
| filterTreeNode | Defines a function to filter (highlight) treeNodes. When the function returns `true`, the corresponding treeNode will be highlighted | function(node) | - | |
| height | Config virtual scroll height. Will not support horizontal scroll when enable this | number | - | |
| icon | Customize treeNode icon | ReactNode \| (props) => ReactNode | - | |
| loadData | Load data asynchronously | function(node) | - | |
| loadedKeys | (Controlled) Set loaded tree nodes. Need work with `loadData` | string\[] | \[] | |
| multiple | Allows selecting multiple treeNodes | boolean | false | |
| rootClassName | ClassName on the root element | string | - | 4.20.0 |
| rootStyle | Style on the root element | CSSProperties | - | 4.20.0 |
| selectable | Whether can be selected | boolean | true | |
| selectedKeys | (Controlled) Specifies the keys of the selected treeNodes | string\[] | - | |
| showIcon | Shows the icon before a TreeNode's title. There is no default style; you must set a custom style for it if set to true | boolean | false | |
| showLine | Shows a connecting line | boolean \| {showLeafIcon: boolean \| ReactNode \| ((props: AntTreeNodeProps) => ReactNode)} | false | |
| switcherIcon | Customize collapse/expand icon of tree node | ReactNode \| ((props: AntTreeNodeProps) => ReactNode) | - | renderProps: 4.20.0 |
| titleRender | Customize tree node title render | (nodeData) => ReactNode | - | 4.5.0 |
| treeData | The treeNodes data Array, if set it then you need not to construct children TreeNode. (key should be unique across the whole array) | array<{ key, title, children, \[disabled, selectable] }> | - | |
| virtual | Disable virtual scroll when set to false | boolean | true | 4.1.0 |
| onCheck | Callback function for when the onCheck event occurs | function(checkedKeys, e:{checked: bool, checkedNodes, node, event, halfCheckedKeys}) | - | |
| onDragEnd | Callback function for when the onDragEnd event occurs | function({event, node}) | - | |
| onDragEnter | Callback function for when the onDragEnter event occurs | function({event, node, expandedKeys}) | - | |
| onDragLeave | Callback function for when the onDragLeave event occurs | function({event, node}) | - | |
| onDragOver | Callback function for when the onDragOver event occurs | function({event, node}) | - | |
| onDragStart | Callback function for when the onDragStart event occurs | function({event, node}) | - | |
| onDrop | Callback function for when the onDrop event occurs | function({event, node, dragNode, dragNodesKeys}) | - | |
| onExpand | Callback function for when a treeNode is expanded or collapsed | function(expandedKeys, {expanded: bool, node}) | - | |
| onLoad | Callback function for when a treeNode is loaded | function(loadedKeys, {event, node}) | - | |
| onRightClick | Callback function for when the user right clicks a treeNode | function({event, node}) | - | |
| onSelect | Callback function for when the user clicks a treeNode | function(selectedKeys, e:{selected: bool, selectedNodes, node, event}) | - | |
### TreeNode props
| Property | Description | Type | Default | |
| --- | --- | --- | --- | --- |
| checkable | When Tree is checkable, set TreeNode display Checkbox or not | boolean | - | |
| disableCheckbox | Disables the checkbox of the treeNode | boolean | false | |
| disabled | Disables the treeNode | boolean | false | |
| icon | Customize icon. When you pass component, whose render will receive full TreeNode props as component props | ReactNode \| (props) => ReactNode | - | |
| isLeaf | Determines if this is a leaf node(effective when `loadData` is specified). `false` will force trade TreeNode as a parent node | boolean | - | |
| key | Used with (default)ExpandedKeys / (default)CheckedKeys / (default)SelectedKeys. P.S.: It must be unique in all of treeNodes of the tree | string | (internal calculated position of treeNode) | |
| selectable | Set whether the treeNode can be selected | boolean | true | |
| title | Title | ReactNode | `---` | |
### DirectoryTree props
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| expandAction | Directory open logic, optional: false \| `click` \| `doubleClick` | string \| boolean | `click` |
## Note
Before `3.4.0`: The number of treeNodes can be very large, but when `checkable=true`, it will increase the compute time. So, we cache some calculations (e.g. `this.treeNodesStates`) to avoid double computing. But, this brings some restrictions. **When you load treeNodes asynchronously, you should render tree like this**:
```jsx
{
this.state.treeData.length ? (
<Tree>
{this.state.treeData.map(data => (
<TreeNode />
))}
</Tree>
) : (
'loading tree'
);
}
```
### Tree Methods
| Name | Description |
| --- | --- |
| scrollTo({ key: string \| number; align?: 'top' \| 'bottom' \| 'auto'; offset?: number }) | Scroll to key item in virtual scroll |
## FAQ
### How to hide file icon when use showLine?
File icon realize by using switcherIcon. You can overwrite the style to hide it: <https://codesandbox.io/s/883vo47xp8>
### Why defaultExpandAll not working on ajax data?
`default` prefix prop only works when inited. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.
### Virtual scroll limitation
Virtual scroll only render items in visible region. Thus not support auto width (like long `title` with horizontal scroll).
### What does `disabled` node work logic in the tree?
Tree change its data by conduction. Includes checked or auto expanded, it will conduction state to parent / children node until current node is `disabled`. So if a controlled node is `disabled`, it will only modify self state and not affect other nodes. For example, a parent node contains 3 child nodes and one of them is `disabled`. When check the parent node, it will only check rest 2 child nodes. As the same, when check these 2 child node, parent will be checked whatever checked state the `disabled` one is.
This conduction logic prevent that modify `disabled` parent checked state by check children node and user can not modify directly with click parent which makes the interactive conflict. If you want to modify this conduction logic, you can customize it with `checkStrictly` prop.
|
components/tree/index.en-US.md
| 1 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.9955561757087708,
0.07698976993560791,
0.0001649793703109026,
0.0003712254110723734,
0.2651674151420593
] |
{
"id": 0,
"code_window": [
"\n",
"### Why defaultExpandAll not working on ajax data?\n",
"\n",
"`default` prefix prop only works when inited. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.\n",
"\n",
"### Virtual scroll limitation\n",
"\n",
"Virtual scroll only render items in visible region. Thus not support auto width (like long `title` with horizontal scroll).\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"`default` prefix prop only works when initializing. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.\n"
],
"file_path": "components/tree/index.en-US.md",
"type": "replace",
"edit_start_line_idx": 113
}
|
import locale from '../locale/pt_BR';
export default locale;
|
components/locale-provider/pt_BR.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00016627975855953991,
0.00016627975855953991,
0.00016627975855953991,
0.00016627975855953991,
0
] |
{
"id": 0,
"code_window": [
"\n",
"### Why defaultExpandAll not working on ajax data?\n",
"\n",
"`default` prefix prop only works when inited. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.\n",
"\n",
"### Virtual scroll limitation\n",
"\n",
"Virtual scroll only render items in visible region. Thus not support auto width (like long `title` with horizontal scroll).\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"`default` prefix prop only works when initializing. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.\n"
],
"file_path": "components/tree/index.en-US.md",
"type": "replace",
"edit_start_line_idx": 113
}
|
import * as React from 'react';
import type { TagProps } from '../tag';
import Tag from '../tag';
export default function PickerTag(props: TagProps) {
return <Tag color="blue" {...props} />;
}
|
components/date-picker/PickerTag.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00016924510418903083,
0.00016924510418903083,
0.00016924510418903083,
0.00016924510418903083,
0
] |
{
"id": 0,
"code_window": [
"\n",
"### Why defaultExpandAll not working on ajax data?\n",
"\n",
"`default` prefix prop only works when inited. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.\n",
"\n",
"### Virtual scroll limitation\n",
"\n",
"Virtual scroll only render items in visible region. Thus not support auto width (like long `title` with horizontal scroll).\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"`default` prefix prop only works when initializing. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.\n"
],
"file_path": "components/tree/index.en-US.md",
"type": "replace",
"edit_start_line_idx": 113
}
|
import classNames from 'classnames';
import RcCheckbox from 'rc-checkbox';
import { composeRef } from 'rc-util/lib/ref';
import * as React from 'react';
import { useContext } from 'react';
import { ConfigContext } from '../config-provider';
import DisabledContext from '../config-provider/DisabledContext';
import { FormItemInputContext } from '../form/context';
import warning from '../_util/warning';
import RadioGroupContext, { RadioOptionTypeContext } from './context';
import type { RadioChangeEvent, RadioProps } from './interface';
const InternalRadio: React.ForwardRefRenderFunction<HTMLElement, RadioProps> = (props, ref) => {
const groupContext = React.useContext(RadioGroupContext);
const radioOptionTypeContext = React.useContext(RadioOptionTypeContext);
const { getPrefixCls, direction } = React.useContext(ConfigContext);
const innerRef = React.useRef<HTMLElement>();
const mergedRef = composeRef(ref, innerRef);
const { isFormItemInput } = useContext(FormItemInputContext);
warning(!('optionType' in props), 'Radio', '`optionType` is only support in Radio.Group.');
const onChange = (e: RadioChangeEvent) => {
props.onChange?.(e);
groupContext?.onChange?.(e);
};
const {
prefixCls: customizePrefixCls,
className,
children,
style,
disabled: customDisabled,
...restProps
} = props;
const radioPrefixCls = getPrefixCls('radio', customizePrefixCls);
const prefixCls =
(groupContext?.optionType || radioOptionTypeContext) === 'button'
? `${radioPrefixCls}-button`
: radioPrefixCls;
const radioProps: RadioProps = { ...restProps };
// ===================== Disabled =====================
const disabled = React.useContext(DisabledContext);
radioProps.disabled = customDisabled || disabled;
if (groupContext) {
radioProps.name = groupContext.name;
radioProps.onChange = onChange;
radioProps.checked = props.value === groupContext.value;
radioProps.disabled = radioProps.disabled || groupContext.disabled;
}
const wrapperClassString = classNames(
`${prefixCls}-wrapper`,
{
[`${prefixCls}-wrapper-checked`]: radioProps.checked,
[`${prefixCls}-wrapper-disabled`]: radioProps.disabled,
[`${prefixCls}-wrapper-rtl`]: direction === 'rtl',
[`${prefixCls}-wrapper-in-form-item`]: isFormItemInput,
},
className,
);
return (
// eslint-disable-next-line jsx-a11y/label-has-associated-control
<label
className={wrapperClassString}
style={style}
onMouseEnter={props.onMouseEnter}
onMouseLeave={props.onMouseLeave}
>
<RcCheckbox {...radioProps} type="radio" prefixCls={prefixCls} ref={mergedRef} />
{children !== undefined ? <span>{children}</span> : null}
</label>
);
};
const Radio = React.forwardRef<unknown, RadioProps>(InternalRadio);
if (process.env.NODE_ENV !== 'production') {
Radio.displayName = 'Radio';
}
export default Radio;
|
components/radio/radio.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00031421560561284423,
0.00020534632494673133,
0.00016596676141489297,
0.00019686414452735335,
0.000043558564357226714
] |
{
"id": 1,
"code_window": [
"@select-tree-prefix-cls: ~'@{ant-prefix}-select-tree';\n",
"@tree-motion: ~'@{ant-prefix}-motion-collapse';\n",
"@tree-node-padding: (@padding-xs / 2);\n",
"@tree-node-hightlight-color: inherit;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"// @deprecated: kept for customization usages, recommend using @tree-node-highlight-color instead.\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "add",
"edit_start_line_idx": 6
}
|
---
category: Components
type: Data Display
title: Tree
cover: https://gw.alipayobjects.com/zos/alicdn/Xh-oWqg9k/Tree.svg
---
A hierarchical list structure component.
## When To Use
Almost anything can be represented in a tree structure. Examples include directories, organization hierarchies, biological classifications, countries, etc. The `Tree` component is a way of representing the hierarchical relationship between these things. You can also expand, collapse, and select a treeNode within a `Tree`.
## API
### Tree props
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| allowDrop | Whether to allow dropping on the node | ({ dropNode, dropPosition }) => boolean | - | |
| autoExpandParent | Whether to automatically expand a parent treeNode | boolean | false | |
| blockNode | Whether treeNode fill remaining horizontal space | boolean | false | |
| checkable | Add a Checkbox before the treeNodes | boolean | false | |
| checkedKeys | (Controlled) Specifies the keys of the checked treeNodes (PS: When this specifies the key of a treeNode which is also a parent treeNode, all the children treeNodes of will be checked; and vice versa, when it specifies the key of a treeNode which is a child treeNode, its parent treeNode will also be checked. When `checkable` and `checkStrictly` is true, its object has `checked` and `halfChecked` property. Regardless of whether the child or parent treeNode is checked, they won't impact each other | string\[] \| {checked: string\[], halfChecked: string\[]} | \[] | |
| checkStrictly | Check treeNode precisely; parent treeNode and children treeNodes are not associated | boolean | false | |
| defaultCheckedKeys | Specifies the keys of the default checked treeNodes | string\[] | \[] | |
| defaultExpandAll | Whether to expand all treeNodes by default | boolean | false | |
| defaultExpandedKeys | Specify the keys of the default expanded treeNodes | string\[] | \[] | |
| defaultExpandParent | If auto expand parent treeNodes when init | boolean | true | |
| defaultSelectedKeys | Specifies the keys of the default selected treeNodes | string\[] | \[] | |
| disabled | Whether disabled the tree | boolean | false | |
| draggable | Specifies whether this Tree or the node is draggable. Use `icon: false` to disable drag handler icon | boolean \| ((node: DataNode) => boolean) \| { icon?: React.ReactNode \| false, nodeDraggable?: (node: DataNode) => boolean } | false | `config`: 4.17.0 |
| expandedKeys | (Controlled) Specifies the keys of the expanded treeNodes | string\[] | \[] | |
| fieldNames | Customize node title, key, children field name | object | { title: `title`, key: `key`, children: `children` } | 4.17.0 |
| filterTreeNode | Defines a function to filter (highlight) treeNodes. When the function returns `true`, the corresponding treeNode will be highlighted | function(node) | - | |
| height | Config virtual scroll height. Will not support horizontal scroll when enable this | number | - | |
| icon | Customize treeNode icon | ReactNode \| (props) => ReactNode | - | |
| loadData | Load data asynchronously | function(node) | - | |
| loadedKeys | (Controlled) Set loaded tree nodes. Need work with `loadData` | string\[] | \[] | |
| multiple | Allows selecting multiple treeNodes | boolean | false | |
| rootClassName | ClassName on the root element | string | - | 4.20.0 |
| rootStyle | Style on the root element | CSSProperties | - | 4.20.0 |
| selectable | Whether can be selected | boolean | true | |
| selectedKeys | (Controlled) Specifies the keys of the selected treeNodes | string\[] | - | |
| showIcon | Shows the icon before a TreeNode's title. There is no default style; you must set a custom style for it if set to true | boolean | false | |
| showLine | Shows a connecting line | boolean \| {showLeafIcon: boolean \| ReactNode \| ((props: AntTreeNodeProps) => ReactNode)} | false | |
| switcherIcon | Customize collapse/expand icon of tree node | ReactNode \| ((props: AntTreeNodeProps) => ReactNode) | - | renderProps: 4.20.0 |
| titleRender | Customize tree node title render | (nodeData) => ReactNode | - | 4.5.0 |
| treeData | The treeNodes data Array, if set it then you need not to construct children TreeNode. (key should be unique across the whole array) | array<{ key, title, children, \[disabled, selectable] }> | - | |
| virtual | Disable virtual scroll when set to false | boolean | true | 4.1.0 |
| onCheck | Callback function for when the onCheck event occurs | function(checkedKeys, e:{checked: bool, checkedNodes, node, event, halfCheckedKeys}) | - | |
| onDragEnd | Callback function for when the onDragEnd event occurs | function({event, node}) | - | |
| onDragEnter | Callback function for when the onDragEnter event occurs | function({event, node, expandedKeys}) | - | |
| onDragLeave | Callback function for when the onDragLeave event occurs | function({event, node}) | - | |
| onDragOver | Callback function for when the onDragOver event occurs | function({event, node}) | - | |
| onDragStart | Callback function for when the onDragStart event occurs | function({event, node}) | - | |
| onDrop | Callback function for when the onDrop event occurs | function({event, node, dragNode, dragNodesKeys}) | - | |
| onExpand | Callback function for when a treeNode is expanded or collapsed | function(expandedKeys, {expanded: bool, node}) | - | |
| onLoad | Callback function for when a treeNode is loaded | function(loadedKeys, {event, node}) | - | |
| onRightClick | Callback function for when the user right clicks a treeNode | function({event, node}) | - | |
| onSelect | Callback function for when the user clicks a treeNode | function(selectedKeys, e:{selected: bool, selectedNodes, node, event}) | - | |
### TreeNode props
| Property | Description | Type | Default | |
| --- | --- | --- | --- | --- |
| checkable | When Tree is checkable, set TreeNode display Checkbox or not | boolean | - | |
| disableCheckbox | Disables the checkbox of the treeNode | boolean | false | |
| disabled | Disables the treeNode | boolean | false | |
| icon | Customize icon. When you pass component, whose render will receive full TreeNode props as component props | ReactNode \| (props) => ReactNode | - | |
| isLeaf | Determines if this is a leaf node(effective when `loadData` is specified). `false` will force trade TreeNode as a parent node | boolean | - | |
| key | Used with (default)ExpandedKeys / (default)CheckedKeys / (default)SelectedKeys. P.S.: It must be unique in all of treeNodes of the tree | string | (internal calculated position of treeNode) | |
| selectable | Set whether the treeNode can be selected | boolean | true | |
| title | Title | ReactNode | `---` | |
### DirectoryTree props
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| expandAction | Directory open logic, optional: false \| `click` \| `doubleClick` | string \| boolean | `click` |
## Note
Before `3.4.0`: The number of treeNodes can be very large, but when `checkable=true`, it will increase the compute time. So, we cache some calculations (e.g. `this.treeNodesStates`) to avoid double computing. But, this brings some restrictions. **When you load treeNodes asynchronously, you should render tree like this**:
```jsx
{
this.state.treeData.length ? (
<Tree>
{this.state.treeData.map(data => (
<TreeNode />
))}
</Tree>
) : (
'loading tree'
);
}
```
### Tree Methods
| Name | Description |
| --- | --- |
| scrollTo({ key: string \| number; align?: 'top' \| 'bottom' \| 'auto'; offset?: number }) | Scroll to key item in virtual scroll |
## FAQ
### How to hide file icon when use showLine?
File icon realize by using switcherIcon. You can overwrite the style to hide it: <https://codesandbox.io/s/883vo47xp8>
### Why defaultExpandAll not working on ajax data?
`default` prefix prop only works when inited. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.
### Virtual scroll limitation
Virtual scroll only render items in visible region. Thus not support auto width (like long `title` with horizontal scroll).
### What does `disabled` node work logic in the tree?
Tree change its data by conduction. Includes checked or auto expanded, it will conduction state to parent / children node until current node is `disabled`. So if a controlled node is `disabled`, it will only modify self state and not affect other nodes. For example, a parent node contains 3 child nodes and one of them is `disabled`. When check the parent node, it will only check rest 2 child nodes. As the same, when check these 2 child node, parent will be checked whatever checked state the `disabled` one is.
This conduction logic prevent that modify `disabled` parent checked state by check children node and user can not modify directly with click parent which makes the interactive conflict. If you want to modify this conduction logic, you can customize it with `checkStrictly` prop.
|
components/tree/index.en-US.md
| 1 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00020798896730411798,
0.00016878501628525555,
0.00016289553605020046,
0.00016461372433695942,
0.000011556197932804935
] |
{
"id": 1,
"code_window": [
"@select-tree-prefix-cls: ~'@{ant-prefix}-select-tree';\n",
"@tree-motion: ~'@{ant-prefix}-motion-collapse';\n",
"@tree-node-padding: (@padding-xs / 2);\n",
"@tree-node-hightlight-color: inherit;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"// @deprecated: kept for customization usages, recommend using @tree-node-highlight-color instead.\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "add",
"edit_start_line_idx": 6
}
|
---
order: 12
title:
zh-CN: 自定义交互图标
en-US: custom action icon
---
## zh-CN
使用 `showUploadList` 设置列表交互图标。
## en-US
Use `showUploadList` for custom action icons of files.
```tsx
import { StarOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, Upload } from 'antd';
import React from 'react';
const props: UploadProps = {
action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
onChange({ file, fileList }) {
if (file.status !== 'uploading') {
console.log(file, fileList);
}
},
defaultFileList: [
{
uid: '1',
name: 'xxx.png',
status: 'done',
response: 'Server Error 500', // custom error message to show
url: 'http://www.baidu.com/xxx.png',
},
{
uid: '2',
name: 'yyy.png',
status: 'done',
url: 'http://www.baidu.com/yyy.png',
},
{
uid: '3',
name: 'zzz.png',
status: 'error',
response: 'Server Error 500', // custom error message to show
url: 'http://www.baidu.com/zzz.png',
},
],
showUploadList: {
showDownloadIcon: true,
downloadIcon: 'Download',
showRemoveIcon: true,
removeIcon: <StarOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
},
};
const App: React.FC = () => (
<Upload {...props}>
<Button icon={<UploadOutlined />}>Upload</Button>
</Upload>
);
export default App;
```
|
components/upload/demo/upload-custom-action-icon.md
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00017681474855635315,
0.00017192579980473965,
0.0001652131468290463,
0.00017179647693410516,
0.0000039862629819253925
] |
{
"id": 1,
"code_window": [
"@select-tree-prefix-cls: ~'@{ant-prefix}-select-tree';\n",
"@tree-motion: ~'@{ant-prefix}-motion-collapse';\n",
"@tree-node-padding: (@padding-xs / 2);\n",
"@tree-node-hightlight-color: inherit;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"// @deprecated: kept for customization usages, recommend using @tree-node-highlight-color instead.\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "add",
"edit_start_line_idx": 6
}
|
@import '../../style/themes/index';
@tree-prefix-cls: ~'@{ant-prefix}-tree';
.@{tree-prefix-cls}.@{tree-prefix-cls}-directory {
// ================== TreeNode ==================
.@{tree-prefix-cls}-treenode {
position: relative;
// Hover color
&::before {
position: absolute;
top: 0;
right: 0;
bottom: 4px;
left: 0;
transition: background-color 0.3s;
content: '';
pointer-events: none;
}
&:hover {
&::before {
background: @item-hover-bg;
}
}
// Elements
> * {
z-index: 1;
}
// >>> Switcher
.@{tree-prefix-cls}-switcher {
transition: color 0.3s;
}
// >>> Title
.@{tree-prefix-cls}-node-content-wrapper {
border-radius: 0;
user-select: none;
&:hover {
background: transparent;
}
&.@{tree-prefix-cls}-node-selected {
color: @tree-directory-selected-color;
background: transparent;
}
}
// ============= Selected =============
&-selected {
&:hover::before,
&::before {
background: @tree-directory-selected-bg;
}
// >>> Switcher
.@{tree-prefix-cls}-switcher {
color: @tree-directory-selected-color;
}
// >>> Title
.@{tree-prefix-cls}-node-content-wrapper {
color: @tree-directory-selected-color;
background: transparent;
}
}
}
}
|
components/tree/style/directory.less
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00032076824572868645,
0.00019312233780510724,
0.00016672494530212134,
0.00017577849212102592,
0.000048568035708740354
] |
{
"id": 1,
"code_window": [
"@select-tree-prefix-cls: ~'@{ant-prefix}-select-tree';\n",
"@tree-motion: ~'@{ant-prefix}-motion-collapse';\n",
"@tree-node-padding: (@padding-xs / 2);\n",
"@tree-node-hightlight-color: inherit;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"// @deprecated: kept for customization usages, recommend using @tree-node-highlight-color instead.\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "add",
"edit_start_line_idx": 6
}
|
import locale from '../locale/mk_MK';
export default locale;
|
components/locale-provider/mk_MK.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00017670131637714803,
0.00017670131637714803,
0.00017670131637714803,
0.00017670131637714803,
0
] |
{
"id": 2,
"code_window": [
"@tree-node-hightlight-color: inherit;\n",
"\n",
".antTreeSwitcherIcon(@type: 'tree-default-open-icon') {\n",
" .@{tree-prefix-cls}-switcher-icon,\n",
" .@{select-tree-prefix-cls}-switcher-icon {\n",
" display: inline-block;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"@tree-node-highlight-color: @tree-node-hightlight-color;\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "add",
"edit_start_line_idx": 7
}
|
---
category: Components
type: Data Display
title: Tree
cover: https://gw.alipayobjects.com/zos/alicdn/Xh-oWqg9k/Tree.svg
---
A hierarchical list structure component.
## When To Use
Almost anything can be represented in a tree structure. Examples include directories, organization hierarchies, biological classifications, countries, etc. The `Tree` component is a way of representing the hierarchical relationship between these things. You can also expand, collapse, and select a treeNode within a `Tree`.
## API
### Tree props
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| allowDrop | Whether to allow dropping on the node | ({ dropNode, dropPosition }) => boolean | - | |
| autoExpandParent | Whether to automatically expand a parent treeNode | boolean | false | |
| blockNode | Whether treeNode fill remaining horizontal space | boolean | false | |
| checkable | Add a Checkbox before the treeNodes | boolean | false | |
| checkedKeys | (Controlled) Specifies the keys of the checked treeNodes (PS: When this specifies the key of a treeNode which is also a parent treeNode, all the children treeNodes of will be checked; and vice versa, when it specifies the key of a treeNode which is a child treeNode, its parent treeNode will also be checked. When `checkable` and `checkStrictly` is true, its object has `checked` and `halfChecked` property. Regardless of whether the child or parent treeNode is checked, they won't impact each other | string\[] \| {checked: string\[], halfChecked: string\[]} | \[] | |
| checkStrictly | Check treeNode precisely; parent treeNode and children treeNodes are not associated | boolean | false | |
| defaultCheckedKeys | Specifies the keys of the default checked treeNodes | string\[] | \[] | |
| defaultExpandAll | Whether to expand all treeNodes by default | boolean | false | |
| defaultExpandedKeys | Specify the keys of the default expanded treeNodes | string\[] | \[] | |
| defaultExpandParent | If auto expand parent treeNodes when init | boolean | true | |
| defaultSelectedKeys | Specifies the keys of the default selected treeNodes | string\[] | \[] | |
| disabled | Whether disabled the tree | boolean | false | |
| draggable | Specifies whether this Tree or the node is draggable. Use `icon: false` to disable drag handler icon | boolean \| ((node: DataNode) => boolean) \| { icon?: React.ReactNode \| false, nodeDraggable?: (node: DataNode) => boolean } | false | `config`: 4.17.0 |
| expandedKeys | (Controlled) Specifies the keys of the expanded treeNodes | string\[] | \[] | |
| fieldNames | Customize node title, key, children field name | object | { title: `title`, key: `key`, children: `children` } | 4.17.0 |
| filterTreeNode | Defines a function to filter (highlight) treeNodes. When the function returns `true`, the corresponding treeNode will be highlighted | function(node) | - | |
| height | Config virtual scroll height. Will not support horizontal scroll when enable this | number | - | |
| icon | Customize treeNode icon | ReactNode \| (props) => ReactNode | - | |
| loadData | Load data asynchronously | function(node) | - | |
| loadedKeys | (Controlled) Set loaded tree nodes. Need work with `loadData` | string\[] | \[] | |
| multiple | Allows selecting multiple treeNodes | boolean | false | |
| rootClassName | ClassName on the root element | string | - | 4.20.0 |
| rootStyle | Style on the root element | CSSProperties | - | 4.20.0 |
| selectable | Whether can be selected | boolean | true | |
| selectedKeys | (Controlled) Specifies the keys of the selected treeNodes | string\[] | - | |
| showIcon | Shows the icon before a TreeNode's title. There is no default style; you must set a custom style for it if set to true | boolean | false | |
| showLine | Shows a connecting line | boolean \| {showLeafIcon: boolean \| ReactNode \| ((props: AntTreeNodeProps) => ReactNode)} | false | |
| switcherIcon | Customize collapse/expand icon of tree node | ReactNode \| ((props: AntTreeNodeProps) => ReactNode) | - | renderProps: 4.20.0 |
| titleRender | Customize tree node title render | (nodeData) => ReactNode | - | 4.5.0 |
| treeData | The treeNodes data Array, if set it then you need not to construct children TreeNode. (key should be unique across the whole array) | array<{ key, title, children, \[disabled, selectable] }> | - | |
| virtual | Disable virtual scroll when set to false | boolean | true | 4.1.0 |
| onCheck | Callback function for when the onCheck event occurs | function(checkedKeys, e:{checked: bool, checkedNodes, node, event, halfCheckedKeys}) | - | |
| onDragEnd | Callback function for when the onDragEnd event occurs | function({event, node}) | - | |
| onDragEnter | Callback function for when the onDragEnter event occurs | function({event, node, expandedKeys}) | - | |
| onDragLeave | Callback function for when the onDragLeave event occurs | function({event, node}) | - | |
| onDragOver | Callback function for when the onDragOver event occurs | function({event, node}) | - | |
| onDragStart | Callback function for when the onDragStart event occurs | function({event, node}) | - | |
| onDrop | Callback function for when the onDrop event occurs | function({event, node, dragNode, dragNodesKeys}) | - | |
| onExpand | Callback function for when a treeNode is expanded or collapsed | function(expandedKeys, {expanded: bool, node}) | - | |
| onLoad | Callback function for when a treeNode is loaded | function(loadedKeys, {event, node}) | - | |
| onRightClick | Callback function for when the user right clicks a treeNode | function({event, node}) | - | |
| onSelect | Callback function for when the user clicks a treeNode | function(selectedKeys, e:{selected: bool, selectedNodes, node, event}) | - | |
### TreeNode props
| Property | Description | Type | Default | |
| --- | --- | --- | --- | --- |
| checkable | When Tree is checkable, set TreeNode display Checkbox or not | boolean | - | |
| disableCheckbox | Disables the checkbox of the treeNode | boolean | false | |
| disabled | Disables the treeNode | boolean | false | |
| icon | Customize icon. When you pass component, whose render will receive full TreeNode props as component props | ReactNode \| (props) => ReactNode | - | |
| isLeaf | Determines if this is a leaf node(effective when `loadData` is specified). `false` will force trade TreeNode as a parent node | boolean | - | |
| key | Used with (default)ExpandedKeys / (default)CheckedKeys / (default)SelectedKeys. P.S.: It must be unique in all of treeNodes of the tree | string | (internal calculated position of treeNode) | |
| selectable | Set whether the treeNode can be selected | boolean | true | |
| title | Title | ReactNode | `---` | |
### DirectoryTree props
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| expandAction | Directory open logic, optional: false \| `click` \| `doubleClick` | string \| boolean | `click` |
## Note
Before `3.4.0`: The number of treeNodes can be very large, but when `checkable=true`, it will increase the compute time. So, we cache some calculations (e.g. `this.treeNodesStates`) to avoid double computing. But, this brings some restrictions. **When you load treeNodes asynchronously, you should render tree like this**:
```jsx
{
this.state.treeData.length ? (
<Tree>
{this.state.treeData.map(data => (
<TreeNode />
))}
</Tree>
) : (
'loading tree'
);
}
```
### Tree Methods
| Name | Description |
| --- | --- |
| scrollTo({ key: string \| number; align?: 'top' \| 'bottom' \| 'auto'; offset?: number }) | Scroll to key item in virtual scroll |
## FAQ
### How to hide file icon when use showLine?
File icon realize by using switcherIcon. You can overwrite the style to hide it: <https://codesandbox.io/s/883vo47xp8>
### Why defaultExpandAll not working on ajax data?
`default` prefix prop only works when inited. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.
### Virtual scroll limitation
Virtual scroll only render items in visible region. Thus not support auto width (like long `title` with horizontal scroll).
### What does `disabled` node work logic in the tree?
Tree change its data by conduction. Includes checked or auto expanded, it will conduction state to parent / children node until current node is `disabled`. So if a controlled node is `disabled`, it will only modify self state and not affect other nodes. For example, a parent node contains 3 child nodes and one of them is `disabled`. When check the parent node, it will only check rest 2 child nodes. As the same, when check these 2 child node, parent will be checked whatever checked state the `disabled` one is.
This conduction logic prevent that modify `disabled` parent checked state by check children node and user can not modify directly with click parent which makes the interactive conflict. If you want to modify this conduction logic, you can customize it with `checkStrictly` prop.
|
components/tree/index.en-US.md
| 1 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.0022676370572298765,
0.00033741744118742645,
0.00016189832240343094,
0.00016614505148027092,
0.0005582165904343128
] |
{
"id": 2,
"code_window": [
"@tree-node-hightlight-color: inherit;\n",
"\n",
".antTreeSwitcherIcon(@type: 'tree-default-open-icon') {\n",
" .@{tree-prefix-cls}-switcher-icon,\n",
" .@{select-tree-prefix-cls}-switcher-icon {\n",
" display: inline-block;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"@tree-node-highlight-color: @tree-node-hightlight-color;\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "add",
"edit_start_line_idx": 7
}
|
---
order: 2
title:
zh-CN: 容器
en-US: Inside a container
---
## zh-CN
放入一个容器中。
## en-US
Spin in a container.
```tsx
import { Spin } from 'antd';
import React from 'react';
const App: React.FC = () => (
<div className="example">
<Spin />
</div>
);
export default App;
```
```css
.example {
margin: 20px 0;
margin-bottom: 20px;
padding: 30px 50px;
text-align: center;
background: rgba(0, 0, 0, 0.05);
border-radius: 4px;
}
```
<style>
.example {
background: rgba(255,255,255,0.08);
}
</style>
|
components/spin/demo/inside.md
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.0001762627944117412,
0.00017354001465719193,
0.00016819810844026506,
0.00017499845125712454,
0.000002935651309599052
] |
{
"id": 2,
"code_window": [
"@tree-node-hightlight-color: inherit;\n",
"\n",
".antTreeSwitcherIcon(@type: 'tree-default-open-icon') {\n",
" .@{tree-prefix-cls}-switcher-icon,\n",
" .@{select-tree-prefix-cls}-switcher-icon {\n",
" display: inline-block;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"@tree-node-highlight-color: @tree-node-hightlight-color;\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "add",
"edit_start_line_idx": 7
}
|
---
order: 3
title:
zh-CN: 跳转
en-US: Jumper
---
## zh-CN
快速跳转到某一页。
## en-US
Jump to a page directly.
```tsx
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
import React from 'react';
const onChange: PaginationProps['onChange'] = pageNumber => {
console.log('Page: ', pageNumber);
};
const App: React.FC = () => (
<>
<Pagination showQuickJumper defaultCurrent={2} total={500} onChange={onChange} />
<br />
<Pagination showQuickJumper defaultCurrent={2} total={500} onChange={onChange} disabled />
</>
);
export default App;
```
|
components/pagination/demo/jump.md
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00017666444182395935,
0.00017359084449708462,
0.00017077504890039563,
0.00017346194363199174,
0.000002249360704809078
] |
{
"id": 2,
"code_window": [
"@tree-node-hightlight-color: inherit;\n",
"\n",
".antTreeSwitcherIcon(@type: 'tree-default-open-icon') {\n",
" .@{tree-prefix-cls}-switcher-icon,\n",
" .@{select-tree-prefix-cls}-switcher-icon {\n",
" display: inline-block;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"@tree-node-highlight-color: @tree-node-hightlight-color;\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "add",
"edit_start_line_idx": 7
}
|
---
order: 0
title:
zh-CN: 基本
en-US: Basic
---
## zh-CN
点击 TimePicker,然后可以在浮层中选择或者输入某一时间。
## en-US
Click `TimePicker`, and then we could select or input a time in panel.
```tsx
import { TimePicker } from 'antd';
import type { Moment } from 'moment';
import moment from 'moment';
import React from 'react';
const onChange = (time: Moment, timeString: string) => {
console.log(time, timeString);
};
const App: React.FC = () => (
<TimePicker onChange={onChange} defaultOpenValue={moment('00:00:00', 'HH:mm:ss')} />
);
export default App;
```
|
components/time-picker/demo/basic.md
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00017922831466421485,
0.00017649900109972805,
0.0001753259712131694,
0.0001757208665367216,
0.0000015840164451219607
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" &:not(&-disabled).filter-node .@{custom-tree-prefix-cls}-title {\n",
" color: @tree-node-hightlight-color;\n",
" font-weight: 500;\n",
" }\n",
"\n",
" &-draggable {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" color: @tree-node-highlight-color;\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "replace",
"edit_start_line_idx": 116
}
|
---
category: Components
type: Data Display
title: Tree
cover: https://gw.alipayobjects.com/zos/alicdn/Xh-oWqg9k/Tree.svg
---
A hierarchical list structure component.
## When To Use
Almost anything can be represented in a tree structure. Examples include directories, organization hierarchies, biological classifications, countries, etc. The `Tree` component is a way of representing the hierarchical relationship between these things. You can also expand, collapse, and select a treeNode within a `Tree`.
## API
### Tree props
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| allowDrop | Whether to allow dropping on the node | ({ dropNode, dropPosition }) => boolean | - | |
| autoExpandParent | Whether to automatically expand a parent treeNode | boolean | false | |
| blockNode | Whether treeNode fill remaining horizontal space | boolean | false | |
| checkable | Add a Checkbox before the treeNodes | boolean | false | |
| checkedKeys | (Controlled) Specifies the keys of the checked treeNodes (PS: When this specifies the key of a treeNode which is also a parent treeNode, all the children treeNodes of will be checked; and vice versa, when it specifies the key of a treeNode which is a child treeNode, its parent treeNode will also be checked. When `checkable` and `checkStrictly` is true, its object has `checked` and `halfChecked` property. Regardless of whether the child or parent treeNode is checked, they won't impact each other | string\[] \| {checked: string\[], halfChecked: string\[]} | \[] | |
| checkStrictly | Check treeNode precisely; parent treeNode and children treeNodes are not associated | boolean | false | |
| defaultCheckedKeys | Specifies the keys of the default checked treeNodes | string\[] | \[] | |
| defaultExpandAll | Whether to expand all treeNodes by default | boolean | false | |
| defaultExpandedKeys | Specify the keys of the default expanded treeNodes | string\[] | \[] | |
| defaultExpandParent | If auto expand parent treeNodes when init | boolean | true | |
| defaultSelectedKeys | Specifies the keys of the default selected treeNodes | string\[] | \[] | |
| disabled | Whether disabled the tree | boolean | false | |
| draggable | Specifies whether this Tree or the node is draggable. Use `icon: false` to disable drag handler icon | boolean \| ((node: DataNode) => boolean) \| { icon?: React.ReactNode \| false, nodeDraggable?: (node: DataNode) => boolean } | false | `config`: 4.17.0 |
| expandedKeys | (Controlled) Specifies the keys of the expanded treeNodes | string\[] | \[] | |
| fieldNames | Customize node title, key, children field name | object | { title: `title`, key: `key`, children: `children` } | 4.17.0 |
| filterTreeNode | Defines a function to filter (highlight) treeNodes. When the function returns `true`, the corresponding treeNode will be highlighted | function(node) | - | |
| height | Config virtual scroll height. Will not support horizontal scroll when enable this | number | - | |
| icon | Customize treeNode icon | ReactNode \| (props) => ReactNode | - | |
| loadData | Load data asynchronously | function(node) | - | |
| loadedKeys | (Controlled) Set loaded tree nodes. Need work with `loadData` | string\[] | \[] | |
| multiple | Allows selecting multiple treeNodes | boolean | false | |
| rootClassName | ClassName on the root element | string | - | 4.20.0 |
| rootStyle | Style on the root element | CSSProperties | - | 4.20.0 |
| selectable | Whether can be selected | boolean | true | |
| selectedKeys | (Controlled) Specifies the keys of the selected treeNodes | string\[] | - | |
| showIcon | Shows the icon before a TreeNode's title. There is no default style; you must set a custom style for it if set to true | boolean | false | |
| showLine | Shows a connecting line | boolean \| {showLeafIcon: boolean \| ReactNode \| ((props: AntTreeNodeProps) => ReactNode)} | false | |
| switcherIcon | Customize collapse/expand icon of tree node | ReactNode \| ((props: AntTreeNodeProps) => ReactNode) | - | renderProps: 4.20.0 |
| titleRender | Customize tree node title render | (nodeData) => ReactNode | - | 4.5.0 |
| treeData | The treeNodes data Array, if set it then you need not to construct children TreeNode. (key should be unique across the whole array) | array<{ key, title, children, \[disabled, selectable] }> | - | |
| virtual | Disable virtual scroll when set to false | boolean | true | 4.1.0 |
| onCheck | Callback function for when the onCheck event occurs | function(checkedKeys, e:{checked: bool, checkedNodes, node, event, halfCheckedKeys}) | - | |
| onDragEnd | Callback function for when the onDragEnd event occurs | function({event, node}) | - | |
| onDragEnter | Callback function for when the onDragEnter event occurs | function({event, node, expandedKeys}) | - | |
| onDragLeave | Callback function for when the onDragLeave event occurs | function({event, node}) | - | |
| onDragOver | Callback function for when the onDragOver event occurs | function({event, node}) | - | |
| onDragStart | Callback function for when the onDragStart event occurs | function({event, node}) | - | |
| onDrop | Callback function for when the onDrop event occurs | function({event, node, dragNode, dragNodesKeys}) | - | |
| onExpand | Callback function for when a treeNode is expanded or collapsed | function(expandedKeys, {expanded: bool, node}) | - | |
| onLoad | Callback function for when a treeNode is loaded | function(loadedKeys, {event, node}) | - | |
| onRightClick | Callback function for when the user right clicks a treeNode | function({event, node}) | - | |
| onSelect | Callback function for when the user clicks a treeNode | function(selectedKeys, e:{selected: bool, selectedNodes, node, event}) | - | |
### TreeNode props
| Property | Description | Type | Default | |
| --- | --- | --- | --- | --- |
| checkable | When Tree is checkable, set TreeNode display Checkbox or not | boolean | - | |
| disableCheckbox | Disables the checkbox of the treeNode | boolean | false | |
| disabled | Disables the treeNode | boolean | false | |
| icon | Customize icon. When you pass component, whose render will receive full TreeNode props as component props | ReactNode \| (props) => ReactNode | - | |
| isLeaf | Determines if this is a leaf node(effective when `loadData` is specified). `false` will force trade TreeNode as a parent node | boolean | - | |
| key | Used with (default)ExpandedKeys / (default)CheckedKeys / (default)SelectedKeys. P.S.: It must be unique in all of treeNodes of the tree | string | (internal calculated position of treeNode) | |
| selectable | Set whether the treeNode can be selected | boolean | true | |
| title | Title | ReactNode | `---` | |
### DirectoryTree props
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| expandAction | Directory open logic, optional: false \| `click` \| `doubleClick` | string \| boolean | `click` |
## Note
Before `3.4.0`: The number of treeNodes can be very large, but when `checkable=true`, it will increase the compute time. So, we cache some calculations (e.g. `this.treeNodesStates`) to avoid double computing. But, this brings some restrictions. **When you load treeNodes asynchronously, you should render tree like this**:
```jsx
{
this.state.treeData.length ? (
<Tree>
{this.state.treeData.map(data => (
<TreeNode />
))}
</Tree>
) : (
'loading tree'
);
}
```
### Tree Methods
| Name | Description |
| --- | --- |
| scrollTo({ key: string \| number; align?: 'top' \| 'bottom' \| 'auto'; offset?: number }) | Scroll to key item in virtual scroll |
## FAQ
### How to hide file icon when use showLine?
File icon realize by using switcherIcon. You can overwrite the style to hide it: <https://codesandbox.io/s/883vo47xp8>
### Why defaultExpandAll not working on ajax data?
`default` prefix prop only works when inited. So `defaultExpandAll` has already executed when ajax load data. You can control `expandedKeys` or render Tree when data loaded to realize expanded all.
### Virtual scroll limitation
Virtual scroll only render items in visible region. Thus not support auto width (like long `title` with horizontal scroll).
### What does `disabled` node work logic in the tree?
Tree change its data by conduction. Includes checked or auto expanded, it will conduction state to parent / children node until current node is `disabled`. So if a controlled node is `disabled`, it will only modify self state and not affect other nodes. For example, a parent node contains 3 child nodes and one of them is `disabled`. When check the parent node, it will only check rest 2 child nodes. As the same, when check these 2 child node, parent will be checked whatever checked state the `disabled` one is.
This conduction logic prevent that modify `disabled` parent checked state by check children node and user can not modify directly with click parent which makes the interactive conflict. If you want to modify this conduction logic, you can customize it with `checkStrictly` prop.
|
components/tree/index.en-US.md
| 1 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.00031619807123206556,
0.00018814952636603266,
0.00016005730140022933,
0.00016596232308074832,
0.00004416432784637436
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" &:not(&-disabled).filter-node .@{custom-tree-prefix-cls}-title {\n",
" color: @tree-node-hightlight-color;\n",
" font-weight: 500;\n",
" }\n",
"\n",
" &-draggable {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" color: @tree-node-highlight-color;\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "replace",
"edit_start_line_idx": 116
}
|
---
category: Ant Design
order: 2
title: 实践案例
---
从 2015 年 4 月起,Ant Design 在蚂蚁集团中后台产品线迅速推广,对接多条业务线,覆盖系统 800 个以上。定位于中台业务的 Ant Design 兼顾专业和非专业的设计人员,具有学习成本低、上手速度快、实现效果好等特点,并且提供从界面设计到前端开发的全链路生态,可以大大提升设计和开发的效率。
Ant Design 目前在外部也有许多产品实践,如果你的公司和产品从中受益,[欢迎留言](https://github.com/ant-design/ant-design/issues/477)。
## 最佳实践
### 蚂蚁金融科技
金融云是面向金融机构深度定制的行业云计算服务;助力金融机构向新金融转型升级,推动平台、数据和技术方面的能力全面对外开放。
[立即访问](https://tech.antfin.com)

### OceanBase 云平台
OceanBase 是一款真正意义上的云端分布式关系型数据库,而 OceanBase Cloud Platform(云平台)是以 OceanBase 数据库为基础的云服务,可以帮助用户快速创建、使用 OB 服务。
[立即访问](https://www.oceanbase.com/docs/enterprise/oceanbase-ocp-cn/V3.3.3/10000000000636101)

### 语雀
与团队一起编写文档,极致体验,高效协同。在微笑中构建专属知识库。
[立即访问](https://yuque.com/)

### Ant Design Pro
Ant Design Pro 是一个企业级中后台前端/设计解决方案,秉承 Ant Design 的设计价值观,致力于在设计规范和基础组件的基础上,继续向上构建,提炼出典型模板/业务组件/配套设计资源,进一步提升企业级中后台产品设计研发过程中的「用户」和「设计者」的体验。
[立即访问](https://pro.ant.design)

### 阿里云流计算
阿里云流计算(Alibaba Cloud StreamCompute)是运行在阿里云平台上的流式大数据分析平台,提供给用户在云上进行流式数据实时化分析工具。
[立即访问](https://data.aliyun.com/product/sc)

|
docs/spec/cases.zh-CN.md
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.001880600000731647,
0.00045629427768290043,
0.00016252658679150045,
0.00017284939531236887,
0.0006369961774908006
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" &:not(&-disabled).filter-node .@{custom-tree-prefix-cls}-title {\n",
" color: @tree-node-hightlight-color;\n",
" font-weight: 500;\n",
" }\n",
"\n",
" &-draggable {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" color: @tree-node-highlight-color;\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "replace",
"edit_start_line_idx": 116
}
|
---
order: 6
title:
zh-CN: 切换菜单类型
en-US: Switch the menu type
---
## zh-CN
展示动态切换模式。
## en-US
Show the dynamic switching mode (between `inline` and `vertical`).
```tsx
import {
AppstoreOutlined,
CalendarOutlined,
LinkOutlined,
MailOutlined,
SettingOutlined,
} from '@ant-design/icons';
import { Divider, Menu, Switch } from 'antd';
import type { MenuProps, MenuTheme } from 'antd/es/menu';
import React, { useState } from 'react';
type MenuItem = Required<MenuProps>['items'][number];
function getItem(
label: React.ReactNode,
key?: React.Key | null,
icon?: React.ReactNode,
children?: MenuItem[],
): MenuItem {
return {
key,
icon,
children,
label,
} as MenuItem;
}
const items: MenuItem[] = [
getItem('Navigation One', '1', <MailOutlined />),
getItem('Navigation Two', '2', <CalendarOutlined />),
getItem('Navigation Two', 'sub1', <AppstoreOutlined />, [
getItem('Option 3', '3'),
getItem('Option 4', '4'),
getItem('Submenu', 'sub1-2', null, [getItem('Option 5', '5'), getItem('Option 6', '6')]),
]),
getItem('Navigation Three', 'sub2', <SettingOutlined />, [
getItem('Option 7', '7'),
getItem('Option 8', '8'),
getItem('Option 9', '9'),
getItem('Option 10', '10'),
]),
getItem(
<a href="https://ant.design" target="_blank" rel="noopener noreferrer">
Ant Design
</a>,
'link',
<LinkOutlined />,
),
];
const App: React.FC = () => {
const [mode, setMode] = useState<'vertical' | 'inline'>('inline');
const [theme, setTheme] = useState<MenuTheme>('light');
const changeMode = (value: boolean) => {
setMode(value ? 'vertical' : 'inline');
};
const changeTheme = (value: boolean) => {
setTheme(value ? 'dark' : 'light');
};
return (
<>
<Switch onChange={changeMode} /> Change Mode
<Divider type="vertical" />
<Switch onChange={changeTheme} /> Change Style
<br />
<br />
<Menu
style={{ width: 256 }}
defaultSelectedKeys={['1']}
defaultOpenKeys={['sub1']}
mode={mode}
theme={theme}
items={items}
/>
</>
);
};
export default App;
```
|
components/menu/demo/switch-mode.md
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.0001769469672581181,
0.00017119574476964772,
0.00016569510626140982,
0.000172122148796916,
0.000004093563347851159
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" &:not(&-disabled).filter-node .@{custom-tree-prefix-cls}-title {\n",
" color: @tree-node-hightlight-color;\n",
" font-weight: 500;\n",
" }\n",
"\n",
" &-draggable {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" color: @tree-node-highlight-color;\n"
],
"file_path": "components/tree/style/mixin.less",
"type": "replace",
"edit_start_line_idx": 116
}
|
---
order: 5
title:
zh-CN: 响应式的栅格列表
en-US: Responsive grid list
---
## zh-CN
响应式的栅格列表。尺寸与 [Layout Grid](/components/grid/#Col) 保持一致。
## en-US
Responsive grid list. The size property the is as same as [Layout Grid](/components/grid/#Col).
```tsx
import { Card, List } from 'antd';
import React from 'react';
const data = [
{
title: 'Title 1',
},
{
title: 'Title 2',
},
{
title: 'Title 3',
},
{
title: 'Title 4',
},
{
title: 'Title 5',
},
{
title: 'Title 6',
},
];
const App: React.FC = () => (
<List
grid={{
gutter: 16,
xs: 1,
sm: 2,
md: 4,
lg: 4,
xl: 6,
xxl: 3,
}}
dataSource={data}
renderItem={item => (
<List.Item>
<Card title={item.title}>Card content</Card>
</List.Item>
)}
/>
);
export default App;
```
|
components/list/demo/responsive.md
| 0 |
https://github.com/ant-design/ant-design/commit/66e932fd8f02c5074234707616832e7d76afeb34
|
[
0.0001737096899887547,
0.00016890223196242005,
0.00016271918138954788,
0.00017057715740520507,
0.000004066627298016101
] |
{
"id": 0,
"code_window": [
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'openExplorerOnEnd' }, \"Automatically open the explorer view at the end of a debug session.\"),\n",
"\t\t\tdefault: false\n",
"\t\t},\n",
"\t\t'debug.inlineValues': {\n",
"\t\t\ttype: 'string',\n",
"\t\t\t'enum': ['on', 'off', 'auto'],\n",
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'inlineValues' }, \"Show variable values inline in editor while debugging.\"),\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t'debug.closeReadonlyTabsOnEnd': {\n",
"\t\t\ttype: 'boolean',\n",
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'closeReadonlyTabsOnEnd' }, \"At the end of a debug session, all the read-only tabs associated with that session will be closed\"),\n",
"\t\t\tdefault: false\n",
"\t\t},\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debug.contribution.ts",
"type": "add",
"edit_start_line_idx": 441
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as aria from 'vs/base/browser/ui/aria/aria';
import { Action, IAction } from 'vs/base/common/actions';
import { distinct } from 'vs/base/common/arrays';
import { raceTimeout, RunOnceScheduler } from 'vs/base/common/async';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { isErrorWithActions } from 'vs/base/common/errorMessage';
import * as errors from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { deepClone, equals } from 'vs/base/common/objects';
import severity from 'vs/base/common/severity';
import { URI, URI as uri } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { ITextModel } from 'vs/editor/common/model';
import * as nls from 'vs/nls';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager';
import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands';
import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';
import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory';
import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';
import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner';
import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID } from 'vs/workbench/contrib/debug/common/debug';
import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot';
import { Debugger } from 'vs/workbench/contrib/debug/common/debugger';
import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage';
import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry';
import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils';
import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel';
import { DisassemblyViewInput } from 'vs/workbench/contrib/debug/common/disassemblyViewInput';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files';
import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
export class DebugService implements IDebugService {
declare readonly _serviceBrand: undefined;
private readonly _onDidChangeState: Emitter<State>;
private readonly _onDidNewSession: Emitter<IDebugSession>;
private readonly _onWillNewSession: Emitter<IDebugSession>;
private readonly _onDidEndSession: Emitter<{ session: IDebugSession; restart: boolean }>;
private readonly restartingSessions = new Set<IDebugSession>();
private debugStorage: DebugStorage;
private model: DebugModel;
private viewModel: ViewModel;
private telemetry: DebugTelemetry;
private taskRunner: DebugTaskRunner;
private configurationManager: ConfigurationManager;
private adapterManager: AdapterManager;
private readonly disposables = new DisposableStore();
private debugType!: IContextKey<string>;
private debugState!: IContextKey<string>;
private inDebugMode!: IContextKey<boolean>;
private debugUx!: IContextKey<string>;
private hasDebugged!: IContextKey<boolean>;
private breakpointsExist!: IContextKey<boolean>;
private disassemblyViewFocus!: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: Set<URI>;
private initializing = false;
private _initializingOptions: IDebugSessionOptions | undefined;
private previousState: State | undefined;
private sessionCancellationTokens = new Map<string, CancellationTokenSource>();
private activity: IDisposable | undefined;
private chosenEnvironments: { [key: string]: string };
private haveDoneLazySetup = false;
constructor(
@IEditorService private readonly editorService: IEditorService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IViewsService private readonly viewsService: IViewsService,
@IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService,
@INotificationService private readonly notificationService: INotificationService,
@IDialogService private readonly dialogService: IDialogService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IExtensionService private readonly extensionService: IExtensionService,
@IFileService private readonly fileService: IFileService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService,
@IActivityService private readonly activityService: IActivityService,
@ICommandService private readonly commandService: ICommandService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IWorkspaceTrustRequestService private readonly workspaceTrustRequestService: IWorkspaceTrustRequestService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService
) {
this.breakpointsToSendOnResourceSaved = new Set<URI>();
this._onDidChangeState = new Emitter<State>();
this._onDidNewSession = new Emitter<IDebugSession>();
this._onWillNewSession = new Emitter<IDebugSession>();
this._onDidEndSession = new Emitter();
this.adapterManager = this.instantiationService.createInstance(AdapterManager, { onDidNewSession: this.onDidNewSession });
this.disposables.add(this.adapterManager);
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.adapterManager);
this.disposables.add(this.configurationManager);
this.debugStorage = this.disposables.add(this.instantiationService.createInstance(DebugStorage));
this.chosenEnvironments = this.debugStorage.loadChosenEnvironments();
this.model = this.instantiationService.createInstance(DebugModel, this.debugStorage);
this.telemetry = this.instantiationService.createInstance(DebugTelemetry, this.model);
this.viewModel = new ViewModel(contextKeyService);
this.taskRunner = this.instantiationService.createInstance(DebugTaskRunner);
this.disposables.add(this.fileService.onDidFilesChange(e => this.onFileChanges(e)));
this.disposables.add(this.lifecycleService.onWillShutdown(this.dispose, this));
this.disposables.add(this.extensionHostDebugService.onAttachSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// EH was started in debug mode -> attach to it
session.configuration.request = 'attach';
session.configuration.port = event.port;
session.setSubId(event.subId);
this.launchOrAttachToSession(session);
}
}));
this.disposables.add(this.extensionHostDebugService.onTerminateSession(event => {
const session = this.model.getSession(event.sessionId);
if (session && session.subId === event.subId) {
session.disconnect();
}
}));
this.disposables.add(this.viewModel.onDidFocusStackFrame(() => {
this.onStateChange();
}));
this.disposables.add(this.viewModel.onDidFocusSession((session: IDebugSession | undefined) => {
this.onStateChange();
if (session) {
this.setExceptionBreakpointFallbackSession(session.getId());
}
}));
this.disposables.add(Event.any(this.adapterManager.onDidRegisterDebugger, this.configurationManager.onDidSelectConfiguration)(() => {
const debugUxValue = (this.state !== State.Inactive || (this.configurationManager.getAllConfigurations().length > 0 && this.adapterManager.hasEnabledDebuggers())) ? 'default' : 'simple';
this.debugUx.set(debugUxValue);
this.debugStorage.storeDebugUxState(debugUxValue);
}));
this.disposables.add(this.model.onDidChangeCallStack(() => {
const numberOfSessions = this.model.getSessions().filter(s => !s.parentSession).length;
this.activity?.dispose();
if (numberOfSessions > 0) {
const viewContainer = this.viewDescriptorService.getViewContainerByViewId(CALLSTACK_VIEW_ID);
if (viewContainer) {
this.activity = this.activityService.showViewContainerActivity(viewContainer.id, { badge: new NumberBadge(numberOfSessions, n => n === 1 ? nls.localize('1activeSession', "1 active session") : nls.localize('nActiveSessions', "{0} active sessions", n)) });
}
}
}));
this.disposables.add(editorService.onDidActiveEditorChange(() => {
this.contextKeyService.bufferChangeEvents(() => {
if (editorService.activeEditor === DisassemblyViewInput.instance) {
this.disassemblyViewFocus.set(true);
} else {
// This key can be initialized a tick after this event is fired
this.disassemblyViewFocus?.reset();
}
});
}));
this.disposables.add(this.lifecycleService.onBeforeShutdown(() => {
for (const editor of editorService.editors) {
// Editors will not be valid on window reload, so close them.
if (editor.resource?.scheme === DEBUG_MEMORY_SCHEME) {
editor.dispose();
}
}
}));
this.initContextKeys(contextKeyService);
}
private initContextKeys(contextKeyService: IContextKeyService): void {
queueMicrotask(() => {
contextKeyService.bufferChangeEvents(() => {
this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.hasDebugged = CONTEXT_HAS_DEBUGGED.bindTo(contextKeyService);
this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService);
this.debugUx.set(this.debugStorage.loadDebugUxState());
this.breakpointsExist = CONTEXT_BREAKPOINTS_EXIST.bindTo(contextKeyService);
// Need to set disassemblyViewFocus here to make it in the same context as the debug event handlers
this.disassemblyViewFocus = CONTEXT_DISASSEMBLY_VIEW_FOCUS.bindTo(contextKeyService);
});
const setBreakpointsExistContext = () => this.breakpointsExist.set(!!(this.model.getBreakpoints().length || this.model.getDataBreakpoints().length || this.model.getFunctionBreakpoints().length));
setBreakpointsExistContext();
this.disposables.add(this.model.onDidChangeBreakpoints(() => setBreakpointsExistContext()));
});
}
getModel(): IDebugModel {
return this.model;
}
getViewModel(): IViewModel {
return this.viewModel;
}
getConfigurationManager(): IConfigurationManager {
return this.configurationManager;
}
getAdapterManager(): IAdapterManager {
return this.adapterManager;
}
sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
dispose(): void {
this.disposables.dispose();
}
//---- state management
get state(): State {
const focusedSession = this.viewModel.focusedSession;
if (focusedSession) {
return focusedSession.state;
}
return this.initializing ? State.Initializing : State.Inactive;
}
get initializingOptions(): IDebugSessionOptions | undefined {
return this._initializingOptions;
}
private startInitializingState(options?: IDebugSessionOptions): void {
if (!this.initializing) {
this.initializing = true;
this._initializingOptions = options;
this.onStateChange();
}
}
private endInitializingState(): void {
if (this.initializing) {
this.initializing = false;
this._initializingOptions = undefined;
this.onStateChange();
}
}
private cancelTokens(id: string | undefined): void {
if (id) {
const token = this.sessionCancellationTokens.get(id);
if (token) {
token.cancel();
this.sessionCancellationTokens.delete(id);
}
} else {
this.sessionCancellationTokens.forEach(t => t.cancel());
this.sessionCancellationTokens.clear();
}
}
private onStateChange(): void {
const state = this.state;
if (this.previousState !== state) {
this.contextKeyService.bufferChangeEvents(() => {
this.debugState.set(getStateLabel(state));
this.inDebugMode.set(state !== State.Inactive);
// Only show the simple ux if debug is not yet started and if no launch.json exists
const debugUxValue = ((state !== State.Inactive && state !== State.Initializing) || (this.adapterManager.hasEnabledDebuggers() && this.configurationManager.selectedConfiguration.name)) ? 'default' : 'simple';
this.debugUx.set(debugUxValue);
this.debugStorage.storeDebugUxState(debugUxValue);
});
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
get onDidChangeState(): Event<State> {
return this._onDidChangeState.event;
}
get onDidNewSession(): Event<IDebugSession> {
return this._onDidNewSession.event;
}
get onWillNewSession(): Event<IDebugSession> {
return this._onWillNewSession.event;
}
get onDidEndSession(): Event<{ session: IDebugSession; restart: boolean }> {
return this._onDidEndSession.event;
}
private lazySetup() {
if (!this.haveDoneLazySetup) {
// Registering fs providers is slow
// https://github.com/microsoft/vscode/issues/159886
this.disposables.add(this.fileService.registerProvider(DEBUG_MEMORY_SCHEME, new DebugMemoryFileSystemProvider(this)));
this.haveDoneLazySetup = true;
}
}
//---- life cycle management
/**
* main entry point
* properly manages compounds, checks for errors and handles the initializing state.
*/
async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions, saveBeforeStart = !options?.parentSession): Promise<boolean> {
const message = options && options.noDebug ? nls.localize('runTrust', "Running executes build tasks and program code from your workspace.") : nls.localize('debugTrust', "Debugging executes build tasks and program code from your workspace.");
const trust = await this.workspaceTrustRequestService.requestWorkspaceTrust({ message });
if (!trust) {
return false;
}
this.lazySetup();
this.startInitializingState(options);
this.hasDebugged.set(true);
try {
// make sure to save all files and that the configuration is up to date
await this.extensionService.activateByEvent('onDebug');
if (saveBeforeStart) {
await saveAllBeforeDebugStart(this.configurationService, this.editorService);
}
await this.extensionService.whenInstalledExtensionsRegistered();
let config: IConfig | undefined;
let compound: ICompound | undefined;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
// we are starting a compound debug, first do some error checking and than start each configuration in the compound
if (!compound.configurations) {
throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations."));
}
if (compound.preLaunchTask) {
const taskResult = await this.taskRunner.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask);
if (taskResult === TaskRunResult.Failure) {
this.endInitializingState();
return false;
}
}
if (compound.stopAll) {
options = { ...options, compoundRoot: new DebugCompoundRoot() };
}
const values = await Promise.all(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound!.name) {
return Promise.resolve(false);
}
let launchForName: ILaunch | undefined;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name));
}
}
return this.createSession(launchForName, launchForName!.getConfiguration(name), options);
}));
const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully
this.endInitializingState();
return result;
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : configOrName.name) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist for passed workspace folder.");
throw new Error(message);
}
const result = await this.createSession(launch, config, options);
this.endInitializingState();
return result;
} catch (err) {
// make sure to get out of initializing state, and propagate the result
this.notificationService.error(err);
this.endInitializingState();
return Promise.reject(err);
}
}
/**
* gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks
*/
private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> {
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string | undefined;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = Object.create(null);
}
if (options && options.noDebug) {
config!.noDebug = true;
} else if (options && typeof options.noDebug === 'undefined' && options.parentSession && options.parentSession.configuration.noDebug) {
config!.noDebug = true;
}
const unresolvedConfig = deepClone(config);
let guess: Debugger | undefined;
let activeEditor: EditorInput | undefined;
if (!type) {
activeEditor = this.editorService.activeEditor;
if (activeEditor && activeEditor.resource) {
type = this.chosenEnvironments[activeEditor.resource.toString()];
}
if (!type) {
guess = await this.adapterManager.guessDebugger(false);
if (guess) {
type = guess.type;
}
}
}
const initCancellationToken = new CancellationTokenSource();
const sessionId = generateUuid();
this.sessionCancellationTokens.set(sessionId, initCancellationToken);
const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, initCancellationToken.token);
// a falsy config indicates an aborted launch
if (configByProviders && configByProviders.type) {
try {
let resolvedConfig = await this.substituteVariables(launch, configByProviders);
if (!resolvedConfig) {
// User cancelled resolving of interactive variables, silently return
return false;
}
if (initCancellationToken.token.isCancellationRequested) {
// User cancelled, silently return
return false;
}
const workspace = launch?.workspace || this.contextService.getWorkspace();
const taskResult = await this.taskRunner.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask);
if (taskResult === TaskRunResult.Failure) {
return false;
}
const cfg = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, resolvedConfig.type, resolvedConfig, initCancellationToken.token);
if (!cfg) {
if (launch && type && cfg === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null".
await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token);
}
return false;
}
resolvedConfig = cfg;
const dbg = this.adapterManager.getDebugger(resolvedConfig.type);
if (!dbg || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) {
let message: string;
if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') {
message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
const actionList: IAction[] = [];
actionList.push(new Action(
'installAdditionalDebuggers',
nls.localize({ key: 'installAdditionalDebuggers', comment: ['Placeholder is the debug type, so for example "node", "python"'] }, "Install {0} Extension", resolvedConfig.type),
undefined,
true,
async () => this.commandService.executeCommand('debug.installAdditionalDebuggers', resolvedConfig?.type)
));
await this.showError(message, actionList);
return false;
}
if (!dbg.enabled) {
await this.showError(debuggerDisabledMessage(dbg.type), []);
return false;
}
const result = await this.doCreateSession(sessionId, launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options);
if (result && guess && activeEditor && activeEditor.resource) {
// Remeber user choice of environment per active editor to make starting debugging smoother #124770
this.chosenEnvironments[activeEditor.resource.toString()] = guess.type;
this.debugStorage.storeChosenEnvironments(this.chosenEnvironments);
}
return result;
} catch (err) {
if (err && err.message) {
await this.showError(err.message);
} else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type."));
}
if (launch && !initCancellationToken.token.isCancellationRequested) {
await launch.openConfigFile({ preserveFocus: true }, initCancellationToken.token);
}
return false;
}
}
if (launch && type && configByProviders === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null".
await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token);
}
return false;
}
/**
* instantiates the new session, initializes the session, registers session listeners and reports telemetry
*/
private async doCreateSession(sessionId: string, root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig; unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> {
const session = this.instantiationService.createInstance(DebugSession, sessionId, configuration, root, this.model, options);
if (options?.startedByUser && this.model.getSessions().some(s => s.getLabel() === session.getLabel()) && configuration.resolved.suppressMultipleSessionWarning !== true) {
// There is already a session with the same name, prompt user #127721
const result = await this.dialogService.confirm({ message: nls.localize('multipleSession', "'{0}' is already running. Do you want to start another instance?", session.getLabel()) });
if (!result.confirmed) {
return false;
}
}
this.model.addSession(session);
// register listeners as the very first thing!
this.registerSessionListeners(session);
// since the Session is now properly registered under its ID and hooked, we can announce it
// this event doesn't go to extensions
this._onWillNewSession.fire(session);
const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug'
if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug !== 'neverOpen' && this.viewModel.firstSessionStart)) && !session.suppressDebugView) {
await this.paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar);
}
try {
await this.launchOrAttachToSession(session);
const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.viewsService.openView(REPL_VIEW_ID, false);
}
this.viewModel.firstSessionStart = false;
const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
const sessions = this.model.getSessions();
const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession);
if (shownSessions.length > 1) {
this.viewModel.setMultiSessionView(true);
}
// since the initialized response has arrived announce the new Session (including extensions)
this._onDidNewSession.fire(session);
return true;
} catch (error) {
if (errors.isCancellationError(error)) {
// don't show 'canceled' error messages to the user #7906
return false;
}
// Show the repl if some error got logged there #5870
if (session && session.getReplElements().length > 0) {
this.viewsService.openView(REPL_VIEW_ID, false);
}
if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) {
// ignore attach timeouts in auto attach mode
return false;
}
const errorMessage = error instanceof Error ? error.message : error;
if (error.showUser !== false) {
// Only show the error when showUser is either not defined, or is true #128484
await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []);
}
return false;
}
}
private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> {
const dbgr = this.adapterManager.getDebugger(session.configuration.type);
try {
await session.initialize(dbgr!);
await session.launchOrAttach(session.configuration);
const launchJsonExists = !!session.root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: session.root.uri });
await this.telemetry.logDebugSessionStart(dbgr!, launchJsonExists);
if (forceFocus || !this.viewModel.focusedSession || (session.parentSession === this.viewModel.focusedSession && session.compact)) {
await this.focusStackFrame(undefined, undefined, session);
}
} catch (err) {
if (this.viewModel.focusedSession === session) {
await this.focusStackFrame(undefined);
}
return Promise.reject(err);
}
}
private registerSessionListeners(session: DebugSession): void {
const listenerDisposables = new DisposableStore();
this.disposables.add(listenerDisposables);
const sessionRunningScheduler = listenerDisposables.add(new RunOnceScheduler(() => {
// Do not immediatly defocus the stack frame if the session is running
if (session.state === State.Running && this.viewModel.focusedSession === session) {
this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false);
}
}, 200));
listenerDisposables.add(session.onDidChangeState(() => {
if (session.state === State.Running && this.viewModel.focusedSession === session) {
sessionRunningScheduler.schedule();
}
if (session === this.viewModel.focusedSession) {
this.onStateChange();
}
}));
listenerDisposables.add(this.onDidEndSession(e => {
if (e.session === session && !e.restart) {
this.disposables.delete(listenerDisposables);
}
}));
listenerDisposables.add(session.onDidEndAdapter(async adapterExitEvent => {
if (adapterExitEvent) {
if (adapterExitEvent.error) {
this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString()));
}
this.telemetry.logDebugSessionStop(session, adapterExitEvent);
}
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
const extensionDebugSession = getExtensionHostDebugSession(session);
if (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) {
this.extensionHostDebugService.close(extensionDebugSession.getId());
}
if (session.configuration.postDebugTask) {
const root = session.root ?? this.contextService.getWorkspace();
try {
await this.taskRunner.runTask(root, session.configuration.postDebugTask);
} catch (err) {
this.notificationService.error(err);
}
}
this.endInitializingState();
this.cancelTokens(session.getId());
this._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) });
const focusedSession = this.viewModel.focusedSession;
if (focusedSession && focusedSession.getId() === session.getId()) {
const { session, thread, stackFrame } = getStackFrameThreadAndSessionToFocus(this.model, undefined, undefined, undefined, focusedSession);
this.viewModel.setFocus(stackFrame, thread, session, false);
}
if (this.model.getSessions().length === 0) {
this.viewModel.setMultiSessionView(false);
if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) {
this.paneCompositeService.openPaneComposite(EXPLORER_VIEWLET_ID, ViewContainerLocation.Sidebar);
}
// Data breakpoints that can not be persisted should be cleared when a session ends
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist);
dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId()));
if (this.configurationService.getValue<IDebugConfiguration>('debug').console.closeOnEnd) {
const debugConsoleContainer = this.viewDescriptorService.getViewContainerByViewId(REPL_VIEW_ID);
if (debugConsoleContainer && this.viewsService.isViewContainerVisible(debugConsoleContainer.id)) {
this.viewsService.closeViewContainer(debugConsoleContainer.id);
}
}
}
this.model.removeExceptionBreakpointsForSession(session.getId());
// session.dispose(); TODO@roblourens
}));
}
async restartSession(session: IDebugSession, restartData?: any): Promise<any> {
if (session.saveBeforeRestart) {
await saveAllBeforeDebugStart(this.configurationService, this.editorService);
}
const isAutoRestart = !!restartData;
const runTasks: () => Promise<TaskRunResult> = async () => {
if (isAutoRestart) {
// Do not run preLaunch and postDebug tasks for automatic restarts
return Promise.resolve(TaskRunResult.Success);
}
const root = session.root || this.contextService.getWorkspace();
await this.taskRunner.runTask(root, session.configuration.preRestartTask);
await this.taskRunner.runTask(root, session.configuration.postDebugTask);
const taskResult1 = await this.taskRunner.runTaskAndCheckErrors(root, session.configuration.preLaunchTask);
if (taskResult1 !== TaskRunResult.Success) {
return taskResult1;
}
return this.taskRunner.runTaskAndCheckErrors(root, session.configuration.postRestartTask);
};
const extensionDebugSession = getExtensionHostDebugSession(session);
if (extensionDebugSession) {
const taskResult = await runTasks();
if (taskResult === TaskRunResult.Success) {
this.extensionHostDebugService.reload(extensionDebugSession.getId());
}
return;
}
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let needsToSubstitute = false;
let unresolved: IConfig | undefined;
const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined;
if (launch) {
unresolved = launch.getConfiguration(session.configuration.name);
if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) {
// Take the type from the session since the debug extension might overwrite it #21316
unresolved.type = session.configuration.type;
unresolved.noDebug = session.configuration.noDebug;
needsToSubstitute = true;
}
}
let resolved: IConfig | undefined | null = session.configuration;
if (launch && needsToSubstitute && unresolved) {
const initCancellationToken = new CancellationTokenSource();
this.sessionCancellationTokens.set(session.getId(), initCancellationToken);
const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, initCancellationToken.token);
if (resolvedByProviders) {
resolved = await this.substituteVariables(launch, resolvedByProviders);
if (resolved && !initCancellationToken.token.isCancellationRequested) {
resolved = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, unresolved.type, resolved, initCancellationToken.token);
}
} else {
resolved = resolvedByProviders;
}
}
if (resolved) {
session.setConfiguration({ resolved, unresolved });
}
session.configuration.__restart = restartData;
const doRestart = async (fn: () => Promise<boolean | undefined>) => {
this.restartingSessions.add(session);
let didRestart = false;
try {
didRestart = (await fn()) !== false;
} catch (e) {
didRestart = false;
throw e;
} finally {
this.restartingSessions.delete(session);
// we previously may have issued an onDidEndSession with restart: true,
// assuming the adapter exited (in `registerSessionListeners`). But the
// restart failed, so emit the final termination now.
if (!didRestart) {
this._onDidEndSession.fire({ session, restart: false });
}
}
};
if (session.capabilities.supportsRestartRequest) {
const taskResult = await runTasks();
if (taskResult === TaskRunResult.Success) {
await doRestart(async () => {
await session.restart();
return true;
});
}
return;
}
const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();
return doRestart(async () => {
// If the restart is automatic -> disconnect, otherwise -> terminate #55064
if (isAutoRestart) {
await session.disconnect(true);
} else {
await session.terminate(true);
}
return new Promise<boolean>((c, e) => {
setTimeout(async () => {
const taskResult = await runTasks();
if (taskResult !== TaskRunResult.Success) {
return c(false);
}
if (!resolved) {
return c(false);
}
try {
await this.launchOrAttachToSession(session, shouldFocus);
this._onDidNewSession.fire(session);
c(true);
} catch (error) {
e(error);
}
}, 300);
});
});
}
async stopSession(session: IDebugSession | undefined, disconnect = false, suspend = false): Promise<any> {
if (session) {
return disconnect ? session.disconnect(undefined, suspend) : session.terminate();
}
const sessions = this.model.getSessions();
if (sessions.length === 0) {
this.taskRunner.cancel();
// User might have cancelled starting of a debug session, and in some cases the quick pick is left open
await this.quickInputService.cancel();
this.endInitializingState();
this.cancelTokens(undefined);
}
return Promise.all(sessions.map(s => disconnect ? s.disconnect(undefined, suspend) : s.terminate()));
}
private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> {
const dbg = this.adapterManager.getDebugger(config.type);
if (dbg) {
let folder: IWorkspaceFolder | undefined = undefined;
if (launch && launch.workspace) {
folder = launch.workspace;
} else {
const folders = this.contextService.getWorkspace().folders;
if (folders.length === 1) {
folder = folders[0];
}
}
try {
return await dbg.substituteVariables(folder, config);
} catch (err) {
this.showError(err.message, undefined, !!launch?.getConfiguration(config.name));
return undefined; // bail out
}
}
return Promise.resolve(config);
}
private async showError(message: string, errorActions: ReadonlyArray<IAction> = [], promptLaunchJson = true): Promise<void> {
const configureAction = new Action(DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL, undefined, true, () => this.commandService.executeCommand(DEBUG_CONFIGURE_COMMAND_ID));
// Don't append the standard command if id of any provided action indicates it is a command
const actions = errorActions.filter((action) => action.id.endsWith('.command')).length > 0 ?
errorActions :
[...errorActions, ...(promptLaunchJson ? [configureAction] : [])];
await this.dialogService.prompt({
type: severity.Error,
message,
buttons: actions.map(action => ({
label: action.label,
run: () => action.run()
})),
cancelButton: true
});
}
//---- focus management
async focusStackFrame(_stackFrame: IStackFrame | undefined, _thread?: IThread, _session?: IDebugSession, options?: { explicit?: boolean; preserveFocus?: boolean; sideBySide?: boolean; pinned?: boolean }): Promise<void> {
const { stackFrame, thread, session } = getStackFrameThreadAndSessionToFocus(this.model, _stackFrame, _thread, _session);
if (stackFrame) {
const editor = await stackFrame.openInEditor(this.editorService, options?.preserveFocus ?? true, options?.sideBySide, options?.pinned);
if (editor) {
if (editor.input === DisassemblyViewInput.instance) {
// Go to address is invoked via setFocus
} else {
const control = editor.getControl();
if (stackFrame && isCodeEditor(control) && control.hasModel()) {
const model = control.getModel();
const lineNumber = stackFrame.range.startLineNumber;
if (lineNumber >= 1 && lineNumber <= model.getLineCount()) {
const lineContent = control.getModel().getLineContent(lineNumber);
aria.alert(nls.localize({ key: 'debuggingPaused', comment: ['First placeholder is the file line content, second placeholder is the reason why debugging is stopped, for example "breakpoint", third is the stack frame name, and last is the line number.'] },
"{0}, debugging paused {1}, {2}:{3}", lineContent, thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber));
}
}
}
}
}
if (session) {
this.debugType.set(session.configuration.type);
} else {
this.debugType.reset();
}
this.viewModel.setFocus(stackFrame, thread, session, !!options?.explicit);
}
//---- watches
addWatchExpression(name?: string): void {
const we = this.model.addWatchExpression(name);
if (!name) {
this.viewModel.setSelectedExpression(we, false);
}
this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions());
}
renameWatchExpression(id: string, newName: string): void {
this.model.renameWatchExpression(id, newName);
this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions());
}
moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions());
}
removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions());
}
//---- breakpoints
canSetBreakpointsIn(model: ITextModel): boolean {
return this.adapterManager.canSetBreakpointsIn(model);
}
async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
this.debugStorage.storeBreakpoints(this.model);
if (breakpoint instanceof Breakpoint) {
await this.sendBreakpoints(breakpoint.originalUri);
} else if (breakpoint instanceof FunctionBreakpoint) {
await this.sendFunctionBreakpoints();
} else if (breakpoint instanceof DataBreakpoint) {
await this.sendDataBreakpoints();
} else if (breakpoint instanceof InstructionBreakpoint) {
await this.sendInstructionBreakpoints();
} else {
await this.sendExceptionBreakpoints();
}
} else {
this.model.enableOrDisableAllBreakpoints(enable);
this.debugStorage.storeBreakpoints(this.model);
await this.sendAllBreakpoints();
}
this.debugStorage.storeBreakpoints(this.model);
}
async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], ariaAnnounce = true): Promise<IBreakpoint[]> {
const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints);
if (ariaAnnounce) {
breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath)));
}
// In some cases we need to store breakpoints before we send them because sending them can take a long time
// And after sending them because the debug adapter can attach adapter data to a breakpoint
this.debugStorage.storeBreakpoints(this.model);
await this.sendBreakpoints(uri);
this.debugStorage.storeBreakpoints(this.model);
return breakpoints;
}
async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> {
this.model.updateBreakpoints(data);
this.debugStorage.storeBreakpoints(this.model);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri);
} else {
await this.sendBreakpoints(uri);
this.debugStorage.storeBreakpoints(this.model);
}
}
async removeBreakpoints(id?: string): Promise<void> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
// note: using the debugger-resolved uri for aria to reflect UI state
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.originalUri.toString()).map(bp => bp.originalUri);
this.model.removeBreakpoints(toRemove);
this.debugStorage.storeBreakpoints(this.model);
await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
setBreakpointsActivated(activated: boolean): Promise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
addFunctionBreakpoint(name?: string, id?: string): void {
this.model.addFunctionBreakpoint(name || '', id);
}
async updateFunctionBreakpoint(id: string, update: { name?: string; hitCondition?: string; condition?: string }): Promise<void> {
this.model.updateFunctionBreakpoint(id, update);
this.debugStorage.storeBreakpoints(this.model);
await this.sendFunctionBreakpoints();
}
async removeFunctionBreakpoints(id?: string): Promise<void> {
this.model.removeFunctionBreakpoints(id);
this.debugStorage.storeBreakpoints(this.model);
await this.sendFunctionBreakpoints();
}
async addDataBreakpoint(label: string, dataId: string, canPersist: boolean, accessTypes: DebugProtocol.DataBreakpointAccessType[] | undefined, accessType: DebugProtocol.DataBreakpointAccessType): Promise<void> {
this.model.addDataBreakpoint(label, dataId, canPersist, accessTypes, accessType);
this.debugStorage.storeBreakpoints(this.model);
await this.sendDataBreakpoints();
this.debugStorage.storeBreakpoints(this.model);
}
async updateDataBreakpoint(id: string, update: { hitCondition?: string; condition?: string }): Promise<void> {
this.model.updateDataBreakpoint(id, update);
this.debugStorage.storeBreakpoints(this.model);
await this.sendDataBreakpoints();
}
async removeDataBreakpoints(id?: string): Promise<void> {
this.model.removeDataBreakpoints(id);
this.debugStorage.storeBreakpoints(this.model);
await this.sendDataBreakpoints();
}
async addInstructionBreakpoint(instructionReference: string, offset: number, address: bigint, condition?: string, hitCondition?: string): Promise<void> {
this.model.addInstructionBreakpoint(instructionReference, offset, address, condition, hitCondition);
this.debugStorage.storeBreakpoints(this.model);
await this.sendInstructionBreakpoints();
this.debugStorage.storeBreakpoints(this.model);
}
async removeInstructionBreakpoints(instructionReference?: string, offset?: number): Promise<void> {
this.model.removeInstructionBreakpoints(instructionReference, offset);
this.debugStorage.storeBreakpoints(this.model);
await this.sendInstructionBreakpoints();
}
setExceptionBreakpointFallbackSession(sessionId: string) {
this.model.setExceptionBreakpointFallbackSession(sessionId);
this.debugStorage.storeBreakpoints(this.model);
}
setExceptionBreakpointsForSession(session: IDebugSession, data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
this.model.setExceptionBreakpointsForSession(session.getId(), data);
this.debugStorage.storeBreakpoints(this.model);
}
async setExceptionBreakpointCondition(exceptionBreakpoint: IExceptionBreakpoint, condition: string | undefined): Promise<void> {
this.model.setExceptionBreakpointCondition(exceptionBreakpoint, condition);
this.debugStorage.storeBreakpoints(this.model);
await this.sendExceptionBreakpoints();
}
async sendAllBreakpoints(session?: IDebugSession): Promise<any> {
const setBreakpointsPromises = distinct(this.model.getBreakpoints(), bp => bp.originalUri.toString())
.map(bp => this.sendBreakpoints(bp.originalUri, false, session));
// If sending breakpoints to one session which we know supports the configurationDone request, can make all requests in parallel
if (session?.capabilities.supportsConfigurationDoneRequest) {
await Promise.all([
...setBreakpointsPromises,
this.sendFunctionBreakpoints(session),
this.sendDataBreakpoints(session),
this.sendInstructionBreakpoints(session),
this.sendExceptionBreakpoints(session),
]);
} else {
await Promise.all(setBreakpointsPromises);
await this.sendFunctionBreakpoints(session);
await this.sendDataBreakpoints(session);
await this.sendInstructionBreakpoints(session);
// send exception breakpoints at the end since some debug adapters may rely on the order - this was the case before
// the configurationDone request was introduced.
await this.sendExceptionBreakpoints(session);
}
}
private async sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getBreakpoints({ originalUri: modelUri, enabledOnly: true });
await sendToOneOrAllSessions(this.model, session, async s => {
if (!s.configuration.noDebug) {
await s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified);
}
});
}
private async sendFunctionBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
await sendToOneOrAllSessions(this.model, session, async s => {
if (s.capabilities.supportsFunctionBreakpoints && !s.configuration.noDebug) {
await s.sendFunctionBreakpoints(breakpointsToSend);
}
});
}
private async sendDataBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
await sendToOneOrAllSessions(this.model, session, async s => {
if (s.capabilities.supportsDataBreakpoints && !s.configuration.noDebug) {
await s.sendDataBreakpoints(breakpointsToSend);
}
});
}
private async sendInstructionBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getInstructionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
await sendToOneOrAllSessions(this.model, session, async s => {
if (s.capabilities.supportsInstructionBreakpoints && !s.configuration.noDebug) {
await s.sendInstructionBreakpoints(breakpointsToSend);
}
});
}
private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> {
return sendToOneOrAllSessions(this.model, session, async s => {
const enabledExceptionBps = this.model.getExceptionBreakpointsForSession(s.getId()).filter(exb => exb.enabled);
if (s.capabilities.supportsConfigurationDoneRequest && (!s.capabilities.exceptionBreakpointFilters || s.capabilities.exceptionBreakpointFilters.length === 0)) {
// Only call `setExceptionBreakpoints` as specified in dap protocol #90001
return;
}
if (!s.configuration.noDebug) {
await s.sendExceptionBreakpoints(enabledExceptionBps);
}
});
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.originalUri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
const toSend: URI[] = [];
for (const uri of this.breakpointsToSendOnResourceSaved) {
if (fileChangesEvent.contains(uri, FileChangeType.UPDATED)) {
toSend.push(uri);
}
}
for (const uri of toSend) {
this.breakpointsToSendOnResourceSaved.delete(uri);
this.sendBreakpoints(uri, true);
}
}
async runTo(uri: uri, lineNumber: number, column?: number): Promise<void> {
let breakpointToRemove: IBreakpoint | undefined;
let threadToContinue = this.getViewModel().focusedThread;
const addTempBreakPoint = async () => {
const bpExists = !!(this.getModel().getBreakpoints({ column, lineNumber, uri }).length);
if (!bpExists) {
const addResult = await this.addAndValidateBreakpoints(uri, lineNumber, column);
if (addResult.thread) {
threadToContinue = addResult.thread;
}
if (addResult.breakpoint) {
breakpointToRemove = addResult.breakpoint;
}
}
return { threadToContinue, breakpointToRemove };
};
const removeTempBreakPoint = (state: State): boolean => {
if (state === State.Stopped || state === State.Inactive) {
if (breakpointToRemove) {
this.removeBreakpoints(breakpointToRemove.getId());
}
return true;
}
return false;
};
await addTempBreakPoint();
if (this.state === State.Inactive) {
// If no session exists start the debugger
const { launch, name, getConfig } = this.getConfigurationManager().selectedConfiguration;
const config = await getConfig();
const configOrName = config ? Object.assign(deepClone(config), {}) : name;
const listener = this.onDidChangeState(state => {
if (removeTempBreakPoint(state)) {
listener.dispose();
}
});
await this.startDebugging(launch, configOrName, undefined, true);
}
if (this.state === State.Stopped) {
const focusedSession = this.getViewModel().focusedSession;
if (!focusedSession || !threadToContinue) {
return;
}
const listener = threadToContinue.session.onDidChangeState(() => {
if (removeTempBreakPoint(focusedSession.state)) {
listener.dispose();
}
});
await threadToContinue.continue();
}
}
private async addAndValidateBreakpoints(uri: URI, lineNumber: number, column?: number) {
const debugModel = this.getModel();
const viewModel = this.getViewModel();
const breakpoints = await this.addBreakpoints(uri, [{ lineNumber, column }], false);
const breakpoint = breakpoints?.[0];
if (!breakpoint) {
return { breakpoint: undefined, thread: viewModel.focusedThread };
}
// If the breakpoint was not initially verified, wait up to 2s for it to become so.
// Inherently racey if multiple sessions can verify async, but not solvable...
if (!breakpoint.verified) {
let listener: IDisposable;
await raceTimeout(new Promise<void>(resolve => {
listener = debugModel.onDidChangeBreakpoints(() => {
if (breakpoint.verified) {
resolve();
}
});
}), 2000);
listener!.dispose();
}
// Look at paused threads for sessions that verified this bp. Prefer, in order:
const enum Score {
/** The focused thread */
Focused,
/** Any other stopped thread of a session that verified the bp */
Verified,
/** Any thread that verified and paused in the same file */
VerifiedAndPausedInFile,
/** The focused thread if it verified the breakpoint */
VerifiedAndFocused,
}
let bestThread = viewModel.focusedThread;
let bestScore = Score.Focused;
for (const sessionId of breakpoint.sessionsThatVerified) {
const session = debugModel.getSession(sessionId);
if (!session) {
continue;
}
const threads = session.getAllThreads().filter(t => t.stopped);
if (bestScore < Score.VerifiedAndFocused) {
if (viewModel.focusedThread && threads.includes(viewModel.focusedThread)) {
bestThread = viewModel.focusedThread;
bestScore = Score.VerifiedAndFocused;
}
}
if (bestScore < Score.VerifiedAndPausedInFile) {
const pausedInThisFile = threads.find(t => {
const top = t.getTopStackFrame();
return top && this.uriIdentityService.extUri.isEqual(top.source.uri, uri);
});
if (pausedInThisFile) {
bestThread = pausedInThisFile;
bestScore = Score.VerifiedAndPausedInFile;
}
}
if (bestScore < Score.Verified) {
bestThread = threads[0];
bestScore = Score.VerifiedAndPausedInFile;
}
}
return { thread: bestThread, breakpoint };
}
}
export function getStackFrameThreadAndSessionToFocus(model: IDebugModel, stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, avoidSession?: IDebugSession): { stackFrame: IStackFrame | undefined; thread: IThread | undefined; session: IDebugSession | undefined } {
if (!session) {
if (stackFrame || thread) {
session = stackFrame ? stackFrame.thread.session : thread!.session;
} else {
const sessions = model.getSessions();
const stoppedSession = sessions.find(s => s.state === State.Stopped);
// Make sure to not focus session that is going down
session = stoppedSession || sessions.find(s => s !== avoidSession && s !== avoidSession?.parentSession) || (sessions.length ? sessions[0] : undefined);
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = session ? session.getAllThreads() : undefined;
const stoppedThread = threads && threads.find(t => t.stopped);
thread = stoppedThread || (threads && threads.length ? threads[0] : undefined);
}
}
if (!stackFrame && thread) {
stackFrame = thread.getTopStackFrame();
}
return { session, thread, stackFrame };
}
async function sendToOneOrAllSessions(model: DebugModel, session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> {
if (session) {
await send(session);
} else {
await Promise.all(model.getSessions().map(s => send(s)));
}
}
|
src/vs/workbench/contrib/debug/browser/debugService.ts
| 1 |
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
|
[
0.001105889561586082,
0.00018337923393119127,
0.00016235635848715901,
0.00016833592962939292,
0.00010392790863988921
] |
{
"id": 0,
"code_window": [
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'openExplorerOnEnd' }, \"Automatically open the explorer view at the end of a debug session.\"),\n",
"\t\t\tdefault: false\n",
"\t\t},\n",
"\t\t'debug.inlineValues': {\n",
"\t\t\ttype: 'string',\n",
"\t\t\t'enum': ['on', 'off', 'auto'],\n",
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'inlineValues' }, \"Show variable values inline in editor while debugging.\"),\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t'debug.closeReadonlyTabsOnEnd': {\n",
"\t\t\ttype: 'boolean',\n",
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'closeReadonlyTabsOnEnd' }, \"At the end of a debug session, all the read-only tabs associated with that session will be closed\"),\n",
"\t\t\tdefault: false\n",
"\t\t},\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debug.contribution.ts",
"type": "add",
"edit_start_line_idx": 441
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* ---------- Icon label ---------- */
.monaco-icon-label {
display: flex; /* required for icons support :before rule */
overflow: hidden;
text-overflow: ellipsis;
}
.monaco-icon-label::before {
/* svg icons rendered as background image */
background-size: 16px;
background-position: left center;
background-repeat: no-repeat;
padding-right: 6px;
width: 16px;
height: 22px;
line-height: inherit !important;
display: inline-block;
/* fonts icons */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
vertical-align: top;
flex-shrink: 0; /* fix for https://github.com/microsoft/vscode/issues/13787 */
}
.monaco-icon-label-container.disabled {
color: var(--vscode-disabledForeground);
}
.monaco-icon-label > .monaco-icon-label-container {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
}
.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-name-container > .label-name {
color: inherit;
white-space: pre; /* enable to show labels that include multiple whitespaces */
}
.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-name-container > .label-name > .label-separator {
margin: 0 2px;
opacity: 0.5;
}
.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-suffix-container > .label-suffix {
opacity: .7;
white-space: pre;
}
.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {
opacity: .7;
margin-left: 0.5em;
font-size: 0.9em;
white-space: pre; /* enable to show labels that include multiple whitespaces */
}
.monaco-icon-label.nowrap > .monaco-icon-label-container > .monaco-icon-description-container > .label-description{
white-space: nowrap
}
.vs .monaco-icon-label > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {
opacity: .95;
}
.monaco-icon-label.italic > .monaco-icon-label-container > .monaco-icon-name-container > .label-name,
.monaco-icon-label.italic > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {
font-style: italic;
}
.monaco-icon-label.deprecated {
text-decoration: line-through;
opacity: 0.66;
}
/* make sure apply italic font style to decorations as well */
.monaco-icon-label.italic::after {
font-style: italic;
}
.monaco-icon-label.strikethrough > .monaco-icon-label-container > .monaco-icon-name-container > .label-name,
.monaco-icon-label.strikethrough > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {
text-decoration: line-through;
}
.monaco-icon-label::after {
opacity: 0.75;
font-size: 90%;
font-weight: 600;
margin: auto 16px 0 5px; /* https://github.com/microsoft/vscode/issues/113223 */
text-align: center;
}
/* make sure selection color wins when a label is being selected */
.monaco-list:focus .selected .monaco-icon-label, /* list */
.monaco-list:focus .selected .monaco-icon-label::after
{
color: inherit !important;
}
.monaco-list-row.focused.selected .label-description,
.monaco-list-row.selected .label-description {
opacity: .8;
}
|
src/vs/base/browser/ui/iconLabel/iconlabel.css
| 0 |
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
|
[
0.0001751785894157365,
0.00017208291683346033,
0.00016874911671038717,
0.00017210299847647548,
0.0000017740763951223926
] |
{
"id": 0,
"code_window": [
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'openExplorerOnEnd' }, \"Automatically open the explorer view at the end of a debug session.\"),\n",
"\t\t\tdefault: false\n",
"\t\t},\n",
"\t\t'debug.inlineValues': {\n",
"\t\t\ttype: 'string',\n",
"\t\t\t'enum': ['on', 'off', 'auto'],\n",
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'inlineValues' }, \"Show variable values inline in editor while debugging.\"),\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t'debug.closeReadonlyTabsOnEnd': {\n",
"\t\t\ttype: 'boolean',\n",
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'closeReadonlyTabsOnEnd' }, \"At the end of a debug session, all the read-only tabs associated with that session will be closed\"),\n",
"\t\t\tdefault: false\n",
"\t\t},\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debug.contribution.ts",
"type": "add",
"edit_start_line_idx": 441
}
|
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.ok()
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
|
extensions/vscode-colorize-tests/test/colorize-fixtures/test.rs
| 0 |
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
|
[
0.00017619793652556837,
0.00017600468709133565,
0.00017581145220901817,
0.00017600468709133565,
1.932421582750976e-7
] |
{
"id": 0,
"code_window": [
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'openExplorerOnEnd' }, \"Automatically open the explorer view at the end of a debug session.\"),\n",
"\t\t\tdefault: false\n",
"\t\t},\n",
"\t\t'debug.inlineValues': {\n",
"\t\t\ttype: 'string',\n",
"\t\t\t'enum': ['on', 'off', 'auto'],\n",
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'inlineValues' }, \"Show variable values inline in editor while debugging.\"),\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t'debug.closeReadonlyTabsOnEnd': {\n",
"\t\t\ttype: 'boolean',\n",
"\t\t\tdescription: nls.localize({ comment: ['This is the description for a setting'], key: 'closeReadonlyTabsOnEnd' }, \"At the end of a debug session, all the read-only tabs associated with that session will be closed\"),\n",
"\t\t\tdefault: false\n",
"\t\t},\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debug.contribution.ts",
"type": "add",
"edit_start_line_idx": 441
}
|
{
"name": "merge-conflict",
"publisher": "vscode",
"displayName": "%displayName%",
"description": "%description%",
"icon": "media/icon.png",
"version": "1.0.0",
"license": "MIT",
"aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255",
"engines": {
"vscode": "^1.5.0"
},
"categories": [
"Other"
],
"capabilities": {
"virtualWorkspaces": true,
"untrustedWorkspaces": {
"supported": true
}
},
"activationEvents": [
"onStartupFinished"
],
"main": "./out/mergeConflictMain",
"browser": "./dist/browser/mergeConflictMain",
"scripts": {
"compile": "gulp compile-extension:merge-conflict",
"watch": "gulp watch-extension:merge-conflict"
},
"contributes": {
"commands": [
{
"category": "%command.category%",
"title": "%command.accept.all-current%",
"original": "Accept All Current",
"command": "merge-conflict.accept.all-current",
"enablement": "!isMergeEditor"
},
{
"category": "%command.category%",
"title": "%command.accept.all-incoming%",
"original": "Accept All Incoming",
"command": "merge-conflict.accept.all-incoming",
"enablement": "!isMergeEditor"
},
{
"category": "%command.category%",
"title": "%command.accept.all-both%",
"original": "Accept All Both",
"command": "merge-conflict.accept.all-both",
"enablement": "!isMergeEditor"
},
{
"category": "%command.category%",
"title": "%command.accept.current%",
"original": "Accept Current",
"command": "merge-conflict.accept.current",
"enablement": "!isMergeEditor"
},
{
"category": "%command.category%",
"title": "%command.accept.incoming%",
"original": "Accept Incoming",
"command": "merge-conflict.accept.incoming",
"enablement": "!isMergeEditor"
},
{
"category": "%command.category%",
"title": "%command.accept.selection%",
"original": "Accept Selection",
"command": "merge-conflict.accept.selection",
"enablement": "!isMergeEditor"
},
{
"category": "%command.category%",
"title": "%command.accept.both%",
"original": "Accept Both",
"command": "merge-conflict.accept.both",
"enablement": "!isMergeEditor"
},
{
"category": "%command.category%",
"title": "%command.next%",
"original": "Next Conflict",
"command": "merge-conflict.next",
"enablement": "!isMergeEditor",
"icon": "$(arrow-down)"
},
{
"category": "%command.category%",
"title": "%command.previous%",
"original": "Previous Conflict",
"command": "merge-conflict.previous",
"enablement": "!isMergeEditor",
"icon": "$(arrow-up)"
},
{
"category": "%command.category%",
"title": "%command.compare%",
"original": "Compare Current Conflict",
"command": "merge-conflict.compare",
"enablement": "!isMergeEditor"
}
],
"menus": {
"scm/resourceState/context": [
{
"command": "merge-conflict.accept.all-current",
"when": "scmProvider == git && scmResourceGroup == merge",
"group": "1_modification"
},
{
"command": "merge-conflict.accept.all-incoming",
"when": "scmProvider == git && scmResourceGroup == merge",
"group": "1_modification"
}
],
"editor/title": [
{
"command": "merge-conflict.previous",
"group": "navigation@1",
"when": "!isMergeEditor && mergeConflictsCount && mergeConflictsCount != 0"
},
{
"command": "merge-conflict.next",
"group": "navigation@2",
"when": "!isMergeEditor && mergeConflictsCount && mergeConflictsCount != 0"
}
]
},
"configuration": {
"title": "%config.title%",
"properties": {
"merge-conflict.codeLens.enabled": {
"type": "boolean",
"description": "%config.codeLensEnabled%",
"default": true
},
"merge-conflict.decorators.enabled": {
"type": "boolean",
"description": "%config.decoratorsEnabled%",
"default": true
},
"merge-conflict.autoNavigateNextConflict.enabled": {
"type": "boolean",
"description": "%config.autoNavigateNextConflictEnabled%",
"default": false
},
"merge-conflict.diffViewPosition": {
"type": "string",
"enum": [
"Current",
"Beside",
"Below"
],
"description": "%config.diffViewPosition%",
"enumDescriptions": [
"%config.diffViewPosition.current%",
"%config.diffViewPosition.beside%",
"%config.diffViewPosition.below%"
],
"default": "Current"
}
}
}
},
"dependencies": {
"@vscode/extension-telemetry": "^0.9.0"
},
"devDependencies": {
"@types/node": "18.x"
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
|
extensions/merge-conflict/package.json
| 0 |
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
|
[
0.00017325083899777383,
0.00017108804604504257,
0.00016733890515752137,
0.00017125012527685612,
0.000001440149276277225
] |
{
"id": 1,
"code_window": [
"import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';\n",
"import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';\n",
"import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace';\n",
"import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';\n",
"import { EditorInput } from 'vs/workbench/common/editor/editorInput';\n",
"import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';\n",
"import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager';\n",
"import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { EditorsOrder } from 'vs/workbench/common/editor';\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "add",
"edit_start_line_idx": 33
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { FileAccess } from 'vs/base/common/network';
import { isMacintosh, isWeb } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/debug.contribution';
import 'vs/css!./media/debugHover';
import { EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import * as nls from 'vs/nls';
import { ICommandActionTitle, Icon } from 'vs/platform/action/common/action';
import { MenuId, MenuRegistry } from 'vs/platform/actions/common/actions';
import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { Extensions as QuickAccessExtensions, IQuickAccessRegistry } from 'vs/platform/quickinput/common/quickAccess';
import { Registry } from 'vs/platform/registry/common/platform';
import { EditorPaneDescriptor, IEditorPaneRegistry } from 'vs/workbench/browser/editor';
import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { EditorExtensions } from 'vs/workbench/common/editor';
import { Extensions as ViewExtensions, IViewContainersRegistry, IViewsRegistry, ViewContainer, ViewContainerLocation } from 'vs/workbench/common/views';
import { BreakpointEditorContribution } from 'vs/workbench/contrib/debug/browser/breakpointEditorContribution';
import { BreakpointsView } from 'vs/workbench/contrib/debug/browser/breakpointsView';
import { CallStackEditorContribution } from 'vs/workbench/contrib/debug/browser/callStackEditorContribution';
import { CallStackView } from 'vs/workbench/contrib/debug/browser/callStackView';
import { registerColors } from 'vs/workbench/contrib/debug/browser/debugColors';
import { ADD_CONFIGURATION_ID, CALLSTACK_BOTTOM_ID, CALLSTACK_BOTTOM_LABEL, CALLSTACK_DOWN_ID, CALLSTACK_DOWN_LABEL, CALLSTACK_TOP_ID, CALLSTACK_TOP_LABEL, CALLSTACK_UP_ID, CALLSTACK_UP_LABEL, CONTINUE_ID, CONTINUE_LABEL, COPY_STACK_TRACE_ID, DEBUG_COMMAND_CATEGORY, DEBUG_CONSOLE_QUICK_ACCESS_PREFIX, DEBUG_QUICK_ACCESS_PREFIX, DEBUG_RUN_COMMAND_ID, DEBUG_RUN_LABEL, DEBUG_START_COMMAND_ID, DEBUG_START_LABEL, DISCONNECT_AND_SUSPEND_ID, DISCONNECT_AND_SUSPEND_LABEL, DISCONNECT_ID, DISCONNECT_LABEL, EDIT_EXPRESSION_COMMAND_ID, FOCUS_REPL_ID, JUMP_TO_CURSOR_ID, NEXT_DEBUG_CONSOLE_ID, NEXT_DEBUG_CONSOLE_LABEL, OPEN_LOADED_SCRIPTS_LABEL, PAUSE_ID, PAUSE_LABEL, PREV_DEBUG_CONSOLE_ID, PREV_DEBUG_CONSOLE_LABEL, REMOVE_EXPRESSION_COMMAND_ID, RESTART_FRAME_ID, RESTART_LABEL, RESTART_SESSION_ID, SELECT_AND_START_ID, SELECT_AND_START_LABEL, SELECT_DEBUG_CONSOLE_ID, SELECT_DEBUG_CONSOLE_LABEL, SELECT_DEBUG_SESSION_ID, SELECT_DEBUG_SESSION_LABEL, SET_EXPRESSION_COMMAND_ID, SHOW_LOADED_SCRIPTS_ID, STEP_INTO_ID, STEP_INTO_LABEL, STEP_INTO_TARGET_ID, STEP_INTO_TARGET_LABEL, STEP_OUT_ID, STEP_OUT_LABEL, STEP_OVER_ID, STEP_OVER_LABEL, STOP_ID, STOP_LABEL, TERMINATE_THREAD_ID, TOGGLE_INLINE_BREAKPOINT_ID } from 'vs/workbench/contrib/debug/browser/debugCommands';
import { DebugConsoleQuickAccess } from 'vs/workbench/contrib/debug/browser/debugConsoleQuickAccess';
import { RunToCursorAction, SelectionToReplAction, SelectionToWatchExpressionsAction } from 'vs/workbench/contrib/debug/browser/debugEditorActions';
import { DebugEditorContribution } from 'vs/workbench/contrib/debug/browser/debugEditorContribution';
import * as icons from 'vs/workbench/contrib/debug/browser/debugIcons';
import { DebugProgressContribution } from 'vs/workbench/contrib/debug/browser/debugProgress';
import { StartDebugQuickAccessProvider } from 'vs/workbench/contrib/debug/browser/debugQuickAccess';
import { DebugService } from 'vs/workbench/contrib/debug/browser/debugService';
import { DebugStatusContribution } from 'vs/workbench/contrib/debug/browser/debugStatus';
import { DebugTitleContribution } from 'vs/workbench/contrib/debug/browser/debugTitle';
import { DebugToolBar } from 'vs/workbench/contrib/debug/browser/debugToolBar';
import { DebugViewPaneContainer } from 'vs/workbench/contrib/debug/browser/debugViewlet';
import { DisassemblyView, DisassemblyViewContribution } from 'vs/workbench/contrib/debug/browser/disassemblyView';
import { LoadedScriptsView } from 'vs/workbench/contrib/debug/browser/loadedScriptsView';
import { Repl } from 'vs/workbench/contrib/debug/browser/repl';
import { StatusBarColorProvider } from 'vs/workbench/contrib/debug/browser/statusbarColorProvider';
import { ADD_TO_WATCH_ID, BREAK_WHEN_VALUE_CHANGES_ID, BREAK_WHEN_VALUE_IS_ACCESSED_ID, BREAK_WHEN_VALUE_IS_READ_ID, COPY_EVALUATE_PATH_ID, COPY_VALUE_ID, SET_VARIABLE_ID, VariablesView, VIEW_MEMORY_ID } from 'vs/workbench/contrib/debug/browser/variablesView';
import { ADD_WATCH_ID, ADD_WATCH_LABEL, REMOVE_WATCH_EXPRESSIONS_COMMAND_ID, REMOVE_WATCH_EXPRESSIONS_LABEL, WatchExpressionsView } from 'vs/workbench/contrib/debug/browser/watchExpressionsView';
import { WelcomeView } from 'vs/workbench/contrib/debug/browser/welcomeView';
import { BREAKPOINTS_VIEW_ID, BREAKPOINT_EDITOR_CONTRIBUTION_ID, CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_BREAK_WHEN_VALUE_CHANGES_SUPPORTED, CONTEXT_BREAK_WHEN_VALUE_IS_ACCESSED_SUPPORTED, CONTEXT_BREAK_WHEN_VALUE_IS_READ_SUPPORTED, CONTEXT_CALLSTACK_ITEM_TYPE, CONTEXT_CAN_VIEW_MEMORY, CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_UX, CONTEXT_FOCUSED_SESSION_IS_ATTACH, CONTEXT_HAS_DEBUGGED, CONTEXT_IN_DEBUG_MODE, CONTEXT_JUMP_TO_CURSOR_SUPPORTED, CONTEXT_LOADED_SCRIPTS_SUPPORTED, CONTEXT_RESTART_FRAME_SUPPORTED, CONTEXT_SET_EXPRESSION_SUPPORTED, CONTEXT_SET_VARIABLE_SUPPORTED, CONTEXT_STACK_FRAME_SUPPORTS_RESTART, CONTEXT_STEP_INTO_TARGETS_SUPPORTED, CONTEXT_SUSPEND_DEBUGGEE_SUPPORTED, CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED, CONTEXT_VARIABLE_EVALUATE_NAME_PRESENT, CONTEXT_VARIABLE_IS_READONLY, CONTEXT_WATCH_ITEM_TYPE, DEBUG_PANEL_ID, DISASSEMBLY_VIEW_ID, EDITOR_CONTRIBUTION_ID, getStateLabel, IDebugService, INTERNAL_CONSOLE_OPTIONS_SCHEMA, LOADED_SCRIPTS_VIEW_ID, REPL_VIEW_ID, State, VARIABLES_VIEW_ID, VIEWLET_ID, WATCH_VIEW_ID } from 'vs/workbench/contrib/debug/common/debug';
import { DebugContentProvider } from 'vs/workbench/contrib/debug/common/debugContentProvider';
import { DebugLifecycle } from 'vs/workbench/contrib/debug/common/debugLifecycle';
import { DisassemblyViewInput } from 'vs/workbench/contrib/debug/common/disassemblyViewInput';
import { launchSchemaId } from 'vs/workbench/services/configuration/common/configuration';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
const debugCategory = nls.localize('debugCategory', "Debug");
registerColors();
registerSingleton(IDebugService, DebugService, InstantiationType.Delayed);
// Register Debug Workbench Contributions
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugStatusContribution, LifecyclePhase.Eventually);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugProgressContribution, LifecyclePhase.Eventually);
if (isWeb) {
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugTitleContribution, LifecyclePhase.Eventually);
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugToolBar, LifecyclePhase.Restored);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugContentProvider, LifecyclePhase.Eventually);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(StatusBarColorProvider, LifecyclePhase.Eventually);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DisassemblyViewContribution, LifecyclePhase.Eventually);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DebugLifecycle, LifecyclePhase.Eventually);
// Register Quick Access
Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess).registerQuickAccessProvider({
ctor: StartDebugQuickAccessProvider,
prefix: DEBUG_QUICK_ACCESS_PREFIX,
contextKey: 'inLaunchConfigurationsPicker',
placeholder: nls.localize('startDebugPlaceholder', "Type the name of a launch configuration to run."),
helpEntries: [{
description: nls.localize('startDebuggingHelp', "Start Debugging"),
commandId: SELECT_AND_START_ID,
commandCenterOrder: 50
}]
});
// Register quick access for debug console
Registry.as<IQuickAccessRegistry>(QuickAccessExtensions.Quickaccess).registerQuickAccessProvider({
ctor: DebugConsoleQuickAccess,
prefix: DEBUG_CONSOLE_QUICK_ACCESS_PREFIX,
contextKey: 'inDebugConsolePicker',
placeholder: nls.localize('tasksQuickAccessPlaceholder', "Type the name of a debug console to open."),
helpEntries: [{ description: nls.localize('tasksQuickAccessHelp', "Show All Debug Consoles"), commandId: SELECT_DEBUG_CONSOLE_ID }]
});
registerEditorContribution('editor.contrib.callStack', CallStackEditorContribution, EditorContributionInstantiation.AfterFirstRender);
registerEditorContribution(BREAKPOINT_EDITOR_CONTRIBUTION_ID, BreakpointEditorContribution, EditorContributionInstantiation.AfterFirstRender);
registerEditorContribution(EDITOR_CONTRIBUTION_ID, DebugEditorContribution, EditorContributionInstantiation.BeforeFirstInteraction);
const registerDebugCommandPaletteItem = (id: string, title: ICommandActionTitle, when?: ContextKeyExpression, precondition?: ContextKeyExpression) => {
MenuRegistry.appendMenuItem(MenuId.CommandPalette, {
when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, when),
group: debugCategory,
command: {
id,
title,
category: DEBUG_COMMAND_CATEGORY,
precondition
}
});
};
registerDebugCommandPaletteItem(RESTART_SESSION_ID, RESTART_LABEL);
registerDebugCommandPaletteItem(TERMINATE_THREAD_ID, nls.localize2('terminateThread', "Terminate Thread"), CONTEXT_IN_DEBUG_MODE);
registerDebugCommandPaletteItem(STEP_OVER_ID, STEP_OVER_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugCommandPaletteItem(STEP_INTO_ID, STEP_INTO_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugCommandPaletteItem(STEP_INTO_TARGET_ID, STEP_INTO_TARGET_LABEL, CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.and(CONTEXT_STEP_INTO_TARGETS_SUPPORTED, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')));
registerDebugCommandPaletteItem(STEP_OUT_ID, STEP_OUT_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugCommandPaletteItem(PAUSE_ID, PAUSE_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('running'));
registerDebugCommandPaletteItem(DISCONNECT_ID, DISCONNECT_LABEL, CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.or(CONTEXT_FOCUSED_SESSION_IS_ATTACH, CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED));
registerDebugCommandPaletteItem(DISCONNECT_AND_SUSPEND_ID, DISCONNECT_AND_SUSPEND_LABEL, CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.or(CONTEXT_FOCUSED_SESSION_IS_ATTACH, ContextKeyExpr.and(CONTEXT_SUSPEND_DEBUGGEE_SUPPORTED, CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED)));
registerDebugCommandPaletteItem(STOP_ID, STOP_LABEL, CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.or(CONTEXT_FOCUSED_SESSION_IS_ATTACH.toNegated(), CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED));
registerDebugCommandPaletteItem(CONTINUE_ID, CONTINUE_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugCommandPaletteItem(FOCUS_REPL_ID, nls.localize2({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugFocusConsole' }, "Focus on Debug Console View"));
registerDebugCommandPaletteItem(JUMP_TO_CURSOR_ID, nls.localize2('jumpToCursor', "Jump to Cursor"), CONTEXT_JUMP_TO_CURSOR_SUPPORTED);
registerDebugCommandPaletteItem(JUMP_TO_CURSOR_ID, nls.localize2('SetNextStatement', "Set Next Statement"), CONTEXT_JUMP_TO_CURSOR_SUPPORTED);
registerDebugCommandPaletteItem(RunToCursorAction.ID, RunToCursorAction.LABEL, CONTEXT_DEBUGGERS_AVAILABLE);
registerDebugCommandPaletteItem(SelectionToReplAction.ID, SelectionToReplAction.LABEL, CONTEXT_IN_DEBUG_MODE);
registerDebugCommandPaletteItem(SelectionToWatchExpressionsAction.ID, SelectionToWatchExpressionsAction.LABEL);
registerDebugCommandPaletteItem(TOGGLE_INLINE_BREAKPOINT_ID, nls.localize2('inlineBreakpoint', "Inline Breakpoint"));
registerDebugCommandPaletteItem(DEBUG_START_COMMAND_ID, DEBUG_START_LABEL, ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.notEqualsTo(getStateLabel(State.Initializing))));
registerDebugCommandPaletteItem(DEBUG_RUN_COMMAND_ID, DEBUG_RUN_LABEL, ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.notEqualsTo(getStateLabel(State.Initializing))));
registerDebugCommandPaletteItem(SELECT_AND_START_ID, SELECT_AND_START_LABEL, ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.notEqualsTo(getStateLabel(State.Initializing))));
registerDebugCommandPaletteItem(NEXT_DEBUG_CONSOLE_ID, NEXT_DEBUG_CONSOLE_LABEL);
registerDebugCommandPaletteItem(PREV_DEBUG_CONSOLE_ID, PREV_DEBUG_CONSOLE_LABEL);
registerDebugCommandPaletteItem(SHOW_LOADED_SCRIPTS_ID, OPEN_LOADED_SCRIPTS_LABEL, CONTEXT_IN_DEBUG_MODE);
registerDebugCommandPaletteItem(SELECT_DEBUG_CONSOLE_ID, SELECT_DEBUG_CONSOLE_LABEL);
registerDebugCommandPaletteItem(SELECT_DEBUG_SESSION_ID, SELECT_DEBUG_SESSION_LABEL);
registerDebugCommandPaletteItem(CALLSTACK_TOP_ID, CALLSTACK_TOP_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugCommandPaletteItem(CALLSTACK_BOTTOM_ID, CALLSTACK_BOTTOM_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugCommandPaletteItem(CALLSTACK_UP_ID, CALLSTACK_UP_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugCommandPaletteItem(CALLSTACK_DOWN_ID, CALLSTACK_DOWN_LABEL, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
// Debug callstack context menu
const registerDebugViewMenuItem = (menuId: MenuId, id: string, title: string | ICommandActionTitle, order: number, when?: ContextKeyExpression, precondition?: ContextKeyExpression, group = 'navigation', icon?: Icon) => {
MenuRegistry.appendMenuItem(menuId, {
group,
when,
order,
icon,
command: {
id,
title,
icon,
precondition
}
});
};
registerDebugViewMenuItem(MenuId.DebugCallStackContext, RESTART_SESSION_ID, RESTART_LABEL, 10, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('session'), undefined, '3_modification');
registerDebugViewMenuItem(MenuId.DebugCallStackContext, DISCONNECT_ID, DISCONNECT_LABEL, 20, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('session'), undefined, '3_modification');
registerDebugViewMenuItem(MenuId.DebugCallStackContext, DISCONNECT_AND_SUSPEND_ID, DISCONNECT_AND_SUSPEND_LABEL, 21, ContextKeyExpr.and(CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('session'), CONTEXT_SUSPEND_DEBUGGEE_SUPPORTED, CONTEXT_TERMINATE_DEBUGGEE_SUPPORTED), undefined, '3_modification');
registerDebugViewMenuItem(MenuId.DebugCallStackContext, STOP_ID, STOP_LABEL, 30, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('session'), undefined, '3_modification');
registerDebugViewMenuItem(MenuId.DebugCallStackContext, PAUSE_ID, PAUSE_LABEL, 10, ContextKeyExpr.and(CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('running')));
registerDebugViewMenuItem(MenuId.DebugCallStackContext, CONTINUE_ID, CONTINUE_LABEL, 10, ContextKeyExpr.and(CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('stopped')));
registerDebugViewMenuItem(MenuId.DebugCallStackContext, STEP_OVER_ID, STEP_OVER_LABEL, 20, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugViewMenuItem(MenuId.DebugCallStackContext, STEP_INTO_ID, STEP_INTO_LABEL, 30, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugViewMenuItem(MenuId.DebugCallStackContext, STEP_OUT_ID, STEP_OUT_LABEL, 40, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), CONTEXT_DEBUG_STATE.isEqualTo('stopped'));
registerDebugViewMenuItem(MenuId.DebugCallStackContext, TERMINATE_THREAD_ID, nls.localize('terminateThread', "Terminate Thread"), 10, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('thread'), undefined, 'termination');
registerDebugViewMenuItem(MenuId.DebugCallStackContext, RESTART_FRAME_ID, nls.localize('restartFrame', "Restart Frame"), 10, ContextKeyExpr.and(CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('stackFrame'), CONTEXT_RESTART_FRAME_SUPPORTED), CONTEXT_STACK_FRAME_SUPPORTS_RESTART);
registerDebugViewMenuItem(MenuId.DebugCallStackContext, COPY_STACK_TRACE_ID, nls.localize('copyStackTrace', "Copy Call Stack"), 20, CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('stackFrame'), undefined, '3_modification');
registerDebugViewMenuItem(MenuId.DebugVariablesContext, VIEW_MEMORY_ID, nls.localize('viewMemory', "View Binary Data"), 15, CONTEXT_CAN_VIEW_MEMORY, CONTEXT_IN_DEBUG_MODE, 'inline', icons.debugInspectMemory);
registerDebugViewMenuItem(MenuId.DebugVariablesContext, SET_VARIABLE_ID, nls.localize('setValue', "Set Value"), 10, ContextKeyExpr.or(CONTEXT_SET_VARIABLE_SUPPORTED, ContextKeyExpr.and(CONTEXT_VARIABLE_EVALUATE_NAME_PRESENT, CONTEXT_SET_EXPRESSION_SUPPORTED)), CONTEXT_VARIABLE_IS_READONLY.toNegated(), '3_modification');
registerDebugViewMenuItem(MenuId.DebugVariablesContext, COPY_VALUE_ID, nls.localize('copyValue', "Copy Value"), 10, undefined, undefined, '5_cutcopypaste');
registerDebugViewMenuItem(MenuId.DebugVariablesContext, COPY_EVALUATE_PATH_ID, nls.localize('copyAsExpression', "Copy as Expression"), 20, CONTEXT_VARIABLE_EVALUATE_NAME_PRESENT, undefined, '5_cutcopypaste');
registerDebugViewMenuItem(MenuId.DebugVariablesContext, ADD_TO_WATCH_ID, nls.localize('addToWatchExpressions', "Add to Watch"), 100, CONTEXT_VARIABLE_EVALUATE_NAME_PRESENT, undefined, 'z_commands');
registerDebugViewMenuItem(MenuId.DebugVariablesContext, BREAK_WHEN_VALUE_IS_READ_ID, nls.localize('breakWhenValueIsRead', "Break on Value Read"), 200, CONTEXT_BREAK_WHEN_VALUE_IS_READ_SUPPORTED, undefined, 'z_commands');
registerDebugViewMenuItem(MenuId.DebugVariablesContext, BREAK_WHEN_VALUE_CHANGES_ID, nls.localize('breakWhenValueChanges', "Break on Value Change"), 210, CONTEXT_BREAK_WHEN_VALUE_CHANGES_SUPPORTED, undefined, 'z_commands');
registerDebugViewMenuItem(MenuId.DebugVariablesContext, BREAK_WHEN_VALUE_IS_ACCESSED_ID, nls.localize('breakWhenValueIsAccessed', "Break on Value Access"), 220, CONTEXT_BREAK_WHEN_VALUE_IS_ACCESSED_SUPPORTED, undefined, 'z_commands');
registerDebugViewMenuItem(MenuId.DebugWatchContext, ADD_WATCH_ID, ADD_WATCH_LABEL, 10, undefined, undefined, '3_modification');
registerDebugViewMenuItem(MenuId.DebugWatchContext, EDIT_EXPRESSION_COMMAND_ID, nls.localize('editWatchExpression', "Edit Expression"), 20, CONTEXT_WATCH_ITEM_TYPE.isEqualTo('expression'), undefined, '3_modification');
registerDebugViewMenuItem(MenuId.DebugWatchContext, SET_EXPRESSION_COMMAND_ID, nls.localize('setValue', "Set Value"), 30, ContextKeyExpr.or(ContextKeyExpr.and(CONTEXT_WATCH_ITEM_TYPE.isEqualTo('expression'), CONTEXT_SET_EXPRESSION_SUPPORTED), ContextKeyExpr.and(CONTEXT_WATCH_ITEM_TYPE.isEqualTo('variable'), CONTEXT_SET_VARIABLE_SUPPORTED)), CONTEXT_VARIABLE_IS_READONLY.toNegated(), '3_modification');
registerDebugViewMenuItem(MenuId.DebugWatchContext, COPY_VALUE_ID, nls.localize('copyValue', "Copy Value"), 40, ContextKeyExpr.or(CONTEXT_WATCH_ITEM_TYPE.isEqualTo('expression'), CONTEXT_WATCH_ITEM_TYPE.isEqualTo('variable')), CONTEXT_IN_DEBUG_MODE, '3_modification');
registerDebugViewMenuItem(MenuId.DebugWatchContext, VIEW_MEMORY_ID, nls.localize('viewMemory', "View Binary Data"), 10, CONTEXT_CAN_VIEW_MEMORY, undefined, 'inline', icons.debugInspectMemory);
registerDebugViewMenuItem(MenuId.DebugWatchContext, REMOVE_EXPRESSION_COMMAND_ID, nls.localize('removeWatchExpression', "Remove Expression"), 20, CONTEXT_WATCH_ITEM_TYPE.isEqualTo('expression'), undefined, 'inline', icons.watchExpressionRemove);
registerDebugViewMenuItem(MenuId.DebugWatchContext, REMOVE_WATCH_EXPRESSIONS_COMMAND_ID, REMOVE_WATCH_EXPRESSIONS_LABEL, 20, undefined, undefined, 'z_commands');
// Touch Bar
if (isMacintosh) {
const registerTouchBarEntry = (id: string, title: string | ICommandActionTitle, order: number, when: ContextKeyExpression | undefined, iconUri: URI) => {
MenuRegistry.appendMenuItem(MenuId.TouchBarContext, {
command: {
id,
title,
icon: { dark: iconUri }
},
when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, when),
group: '9_debug',
order
});
};
registerTouchBarEntry(DEBUG_RUN_COMMAND_ID, DEBUG_RUN_LABEL, 0, CONTEXT_IN_DEBUG_MODE.toNegated(), FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/continue-tb.png'));
registerTouchBarEntry(DEBUG_START_COMMAND_ID, DEBUG_START_LABEL, 1, CONTEXT_IN_DEBUG_MODE.toNegated(), FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/run-with-debugging-tb.png'));
registerTouchBarEntry(CONTINUE_ID, CONTINUE_LABEL, 0, CONTEXT_DEBUG_STATE.isEqualTo('stopped'), FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/continue-tb.png'));
registerTouchBarEntry(PAUSE_ID, PAUSE_LABEL, 1, ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, ContextKeyExpr.notEquals('debugState', 'stopped')), FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/pause-tb.png'));
registerTouchBarEntry(STEP_OVER_ID, STEP_OVER_LABEL, 2, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/stepover-tb.png'));
registerTouchBarEntry(STEP_INTO_ID, STEP_INTO_LABEL, 3, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/stepinto-tb.png'));
registerTouchBarEntry(STEP_OUT_ID, STEP_OUT_LABEL, 4, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/stepout-tb.png'));
registerTouchBarEntry(RESTART_SESSION_ID, RESTART_LABEL, 5, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/restart-tb.png'));
registerTouchBarEntry(STOP_ID, STOP_LABEL, 6, CONTEXT_IN_DEBUG_MODE, FileAccess.asFileUri('vs/workbench/contrib/debug/browser/media/stop-tb.png'));
}
// Editor Title Menu's "Run/Debug" dropdown item
MenuRegistry.appendMenuItem(MenuId.EditorTitle, { submenu: MenuId.EditorTitleRun, rememberDefaultAction: true, title: nls.localize2('run', "Run or Debug..."), icon: icons.debugRun, group: 'navigation', order: -1 });
// Debug menu
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarDebugMenu,
title: {
value: 'Run',
original: 'Run',
mnemonicTitle: nls.localize({ key: 'mRun', comment: ['&& denotes a mnemonic'] }, "&&Run")
},
order: 6
});
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '1_debug',
command: {
id: DEBUG_START_COMMAND_ID,
title: nls.localize({ key: 'miStartDebugging', comment: ['&& denotes a mnemonic'] }, "&&Start Debugging")
},
order: 1,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '1_debug',
command: {
id: DEBUG_RUN_COMMAND_ID,
title: nls.localize({ key: 'miRun', comment: ['&& denotes a mnemonic'] }, "Run &&Without Debugging")
},
order: 2,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '1_debug',
command: {
id: STOP_ID,
title: nls.localize({ key: 'miStopDebugging', comment: ['&& denotes a mnemonic'] }, "&&Stop Debugging"),
precondition: CONTEXT_IN_DEBUG_MODE
},
order: 3,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '1_debug',
command: {
id: RESTART_SESSION_ID,
title: nls.localize({ key: 'miRestart Debugging', comment: ['&& denotes a mnemonic'] }, "&&Restart Debugging"),
precondition: CONTEXT_IN_DEBUG_MODE
},
order: 4,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
// Configuration
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '2_configuration',
command: {
id: ADD_CONFIGURATION_ID,
title: nls.localize({ key: 'miAddConfiguration', comment: ['&& denotes a mnemonic'] }, "A&&dd Configuration...")
},
order: 2,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
// Step Commands
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '3_step',
command: {
id: STEP_OVER_ID,
title: nls.localize({ key: 'miStepOver', comment: ['&& denotes a mnemonic'] }, "Step &&Over"),
precondition: CONTEXT_DEBUG_STATE.isEqualTo('stopped')
},
order: 1,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '3_step',
command: {
id: STEP_INTO_ID,
title: nls.localize({ key: 'miStepInto', comment: ['&& denotes a mnemonic'] }, "Step &&Into"),
precondition: CONTEXT_DEBUG_STATE.isEqualTo('stopped')
},
order: 2,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '3_step',
command: {
id: STEP_OUT_ID,
title: nls.localize({ key: 'miStepOut', comment: ['&& denotes a mnemonic'] }, "Step O&&ut"),
precondition: CONTEXT_DEBUG_STATE.isEqualTo('stopped')
},
order: 3,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '3_step',
command: {
id: CONTINUE_ID,
title: nls.localize({ key: 'miContinue', comment: ['&& denotes a mnemonic'] }, "&&Continue"),
precondition: CONTEXT_DEBUG_STATE.isEqualTo('stopped')
},
order: 4,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
// New Breakpoints
MenuRegistry.appendMenuItem(MenuId.MenubarNewBreakpointMenu, {
group: '1_breakpoints',
command: {
id: TOGGLE_INLINE_BREAKPOINT_ID,
title: nls.localize({ key: 'miInlineBreakpoint', comment: ['&& denotes a mnemonic'] }, "Inline Breakp&&oint")
},
order: 2,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: '4_new_breakpoint',
title: nls.localize({ key: 'miNewBreakpoint', comment: ['&& denotes a mnemonic'] }, "&&New Breakpoint"),
submenu: MenuId.MenubarNewBreakpointMenu,
order: 2,
when: CONTEXT_DEBUGGERS_AVAILABLE
});
// Breakpoint actions are registered from breakpointsView.ts
// Install Debuggers
MenuRegistry.appendMenuItem(MenuId.MenubarDebugMenu, {
group: 'z_install',
command: {
id: 'debug.installAdditionalDebuggers',
title: nls.localize({ key: 'miInstallAdditionalDebuggers', comment: ['&& denotes a mnemonic'] }, "&&Install Additional Debuggers...")
},
order: 1
});
// register repl panel
const VIEW_CONTAINER: ViewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({
id: DEBUG_PANEL_ID,
title: nls.localize2({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugPanel' }, "Debug Console"),
icon: icons.debugConsoleViewIcon,
ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [DEBUG_PANEL_ID, { mergeViewWithContainerWhenSingleView: true }]),
storageId: DEBUG_PANEL_ID,
hideIfEmpty: true,
order: 2,
}, ViewContainerLocation.Panel, { doNotRegisterOpenCommand: true });
Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([{
id: REPL_VIEW_ID,
name: nls.localize2({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugPanel' }, "Debug Console"),
containerIcon: icons.debugConsoleViewIcon,
canToggleVisibility: false,
canMoveView: true,
when: CONTEXT_DEBUGGERS_AVAILABLE,
ctorDescriptor: new SyncDescriptor(Repl),
openCommandActionDescriptor: {
id: 'workbench.debug.action.toggleRepl',
mnemonicTitle: nls.localize({ key: 'miToggleDebugConsole', comment: ['&& denotes a mnemonic'] }, "De&&bug Console"),
keybindings: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyY },
order: 2
}
}], VIEW_CONTAINER);
const viewContainer = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry).registerViewContainer({
id: VIEWLET_ID,
title: nls.localize2('run and debug', "Run and Debug"),
openCommandActionDescriptor: {
id: VIEWLET_ID,
mnemonicTitle: nls.localize({ key: 'miViewRun', comment: ['&& denotes a mnemonic'] }, "&&Run"),
keybindings: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyD },
order: 3
},
ctorDescriptor: new SyncDescriptor(DebugViewPaneContainer),
icon: icons.runViewIcon,
alwaysUseContainerInfo: true,
order: 3,
}, ViewContainerLocation.Sidebar);
// Register default debug views
const viewsRegistry = Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry);
viewsRegistry.registerViews([{ id: VARIABLES_VIEW_ID, name: nls.localize2('variables', "Variables"), containerIcon: icons.variablesViewIcon, ctorDescriptor: new SyncDescriptor(VariablesView), order: 10, weight: 40, canToggleVisibility: true, canMoveView: true, focusCommand: { id: 'workbench.debug.action.focusVariablesView' }, when: CONTEXT_DEBUG_UX.isEqualTo('default') }], viewContainer);
viewsRegistry.registerViews([{ id: WATCH_VIEW_ID, name: nls.localize2('watch', "Watch"), containerIcon: icons.watchViewIcon, ctorDescriptor: new SyncDescriptor(WatchExpressionsView), order: 20, weight: 10, canToggleVisibility: true, canMoveView: true, focusCommand: { id: 'workbench.debug.action.focusWatchView' }, when: CONTEXT_DEBUG_UX.isEqualTo('default') }], viewContainer);
viewsRegistry.registerViews([{ id: CALLSTACK_VIEW_ID, name: nls.localize2('callStack', "Call Stack"), containerIcon: icons.callStackViewIcon, ctorDescriptor: new SyncDescriptor(CallStackView), order: 30, weight: 30, canToggleVisibility: true, canMoveView: true, focusCommand: { id: 'workbench.debug.action.focusCallStackView' }, when: CONTEXT_DEBUG_UX.isEqualTo('default') }], viewContainer);
viewsRegistry.registerViews([{ id: BREAKPOINTS_VIEW_ID, name: nls.localize2('breakpoints', "Breakpoints"), containerIcon: icons.breakpointsViewIcon, ctorDescriptor: new SyncDescriptor(BreakpointsView), order: 40, weight: 20, canToggleVisibility: true, canMoveView: true, focusCommand: { id: 'workbench.debug.action.focusBreakpointsView' }, when: ContextKeyExpr.or(CONTEXT_BREAKPOINTS_EXIST, CONTEXT_DEBUG_UX.isEqualTo('default'), CONTEXT_HAS_DEBUGGED) }], viewContainer);
viewsRegistry.registerViews([{ id: WelcomeView.ID, name: WelcomeView.LABEL, containerIcon: icons.runViewIcon, ctorDescriptor: new SyncDescriptor(WelcomeView), order: 1, weight: 40, canToggleVisibility: true, when: CONTEXT_DEBUG_UX.isEqualTo('simple') }], viewContainer);
viewsRegistry.registerViews([{ id: LOADED_SCRIPTS_VIEW_ID, name: nls.localize2('loadedScripts', "Loaded Scripts"), containerIcon: icons.loadedScriptsViewIcon, ctorDescriptor: new SyncDescriptor(LoadedScriptsView), order: 35, weight: 5, canToggleVisibility: true, canMoveView: true, collapsed: true, when: ContextKeyExpr.and(CONTEXT_LOADED_SCRIPTS_SUPPORTED, CONTEXT_DEBUG_UX.isEqualTo('default')) }], viewContainer);
// Register disassembly view
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
EditorPaneDescriptor.create(DisassemblyView, DISASSEMBLY_VIEW_ID, nls.localize('disassembly', "Disassembly")),
[new SyncDescriptor(DisassemblyViewInput)]
);
// Register configuration
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
configurationRegistry.registerConfiguration({
id: 'debug',
order: 20,
title: nls.localize('debugConfigurationTitle', "Debug"),
type: 'object',
properties: {
'debug.allowBreakpointsEverywhere': {
type: 'boolean',
description: nls.localize({ comment: ['This is the description for a setting'], key: 'allowBreakpointsEverywhere' }, "Allow setting breakpoints in any file."),
default: false
},
'debug.openExplorerOnEnd': {
type: 'boolean',
description: nls.localize({ comment: ['This is the description for a setting'], key: 'openExplorerOnEnd' }, "Automatically open the explorer view at the end of a debug session."),
default: false
},
'debug.inlineValues': {
type: 'string',
'enum': ['on', 'off', 'auto'],
description: nls.localize({ comment: ['This is the description for a setting'], key: 'inlineValues' }, "Show variable values inline in editor while debugging."),
'enumDescriptions': [
nls.localize('inlineValues.on', "Always show variable values inline in editor while debugging."),
nls.localize('inlineValues.off', "Never show variable values inline in editor while debugging."),
nls.localize('inlineValues.focusNoScroll', "Show variable values inline in editor while debugging when the language supports inline value locations."),
],
default: 'auto'
},
'debug.toolBarLocation': {
enum: ['floating', 'docked', 'commandCenter', 'hidden'],
markdownDescription: nls.localize({ comment: ['This is the description for a setting'], key: 'toolBarLocation' }, "Controls the location of the debug toolbar. Either `floating` in all views, `docked` in the debug view, `commandCenter` (requires `{0}`), or `hidden`.", '#window.commandCenter#'),
default: 'floating',
markdownEnumDescriptions: [
nls.localize('debugToolBar.floating', "Show debug toolbar in all views."),
nls.localize('debugToolBar.docked', "Show debug toolbar only in debug views."),
nls.localize('debugToolBar.commandCenter', "`(Experimental)` Show debug toolbar in the command center."),
nls.localize('debugToolBar.hidden', "Do not show debug toolbar."),
]
},
'debug.showInStatusBar': {
enum: ['never', 'always', 'onFirstSessionStart'],
enumDescriptions: [nls.localize('never', "Never show debug in Status bar"), nls.localize('always', "Always show debug in Status bar"), nls.localize('onFirstSessionStart', "Show debug in Status bar only after debug was started for the first time")],
description: nls.localize({ comment: ['This is the description for a setting'], key: 'showInStatusBar' }, "Controls when the debug Status bar should be visible."),
default: 'onFirstSessionStart'
},
'debug.internalConsoleOptions': INTERNAL_CONSOLE_OPTIONS_SCHEMA,
'debug.console.closeOnEnd': {
type: 'boolean',
description: nls.localize('debug.console.closeOnEnd', "Controls if the Debug Console should be automatically closed when the debug session ends."),
default: false
},
'debug.terminal.clearBeforeReusing': {
type: 'boolean',
description: nls.localize({ comment: ['This is the description for a setting'], key: 'debug.terminal.clearBeforeReusing' }, "Before starting a new debug session in an integrated or external terminal, clear the terminal."),
default: false
},
'debug.openDebug': {
enum: ['neverOpen', 'openOnSessionStart', 'openOnFirstSessionStart', 'openOnDebugBreak'],
default: 'openOnDebugBreak',
description: nls.localize('openDebug', "Controls when the debug view should open.")
},
'debug.showSubSessionsInToolBar': {
type: 'boolean',
description: nls.localize({ comment: ['This is the description for a setting'], key: 'showSubSessionsInToolBar' }, "Controls whether the debug sub-sessions are shown in the debug tool bar. When this setting is false the stop command on a sub-session will also stop the parent session."),
default: false
},
'debug.console.fontSize': {
type: 'number',
description: nls.localize('debug.console.fontSize', "Controls the font size in pixels in the Debug Console."),
default: isMacintosh ? 12 : 14,
},
'debug.console.fontFamily': {
type: 'string',
description: nls.localize('debug.console.fontFamily', "Controls the font family in the Debug Console."),
default: 'default'
},
'debug.console.lineHeight': {
type: 'number',
description: nls.localize('debug.console.lineHeight', "Controls the line height in pixels in the Debug Console. Use 0 to compute the line height from the font size."),
default: 0
},
'debug.console.wordWrap': {
type: 'boolean',
description: nls.localize('debug.console.wordWrap', "Controls if the lines should wrap in the Debug Console."),
default: true
},
'debug.console.historySuggestions': {
type: 'boolean',
description: nls.localize('debug.console.historySuggestions', "Controls if the Debug Console should suggest previously typed input."),
default: true
},
'debug.console.collapseIdenticalLines': {
type: 'boolean',
description: nls.localize('debug.console.collapseIdenticalLines', "Controls if the Debug Console should collapse identical lines and show a number of occurrences with a badge."),
default: true
},
'debug.console.acceptSuggestionOnEnter': {
enum: ['off', 'on'],
description: nls.localize('debug.console.acceptSuggestionOnEnter', "Controls whether suggestions should be accepted on Enter in the Debug Console. Enter is also used to evaluate whatever is typed in the Debug Console."),
default: 'off'
},
'launch': {
type: 'object',
description: nls.localize({ comment: ['This is the description for a setting'], key: 'launch' }, "Global debug launch configuration. Should be used as an alternative to 'launch.json' that is shared across workspaces."),
default: { configurations: [], compounds: [] },
$ref: launchSchemaId
},
'debug.focusWindowOnBreak': {
type: 'boolean',
description: nls.localize('debug.focusWindowOnBreak', "Controls whether the workbench window should be focused when the debugger breaks."),
default: true
},
'debug.focusEditorOnBreak': {
type: 'boolean',
description: nls.localize('debug.focusEditorOnBreak', "Controls whether the editor should be focused when the debugger breaks."),
default: true
},
'debug.onTaskErrors': {
enum: ['debugAnyway', 'showErrors', 'prompt', 'abort'],
enumDescriptions: [nls.localize('debugAnyway', "Ignore task errors and start debugging."), nls.localize('showErrors', "Show the Problems view and do not start debugging."), nls.localize('prompt', "Prompt user."), nls.localize('cancel', "Cancel debugging.")],
description: nls.localize('debug.onTaskErrors', "Controls what to do when errors are encountered after running a preLaunchTask."),
default: 'prompt'
},
'debug.showBreakpointsInOverviewRuler': {
type: 'boolean',
description: nls.localize({ comment: ['This is the description for a setting'], key: 'showBreakpointsInOverviewRuler' }, "Controls whether breakpoints should be shown in the overview ruler."),
default: false
},
'debug.showInlineBreakpointCandidates': {
type: 'boolean',
description: nls.localize({ comment: ['This is the description for a setting'], key: 'showInlineBreakpointCandidates' }, "Controls whether inline breakpoints candidate decorations should be shown in the editor while debugging."),
default: true
},
'debug.saveBeforeStart': {
description: nls.localize('debug.saveBeforeStart', "Controls what editors to save before starting a debug session."),
enum: ['allEditorsInActiveGroup', 'nonUntitledEditorsInActiveGroup', 'none'],
enumDescriptions: [
nls.localize('debug.saveBeforeStart.allEditorsInActiveGroup', "Save all editors in the active group before starting a debug session."),
nls.localize('debug.saveBeforeStart.nonUntitledEditorsInActiveGroup', "Save all editors in the active group except untitled ones before starting a debug session."),
nls.localize('debug.saveBeforeStart.none', "Don't save any editors before starting a debug session."),
],
default: 'allEditorsInActiveGroup',
scope: ConfigurationScope.LANGUAGE_OVERRIDABLE
},
'debug.confirmOnExit': {
description: nls.localize('debug.confirmOnExit', "Controls whether to confirm when the window closes if there are active debug sessions."),
type: 'string',
enum: ['never', 'always'],
enumDescriptions: [
nls.localize('debug.confirmOnExit.never', "Never confirm."),
nls.localize('debug.confirmOnExit.always', "Always confirm if there are debug sessions."),
],
default: 'never'
},
'debug.disassemblyView.showSourceCode': {
type: 'boolean',
default: true,
description: nls.localize('debug.disassemblyView.showSourceCode', "Show Source Code in Disassembly View.")
},
'debug.autoExpandLazyVariables': {
type: 'boolean',
default: false,
description: nls.localize('debug.autoExpandLazyVariables', "Automatically show values for variables that are lazily resolved by the debugger, such as getters.")
},
'debug.enableStatusBarColor': {
type: 'boolean',
description: nls.localize('debug.enableStatusBarColor', "Color of the Status bar when debugger is active."),
default: true
},
'debug.hideLauncherWhileDebugging': {
type: 'boolean',
markdownDescription: nls.localize({ comment: ['This is the description for a setting'], key: 'debug.hideLauncherWhileDebugging' }, "Hide 'Start Debugging' control in title bar of 'Run and Debug' view while debugging is active. Only relevant when `{0}` is not `docked`.", '#debug.toolBarLocation#'),
default: false
}
}
});
|
src/vs/workbench/contrib/debug/browser/debug.contribution.ts
| 1 |
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
|
[
0.005293577443808317,
0.000344474014127627,
0.0001636296947253868,
0.00017200512229464948,
0.0007631342159584165
] |
{
"id": 1,
"code_window": [
"import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';\n",
"import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';\n",
"import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace';\n",
"import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';\n",
"import { EditorInput } from 'vs/workbench/common/editor/editorInput';\n",
"import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';\n",
"import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager';\n",
"import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { EditorsOrder } from 'vs/workbench/common/editor';\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "add",
"edit_start_line_idx": 33
}
|
# Git static contributions and remote repository picker
**Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled.
## Features
Git static contributions and remote repository picker.
## API
The Git extension exposes an API, reachable by any other extension.
1. Copy `src/api/git-base.d.ts` to your extension's sources;
2. Include `git-base.d.ts` in your extension's compilation.
3. Get a hold of the API with the following snippet:
```ts
const gitBaseExtension = vscode.extensions.getExtension<GitBaseExtension>('vscode.git-base').exports;
const git = gitBaseExtension.getAPI(1);
```
|
extensions/git-base/README.md
| 0 |
https://github.com/microsoft/vscode/commit/41ca350393f47f56385c7b9b9d31fb6b9f1d6115
|
[
0.00017520130495540798,
0.0001727180788293481,
0.00016957009211182594,
0.0001733828685246408,
0.0000023464992864319356
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.