hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 5, "code_window": [ "/// <reference path=\"../../../../../lib/vscode/src/typings/node-pty.d.ts\" />\n", "import { EventEmitter } from \"events\";\n", "import * as pty from \"node-pty\";\n", "import { ServerProxy } from \"../../common/proxy\";\n", "import { preserveEnv } from \"../../common/util\";\n", "\n", "// tslint:disable completed-docs\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"../../common/util\";\n" ], "file_path": "packages/protocol/src/node/modules/node-pty.ts", "type": "replace", "edit_start_line_idx": 4 }
out cli* !cli.ts build resources # This file is generated when the binary is created. # We want to use the parent tsconfig so we can ignore it. tsconfig.json
packages/server/.gitignore
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0001647800236241892, 0.0001647800236241892, 0.0001647800236241892, 0.0001647800236241892, 0 ]
{ "id": 5, "code_window": [ "/// <reference path=\"../../../../../lib/vscode/src/typings/node-pty.d.ts\" />\n", "import { EventEmitter } from \"events\";\n", "import * as pty from \"node-pty\";\n", "import { ServerProxy } from \"../../common/proxy\";\n", "import { preserveEnv } from \"../../common/util\";\n", "\n", "// tslint:disable completed-docs\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"../../common/util\";\n" ], "file_path": "packages/protocol/src/node/modules/node-pty.ts", "type": "replace", "edit_start_line_idx": 4 }
import * as cp from "child_process"; import * as path from "path"; import * as fs from "fs"; import * as os from "os"; import { fromTar, RequireFS, fromZip } from "../src/requirefs"; export const isMac = os.platform() === "darwin"; /** * Encapsulates a RequireFS Promise and the * name of the test case it will be used in. */ interface TestCase { rfs: Promise<RequireFS>; name: string; } /** * TestCaseArray allows tests and benchmarks to share * test cases while limiting redundancy. */ export class TestCaseArray { private cases: Array<TestCase> = []; constructor(cases?: Array<TestCase>) { if (!cases) { this.cases = TestCaseArray.defaults(); return } this.cases = cases; } /** * Returns default test cases. MacOS users need to have `gtar` binary * in order to run GNU-tar tests and benchmarks. */ public static defaults(): Array<TestCase> { let cases: Array<TestCase> = [ TestCaseArray.newCase("cd lib && zip -r ../lib.zip ./*", "lib.zip", async (c) => fromZip(c), "zip"), TestCaseArray.newCase("cd lib && bsdtar cvf ../lib.tar ./*", "lib.tar", async (c) => fromTar(c), "bsdtar"), ]; if (isMac) { const gtarInstalled: boolean = cp.execSync("which tar").length > 0; if (gtarInstalled) { cases.push(TestCaseArray.newCase("cd lib && gtar cvf ../lib.tar ./*", "lib.tar", async (c) => fromTar(c), "gtar")); } else { throw new Error("failed to setup gtar test case, gtar binary is necessary to test GNU-tar on MacOS"); } } else { cases.push(TestCaseArray.newCase("cd lib && tar cvf ../lib.tar ./*", "lib.tar", async (c) => fromTar(c), "tar")); } return cases; }; /** * Returns a test case prepared with the provided RequireFS Promise. * @param command Command to run immediately. For setup. * @param targetFile File to be read and handled by prepare function. * @param prepare Run on target file contents before test. * @param name Test case name. */ public static newCase(command: string, targetFile: string, prepare: (content: Uint8Array) => Promise<RequireFS>, name: string): TestCase { cp.execSync(command, { cwd: __dirname }); const content = fs.readFileSync(path.join(__dirname, targetFile)); return { name, rfs: prepare(content), }; } /** * Returns updated TestCaseArray instance, with a new test case. * @see TestCaseArray.newCase */ public add(command: string, targetFile: string, prepare: (content: Uint8Array) => Promise<RequireFS>, name: string): TestCaseArray { this.cases.push(TestCaseArray.newCase(command, targetFile, prepare, name)); return this; }; /** * Gets a test case by index. * @param id Test case index. */ public byID(id: number): TestCase { if (!this.cases[id]) { if (id < 0 || id >= this.cases.length) { throw new Error(`test case index "${id}" out of bounds`); } throw new Error(`test case at index "${id}" not found`); } return this.cases[id]; } /** * Gets a test case by name. * @param name Test case name. */ public byName(name: string): TestCase { let c = this.cases.find((c) => c.name === name); if (!c) { throw new Error(`test case "${name}" not found`); } return c; } /** * Gets the number of test cases. */ public length(): number { return this.cases.length; } }
packages/requirefs/test/requirefs.util.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017696300346869975, 0.0001705186441540718, 0.00016252628120128065, 0.00017177041445393115, 0.000004487989826884586 ]
{ "id": 6, "code_window": [ " */\n", "export class NodePtyModuleProxy {\n", "\tpublic async spawn(file: string, args: string[] | string, options: pty.IPtyForkOptions): Promise<NodePtyProcessProxy> {\n", "\t\tpreserveEnv(options);\n", "\n", "\t\treturn new NodePtyProcessProxy(require(\"node-pty\").spawn(file, args, options));\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\treturn new NodePtyProcessProxy(require(\"node-pty\").spawn(file, args, withEnv(options)));\n" ], "file_path": "packages/protocol/src/node/modules/node-pty.ts", "type": "replace", "edit_start_line_idx": 68 }
/// <reference path="../../../../../lib/vscode/src/typings/node-pty.d.ts" /> import { EventEmitter } from "events"; import * as pty from "node-pty"; import { ServerProxy } from "../../common/proxy"; import { preserveEnv } from "../../common/util"; // tslint:disable completed-docs /** * Server-side IPty proxy. */ export class NodePtyProcessProxy extends ServerProxy { public constructor(private readonly process: pty.IPty) { super({ bindEvents: ["process", "data", "exit"], doneEvents: ["exit"], instance: new EventEmitter(), }); this.process.on("data", (data) => this.instance.emit("data", data)); this.process.on("exit", (exitCode, signal) => this.instance.emit("exit", exitCode, signal)); let name = process.process; setTimeout(() => { // Need to wait for the caller to listen to the event. this.instance.emit("process", name); }, 1); const timer = setInterval(() => { if (process.process !== name) { name = process.process; this.instance.emit("process", name); } }, 200); this.process.on("exit", () => clearInterval(timer)); } public async getPid(): Promise<number> { return this.process.pid; } public async getProcess(): Promise<string> { return this.process.process; } public async kill(signal?: string): Promise<void> { this.process.kill(signal); } public async resize(columns: number, rows: number): Promise<void> { this.process.resize(columns, rows); } public async write(data: string): Promise<void> { this.process.write(data); } public async dispose(): Promise<void> { this.process.kill(); setTimeout(() => this.process.kill("SIGKILL"), 5000); // Double tap. await super.dispose(); } } /** * Server-side node-pty proxy. */ export class NodePtyModuleProxy { public async spawn(file: string, args: string[] | string, options: pty.IPtyForkOptions): Promise<NodePtyProcessProxy> { preserveEnv(options); return new NodePtyProcessProxy(require("node-pty").spawn(file, args, options)); } }
packages/protocol/src/node/modules/node-pty.ts
1
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.9895323514938354, 0.18202823400497437, 0.0001668796903686598, 0.00017315213335677981, 0.3408568799495697 ]
{ "id": 6, "code_window": [ " */\n", "export class NodePtyModuleProxy {\n", "\tpublic async spawn(file: string, args: string[] | string, options: pty.IPtyForkOptions): Promise<NodePtyProcessProxy> {\n", "\t\tpreserveEnv(options);\n", "\n", "\t\treturn new NodePtyProcessProxy(require(\"node-pty\").spawn(file, args, options));\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\treturn new NodePtyProcessProxy(require(\"node-pty\").spawn(file, args, withEnv(options)));\n" ], "file_path": "packages/protocol/src/node/modules/node-pty.ts", "type": "replace", "edit_start_line_idx": 68 }
class Watchdog { public start(): void { // No action required. } } export = new Watchdog();
packages/vscode/src/fill/native-watchdog.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017363335064146668, 0.00017363335064146668, 0.00017363335064146668, 0.00017363335064146668, 0 ]
{ "id": 6, "code_window": [ " */\n", "export class NodePtyModuleProxy {\n", "\tpublic async spawn(file: string, args: string[] | string, options: pty.IPtyForkOptions): Promise<NodePtyProcessProxy> {\n", "\t\tpreserveEnv(options);\n", "\n", "\t\treturn new NodePtyProcessProxy(require(\"node-pty\").spawn(file, args, options));\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\treturn new NodePtyProcessProxy(require(\"node-pty\").spawn(file, args, withEnv(options)));\n" ], "file_path": "packages/protocol/src/node/modules/node-pty.ts", "type": "replace", "edit_start_line_idx": 68 }
import { RequireFS } from "../src/requirefs"; import { TestCaseArray, isMac } from "./requirefs.util"; const toTest = new TestCaseArray(); describe("requirefs", () => { for (let i = 0; i < toTest.length(); i++) { const testCase = toTest.byID(i); if (!isMac && testCase.name === "gtar") { break; } if (isMac && testCase.name === "tar") { break; } describe(testCase.name, () => { let rfs: RequireFS; beforeAll(async () => { rfs = await testCase.rfs; }); it("should parse individual module", () => { expect(rfs.require("./individual.js").frog).toEqual("hi"); }); it("should parse chained modules", () => { expect(rfs.require("./chained-1").text).toEqual("moo"); }); it("should parse through subfolders", () => { expect(rfs.require("./subfolder").orangeColor).toEqual("blue"); }); it("should be able to move up directories", () => { expect(rfs.require("./subfolder/goingUp").frog).toEqual("hi"); }); it("should resolve node_modules", () => { expect(rfs.require("./nodeResolve").banana).toEqual("potato"); }); it("should access global scope", () => { // tslint:disable-next-line no-any for testing (window as any).coder = { test: "hi", }; expect(rfs.require("./scope")).toEqual("hi"); }); it("should find custom module", () => { rfs.provide("donkey", "ok"); expect(rfs.require("./customModule")).toEqual("ok"); }); }); } });
packages/requirefs/test/requirefs.test.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017782600480131805, 0.00017579109407961369, 0.00017438361828681082, 0.0001755886769387871, 0.0000012508498912211508 ]
{ "id": 6, "code_window": [ " */\n", "export class NodePtyModuleProxy {\n", "\tpublic async spawn(file: string, args: string[] | string, options: pty.IPtyForkOptions): Promise<NodePtyProcessProxy> {\n", "\t\tpreserveEnv(options);\n", "\n", "\t\treturn new NodePtyProcessProxy(require(\"node-pty\").spawn(file, args, options));\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\treturn new NodePtyProcessProxy(require(\"node-pty\").spawn(file, args, withEnv(options)));\n" ], "file_path": "packages/protocol/src/node/modules/node-pty.ts", "type": "replace", "edit_start_line_idx": 68 }
# code-server [!["Open Issues"](https://img.shields.io/github/issues-raw/cdr/code-server.svg)](https://github.com/cdr/code-server/issues) [!["Latest Release"](https://img.shields.io/github/release/cdr/code-server.svg)](https://github.com/cdr/code-server/releases/latest) [![MIT license](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/codercom/code-server/blob/master/LICENSE) [![Discord](https://img.shields.io/discord/463752820026376202.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/zxSwN8Z) `code-server` is [VS Code](https://github.com/Microsoft/vscode) running on a remote server, accessible through the browser. Try it out: ```bash docker run -it -p 127.0.0.1:8443:8443 -v "${PWD}:/home/coder/project" codercom/code-server --allow-http --no-auth ``` - Code on your Chromebook, tablet, and laptop with a consistent dev environment. - If you have a Windows or Mac workstation, more easily develop for Linux. - Take advantage of large cloud servers to speed up tests, compilations, downloads, and more. - Preserve battery life when you're on the go. - All intensive computation runs on your server. - You're no longer running excess instances of Chrome. ![Screenshot](/doc/assets/ide.png) ## Getting Started ### Run over SSH Use [sshcode](https://github.com/codercom/sshcode) for a simple setup. ### Docker See docker oneliner mentioned above. Dockerfile is at [/Dockerfile](/Dockerfile). ### Binaries 1. [Download a binary](https://github.com/codercom/code-server/releases) (Linux and OS X supported. Windows coming soon) 2. Start the binary with the project directory as the first argument ``` code-server <initial directory to open> ``` > You will be prompted to enter the password shown in the CLI `code-server` should now be running at https://localhost:8443. > code-server uses a self-signed SSL certificate that may prompt your browser to ask you some additional questions before you proceed. Please [read here](doc/self-hosted/index.md) for more information. For detailed instructions and troubleshooting, see the [self-hosted quick start guide](doc/self-hosted/index.md). Quickstart guides for [Google Cloud](doc/admin/install/google_cloud.md), [AWS](doc/admin/install/aws.md), and [DigitalOcean](doc/admin/install/digitalocean.md). How to [secure your setup](/doc/security/ssl.md). ## Development ### Known Issues - Creating custom VS Code extensions and debugging them doesn't work. ### Future - **Stay up to date!** Get notified about new releases of code-server. ![Screenshot](/doc/assets/release.gif) - Windows support. - Electron and Chrome OS applications to bridge the gap between local<->remote. - Run VS Code unit tests against our builds to ensure features work as expected. ### Extensions At the moment we can't use the official VSCode Marketplace. We've created a custom extension marketplace focused around open-sourced extensions. However, if you have access to the `.vsix` file, you can manually install the extension. ## Telemetry Use the `--disable-telemetry` flag or set `DISABLE_TELEMETRY=true` to disable tracking ENTIRELY. We use data collected to improve code-server. ## Contributing Development guides are coming soon. ## License [MIT](LICENSE) ## Enterprise Visit [our enterprise page](https://coder.com/enterprise) for more information about our enterprise offering. ## Commercialization If you would like to commercialize code-server, please contact [email protected].
README.md
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0001785280037438497, 0.00017120109987445176, 0.00016489853442180902, 0.0001715066027827561, 0.000004342947704571998 ]
{ "id": 7, "code_window": [ "import { field, logger } from \"@coder/logger\";\n", "import { ServerMessage, SharedProcessActive } from \"@coder/protocol/src/proto\";\n", "import { preserveEnv } from \"@coder/protocol\";\n", "import { ChildProcess, fork, ForkOptions } from \"child_process\";\n", "import { randomFillSync } from \"crypto\";\n", "import * as fs from \"fs\";\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"@coder/protocol\";\n" ], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 2 }
/// <reference path="../../../../../lib/vscode/src/typings/node-pty.d.ts" /> import { EventEmitter } from "events"; import * as pty from "node-pty"; import { ServerProxy } from "../../common/proxy"; import { preserveEnv } from "../../common/util"; // tslint:disable completed-docs /** * Server-side IPty proxy. */ export class NodePtyProcessProxy extends ServerProxy { public constructor(private readonly process: pty.IPty) { super({ bindEvents: ["process", "data", "exit"], doneEvents: ["exit"], instance: new EventEmitter(), }); this.process.on("data", (data) => this.instance.emit("data", data)); this.process.on("exit", (exitCode, signal) => this.instance.emit("exit", exitCode, signal)); let name = process.process; setTimeout(() => { // Need to wait for the caller to listen to the event. this.instance.emit("process", name); }, 1); const timer = setInterval(() => { if (process.process !== name) { name = process.process; this.instance.emit("process", name); } }, 200); this.process.on("exit", () => clearInterval(timer)); } public async getPid(): Promise<number> { return this.process.pid; } public async getProcess(): Promise<string> { return this.process.process; } public async kill(signal?: string): Promise<void> { this.process.kill(signal); } public async resize(columns: number, rows: number): Promise<void> { this.process.resize(columns, rows); } public async write(data: string): Promise<void> { this.process.write(data); } public async dispose(): Promise<void> { this.process.kill(); setTimeout(() => this.process.kill("SIGKILL"), 5000); // Double tap. await super.dispose(); } } /** * Server-side node-pty proxy. */ export class NodePtyModuleProxy { public async spawn(file: string, args: string[] | string, options: pty.IPtyForkOptions): Promise<NodePtyProcessProxy> { preserveEnv(options); return new NodePtyProcessProxy(require("node-pty").spawn(file, args, options)); } }
packages/protocol/src/node/modules/node-pty.ts
1
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.000267105147941038, 0.00018287792045157403, 0.00016583593969698995, 0.00017095974180847406, 0.00003192580697941594 ]
{ "id": 7, "code_window": [ "import { field, logger } from \"@coder/logger\";\n", "import { ServerMessage, SharedProcessActive } from \"@coder/protocol/src/proto\";\n", "import { preserveEnv } from \"@coder/protocol\";\n", "import { ChildProcess, fork, ForkOptions } from \"child_process\";\n", "import { randomFillSync } from \"crypto\";\n", "import * as fs from \"fs\";\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"@coder/protocol\";\n" ], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 2 }
import { OperatingSystem, InitData } from "@coder/protocol"; import { client } from "./client"; class OS { private _homedir: string | undefined; private _tmpdir: string | undefined; private _platform: NodeJS.Platform | undefined; public constructor() { client.initData.then((d) => this.initialize(d)); } public homedir(): string { if (typeof this._homedir === "undefined") { throw new Error("trying to access homedir before it has been set"); } return this._homedir; } public tmpdir(): string { if (typeof this._tmpdir === "undefined") { throw new Error("trying to access tmpdir before it has been set"); } return this._tmpdir; } public initialize(data: InitData): void { this._homedir = data.homeDirectory; this._tmpdir = data.tmpDirectory; switch (data.os) { case OperatingSystem.Windows: this._platform = "win32"; break; case OperatingSystem.Mac: this._platform = "darwin"; break; default: this._platform = "linux"; break; } process.platform = this._platform; } public release(): string { return "Unknown"; } public platform(): NodeJS.Platform { if (typeof this._platform === "undefined") { throw new Error("trying to access platform before it has been set"); } return this._platform; } } export = new OS();
packages/ide/src/fill/os.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00021133733389433473, 0.00017833879974205047, 0.00016777012206148356, 0.00017297193699050695, 0.000014959732652641833 ]
{ "id": 7, "code_window": [ "import { field, logger } from \"@coder/logger\";\n", "import { ServerMessage, SharedProcessActive } from \"@coder/protocol/src/proto\";\n", "import { preserveEnv } from \"@coder/protocol\";\n", "import { ChildProcess, fork, ForkOptions } from \"child_process\";\n", "import { randomFillSync } from \"crypto\";\n", "import * as fs from \"fs\";\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"@coder/protocol\";\n" ], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 2 }
!lib/node_modules *.tar *.zip
packages/requirefs/test/.gitignore
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017079491226468235, 0.00017079491226468235, 0.00017079491226468235, 0.00017079491226468235, 0 ]
{ "id": 7, "code_window": [ "import { field, logger } from \"@coder/logger\";\n", "import { ServerMessage, SharedProcessActive } from \"@coder/protocol/src/proto\";\n", "import { preserveEnv } from \"@coder/protocol\";\n", "import { ChildProcess, fork, ForkOptions } from \"child_process\";\n", "import { randomFillSync } from \"crypto\";\n", "import * as fs from \"fs\";\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"@coder/protocol\";\n" ], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 2 }
--- name: Bug Report about: Report problems and unexpected behavior. title: '' labels: 'bug' assignees: '' --- <!-- Please search existing issues to avoid creating duplicates. --> <!-- All extension-specific issues should be created with the `Extension Bug` template. --> - `code-server` version: <!-- The version of code-server --> - OS Version: <!-- OS version, cloud provider, --> ## Description <!-- Describes the problem here --> ## Steps to Reproduce 1. <!-- step 1: click ... --> 1. <!-- step 2: ... -->
.github/ISSUE_TEMPLATE/bug_report.md
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017528049647808075, 0.00017290690448135138, 0.00016829803644213825, 0.0001751421659719199, 0.000003259447566961171 ]
{ "id": 8, "code_window": [ "\t\tlogger.warn('\"--data-dir\" is deprecated. Use \"--user-data-dir\" instead.');\n", "\t}\n", "\n", "\tif (options.installExtension) {\n", "\n", "\t\tlet forkOptions = {\n", "\t\t\tenv: {\n", "\t\t\t\tVSCODE_ALLOW_IO: \"true\"\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tpreserveEnv(forkOptions);\n", "\n", "\t\tconst fork = forkModule(\"vs/code/node/cli\", [\n", "\t\t\t\"--user-data-dir\", dataDir,\n", "\t\t\t\"--builtin-extensions-dir\", builtInExtensionsDir,\n", "\t\t\t\"--extensions-dir\", extensionsDir,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 177 }
import { ChildProcess } from "child_process"; import * as os from "os"; import * as path from "path"; import { forkModule } from "./bootstrapFork"; import { StdioIpcHandler } from "../ipc"; import { ParsedArgs } from "vs/platform/environment/common/environment"; import { Emitter } from "@coder/events/src"; import { retry } from "@coder/ide/src/retry"; import { logger, field, Level } from "@coder/logger"; import { preserveEnv } from "@coder/protocol"; export enum SharedProcessState { Stopped, Starting, Ready, } export type SharedProcessEvent = { readonly state: SharedProcessState.Ready | SharedProcessState.Starting; } | { readonly state: SharedProcessState.Stopped; readonly error: string; }; export class SharedProcess { public readonly socketPath: string = os.platform() === "win32" ? path.join("\\\\?\\pipe", os.tmpdir(), `.code-server${Math.random().toString()}`) : path.join(os.tmpdir(), `.code-server${Math.random().toString()}`); private _state: SharedProcessState = SharedProcessState.Stopped; private activeProcess: ChildProcess | undefined; private ipcHandler: StdioIpcHandler | undefined; private readonly onStateEmitter = new Emitter<SharedProcessEvent>(); public readonly onState = this.onStateEmitter.event; private readonly logger = logger.named("shared"); private readonly retry = retry.register("Shared process", () => this.connect()); private disposed: boolean = false; public constructor( private readonly userDataDir: string, private readonly extensionsDir: string, private readonly builtInExtensionsDir: string, ) { this.retry.run(); } public get state(): SharedProcessState { return this._state; } /** * Signal the shared process to terminate. */ public dispose(): void { this.disposed = true; if (this.ipcHandler) { this.ipcHandler.send("handshake:goodbye"); } this.ipcHandler = undefined; } /** * Start and connect to the shared process. */ private async connect(): Promise<void> { this.setState({ state: SharedProcessState.Starting }); const activeProcess = await this.restart(); activeProcess.on("exit", (exitCode) => { const error = new Error(`Exited with ${exitCode}`); this.setState({ error: error.message, state: SharedProcessState.Stopped, }); if (!this.disposed) { this.retry.run(error); } }); this.setState({ state: SharedProcessState.Ready }); } /** * Restart the shared process. Kill existing process if running. Resolve when * the shared process is ready and reject when it errors or dies before being * ready. */ private async restart(): Promise<ChildProcess> { if (this.activeProcess && !this.activeProcess.killed) { this.activeProcess.kill(); } let forkOptions = { env: { VSCODE_ALLOW_IO: "true" } } preserveEnv(forkOptions); const activeProcess = forkModule("vs/code/electron-browser/sharedProcess/sharedProcessMain", [], forkOptions, this.userDataDir); this.activeProcess = activeProcess; await new Promise((resolve, reject): void => { const doReject = (error: Error | number | null): void => { if (error === null) { error = new Error("Exited unexpectedly"); } else if (typeof error === "number") { error = new Error(`Exited with ${error}`); } activeProcess.removeAllListeners(); this.setState({ error: error.message, state: SharedProcessState.Stopped, }); reject(error); }; activeProcess.on("error", doReject); activeProcess.on("exit", doReject); activeProcess.stdout.on("data", (data) => { logger.trace("stdout", field("data", data.toString())); }); activeProcess.stderr.on("data", (data) => { // Warn instead of error to prevent panic. It's unlikely stderr here is // about anything critical to the functioning of the editor. logger.warn("stderr", field("data", data.toString())); }); this.ipcHandler = new StdioIpcHandler(activeProcess); this.ipcHandler.once("handshake:hello", () => { const data: { sharedIPCHandle: string; args: Partial<ParsedArgs>; logLevel: Level; } = { args: { "builtin-extensions-dir": this.builtInExtensionsDir, "user-data-dir": this.userDataDir, "extensions-dir": this.extensionsDir, }, logLevel: this.logger.level, sharedIPCHandle: this.socketPath, }; this.ipcHandler!.send("handshake:hey there", "", data); }); this.ipcHandler.once("handshake:im ready", () => { activeProcess.removeListener("error", doReject); activeProcess.removeListener("exit", doReject); resolve(); }); }); return activeProcess; } /** * Set the internal shared process state and emit the state event. */ private setState(event: SharedProcessEvent): void { this._state = event.state; this.onStateEmitter.emit(event); } }
packages/server/src/vscode/sharedProcess.ts
1
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.9972672462463379, 0.05900665745139122, 0.00016427486843895167, 0.0001733688113745302, 0.23456555604934692 ]
{ "id": 8, "code_window": [ "\t\tlogger.warn('\"--data-dir\" is deprecated. Use \"--user-data-dir\" instead.');\n", "\t}\n", "\n", "\tif (options.installExtension) {\n", "\n", "\t\tlet forkOptions = {\n", "\t\t\tenv: {\n", "\t\t\t\tVSCODE_ALLOW_IO: \"true\"\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tpreserveEnv(forkOptions);\n", "\n", "\t\tconst fork = forkModule(\"vs/code/node/cli\", [\n", "\t\t\t\"--user-data-dir\", dataDir,\n", "\t\t\t\"--builtin-extensions-dir\", builtInExtensionsDir,\n", "\t\t\t\"--extensions-dir\", extensionsDir,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 177 }
{ "extends": "../tsconfig.json" }
packages/tsconfig.json
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017202578601427376, 0.00017202578601427376, 0.00017202578601427376, 0.00017202578601427376, 0 ]
{ "id": 8, "code_window": [ "\t\tlogger.warn('\"--data-dir\" is deprecated. Use \"--user-data-dir\" instead.');\n", "\t}\n", "\n", "\tif (options.installExtension) {\n", "\n", "\t\tlet forkOptions = {\n", "\t\t\tenv: {\n", "\t\t\t\tVSCODE_ALLOW_IO: \"true\"\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tpreserveEnv(forkOptions);\n", "\n", "\t\tconst fork = forkModule(\"vs/code/node/cli\", [\n", "\t\t\t\"--user-data-dir\", dataDir,\n", "\t\t\t\"--builtin-extensions-dir\", builtInExtensionsDir,\n", "\t\t\t\"--extensions-dir\", extensionsDir,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 177 }
import * as spdlog from "spdlog"; import { ClientProxy, ClientServerProxy } from "../../common/proxy"; import { RotatingLoggerProxy, SpdlogModuleProxy } from "../../node/modules/spdlog"; // tslint:disable completed-docs interface ClientRotatingLoggerProxy extends RotatingLoggerProxy, ClientServerProxy {} class RotatingLogger extends ClientProxy<ClientRotatingLoggerProxy> implements spdlog.RotatingLogger { public constructor( private readonly moduleProxy: ClientSpdlogModuleProxy, private readonly name: string, private readonly filename: string, private readonly filesize: number, private readonly filecount: number, ) { super(moduleProxy.createLogger(name, filename, filesize, filecount)); } public trace (message: string): void { this.catch(this.proxy.trace(message)); } public debug (message: string): void { this.catch(this.proxy.debug(message)); } public info (message: string): void { this.catch(this.proxy.info(message)); } public warn (message: string): void { this.catch(this.proxy.warn(message)); } public error (message: string): void { this.catch(this.proxy.error(message)); } public critical (message: string): void { this.catch(this.proxy.critical(message)); } public setLevel (level: number): void { this.catch(this.proxy.setLevel(level)); } public clearFormatters (): void { this.catch(this.proxy.clearFormatters()); } public flush (): void { this.catch(this.proxy.flush()); } public drop (): void { this.catch(this.proxy.drop()); } protected handleDisconnect(): void { this.initialize(this.moduleProxy.createLogger(this.name, this.filename, this.filesize, this.filecount)); } } interface ClientSpdlogModuleProxy extends SpdlogModuleProxy, ClientServerProxy { createLogger(name: string, filePath: string, fileSize: number, fileCount: number): Promise<ClientRotatingLoggerProxy>; } export class SpdlogModule { public readonly RotatingLogger: typeof spdlog.RotatingLogger; public constructor(private readonly proxy: ClientSpdlogModuleProxy) { this.RotatingLogger = class extends RotatingLogger { public constructor(name: string, filename: string, filesize: number, filecount: number) { super(proxy, name, filename, filesize, filecount); } }; } public setAsyncMode = (bufferSize: number, flushInterval: number): Promise<void> => { return this.proxy.setAsyncMode(bufferSize, flushInterval); } public createRotatingLogger(name: string, filename: string, filesize: number, filecount: number): RotatingLogger { return new RotatingLogger(this.proxy, name, filename, filesize, filecount); } public createRotatingLoggerAsync(name: string, filename: string, filesize: number, filecount: number): Promise<RotatingLogger> { return Promise.resolve(this.createRotatingLogger(name, filename, filesize, filecount)); } }
packages/protocol/src/browser/modules/spdlog.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0005069035105407238, 0.0002164854813599959, 0.00016393719124607742, 0.00016848881205078214, 0.00011859973892569542 ]
{ "id": 8, "code_window": [ "\t\tlogger.warn('\"--data-dir\" is deprecated. Use \"--user-data-dir\" instead.');\n", "\t}\n", "\n", "\tif (options.installExtension) {\n", "\n", "\t\tlet forkOptions = {\n", "\t\t\tenv: {\n", "\t\t\t\tVSCODE_ALLOW_IO: \"true\"\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tpreserveEnv(forkOptions);\n", "\n", "\t\tconst fork = forkModule(\"vs/code/node/cli\", [\n", "\t\t\t\"--user-data-dir\", dataDir,\n", "\t\t\t\"--builtin-extensions-dir\", builtInExtensionsDir,\n", "\t\t\t\"--extensions-dir\", extensionsDir,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 177 }
import "./index.scss"; import "@coder/vscode";
packages/web/src/index.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017213883984368294, 0.00017213883984368294, 0.00017213883984368294, 0.00017213883984368294, 0 ]
{ "id": 9, "code_window": [ "\t\tconst fork = forkModule(\"vs/code/node/cli\", [\n", "\t\t\t\"--user-data-dir\", dataDir,\n", "\t\t\t\"--builtin-extensions-dir\", builtInExtensionsDir,\n", "\t\t\t\"--extensions-dir\", extensionsDir,\n", "\t\t\t\"--install-extension\", options.installExtension,\n", "\t\t], forkOptions, dataDir);\n", "\n", "\t\tfork.stdout.on(\"data\", (d: Buffer) => d.toString().split(\"\\n\").forEach((l) => logger.info(l)));\n", "\t\tfork.stderr.on(\"data\", (d: Buffer) => d.toString().split(\"\\n\").forEach((l) => logger.error(l)));\n", "\t\tfork.on(\"exit\", () => process.exit());\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t], withEnv({ env: { VSCODE_ALLOW_IO: \"true\" } }), dataDir);\n" ], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 191 }
/// <reference path="../../../../../lib/vscode/src/typings/node-pty.d.ts" /> import { EventEmitter } from "events"; import * as pty from "node-pty"; import { ServerProxy } from "../../common/proxy"; import { preserveEnv } from "../../common/util"; // tslint:disable completed-docs /** * Server-side IPty proxy. */ export class NodePtyProcessProxy extends ServerProxy { public constructor(private readonly process: pty.IPty) { super({ bindEvents: ["process", "data", "exit"], doneEvents: ["exit"], instance: new EventEmitter(), }); this.process.on("data", (data) => this.instance.emit("data", data)); this.process.on("exit", (exitCode, signal) => this.instance.emit("exit", exitCode, signal)); let name = process.process; setTimeout(() => { // Need to wait for the caller to listen to the event. this.instance.emit("process", name); }, 1); const timer = setInterval(() => { if (process.process !== name) { name = process.process; this.instance.emit("process", name); } }, 200); this.process.on("exit", () => clearInterval(timer)); } public async getPid(): Promise<number> { return this.process.pid; } public async getProcess(): Promise<string> { return this.process.process; } public async kill(signal?: string): Promise<void> { this.process.kill(signal); } public async resize(columns: number, rows: number): Promise<void> { this.process.resize(columns, rows); } public async write(data: string): Promise<void> { this.process.write(data); } public async dispose(): Promise<void> { this.process.kill(); setTimeout(() => this.process.kill("SIGKILL"), 5000); // Double tap. await super.dispose(); } } /** * Server-side node-pty proxy. */ export class NodePtyModuleProxy { public async spawn(file: string, args: string[] | string, options: pty.IPtyForkOptions): Promise<NodePtyProcessProxy> { preserveEnv(options); return new NodePtyProcessProxy(require("node-pty").spawn(file, args, options)); } }
packages/protocol/src/node/modules/node-pty.ts
1
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0004441078344825655, 0.00020421535009518266, 0.00016466928354930133, 0.00016993415192700922, 0.00009075139678316191 ]
{ "id": 9, "code_window": [ "\t\tconst fork = forkModule(\"vs/code/node/cli\", [\n", "\t\t\t\"--user-data-dir\", dataDir,\n", "\t\t\t\"--builtin-extensions-dir\", builtInExtensionsDir,\n", "\t\t\t\"--extensions-dir\", extensionsDir,\n", "\t\t\t\"--install-extension\", options.installExtension,\n", "\t\t], forkOptions, dataDir);\n", "\n", "\t\tfork.stdout.on(\"data\", (d: Buffer) => d.toString().split(\"\\n\").forEach((l) => logger.info(l)));\n", "\t\tfork.stderr.on(\"data\", (d: Buffer) => d.toString().split(\"\\n\").forEach((l) => logger.error(l)));\n", "\t\tfork.on(\"exit\", () => process.exit());\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t], withEnv({ env: { VSCODE_ALLOW_IO: \"true\" } }), dataDir);\n" ], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 191 }
{ "name": "@coder/disposable", "main": "src/index.ts" }
packages/disposable/package.json
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0001726263581076637, 0.0001726263581076637, 0.0001726263581076637, 0.0001726263581076637, 0 ]
{ "id": 9, "code_window": [ "\t\tconst fork = forkModule(\"vs/code/node/cli\", [\n", "\t\t\t\"--user-data-dir\", dataDir,\n", "\t\t\t\"--builtin-extensions-dir\", builtInExtensionsDir,\n", "\t\t\t\"--extensions-dir\", extensionsDir,\n", "\t\t\t\"--install-extension\", options.installExtension,\n", "\t\t], forkOptions, dataDir);\n", "\n", "\t\tfork.stdout.on(\"data\", (d: Buffer) => d.toString().split(\"\\n\").forEach((l) => logger.info(l)));\n", "\t\tfork.stderr.on(\"data\", (d: Buffer) => d.toString().split(\"\\n\").forEach((l) => logger.error(l)));\n", "\t\tfork.on(\"exit\", () => process.exit());\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t], withEnv({ env: { VSCODE_ALLOW_IO: \"true\" } }), dataDir);\n" ], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 191 }
import * as ts from "typescript"; import * as Lint from "tslint"; /** * Rule for disallowing blank lines around the content of blocks. */ export class Rule extends Lint.Rules.AbstractRule { public static BEFORE_FAILURE_STRING = "Blocks must not start with blank lines"; public static AFTER_FAILURE_STRING = "Blocks must not end with blank lines"; /** * Apply the rule. */ public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithWalker(new NoBlockPaddingWalker(sourceFile, this.getOptions())); } } /** * Walker for checking block padding. */ class NoBlockPaddingWalker extends Lint.RuleWalker { /** * Apply this rule to interfaces. */ public visitInterfaceDeclaration(node: ts.InterfaceDeclaration): void { this.visitBlockNode(node); super.visitInterfaceDeclaration(node); } /** * Apply this rule to classes. */ public visitClassDeclaration(node: ts.ClassDeclaration): void { this.visitBlockNode(node); super.visitClassDeclaration(node); } /** * Add failures to blank lines surrounding a block's content. */ private visitBlockNode(node: ts.ClassDeclaration | ts.InterfaceDeclaration): void { const sourceFile = node.getSourceFile(); const children = node.getChildren(); const openBraceIndex = children.findIndex((n) => n.kind === ts.SyntaxKind.OpenBraceToken); if (openBraceIndex !== -1) { const nextToken = children[openBraceIndex + 1]; if (nextToken) { const startLine = this.getStartIncludingComments(sourceFile, nextToken); const openBraceToken = children[openBraceIndex]; if (ts.getLineAndCharacterOfPosition(sourceFile, openBraceToken.getEnd()).line + 1 < startLine) { this.addFailureAt(openBraceToken.getEnd(), openBraceToken.getEnd(), Rule.BEFORE_FAILURE_STRING); } } } const closeBraceIndex = children.findIndex((n) => n.kind === ts.SyntaxKind.CloseBraceToken); if (closeBraceIndex >= 2) { const previousToken = children[closeBraceIndex - 1]; if (previousToken) { let endLine = ts.getLineAndCharacterOfPosition(sourceFile, previousToken.getEnd()).line; const closeBraceToken = children[closeBraceIndex]; if (this.getStartIncludingComments(sourceFile, closeBraceToken) > endLine + 1) { this.addFailureAt(closeBraceToken.getStart(), closeBraceToken.getStart(), Rule.AFTER_FAILURE_STRING); } } } } /** * getStart() doesn't account for comments while this does. */ private getStartIncludingComments(sourceFile: ts.SourceFile, node: ts.Node): number { // This gets the line the node starts on without counting comments. let startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.getStart()).line; // Adjust the start line for the comments. const comments = ts.getLeadingCommentRanges(sourceFile.text, node.pos) || []; comments.forEach((c) => { const commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, c.pos).line; if (commentStartLine < startLine) { startLine = commentStartLine; } }); return startLine; } }
rules/src/noBlockPaddingRule.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017626195040065795, 0.00017233967082574964, 0.00016667073941789567, 0.00017300783656537533, 0.0000029066952720313566 ]
{ "id": 9, "code_window": [ "\t\tconst fork = forkModule(\"vs/code/node/cli\", [\n", "\t\t\t\"--user-data-dir\", dataDir,\n", "\t\t\t\"--builtin-extensions-dir\", builtInExtensionsDir,\n", "\t\t\t\"--extensions-dir\", extensionsDir,\n", "\t\t\t\"--install-extension\", options.installExtension,\n", "\t\t], forkOptions, dataDir);\n", "\n", "\t\tfork.stdout.on(\"data\", (d: Buffer) => d.toString().split(\"\\n\").forEach((l) => logger.info(l)));\n", "\t\tfork.stderr.on(\"data\", (d: Buffer) => d.toString().split(\"\\n\").forEach((l) => logger.error(l)));\n", "\t\tfork.on(\"exit\", () => process.exit());\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t], withEnv({ env: { VSCODE_ALLOW_IO: \"true\" } }), dataDir);\n" ], "file_path": "packages/server/src/cli.ts", "type": "replace", "edit_start_line_idx": 191 }
# Protocol This module provides a way for the browser to run Node modules like `fs`, `net`, etc. ## Internals ### Server-side proxies The server-side proxies are regular classes that call native Node functions. The only thing special about them is that they must return promises and they must return serializable values. The only exception to the promise rule are event-related methods such as `onEvent` and `onDone` (these are synchronous). The server will simply immediately bind and push all events it can to the client. It doesn't wait for the client to start listening. This prevents issues with the server not receiving the client's request to start listening in time. However, there is a way to specify events that should not bind immediately and should wait for the client to request it, because some events (like `data` on a stream) cannot be bound immediately (because doing so changes how the stream behaves). ### Client-side proxies Client-side proxies are `Proxy` instances. They simply make remote calls for any method you call on it. The only exception is for events. Each client proxy has a local emitter which it uses in place of a remote call (this allows the call to be completed synchronously on the client). Then when an event is received from the server, it gets emitted on that local emitter. When an event is listened to, the proxy also notifies the server so it can start listening in case it isn't already (see the `data` example above). This only works for events that only fire after they are bound. ### Client-side fills The client-side fills implement the Node API and make calls to the server-side proxies using the client-side proxies. When a proxy returns a proxy (for example `fs.createWriteStream`), that proxy is a promise (since communicating with the server is asynchronous). We have to return the fill from `fs.createWriteStream` synchronously, so that means the fill has to contain a proxy promise. To eliminate the need for calling `then` and to keep the code looking clean every time you use the proxy, the proxy is itself wrapped in another proxy which just calls the method after a `then`. This works since all the methods return promises (aside from the event methods, but those are not used by the fills directly—they are only used internally to forward events to the fill if it is an event emitter).
packages/protocol/README.md
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0001674466475378722, 0.00016395497368648648, 0.00015750578313600272, 0.00016535198665224016, 0.0000037161362342885695 ]
{ "id": 10, "code_window": [ "import { Emitter } from \"@coder/events/src\";\n", "import { retry } from \"@coder/ide/src/retry\";\n", "import { logger, field, Level } from \"@coder/logger\";\n", "import { preserveEnv } from \"@coder/protocol\";\n", "\n", "export enum SharedProcessState {\n", "\tStopped,\n", "\tStarting,\n", "\tReady,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"@coder/protocol\";\n" ], "file_path": "packages/server/src/vscode/sharedProcess.ts", "type": "replace", "edit_start_line_idx": 9 }
import { field, logger } from "@coder/logger"; import { ServerMessage, SharedProcessActive } from "@coder/protocol/src/proto"; import { preserveEnv } from "@coder/protocol"; import { ChildProcess, fork, ForkOptions } from "child_process"; import { randomFillSync } from "crypto"; import * as fs from "fs"; import * as fse from "fs-extra"; import * as os from "os"; import * as path from "path"; import * as WebSocket from "ws"; import { buildDir, cacheHome, dataHome, isCli, serveStatic } from "./constants"; import { createApp } from "./server"; import { forkModule, requireModule } from "./vscode/bootstrapFork"; import { SharedProcess, SharedProcessState } from "./vscode/sharedProcess"; import opn = require("opn"); import * as commander from "commander"; commander.version(process.env.VERSION || "development") .name("code-server") .description("Run VS Code on a remote server.") .option("--cert <value>") .option("--cert-key <value>") .option("-e, --extensions-dir <dir>", "Set the root path for extensions.") .option("-d --user-data-dir <dir>", " Specifies the directory that user data is kept in, useful when running as root.") .option("--data-dir <value>", "DEPRECATED: Use '--user-data-dir' instead. Customize where user-data is stored.") .option("-h, --host <value>", "Customize the hostname.", "0.0.0.0") .option("-o, --open", "Open in the browser on startup.", false) .option("-p, --port <number>", "Port to bind on.", parseInt(process.env.PORT!, 10) || 8443) .option("-N, --no-auth", "Start without requiring authentication.", false) .option("-H, --allow-http", "Allow http connections.", false) .option("-P, --password <value>", "DEPRECATED: Use the PASSWORD environment variable instead. Specify a password for authentication.") .option("--disable-telemetry", "Disables ALL telemetry.", false) .option("--socket <value>", "Listen on a UNIX socket. Host and port will be ignored when set.") .option("--install-extension <value>", "Install an extension by its ID.") .option("--bootstrap-fork <name>", "Used for development. Never set.") .option("--extra-args <args>", "Used for development. Never set.") .arguments("Specify working directory.") .parse(process.argv); Error.stackTraceLimit = Infinity; if (isCli) { require("nbin").shimNativeFs(buildDir); require("nbin").shimNativeFs("/node_modules"); } // Makes strings or numbers bold in stdout const bold = (text: string | number): string | number => { return `\u001B[1m${text}\u001B[0m`; }; (async (): Promise<void> => { const args = commander.args; const options = commander.opts() as { noAuth: boolean; readonly allowHttp: boolean; readonly host: string; readonly port: number; readonly disableTelemetry: boolean; readonly userDataDir?: string; readonly extensionsDir?: string; readonly dataDir?: string; readonly password?: string; readonly open?: boolean; readonly cert?: string; readonly certKey?: string; readonly socket?: string; readonly installExtension?: string; readonly bootstrapFork?: string; readonly extraArgs?: string; }; if (options.disableTelemetry) { process.env.DISABLE_TELEMETRY = "true"; } // Commander has an exception for `--no` prefixes. Here we'll adjust that. // tslint:disable-next-line:no-any const noAuthValue = (commander as any).auth; options.noAuth = !noAuthValue; const dataDir = path.resolve(options.userDataDir || options.dataDir || path.join(dataHome, "code-server")); const extensionsDir = options.extensionsDir ? path.resolve(options.extensionsDir) : path.resolve(dataDir, "extensions"); const workingDir = path.resolve(args[0] || process.cwd()); const dependenciesDir = path.join(os.tmpdir(), "code-server/dependencies"); if (!fs.existsSync(dataDir)) { const oldDataDir = path.resolve(path.join(os.homedir(), ".code-server")); if (fs.existsSync(oldDataDir)) { await fse.move(oldDataDir, dataDir); logger.info(`Moved data directory from ${oldDataDir} to ${dataDir}`); } } await Promise.all([ fse.mkdirp(cacheHome), fse.mkdirp(dataDir), fse.mkdirp(extensionsDir), fse.mkdirp(workingDir), fse.mkdirp(dependenciesDir), ]); const unpackExecutable = (binaryName: string): void => { const memFile = path.join(isCli ? buildDir! : path.join(__dirname, ".."), "build/dependencies", binaryName); const diskFile = path.join(dependenciesDir, binaryName); if (!fse.existsSync(diskFile)) { fse.writeFileSync(diskFile, fse.readFileSync(memFile)); } fse.chmodSync(diskFile, "755"); }; unpackExecutable("rg"); // tslint:disable-next-line no-any (<any>global).RIPGREP_LOCATION = path.join(dependenciesDir, "rg"); const builtInExtensionsDir = path.resolve(buildDir || path.join(__dirname, ".."), "build/extensions"); if (options.bootstrapFork) { const modulePath = options.bootstrapFork; if (!modulePath) { logger.error("No module path specified to fork!"); process.exit(1); } process.argv = [ process.argv[0], process.argv[1], ...(options.extraArgs ? JSON.parse(options.extraArgs) : []), ]; return requireModule(modulePath, builtInExtensionsDir); } const logDir = path.join(cacheHome, "code-server/logs", new Date().toISOString().replace(/[-:.TZ]/g, "")); process.env.VSCODE_LOGS = logDir; const certPath = options.cert ? path.resolve(options.cert) : undefined; const certKeyPath = options.certKey ? path.resolve(options.certKey) : undefined; if (certPath && !certKeyPath) { logger.error("'--cert-key' flag is required when specifying a certificate!"); process.exit(1); } if (!certPath && certKeyPath) { logger.error("'--cert' flag is required when specifying certificate key!"); process.exit(1); } let certData: Buffer | undefined; let certKeyData: Buffer | undefined; if (typeof certPath !== "undefined" && typeof certKeyPath !== "undefined") { try { certData = fs.readFileSync(certPath); } catch (ex) { logger.error(`Failed to read certificate: ${ex.message}`); process.exit(1); } try { certKeyData = fs.readFileSync(certKeyPath); } catch (ex) { logger.error(`Failed to read certificate key: ${ex.message}`); process.exit(1); } } logger.info(`\u001B[1mcode-server ${process.env.VERSION ? `v${process.env.VERSION}` : "development"}`); if (options.dataDir) { logger.warn('"--data-dir" is deprecated. Use "--user-data-dir" instead.'); } if (options.installExtension) { let forkOptions = { env: { VSCODE_ALLOW_IO: "true" } } preserveEnv(forkOptions); const fork = forkModule("vs/code/node/cli", [ "--user-data-dir", dataDir, "--builtin-extensions-dir", builtInExtensionsDir, "--extensions-dir", extensionsDir, "--install-extension", options.installExtension, ], forkOptions, dataDir); fork.stdout.on("data", (d: Buffer) => d.toString().split("\n").forEach((l) => logger.info(l))); fork.stderr.on("data", (d: Buffer) => d.toString().split("\n").forEach((l) => logger.error(l))); fork.on("exit", () => process.exit()); return; } // TODO: fill in appropriate doc url logger.info("Additional documentation: http://github.com/codercom/code-server"); logger.info("Initializing", field("data-dir", dataDir), field("extensions-dir", extensionsDir), field("working-dir", workingDir), field("log-dir", logDir)); const sharedProcess = new SharedProcess(dataDir, extensionsDir, builtInExtensionsDir); const sendSharedProcessReady = (socket: WebSocket): void => { const active = new SharedProcessActive(); active.setSocketPath(sharedProcess.socketPath); active.setLogPath(logDir); const serverMessage = new ServerMessage(); serverMessage.setSharedProcessActive(active); socket.send(serverMessage.serializeBinary()); }; sharedProcess.onState((event) => { if (event.state === SharedProcessState.Ready) { app.wss.clients.forEach((c) => sendSharedProcessReady(c)); } }); if (options.password) { logger.warn('"--password" is deprecated. Use the PASSWORD environment variable instead.'); } let password = options.password || process.env.PASSWORD; const usingCustomPassword = !!password; if (!password) { // Generate a random password with a length of 24. const buffer = Buffer.alloc(12); randomFillSync(buffer); password = buffer.toString("hex"); } const hasCustomHttps = certData && certKeyData; const app = await createApp({ allowHttp: options.allowHttp, bypassAuth: options.noAuth, registerMiddleware: (app): void => { // If we're not running from the binary and we aren't serving the static // pre-built version, use webpack to serve the web files. if (!isCli && !serveStatic) { const webpackConfig = require(path.resolve(__dirname, "..", "..", "web", "webpack.config.js")); const compiler = require("webpack")(webpackConfig); app.use(require("webpack-dev-middleware")(compiler, { logger: { trace: (m: string): void => logger.trace("webpack", field("message", m)), debug: (m: string): void => logger.debug("webpack", field("message", m)), info: (m: string): void => logger.info("webpack", field("message", m)), warn: (m: string): void => logger.warn("webpack", field("message", m)), error: (m: string): void => logger.error("webpack", field("message", m)), }, publicPath: webpackConfig.output.publicPath, stats: webpackConfig.stats, })); app.use(require("webpack-hot-middleware")(compiler)); } }, serverOptions: { extensionsDirectory: extensionsDir, builtInExtensionsDirectory: builtInExtensionsDir, dataDirectory: dataDir, workingDirectory: workingDir, cacheDirectory: cacheHome, fork: (modulePath: string, args?: string[], options?: ForkOptions): ChildProcess => { if (options && options.env && options.env.AMD_ENTRYPOINT) { return forkModule(options.env.AMD_ENTRYPOINT, args, options, dataDir); } return fork(modulePath, args, options); }, }, password, httpsOptions: hasCustomHttps ? { key: certKeyData, cert: certData, } : undefined, }); logger.info("Starting webserver...", field("host", options.host), field("port", options.port)); if (options.socket) { app.server.listen(options.socket); } else { app.server.listen(options.port, options.host); } let clientId = 1; app.wss.on("connection", (ws, req) => { const id = clientId++; if (sharedProcess.state === SharedProcessState.Ready) { sendSharedProcessReady(ws); } logger.info(`WebSocket opened \u001B[0m${req.url}`, field("client", id), field("ip", req.socket.remoteAddress)); ws.on("close", (code) => { logger.info(`WebSocket closed \u001B[0m${req.url}`, field("client", id), field("code", code)); }); }); app.wss.on("error", (err: NodeJS.ErrnoException) => { if (err.code === "EADDRINUSE") { if (options.socket) { logger.error(`Socket ${bold(options.socket)} is in use. Please specify a different socket.`); } else { logger.error(`Port ${bold(options.port)} is in use. Please free up port ${options.port} or specify a different port with the -p flag`); } process.exit(1); } }); if (!options.certKey && !options.cert) { logger.warn("No certificate specified. \u001B[1mThis could be insecure."); // TODO: fill in appropriate doc url logger.warn("Documentation on securing your setup: https://github.com/codercom/code-server/blob/master/doc/security/ssl.md"); } if (!options.noAuth && !usingCustomPassword) { logger.info(" "); logger.info(`Password:\u001B[1m ${password}`); } else { logger.warn("Launched without authentication."); } if (options.disableTelemetry) { logger.info("Telemetry is disabled"); } const protocol = options.allowHttp ? "http" : "https"; const url = `${protocol}://localhost:${options.port}/`; logger.info(" "); logger.info("Started (click the link below to open):"); logger.info(url); logger.info(" "); if (options.open) { try { await opn(url); } catch (e) { logger.warn("Url couldn't be opened automatically.", field("url", url), field("exception", e)); } } })().catch((ex) => { logger.error(ex); });
packages/server/src/cli.ts
1
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.9966859221458435, 0.05827872455120087, 0.0001648914476390928, 0.0001719058636808768, 0.23124630749225616 ]
{ "id": 10, "code_window": [ "import { Emitter } from \"@coder/events/src\";\n", "import { retry } from \"@coder/ide/src/retry\";\n", "import { logger, field, Level } from \"@coder/logger\";\n", "import { preserveEnv } from \"@coder/protocol\";\n", "\n", "export enum SharedProcessState {\n", "\tStopped,\n", "\tStarting,\n", "\tReady,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"@coder/protocol\";\n" ], "file_path": "packages/server/src/vscode/sharedProcess.ts", "type": "replace", "edit_start_line_idx": 9 }
src tsconfig.build.json webpack.config.js yarn.lock
packages/logger/.npmignore
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017279516032431275, 0.00017279516032431275, 0.00017279516032431275, 0.00017279516032431275, 0 ]
{ "id": 10, "code_window": [ "import { Emitter } from \"@coder/events/src\";\n", "import { retry } from \"@coder/ide/src/retry\";\n", "import { logger, field, Level } from \"@coder/logger\";\n", "import { preserveEnv } from \"@coder/protocol\";\n", "\n", "export enum SharedProcessState {\n", "\tStopped,\n", "\tStarting,\n", "\tReady,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"@coder/protocol\";\n" ], "file_path": "packages/server/src/vscode/sharedProcess.ts", "type": "replace", "edit_start_line_idx": 9 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/ip-address@^5.8.2": version "5.8.2" resolved "https://registry.yarnpkg.com/@types/ip-address/-/ip-address-5.8.2.tgz#5e413c477f78b3a264745eac937538a6e6e0c1f6" integrity sha512-LFlDGRjJDnahfPyNCZGXvlaevSmZTi/zDxjTdXeTs8TQ9pQkNZKbCWaJXW29a3bGPRsASqeO+jGgZlaTUi9jTw== dependencies: "@types/jsbn" "*" "@types/jsbn@*": version "1.2.29" resolved "https://registry.yarnpkg.com/@types/jsbn/-/jsbn-1.2.29.tgz#28229bc0262c704a1506c3ed69a7d7e115bd7832" integrity sha512-2dVz9LTEGWVj9Ov9zaDnpvqHFV+W4bXtU0EUEGAzWfdRNO3dlUuosdHpENI6/oQW+Kejn0hAjk6P/czs9h/hvg== [email protected]: version "0.7.0" resolved "https://registry.yarnpkg.com/bunyan/-/bunyan-0.7.0.tgz#921065e70c936fe302a740e2c5605775beea2f42" integrity sha1-khBl5wyTb+MCp0DixWBXdb7qL0I= "coffee-script@>= 1.1.1": version "1.12.7" resolved "https://registry.yarnpkg.com/coffee-script/-/coffee-script-1.12.7.tgz#c05dae0cb79591d05b3070a8433a98c9a89ccc53" integrity sha512-fLeEhqwymYat/MpTPUjSKHVYYl0ec2mOyALEMLmzr5i1isuG+6jfI2j2d5oBO3VIzgUXgBVIcOT9uH1TFxBckw== ip-address@^5.8.9: version "5.8.9" resolved "https://registry.yarnpkg.com/ip-address/-/ip-address-5.8.9.tgz#6379277c23fc5adb20511e4d23ec2c1bde105dfd" integrity sha512-7ay355oMN34iXhET1BmCJVsHjOTSItEEIIpOs38qUC23AIhOy+xIPnkrTuEFjeLMrTJ7m8KMXWgWfy/2Vn9sDw== dependencies: jsbn "1.1.0" lodash.find "^4.6.0" lodash.max "^4.0.1" lodash.merge "^4.6.0" lodash.padstart "^4.6.1" lodash.repeat "^4.1.0" sprintf-js "1.1.0" [email protected]: version "0.1.1" resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-0.1.1.tgz#28c6a7c116a021c555544f906ab1ad540b1d635a" integrity sha1-KManwRagIcVVVE+QarGtVAsdY1o= dependencies: coffee-script ">= 1.1.1" [email protected]: version "1.1.0" resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-1.1.0.tgz#b01307cb29b618a1ed26ec79e911f803c4da0040" integrity sha1-sBMHyym2GKHtJux56RH4A8TaAEA= lodash.find@^4.6.0: version "4.6.0" resolved "https://registry.yarnpkg.com/lodash.find/-/lodash.find-4.6.0.tgz#cb0704d47ab71789ffa0de8b97dd926fb88b13b1" integrity sha1-ywcE1Hq3F4n/oN6Ll92Sb7iLE7E= lodash.max@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/lodash.max/-/lodash.max-4.0.1.tgz#8735566c618b35a9f760520b487ae79658af136a" integrity sha1-hzVWbGGLNan3YFILSHrnllivE2o= lodash.merge@^4.6.0: version "4.6.1" resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.1.tgz#adc25d9cb99b9391c59624f379fbba60d7111d54" integrity sha512-AOYza4+Hf5z1/0Hztxpm2/xiPZgi/cjMqdnKTUWTBSKchJlxXXuUSxCCl8rJlf4g6yww/j6mA8nC8Hw/EZWxKQ== lodash.padstart@^4.6.1: version "4.6.1" resolved "https://registry.yarnpkg.com/lodash.padstart/-/lodash.padstart-4.6.1.tgz#d2e3eebff0d9d39ad50f5cbd1b52a7bce6bb611b" integrity sha1-0uPuv/DZ05rVD1y9G1KnvOa7YRs= lodash.repeat@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/lodash.repeat/-/lodash.repeat-4.1.0.tgz#fc7de8131d8c8ac07e4b49f74ffe829d1f2bec44" integrity sha1-/H3oEx2MisB+S0n3T/6CnR8r7EQ= node-named@^0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/node-named/-/node-named-0.0.1.tgz#3607b434cf237ab99440f5ff6d19c05e3a93e217" integrity sha1-Nge0NM8jermUQPX/bRnAXjqT4hc= dependencies: bunyan "0.7.0" ipaddr.js "0.1.1" [email protected]: version "1.1.0" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.1.0.tgz#cffcaf702daf65ea39bb4e0fa2b299cec1a1be46" integrity sha1-z/yvcC2vZeo5u04PorKZzsGhvkY=
packages/dns/yarn.lock
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0001737718121148646, 0.00017029503942467272, 0.00016316617256961763, 0.00017053876945283264, 0.000002974581548187416 ]
{ "id": 10, "code_window": [ "import { Emitter } from \"@coder/events/src\";\n", "import { retry } from \"@coder/ide/src/retry\";\n", "import { logger, field, Level } from \"@coder/logger\";\n", "import { preserveEnv } from \"@coder/protocol\";\n", "\n", "export enum SharedProcessState {\n", "\tStopped,\n", "\tStarting,\n", "\tReady,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { withEnv } from \"@coder/protocol\";\n" ], "file_path": "packages/server/src/vscode/sharedProcess.ts", "type": "replace", "edit_start_line_idx": 9 }
# Protocol This module provides a way for the browser to run Node modules like `fs`, `net`, etc. ## Internals ### Server-side proxies The server-side proxies are regular classes that call native Node functions. The only thing special about them is that they must return promises and they must return serializable values. The only exception to the promise rule are event-related methods such as `onEvent` and `onDone` (these are synchronous). The server will simply immediately bind and push all events it can to the client. It doesn't wait for the client to start listening. This prevents issues with the server not receiving the client's request to start listening in time. However, there is a way to specify events that should not bind immediately and should wait for the client to request it, because some events (like `data` on a stream) cannot be bound immediately (because doing so changes how the stream behaves). ### Client-side proxies Client-side proxies are `Proxy` instances. They simply make remote calls for any method you call on it. The only exception is for events. Each client proxy has a local emitter which it uses in place of a remote call (this allows the call to be completed synchronously on the client). Then when an event is received from the server, it gets emitted on that local emitter. When an event is listened to, the proxy also notifies the server so it can start listening in case it isn't already (see the `data` example above). This only works for events that only fire after they are bound. ### Client-side fills The client-side fills implement the Node API and make calls to the server-side proxies using the client-side proxies. When a proxy returns a proxy (for example `fs.createWriteStream`), that proxy is a promise (since communicating with the server is asynchronous). We have to return the fill from `fs.createWriteStream` synchronously, so that means the fill has to contain a proxy promise. To eliminate the need for calling `then` and to keep the code looking clean every time you use the proxy, the proxy is itself wrapped in another proxy which just calls the method after a `then`. This works since all the methods return promises (aside from the event methods, but those are not used by the fills directly—they are only used internally to forward events to the fill if it is an event emitter).
packages/protocol/README.md
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0001896340399980545, 0.00017288830713368952, 0.00016132197924889624, 0.00016280236013699323, 0.000013129476428730413 ]
{ "id": 11, "code_window": [ "\t\t\tthis.activeProcess.kill();\n", "\t\t}\n", "\n", "\t\tlet forkOptions = {\n", "\t\t\tenv: {\n", "\t\t\t\tVSCODE_ALLOW_IO: \"true\"\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tpreserveEnv(forkOptions);\n", "\n", "\t\tconst activeProcess = forkModule(\"vs/code/electron-browser/sharedProcess/sharedProcessMain\", [], forkOptions, this.userDataDir);\n", "\t\tthis.activeProcess = activeProcess;\n", "\n", "\t\tawait new Promise((resolve, reject): void => {\n", "\t\t\tconst doReject = (error: Error | number | null): void => {\n", "\t\t\t\tif (error === null) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst activeProcess = forkModule(\n", "\t\t\t\"vs/code/electron-browser/sharedProcess/sharedProcessMain\", [],\n", "\t\t\twithEnv({ env: { VSCODE_ALLOW_IO: \"true\" } }), this.userDataDir,\n", "\t\t);\n" ], "file_path": "packages/server/src/vscode/sharedProcess.ts", "type": "replace", "edit_start_line_idx": 91 }
import * as cp from "child_process"; import { ServerProxy } from "../../common/proxy"; import { preserveEnv } from "../../common/util"; import { WritableProxy, ReadableProxy } from "./stream"; // tslint:disable completed-docs export type ForkProvider = (modulePath: string, args?: string[], options?: cp.ForkOptions) => cp.ChildProcess; export class ChildProcessProxy extends ServerProxy<cp.ChildProcess> { public constructor(instance: cp.ChildProcess) { super({ bindEvents: ["close", "disconnect", "error", "exit", "message"], doneEvents: ["close"], instance, }); } public async kill(signal?: string): Promise<void> { this.instance.kill(signal); } public async disconnect(): Promise<void> { this.instance.disconnect(); } public async ref(): Promise<void> { this.instance.ref(); } public async unref(): Promise<void> { this.instance.unref(); } // tslint:disable-next-line no-any public async send(message: any): Promise<void> { return new Promise((resolve, reject): void => { this.instance.send(message, (error) => { if (error) { reject(error); } else { resolve(); } }); }); } public async getPid(): Promise<number> { return this.instance.pid; } public async dispose(): Promise<void> { this.instance.kill(); setTimeout(() => this.instance.kill("SIGKILL"), 5000); // Double tap. await super.dispose(); } } export interface ChildProcessProxies { childProcess: ChildProcessProxy; stdin?: WritableProxy | null; stdout?: ReadableProxy | null; stderr?: ReadableProxy | null; } export class ChildProcessModuleProxy { public constructor(private readonly forkProvider?: ForkProvider) {} public async exec( command: string, options?: { encoding?: string | null } & cp.ExecOptions | null, callback?: ((error: cp.ExecException | null, stdin: string | Buffer, stdout: string | Buffer) => void), ): Promise<ChildProcessProxies> { preserveEnv(options); return this.returnProxies(cp.exec(command, options, callback)); } public async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> { preserveEnv(options); return this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, options)); } public async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> { preserveEnv(options); return this.returnProxies(cp.spawn(command, args, options)); } private returnProxies(process: cp.ChildProcess): ChildProcessProxies { return { childProcess: new ChildProcessProxy(process), stdin: process.stdin && new WritableProxy(process.stdin), // Child processes streams appear to immediately flow so we need to bind // to the data event right away. stdout: process.stdout && new ReadableProxy(process.stdout, ["data"]), stderr: process.stderr && new ReadableProxy(process.stderr, ["data"]), }; } }
packages/protocol/src/node/modules/child_process.ts
1
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.006377657875418663, 0.0011088098399341106, 0.00016317039262503386, 0.00022995354083832353, 0.0017666672356426716 ]
{ "id": 11, "code_window": [ "\t\t\tthis.activeProcess.kill();\n", "\t\t}\n", "\n", "\t\tlet forkOptions = {\n", "\t\t\tenv: {\n", "\t\t\t\tVSCODE_ALLOW_IO: \"true\"\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tpreserveEnv(forkOptions);\n", "\n", "\t\tconst activeProcess = forkModule(\"vs/code/electron-browser/sharedProcess/sharedProcessMain\", [], forkOptions, this.userDataDir);\n", "\t\tthis.activeProcess = activeProcess;\n", "\n", "\t\tawait new Promise((resolve, reject): void => {\n", "\t\t\tconst doReject = (error: Error | number | null): void => {\n", "\t\t\t\tif (error === null) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst activeProcess = forkModule(\n", "\t\t\t\"vs/code/electron-browser/sharedProcess/sharedProcessMain\", [],\n", "\t\t\twithEnv({ env: { VSCODE_ALLOW_IO: \"true\" } }), this.userDataDir,\n", "\t\t);\n" ], "file_path": "packages/server/src/vscode/sharedProcess.ts", "type": "replace", "edit_start_line_idx": 91 }
/// <reference path="../../../../lib/vscode/src/typings/electron.d.ts" /> import { EventEmitter } from "events"; import * as fs from "fs"; import * as trash from "trash"; import { logger, field } from "@coder/logger"; import { IKey, Dialog as DialogBox } from "./dialog"; import { clipboard } from "./clipboard"; // tslint:disable-next-line no-any (global as any).getOpenUrls = (): string[] => { return []; }; // This is required to make the fill load in Node without erroring. if (typeof document === "undefined") { // tslint:disable-next-line no-any (global as any).document = {} as any; } const oldCreateElement = document.createElement; const newCreateElement = <K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K] => { const createElement = <K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K] => { // tslint:disable-next-line:no-any return oldCreateElement.call(document, tagName as any); }; // tslint:disable-next-line:no-any const getPropertyDescriptor = (object: any, id: string): PropertyDescriptor | undefined => { let op = Object.getPrototypeOf(object); while (!Object.getOwnPropertyDescriptor(op, id)) { op = Object.getPrototypeOf(op); } return Object.getOwnPropertyDescriptor(op, id); }; if (tagName === "img") { const img = createElement("img"); const oldSrc = getPropertyDescriptor(img, "src"); if (!oldSrc) { throw new Error("Failed to find src property"); } Object.defineProperty(img, "src", { get: (): string => { return oldSrc!.get!.call(img); }, set: (value: string): void => { if (value) { const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource"; value = value.replace(/file:\/\//g, resourceBaseUrl); } oldSrc!.set!.call(img, value); }, }); return img; } if (tagName === "style") { const style = createElement("style"); const oldInnerHtml = getPropertyDescriptor(style, "innerHTML"); if (!oldInnerHtml) { throw new Error("Failed to find innerHTML property"); } Object.defineProperty(style, "innerHTML", { get: (): string => { return oldInnerHtml!.get!.call(style); }, set: (value: string): void => { if (value) { const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource"; value = value.replace(/file:\/\//g, resourceBaseUrl); } oldInnerHtml!.set!.call(style, value); }, }); let overridden = false; const oldSheet = getPropertyDescriptor(style, "sheet"); Object.defineProperty(style, "sheet", { // tslint:disable-next-line:no-any get: (): any => { const sheet = oldSheet!.get!.call(style); if (sheet && !overridden) { const oldInsertRule = sheet.insertRule; sheet.insertRule = (rule: string, index?: number): void => { const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource"; rule = rule.replace(/file:\/\//g, resourceBaseUrl); oldInsertRule.call(sheet, rule, index); }; overridden = true; } return sheet; }, }); return style; } if (tagName === "webview") { const view = createElement("iframe") as HTMLIFrameElement; view.style.border = "0px"; const frameID = Math.random().toString(); view.addEventListener("error", (event) => { logger.error("iframe error", field("event", event)); }); window.addEventListener("message", (event) => { if (!event.data || !event.data.id) { return; } if (event.data.id !== frameID) { return; } const e = new CustomEvent("ipc-message"); (e as any).channel = event.data.channel; // tslint:disable-line no-any (e as any).args = event.data.data; // tslint:disable-line no-any view.dispatchEvent(e); }); view.sandbox.add("allow-same-origin", "allow-scripts", "allow-popups", "allow-forms"); Object.defineProperty(view, "preload", { set: (url: string): void => { view.onload = (): void => { if (view.contentDocument) { view.contentDocument.body.id = frameID; view.contentDocument.body.parentElement!.style.overflow = "hidden"; const script = createElement("script"); script.src = url; script.addEventListener("load", () => { view.contentDocument!.dispatchEvent(new Event("DOMContentLoaded", { bubbles: true, cancelable: true, })); // const e = new CustomEvent("ipc-message"); // (e as any).channel = "webview-ready"; // tslint:disable-line no-any // (e as any).args = [frameID]; // tslint:disable-line no-any // view.dispatchEvent(e); }); view.contentDocument.head.appendChild(script); } }; }, }); view.src = require("!!file-loader?name=[path][name].[ext]!./webview.html"); Object.defineProperty(view, "src", { set: (): void => { /* Nope. */ }, }); (view as any).getWebContents = (): void => undefined; // tslint:disable-line no-any (view as any).send = (channel: string, ...args: any[]): void => { // tslint:disable-line no-any if (args[0] && typeof args[0] === "object" && args[0].contents) { // TODO const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource"; args[0].contents = (args[0].contents as string).replace(/"(file:\/\/[^"]*)"/g, (m1) => `"${resourceBaseUrl}${m1}"`); args[0].contents = (args[0].contents as string).replace(/"vscode-resource:([^"]*)"/g, (m, m1) => `"${resourceBaseUrl}${m1}"`); args[0].contents = (args[0].contents as string).replace(/style-src vscode-core-resource:/g, "style-src 'self'"); } if (view.contentWindow) { view.contentWindow.postMessage({ channel, data: args, id: frameID, }, "*"); } }; return view; } return createElement(tagName); }; document.createElement = newCreateElement; class Clipboard { private readonly buffers = new Map<string, Buffer>(); public has(format: string): boolean { return this.buffers.has(format); } public readFindText(): string { return ""; } public writeFindText(_text: string): void { // Nothing. } public writeText(value: string): Promise<void> { return clipboard.writeText(value); } public readText(): Promise<string> { return clipboard.readText(); } public writeBuffer(format: string, buffer: Buffer): void { this.buffers.set(format, buffer); } public readBuffer(format: string): Buffer | undefined { return this.buffers.get(format); } } class Shell { public async moveItemToTrash(path: string): Promise<void> { await trash(path); } } class App extends EventEmitter { public isAccessibilitySupportEnabled(): boolean { return false; } public setAsDefaultProtocolClient(): void { throw new Error("not implemented"); } } class Dialog { public showSaveDialog(_: void, options: Electron.SaveDialogOptions, callback: (filename: string | undefined) => void): void { const defaultPath = options.defaultPath || "/untitled"; const fileIndex = defaultPath.lastIndexOf("/"); const extensionIndex = defaultPath.lastIndexOf("."); const saveDialogOptions = { buttons: ["Cancel", "Save"], detail: "Enter a path for this file", input: { value: defaultPath, selection: { start: fileIndex === -1 ? 0 : fileIndex + 1, end: extensionIndex === -1 ? defaultPath.length : extensionIndex, }, }, message: "Save file", }; const dialog = new DialogBox(saveDialogOptions); dialog.onAction((action) => { if (action.key !== IKey.Enter && action.buttonIndex !== 1) { dialog.hide(); return callback(undefined); } const inputValue = dialog.inputValue || ""; const filePath = inputValue.replace(/\/+$/, ""); const split = filePath.split("/"); const fileName = split.pop(); const parentName = split.pop() || "/"; if (fileName === "") { dialog.error = "You must enter a file name."; return; } fs.stat(filePath, (error, stats) => { if (error && error.code === "ENOENT") { dialog.hide(); callback(filePath); } else if (error) { dialog.error = error.message; } else if (stats.isDirectory()) { dialog.error = `A directory named "${fileName}" already exists.`; } else { dialog.error = undefined; const confirmDialog = new DialogBox({ message: `A file named "${fileName}" already exists. Do you want to replace it?`, detail: `The file already exists in "${parentName}". Replacing it will overwrite its contents.`, buttons: ["Cancel", "Replace"], }); confirmDialog.onAction((action) => { if (action.buttonIndex === 1) { confirmDialog.hide(); return callback(filePath); } confirmDialog.hide(); dialog.show(); }); dialog.hide(); confirmDialog.show(); } }); }); dialog.show(); } public showOpenDialog(): void { throw new Error("not implemented"); } public showMessageBox(_: void, options: Electron.MessageBoxOptions, callback: (button: number | undefined, checked: boolean) => void): void { const dialog = new DialogBox(options); dialog.onAction((action) => { dialog.hide(); callback(action.buttonIndex, false); }); dialog.show(); } } class WebFrame { public getZoomFactor(): number { return 1; } public getZoomLevel(): number { return 1; } public setZoomLevel(): void { // Nothing. } } class Screen { public getAllDisplays(): [] { return []; } } class WebRequest extends EventEmitter { public onBeforeRequest(): void { throw new Error("not implemented"); } public onBeforeSendHeaders(): void { throw new Error("not implemented"); } public onHeadersReceived(): void { throw new Error("not implemented"); } } class Session extends EventEmitter { public webRequest = new WebRequest(); public resolveProxy(url: string, callback: (proxy: string) => void): void { // TODO: not sure what this actually does. callback(url); } } class WebContents extends EventEmitter { public session = new Session(); } class BrowserWindow extends EventEmitter { public webContents = new WebContents(); private representedFilename: string = ""; public static getFocusedWindow(): undefined { return undefined; } public focus(): void { window.focus(); } public show(): void { window.focus(); } public reload(): void { location.reload(); } public isMaximized(): boolean { return false; } public setFullScreen(fullscreen: boolean): void { if (fullscreen) { document.documentElement.requestFullscreen().catch((error) => { logger.error(error.message); }); } else { document.exitFullscreen().catch((error) => { logger.error(error.message); }); } } public isFullScreen(): boolean { // TypeScript doesn't recognize this property. // tslint:disable no-any if (typeof (window as any)["fullScreen"] !== "undefined") { return (window as any)["fullScreen"]; } // tslint:enable no-any try { return window.matchMedia("(display-mode: fullscreen)").matches; } catch (error) { logger.error(error.message); return false; } } public isFocused(): boolean { return document.hasFocus(); } public setMenuBarVisibility(): void { throw new Error("not implemented"); } public setAutoHideMenuBar(): void { throw new Error("not implemented"); } public setRepresentedFilename(filename: string): void { this.representedFilename = filename; } public getRepresentedFilename(): string { return this.representedFilename; } public setTitle(value: string): void { document.title = value; } } /** * We won't be able to do a 1 to 1 fill because things like moveItemToTrash for * example returns a boolean while we need a promise. */ class ElectronFill { public readonly shell = new Shell(); public readonly clipboard = new Clipboard(); public readonly app = new App(); public readonly dialog = new Dialog(); public readonly webFrame = new WebFrame(); public readonly screen = new Screen(); private readonly rendererToMainEmitter = new EventEmitter(); private readonly mainToRendererEmitter = new EventEmitter(); public get BrowserWindow(): typeof BrowserWindow { return BrowserWindow; } // tslint:disable no-any public get ipcRenderer(): object { return { send: (str: string, ...args: any[]): void => { this.rendererToMainEmitter.emit(str, { sender: module.exports.ipcMain, }, ...args); }, on: (str: string, listener: (...args: any[]) => void): void => { this.mainToRendererEmitter.on(str, listener); }, once: (str: string, listener: (...args: any[]) => void): void => { this.mainToRendererEmitter.once(str, listener); }, removeListener: (str: string, listener: (...args: any[]) => void): void => { this.mainToRendererEmitter.removeListener(str, listener); }, }; } public get ipcMain(): object { return { send: (str: string, ...args: any[]): void => { this.mainToRendererEmitter.emit(str, { sender: module.exports.ipcRenderer, }, ...args); }, on: (str: string, listener: (...args: any[]) => void): void => { this.rendererToMainEmitter.on(str, listener); }, once: (str: string, listener: (...args: any[]) => void): void => { this.rendererToMainEmitter.once(str, listener); }, }; } // tslint:enable no-any } module.exports = new ElectronFill();
packages/ide/src/fill/electron.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.0003077694564126432, 0.00017651868984103203, 0.00016426124784629792, 0.0001708588533801958, 0.000025373417884111404 ]
{ "id": 11, "code_window": [ "\t\t\tthis.activeProcess.kill();\n", "\t\t}\n", "\n", "\t\tlet forkOptions = {\n", "\t\t\tenv: {\n", "\t\t\t\tVSCODE_ALLOW_IO: \"true\"\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tpreserveEnv(forkOptions);\n", "\n", "\t\tconst activeProcess = forkModule(\"vs/code/electron-browser/sharedProcess/sharedProcessMain\", [], forkOptions, this.userDataDir);\n", "\t\tthis.activeProcess = activeProcess;\n", "\n", "\t\tawait new Promise((resolve, reject): void => {\n", "\t\t\tconst doReject = (error: Error | number | null): void => {\n", "\t\t\t\tif (error === null) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst activeProcess = forkModule(\n", "\t\t\t\"vs/code/electron-browser/sharedProcess/sharedProcessMain\", [],\n", "\t\t\twithEnv({ env: { VSCODE_ALLOW_IO: \"true\" } }), this.userDataDir,\n", "\t\t);\n" ], "file_path": "packages/server/src/vscode/sharedProcess.ts", "type": "replace", "edit_start_line_idx": 91 }
import * as nls from "vs/nls"; import { Action } from "vs/base/common/actions"; import { TERMINAL_COMMAND_ID } from "vs/workbench/contrib/terminal/common/terminalCommands"; import { ITerminalService } from "vs/workbench/contrib/terminal/common/terminal"; import * as actions from "vs/workbench/contrib/terminal/browser/terminalActions"; import * as instance from "vs/workbench/contrib/terminal/browser/terminalInstance"; import { client } from "../client"; const getLabel = (key: string, enabled: boolean): string => { return enabled ? nls.localize(key, "Paste") : nls.localize(`${key}WithKeybind`, "Paste (must use keybind)"); }; export class PasteAction extends Action { private static readonly KEY = "paste"; public constructor() { super( "editor.action.clipboardPasteAction", getLabel(PasteAction.KEY, client.clipboard.isEnabled), undefined, client.clipboard.isEnabled, async (): Promise<boolean> => client.clipboard.paste(), ); client.clipboard.onPermissionChange((enabled) => { this.label = getLabel(PasteAction.KEY, enabled); this.enabled = enabled; }); } } class TerminalPasteAction extends Action { private static readonly KEY = "workbench.action.terminal.paste"; public static readonly ID = TERMINAL_COMMAND_ID.PASTE; public static readonly LABEL = nls.localize("workbench.action.terminal.paste", "Paste into Active Terminal"); public static readonly SHORT_LABEL = getLabel(TerminalPasteAction.KEY, client.clipboard.isEnabled); public constructor( id: string, label: string, @ITerminalService private terminalService: ITerminalService, ) { super(id, label); client.clipboard.onPermissionChange((enabled) => { this._setLabel(getLabel(TerminalPasteAction.KEY, enabled)); }); this._setLabel(getLabel(TerminalPasteAction.KEY, client.clipboard.isEnabled)); } public run(): Promise<void> { const instance = this.terminalService.getActiveOrCreateInstance(); if (instance) { // tslint:disable-next-line no-any it will return a promise (see below) return (instance as any).paste(); } return Promise.resolve(); } } class TerminalInstance extends instance.TerminalInstance { public async paste(): Promise<void> { this.focus(); if (client.clipboard.isEnabled) { const text = await client.clipboard.readText(); this.sendText(text, false); } else { document.execCommand("paste"); } } } const actionsTarget = actions as typeof actions; // @ts-ignore TODO: don't ignore it. actionsTarget.TerminalPasteAction = TerminalPasteAction; const instanceTarget = instance as typeof instance; instanceTarget.TerminalInstance = TerminalInstance;
packages/vscode/src/fill/paste.ts
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017575446690898389, 0.00017027689318638295, 0.00016083050286397338, 0.0001718136772979051, 0.000004255198746250244 ]
{ "id": 11, "code_window": [ "\t\t\tthis.activeProcess.kill();\n", "\t\t}\n", "\n", "\t\tlet forkOptions = {\n", "\t\t\tenv: {\n", "\t\t\t\tVSCODE_ALLOW_IO: \"true\"\n", "\t\t\t}\n", "\t\t}\n", "\n", "\t\tpreserveEnv(forkOptions);\n", "\n", "\t\tconst activeProcess = forkModule(\"vs/code/electron-browser/sharedProcess/sharedProcessMain\", [], forkOptions, this.userDataDir);\n", "\t\tthis.activeProcess = activeProcess;\n", "\n", "\t\tawait new Promise((resolve, reject): void => {\n", "\t\t\tconst doReject = (error: Error | number | null): void => {\n", "\t\t\t\tif (error === null) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst activeProcess = forkModule(\n", "\t\t\t\"vs/code/electron-browser/sharedProcess/sharedProcessMain\", [],\n", "\t\t\twithEnv({ env: { VSCODE_ALLOW_IO: \"true\" } }), this.userDataDir,\n", "\t\t);\n" ], "file_path": "packages/server/src/vscode/sharedProcess.ts", "type": "replace", "edit_start_line_idx": 91 }
* @code-asher @kylecarbs Dockerfile @nhooyr
.github/CODEOWNERS
0
https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06
[ 0.00017134756490122527, 0.00017134756490122527, 0.00017134756490122527, 0.00017134756490122527, 0 ]
{ "id": 0, "code_window": [ "\t\tfontStyle: {\n", "\t\t\ttype: 'string',\n", "\t\t\tdescription: nls.localize('schema.token.fontStyle', 'Font style of the rule: \\'italic\\', \\'bold\\' or \\'underline\\' or a combination. The empty string unsets inherited settings.'),\n", "\t\t\tpattern: '^(\\\\s*\\\\b(italic|bold|underline))*\\\\s*$',\n", "\t\t\tpatternErrorMessage: nls.localize('schema.fontStyle.error', 'Font style must be \\'italic\\', \\'bold\\' or \\'underline\\' or a combination or the empty string.'),\n", "\t\t\tdefaultSnippets: [{ body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]\n", "\t\t}\n", "\t},\n", "\tadditionalProperties: false,\n", "\tdefaultSnippets: [{ body: { foreground: '${1:#FF0000}', fontStyle: '${2:bold}' } }]\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tdefaultSnippets: [{ label: nls.localize('schema.token.fontStyle.none', 'None (clear inherited style)'), bodyText: '\"\"' }, { body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "replace", "edit_start_line_idx": 135 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0006002505542710423, 0.00019141723169013858, 0.00016206914733629674, 0.00016846107610035688, 0.00008451842586509883 ]
{ "id": 0, "code_window": [ "\t\tfontStyle: {\n", "\t\t\ttype: 'string',\n", "\t\t\tdescription: nls.localize('schema.token.fontStyle', 'Font style of the rule: \\'italic\\', \\'bold\\' or \\'underline\\' or a combination. The empty string unsets inherited settings.'),\n", "\t\t\tpattern: '^(\\\\s*\\\\b(italic|bold|underline))*\\\\s*$',\n", "\t\t\tpatternErrorMessage: nls.localize('schema.fontStyle.error', 'Font style must be \\'italic\\', \\'bold\\' or \\'underline\\' or a combination or the empty string.'),\n", "\t\t\tdefaultSnippets: [{ body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]\n", "\t\t}\n", "\t},\n", "\tadditionalProperties: false,\n", "\tdefaultSnippets: [{ body: { foreground: '${1:#FF0000}', fontStyle: '${2:bold}' } }]\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tdefaultSnippets: [{ label: nls.localize('schema.token.fontStyle.none', 'None (clear inherited style)'), bodyText: '\"\"' }, { body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "replace", "edit_start_line_idx": 135 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "emmetConfigurationTitle": "Emmet", "triggerExpansionOnTab": "Se abilitate, le abbreviazioni Emmet vengono espanse quando si preme TAB. Non applicabile quando emmet.useNewemmet è impostato su true.", "emmetPreferences": "Preferenze usate per modificare il comportamento di alcune azioni e i resolver di Emmet. Non applicabile quando emmet.useNewemmet è impostato su true.", "emmetSyntaxProfiles": "Consente di definire il profilo per la sintassi specificata oppure di usare un profilo personalizzato con regole specifiche.", "emmetExclude": "Matrice di linguaggi in cui le abbreviazioni Emmet non devono essere espanse.", "emmetExtensionsPath": "Percorso di una cartella contenente snippet, preferenze e profili Emmet. Quando emmet.useNewEmmet è impostato su true, vengono gestiti solo i profili di questo percorso di estensione.", "useNewEmmet": "Prova i nuovi moduli emmet (che andrà a sostituire la vecchia libreria singola emmet) per tutte le funzionalità emmet." }
i18n/ita/src/vs/workbench/parts/emmet/electron-browser/emmet.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017542715067975223, 0.00017498680972494185, 0.0001745464833220467, 0.00017498680972494185, 4.4033367885276675e-7 ]
{ "id": 0, "code_window": [ "\t\tfontStyle: {\n", "\t\t\ttype: 'string',\n", "\t\t\tdescription: nls.localize('schema.token.fontStyle', 'Font style of the rule: \\'italic\\', \\'bold\\' or \\'underline\\' or a combination. The empty string unsets inherited settings.'),\n", "\t\t\tpattern: '^(\\\\s*\\\\b(italic|bold|underline))*\\\\s*$',\n", "\t\t\tpatternErrorMessage: nls.localize('schema.fontStyle.error', 'Font style must be \\'italic\\', \\'bold\\' or \\'underline\\' or a combination or the empty string.'),\n", "\t\t\tdefaultSnippets: [{ body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]\n", "\t\t}\n", "\t},\n", "\tadditionalProperties: false,\n", "\tdefaultSnippets: [{ body: { foreground: '${1:#FF0000}', fontStyle: '${2:bold}' } }]\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tdefaultSnippets: [{ label: nls.localize('schema.token.fontStyle.none', 'None (clear inherited style)'), bodyText: '\"\"' }, { body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "replace", "edit_start_line_idx": 135 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .monaco-editor-overlaymessage { padding-bottom: 8px; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-editor .monaco-editor-overlaymessage.fadeIn { animation: fadeIn 150ms ease-out; } @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } } .monaco-editor .monaco-editor-overlaymessage.fadeOut { animation: fadeOut 100ms ease-out; } .monaco-editor .monaco-editor-overlaymessage .message { padding: 1px 4px; } .monaco-editor .monaco-editor-overlaymessage .anchor { width: 0 !important; height: 0 !important; border-color: transparent; border-style: solid; z-index: 1000; border-width: 8px; position: absolute; }
src/vs/editor/contrib/message/messageController.css
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017553892394062132, 0.0001725630136206746, 0.00017025135457515717, 0.0001722308952594176, 0.0000019002925455424702 ]
{ "id": 0, "code_window": [ "\t\tfontStyle: {\n", "\t\t\ttype: 'string',\n", "\t\t\tdescription: nls.localize('schema.token.fontStyle', 'Font style of the rule: \\'italic\\', \\'bold\\' or \\'underline\\' or a combination. The empty string unsets inherited settings.'),\n", "\t\t\tpattern: '^(\\\\s*\\\\b(italic|bold|underline))*\\\\s*$',\n", "\t\t\tpatternErrorMessage: nls.localize('schema.fontStyle.error', 'Font style must be \\'italic\\', \\'bold\\' or \\'underline\\' or a combination or the empty string.'),\n", "\t\t\tdefaultSnippets: [{ body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]\n", "\t\t}\n", "\t},\n", "\tadditionalProperties: false,\n", "\tdefaultSnippets: [{ body: { foreground: '${1:#FF0000}', fontStyle: '${2:bold}' } }]\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tdefaultSnippets: [{ label: nls.localize('schema.token.fontStyle.none', 'None (clear inherited style)'), bodyText: '\"\"' }, { body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "replace", "edit_start_line_idx": 135 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "binaryFileEditor": "Binärdateianzeige" }
i18n/deu/src/vs/workbench/parts/files/browser/editors/binaryFileEditor.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0001762526953825727, 0.00017178000416606665, 0.00016730731294956058, 0.00017178000416606665, 0.000004472691216506064 ]
{ "id": 1, "code_window": [ "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t]\n", "\t\t\t\t},\n", "\t\t\t\tsettings: tokenColorizationSettingSchema\n", "\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\t\tsettings: tokenColorizationSettingSchema,\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "replace", "edit_start_line_idx": 178 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0024721799418330193, 0.0002827325079124421, 0.00016403273912146688, 0.0001703457091934979, 0.00037636415800079703 ]
{ "id": 1, "code_window": [ "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t]\n", "\t\t\t\t},\n", "\t\t\t\tsettings: tokenColorizationSettingSchema\n", "\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\t\tsettings: tokenColorizationSettingSchema,\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "replace", "edit_start_line_idx": 178 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "updateImageSize": "Emmet: Bildgröße aktualisieren" }
i18n/deu/src/vs/workbench/parts/emmet/node/actions/updateImageSize.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017345215019304305, 0.00017345215019304305, 0.00017345215019304305, 0.00017345215019304305, 0 ]
{ "id": 1, "code_window": [ "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t]\n", "\t\t\t\t},\n", "\t\t\t\tsettings: tokenColorizationSettingSchema\n", "\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\t\tsettings: tokenColorizationSettingSchema,\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "replace", "edit_start_line_idx": 178 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "splitJoinTag": "Emmet: 태그 분할/조인" }
i18n/kor/src/vs/workbench/parts/emmet/electron-browser/actions/splitJoinTag.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017207075143232942, 0.00017207075143232942, 0.00017207075143232942, 0.00017207075143232942, 0 ]
{ "id": 1, "code_window": [ "\t\t\t\t\t\t\t}\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t]\n", "\t\t\t\t},\n", "\t\t\t\tsettings: tokenColorizationSettingSchema\n", "\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\t\tsettings: tokenColorizationSettingSchema,\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "replace", "edit_start_line_idx": 178 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { CommandManager } from './utils/commandManager'; import TypeScriptServiceClientHost from './typeScriptServiceClientHost'; import * as commands from './commands'; import TypeScriptTaskProviderManager from './features/taskProvider'; import { getContributedTypeScriptServerPlugins, TypeScriptServerPlugin } from './utils/plugins'; import * as ProjectStatus from './utils/projectStatus'; import * as languageModeIds from './utils/languageModeIds'; import * as languageConfigurations from './utils/languageConfigurations'; import { standardLanguageDescriptions } from './utils/languageDescription'; import ManagedFileContextManager from './utils/managedFileContext'; import { lazy, Lazy } from './utils/lazy'; import * as fileSchemes from './utils/fileSchemes'; import LogDirectoryProvider from './utils/logDirectoryProvider'; export function activate( context: vscode.ExtensionContext ): void { const plugins = getContributedTypeScriptServerPlugins(); const commandManager = new CommandManager(); context.subscriptions.push(commandManager); const lazyClientHost = createLazyClientHost(context, plugins, commandManager); registerCommands(commandManager, lazyClientHost); context.subscriptions.push(new TypeScriptTaskProviderManager(lazyClientHost.map(x => x.serviceClient))); context.subscriptions.push(vscode.languages.setLanguageConfiguration(languageModeIds.jsxTags, languageConfigurations.jsxTags)); const supportedLanguage = [].concat.apply([], standardLanguageDescriptions.map(x => x.modeIds).concat(plugins.map(x => x.languages))); function didOpenTextDocument(textDocument: vscode.TextDocument): boolean { if (isSupportedDocument(supportedLanguage, textDocument)) { openListener.dispose(); // Force activation // tslint:disable-next-line:no-unused-expression void lazyClientHost.value; context.subscriptions.push(new ManagedFileContextManager(resource => { return lazyClientHost.value.serviceClient.normalizePath(resource); })); return true; } return false; } const openListener = vscode.workspace.onDidOpenTextDocument(didOpenTextDocument, undefined, context.subscriptions); for (const textDocument of vscode.workspace.textDocuments) { if (didOpenTextDocument(textDocument)) { break; } } } function createLazyClientHost( context: vscode.ExtensionContext, plugins: TypeScriptServerPlugin[], commandManager: CommandManager ): Lazy<TypeScriptServiceClientHost> { return lazy(() => { const logDirectoryProvider = new LogDirectoryProvider(context); const clientHost = new TypeScriptServiceClientHost( standardLanguageDescriptions, context.workspaceState, plugins, commandManager, logDirectoryProvider); context.subscriptions.push(clientHost); clientHost.serviceClient.onReady(() => { context.subscriptions.push( ProjectStatus.create( clientHost.serviceClient, clientHost.serviceClient.telemetryReporter, path => new Promise<boolean>(resolve => setTimeout(() => resolve(clientHost.handles(path)), 750)), context.workspaceState)); }); return clientHost; }); } function registerCommands( commandManager: CommandManager, lazyClientHost: Lazy<TypeScriptServiceClientHost> ) { commandManager.register(new commands.ReloadTypeScriptProjectsCommand(lazyClientHost)); commandManager.register(new commands.ReloadJavaScriptProjectsCommand(lazyClientHost)); commandManager.register(new commands.SelectTypeScriptVersionCommand(lazyClientHost)); commandManager.register(new commands.OpenTsServerLogCommand(lazyClientHost)); commandManager.register(new commands.RestartTsServerCommand(lazyClientHost)); commandManager.register(new commands.TypeScriptGoToProjectConfigCommand(lazyClientHost)); commandManager.register(new commands.JavaScriptGoToProjectConfigCommand(lazyClientHost)); } function isSupportedDocument( supportedLanguage: string[], document: vscode.TextDocument ): boolean { if (supportedLanguage.indexOf(document.languageId) < 0) { return false; } return fileSchemes.isSupportedScheme(document.uri.scheme); }
extensions/typescript/src/extension.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017326255328953266, 0.00016986255650408566, 0.00016648154996801168, 0.000170521714608185, 0.0000020624190710805124 ]
{ "id": 2, "code_window": [ "\t\t\t},\n", "\t\t\tadditionalProperties: false\n", "\t\t}\n", "\t};\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\trequired: [\n", "\t\t\t\t'settings', 'scope'\n", "\t\t\t],\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "add", "edit_start_line_idx": 180 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00022108918346930295, 0.00017475654021836817, 0.00016420893371105194, 0.00016793585382401943, 0.00001552222420286853 ]
{ "id": 2, "code_window": [ "\t\t\t},\n", "\t\t\tadditionalProperties: false\n", "\t\t}\n", "\t};\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\trequired: [\n", "\t\t\t\t'settings', 'scope'\n", "\t\t\t],\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "add", "edit_start_line_idx": 180 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "no result": "結果がありません。", "aria": "'{0}' から '{1}' への名前変更が正常に完了しました。概要: {2}", "rename.failed": "申し訳ありません。名前の変更を実行できませんでした。", "rename.label": "シンボルの名前を変更" }
i18n/jpn/src/vs/editor/contrib/rename/browser/rename.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017518842651043087, 0.00017192773520946503, 0.0001686670584604144, 0.00017192773520946503, 0.0000032606840250082314 ]
{ "id": 2, "code_window": [ "\t\t\t},\n", "\t\t\tadditionalProperties: false\n", "\t\t}\n", "\t};\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\trequired: [\n", "\t\t\t\t'settings', 'scope'\n", "\t\t\t],\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "add", "edit_start_line_idx": 180 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path='./node.d.ts'/> declare module 'iconv-lite' { export function decode(buffer: NodeBuffer, encoding: string): string; export function encode(content: string | NodeBuffer, encoding: string, options?: { addBOM?: boolean }): NodeBuffer; export function encodingExists(encoding: string): boolean; export function decodeStream(encoding: string): NodeJS.ReadWriteStream; export function encodeStream(encoding: string, options?: { addBOM?: boolean }): NodeJS.ReadWriteStream; }
src/typings/iconv-lite.d.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017232589016202837, 0.00017018777725752443, 0.0001680496643530205, 0.00017018777725752443, 0.0000021381129045039415 ]
{ "id": 2, "code_window": [ "\t\t\t},\n", "\t\t\tadditionalProperties: false\n", "\t\t}\n", "\t};\n", "}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\trequired: [\n", "\t\t\t\t'settings', 'scope'\n", "\t\t\t],\n" ], "file_path": "src/vs/workbench/services/themes/common/colorThemeSchema.ts", "type": "add", "edit_start_line_idx": 180 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "summary.0": "未做编辑", "summary.nm": "在 {1} 个文件中进行了 {0} 次编辑", "summary.n0": "在 1 个文件中进行了 {0} 次编辑", "conflict": "这些文件也已同时更改: {0}" }
i18n/chs/src/vs/editor/browser/services/bulkEdit.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017001094238366932, 0.00016945117386057973, 0.0001688913907855749, 0.00016945117386057973, 5.597757990472019e-7 ]
{ "id": 3, "code_window": [ "\t}\n", "\n", "\tpublic setCustomColors(colors: IColorCustomizations) {\n", "\t\tthis.customColorMap = {};\n", "\t\tthis.overwriteCustomColors(colors);\n", "\t\tif (`[${this.settingsId}]` in colors) {\n", "\t\t\tconst themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations;\n", "\t\t\tif (types.isObject(themeSpecificColors)) {\n", "\t\t\t\tthis.overwriteCustomColors(themeSpecificColors);\n", "\t\t\t}\n", "\t\t}\n", "\t\tif (this.themeTokenColors && this.themeTokenColors.length) {\n", "\t\t\tupdateDefaultRuleSettings(this.themeTokenColors[0], this);\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tconst themeSpecificColors = colors[`[${this.settingsId}]`] as IColorCustomizations;\n", "\t\tif (types.isObject(themeSpecificColors)) {\n", "\t\t\tthis.overwriteCustomColors(themeSpecificColors);\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 83 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import { Registry } from 'vs/platform/registry/common/platform'; import { Extensions as JSONExtensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { Extensions as ThemeingExtensions, IColorRegistry } from 'vs/platform/theme/common/colorRegistry'; let themingRegistry = <IColorRegistry>Registry.as(ThemeingExtensions.ColorContribution); let textMateScopes = [ 'comment', 'comment.block', 'comment.block.documentation', 'comment.line', 'constant', 'constant.character', 'constant.character.escape', 'constant.numeric', 'constant.numeric.integer', 'constant.numeric.float', 'constant.numeric.hex', 'constant.numeric.octal', 'constant.other', 'constant.regexp', 'constant.rgb-value', 'emphasis', 'entity', 'entity.name', 'entity.name.class', 'entity.name.function', 'entity.name.method', 'entity.name.section', 'entity.name.selector', 'entity.name.tag', 'entity.name.type', 'entity.other', 'entity.other.attribute-name', 'entity.other.inherited-class', 'invalid', 'invalid.deprecated', 'invalid.illegal', 'keyword', 'keyword.control', 'keyword.operator', 'keyword.operator.new', 'keyword.operator.assignment', 'keyword.operator.arithmetic', 'keyword.operator.logical', 'keyword.other', 'markup', 'markup.bold', 'markup.changed', 'markup.deleted', 'markup.heading', 'markup.inline.raw', 'markup.inserted', 'markup.italic', 'markup.list', 'markup.list.numbered', 'markup.list.unnumbered', 'markup.other', 'markup.quote', 'markup.raw', 'markup.underline', 'markup.underline.link', 'meta', 'meta.block', 'meta.cast', 'meta.class', 'meta.function', 'meta.function-call', 'meta.preprocessor', 'meta.return-type', 'meta.selector', 'meta.tag', 'meta.type.annotation', 'meta.type', 'punctuation.definition.string.begin', 'punctuation.definition.string.end', 'punctuation.separator', 'punctuation.separator.continuation', 'punctuation.terminator', 'storage', 'storage.modifier', 'storage.type', 'string', 'string.interpolated', 'string.other', 'string.quoted', 'string.quoted.double', 'string.quoted.other', 'string.quoted.single', 'string.quoted.triple', 'string.regexp', 'string.unquoted', 'strong', 'support', 'support.class', 'support.constant', 'support.function', 'support.other', 'support.type', 'support.type.property-name', 'support.variable', 'variable', 'variable.language', 'variable.name', 'variable.other', 'variable.other.readwrite', 'variable.parameter' ]; export const tokenColorizationSettingSchema: IJSONSchema = { type: 'object', description: nls.localize('schema.token.settings', 'Colors and styles for the token.'), properties: { foreground: { type: 'string', description: nls.localize('schema.token.foreground', 'Foreground color for the token.'), format: 'color-hex', default: '#ff0000' }, background: { type: 'string', deprecationMessage: nls.localize('schema.token.background.warning', 'Token background colors are currently not supported.') }, fontStyle: { type: 'string', description: nls.localize('schema.token.fontStyle', 'Font style of the rule: \'italic\', \'bold\' or \'underline\' or a combination. The empty string unsets inherited settings.'), pattern: '^(\\s*\\b(italic|bold|underline))*\\s*$', patternErrorMessage: nls.localize('schema.fontStyle.error', 'Font style must be \'italic\', \'bold\' or \'underline\' or a combination or the empty string.'), defaultSnippets: [{ body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }] } }, additionalProperties: false, defaultSnippets: [{ body: { foreground: '${1:#FF0000}', fontStyle: '${2:bold}' } }] }; export const colorsSchema = themingRegistry.getColorSchema(); export function tokenColorsSchema(description: string): IJSONSchema { return { type: 'array', description, items: { type: 'object', defaultSnippets: [{ body: { scope: '${1:keyword.operator}', settings: { foreground: '${2:#FF0000}' } } }], properties: { name: { type: 'string', description: nls.localize('schema.properties.name', 'Description of the rule.') }, scope: { description: nls.localize('schema.properties.scope', 'Scope selector against which this rule matches.'), anyOf: [ { enum: textMateScopes }, { type: 'string' }, { type: 'array', items: { enum: textMateScopes } }, { type: 'array', items: { type: 'string' } } ] }, settings: tokenColorizationSettingSchema }, additionalProperties: false } }; } const schemaId = 'vscode://schemas/color-theme'; const schema: IJSONSchema = { type: 'object', allowComments: true, properties: { colors: colorsSchema, tokenColors: { anyOf: [{ type: 'string', description: nls.localize('schema.tokenColors.path', 'Path to a tmTheme file (relative to the current file).') }, tokenColorsSchema(nls.localize('schema.colors', 'Colors for syntax highlighting')) ] } } }; export function register() { let schemaRegistry = <IJSONContributionRegistry>Registry.as(JSONExtensions.JSONContribution); schemaRegistry.registerSchema(schemaId, schema); }
src/vs/workbench/services/themes/common/colorThemeSchema.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.002586653921753168, 0.00028598090284503996, 0.00016452943964395672, 0.00017181433213409036, 0.0005144556635059416 ]
{ "id": 3, "code_window": [ "\t}\n", "\n", "\tpublic setCustomColors(colors: IColorCustomizations) {\n", "\t\tthis.customColorMap = {};\n", "\t\tthis.overwriteCustomColors(colors);\n", "\t\tif (`[${this.settingsId}]` in colors) {\n", "\t\t\tconst themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations;\n", "\t\t\tif (types.isObject(themeSpecificColors)) {\n", "\t\t\t\tthis.overwriteCustomColors(themeSpecificColors);\n", "\t\t\t}\n", "\t\t}\n", "\t\tif (this.themeTokenColors && this.themeTokenColors.length) {\n", "\t\t\tupdateDefaultRuleSettings(this.themeTokenColors[0], this);\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tconst themeSpecificColors = colors[`[${this.settingsId}]`] as IColorCustomizations;\n", "\t\tif (types.isObject(themeSpecificColors)) {\n", "\t\t\tthis.overwriteCustomColors(themeSpecificColors);\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 83 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "noWorkspace": "열린 폴더 없음", "explorerSection": "파일 탐색기 섹션", "noWorkspaceHelp": "작업 영역에 아직 폴더를 추가하지 않았습니다.", "addFolder": "폴더 추가", "noFolderHelp": "아직 폴더를 열지 않았습니다.", "openFolder": "폴더 열기" }
i18n/kor/src/vs/workbench/parts/files/electron-browser/views/emptyView.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017711898544803262, 0.00017393814050592482, 0.00017075729556381702, 0.00017393814050592482, 0.0000031808449421077967 ]
{ "id": 3, "code_window": [ "\t}\n", "\n", "\tpublic setCustomColors(colors: IColorCustomizations) {\n", "\t\tthis.customColorMap = {};\n", "\t\tthis.overwriteCustomColors(colors);\n", "\t\tif (`[${this.settingsId}]` in colors) {\n", "\t\t\tconst themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations;\n", "\t\t\tif (types.isObject(themeSpecificColors)) {\n", "\t\t\t\tthis.overwriteCustomColors(themeSpecificColors);\n", "\t\t\t}\n", "\t\t}\n", "\t\tif (this.themeTokenColors && this.themeTokenColors.length) {\n", "\t\t\tupdateDefaultRuleSettings(this.themeTokenColors[0], this);\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tconst themeSpecificColors = colors[`[${this.settingsId}]`] as IColorCustomizations;\n", "\t\tif (types.isObject(themeSpecificColors)) {\n", "\t\t\tthis.overwriteCustomColors(themeSpecificColors);\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 83 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "mutlicursor.insertAbove": "Ajouter un curseur au-dessus", "mutlicursor.insertBelow": "Ajouter un curseur en dessous", "mutlicursor.insertAtEndOfEachLineSelected": "Ajouter des curseurs à la fin des lignes", "addSelectionToNextFindMatch": "Ajouter la sélection à la correspondance de recherche suivante", "addSelectionToPreviousFindMatch": "Ajouter la sélection à la correspondance de recherche précédente", "moveSelectionToNextFindMatch": "Déplacer la dernière sélection vers la correspondance de recherche suivante", "moveSelectionToPreviousFindMatch": "Déplacer la dernière sélection à la correspondance de recherche précédente", "selectAllOccurrencesOfFindMatch": "Sélectionner toutes les occurrences des correspondances de la recherche", "changeAll.label": "Modifier toutes les occurrences" }
i18n/fra/src/vs/editor/contrib/multicursor/multicursor.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017717100854497403, 0.00017609031056053936, 0.0001750096125761047, 0.00017609031056053936, 0.0000010806979844346642 ]
{ "id": 3, "code_window": [ "\t}\n", "\n", "\tpublic setCustomColors(colors: IColorCustomizations) {\n", "\t\tthis.customColorMap = {};\n", "\t\tthis.overwriteCustomColors(colors);\n", "\t\tif (`[${this.settingsId}]` in colors) {\n", "\t\t\tconst themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations;\n", "\t\t\tif (types.isObject(themeSpecificColors)) {\n", "\t\t\t\tthis.overwriteCustomColors(themeSpecificColors);\n", "\t\t\t}\n", "\t\t}\n", "\t\tif (this.themeTokenColors && this.themeTokenColors.length) {\n", "\t\t\tupdateDefaultRuleSettings(this.themeTokenColors[0], this);\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tconst themeSpecificColors = colors[`[${this.settingsId}]`] as IColorCustomizations;\n", "\t\tif (types.isObject(themeSpecificColors)) {\n", "\t\t\tthis.overwriteCustomColors(themeSpecificColors);\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 83 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "showTriggerActions": "Mostrar todos os comandos", "clearCommandHistory": "Limpar o Histórico de Comandos", "showCommands.label": "Paleta de comandos...", "entryAriaLabelWithKey": "{0}, {1}, comandos", "entryAriaLabel": "{0}, comandos", "canNotRun": "O comando '{0}' não pode ser executado a partir daqui.", "actionNotEnabled": "O comando '{0}' não está habilitado no contexto atual.", "recentlyUsed": "usados recentemente", "morecCommands": "outros comandos", "cat.title": "{0}: {1}", "noCommandsMatching": "Não há comandos correspondentes" }
i18n/ptb/src/vs/workbench/parts/quickopen/browser/commandsHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017713992565404624, 0.00017459761875215918, 0.00016996037447825074, 0.00017669255612418056, 0.0000032841091979207704 ]
{ "id": 4, "code_window": [ "\n", "\tpublic setCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n", "\t\tthis.customTokenColors = [];\n", "\t\tlet customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {};\n", "\t\tfor (let key in customTokenColors) {\n", "\t\t\tif (key[0] !== '[') {\n", "\t\t\t\tcustomTokenColorsWithoutThemeSpecific[key] = customTokenColors[key];\n", "\t\t\t}\n", "\t\t}\n", "\t\tthis.addCustomTokenColors(customTokenColorsWithoutThemeSpecific);\n", "\t\tif (`[${this.settingsId}]` in customTokenColors) {\n", "\t\t\tconst themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`];\n", "\t\t\tif (types.isObject(themeSpecificTokenColors)) {\n", "\t\t\t\tthis.addCustomTokenColors(themeSpecificTokenColors);\n", "\t\t\t}\n", "\t\t}\n", "\t}\n", "\n", "\tprivate addCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// first add the non-theme specific settings\n", "\t\tthis.addCustomTokenColors(customTokenColors);\n", "\n", "\t\t// append theme specific settings. Last rules will win.\n", "\t\tconst themeSpecificTokenColors = customTokenColors[`[${this.settingsId}]`] as ITokenColorCustomizations;\n", "\t\tif (types.isObject(themeSpecificTokenColors)) {\n", "\t\t\tthis.addCustomTokenColors(themeSpecificTokenColors);\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 105 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.9981088638305664, 0.057785023003816605, 0.00016294431407004595, 0.0014680750900879502, 0.22180631756782532 ]
{ "id": 4, "code_window": [ "\n", "\tpublic setCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n", "\t\tthis.customTokenColors = [];\n", "\t\tlet customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {};\n", "\t\tfor (let key in customTokenColors) {\n", "\t\t\tif (key[0] !== '[') {\n", "\t\t\t\tcustomTokenColorsWithoutThemeSpecific[key] = customTokenColors[key];\n", "\t\t\t}\n", "\t\t}\n", "\t\tthis.addCustomTokenColors(customTokenColorsWithoutThemeSpecific);\n", "\t\tif (`[${this.settingsId}]` in customTokenColors) {\n", "\t\t\tconst themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`];\n", "\t\t\tif (types.isObject(themeSpecificTokenColors)) {\n", "\t\t\t\tthis.addCustomTokenColors(themeSpecificTokenColors);\n", "\t\t\t}\n", "\t\t}\n", "\t}\n", "\n", "\tprivate addCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// first add the non-theme specific settings\n", "\t\tthis.addCustomTokenColors(customTokenColors);\n", "\n", "\t\t// append theme specific settings. Last rules will win.\n", "\t\tconst themeSpecificTokenColors = customTokenColors[`[${this.settingsId}]`] as ITokenColorCustomizations;\n", "\t\tif (types.isObject(themeSpecificTokenColors)) {\n", "\t\t\tthis.addCustomTokenColors(themeSpecificTokenColors);\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 105 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "editorCommand.activeEditorMove.description": "Consente di spostare l'editor attivo per schede o gruppi", "editorCommand.activeEditorMove.arg.name": "Argomento per spostamento editor attivo", "editorCommand.activeEditorMove.arg.description": "Proprietà degli argomenti:\n\t* 'to': valore stringa che specifica dove eseguire lo spostamento.\n\t* 'by': valore stringa che specifica l'unità per lo spostamento, ovvero per scheda o per gruppo.\n\t* 'value': valore numerico che specifica il numero di posizioni o una posizione assoluta per lo spostamento." }
i18n/ita/src/vs/workbench/browser/parts/editor/editorCommands.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0001724953908706084, 0.00017032158211804926, 0.0001681477588135749, 0.00017032158211804926, 0.0000021738160285167396 ]
{ "id": 4, "code_window": [ "\n", "\tpublic setCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n", "\t\tthis.customTokenColors = [];\n", "\t\tlet customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {};\n", "\t\tfor (let key in customTokenColors) {\n", "\t\t\tif (key[0] !== '[') {\n", "\t\t\t\tcustomTokenColorsWithoutThemeSpecific[key] = customTokenColors[key];\n", "\t\t\t}\n", "\t\t}\n", "\t\tthis.addCustomTokenColors(customTokenColorsWithoutThemeSpecific);\n", "\t\tif (`[${this.settingsId}]` in customTokenColors) {\n", "\t\t\tconst themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`];\n", "\t\t\tif (types.isObject(themeSpecificTokenColors)) {\n", "\t\t\t\tthis.addCustomTokenColors(themeSpecificTokenColors);\n", "\t\t\t}\n", "\t\t}\n", "\t}\n", "\n", "\tprivate addCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// first add the non-theme specific settings\n", "\t\tthis.addCustomTokenColors(customTokenColors);\n", "\n", "\t\t// append theme specific settings. Last rules will win.\n", "\t\tconst themeSpecificTokenColors = customTokenColors[`[${this.settingsId}]`] as ITokenColorCustomizations;\n", "\t\tif (types.isObject(themeSpecificTokenColors)) {\n", "\t\t\tthis.addCustomTokenColors(themeSpecificTokenColors);\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 105 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { renderViewLine2 as renderViewLine, RenderLineInput, CharacterMapping } from 'vs/editor/common/viewLayout/viewLineRenderer'; import { ViewLineToken, ViewLineTokens } from 'vs/editor/test/common/core/viewLineToken'; import { CharCode } from 'vs/base/common/charCode'; import { MetadataConsts } from 'vs/editor/common/modes'; import { LineDecoration } from 'vs/editor/common/viewLayout/lineDecorations'; import { InlineDecorationType } from 'vs/editor/common/viewModel/viewModel'; import { IViewLineTokens } from 'vs/editor/common/core/lineTokens'; function createViewLineTokens(viewLineTokens: ViewLineToken[]): IViewLineTokens { return new ViewLineTokens(viewLineTokens); } function createPart(endIndex: number, foreground: number): ViewLineToken { return new ViewLineToken(endIndex, ( foreground << MetadataConsts.FOREGROUND_OFFSET ) >>> 0); } suite('viewLineRenderer.renderLine', () => { function assertCharacterReplacement(lineContent: string, tabSize: number, expected: string, expectedCharOffsetInPart: number[][], expectedPartLengts: number[]): void { let _actual = renderViewLine(new RenderLineInput( false, lineContent, false, 0, createViewLineTokens([new ViewLineToken(lineContent.length, 0)]), [], tabSize, 0, -1, 'none', false, false )); assert.equal(_actual.html, '<span><span class="mtk0">' + expected + '</span></span>'); assertCharacterMapping(_actual.characterMapping, expectedCharOffsetInPart, expectedPartLengts); } test('replaces spaces', () => { assertCharacterReplacement(' ', 4, '\u00a0', [[0, 1]], [1]); assertCharacterReplacement(' ', 4, '\u00a0\u00a0', [[0, 1, 2]], [2]); assertCharacterReplacement('a b', 4, 'a\u00a0\u00a0b', [[0, 1, 2, 3, 4]], [4]); }); test('escapes HTML markup', () => { assertCharacterReplacement('a<b', 4, 'a&lt;b', [[0, 1, 2, 3]], [3]); assertCharacterReplacement('a>b', 4, 'a&gt;b', [[0, 1, 2, 3]], [3]); assertCharacterReplacement('a&b', 4, 'a&amp;b', [[0, 1, 2, 3]], [3]); }); test('replaces some bad characters', () => { assertCharacterReplacement('a\0b', 4, 'a&#00;b', [[0, 1, 2, 3]], [3]); assertCharacterReplacement('a' + String.fromCharCode(CharCode.UTF8_BOM) + 'b', 4, 'a\ufffdb', [[0, 1, 2, 3]], [3]); assertCharacterReplacement('a\u2028b', 4, 'a\ufffdb', [[0, 1, 2, 3]], [3]); }); test('handles tabs', () => { assertCharacterReplacement('\t', 4, '\u00a0\u00a0\u00a0\u00a0', [[0, 4]], [4]); assertCharacterReplacement('x\t', 4, 'x\u00a0\u00a0\u00a0', [[0, 1, 4]], [4]); assertCharacterReplacement('xx\t', 4, 'xx\u00a0\u00a0', [[0, 1, 2, 4]], [4]); assertCharacterReplacement('xxx\t', 4, 'xxx\u00a0', [[0, 1, 2, 3, 4]], [4]); assertCharacterReplacement('xxxx\t', 4, 'xxxx\u00a0\u00a0\u00a0\u00a0', [[0, 1, 2, 3, 4, 8]], [8]); }); function assertParts(lineContent: string, tabSize: number, parts: ViewLineToken[], expected: string, expectedCharOffsetInPart: number[][], expectedPartLengts: number[]): void { let _actual = renderViewLine(new RenderLineInput( false, lineContent, false, 0, createViewLineTokens(parts), [], tabSize, 0, -1, 'none', false, false )); assert.equal(_actual.html, '<span>' + expected + '</span>'); assertCharacterMapping(_actual.characterMapping, expectedCharOffsetInPart, expectedPartLengts); } test('empty line', () => { assertParts('', 4, [], '<span>\u00a0</span>', [], []); }); test('uses part type', () => { assertParts('x', 4, [createPart(1, 10)], '<span class="mtk10">x</span>', [[0, 1]], [1]); assertParts('x', 4, [createPart(1, 20)], '<span class="mtk20">x</span>', [[0, 1]], [1]); assertParts('x', 4, [createPart(1, 30)], '<span class="mtk30">x</span>', [[0, 1]], [1]); }); test('two parts', () => { assertParts('xy', 4, [createPart(1, 1), createPart(2, 2)], '<span class="mtk1">x</span><span class="mtk2">y</span>', [[0], [0, 1]], [1, 1]); assertParts('xyz', 4, [createPart(1, 1), createPart(3, 2)], '<span class="mtk1">x</span><span class="mtk2">yz</span>', [[0], [0, 1, 2]], [1, 2]); assertParts('xyz', 4, [createPart(2, 1), createPart(3, 2)], '<span class="mtk1">xy</span><span class="mtk2">z</span>', [[0, 1], [0, 1]], [2, 1]); }); test('overflow', () => { let _actual = renderViewLine(new RenderLineInput( false, 'Hello world!', false, 0, createViewLineTokens([ createPart(1, 0), createPart(2, 1), createPart(3, 2), createPart(4, 3), createPart(5, 4), createPart(6, 5), createPart(7, 6), createPart(8, 7), createPart(9, 8), createPart(10, 9), createPart(11, 10), createPart(12, 11), ]), [], 4, 10, 6, 'boundary', false, false )); let expectedOutput = [ '<span class="mtk0">H</span>', '<span class="mtk1">e</span>', '<span class="mtk2">l</span>', '<span class="mtk3">l</span>', '<span class="mtk4">o</span>', '<span class="mtk5">\u00a0</span>', '<span>&hellip;</span>' ].join(''); assert.equal(_actual.html, '<span>' + expectedOutput + '</span>'); assertCharacterMapping(_actual.characterMapping, [ [0], [0], [0], [0], [0], [0, 1], ], [1, 1, 1, 1, 1, 1] ); }); test('typical line', () => { let lineText = '\t export class Game { // http://test.com '; let lineParts = createViewLineTokens([ createPart(5, 1), createPart(11, 2), createPart(12, 3), createPart(17, 4), createPart(18, 5), createPart(22, 6), createPart(23, 7), createPart(24, 8), createPart(25, 9), createPart(28, 10), createPart(43, 11), createPart(48, 12), ]); let expectedOutput = [ '<span class="vs-whitespace" style="width:40px">\u2192\u00a0\u00a0\u00a0</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '<span class="mtk2">export</span>', '<span class="mtk3">\u00a0</span>', '<span class="mtk4">class</span>', '<span class="mtk5">\u00a0</span>', '<span class="mtk6">Game</span>', '<span class="mtk7">\u00a0</span>', '<span class="mtk8">{</span>', '<span class="mtk9">\u00a0</span>', '<span class="mtk10">//\u00a0</span>', '<span class="mtk11">http://test.com</span>', '<span class="vs-whitespace" style="width:20px">\u00b7\u00b7</span>', '<span class="vs-whitespace" style="width:30px">\u00b7\u00b7\u00b7</span>' ].join(''); let expectedOffsetsArr = [ [0], [0, 1, 2, 3], [0, 1, 2, 3, 4, 5], [0], [0, 1, 2, 3, 4], [0], [0, 1, 2, 3], [0], [0], [0], [0, 1, 2], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [0, 1], [0, 1, 2, 3], ]; let _actual = renderViewLine(new RenderLineInput( false, lineText, false, 0, lineParts, [], 4, 10, -1, 'boundary', false, false )); assert.equal(_actual.html, '<span>' + expectedOutput + '</span>'); assertCharacterMapping(_actual.characterMapping, expectedOffsetsArr, [4, 4, 6, 1, 5, 1, 4, 1, 1, 1, 3, 15, 2, 3]); }); test('issue #2255: Weird line rendering part 1', () => { let lineText = '\t\t\tcursorStyle:\t\t\t\t\t\t(prevOpts.cursorStyle !== newOpts.cursorStyle),'; let lineParts = createViewLineTokens([ createPart(3, 1), // 3 chars createPart(15, 2), // 12 chars createPart(21, 3), // 6 chars createPart(22, 4), // 1 char createPart(43, 5), // 21 chars createPart(45, 6), // 2 chars createPart(46, 7), // 1 char createPart(66, 8), // 20 chars createPart(67, 9), // 1 char createPart(68, 10), // 2 chars ]); let expectedOutput = [ '<span class="mtk1">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0</span>', '<span class="mtk2">cursorStyle:</span>', '<span class="mtk3">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0</span>', '<span class="mtk4">(</span>', '<span class="mtk5">prevOpts.cursorStyle\u00a0</span>', '<span class="mtk6">!=</span>', '<span class="mtk7">=</span>', '<span class="mtk8">\u00a0newOpts.cursorStyle</span>', '<span class="mtk9">)</span>', '<span class="mtk10">,</span>', ].join(''); let expectedOffsetsArr = [ [0, 4, 8], // 3 chars [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], // 12 chars [0, 4, 8, 12, 16, 20], // 6 chars [0], // 1 char [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], // 21 chars [0, 1], // 2 chars [0], // 1 char [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], // 20 chars [0], // 1 char [0, 1] // 2 chars ]; let _actual = renderViewLine(new RenderLineInput( false, lineText, false, 0, lineParts, [], 4, 10, -1, 'none', false, false )); assert.equal(_actual.html, '<span>' + expectedOutput + '</span>'); assertCharacterMapping(_actual.characterMapping, expectedOffsetsArr, [12, 12, 24, 1, 21, 2, 1, 20, 1, 1]); }); test('issue #2255: Weird line rendering part 2', () => { let lineText = ' \t\t\tcursorStyle:\t\t\t\t\t\t(prevOpts.cursorStyle !== newOpts.cursorStyle),'; let lineParts = createViewLineTokens([ createPart(4, 1), // 4 chars createPart(16, 2), // 12 chars createPart(22, 3), // 6 chars createPart(23, 4), // 1 char createPart(44, 5), // 21 chars createPart(46, 6), // 2 chars createPart(47, 7), // 1 char createPart(67, 8), // 20 chars createPart(68, 9), // 1 char createPart(69, 10), // 2 chars ]); let expectedOutput = [ '<span class="mtk1">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0</span>', '<span class="mtk2">cursorStyle:</span>', '<span class="mtk3">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0</span>', '<span class="mtk4">(</span>', '<span class="mtk5">prevOpts.cursorStyle\u00a0</span>', '<span class="mtk6">!=</span>', '<span class="mtk7">=</span>', '<span class="mtk8">\u00a0newOpts.cursorStyle</span>', '<span class="mtk9">)</span>', '<span class="mtk10">,</span>', ].join(''); let expectedOffsetsArr = [ [0, 1, 4, 8], // 4 chars [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], // 12 chars [0, 4, 8, 12, 16, 20], // 6 chars [0], // 1 char [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], // 21 chars [0, 1], // 2 chars [0], // 1 char [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], // 20 chars [0], // 1 char [0, 1] // 2 chars ]; let _actual = renderViewLine(new RenderLineInput( false, lineText, false, 0, lineParts, [], 4, 10, -1, 'none', false, false )); assert.equal(_actual.html, '<span>' + expectedOutput + '</span>'); assertCharacterMapping(_actual.characterMapping, expectedOffsetsArr, [12, 12, 24, 1, 21, 2, 1, 20, 1, 1]); }); test('issue Microsoft/monaco-editor#280: Improved source code rendering for RTL languages', () => { let lineText = 'var קודמות = \"מיותר קודמות צ\'ט של, אם לשון העברית שינויים ויש, אם\";'; let lineParts = createViewLineTokens([ createPart(3, 6), createPart(13, 1), createPart(66, 20), createPart(67, 1), ]); let expectedOutput = [ '<span class="mtk6" dir="ltr">var</span>', '<span class="mtk1" dir="ltr">\u00a0קודמות\u00a0=\u00a0</span>', '<span class="mtk20" dir="ltr">"מיותר\u00a0קודמות\u00a0צ\'ט\u00a0של,\u00a0אם\u00a0לשון\u00a0העברית\u00a0שינויים\u00a0ויש,\u00a0אם"</span>', '<span class="mtk1" dir="ltr">;</span>' ].join(''); let _actual = renderViewLine(new RenderLineInput( false, lineText, true, 0, lineParts, [], 4, 10, -1, 'none', false, false )); assert.equal(_actual.html, '<span>' + expectedOutput + '</span>'); assert.equal(_actual.containsRTL, true); }); test('issue #6885: Splits large tokens', () => { // 1 1 1 // 1 2 3 4 5 6 7 8 9 0 1 2 // 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234 let _lineText = 'This is just a long line that contains very interesting text. This is just a long line that contains very interesting text.'; function assertSplitsTokens(message: string, lineText: string, expectedOutput: string[]): void { let lineParts = createViewLineTokens([createPart(lineText.length, 1)]); let actual = renderViewLine(new RenderLineInput( false, lineText, false, 0, lineParts, [], 4, 10, -1, 'none', false, false )); assert.equal(actual.html, '<span>' + expectedOutput.join('') + '</span>', message); } // A token with 49 chars { assertSplitsTokens( '49 chars', _lineText.substr(0, 49), [ '<span class="mtk1">This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains\u00a0very\u00a0inter</span>', ] ); } // A token with 50 chars { assertSplitsTokens( '50 chars', _lineText.substr(0, 50), [ '<span class="mtk1">This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains\u00a0very\u00a0intere</span>', ] ); } // A token with 51 chars { assertSplitsTokens( '51 chars', _lineText.substr(0, 51), [ '<span class="mtk1">This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains\u00a0very\u00a0intere</span>', '<span class="mtk1">s</span>', ] ); } // A token with 99 chars { assertSplitsTokens( '99 chars', _lineText.substr(0, 99), [ '<span class="mtk1">This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains\u00a0very\u00a0intere</span>', '<span class="mtk1">sting\u00a0text.\u00a0This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contain</span>', ] ); } // A token with 100 chars { assertSplitsTokens( '100 chars', _lineText.substr(0, 100), [ '<span class="mtk1">This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains\u00a0very\u00a0intere</span>', '<span class="mtk1">sting\u00a0text.\u00a0This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains</span>', ] ); } // A token with 101 chars { assertSplitsTokens( '101 chars', _lineText.substr(0, 101), [ '<span class="mtk1">This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains\u00a0very\u00a0intere</span>', '<span class="mtk1">sting\u00a0text.\u00a0This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains</span>', '<span class="mtk1">\u00a0</span>', ] ); } }); test('issue #21476: Does not split large tokens when ligatures are on', () => { // 1 1 1 // 1 2 3 4 5 6 7 8 9 0 1 2 // 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234 let _lineText = 'This is just a long line that contains very interesting text. This is just a long line that contains very interesting text.'; function assertSplitsTokens(message: string, lineText: string, expectedOutput: string[]): void { let lineParts = createViewLineTokens([createPart(lineText.length, 1)]); let actual = renderViewLine(new RenderLineInput( false, lineText, false, 0, lineParts, [], 4, 10, -1, 'none', false, true )); assert.equal(actual.html, '<span>' + expectedOutput.join('') + '</span>', message); } // A token with 101 chars { assertSplitsTokens( '101 chars', _lineText.substr(0, 101), [ '<span class="mtk1">This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains\u00a0very\u00a0interesting\u00a0text.\u00a0This\u00a0is\u00a0just\u00a0a\u00a0long\u00a0line\u00a0that\u00a0contains\u00a0</span>', ] ); } }); test('issue #20624: Unaligned surrogate pairs are corrupted at multiples of 50 columns', () => { let lineText = 'a𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷'; let lineParts = createViewLineTokens([createPart(lineText.length, 1)]); let actual = renderViewLine(new RenderLineInput( false, lineText, false, 0, lineParts, [], 4, 10, -1, 'none', false, false )); let expectedOutput = [ '<span class="mtk1">a𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷</span>', '<span class="mtk1">𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷</span>', '<span class="mtk1">𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷</span>', '<span class="mtk1">𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷</span>', '<span class="mtk1">𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷𠮷</span>', ]; assert.equal(actual.html, '<span>' + expectedOutput.join('') + '</span>'); }); test('issue #6885: Does not split large tokens in RTL text', () => { let lineText = 'את גרמנית בהתייחסות שמו, שנתי המשפט אל חפש, אם כתב אחרים ולחבר. של התוכן אודות בויקיפדיה כלל, של עזרה כימיה היא. על עמוד יוצרים מיתולוגיה סדר, אם שכל שתפו לעברית שינויים, אם שאלות אנגלית עזה. שמות בקלות מה סדר.'; let lineParts = createViewLineTokens([createPart(lineText.length, 1)]); let expectedOutput = [ '<span class="mtk1" dir="ltr">את\u00a0גרמנית\u00a0בהתייחסות\u00a0שמו,\u00a0שנתי\u00a0המשפט\u00a0אל\u00a0חפש,\u00a0אם\u00a0כתב\u00a0אחרים\u00a0ולחבר.\u00a0של\u00a0התוכן\u00a0אודות\u00a0בויקיפדיה\u00a0כלל,\u00a0של\u00a0עזרה\u00a0כימיה\u00a0היא.\u00a0על\u00a0עמוד\u00a0יוצרים\u00a0מיתולוגיה\u00a0סדר,\u00a0אם\u00a0שכל\u00a0שתפו\u00a0לעברית\u00a0שינויים,\u00a0אם\u00a0שאלות\u00a0אנגלית\u00a0עזה.\u00a0שמות\u00a0בקלות\u00a0מה\u00a0סדר.</span>' ]; let actual = renderViewLine(new RenderLineInput( false, lineText, true, 0, lineParts, [], 4, 10, -1, 'none', false, false )); assert.equal(actual.html, '<span>' + expectedOutput.join('') + '</span>'); assert.equal(actual.containsRTL, true); }); test('issue #19673: Monokai Theme bad-highlighting in line wrap', () => { let lineText = ' MongoCallback<string>): void {'; let lineParts = createViewLineTokens([ createPart(17, 1), createPart(18, 2), createPart(24, 3), createPart(26, 4), createPart(27, 5), createPart(28, 6), createPart(32, 7), createPart(34, 8), ]); let expectedOutput = [ '<span class="">\u00a0\u00a0\u00a0\u00a0</span>', '<span class="mtk1">MongoCallback</span>', '<span class="mtk2">&lt;</span>', '<span class="mtk3">string</span>', '<span class="mtk4">&gt;)</span>', '<span class="mtk5">:</span>', '<span class="mtk6">\u00a0</span>', '<span class="mtk7">void</span>', '<span class="mtk8">\u00a0{</span>' ].join(''); let _actual = renderViewLine(new RenderLineInput( true, lineText, false, 4, lineParts, [], 4, 10, -1, 'none', false, false )); assert.equal(_actual.html, '<span>' + expectedOutput + '</span>'); }); function assertCharacterMapping(actual: CharacterMapping, expectedCharPartOffsets: number[][], expectedPartLengths: number[]): void { assertCharPartOffsets(actual, expectedCharPartOffsets); let expectedCharAbsoluteOffset: number[] = [], currentPartAbsoluteOffset = 0; for (let partIndex = 0; partIndex < expectedCharPartOffsets.length; partIndex++) { const part = expectedCharPartOffsets[partIndex]; for (let i = 0; i < part.length; i++) { const charIndex = part[i]; expectedCharAbsoluteOffset.push(currentPartAbsoluteOffset + charIndex); } currentPartAbsoluteOffset += expectedPartLengths[partIndex]; } let actualCharOffset: number[] = []; let tmp = actual.getAbsoluteOffsets(); for (let i = 0; i < tmp.length; i++) { actualCharOffset[i] = tmp[i]; } assert.deepEqual(actualCharOffset, expectedCharAbsoluteOffset); } function assertCharPartOffsets(actual: CharacterMapping, expected: number[][]): void { let charOffset = 0; for (let partIndex = 0; partIndex < expected.length; partIndex++) { let part = expected[partIndex]; for (let i = 0; i < part.length; i++) { let charIndex = part[i]; // here let _actualPartData = actual.charOffsetToPartData(charOffset); let actualPartIndex = CharacterMapping.getPartIndex(_actualPartData); let actualCharIndex = CharacterMapping.getCharIndex(_actualPartData); assert.deepEqual( { partIndex: actualPartIndex, charIndex: actualCharIndex }, { partIndex: partIndex, charIndex: charIndex }, `character mapping for offset ${charOffset}` ); // here let actualOffset = actual.partDataToCharOffset(partIndex, part[part.length - 1] + 1, charIndex); assert.equal( actualOffset, charOffset, `character mapping for part ${partIndex}, ${charIndex}` ); charOffset++; } } assert.equal(actual.length, charOffset); } }); suite('viewLineRenderer.renderLine 2', () => { function testCreateLineParts(fontIsMonospace: boolean, lineContent: string, tokens: ViewLineToken[], fauxIndentLength: number, renderWhitespace: 'none' | 'boundary' | 'all', expected: string): void { let actual = renderViewLine(new RenderLineInput( fontIsMonospace, lineContent, false, fauxIndentLength, createViewLineTokens(tokens), [], 4, 10, -1, renderWhitespace, false, false )); assert.deepEqual(actual.html, expected); } test('issue #18616: Inline decorations ending at the text length are no longer rendered', () => { let lineContent = 'https://microsoft.com'; let actual = renderViewLine(new RenderLineInput( false, lineContent, false, 0, createViewLineTokens([createPart(21, 3)]), [new LineDecoration(1, 22, 'link', InlineDecorationType.Regular)], 4, 10, -1, 'none', false, false )); let expected = [ '<span>', '<span class="mtk3 link">https://microsoft.com</span>', '</span>' ].join(''); assert.deepEqual(actual.html, expected); }); test('issue #19207: Link in Monokai is not rendered correctly', () => { let lineContent = '\'let url = `http://***/_api/web/lists/GetByTitle(\\\'Teambuildingaanvragen\\\')/items`;\''; let actual = renderViewLine(new RenderLineInput( true, lineContent, false, 0, createViewLineTokens([ createPart(49, 6), createPart(51, 4), createPart(72, 6), createPart(74, 4), createPart(84, 6), ]), [ new LineDecoration(13, 51, 'detected-link', InlineDecorationType.Regular) ], 4, 10, -1, 'none', false, false )); let expected = [ '<span>', '<span class="mtk6">\'let\u00a0url\u00a0=\u00a0`</span>', '<span class="mtk6 detected-link">http://***/_api/web/lists/GetByTitle(</span>', '<span class="mtk4 detected-link">\\</span>', '<span class="mtk4">\'</span>', '<span class="mtk6">Teambuildingaanvragen</span>', '<span class="mtk4">\\\'</span>', '<span class="mtk6">)/items`;\'</span>', '</span>' ].join(''); assert.deepEqual(actual.html, expected); }); test('createLineParts simple', () => { testCreateLineParts( false, 'Hello world!', [ createPart(12, 1) ], 0, 'none', [ '<span>', '<span class="mtk1">Hello\u00a0world!</span>', '</span>', ].join('') ); }); test('createLineParts simple two tokens', () => { testCreateLineParts( false, 'Hello world!', [ createPart(6, 1), createPart(12, 2) ], 0, 'none', [ '<span>', '<span class="mtk1">Hello\u00a0</span>', '<span class="mtk2">world!</span>', '</span>', ].join('') ); }); test('createLineParts render whitespace - 4 leading spaces', () => { testCreateLineParts( false, ' Hello world! ', [ createPart(4, 1), createPart(6, 2), createPart(20, 3) ], 0, 'boundary', [ '<span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '<span class="mtk2">He</span>', '<span class="mtk3">llo\u00a0world!</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '</span>', ].join('') ); }); test('createLineParts render whitespace - 8 leading spaces', () => { testCreateLineParts( false, ' Hello world! ', [ createPart(8, 1), createPart(10, 2), createPart(28, 3) ], 0, 'boundary', [ '<span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '<span class="mtk2">He</span>', '<span class="mtk3">llo\u00a0world!</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '</span>', ].join('') ); }); test('createLineParts render whitespace - 2 leading tabs', () => { testCreateLineParts( false, '\t\tHello world!\t', [ createPart(2, 1), createPart(4, 2), createPart(15, 3) ], 0, 'boundary', [ '<span>', '<span class="vs-whitespace" style="width:40px">\u2192\u00a0\u00a0\u00a0</span>', '<span class="vs-whitespace" style="width:40px">\u2192\u00a0\u00a0\u00a0</span>', '<span class="mtk2">He</span>', '<span class="mtk3">llo\u00a0world!</span>', '<span class="vs-whitespace" style="width:40px">\u2192\u00a0\u00a0\u00a0</span>', '</span>', ].join('') ); }); test('createLineParts render whitespace - mixed leading spaces and tabs', () => { testCreateLineParts( false, ' \t\t Hello world! \t \t \t ', [ createPart(6, 1), createPart(8, 2), createPart(31, 3) ], 0, 'boundary', [ '<span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u2192\u00a0</span>', '<span class="vs-whitespace" style="width:40px">\u2192\u00a0\u00a0\u00a0</span>', '<span class="vs-whitespace" style="width:20px">\u00b7\u00b7</span>', '<span class="mtk2">He</span>', '<span class="mtk3">llo\u00a0world!</span>', '<span class="vs-whitespace" style="width:20px">\u00b7\u2192</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u2192\u00a0</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u2192</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '</span>', ].join('') ); }); test('createLineParts render whitespace skips faux indent', () => { testCreateLineParts( false, '\t\t Hello world! \t \t \t ', [ createPart(4, 1), createPart(6, 2), createPart(29, 3) ], 2, 'boundary', [ '<span>', '<span class="">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0</span>', '<span class="vs-whitespace" style="width:20px">\u00b7\u00b7</span>', '<span class="mtk2">He</span>', '<span class="mtk3">llo\u00a0world!</span>', '<span class="vs-whitespace" style="width:20px">\u00b7\u2192</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u2192\u00a0</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u2192</span>', '<span class="vs-whitespace" style="width:40px">\u00b7\u00b7\u00b7\u00b7</span>', '</span>', ].join('') ); }); test('createLineParts does not emit width for monospace fonts', () => { testCreateLineParts( true, '\t\t Hello world! \t \t \t ', [ createPart(4, 1), createPart(6, 2), createPart(29, 3) ], 2, 'boundary', [ '<span>', '<span class="">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0</span>', '<span class="vs-whitespace">\u00b7\u00b7</span>', '<span class="mtk2">He</span>', '<span class="mtk3">llo\u00a0world!</span>', '<span class="vs-whitespace">\u00b7\u2192\u00b7\u00b7\u2192\u00a0\u00b7\u00b7\u00b7\u2192\u00b7\u00b7\u00b7\u00b7</span>', '</span>', ].join('') ); }); test('createLineParts render whitespace in middle but not for one space', () => { testCreateLineParts( false, 'it it it it', [ createPart(6, 1), createPart(7, 2), createPart(13, 3) ], 0, 'boundary', [ '<span>', '<span class="mtk1">it</span>', '<span class="vs-whitespace" style="width:20px">\u00b7\u00b7</span>', '<span class="mtk1">it</span>', '<span class="mtk2">\u00a0</span>', '<span class="mtk3">it</span>', '<span class="vs-whitespace" style="width:20px">\u00b7\u00b7</span>', '<span class="mtk3">it</span>', '</span>', ].join('') ); }); test('createLineParts render whitespace for all in middle', () => { testCreateLineParts( false, ' Hello world!\t', [ createPart(4, 0), createPart(6, 1), createPart(14, 2) ], 0, 'all', [ '<span>', '<span class="vs-whitespace" style="width:10px">\u00b7</span>', '<span class="mtk0">Hel</span>', '<span class="mtk1">lo</span>', '<span class="vs-whitespace" style="width:10px">\u00b7</span>', '<span class="mtk2">world!</span>', '<span class="vs-whitespace" style="width:30px">\u2192\u00a0\u00a0</span>', '</span>', ].join('') ); }); test('createLineParts can handle unsorted inline decorations', () => { let actual = renderViewLine(new RenderLineInput( false, 'Hello world', false, 0, createViewLineTokens([createPart(11, 0)]), [ new LineDecoration(5, 7, 'a', InlineDecorationType.Regular), new LineDecoration(1, 3, 'b', InlineDecorationType.Regular), new LineDecoration(2, 8, 'c', InlineDecorationType.Regular), ], 4, 10, -1, 'none', false, false )); // 01234567890 // Hello world // ----aa----- // bb--------- // -cccccc---- assert.deepEqual(actual.html, [ '<span>', '<span class="mtk0 b">H</span>', '<span class="mtk0 b c">e</span>', '<span class="mtk0 c">ll</span>', '<span class="mtk0 a c">o\u00a0</span>', '<span class="mtk0 c">w</span>', '<span class="mtk0">orld</span>', '</span>', ].join('')); }); test('issue #11485: Visible whitespace conflicts with before decorator attachment', () => { let lineContent = '\tbla'; let actual = renderViewLine(new RenderLineInput( false, lineContent, false, 0, createViewLineTokens([createPart(4, 3)]), [new LineDecoration(1, 2, 'before', InlineDecorationType.Before)], 4, 10, -1, 'all', false, true )); let expected = [ '<span>', '<span class="vs-whitespace before">\u2192\u00a0\u00a0\u00a0</span>', '<span class="mtk3">bla</span>', '</span>' ].join(''); assert.deepEqual(actual.html, expected); }); test('issue #32436: Non-monospace font + visible whitespace + After decorator causes line to "jump"', () => { let lineContent = '\tbla'; let actual = renderViewLine(new RenderLineInput( false, lineContent, false, 0, createViewLineTokens([createPart(4, 3)]), [new LineDecoration(2, 3, 'before', InlineDecorationType.Before)], 4, 10, -1, 'all', false, true )); let expected = [ '<span>', '<span class="vs-whitespace" style="width:40px">\u2192\u00a0\u00a0\u00a0</span>', '<span class="mtk3 before">b</span>', '<span class="mtk3">la</span>', '</span>' ].join(''); assert.deepEqual(actual.html, expected); }); test('issue #30133: Empty lines don\'t render inline decorations', () => { let lineContent = ''; let actual = renderViewLine(new RenderLineInput( false, lineContent, false, 0, createViewLineTokens([createPart(0, 3)]), [new LineDecoration(1, 2, 'before', InlineDecorationType.Before)], 4, 10, -1, 'all', false, true )); let expected = [ '<span>', '<span class="before"></span>', '</span>' ].join(''); assert.deepEqual(actual.html, expected); }); test('issue #37208: Collapsing bullet point containing emoji in Markdown document results in [??] character', () => { let actual = renderViewLine(new RenderLineInput( true, ' 1. 🙏', false, 0, createViewLineTokens([createPart(7, 3)]), [new LineDecoration(7, 8, 'inline-folded', InlineDecorationType.After)], 2, 10, 10000, 'none', false, false )); let expected = [ '<span>', '<span class="mtk3">\u00a0\u00a01.\u00a0</span>', '<span class="mtk3 inline-folded">🙏</span>', '</span>' ].join(''); assert.deepEqual(actual.html, expected); }); test('issue #37401: Allow both before and after decorations on empty line', () => { let actual = renderViewLine(new RenderLineInput( true, '', false, 0, createViewLineTokens([createPart(0, 3)]), [ new LineDecoration(1, 2, 'before', InlineDecorationType.Before), new LineDecoration(0, 1, 'after', InlineDecorationType.After), ], 2, 10, 10000, 'none', false, false )); let expected = [ '<span>', '<span class="before after"></span>', '</span>' ].join(''); assert.deepEqual(actual.html, expected); }); test('issue #38935: GitLens end-of-line blame no longer rendering', () => { let actual = renderViewLine(new RenderLineInput( true, '\t}', false, 0, createViewLineTokens([createPart(2, 3)]), [ new LineDecoration(3, 3, 'ced-TextEditorDecorationType2-5e9b9b3f-3 ced-TextEditorDecorationType2-3', InlineDecorationType.Before), new LineDecoration(3, 3, 'ced-TextEditorDecorationType2-5e9b9b3f-4 ced-TextEditorDecorationType2-4', InlineDecorationType.After), ], 4, 10, 10000, 'none', false, false )); let expected = [ '<span>', '<span class="mtk3">\u00a0\u00a0\u00a0\u00a0}</span>', '<span class="ced-TextEditorDecorationType2-5e9b9b3f-3 ced-TextEditorDecorationType2-3 ced-TextEditorDecorationType2-5e9b9b3f-4 ced-TextEditorDecorationType2-4"></span>', '</span>' ].join(''); assert.deepEqual(actual.html, expected); }); function createTestGetColumnOfLinePartOffset(lineContent: string, tabSize: number, parts: ViewLineToken[], expectedPartLengths: number[]): (partIndex: number, partLength: number, offset: number, expected: number) => void { let renderLineOutput = renderViewLine(new RenderLineInput( false, lineContent, false, 0, createViewLineTokens(parts), [], tabSize, 10, -1, 'none', false, false )); return (partIndex: number, partLength: number, offset: number, expected: number) => { let charOffset = renderLineOutput.characterMapping.partDataToCharOffset(partIndex, partLength, offset); let actual = charOffset + 1; assert.equal(actual, expected, 'getColumnOfLinePartOffset for ' + partIndex + ' @ ' + offset); }; } test('getColumnOfLinePartOffset 1 - simple text', () => { let testGetColumnOfLinePartOffset = createTestGetColumnOfLinePartOffset( 'hello world', 4, [ createPart(11, 1) ], [11] ); testGetColumnOfLinePartOffset(0, 11, 0, 1); testGetColumnOfLinePartOffset(0, 11, 1, 2); testGetColumnOfLinePartOffset(0, 11, 2, 3); testGetColumnOfLinePartOffset(0, 11, 3, 4); testGetColumnOfLinePartOffset(0, 11, 4, 5); testGetColumnOfLinePartOffset(0, 11, 5, 6); testGetColumnOfLinePartOffset(0, 11, 6, 7); testGetColumnOfLinePartOffset(0, 11, 7, 8); testGetColumnOfLinePartOffset(0, 11, 8, 9); testGetColumnOfLinePartOffset(0, 11, 9, 10); testGetColumnOfLinePartOffset(0, 11, 10, 11); testGetColumnOfLinePartOffset(0, 11, 11, 12); }); test('getColumnOfLinePartOffset 2 - regular JS', () => { let testGetColumnOfLinePartOffset = createTestGetColumnOfLinePartOffset( 'var x = 3;', 4, [ createPart(3, 1), createPart(4, 2), createPart(5, 3), createPart(8, 4), createPart(9, 5), createPart(10, 6), ], [3, 1, 1, 3, 1, 1] ); testGetColumnOfLinePartOffset(0, 3, 0, 1); testGetColumnOfLinePartOffset(0, 3, 1, 2); testGetColumnOfLinePartOffset(0, 3, 2, 3); testGetColumnOfLinePartOffset(0, 3, 3, 4); testGetColumnOfLinePartOffset(1, 1, 0, 4); testGetColumnOfLinePartOffset(1, 1, 1, 5); testGetColumnOfLinePartOffset(2, 1, 0, 5); testGetColumnOfLinePartOffset(2, 1, 1, 6); testGetColumnOfLinePartOffset(3, 3, 0, 6); testGetColumnOfLinePartOffset(3, 3, 1, 7); testGetColumnOfLinePartOffset(3, 3, 2, 8); testGetColumnOfLinePartOffset(3, 3, 3, 9); testGetColumnOfLinePartOffset(4, 1, 0, 9); testGetColumnOfLinePartOffset(4, 1, 1, 10); testGetColumnOfLinePartOffset(5, 1, 0, 10); testGetColumnOfLinePartOffset(5, 1, 1, 11); }); test('getColumnOfLinePartOffset 3 - tab with tab size 6', () => { let testGetColumnOfLinePartOffset = createTestGetColumnOfLinePartOffset( '\t', 6, [ createPart(1, 1) ], [6] ); testGetColumnOfLinePartOffset(0, 6, 0, 1); testGetColumnOfLinePartOffset(0, 6, 1, 1); testGetColumnOfLinePartOffset(0, 6, 2, 1); testGetColumnOfLinePartOffset(0, 6, 3, 1); testGetColumnOfLinePartOffset(0, 6, 4, 2); testGetColumnOfLinePartOffset(0, 6, 5, 2); testGetColumnOfLinePartOffset(0, 6, 6, 2); }); test('getColumnOfLinePartOffset 4 - once indented line, tab size 4', () => { let testGetColumnOfLinePartOffset = createTestGetColumnOfLinePartOffset( '\tfunction', 4, [ createPart(1, 1), createPart(9, 2), ], [4, 8] ); testGetColumnOfLinePartOffset(0, 4, 0, 1); testGetColumnOfLinePartOffset(0, 4, 1, 1); testGetColumnOfLinePartOffset(0, 4, 2, 1); testGetColumnOfLinePartOffset(0, 4, 3, 2); testGetColumnOfLinePartOffset(0, 4, 4, 2); testGetColumnOfLinePartOffset(1, 8, 0, 2); testGetColumnOfLinePartOffset(1, 8, 1, 3); testGetColumnOfLinePartOffset(1, 8, 2, 4); testGetColumnOfLinePartOffset(1, 8, 3, 5); testGetColumnOfLinePartOffset(1, 8, 4, 6); testGetColumnOfLinePartOffset(1, 8, 5, 7); testGetColumnOfLinePartOffset(1, 8, 6, 8); testGetColumnOfLinePartOffset(1, 8, 7, 9); testGetColumnOfLinePartOffset(1, 8, 8, 10); }); test('getColumnOfLinePartOffset 5 - twice indented line, tab size 4', () => { let testGetColumnOfLinePartOffset = createTestGetColumnOfLinePartOffset( '\t\tfunction', 4, [ createPart(2, 1), createPart(10, 2), ], [8, 8] ); testGetColumnOfLinePartOffset(0, 8, 0, 1); testGetColumnOfLinePartOffset(0, 8, 1, 1); testGetColumnOfLinePartOffset(0, 8, 2, 1); testGetColumnOfLinePartOffset(0, 8, 3, 2); testGetColumnOfLinePartOffset(0, 8, 4, 2); testGetColumnOfLinePartOffset(0, 8, 5, 2); testGetColumnOfLinePartOffset(0, 8, 6, 2); testGetColumnOfLinePartOffset(0, 8, 7, 3); testGetColumnOfLinePartOffset(0, 8, 8, 3); testGetColumnOfLinePartOffset(1, 8, 0, 3); testGetColumnOfLinePartOffset(1, 8, 1, 4); testGetColumnOfLinePartOffset(1, 8, 2, 5); testGetColumnOfLinePartOffset(1, 8, 3, 6); testGetColumnOfLinePartOffset(1, 8, 4, 7); testGetColumnOfLinePartOffset(1, 8, 5, 8); testGetColumnOfLinePartOffset(1, 8, 6, 9); testGetColumnOfLinePartOffset(1, 8, 7, 10); testGetColumnOfLinePartOffset(1, 8, 8, 11); }); });
src/vs/editor/test/common/viewLayout/viewLineRenderer.test.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.004169925581663847, 0.0002886249276343733, 0.00016474217409268022, 0.00016790846711955965, 0.0005519731785170734 ]
{ "id": 4, "code_window": [ "\n", "\tpublic setCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n", "\t\tthis.customTokenColors = [];\n", "\t\tlet customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {};\n", "\t\tfor (let key in customTokenColors) {\n", "\t\t\tif (key[0] !== '[') {\n", "\t\t\t\tcustomTokenColorsWithoutThemeSpecific[key] = customTokenColors[key];\n", "\t\t\t}\n", "\t\t}\n", "\t\tthis.addCustomTokenColors(customTokenColorsWithoutThemeSpecific);\n", "\t\tif (`[${this.settingsId}]` in customTokenColors) {\n", "\t\t\tconst themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`];\n", "\t\t\tif (types.isObject(themeSpecificTokenColors)) {\n", "\t\t\t\tthis.addCustomTokenColors(themeSpecificTokenColors);\n", "\t\t\t}\n", "\t\t}\n", "\t}\n", "\n", "\tprivate addCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// first add the non-theme specific settings\n", "\t\tthis.addCustomTokenColors(customTokenColors);\n", "\n", "\t\t// append theme specific settings. Last rules will win.\n", "\t\tconst themeSpecificTokenColors = customTokenColors[`[${this.settingsId}]`] as ITokenColorCustomizations;\n", "\t\tif (types.isObject(themeSpecificTokenColors)) {\n", "\t\t\tthis.addCustomTokenColors(themeSpecificTokenColors);\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 105 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { onUnexpectedError } from 'vs/base/common/errors'; import { IDisposable } from 'vs/base/common/lifecycle'; import * as dom from 'vs/base/browser/dom'; import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { Range } from 'vs/editor/common/core/range'; import { ViewEventHandler } from 'vs/editor/common/viewModel/viewEventHandler'; import { Configuration } from 'vs/editor/browser/config/configuration'; import { TextAreaHandler, ITextAreaHandlerHelper } from 'vs/editor/browser/controller/textAreaHandler'; import { PointerHandler } from 'vs/editor/browser/controller/pointerHandler'; import * as editorBrowser from 'vs/editor/browser/editorBrowser'; import { ViewController, ExecCoreEditorCommandFunc } from 'vs/editor/browser/view/viewController'; import { ViewEventDispatcher } from 'vs/editor/common/view/viewEventDispatcher'; import { ContentViewOverlays, MarginViewOverlays } from 'vs/editor/browser/view/viewOverlays'; import { ViewContentWidgets } from 'vs/editor/browser/viewParts/contentWidgets/contentWidgets'; import { CurrentLineHighlightOverlay } from 'vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight'; import { CurrentLineMarginHighlightOverlay } from 'vs/editor/browser/viewParts/currentLineMarginHighlight/currentLineMarginHighlight'; import { DecorationsOverlay } from 'vs/editor/browser/viewParts/decorations/decorations'; import { GlyphMarginOverlay } from 'vs/editor/browser/viewParts/glyphMargin/glyphMargin'; import { LineNumbersOverlay } from 'vs/editor/browser/viewParts/lineNumbers/lineNumbers'; import { IndentGuidesOverlay } from 'vs/editor/browser/viewParts/indentGuides/indentGuides'; import { ViewLines } from 'vs/editor/browser/viewParts/lines/viewLines'; import { Margin } from 'vs/editor/browser/viewParts/margin/margin'; import { LinesDecorationsOverlay } from 'vs/editor/browser/viewParts/linesDecorations/linesDecorations'; import { MarginViewLineDecorationsOverlay } from 'vs/editor/browser/viewParts/marginDecorations/marginDecorations'; import { ViewOverlayWidgets } from 'vs/editor/browser/viewParts/overlayWidgets/overlayWidgets'; import { DecorationsOverviewRuler } from 'vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler'; import { OverviewRuler } from 'vs/editor/browser/viewParts/overviewRuler/overviewRuler'; import { Rulers } from 'vs/editor/browser/viewParts/rulers/rulers'; import { ScrollDecorationViewPart } from 'vs/editor/browser/viewParts/scrollDecoration/scrollDecoration'; import { SelectionsOverlay } from 'vs/editor/browser/viewParts/selections/selections'; import { ViewCursors } from 'vs/editor/browser/viewParts/viewCursors/viewCursors'; import { ViewZones } from 'vs/editor/browser/viewParts/viewZones/viewZones'; import { ViewPart, PartFingerprint, PartFingerprints } from 'vs/editor/browser/view/viewPart'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import { IViewModel } from 'vs/editor/common/viewModel/viewModel'; import { RenderingContext } from 'vs/editor/common/view/renderingContext'; import { IPointerHandlerHelper } from 'vs/editor/browser/controller/mouseHandler'; import { ViewOutgoingEvents } from 'vs/editor/browser/view/viewOutgoingEvents'; import { ViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData'; import { EditorScrollbar } from 'vs/editor/browser/viewParts/editorScrollbar/editorScrollbar'; import { Minimap } from 'vs/editor/browser/viewParts/minimap/minimap'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { IThemeService, getThemeTypeSelector } from 'vs/platform/theme/common/themeService'; import { Cursor } from 'vs/editor/common/controller/cursor'; import { IMouseEvent } from 'vs/base/browser/mouseEvent'; export interface IContentWidgetData { widget: editorBrowser.IContentWidget; position: editorBrowser.IContentWidgetPosition; } export interface IOverlayWidgetData { widget: editorBrowser.IOverlayWidget; position: editorBrowser.IOverlayWidgetPosition; } export class View extends ViewEventHandler { private eventDispatcher: ViewEventDispatcher; private _scrollbar: EditorScrollbar; private _context: ViewContext; private _cursor: Cursor; // The view lines private viewLines: ViewLines; // These are parts, but we must do some API related calls on them, so we keep a reference private viewZones: ViewZones; private contentWidgets: ViewContentWidgets; private overlayWidgets: ViewOverlayWidgets; private viewCursors: ViewCursors; private viewParts: ViewPart[]; private readonly _textAreaHandler: TextAreaHandler; private readonly pointerHandler: PointerHandler; private readonly outgoingEvents: ViewOutgoingEvents; // Dom nodes private linesContent: FastDomNode<HTMLElement>; public domNode: FastDomNode<HTMLElement>; private overflowGuardContainer: FastDomNode<HTMLElement>; // Actual mutable state private _renderAnimationFrame: IDisposable; constructor( commandService: ICommandService, configuration: Configuration, themeService: IThemeService, model: IViewModel, cursor: Cursor, execCoreEditorCommandFunc: ExecCoreEditorCommandFunc ) { super(); this._cursor = cursor; this._renderAnimationFrame = null; this.outgoingEvents = new ViewOutgoingEvents(model); let viewController = new ViewController(configuration, model, execCoreEditorCommandFunc, this.outgoingEvents, commandService); // The event dispatcher will always go through _renderOnce before dispatching any events this.eventDispatcher = new ViewEventDispatcher((callback: () => void) => this._renderOnce(callback)); // Ensure the view is the first event handler in order to update the layout this.eventDispatcher.addEventHandler(this); // The view context is passed on to most classes (basically to reduce param. counts in ctors) this._context = new ViewContext(configuration, themeService.getTheme(), model, this.eventDispatcher); this._register(themeService.onThemeChange(theme => { this._context.theme = theme; this.eventDispatcher.emit(new viewEvents.ViewThemeChangedEvent()); this.render(true, false); })); this.viewParts = []; // Keyboard handler this._textAreaHandler = new TextAreaHandler(this._context, viewController, this.createTextAreaHandlerHelper()); this.viewParts.push(this._textAreaHandler); this.createViewParts(); this._setLayout(); // Pointer handler this.pointerHandler = new PointerHandler(this._context, viewController, this.createPointerHandlerHelper()); this._register(model.addEventListener((events: viewEvents.ViewEvent[]) => { this.eventDispatcher.emitMany(events); })); this._register(this._cursor.addEventListener((events: viewEvents.ViewEvent[]) => { this.eventDispatcher.emitMany(events); })); } private createViewParts(): void { // These two dom nodes must be constructed up front, since references are needed in the layout provider (scrolling & co.) this.linesContent = createFastDomNode(document.createElement('div')); this.linesContent.setClassName('lines-content' + ' monaco-editor-background'); this.linesContent.setPosition('absolute'); this.domNode = createFastDomNode(document.createElement('div')); this.domNode.setClassName(this.getEditorClassName()); this.overflowGuardContainer = createFastDomNode(document.createElement('div')); PartFingerprints.write(this.overflowGuardContainer, PartFingerprint.OverflowGuard); this.overflowGuardContainer.setClassName('overflow-guard'); this._scrollbar = new EditorScrollbar(this._context, this.linesContent, this.domNode, this.overflowGuardContainer); this.viewParts.push(this._scrollbar); // View Lines this.viewLines = new ViewLines(this._context, this.linesContent); // View Zones this.viewZones = new ViewZones(this._context); this.viewParts.push(this.viewZones); // Decorations overview ruler let decorationsOverviewRuler = new DecorationsOverviewRuler(this._context); this.viewParts.push(decorationsOverviewRuler); let scrollDecoration = new ScrollDecorationViewPart(this._context); this.viewParts.push(scrollDecoration); let contentViewOverlays = new ContentViewOverlays(this._context); this.viewParts.push(contentViewOverlays); contentViewOverlays.addDynamicOverlay(new CurrentLineHighlightOverlay(this._context)); contentViewOverlays.addDynamicOverlay(new SelectionsOverlay(this._context)); contentViewOverlays.addDynamicOverlay(new DecorationsOverlay(this._context)); contentViewOverlays.addDynamicOverlay(new IndentGuidesOverlay(this._context)); let marginViewOverlays = new MarginViewOverlays(this._context); this.viewParts.push(marginViewOverlays); marginViewOverlays.addDynamicOverlay(new CurrentLineMarginHighlightOverlay(this._context)); marginViewOverlays.addDynamicOverlay(new GlyphMarginOverlay(this._context)); marginViewOverlays.addDynamicOverlay(new MarginViewLineDecorationsOverlay(this._context)); marginViewOverlays.addDynamicOverlay(new LinesDecorationsOverlay(this._context)); marginViewOverlays.addDynamicOverlay(new LineNumbersOverlay(this._context)); let margin = new Margin(this._context); margin.getDomNode().appendChild(this.viewZones.marginDomNode); margin.getDomNode().appendChild(marginViewOverlays.getDomNode()); this.viewParts.push(margin); // Content widgets this.contentWidgets = new ViewContentWidgets(this._context, this.domNode); this.viewParts.push(this.contentWidgets); this.viewCursors = new ViewCursors(this._context); this.viewParts.push(this.viewCursors); // Overlay widgets this.overlayWidgets = new ViewOverlayWidgets(this._context); this.viewParts.push(this.overlayWidgets); let rulers = new Rulers(this._context); this.viewParts.push(rulers); let minimap = new Minimap(this._context); this.viewParts.push(minimap); // -------------- Wire dom nodes up if (decorationsOverviewRuler) { let overviewRulerData = this._scrollbar.getOverviewRulerLayoutInfo(); overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore); } this.linesContent.appendChild(contentViewOverlays.getDomNode()); this.linesContent.appendChild(rulers.domNode); this.linesContent.appendChild(this.viewZones.domNode); this.linesContent.appendChild(this.viewLines.getDomNode()); this.linesContent.appendChild(this.contentWidgets.domNode); this.linesContent.appendChild(this.viewCursors.getDomNode()); this.overflowGuardContainer.appendChild(margin.getDomNode()); this.overflowGuardContainer.appendChild(this._scrollbar.getDomNode()); this.overflowGuardContainer.appendChild(scrollDecoration.getDomNode()); this.overflowGuardContainer.appendChild(this._textAreaHandler.textArea); this.overflowGuardContainer.appendChild(this._textAreaHandler.textAreaCover); this.overflowGuardContainer.appendChild(this.overlayWidgets.getDomNode()); this.overflowGuardContainer.appendChild(minimap.getDomNode()); this.domNode.appendChild(this.overflowGuardContainer); this.domNode.appendChild(this.contentWidgets.overflowingContentWidgetsDomNode); } private _flushAccumulatedAndRenderNow(): void { this._renderNow(); } private createPointerHandlerHelper(): IPointerHandlerHelper { return { viewDomNode: this.domNode.domNode, linesContentDomNode: this.linesContent.domNode, focusTextArea: () => { this.focus(); }, getLastViewCursorsRenderData: () => { return this.viewCursors.getLastRenderData() || []; }, shouldSuppressMouseDownOnViewZone: (viewZoneId: number) => { return this.viewZones.shouldSuppressMouseDownOnViewZone(viewZoneId); }, shouldSuppressMouseDownOnWidget: (widgetId: string) => { return this.contentWidgets.shouldSuppressMouseDownOnWidget(widgetId); }, getPositionFromDOMInfo: (spanNode: HTMLElement, offset: number) => { this._flushAccumulatedAndRenderNow(); return this.viewLines.getPositionFromDOMInfo(spanNode, offset); }, visibleRangeForPosition2: (lineNumber: number, column: number) => { this._flushAccumulatedAndRenderNow(); let visibleRanges = this.viewLines.visibleRangesForRange2(new Range(lineNumber, column, lineNumber, column)); if (!visibleRanges) { return null; } return visibleRanges[0]; }, getLineWidth: (lineNumber: number) => { this._flushAccumulatedAndRenderNow(); return this.viewLines.getLineWidth(lineNumber); } }; } private createTextAreaHandlerHelper(): ITextAreaHandlerHelper { return { visibleRangeForPositionRelativeToEditor: (lineNumber: number, column: number) => { this._flushAccumulatedAndRenderNow(); let visibleRanges = this.viewLines.visibleRangesForRange2(new Range(lineNumber, column, lineNumber, column)); if (!visibleRanges) { return null; } return visibleRanges[0]; } }; } private _setLayout(): void { const layoutInfo = this._context.configuration.editor.layoutInfo; this.domNode.setWidth(layoutInfo.width); this.domNode.setHeight(layoutInfo.height); this.overflowGuardContainer.setWidth(layoutInfo.width); this.overflowGuardContainer.setHeight(layoutInfo.height); this.linesContent.setWidth(1000000); this.linesContent.setHeight(1000000); } private getEditorClassName() { let focused = this._textAreaHandler.isFocused() ? ' focused' : ''; return this._context.configuration.editor.editorClassName + ' ' + getThemeTypeSelector(this._context.theme.type) + focused; } // --- begin event handlers public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { if (e.editorClassName) { this.domNode.setClassName(this.getEditorClassName()); } if (e.layoutInfo) { this._setLayout(); } return false; } public onFocusChanged(e: viewEvents.ViewFocusChangedEvent): boolean { this.domNode.setClassName(this.getEditorClassName()); if (e.isFocused) { this.outgoingEvents.emitViewFocusGained(); } else { this.outgoingEvents.emitViewFocusLost(); } return false; } public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean { this.outgoingEvents.emitScrollChanged(e); return false; } public onThemeChanged(e: viewEvents.ViewThemeChangedEvent): boolean { this.domNode.setClassName(this.getEditorClassName()); return false; } // --- end event handlers public dispose(): void { if (this._renderAnimationFrame !== null) { this._renderAnimationFrame.dispose(); this._renderAnimationFrame = null; } this.eventDispatcher.removeEventHandler(this); this.outgoingEvents.dispose(); this.pointerHandler.dispose(); this.viewLines.dispose(); // Destroy view parts for (let i = 0, len = this.viewParts.length; i < len; i++) { this.viewParts[i].dispose(); } this.viewParts = []; super.dispose(); } private _renderOnce(callback: () => any): any { let r = safeInvokeNoArg(callback); this._scheduleRender(); return r; } private _scheduleRender(): void { if (this._renderAnimationFrame === null) { this._renderAnimationFrame = dom.runAtThisOrScheduleAtNextAnimationFrame(this._onRenderScheduled.bind(this), 100); } } private _onRenderScheduled(): void { this._renderAnimationFrame = null; this._flushAccumulatedAndRenderNow(); } private _renderNow(): void { safeInvokeNoArg(() => this._actualRender()); } private _getViewPartsToRender(): ViewPart[] { let result: ViewPart[] = [], resultLen = 0; for (let i = 0, len = this.viewParts.length; i < len; i++) { let viewPart = this.viewParts[i]; if (viewPart.shouldRender()) { result[resultLen++] = viewPart; } } return result; } private _actualRender(): void { if (!dom.isInDOM(this.domNode.domNode)) { return; } let viewPartsToRender = this._getViewPartsToRender(); if (!this.viewLines.shouldRender() && viewPartsToRender.length === 0) { // Nothing to render return; } const partialViewportData = this._context.viewLayout.getLinesViewportData(); this._context.model.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber); let viewportData = new ViewportData( this._cursor.getViewSelections(), partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.model ); if (this.contentWidgets.shouldRender()) { // Give the content widgets a chance to set their max width before a possible synchronous layout this.contentWidgets.onBeforeRender(viewportData); } if (this.viewLines.shouldRender()) { this.viewLines.renderText(viewportData); this.viewLines.onDidRender(); // Rendering of viewLines might cause scroll events to occur, so collect view parts to render again viewPartsToRender = this._getViewPartsToRender(); } let renderingContext = new RenderingContext(this._context.viewLayout, viewportData, this.viewLines); // Render the rest of the parts for (let i = 0, len = viewPartsToRender.length; i < len; i++) { let viewPart = viewPartsToRender[i]; viewPart.prepareRender(renderingContext); } for (let i = 0, len = viewPartsToRender.length; i < len; i++) { let viewPart = viewPartsToRender[i]; viewPart.render(renderingContext); viewPart.onDidRender(); } } // --- BEGIN CodeEditor helpers public delegateVerticalScrollbarMouseDown(browserEvent: IMouseEvent): void { this._scrollbar.delegateVerticalScrollbarMouseDown(browserEvent); } public restoreState(scrollPosition: { scrollLeft: number; scrollTop: number; }): void { this._context.viewLayout.setScrollPositionNow({ scrollTop: scrollPosition.scrollTop }); this._renderNow(); this.viewLines.updateLineWidths(); this._context.viewLayout.setScrollPositionNow({ scrollLeft: scrollPosition.scrollLeft }); } public getOffsetForColumn(modelLineNumber: number, modelColumn: number): number { let modelPosition = this._context.model.validateModelPosition({ lineNumber: modelLineNumber, column: modelColumn }); let viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); this._flushAccumulatedAndRenderNow(); let visibleRanges = this.viewLines.visibleRangesForRange2(new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column)); if (!visibleRanges) { return -1; } return visibleRanges[0].left; } public getTargetAtClientPoint(clientX: number, clientY: number): editorBrowser.IMouseTarget { return this.pointerHandler.getTargetAtClientPoint(clientX, clientY); } public getInternalEventBus(): ViewOutgoingEvents { return this.outgoingEvents; } public createOverviewRuler(cssClassName: string): OverviewRuler { return new OverviewRuler(this._context, cssClassName); } public change(callback: (changeAccessor: editorBrowser.IViewZoneChangeAccessor) => any): boolean { let zonesHaveChanged = false; this._renderOnce(() => { let changeAccessor: editorBrowser.IViewZoneChangeAccessor = { addZone: (zone: editorBrowser.IViewZone): number => { zonesHaveChanged = true; return this.viewZones.addZone(zone); }, removeZone: (id: number): void => { if (!id) { return; } zonesHaveChanged = this.viewZones.removeZone(id) || zonesHaveChanged; }, layoutZone: (id: number): void => { if (!id) { return; } zonesHaveChanged = this.viewZones.layoutZone(id) || zonesHaveChanged; } }; safeInvoke1Arg(callback, changeAccessor); // Invalidate changeAccessor changeAccessor.addZone = null; changeAccessor.removeZone = null; if (zonesHaveChanged) { this._context.viewLayout.onHeightMaybeChanged(); this._context.privateViewEventBus.emit(new viewEvents.ViewZonesChangedEvent()); } }); return zonesHaveChanged; } public render(now: boolean, everything: boolean): void { if (everything) { // Force everything to render... this.viewLines.forceShouldRender(); for (let i = 0, len = this.viewParts.length; i < len; i++) { let viewPart = this.viewParts[i]; viewPart.forceShouldRender(); } } if (now) { this._flushAccumulatedAndRenderNow(); } else { this._scheduleRender(); } } public focus(): void { this._textAreaHandler.focusTextArea(); } public isFocused(): boolean { return this._textAreaHandler.isFocused(); } public addContentWidget(widgetData: IContentWidgetData): void { this.contentWidgets.addWidget(widgetData.widget); this.layoutContentWidget(widgetData); this._scheduleRender(); } public layoutContentWidget(widgetData: IContentWidgetData): void { let newPosition = widgetData.position ? widgetData.position.position : null; let newPreference = widgetData.position ? widgetData.position.preference : null; this.contentWidgets.setWidgetPosition(widgetData.widget, newPosition, newPreference); this._scheduleRender(); } public removeContentWidget(widgetData: IContentWidgetData): void { this.contentWidgets.removeWidget(widgetData.widget); this._scheduleRender(); } public addOverlayWidget(widgetData: IOverlayWidgetData): void { this.overlayWidgets.addWidget(widgetData.widget); this.layoutOverlayWidget(widgetData); this._scheduleRender(); } public layoutOverlayWidget(widgetData: IOverlayWidgetData): void { let newPreference = widgetData.position ? widgetData.position.preference : null; let shouldRender = this.overlayWidgets.setWidgetPosition(widgetData.widget, newPreference); if (shouldRender) { this._scheduleRender(); } } public removeOverlayWidget(widgetData: IOverlayWidgetData): void { this.overlayWidgets.removeWidget(widgetData.widget); this._scheduleRender(); } // --- END CodeEditor helpers } function safeInvokeNoArg(func: Function): any { try { return func(); } catch (e) { onUnexpectedError(e); } } function safeInvoke1Arg(func: Function, arg1: any): any { try { return func(arg1); } catch (e) { onUnexpectedError(e); } }
src/vs/editor/browser/view/viewImpl.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0005312642897479236, 0.0001761115127010271, 0.00016445557412225753, 0.00016703108849469572, 0.00004711790461442433 ]
{ "id": 5, "code_window": [ "\t}\n", "\n", "\tprivate addCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n", "\t\tlet generalRules: ITokenColorizationRule[] = [];\n", "\n", "\t\tObject.keys(tokenGroupToScopesMap).forEach(key => {\n", "\t\t\tlet value = customTokenColors[key];\n", "\t\t\tif (value) {\n", "\t\t\t\tlet settings = typeof value === 'string' ? { foreground: value } : value;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t// Put the general customizations such as comments, strings, etc. first so that\n", "\t\t// they can be overridden by specific customizations like \"string.interpolated\"\n", "\t\tfor (let tokenGroup in tokenGroupToScopesMap) {\n", "\t\t\tlet value = customTokenColors[tokenGroup];\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 121 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.9990251064300537, 0.2578437030315399, 0.0001679506676737219, 0.0019257550593465567, 0.4050728380680084 ]
{ "id": 5, "code_window": [ "\t}\n", "\n", "\tprivate addCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n", "\t\tlet generalRules: ITokenColorizationRule[] = [];\n", "\n", "\t\tObject.keys(tokenGroupToScopesMap).forEach(key => {\n", "\t\t\tlet value = customTokenColors[key];\n", "\t\t\tif (value) {\n", "\t\t\t\tlet settings = typeof value === 'string' ? { foreground: value } : value;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t// Put the general customizations such as comments, strings, etc. first so that\n", "\t\t// they can be overridden by specific customizations like \"string.interpolated\"\n", "\t\tfor (let tokenGroup in tokenGroupToScopesMap) {\n", "\t\t\tlet value = customTokenColors[tokenGroup];\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 121 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "vscode.extension.contributes.localizations": "向编辑器提供本地化内容", "vscode.extension.contributes.localizations.languageId": "显示字符串翻译的目标语言 ID。", "vscode.extension.contributes.localizations.languageName": "语言的英文名称。", "vscode.extension.contributes.localizations.languageNameLocalized": "提供语言的名称。", "vscode.extension.contributes.localizations.translations": "与语言关联的翻译的列表。", "vscode.extension.contributes.localizations.translations.id": "使用此翻译的 VS Code 或扩展的 ID。VS Code 的 ID 总为 \"vscode\",扩展的 ID 的格式应为 \"publisherId.extensionName\"。", "vscode.extension.contributes.localizations.translations.id.pattern": "翻译 VS Code 或者扩展,ID 分别应为 \"vscode\" 或格式为 \"publisherId.extensionName\"。", "vscode.extension.contributes.localizations.translations.path": "包含语言翻译的文件的相对路径。" }
i18n/chs/src/vs/platform/localizations/common/localizations.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017774563457351178, 0.000173854612512514, 0.00016996360500343144, 0.000173854612512514, 0.00000389101478504017 ]
{ "id": 5, "code_window": [ "\t}\n", "\n", "\tprivate addCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n", "\t\tlet generalRules: ITokenColorizationRule[] = [];\n", "\n", "\t\tObject.keys(tokenGroupToScopesMap).forEach(key => {\n", "\t\t\tlet value = customTokenColors[key];\n", "\t\t\tif (value) {\n", "\t\t\t\tlet settings = typeof value === 'string' ? { foreground: value } : value;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t// Put the general customizations such as comments, strings, etc. first so that\n", "\t\t// they can be overridden by specific customizations like \"string.interpolated\"\n", "\t\tfor (let tokenGroup in tokenGroupToScopesMap) {\n", "\t\t\tlet value = customTokenColors[tokenGroup];\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 121 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "previousEditPoint": "Emmet: 前の編集点", "nextEditPoint": "Emmet: 次の編集点" }
i18n/jpn/src/vs/workbench/parts/emmet/node/actions/editPoints.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0001767997455317527, 0.0001767997455317527, 0.0001767997455317527, 0.0001767997455317527, 0 ]
{ "id": 5, "code_window": [ "\t}\n", "\n", "\tprivate addCustomTokenColors(customTokenColors: ITokenColorCustomizations) {\n", "\t\tlet generalRules: ITokenColorizationRule[] = [];\n", "\n", "\t\tObject.keys(tokenGroupToScopesMap).forEach(key => {\n", "\t\t\tlet value = customTokenColors[key];\n", "\t\t\tif (value) {\n", "\t\t\t\tlet settings = typeof value === 'string' ? { foreground: value } : value;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t// Put the general customizations such as comments, strings, etc. first so that\n", "\t\t// they can be overridden by specific customizations like \"string.interpolated\"\n", "\t\tfor (let tokenGroup in tokenGroupToScopesMap) {\n", "\t\t\tlet value = customTokenColors[tokenGroup];\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 121 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { Constants } from 'vs/editor/common/view/minimapCharRenderer'; import { MinimapCharRendererFactory } from 'vs/editor/test/common/view/minimapCharRendererFactory'; import { getOrCreateMinimapCharRenderer } from 'vs/editor/common/view/runtimeMinimapCharRenderer'; import { RGBA8 } from 'vs/editor/common/core/rgba'; suite('MinimapCharRenderer', () => { let sampleData: Uint8ClampedArray = null; suiteSetup(() => { sampleData = new Uint8ClampedArray(Constants.SAMPLED_CHAR_HEIGHT * Constants.SAMPLED_CHAR_WIDTH * Constants.RGBA_CHANNELS_CNT * Constants.CHAR_COUNT); }); suiteTeardown(() => { sampleData = null; }); setup(() => { for (let i = 0; i < sampleData.length; i++) { sampleData[i] = 0; } }); const sampleD = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xd0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xd0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xd0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x0d, 0xff, 0xff, 0xff, 0xa3, 0xff, 0xff, 0xff, 0xf3, 0xff, 0xff, 0xff, 0xe5, 0xff, 0xff, 0xff, 0x5e, 0xff, 0xff, 0xff, 0xd0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xa4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x10, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x94, 0xff, 0xff, 0xff, 0x02, 0xff, 0xff, 0xff, 0x6a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x3b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x22, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x03, 0xff, 0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x47, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xd6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x31, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xe7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x0e, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x69, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x9b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0xff, 0xff, 0xff, 0xb9, 0xff, 0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x0e, 0xff, 0xff, 0xff, 0xa7, 0xff, 0xff, 0xff, 0xf5, 0xff, 0xff, 0xff, 0xe8, 0xff, 0xff, 0xff, 0x71, 0xff, 0xff, 0xff, 0xd0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; function setSampleData(charCode: number, data: number[]) { const rowWidth = Constants.SAMPLED_CHAR_WIDTH * Constants.RGBA_CHANNELS_CNT * Constants.CHAR_COUNT; let chIndex = charCode - Constants.START_CH_CODE; let globalOutputOffset = chIndex * Constants.SAMPLED_CHAR_WIDTH * Constants.RGBA_CHANNELS_CNT; let inputOffset = 0; for (let i = 0; i < Constants.SAMPLED_CHAR_HEIGHT; i++) { let outputOffset = globalOutputOffset; for (let j = 0; j < Constants.SAMPLED_CHAR_WIDTH; j++) { for (let channel = 0; channel < Constants.RGBA_CHANNELS_CNT; channel++) { sampleData[outputOffset] = data[inputOffset]; inputOffset++; outputOffset++; } } globalOutputOffset += rowWidth; } } function createFakeImageData(width: number, height: number): ImageData { return { width: width, height: height, data: new Uint8ClampedArray(width * height * Constants.RGBA_CHANNELS_CNT) }; } test('letter d @ 2x', () => { setSampleData('d'.charCodeAt(0), sampleD); let renderer = MinimapCharRendererFactory.create(sampleData); let background = new RGBA8(0, 0, 0, 255); let color = new RGBA8(255, 255, 255, 255); let imageData = createFakeImageData(Constants.x2_CHAR_WIDTH, Constants.x2_CHAR_HEIGHT); // set the background color for (let i = 0, len = imageData.data.length / 4; i < len; i++) { imageData.data[4 * i + 0] = background.r; imageData.data[4 * i + 1] = background.g; imageData.data[4 * i + 2] = background.b; imageData.data[4 * i + 3] = 255; } renderer.x2RenderChar(imageData, 0, 0, 'd'.charCodeAt(0), color, background, false); let actual: number[] = []; for (let i = 0; i < imageData.data.length; i++) { actual[i] = imageData.data[i]; } assert.deepEqual(actual, [ 0x00, 0x00, 0x00, 0xff, 0x6d, 0x6d, 0x6d, 0xff, 0xbb, 0xbb, 0xbb, 0xff, 0xbe, 0xbe, 0xbe, 0xff, 0x94, 0x94, 0x94, 0xff, 0x7e, 0x7e, 0x7e, 0xff, 0xb1, 0xb1, 0xb1, 0xff, 0xbb, 0xbb, 0xbb, 0xff, ]); }); test('letter d @ 2x at runtime', () => { let renderer = getOrCreateMinimapCharRenderer(); let background = new RGBA8(0, 0, 0, 255); let color = new RGBA8(255, 255, 255, 255); let imageData = createFakeImageData(Constants.x2_CHAR_WIDTH, Constants.x2_CHAR_HEIGHT); // set the background color for (let i = 0, len = imageData.data.length / 4; i < len; i++) { imageData.data[4 * i + 0] = background.r; imageData.data[4 * i + 1] = background.g; imageData.data[4 * i + 2] = background.b; imageData.data[4 * i + 3] = 255; } renderer.x2RenderChar(imageData, 0, 0, 'd'.charCodeAt(0), color, background, false); let actual: number[] = []; for (let i = 0; i < imageData.data.length; i++) { actual[i] = imageData.data[i]; } assert.deepEqual(actual, [ 0x00, 0x00, 0x00, 0xff, 0x6d, 0x6d, 0x6d, 0xff, 0xbb, 0xbb, 0xbb, 0xff, 0xbe, 0xbe, 0xbe, 0xff, 0x94, 0x94, 0x94, 0xff, 0x7e, 0x7e, 0x7e, 0xff, 0xb1, 0xb1, 0xb1, 0xff, 0xbb, 0xbb, 0xbb, 0xff, ]); }); test('letter d @ 1x', () => { setSampleData('d'.charCodeAt(0), sampleD); let renderer = MinimapCharRendererFactory.create(sampleData); let background = new RGBA8(0, 0, 0, 255); let color = new RGBA8(255, 255, 255, 255); let imageData = createFakeImageData(Constants.x1_CHAR_WIDTH, Constants.x1_CHAR_HEIGHT); // set the background color for (let i = 0, len = imageData.data.length / 4; i < len; i++) { imageData.data[4 * i + 0] = background.r; imageData.data[4 * i + 1] = background.g; imageData.data[4 * i + 2] = background.b; imageData.data[4 * i + 3] = 255; } renderer.x1RenderChar(imageData, 0, 0, 'd'.charCodeAt(0), color, background, false); let actual: number[] = []; for (let i = 0; i < imageData.data.length; i++) { actual[i] = imageData.data[i]; } assert.deepEqual(actual, [ 0x55, 0x55, 0x55, 0xff, 0x93, 0x93, 0x93, 0xff, ]); }); test('letter d @ 1x at runtime', () => { let renderer = getOrCreateMinimapCharRenderer(); let background = new RGBA8(0, 0, 0, 255); let color = new RGBA8(255, 255, 255, 255); let imageData = createFakeImageData(Constants.x1_CHAR_WIDTH, Constants.x1_CHAR_HEIGHT); // set the background color for (let i = 0, len = imageData.data.length / 4; i < len; i++) { imageData.data[4 * i + 0] = background.r; imageData.data[4 * i + 1] = background.g; imageData.data[4 * i + 2] = background.b; imageData.data[4 * i + 3] = 255; } renderer.x1RenderChar(imageData, 0, 0, 'd'.charCodeAt(0), color, background, false); let actual: number[] = []; for (let i = 0; i < imageData.data.length; i++) { actual[i] = imageData.data[i]; } assert.deepEqual(actual, [ 0x55, 0x55, 0x55, 0xff, 0x93, 0x93, 0x93, 0xff, ]); }); });
src/vs/editor/test/common/view/minimapCharRenderer.test.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017716747242957354, 0.00017414292960893363, 0.00016911025159060955, 0.00017460774688515812, 0.000002020410192926647 ]
{ "id": 6, "code_window": [ "\t\t\tif (value) {\n", "\t\t\t\tlet settings = typeof value === 'string' ? { foreground: value } : value;\n", "\t\t\t\tlet scopes = tokenGroupToScopesMap[key];\n", "\t\t\t\tfor (let scope of scopes) {\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\t\tlet scopes = tokenGroupToScopesMap[tokenGroup];\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 127 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.9980668425559998, 0.07908016443252563, 0.00016543541278224438, 0.00017438438953831792, 0.2681911587715149 ]
{ "id": 6, "code_window": [ "\t\t\tif (value) {\n", "\t\t\t\tlet settings = typeof value === 'string' ? { foreground: value } : value;\n", "\t\t\t\tlet scopes = tokenGroupToScopesMap[key];\n", "\t\t\t\tfor (let scope of scopes) {\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\t\tlet scopes = tokenGroupToScopesMap[tokenGroup];\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 127 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><style type="text/css">.icon-canvas-transparent{opacity:0;fill:#F6F6F6;} .icon-vs-out{fill:#F6F6F6;} .icon-vs-bg{fill:#424242;} .icon-vs-action-blue{fill:#00539C;}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M11 13c0-1.526-1.15-2.775-2.624-2.962L12 6.414V1.586l-2 2V1H6v2.586l-2-2v4.828l3.624 3.624C6.15 10.225 5 11.474 5 13c0 1.654 1.346 3 3 3s3-1.346 3-3z" id="outline"/><path class="icon-vs-bg" d="M8 11c1.104 0 2 .896 2 2s-.896 2-2 2-2-.896-2-2 .896-2 2-2z" id="iconBg"/><path class="icon-vs-action-blue" d="M8 9L5 6V4l2 2V2h2v4l2-2v2L8 9z" id="colorAction"/></svg>
src/vs/workbench/parts/debug/browser/media/step-into.svg
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00016487353423144668, 0.00016487353423144668, 0.00016487353423144668, 0.00016487353423144668, 0 ]
{ "id": 6, "code_window": [ "\t\t\tif (value) {\n", "\t\t\t\tlet settings = typeof value === 'string' ? { foreground: value } : value;\n", "\t\t\t\tlet scopes = tokenGroupToScopesMap[key];\n", "\t\t\t\tfor (let scope of scopes) {\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\t\tlet scopes = tokenGroupToScopesMap[tokenGroup];\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 127 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#2d2d30}.icon-vs-out{fill:#2d2d30}.icon-vs-bg{fill:#c5c5c5}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M10.702 10.5l2-2-2-2 .5-.5H10v5h1v3H5v-3h1V6H4.798l.5.5-2 2 2 2L3 12.797l-3-3V7.201l3-3V2h10v2.201l3 3v2.596l-3 3-2.298-2.297z" id="outline" style="display: none;"/><path class="icon-vs-bg" d="M4 3h8v2h-1v-.5c0-.277-.224-.5-.5-.5H9v7.5c0 .275.224.5.5.5h.5v1H6v-1h.5a.5.5 0 0 0 .5-.5V4H5.5a.5.5 0 0 0-.5.5V5H4V3zM3 5.615L.116 8.5 3 11.383l.884-.883-2-2 2-2L3 5.615zm10 0l-.884.885 2 2-2 2 .884.883L15.884 8.5 13 5.615z" id="iconBg"/></svg>
src/vs/workbench/parts/quickopen/browser/media/Template_16x_vscode_inverse.svg
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00016347997006960213, 0.00016347997006960213, 0.00016347997006960213, 0.00016347997006960213, 0 ]
{ "id": 6, "code_window": [ "\t\t\tif (value) {\n", "\t\t\t\tlet settings = typeof value === 'string' ? { foreground: value } : value;\n", "\t\t\t\tlet scopes = tokenGroupToScopesMap[key];\n", "\t\t\t\tfor (let scope of scopes) {\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\t\tlet scopes = tokenGroupToScopesMap[tokenGroup];\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 127 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "mergeLines": "Emmet: Esegui merge delle righe" }
i18n/ita/src/vs/workbench/parts/emmet/node/actions/mergeLines.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017597345868125558, 0.00017597345868125558, 0.00017597345868125558, 0.00017597345868125558, 0 ]
{ "id": 7, "code_window": [ "\t\t\t\tfor (let scope of scopes) {\n", "\t\t\t\t\tgeneralRules.push({\n", "\t\t\t\t\t\tscope,\n", "\t\t\t\t\t\tsettings\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tthis.customTokenColors.push({ scope, settings });\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.9980986714363098, 0.08195280283689499, 0.00016640618559904397, 0.00017220446898136288, 0.2581448256969452 ]
{ "id": 7, "code_window": [ "\t\t\t\tfor (let scope of scopes) {\n", "\t\t\t\t\tgeneralRules.push({\n", "\t\t\t\t\t\tscope,\n", "\t\t\t\t\t\tsettings\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tthis.customTokenColors.push({ scope, settings });\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'mocha'; import * as path from 'path'; import * as fs from 'fs'; import * as assert from 'assert'; import { getLanguageModes } from '../modes/languageModes'; import { TextDocument, Range, TextEdit, FormattingOptions } from 'vscode-languageserver-types'; import { format } from '../modes/formatting'; suite('HTML Embedded Formatting', () => { function assertFormat(value: string, expected: string, options?: any, formatOptions?: FormattingOptions, message?: string): void { var languageModes = getLanguageModes({ css: true, javascript: true }); if (options) { languageModes.getAllModes().forEach(m => m.configure!(options)); } let rangeStartOffset = value.indexOf('|'); let rangeEndOffset; if (rangeStartOffset !== -1) { value = value.substr(0, rangeStartOffset) + value.substr(rangeStartOffset + 1); rangeEndOffset = value.indexOf('|'); value = value.substr(0, rangeEndOffset) + value.substr(rangeEndOffset + 1); } else { rangeStartOffset = 0; rangeEndOffset = value.length; } let document = TextDocument.create('test://test/test.html', 'html', 0, value); let range = Range.create(document.positionAt(rangeStartOffset), document.positionAt(rangeEndOffset)); if (!formatOptions) { formatOptions = FormattingOptions.create(2, true); } let result = format(languageModes, document, range, formatOptions, void 0, { css: true, javascript: true }); let actual = applyEdits(document, result); assert.equal(actual, expected, message); } function assertFormatWithFixture(fixtureName: string, expectedPath: string, options?: any, formatOptions?: FormattingOptions): void { let input = fs.readFileSync(path.join(__dirname, 'fixtures', 'inputs', fixtureName)).toString(); let expected = fs.readFileSync(path.join(__dirname, 'fixtures', 'expected', expectedPath)).toString(); assertFormat(input, expected, options, formatOptions, expectedPath); } test('HTML only', function (): any { assertFormat('<html><body><p>Hello</p></body></html>', '<html>\n\n<body>\n <p>Hello</p>\n</body>\n\n</html>'); assertFormat('|<html><body><p>Hello</p></body></html>|', '<html>\n\n<body>\n <p>Hello</p>\n</body>\n\n</html>'); assertFormat('<html>|<body><p>Hello</p></body>|</html>', '<html><body>\n <p>Hello</p>\n</body></html>'); }); test('HTML & Scripts', function (): any { assertFormat('<html><head><script></script></head></html>', '<html>\n\n<head>\n <script></script>\n</head>\n\n</html>'); assertFormat('<html><head><script>var x=1;</script></head></html>', '<html>\n\n<head>\n <script>var x = 1;</script>\n</head>\n\n</html>'); assertFormat('<html><head><script>\nvar x=2;\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 2;\n </script>\n</head>\n\n</html>'); assertFormat('<html><head>\n <script>\nvar x=3;\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 3;\n </script>\n</head>\n\n</html>'); assertFormat('<html><head>\n <script>\nvar x=4;\nconsole.log("Hi");\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 4;\n console.log("Hi");\n </script>\n</head>\n\n</html>'); assertFormat('<html><head>\n |<script>\nvar x=5;\n</script>|</head></html>', '<html><head>\n <script>\n var x = 5;\n </script></head></html>'); }); test('HTLM & Scripts - Fixtures', function () { assertFormatWithFixture('19813.html', '19813.html'); assertFormatWithFixture('19813.html', '19813-4spaces.html', void 0, FormattingOptions.create(4, true)); assertFormatWithFixture('19813.html', '19813-tab.html', void 0, FormattingOptions.create(1, false)); assertFormatWithFixture('21634.html', '21634.html'); }); test('Script end tag', function (): any { assertFormat('<html>\n<head>\n <script>\nvar x = 0;\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 0;\n </script>\n</head>\n\n</html>'); }); test('HTML & Multiple Scripts', function (): any { assertFormat('<html><head>\n<script>\nif(x){\nbar(); }\n</script><script>\nfunction(x){ }\n</script></head></html>', '<html>\n\n<head>\n <script>\n if (x) {\n bar();\n }\n </script>\n <script>\n function(x) {}\n </script>\n</head>\n\n</html>'); }); test('HTML & Styles', function (): any { assertFormat('<html><head>\n<style>\n.foo{display:none;}\n</style></head></html>', '<html>\n\n<head>\n <style>\n .foo {\n display: none;\n }\n </style>\n</head>\n\n</html>'); }); test('EndWithNewline', function (): any { let options = { html: { format: { endWithNewline: true } } }; assertFormat('<html><body><p>Hello</p></body></html>', '<html>\n\n<body>\n <p>Hello</p>\n</body>\n\n</html>\n', options); assertFormat('<html>|<body><p>Hello</p></body>|</html>', '<html><body>\n <p>Hello</p>\n</body></html>', options); assertFormat('<html><head><script>\nvar x=1;\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 1;\n </script>\n</head>\n\n</html>\n', options); }); test('Inside script', function (): any { assertFormat('<html><head>\n <script>\n|var x=6;|\n</script></head></html>', '<html><head>\n <script>\n var x = 6;\n</script></head></html>'); assertFormat('<html><head>\n <script>\n|var x=6;\nvar y= 9;|\n</script></head></html>', '<html><head>\n <script>\n var x = 6;\n var y = 9;\n</script></head></html>'); }); test('Range after new line', function (): any { assertFormat('<html><head>\n |<script>\nvar x=6;\n</script>\n|</head></html>', '<html><head>\n <script>\n var x = 6;\n </script>\n</head></html>'); }); test('bug 36574', function (): any { assertFormat('<script src="/js/main.js"> </script>', '<script src="/js/main.js"> </script>'); }); }); function applyEdits(document: TextDocument, edits: TextEdit[]): string { let text = document.getText(); let sortedEdits = edits.sort((a, b) => { let startDiff = document.offsetAt(b.range.start) - document.offsetAt(a.range.start); if (startDiff === 0) { return document.offsetAt(b.range.end) - document.offsetAt(a.range.end); } return startDiff; }); let lastOffset = text.length; sortedEdits.forEach(e => { let startOffset = document.offsetAt(e.range.start); let endOffset = document.offsetAt(e.range.end); assert.ok(startOffset <= endOffset); assert.ok(endOffset <= lastOffset); text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); lastOffset = startOffset; }); return text; }
extensions/html/server/src/test/formatting.test.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0001774020929588005, 0.00017099401156883687, 0.00016551194130443037, 0.00017148934421129525, 0.0000030375611004274106 ]
{ "id": 7, "code_window": [ "\t\t\t\tfor (let scope of scopes) {\n", "\t\t\t\t\tgeneralRules.push({\n", "\t\t\t\t\t\tscope,\n", "\t\t\t\t\t\tsettings\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tthis.customTokenColors.push({ scope, settings });\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "tasksAriaLabel": "Type the name of a task to terminate", "noTasksMatching": "No tasks matching", "noTasksFound": "No tasks to terminate found" }
i18n/esn/src/vs/workbench/parts/tasks/browser/terminateQuickOpen.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017986482998821884, 0.0001778283331077546, 0.00017579183622729033, 0.0001778283331077546, 0.000002036496880464256 ]
{ "id": 7, "code_window": [ "\t\t\t\tfor (let scope of scopes) {\n", "\t\t\t\t\tgeneralRules.push({\n", "\t\t\t\t\t\tscope,\n", "\t\t\t\t\t\tsettings\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tthis.customTokenColors.push({ scope, settings });\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 129 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import URI from 'vs/base/common/uri'; import { TPromise } from 'vs/base/common/winjs.base'; import { IUntitledEditorService, UNTITLED_SCHEMA } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import errors = require('vs/base/common/errors'); import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { Position, IResourceInput, IUntitledResourceInput } from 'vs/platform/editor/common/editor'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { Schemas } from 'vs/base/common/network'; import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; export class BackupRestorer implements IWorkbenchContribution { private static readonly UNTITLED_REGEX = /Untitled-\d+/; constructor( @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IBackupFileService private backupFileService: IBackupFileService, @ITextFileService private textFileService: ITextFileService, @IEditorGroupService private groupService: IEditorGroupService, @ILifecycleService private lifecycleService: ILifecycleService ) { this.restoreBackups(); } private restoreBackups(): void { if (this.backupFileService.backupEnabled) { this.lifecycleService.when(LifecyclePhase.Running).then(() => { this.doRestoreBackups().done(null, errors.onUnexpectedError); }); } } private doRestoreBackups(): TPromise<URI[]> { // Find all files and untitled with backups return this.backupFileService.getWorkspaceFileBackups().then(backups => { // Resolve backups that are opened in stacks model return this.doResolveOpenedBackups(backups).then(unresolved => { // Some failed to restore or were not opened at all so we open and resolve them manually if (unresolved.length > 0) { return this.doOpenEditors(unresolved).then(() => this.doResolveOpenedBackups(unresolved)); } return void 0; }); }); } private doResolveOpenedBackups(backups: URI[]): TPromise<URI[]> { const stacks = this.groupService.getStacksModel(); const restorePromises: TPromise<any>[] = []; const unresolved: URI[] = []; backups.forEach(backup => { if (stacks.isOpen(backup)) { if (backup.scheme === Schemas.file) { restorePromises.push(this.textFileService.models.loadOrCreate(backup).then(null, () => unresolved.push(backup))); } else if (backup.scheme === UNTITLED_SCHEMA) { restorePromises.push(this.untitledEditorService.loadOrCreate({ resource: backup }).then(null, () => unresolved.push(backup))); } } else { unresolved.push(backup); } }); return TPromise.join(restorePromises).then(() => unresolved, () => unresolved); } private doOpenEditors(resources: URI[]): TPromise<void> { const stacks = this.groupService.getStacksModel(); const hasOpenedEditors = stacks.groups.length > 0; const inputs = resources.map((resource, index) => this.resolveInput(resource, index, hasOpenedEditors)); // Open all remaining backups as editors and resolve them to load their backups return this.editorService.openEditors(inputs.map(input => { return { input, position: Position.ONE }; })).then(() => void 0); } private resolveInput(resource: URI, index: number, hasOpenedEditors: boolean): IResourceInput | IUntitledResourceInput { const options = { pinned: true, preserveFocus: true, inactive: index > 0 || hasOpenedEditors }; if (resource.scheme === UNTITLED_SCHEMA && !BackupRestorer.UNTITLED_REGEX.test(resource.fsPath)) { return { filePath: resource.fsPath, options }; } return { resource, options }; } }
src/vs/workbench/parts/backup/common/backupRestorer.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017954081704374403, 0.0001739867147989571, 0.0001670443161856383, 0.0001739530125632882, 0.000003115757408522768 ]
{ "id": 8, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t});\n", "\n", "\t\tconst textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || [];\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t}\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 135 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.9991495609283447, 0.1489892601966858, 0.00016479101032018661, 0.00023922065156511962, 0.3315744698047638 ]
{ "id": 8, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t});\n", "\n", "\t\tconst textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || [];\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t}\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 135 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "editorSuggestWidgetBackground": "建议小组件的背景颜色", "editorSuggestWidgetBorder": "建议小组件的边框颜色", "editorSuggestWidgetForeground": "建议小组件的前景颜色。", "editorSuggestWidgetSelectedBackground": "建议小组件中被选择条目的背景颜色。", "editorSuggestWidgetHighlightForeground": "建议小组件中匹配内容的高亮颜色。", "readMore": "阅读详细信息...{0}", "suggestionWithDetailsAriaLabel": "{0}(建议)具有详细信息", "suggestionAriaLabel": "{0},建议", "readLess": "阅读简略信息...{0}", "suggestWidget.loading": "正在加载...", "suggestWidget.noSuggestions": "无建议。", "suggestionAriaAccepted": "{0},已接受", "ariaCurrentSuggestionWithDetails": "{0}(建议)具有详细信息", "ariaCurrentSuggestion": "{0},建议" }
i18n/chs/src/vs/editor/contrib/suggest/suggestWidget.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017376651521772146, 0.0001697578263701871, 0.00016684165166225284, 0.00016866528312675655, 0.000002930717300841934 ]
{ "id": 8, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t});\n", "\n", "\t\tconst textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || [];\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t}\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 135 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { Client } from 'vs/base/parts/ipc/node/ipc.cp'; import uri from 'vs/base/common/uri'; import { always } from 'vs/base/common/async'; import { ITestChannel, TestServiceClient, ITestService } from './testService'; function createClient(): Client { return new Client(uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'TestServer', env: { AMD_ENTRYPOINT: 'vs/base/parts/ipc/test/node/testApp', verbose: true } }); } // Rename to ipc.perf.test.ts and run with ./scripts/test.sh --grep IPC.performance --timeout 60000 suite('IPC performance', () => { test('increasing batch size', () => { const client = createClient(); const channel = client.getChannel<ITestChannel>('test'); const service = new TestServiceClient(channel); const runs = [ { batches: 250000, size: 1 }, { batches: 2500, size: 100 }, { batches: 500, size: 500 }, { batches: 250, size: 1000 }, { batches: 50, size: 5000 }, { batches: 25, size: 10000 }, // { batches: 10, size: 25000 }, // { batches: 5, size: 50000 }, // { batches: 1, size: 250000 }, ]; const dataSizes = [ 100, 250, ]; let i = 0, j = 0; const result = measure(service, 10, 10, 250) // warm-up .then(() => { return (function nextRun() { if (i >= runs.length) { if (++j >= dataSizes.length) { return; } i = 0; } const run = runs[i++]; return measure(service, run.batches, run.size, dataSizes[j]) .then(() => { return nextRun(); }); })(); }); return always(result, () => client.dispose()); }); test('increasing raw data size', () => { const client = createClient(); const channel = client.getChannel<ITestChannel>('test'); const service = new TestServiceClient(channel); const runs = [ { batches: 250000, dataSize: 100 }, { batches: 25000, dataSize: 1000 }, { batches: 2500, dataSize: 10000 }, { batches: 1250, dataSize: 20000 }, { batches: 500, dataSize: 50000 }, { batches: 250, dataSize: 100000 }, { batches: 125, dataSize: 200000 }, { batches: 50, dataSize: 500000 }, { batches: 25, dataSize: 1000000 }, ]; let i = 0; const result = measure(service, 10, 10, 250) // warm-up .then(() => { return (function nextRun() { if (i >= runs.length) { return; } const run = runs[i++]; return measure(service, run.batches, 1, run.dataSize) .then(() => { return nextRun(); }); })(); }); return always(result, () => client.dispose()); }); function measure(service: ITestService, batches: number, size: number, dataSize: number) { const start = Date.now(); let hits = 0; let count = 0; return service.batchPerf(batches, size, dataSize) .then(() => { console.log(`Batches: ${batches}, size: ${size}, dataSize: ${dataSize}, n: ${batches * size * dataSize}, duration: ${Date.now() - start}`); assert.strictEqual(hits, batches); assert.strictEqual(count, batches * size); }, err => assert.fail(err), batch => { hits++; count += batch.length; }); } });
src/vs/base/parts/ipc/test/node/ipc.perf.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017578831466380507, 0.00017076490621548146, 0.000166412050020881, 0.0001715279504423961, 0.000003165140469718608 ]
{ "id": 8, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t});\n", "\n", "\t\tconst textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || [];\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t}\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 135 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "close": "Chiudi", "cancel": "Annulla", "ok": "OK" }
i18n/ita/src/vs/workbench/api/electron-browser/mainThreadMessageService.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0001777946308720857, 0.00017737646703608334, 0.00017695828864816576, 0.00017737646703608334, 4.1817111195996404e-7 ]
{ "id": 9, "code_window": [ "\n", "\t\t// Put the general customizations such as comments, strings, etc. first so that\n", "\t\t// they can be overridden by specific customizations like \"string.interpolated\"\n", "\t\tthis.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules);\n", "\t}\n", "\n", "\tpublic ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> {\n", "\t\tif (!this.isLoaded) {\n", "\t\t\tif (this.path) {\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// specific customizations\n", "\t\tif (Array.isArray(customTokenColors.textMateRules)) {\n", "\t\t\tfor (let rule of customTokenColors.textMateRules) {\n", "\t\t\t\tif (rule.scope && rule.settings) {\n", "\t\t\t\t\tthis.customTokenColors.push(rule);\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 139 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.9979227185249329, 0.0315527617931366, 0.0001642374409129843, 0.0006741903489455581, 0.15970107913017273 ]
{ "id": 9, "code_window": [ "\n", "\t\t// Put the general customizations such as comments, strings, etc. first so that\n", "\t\t// they can be overridden by specific customizations like \"string.interpolated\"\n", "\t\tthis.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules);\n", "\t}\n", "\n", "\tpublic ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> {\n", "\t\tif (!this.isLoaded) {\n", "\t\t\tif (this.path) {\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// specific customizations\n", "\t\tif (Array.isArray(customTokenColors.textMateRules)) {\n", "\t\t\tfor (let rule of customTokenColors.textMateRules) {\n", "\t\t\t\tif (rule.scope && rule.settings) {\n", "\t\t\t\t\tthis.customTokenColors.push(rule);\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 139 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Event, { filterEvent, mapEvent, anyEvent } from 'vs/base/common/event'; import { TPromise } from 'vs/base/common/winjs.base'; import { IWindowService, IWindowsService, INativeOpenDialogOptions, IEnterWorkspaceResult, IMessageBoxResult, IWindowConfiguration } from 'vs/platform/windows/common/windows'; import { IRecentlyOpened } from 'vs/platform/history/common/history'; import { ICommandAction } from 'vs/platform/actions/common/actions'; import { IWorkspaceFolderCreationData } from 'vs/platform/workspaces/common/workspaces'; export class WindowService implements IWindowService { readonly onDidChangeFocus: Event<boolean>; _serviceBrand: any; constructor( private windowId: number, private configuration: IWindowConfiguration, @IWindowsService private windowsService: IWindowsService ) { const onThisWindowFocus = mapEvent(filterEvent(windowsService.onWindowFocus, id => id === windowId), _ => true); const onThisWindowBlur = mapEvent(filterEvent(windowsService.onWindowBlur, id => id === windowId), _ => false); this.onDidChangeFocus = anyEvent(onThisWindowFocus, onThisWindowBlur); } getCurrentWindowId(): number { return this.windowId; } getConfiguration(): IWindowConfiguration { return this.configuration; } pickFileFolderAndOpen(options: INativeOpenDialogOptions): TPromise<void> { options.windowId = this.windowId; return this.windowsService.pickFileFolderAndOpen(options); } pickFileAndOpen(options: INativeOpenDialogOptions): TPromise<void> { options.windowId = this.windowId; return this.windowsService.pickFileAndOpen(options); } pickFolderAndOpen(options: INativeOpenDialogOptions): TPromise<void> { options.windowId = this.windowId; return this.windowsService.pickFolderAndOpen(options); } pickWorkspaceAndOpen(options: INativeOpenDialogOptions): TPromise<void> { options.windowId = this.windowId; return this.windowsService.pickWorkspaceAndOpen(options); } reloadWindow(): TPromise<void> { return this.windowsService.reloadWindow(this.windowId); } openDevTools(): TPromise<void> { return this.windowsService.openDevTools(this.windowId); } toggleDevTools(): TPromise<void> { return this.windowsService.toggleDevTools(this.windowId); } closeWorkspace(): TPromise<void> { return this.windowsService.closeWorkspace(this.windowId); } createAndEnterWorkspace(folders?: IWorkspaceFolderCreationData[], path?: string): TPromise<IEnterWorkspaceResult> { return this.windowsService.createAndEnterWorkspace(this.windowId, folders, path); } saveAndEnterWorkspace(path: string): TPromise<IEnterWorkspaceResult> { return this.windowsService.saveAndEnterWorkspace(this.windowId, path); } closeWindow(): TPromise<void> { return this.windowsService.closeWindow(this.windowId); } toggleFullScreen(): TPromise<void> { return this.windowsService.toggleFullScreen(this.windowId); } setRepresentedFilename(fileName: string): TPromise<void> { return this.windowsService.setRepresentedFilename(this.windowId, fileName); } getRecentlyOpened(): TPromise<IRecentlyOpened> { return this.windowsService.getRecentlyOpened(this.windowId); } focusWindow(): TPromise<void> { return this.windowsService.focusWindow(this.windowId); } isFocused(): TPromise<boolean> { return this.windowsService.isFocused(this.windowId); } onWindowTitleDoubleClick(): TPromise<void> { return this.windowsService.onWindowTitleDoubleClick(this.windowId); } setDocumentEdited(flag: boolean): TPromise<void> { return this.windowsService.setDocumentEdited(this.windowId, flag); } show(): TPromise<void> { return this.windowsService.showWindow(this.windowId); } showMessageBox(options: Electron.MessageBoxOptions): TPromise<IMessageBoxResult> { return this.windowsService.showMessageBox(this.windowId, options); } showSaveDialog(options: Electron.SaveDialogOptions): TPromise<string> { return this.windowsService.showSaveDialog(this.windowId, options); } showOpenDialog(options: Electron.OpenDialogOptions): TPromise<string[]> { return this.windowsService.showOpenDialog(this.windowId, options); } updateTouchBar(items: ICommandAction[][]): TPromise<void> { return this.windowsService.updateTouchBar(this.windowId, items); } }
src/vs/platform/windows/electron-browser/windowService.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00019186659483239055, 0.00017309286340605468, 0.00016450058319605887, 0.00017163452866952866, 0.000006574878625542624 ]
{ "id": 9, "code_window": [ "\n", "\t\t// Put the general customizations such as comments, strings, etc. first so that\n", "\t\t// they can be overridden by specific customizations like \"string.interpolated\"\n", "\t\tthis.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules);\n", "\t}\n", "\n", "\tpublic ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> {\n", "\t\tif (!this.isLoaded) {\n", "\t\t\tif (this.path) {\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// specific customizations\n", "\t\tif (Array.isArray(customTokenColors.textMateRules)) {\n", "\t\t\tfor (let rule of customTokenColors.textMateRules) {\n", "\t\t\t\tif (rule.scope && rule.settings) {\n", "\t\t\t\t\tthis.customTokenColors.push(rule);\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 139 }
node_modules
extensions/yaml/.gitignore
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017092801863327622, 0.00017092801863327622, 0.00017092801863327622, 0.00017092801863327622, 0 ]
{ "id": 9, "code_window": [ "\n", "\t\t// Put the general customizations such as comments, strings, etc. first so that\n", "\t\t// they can be overridden by specific customizations like \"string.interpolated\"\n", "\t\tthis.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules);\n", "\t}\n", "\n", "\tpublic ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> {\n", "\t\tif (!this.isLoaded) {\n", "\t\t\tif (this.path) {\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// specific customizations\n", "\t\tif (Array.isArray(customTokenColors.textMateRules)) {\n", "\t\t\tfor (let rule of customTokenColors.textMateRules) {\n", "\t\t\t\tif (rule.scope && rule.settings) {\n", "\t\t\t\t\tthis.customTokenColors.push(rule);\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 139 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import { Registry } from 'vs/platform/registry/common/platform'; import { Action } from 'vs/base/common/actions'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { IWorkbenchActionRegistry, Extensions } from 'vs/workbench/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; export class ToggleTabsVisibilityAction extends Action { public static readonly ID = 'workbench.action.toggleTabsVisibility'; public static readonly LABEL = nls.localize('toggleTabs', "Toggle Tab Visibility"); private static readonly tabsVisibleKey = 'workbench.editor.showTabs'; constructor( id: string, label: string, @IConfigurationService private configurationService: IConfigurationService ) { super(id, label); } public run(): TPromise<any> { const visibility = this.configurationService.getValue<string>(ToggleTabsVisibilityAction.tabsVisibleKey); const newVisibilityValue = !visibility; return this.configurationService.updateValue(ToggleTabsVisibilityAction.tabsVisibleKey, newVisibilityValue); } } const registry = Registry.as<IWorkbenchActionRegistry>(Extensions.WorkbenchActions); registry.registerWorkbenchAction(new SyncActionDescriptor(ToggleTabsVisibilityAction, ToggleTabsVisibilityAction.ID, ToggleTabsVisibilityAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.KEY_W }), 'View: Toggle Tab Visibility', nls.localize('view', "View"));
src/vs/workbench/browser/actions/toggleTabsVisibility.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00023258724831975996, 0.00018242854275740683, 0.00016578819486312568, 0.00017110117187257856, 0.000025170145818265155 ]
{ "id": 10, "code_window": [ "\t\treturn TPromise.as(null);\n", "\t}\n", "\n", "\t/**\n", "\t * Place the default settings first and add add the token-info rules\n", "\t */\n", "\tprivate sanitizeTokenColors() {\n", "\t\tlet hasDefaultTokens = false;\n", "\t\tlet updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)];\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t * Place the default settings first and add the token-info rules\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.9992706179618835, 0.212473064661026, 0.0001648568722885102, 0.0007538681384176016, 0.36156749725341797 ]
{ "id": 10, "code_window": [ "\t\treturn TPromise.as(null);\n", "\t}\n", "\n", "\t/**\n", "\t * Place the default settings first and add add the token-info rules\n", "\t */\n", "\tprivate sanitizeTokenColors() {\n", "\t\tlet hasDefaultTokens = false;\n", "\t\tlet updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)];\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t * Place the default settings first and add the token-info rules\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 157 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "checkout": "Extraer del repositorio...", "sync changes": "Sincronizar cambios", "publish changes": "Publicar cambios", "syncing changes": "Sincronizando cambios..." }
i18n/esn/extensions/git/out/statusbar.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017927752924151719, 0.00017753493739292026, 0.0001757923309924081, 0.00017753493739292026, 0.0000017425991245545447 ]
{ "id": 10, "code_window": [ "\t\treturn TPromise.as(null);\n", "\t}\n", "\n", "\t/**\n", "\t * Place the default settings first and add add the token-info rules\n", "\t */\n", "\tprivate sanitizeTokenColors() {\n", "\t\tlet hasDefaultTokens = false;\n", "\t\tlet updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)];\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t * Place the default settings first and add the token-info rules\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "vscode.extension.contributes.view": "Ajoute une vue personnalisée", "vscode.extension.contributes.view.id": "ID unique utilisé pour identifier la vue créée avec vscode.workspace.createTreeView", "vscode.extension.contributes.view.label": "Chaîne contrôlable de visu permettant d'afficher la vue", "vscode.extension.contributes.view.icon": "Chemin de l'icône de la vue", "vscode.extension.contributes.views": "Ajoute des vues personnalisées", "showViewlet": "Afficher {0}", "view": "Affichage" }
i18n/fra/src/vs/workbench/parts/explorers/browser/treeExplorer.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017688692605588585, 0.00017502668197266757, 0.0001731664378894493, 0.00017502668197266757, 0.0000018602440832182765 ]
{ "id": 10, "code_window": [ "\t\treturn TPromise.as(null);\n", "\t}\n", "\n", "\t/**\n", "\t * Place the default settings first and add add the token-info rules\n", "\t */\n", "\tprivate sanitizeTokenColors() {\n", "\t\tlet hasDefaultTokens = false;\n", "\t\tlet updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)];\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t * Place the default settings first and add the token-info rules\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export const typescript = 'typescript'; export const typescriptreact = 'typescriptreact'; export const javascript = 'javascript'; export const javascriptreact = 'javascriptreact'; export const jsxTags = 'jsx-tags';
extensions/typescript/src/utils/languageModeIds.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017759588081389666, 0.00017463337280787528, 0.0001716708648018539, 0.00017463337280787528, 0.0000029625080060213804 ]
{ "id": 11, "code_window": [ "\t */\n", "\tprivate sanitizeTokenColors() {\n", "\t\tlet hasDefaultTokens = false;\n", "\t\tlet updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)];\n", "\t\tthis.tokenColors.forEach(rule => {\n", "\t\t\tif (rule.scope) {\n", "\t\t\t\tif (rule.scope === 'token.info-token') {\n", "\t\t\t\t\thasDefaultTokens = true;\n", "\t\t\t\t}\n", "\t\t\t\tupdatedTokenColors.push(rule);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.themeTokenColors.forEach(rule => {\n", "\t\t\tif (rule.scope && rule.settings) {\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 162 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import Paths = require('vs/base/common/paths'); import Json = require('vs/base/common/json'); import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITokenColorizationRule, IColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/electron-browser/themeCompatibility'; import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import * as types from 'vs/base/common/types'; import * as objects from 'vs/base/common/objects'; import pfs = require('vs/base/node/pfs'); import { Extensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ThemeType } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { WorkbenchThemeService, IColorCustomizations } from 'vs/workbench/services/themes/electron-browser/workbenchThemeService'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; let colorRegistry = <IColorRegistry>Registry.as(Extensions.ColorContribution); const tokenGroupToScopesMap: { [setting: string]: string[] } = { comments: ['comment'], strings: ['string'], keywords: ['keyword', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable'] }; export class ColorThemeData implements IColorTheme { private constructor() { } id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; path?: string; extensionData: ExtensionData; get tokenColors(): ITokenColorizationRule[] { // Add the custom colors after the theme colors // so that they will override them return this.themeTokenColors.concat(this.customTokenColors); } private themeTokenColors: ITokenColorizationRule[] = []; private customTokenColors: ITokenColorizationRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color { let color = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } public getDefault(colorId: ColorIdentifier): Color { return colorRegistry.resolveDefaultColor(colorId, this); } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); if (`[${this.settingsId}]` in colors) { const themeSpecificColors = (colors[`[${this.settingsId}]`] || {}) as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } } if (this.themeTokenColors && this.themeTokenColors.length) { updateDefaultRuleSettings(this.themeTokenColors[0], this); } } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; let customTokenColorsWithoutThemeSpecific: ITokenColorCustomizations = {}; for (let key in customTokenColors) { if (key[0] !== '[') { customTokenColorsWithoutThemeSpecific[key] = customTokenColors[key]; } } this.addCustomTokenColors(customTokenColorsWithoutThemeSpecific); if (`[${this.settingsId}]` in customTokenColors) { const themeSpecificTokenColors: ITokenColorCustomizations = customTokenColors[`[${this.settingsId}]`]; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { let generalRules: ITokenColorizationRule[] = []; Object.keys(tokenGroupToScopesMap).forEach(key => { let value = customTokenColors[key]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[key]; for (let scope of scopes) { generalRules.push({ scope, settings }); } } }); const textMateRules: ITokenColorizationRule[] = customTokenColors.textMateRules || []; // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" this.customTokenColors = this.customTokenColors.concat(generalRules, textMateRules); } public ensureLoaded(themeService: WorkbenchThemeService): TPromise<void> { if (!this.isLoaded) { if (this.path) { return _loadColorThemeFromFile(this.path, this.themeTokenColors, this.colorMap).then(_ => { this.isLoaded = true; this.sanitizeTokenColors(); }); } } return TPromise.as(null); } /** * Place the default settings first and add add the token-info rules */ private sanitizeTokenColors() { let hasDefaultTokens = false; let updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)]; this.tokenColors.forEach(rule => { if (rule.scope) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } updatedTokenColors.push(rule); } }); if (!hasDefaultTokens) { updatedTokenColors.push(...defaultThemeColors[this.type]); } this.themeTokenColors = updatedTokenColors; } toStorageData() { let colorMapData = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings return JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, selector: this.id.split(' ').join('.'), // to not break old clients themeTokenColors: this.themeTokenColors, extensionData: this.extensionData, colorMap: colorMapData }); } hasEqualData(other: ColorThemeData) { return objects.equals(this.colorMap, other.colorMap) && objects.equals(this.tokenColors, other.tokenColors); } get type(): ThemeType { let baseTheme = this.id.split(' ')[0]; switch (baseTheme) { case VS_LIGHT_THEME: return 'light'; case VS_HC_THEME: return 'hc'; default: return 'dark'; } } // constructors static createUnloadedTheme(id: string): ColorThemeData { let themeData = new ColorThemeData(); themeData.id = id; themeData.label = ''; themeData.settingsId = null; themeData.isLoaded = false; themeData.themeTokenColors = [{ settings: {} }]; return themeData; } static fromStorageData(input: string): ColorThemeData { try { let data = JSON.parse(input); let theme = new ColorThemeData(); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'extensionData': theme[key] = data[key]; break; } } return theme; } catch (e) { return null; } } static fromExtensionTheme(theme: IThemeExtensionPoint, normalizedAbsolutePath: string, extensionData: ExtensionData): ColorThemeData { let baseTheme: string = theme['uiTheme'] || 'vs-dark'; let themeSelector = toCSSSelector(extensionData.extensionId + '-' + Paths.normalize(theme.path)); let themeData = new ColorThemeData(); themeData.id = `${baseTheme} ${themeSelector}`; themeData.label = theme.label || Paths.basename(theme.path); themeData.settingsId = theme.id || themeData.label; themeData.description = theme.description; themeData.path = normalizedAbsolutePath; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(str: string) { str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } function _loadColorThemeFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { if (Paths.extname(themePath) === '.json') { return pfs.readFile(themePath).then(content => { let errors: Json.ParseError[] = []; let contentValue = Json.parse(content.toString(), errors); if (errors.length > 0) { return TPromise.wrapError(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } let includeCompletes = TPromise.as(null); if (contentValue.include) { includeCompletes = _loadColorThemeFromFile(Paths.join(Paths.dirname(themePath), contentValue.include), resultRules, resultColors); } return includeCompletes.then(_ => { if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, resultRules, resultColors); return null; } let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themePath))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null resultColors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { resultRules.push(...tokenColors); return null; } else if (typeof tokenColors === 'string') { return _loadSyntaxTokensFromFile(Paths.join(Paths.dirname(themePath), tokenColors), resultRules, {}); } else { return TPromise.wrapError(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themePath))); } } return null; }); }); } else { return _loadSyntaxTokensFromFile(themePath, resultRules, resultColors); } } let pListParser: Thenable<{ parse(content: string) }>; function getPListParser() { return pListParser || import('fast-plist'); } function _loadSyntaxTokensFromFile(themePath: string, resultRules: ITokenColorizationRule[], resultColors: IColorMap): TPromise<any> { return pfs.readFile(themePath).then(content => { return getPListParser().then(parser => { try { let contentValue = parser.parse(content.toString()); let settings: ITokenColorizationRule[] = contentValue.settings; if (!Array.isArray(settings)) { return TPromise.wrapError(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, resultRules, resultColors); return TPromise.as(null); } catch (e) { return TPromise.wrapError(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }); }, error => { return TPromise.wrapError(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themePath, error.message))); }); } function updateDefaultRuleSettings(defaultRule: ITokenColorizationRule, theme: ColorThemeData): ITokenColorizationRule { let foreground = theme.getColor(editorForeground) || theme.getDefault(editorForeground); let background = theme.getColor(editorBackground) || theme.getDefault(editorBackground); defaultRule.settings.foreground = Color.Format.CSS.formatHexA(foreground); defaultRule.settings.background = Color.Format.CSS.formatHexA(background); return defaultRule; } let defaultThemeColors: { [baseTheme: string]: ITokenColorizationRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], };
src/vs/workbench/services/themes/electron-browser/colorThemeData.ts
1
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.9990831613540649, 0.08366082608699799, 0.0001668784098001197, 0.00022554164752364159, 0.26799437403678894 ]
{ "id": 11, "code_window": [ "\t */\n", "\tprivate sanitizeTokenColors() {\n", "\t\tlet hasDefaultTokens = false;\n", "\t\tlet updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)];\n", "\t\tthis.tokenColors.forEach(rule => {\n", "\t\t\tif (rule.scope) {\n", "\t\t\t\tif (rule.scope === 'token.info-token') {\n", "\t\t\t\t\thasDefaultTokens = true;\n", "\t\t\t\t}\n", "\t\t\t\tupdatedTokenColors.push(rule);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.themeTokenColors.forEach(rule => {\n", "\t\t\tif (rule.scope && rule.settings) {\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 162 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "currentChange": "(modifica corrente)", "incomingChange": "(modifica in ingresso)" }
i18n/ita/extensions/merge-conflict/out/mergeDecorator.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.00017904964624904096, 0.00017729989485815167, 0.00017555012891534716, 0.00017729989485815167, 0.0000017497586668469012 ]
{ "id": 11, "code_window": [ "\t */\n", "\tprivate sanitizeTokenColors() {\n", "\t\tlet hasDefaultTokens = false;\n", "\t\tlet updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)];\n", "\t\tthis.tokenColors.forEach(rule => {\n", "\t\t\tif (rule.scope) {\n", "\t\t\t\tif (rule.scope === 'token.info-token') {\n", "\t\t\t\t\thasDefaultTokens = true;\n", "\t\t\t\t}\n", "\t\t\t\tupdatedTokenColors.push(rule);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.themeTokenColors.forEach(rule => {\n", "\t\t\tif (rule.scope && rule.settings) {\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 162 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { INavigator, ArrayNavigator } from 'vs/base/common/iterator'; export class HistoryNavigator<T> implements INavigator<T> { private _history: Set<T>; private _limit: number; private _navigator: ArrayNavigator<T>; constructor(history: T[] = [], limit: number = 10) { this._initialize(history); this._limit = limit; this._onChange(); } public getHistory(): T[] { return this._elements; } public add(t: T) { this._history.delete(t); this._history.add(t); this._onChange(); } public addIfNotPresent(t: T) { if (!this._history.has(t)) { this.add(t); } } public next(): T { if (this._navigator.next()) { return this._navigator.current(); } this.last(); return null; } public previous(): T { if (this._navigator.previous()) { return this._navigator.current(); } this.first(); return null; } public current(): T { return this._navigator.current(); } public parent(): T { return null; } public first(): T { return this._navigator.first(); } public last(): T { return this._navigator.last(); } private _onChange() { this._reduceToLimit(); this._navigator = new ArrayNavigator(this._elements); this._navigator.last(); } private _reduceToLimit() { let data = this._elements; if (data.length > this._limit) { this._initialize(data.slice(data.length - this._limit)); } } private _initialize(history: T[]): void { this._history = new Set(); for (const entry of history) { this._history.add(entry); } } private get _elements(): T[] { const elements: T[] = []; this._history.forEach(e => elements.push(e)); return elements; } }
src/vs/base/common/history.ts
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0001787202781997621, 0.00017238545115105808, 0.00016765865439083427, 0.00017167160694953054, 0.000002890622909035301 ]
{ "id": 11, "code_window": [ "\t */\n", "\tprivate sanitizeTokenColors() {\n", "\t\tlet hasDefaultTokens = false;\n", "\t\tlet updatedTokenColors: ITokenColorizationRule[] = [updateDefaultRuleSettings({ settings: {} }, this)];\n", "\t\tthis.tokenColors.forEach(rule => {\n", "\t\t\tif (rule.scope) {\n", "\t\t\t\tif (rule.scope === 'token.info-token') {\n", "\t\t\t\t\thasDefaultTokens = true;\n", "\t\t\t\t}\n", "\t\t\t\tupdatedTokenColors.push(rule);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.themeTokenColors.forEach(rule => {\n", "\t\t\tif (rule.scope && rule.settings) {\n" ], "file_path": "src/vs/workbench/services/themes/electron-browser/colorThemeData.ts", "type": "replace", "edit_start_line_idx": 162 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "open": "Abrir", "index modified": "Índice modificado", "modified": "Modificado", "index added": "Índice añadido", "index deleted": "Índice Eliminado", "deleted": "Eliminado", "index renamed": "Nombre de Índice Cambiado", "index copied": "Índice copiado", "untracked": "Sin seguimiento", "ignored": "Omitido", "both deleted": "Ambos eliminados", "added by us": "Agregado por nosotros", "deleted by them": "Eliminado por ellos", "added by them": "Agregado por ellos", "deleted by us": "Borrado por nosotros", "both added": "Ambos añadidos", "both modified": "Ambos modificados", "commitMessage": "Message (press {0} to commit)", "commit": "Confirmar", "merge changes": "Fusionar cambios mediante combinación", "staged changes": "Cambios almacenados provisionalmente", "changes": "Cambios", "commitMessageCountdown": "quedan {0} caracteres en la línea actual", "commitMessageWarning": "{0} caracteres sobre {1} en la línea actual", "ok": "Aceptar", "neveragain": "No volver a mostrar", "huge": "El repositorio Git '{0}' contiene muchos cambios activos, solamente un subconjunto de las características de Git serán habilitadas." }
i18n/esn/extensions/git/out/repository.i18n.json
0
https://github.com/microsoft/vscode/commit/4aec98a3cdb88a3bd08a9efa4704f10ab537356c
[ 0.0001790721871657297, 0.00017629950889386237, 0.00017479583038948476, 0.00017566498718224466, 0.000001648318402658333 ]
{ "id": 0, "code_window": [ " modelValue: number | string | null | undefined\n", " showValidationError?: boolean\n", "}\n", "\n", "const { modelValue, showValidationError = true } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const { t } = useI18n()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { modelValue, showValidationError } = withDefaults(defineProps<Props>(), { showValidationError: true })\n" ], "file_path": "packages/nc-gui/components/cell/Duration.vue", "type": "replace", "edit_start_line_idx": 22 }
<script lang="ts" setup> import type { ColumnType } from 'nocodb-sdk' import { UITypes, isVirtualCol } from 'nocodb-sdk' import { ActiveCellInj, IsFormInj, ReadonlyInj, iconMap, inject, isAttachment, ref, useExpandedFormDetached, useLTARStoreOrThrow, } from '#imports' interface Props { value: string | number | boolean item: any column: any showUnlinkButton?: boolean border?: boolean readonly?: boolean } const { value, item, column, showUnlinkButton, border = true, readonly: readonlyProp } = defineProps<Props>() const emit = defineEmits(['unlink']) const { relatedTableMeta } = useLTARStoreOrThrow()! const { isUIAllowed } = useRoles() const readOnly = inject(ReadonlyInj, ref(false)) const active = inject(ActiveCellInj, ref(false)) const isForm = inject(IsFormInj)! const { open } = useExpandedFormDetached() function openExpandedForm() { const rowId = extractPkFromRow(item, relatedTableMeta.value.columns as ColumnType[]) if (!readOnly.value && !readonlyProp && rowId) { open({ isOpen: true, row: { row: item, rowMeta: {}, oldRow: { ...item } }, meta: relatedTableMeta.value, rowId, useMetaFields: true, }) } } </script> <script lang="ts"> export default { name: 'ItemChip', } </script> <template> <div v-e="['c:row-expand:open']" class="chip group mr-1 my-1 flex items-center rounded-[2px] flex-row" :class="{ active, 'border-1 py-1 px-2': isAttachment(column) }" @click="openExpandedForm" > <span class="name"> <!-- Render virtual cell --> <div v-if="isVirtualCol(column)"> <template v-if="column.uidt === UITypes.LinkToAnotherRecord"> <LazySmartsheetVirtualCell :edit-enabled="false" :model-value="value" :column="column" :read-only="true" /> </template> <LazySmartsheetVirtualCell v-else :edit-enabled="false" :read-only="true" :model-value="value" :column="column" /> </div> <!-- Render normal cell --> <template v-else> <div v-if="isAttachment(column) && value && !Array.isArray(value) && typeof value === 'object'"> <LazySmartsheetCell :model-value="value" :column="column" :edit-enabled="false" :read-only="true" /> </div> <!-- For attachment cell avoid adding chip style --> <template v-else> <div class="min-w-max" :class="{ 'px-1 rounded-full flex-1': !isAttachment(column), 'border-gray-200 rounded border-1': border && ![UITypes.Attachment, UITypes.MultiSelect, UITypes.SingleSelect].includes(column.uidt), }" > <LazySmartsheetCell :model-value="value" :column="column" :edit-enabled="false" :virtual="true" :read-only="true" /> </div> </template> </template> </span> <div v-show="active || isForm" v-if="showUnlinkButton && !readOnly && isUIAllowed('dataEdit')" class="flex items-center"> <component :is="iconMap.closeThick" class="nc-icon unlink-icon text-xs text-gray-500/50 group-hover:text-gray-500" @click.stop="emit('unlink')" /> </div> </div> </template> <style scoped lang="scss"> .chip { max-width: max(100%, 60px); .name { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; } } </style>
packages/nc-gui/components/virtual-cell/components/ItemChip.vue
1
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.005309285596013069, 0.0008730182307772338, 0.00016953502199612558, 0.00017423633835278451, 0.0016067764954641461 ]
{ "id": 0, "code_window": [ " modelValue: number | string | null | undefined\n", " showValidationError?: boolean\n", "}\n", "\n", "const { modelValue, showValidationError = true } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const { t } = useI18n()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { modelValue, showValidationError } = withDefaults(defineProps<Props>(), { showValidationError: true })\n" ], "file_path": "packages/nc-gui/components/cell/Duration.vue", "type": "replace", "edit_start_line_idx": 22 }
import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { extractRolesObj, ProjectRoles } from 'nocodb-sdk'; import { Strategy } from 'passport-custom'; import type { Request } from 'express'; import { ApiToken, User } from '~/models'; import { sanitiseUserObj } from '~/utils'; @Injectable() export class AuthTokenStrategy extends PassportStrategy(Strategy, 'authtoken') { // eslint-disable-next-line @typescript-eslint/ban-types async validate(req: Request, callback: Function) { try { let user; if (req.headers['xc-token']) { const apiToken = await ApiToken.getByToken(req.headers['xc-token']); if (!apiToken) { return callback({ msg: 'Invalid token' }); } user = { is_api_token: true, }; // old auth tokens will not have fk_user_id, so we return editor role if (!apiToken.fk_user_id) { user.base_roles = extractRolesObj(ProjectRoles.EDITOR); return callback(null, user); } const dbUser: Record<string, any> = await User.getWithRoles( apiToken.fk_user_id, { baseId: req['ncBaseId'], ...(req['ncWorkspaceId'] ? { workspaceId: req['ncWorkspaceId'] } : {}), }, ); if (!dbUser) { return callback({ msg: 'User not found' }); } Object.assign(user, { id: dbUser.id, roles: extractRolesObj(dbUser.roles), base_roles: extractRolesObj(dbUser.base_roles), ...(dbUser.workspace_roles ? { workspace_roles: extractRolesObj(dbUser.workspace_roles) } : {}), }); } return callback(null, sanitiseUserObj(user)); } catch (error) { return callback(error); } } }
packages/nocodb/src/strategies/authtoken.strategy/authtoken.strategy.ts
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00017593000666238368, 0.00017321207269560546, 0.00016936763131525367, 0.0001733451645122841, 0.000002068175717795384 ]
{ "id": 0, "code_window": [ " modelValue: number | string | null | undefined\n", " showValidationError?: boolean\n", "}\n", "\n", "const { modelValue, showValidationError = true } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const { t } = useI18n()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { modelValue, showValidationError } = withDefaults(defineProps<Props>(), { showValidationError: true })\n" ], "file_path": "packages/nc-gui/components/cell/Duration.vue", "type": "replace", "edit_start_line_idx": 22 }
<script setup lang="ts"> import type { VNodeRef } from '@vue/runtime-core' import type { OrgUserReqType } from 'nocodb-sdk' import { OrgUserRoles } from 'nocodb-sdk' import type { User, Users } from '#imports' import { Form, computed, emailValidator, extractSdkResponseErrorMsg, iconMap, message, ref, useCopy, useDashboard, useI18n, useNuxtApp, } from '#imports' interface Props { show: boolean selectedUser?: User } const { show } = defineProps<Props>() const emit = defineEmits(['closed', 'reload']) const { t } = useI18n() const { $api, $e } = useNuxtApp() const { copy } = useCopy() const { dashboardUrl } = useDashboard() const { clearBasesUser } = useBases() const usersData = ref<Users>({ emails: '', role: OrgUserRoles.VIEWER, invitationToken: undefined }) const formRef = ref() const useForm = Form.useForm const validators = computed(() => { return { emails: [emailValidator], } }) const { validateInfos } = useForm(usersData.value, validators) const saveUser = async () => { $e('a:org-user:invite', { role: usersData.value.role }) await formRef.value?.validateFields() try { const res = await $api.orgUsers.add({ roles: usersData.value.role, email: usersData.value.emails, } as unknown as OrgUserReqType) usersData.value.invitationToken = res.invite_token emit('reload') // Successfully updated the user details message.success(t('msg.success.userAdded')) clearBasesUser() } catch (e: any) { console.error(e) message.error(await extractSdkResponseErrorMsg(e)) } } const inviteUrl = computed(() => usersData.value.invitationToken ? `${dashboardUrl.value}#/signup/${usersData.value.invitationToken}` : null, ) const copyUrl = async () => { if (!inviteUrl.value) return try { await copy(inviteUrl.value) // Copied shareable source url to clipboard! message.success(t('msg.toast.inviteUrlCopy')) } catch (e: any) { message.error(e.message) } $e('c:shared-base:copy-url') } const clickInviteMore = () => { $e('c:user:invite-more') usersData.value.invitationToken = undefined usersData.value.role = OrgUserRoles.VIEWER usersData.value.emails = '' } const emailInput: VNodeRef = (el) => (el as HTMLInputElement)?.focus() </script> <template> <a-modal :class="{ active: show }" :footer="null" centered :visible="show" :closable="false" width="max(50vw, 44rem)" wrap-class-name="nc-modal-invite-user" @cancel="emit('closed')" > <div class="flex flex-col"> <div class="flex flex-row justify-between items-center pb-1.5 mb-2 border-b-1 w-full"> <a-typography-title class="select-none" :level="4" data-rec="true"> {{ $t('activity.inviteUser') }}</a-typography-title> <a-button type="text" class="!rounded-md mr-1 -mt-1.5" @click="emit('closed')"> <template #icon> <MaterialSymbolsCloseRounded data-testid="nc-root-user-invite-modal-close" class="flex mx-auto" /> </template> </a-button> </div> <div class="px-2 mt-1.5"> <template v-if="usersData.invitationToken"> <div class="flex flex-col mt-1 pb-5"> <div class="flex flex-row items-center pl-1.5 pb-1 h-[1.1rem]"> <component :is="iconMap.account" /> <div class="text-xs ml-0.5 mt-0.5" data-rec="true">{{ $t('activity.copyInviteURL') }}</div> </div> <a-alert class="!mt-2" type="success" show-icon> <template #message> <div class="flex flex-row justify-between items-center py-1"> <div class="flex pl-2 text-green-700 text-xs" data-rec="true"> {{ inviteUrl }} </div> <a-button type="text" class="!rounded-md -mt-0.5" @click="copyUrl"> <template #icon> <component :is="iconMap.copy" class="flex mx-auto text-green-700 h-[1rem]" /> </template> </a-button> </div> </template> </a-alert> <div class="flex text-xs text-gray-500 mt-2 justify-start ml-2" data-rec="true"> {{ $t('msg.info.userInviteNoSMTP') }} {{ usersData.invitationToken && usersData.emails }} </div> <div class="flex flex-row justify-end mt-4 ml-2"> <a-button size="middle" outlined @click="clickInviteMore"> <div class="flex flex-row justify-center items-center space-x-0.5"> <MaterialSymbolsSendOutline class="flex mx-auto text-gray-600 h-[0.8rem]" /> <div class="text-xs text-gray-600" data-rec="true">{{ $t('activity.inviteMore') }}</div> </div> </a-button> </div> </div> </template> <div v-else class="flex flex-col pb-4"> <div class="border-1 py-3 px-4 rounded-md mt-1"> <a-form ref="formRef" :validate-on-rule-change="false" :model="usersData" validate-trigger="onBlur" @finish="saveUser" > <div class="flex flex-row space-x-4"> <div class="flex flex-col w-3/4"> <a-form-item v-bind="validateInfos.emails" validate-trigger="onBlur" name="emails" :rules="[{ required: true, message: $t('msg.plsInputEmail') }]" > <div class="ml-1 mb-1 text-xs text-gray-500" data-rec="true">{{ $t('datatype.Email') }}:</div> <a-input :ref="emailInput" v-model:value="usersData.emails" size="middle" validate-trigger="onBlur" :placeholder="$t('labels.email')" /> </a-form-item> </div> <div class="flex flex-col w-2/4"> <a-form-item name="role" :rules="[{ required: true, message: $t('msg.roleRequired') }]"> <div class="ml-1 mb-1 text-xs text-gray-500">{{ $t('labels.selectUserRole') }}</div> <a-select v-model:value="usersData.role" class="nc-user-roles" dropdown-class-name="nc-dropdown-user-role !px-2" > <a-select-option class="nc-role-option" :value="OrgUserRoles.CREATOR" :label="$t(`objects.roleType.orgLevelCreator`)" > <div class="flex items-center gap-1 justify-between"> <div data-rec="true">{{ $t(`objects.roleType.orgLevelCreator`) }}</div> <GeneralIcon v-if="usersData.role === OrgUserRoles.CREATOR" id="nc-selected-item-icon" icon="check" class="w-4 h-4 text-primary" /> </div> <span class="text-gray-500 text-xs whitespace-normal" data-rec="true"> {{ $t('msg.info.roles.orgCreator') }} </span> </a-select-option> <a-select-option class="nc-role-option" :value="OrgUserRoles.VIEWER" :label="$t(`objects.roleType.orgLevelViewer`)" > <div class="flex items-center gap-1 justify-between"> <div data-rec="true">{{ $t(`objects.roleType.orgLevelViewer`) }}</div> <GeneralIcon v-if="usersData.role === OrgUserRoles.VIEWER" id="nc-selected-item-icon" icon="check" class="w-4 h-4 text-primary" /> </div> <span class="text-gray-500 text-xs whitespace-normal" data-rec="true"> {{ $t('msg.info.roles.orgViewer') }} </span> </a-select-option> </a-select> </a-form-item> </div> </div> <div class="flex flex-row justify-end"> <a-button type="primary" class="!rounded-md" html-type="submit"> <div class="flex flex-row justify-center items-center space-x-1.5"> <MaterialSymbolsSendOutline class="flex h-[0.8rem]" /> <div data-rec="true">{{ $t('activity.invite') }}</div> </div> </a-button> </div> </a-form> </div> </div> </div> </div> </a-modal> </template>
packages/nc-gui/components/account/UsersModal.vue
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.9714158177375793, 0.042644038796424866, 0.00016670618788339198, 0.0001738185528665781, 0.18507777154445648 ]
{ "id": 0, "code_window": [ " modelValue: number | string | null | undefined\n", " showValidationError?: boolean\n", "}\n", "\n", "const { modelValue, showValidationError = true } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const { t } = useI18n()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { modelValue, showValidationError } = withDefaults(defineProps<Props>(), { showValidationError: true })\n" ], "file_path": "packages/nc-gui/components/cell/Duration.vue", "type": "replace", "edit_start_line_idx": 22 }
<script lang="ts" setup> import { Icon as IconifyIcon } from '@iconify/vue' import InfiniteLoading from 'v3-infinite-loading' import { emojiIcons } from '#imports' const props = defineProps<{ showReset?: boolean }>() const emit = defineEmits(['selectIcon']) const search = ref('') // keep a variable to load icons with infinite scroll // set initial value to 60 to load first 60 icons (index - `0 - 59`) // and next value will be 120 and shows first 120 icons ( index - `0 - 129`) const toIndex = ref(60) const filteredIcons = computed(() => { return emojiIcons .filter((icon) => !search.value || icon.toLowerCase().includes(search.value.toLowerCase())) .slice(0, toIndex.value) }) const load = () => { // increment `toIndex` to include next set of icons toIndex.value += Math.min(filteredIcons.value.length, toIndex.value + 60) if (toIndex.value > filteredIcons.value.length) { toIndex.value = filteredIcons.value.length } } const selectIcon = (icon?: string) => { search.value = '' emit('selectIcon', icon && `emojione:${icon}`) } </script> <template> <div> <div class="p-1 w-[280px] h-[280px] flex flex-col gap-1 justify-start nc-emoji" data-testid="nc-emoji-container"> <div @click.stop> <input v-model="search" data-testid="nc-emoji-filter" class="p-1 text-xs border-1 w-full overflow-y-auto" placeholder="Search" @input="toIndex = 60" /> </div> <div class="flex gap-1 flex-wrap w-full flex-shrink overflow-y-auto scrollbar-thin-dull"> <div v-for="icon of filteredIcons" :key="icon" @click="selectIcon(icon)"> <span class="cursor-pointer nc-emoji-item"> <IconifyIcon class="text-xl iconify" :icon="`emojione:${icon}`"></IconifyIcon> </span> </div> <InfiniteLoading @infinite="load"><span /></InfiniteLoading> </div> </div> <div v-if="props.showReset" class="m-1"> <a-divider class="!my-2 w-full" /> <div class="p-1 mt-1 cursor-pointer text-xs inline-block border-gray-200 border-1 rounded" @click="selectIcon()"> <PhXCircleLight class="text-sm" /> Reset Icon </div> </div> </div> </template> <style scoped> .nc-emoji-item { @apply hover:(bg-primary bg-opacity-10) active:(bg-primary !bg-opacity-20) rounded-md w-[38px] h-[38px] block flex items-center justify-center; } </style>
packages/nc-gui/components/general/EmojiIcons.vue
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.9815105199813843, 0.12552103400230408, 0.0001724363537505269, 0.00017464248230680823, 0.32360967993736267 ]
{ "id": 1, "code_window": [ " isPk?: boolean\n", "}\n", "\n", "const { modelValue, isPk = false } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const { modelValue, isPk = false } = withDefaults(defineProps<Props>(), { isPk: false })\n" ], "file_path": "packages/nc-gui/components/cell/YearPicker.vue", "type": "replace", "edit_start_line_idx": 20 }
<script lang="ts" setup> import type { BaseType } from 'nocodb-sdk' import { iconMap, navigateTo, useColors, useNuxtApp } from '#imports' interface Props { bases?: BaseType[] } const { bases = [] } = defineProps<Props>() const emit = defineEmits(['delete-base']) const { $e } = useNuxtApp() const { getColorByIndex } = useColors(true) const openProject = async (base: BaseType) => { await navigateTo(`/nc/${base.id}`) $e('a:base:open', { count: bases.length }) } const formatTitle = (title?: string) => title ?.split(' ') .map((w) => w[0]) .slice(0, 2) .join('') </script> <template> <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 3xl:grid-cols-8 gap-6 md:(gap-y-16)"> <div class="group flex flex-col items-center gap-2"> <v-menu> <template #activator="{ props }"> <div class="thumbnail hover:(after:!opacity-100 shadow-lg to-primary/50)" :style="{ '--thumbnail-color': '#1348ba' }" @click="props.onClick" > a <component :is="iconMap.plus" /> </div> <div class="prose-lg font-semibold"> {{ $t('title.newProj') }} </div> </template> <v-list class="!py-0 flex flex-col bg-white rounded-lg shadow-md border-1 border-gray-300 mt-2 ml-2"> <div class="grid grid-cols-12 cursor-pointer hover:bg-gray-200 flex items-center p-2" @click="navigateTo('/base/create')" > <component :is="iconMap.plus" class="col-span-2 mr-1 mt-[1px] text-primary text-lg" /> <div class="col-span-10 text-sm xl:text-md">{{ $t('activity.createProject') }}</div> </div> <div class="grid grid-cols-12 cursor-pointer hover:bg-gray-200 flex items-center p-2" @click="navigateTo('/base/create-external')" > <component :is="iconMap.dtabase" class="col-span-2 mr-1 mt-[1px] text-green-500 text-lg" /> <div class="col-span-10 text-sm xl:text-md" v-html="$t('activity.createProjectExtended.extDB')" /> </div> </v-list> </v-menu> </div> <div v-for="(base, i) of bases" :key="base.id" class="group flex flex-col items-center gap-2"> <div class="thumbnail" :style="{ '--thumbnail-color': getColorByIndex(i) }" @click="openProject(base)"> {{ formatTitle(base.title) }} <a-dropdown overlay-class-name="nc-dropdown-base-operations" @click.stop> <component :is="iconMap.arrowDown" class="menu-icon" /> <template #overlay> <a-menu> <a-menu-item @click.stop="emit('delete-base', base)"> <div class="grid grid-cols-6 cursor-pointer flex items-center p-2"> <component :is="iconMap.delete" class="col-span-2 mr-1 mt-[1px] text-red text-lg" /> <div class="col-span-4 text-sm xl:text-md">{{ $t('general.delete') }}</div> </div> </a-menu-item> <a-menu-item @click.stop="navigateTo(`/base/${base.id}`)"> <div class="grid grid-cols-6 cursor-pointer flex items-center p-2"> <component :is="iconMap.edit" class="col-span-2 mr-1 mt-[1px] text-primary text-lg" /> <div class="col-span-4 text-sm xl:text-md">{{ $t('general.edit') }}</div> </div> </a-menu-item> </a-menu> </template> </a-dropdown> </div> <div class="prose-lg font-semibold overflow-ellipsis w-full overflow-hidden text-center capitalize"> {{ base.title || 'Untitled' }} </div> </div> </div> </template> <style scoped> .thumbnail { @apply relative rounded-md opacity-75 font-bold text-white text-[75px] h-[100px] w-full w-[100px] shadow-md cursor-pointer uppercase flex items-center justify-center color-transition hover:(after:opacity-100 shadow-none); } .thumbnail::after { @apply rounded-md absolute top-0 left-0 right-0 bottom-0 transition-all duration-150 ease-in-out opacity-75; background-color: var(--thumbnail-color); content: ''; z-index: -1; } .thumbnail:hover::after { @apply shadow-2xl transform scale-110; } .menu-icon, .star-icon { @apply w-auto opacity-0 absolute h-[1.75rem] transition-opacity !duration-200 group-hover:opacity-100; } .star-icon { @apply top-1 right-1 transform hover:(scale-120 text-yellow-300/75) transition-all duration-100 ease; } .menu-icon { @apply bottom-1 right-1 transform hover:(scale-150 text-gray-200) transition-all duration-100 ease; } </style>
packages/nc-gui/pages/projects/index/index.vue
1
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.019099095836281776, 0.002805509138852358, 0.00016595695342402905, 0.00017179269343614578, 0.006216511595994234 ]
{ "id": 1, "code_window": [ " isPk?: boolean\n", "}\n", "\n", "const { modelValue, isPk = false } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const { modelValue, isPk = false } = withDefaults(defineProps<Props>(), { isPk: false })\n" ], "file_path": "packages/nc-gui/components/cell/YearPicker.vue", "type": "replace", "edit_start_line_idx": 20 }
# compiled output /dist /node_modules # Logs logs *.log npm-debug.log* pnpm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # OS .DS_Store # Tests /coverage /.nyc_output # IDEs and editors /.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json /noco.db # export export/** # test dbs test_sakila_?.db # ignoring to avoid commiting those files # nc-gui dir is copied for building local docker. /docker/main.js /docker/nc-gui/ /tests/unit/.env
packages/nocodb/.gitignore
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00017255527200177312, 0.00017144964658655226, 0.00016937375767156482, 0.0001718654384603724, 0.0000011861292250614497 ]
{ "id": 1, "code_window": [ " isPk?: boolean\n", "}\n", "\n", "const { modelValue, isPk = false } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const { modelValue, isPk = false } = withDefaults(defineProps<Props>(), { isPk: false })\n" ], "file_path": "packages/nc-gui/components/cell/YearPicker.vue", "type": "replace", "edit_start_line_idx": 20 }
export { all } from 'locale-codes'
packages/nc-gui/utils/currencyCodes.ts
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00017095671501010656, 0.00017095671501010656, 0.00017095671501010656, 0.00017095671501010656, 0 ]
{ "id": 1, "code_window": [ " isPk?: boolean\n", "}\n", "\n", "const { modelValue, isPk = false } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const { modelValue, isPk = false } = withDefaults(defineProps<Props>(), { isPk: false })\n" ], "file_path": "packages/nc-gui/components/cell/YearPicker.vue", "type": "replace", "edit_start_line_idx": 20 }
<script lang="ts" setup> import type { ColumnType } from 'nocodb-sdk' import { isVirtualCol } from 'nocodb-sdk' const { column } = defineProps<{ column: ColumnType }>() </script> <template> <SmartsheetHeaderVirtualCellIcon v-if="isVirtualCol(column)" :column-meta="column" /> <SmartsheetHeaderCellIcon v-else :column-meta="column" /> </template>
packages/nc-gui/components/smartsheet/header/Icon.vue
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.0014808154664933681, 0.0008288132376037538, 0.00017681103781796992, 0.0008288132376037538, 0.0006520021706819534 ]
{ "id": 2, "code_window": [ " sourceId: string\n", " importDataOnly?: boolean\n", "}\n", "\n", "const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const { $api } = useNuxtApp()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { importType, importDataOnly, sourceId, ...rest } = withDefaults(defineProps<Props>(), { importDataOnly: false })\n" ], "file_path": "packages/nc-gui/components/dlg/QuickImport.vue", "type": "replace", "edit_start_line_idx": 47 }
<script lang="ts" setup> import type { BaseType } from 'nocodb-sdk' import { iconMap, navigateTo } from '#imports' interface Props { bases?: BaseType[] } const { bases = [] } = defineProps<Props>() const emit = defineEmits(['delete-base']) const { $e } = useNuxtApp() const openProject = async (base: BaseType) => { await navigateTo(`/nc/${base.id}`) $e('a:base:open', { count: bases.length }) } </script> <template> <div> <div class="grid grid-cols-3 gap-2 prose-md p-2 font-semibold"> <div>{{ $t('general.title') }}</div> <div>Updated At</div> <div></div> </div> <div class="col-span-3 w-full h-[1px] bg-gray-500/50" /> <template v-for="base of bases" :key="base.id"> <div class="cursor-pointer grid grid-cols-3 gap-2 prose-md hover:(bg-gray-300/30) p-2 transition-color ease-in duration-100" @click="openProject(base)" > <div class="font-semibold capitalize">{{ base.title || 'Untitled' }}</div> <div>{{ base.updated_at }}</div> <div class="flex justify-center"> <component :is="iconMap.delete" class="text-gray-500 hover:text-red-500 mr-2" @click.stop="emit('delete-base', base)" /> <component :is="iconMap.edit" class="text-gray-500 hover:text-primary mr-2" @click.stop="navigateTo(`/base/${base.id}`)" /> </div> </div> <div class="col-span-3 w-full h-[1px] bg-gray-500/30" /> </template> </div> </template>
packages/nc-gui/pages/projects/index/list.vue
1
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.5864571332931519, 0.09875619411468506, 0.00017132092034444213, 0.0001746647758409381, 0.21811479330062866 ]
{ "id": 2, "code_window": [ " sourceId: string\n", " importDataOnly?: boolean\n", "}\n", "\n", "const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const { $api } = useNuxtApp()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { importType, importDataOnly, sourceId, ...rest } = withDefaults(defineProps<Props>(), { importDataOnly: false })\n" ], "file_path": "packages/nc-gui/components/dlg/QuickImport.vue", "type": "replace", "edit_start_line_idx": 47 }
import { T } from 'nc-help'; import type { Request } from 'express'; const countMap = {}; // eslint-disable-next-line @typescript-eslint/no-unused-vars const metrics = async (req: Request, c = 150) => { if (!req?.route?.path) return; const event = `a:api:${req.route.path}:${req.method}`; countMap[event] = (countMap[event] || 0) + 1; if (countMap[event] >= c) { T.event({ event }); countMap[event] = 0; } }; const metaApiMetrics = (_req: Request, _res, next) => { // metrics(req, 50).then(() => {}); next(); }; export default (_req: Request, _res, next) => { // metrics(req).then(() => {}); next(); }; export { metaApiMetrics };
packages/nocodb/src/helpers/apiMetrics.ts
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00017256135470233858, 0.000171976862475276, 0.00017113203648477793, 0.00017223719623871148, 6.118648343544919e-7 ]
{ "id": 2, "code_window": [ " sourceId: string\n", " importDataOnly?: boolean\n", "}\n", "\n", "const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const { $api } = useNuxtApp()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { importType, importDataOnly, sourceId, ...rest } = withDefaults(defineProps<Props>(), { importDataOnly: false })\n" ], "file_path": "packages/nc-gui/components/dlg/QuickImport.vue", "type": "replace", "edit_start_line_idx": 47 }
--- title: 'Base collaboration' description: 'Invite team members to work on a base' tags: ['Bases', 'Collaboration', 'Members', 'Invite', 'Roles', 'Permissions'] keywords: ['NocoDB base', 'base collaboration'] --- A member added to a workspace will carry his assigned role specific permissions to all the base with in workspace. To override member permissions to your base, please follow steps outlined below: 1. Go to the left sidebar and select `Base name` to access the `Base Dashboard.` 2. Click on the `Members` tab. 3. Use the dropdown menu to specify the access permissions for the member you wish to collaborate. 4. Finalize the process by assigning the desired role to the user. ![image](/img/v2/base/base-collaboration.png) More details about roles & permissions can be found [here](/roles-and-permissions/roles-permissions-overview). ## Related articles - [Base overview](/bases/base-overview) - [Create an empty base](/bases/create-base) - [Import base from Airtable](/bases/import-base-from-airtable) - [Invite team members to work on a base](/bases/base-collaboration) - [Share base publicly](/bases/share-base) - [Rename base](/bases/actions-on-base#rename-base) - [Duplicate base](/bases/actions-on-base#duplicate-base) - [Bookmark base](/bases/actions-on-base#star-base) - [Delete base](/bases/actions-on-base#delete-base)
packages/noco-docs/docs/040.bases/050.base-collaboration.md
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.0001730084914015606, 0.00016855394642334431, 0.000162572629051283, 0.00017008067516144365, 0.0000043950740291620605 ]
{ "id": 2, "code_window": [ " sourceId: string\n", " importDataOnly?: boolean\n", "}\n", "\n", "const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const { $api } = useNuxtApp()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { importType, importDataOnly, sourceId, ...rest } = withDefaults(defineProps<Props>(), { importDataOnly: false })\n" ], "file_path": "packages/nc-gui/components/dlg/QuickImport.vue", "type": "replace", "edit_start_line_idx": 47 }
<script lang="ts" setup> import type { Ref } from '@vue/reactivity' import UploadIcon from '~icons/nc-icons/upload' import DownloadIcon from '~icons/nc-icons/download' import { ActiveViewInj, IsLockedInj, IsPublicInj, LockType, MetaInj, extractSdkResponseErrorMsg, iconMap, inject, message, ref, useBase, useI18n, useMenuCloseOnEsc, useNuxtApp, useRoles, useSmartsheetStoreOrThrow, } from '#imports' const { t } = useI18n() const sharedViewListDlg = ref(false) const isPublicView = inject(IsPublicInj, ref(false)) const isView = false const { $api, $e } = useNuxtApp() const { isSqlView } = useSmartsheetStoreOrThrow() const selectedView = inject(ActiveViewInj, ref()) const isLocked = inject(IsLockedInj, ref(false)) const showWebhookDrawer = ref(false) const showApiSnippetDrawer = ref(false) const showErd = ref(false) type QuickImportDialogType = 'csv' | 'excel' | 'json' // TODO: add 'json' when it's ready const quickImportDialogTypes: QuickImportDialogType[] = ['csv', 'excel'] const quickImportDialogs: Record<(typeof quickImportDialogTypes)[number], Ref<boolean>> = quickImportDialogTypes.reduce( (acc: any, curr) => { acc[curr] = ref(false) return acc }, {}, ) as Record<QuickImportDialogType, Ref<boolean>> const { isUIAllowed } = useRoles() useBase() const meta = inject(MetaInj, ref()) const currentBaseId = computed(() => meta.value?.source_id) /* const Icon = computed(() => { switch (selectedView.value?.lock_type) { case LockType.Personal: return iconMap.account case LockType.Locked: return iconMap.lock case LockType.Collaborative: default: return iconMap.users } }) */ const lockType = computed(() => (selectedView.value?.lock_type as LockType) || LockType.Collaborative) async function changeLockType(type: LockType) { $e('a:grid:lockmenu', { lockType: type }) if (!selectedView.value) return if (type === 'personal') { // Coming soon return message.info(t('msg.toast.futureRelease')) } try { selectedView.value.lock_type = type await $api.dbView.update(selectedView.value.id as string, { lock_type: type, }) message.success(`Successfully Switched to ${type} view`) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } } const open = ref(false) useMenuCloseOnEsc(open) </script> <template> <div> <a-dropdown v-model:visible="open" :trigger="['click']" overlay-class-name="nc-dropdown-actions-menu" placement="bottomRight"> <a-button v-e="['c:actions']" class="nc-actions-menu-btn nc-toolbar-btn !border-1 !border-gray-200 !rounded-md !py-1 !px-2"> <MdiDotsHorizontal class="!w-4 !h-4" /> </a-button> <template #overlay> <a-menu class="!py-0 !rounded !text-gray-800 text-sm" data-testid="toolbar-actions" @click="open = false"> <a-menu-item-group> <template v-if="isUIAllowed('csvTableImport') && !isView && !isPublicView && !isSqlView"> <a-sub-menu key="upload"> <template #title> <div v-e="['c:navdraw:preview-as']" class="nc-base-menu-item group"> <UploadIcon class="w-4 h-4" /> {{ $t('general.upload') }} <div class="flex-1" /> <component :is="iconMap.arrowRight" /> </div> </template> <template #expandIcon></template> <template v-for="(dialog, type) in quickImportDialogs"> <a-menu-item v-if="isUIAllowed(`${type}TableImport`) && !isView && !isPublicView" :key="type"> <div v-e="[`a:upload:${type}`]" class="nc-base-menu-item" :class="{ disabled: isLocked }" @click="!isLocked ? (dialog.value = true) : {}" > <component :is="iconMap.upload" /> {{ `${$t('general.upload')} ${type.toUpperCase()}` }} </div> </a-menu-item> </template> </a-sub-menu> </template> <a-sub-menu key="download"> <template #title> <div v-e="['c:download']" class="nc-base-menu-item group"> <DownloadIcon class="w-4 h-4" /> {{ $t('general.download') }} <div class="flex-1" /> <component :is="iconMap.arrowRight" /> </div> </template> <template #expandIcon></template> <LazySmartsheetToolbarExportSubActions /> </a-sub-menu> <a-sub-menu v-if="isUIAllowed('viewCreateOrEdit')" key="lock-type" class="scrollbar-thin-dull max-h-90vh overflow-auto !py-0" > <template #title> <div v-e="['c:navdraw:preview-as']" class="nc-base-menu-item group px-0 !py-0"> <LazySmartsheetToolbarLockType hide-tick :type="lockType" /> <component :is="iconMap.arrowRight" /> </div> </template> <template #expandIcon></template> <a-menu-item @click="changeLockType(LockType.Collaborative)"> <LazySmartsheetToolbarLockType :type="LockType.Collaborative" /> </a-menu-item> <a-menu-item @click="changeLockType(LockType.Locked)"> <LazySmartsheetToolbarLockType :type="LockType.Locked" /> </a-menu-item> <!-- <a-menu-item @click="changeLockType(LockType.Personal)"> <LazySmartsheetToolbarLockType :type="LockType.Personal" /> </a-menu-item> --> </a-sub-menu> </a-menu-item-group> </a-menu> </template> </a-dropdown> <template v-if="currentBaseId"> <LazyDlgQuickImport v-for="tp in quickImportDialogTypes" :key="tp" v-model="quickImportDialogs[tp].value" :import-type="tp" :source-id="currentBaseId" :import-data-only="true" /> </template> <LazyWebhookDrawer v-if="showWebhookDrawer" v-model="showWebhookDrawer" /> <LazySmartsheetToolbarErd v-model="showErd" /> <a-modal v-model:visible="sharedViewListDlg" :class="{ active: sharedViewListDlg }" :title="$t('activity.listSharedView')" width="max(900px,60vw)" :footer="null" wrap-class-name="nc-modal-shared-view-list" > <LazySmartsheetToolbarSharedViewList v-if="sharedViewListDlg" /> </a-modal> <LazySmartsheetApiSnippet v-model="showApiSnippetDrawer" /> </div> </template> <style scoped> :deep(.ant-dropdown-menu-submenu-title) { @apply py-0; } :deep(.ant-dropdown-menu-item-group-title) { @apply hidden; } </style>
packages/nc-gui/components/smartsheet/toolbar/ViewActions.vue
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.9600883722305298, 0.04021068662405014, 0.00016542768571525812, 0.00017285291687585413, 0.1918078064918518 ]
{ "id": 3, "code_window": [ " (event: 'close'): void\n", "\n", " (event: 'open'): void\n", "}\n", "\n", "const { transition = true, teleportDisabled = false, inline = false, target, zIndex = 100, ...rest } = defineProps<Props>()\n", "\n", "const emits = defineEmits<Emits>()\n", "\n", "const vModel = useVModel(rest, 'modelValue', emits)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { transition, teleportDisabled, inline, target, zIndex, ...rest } = withDefaults(defineProps<Props>(), {\n", " transition: true,\n", " teleportDisabled: false,\n", " inline: false,\n", " zIndex: 100,\n", "})\n" ], "file_path": "packages/nc-gui/components/general/Overlay.vue", "type": "replace", "edit_start_line_idx": 24 }
<script lang="ts" setup> import { computed, ref } from '#imports' interface Props { placement?: | 'top' | 'left' | 'right' | 'bottom' | 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'leftTop' | 'leftBottom' | 'rightTop' | 'rightBottom' length?: number } const { placement = 'bottom', length = 20 } = defineProps<Props>() const text = ref<HTMLDivElement>() const enableTooltip = computed(() => text.value?.textContent?.length && text.value?.textContent?.length > length) const shortName = computed(() => text.value?.textContent?.length && text.value?.textContent.length > length ? `${text.value?.textContent?.substr(0, length - 3)}...` : text.value?.textContent, ) </script> <template> <a-tooltip v-if="enableTooltip" :placement="placement"> <template #title> <slot /> </template> <div class="w-full">{{ shortName }}</div> </a-tooltip> <div v-else class="w-full" data-testid="truncate-label"> <slot /> </div> <div ref="text" class="hidden"><slot /></div> </template>
packages/nc-gui/components/general/TruncateText.vue
1
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.001871823100373149, 0.0005163085879758, 0.0001706150360405445, 0.00017516255320515484, 0.0006777930539101362 ]
{ "id": 3, "code_window": [ " (event: 'close'): void\n", "\n", " (event: 'open'): void\n", "}\n", "\n", "const { transition = true, teleportDisabled = false, inline = false, target, zIndex = 100, ...rest } = defineProps<Props>()\n", "\n", "const emits = defineEmits<Emits>()\n", "\n", "const vModel = useVModel(rest, 'modelValue', emits)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { transition, teleportDisabled, inline, target, zIndex, ...rest } = withDefaults(defineProps<Props>(), {\n", " transition: true,\n", " teleportDisabled: false,\n", " inline: false,\n", " zIndex: 100,\n", "})\n" ], "file_path": "packages/nc-gui/components/general/Overlay.vue", "type": "replace", "edit_start_line_idx": 24 }
<script setup lang="ts"> import type { ColumnType, TableType, ViewType } from 'nocodb-sdk' import { ViewTypes, isLinksOrLTAR, isSystemColumn, isVirtualCol } from 'nocodb-sdk' import type { Ref } from 'vue' import MdiChevronDown from '~icons/mdi/chevron-down' import { CellClickHookInj, FieldsInj, IsExpandedFormOpenInj, IsKanbanInj, IsPublicInj, MetaInj, ReloadRowDataHookInj, computedInject, createEventHook, iconMap, inject, message, provide, ref, toRef, useActiveKeyupListener, useProvideExpandedFormStore, useProvideSmartsheetStore, useRoles, useRouter, useVModel, watch, } from '#imports' interface Props { modelValue?: boolean state?: Record<string, any> | null meta: TableType loadRow?: boolean useMetaFields?: boolean row?: Row rowId?: string view?: ViewType showNextPrevIcons?: boolean firstRow?: boolean lastRow?: boolean closeAfterSave?: boolean newRecordHeader?: string } const props = defineProps<Props>() const emits = defineEmits(['update:modelValue', 'cancel', 'next', 'prev', 'createdRecord']) const { activeView } = storeToRefs(useViewsStore()) const key = ref(0) const wrapper = ref() const { dashboardUrl } = useDashboard() const { copy } = useClipboard() const { isMobileMode } = useGlobal() const { t } = useI18n() const rowId = toRef(props, 'rowId') const row = toRef(props, 'row') const state = toRef(props, 'state') const meta = toRef(props, 'meta') const islastRow = toRef(props, 'lastRow') const isFirstRow = toRef(props, 'firstRow') const route = useRoute() const router = useRouter() const isPublic = inject(IsPublicInj, ref(false)) // to check if a expanded form which is not yet saved exist or not const isUnsavedFormExist = ref(false) const isRecordLinkCopied = ref(false) const { isUIAllowed } = useRoles() const readOnly = computed(() => !isUIAllowed('dataEdit') || isPublic.value) const expandedFormScrollWrapper = ref() const reloadTrigger = inject(ReloadRowDataHookInj, createEventHook()) const { addOrEditStackRow } = useKanbanViewStoreOrThrow() const { isExpandedFormCommentMode } = storeToRefs(useConfigStore()) // override cell click hook to avoid unexpected behavior at form fields provide(CellClickHookInj, undefined) const fields = computedInject(FieldsInj, (_fields) => { if (props.useMetaFields) { return (meta.value.columns ?? []).filter((col) => !isSystemColumn(col)) } return _fields?.value ?? [] }) const hiddenFields = computed(() => { return (meta.value.columns ?? []).filter((col) => !fields.value?.includes(col)).filter((col) => !isSystemColumn(col)) }) const showHiddenFields = ref(false) const toggleHiddenFields = () => { showHiddenFields.value = !showHiddenFields.value } const isKanban = inject(IsKanbanInj, ref(false)) provide(MetaInj, meta) const isLoading = ref(true) const { commentsDrawer, changedColumns, deleteRowById, displayValue, state: rowState, isNew, loadRow: _loadRow, primaryKey, saveRowAndStay, row: _row, save: _save, loadCommentsAndLogs, clearColumns, } = useProvideExpandedFormStore(meta, row) const duplicatingRowInProgress = ref(false) useProvideSmartsheetStore(ref({}) as Ref<ViewType>, meta) watch( state, () => { if (state.value) { rowState.value = state.value } else { rowState.value = {} } }, { immediate: true }, ) const isExpanded = useVModel(props, 'modelValue', emits, { defaultValue: false, }) const onClose = () => { if (changedColumns.value.size > 0) { isCloseModalOpen.value = true } else { if (_row.value?.rowMeta?.new) emits('cancel') isExpanded.value = false } } const onDuplicateRow = () => { duplicatingRowInProgress.value = true isUnsavedFormExist.value = true const oldRow = { ..._row.value.row } delete oldRow.ncRecordId const newRow = Object.assign( {}, { row: oldRow, oldRow: {}, rowMeta: { new: true }, }, ) setTimeout(async () => { _row.value = newRow duplicatingRowInProgress.value = false message.success(t('msg.success.rowDuplicatedWithoutSavedYet')) }, 500) } const save = async () => { let kanbanClbk if (activeView.value?.type === ViewTypes.KANBAN) { kanbanClbk = (row: any, isNewRow: boolean) => { addOrEditStackRow(row, isNewRow) } } if (isNew.value) { await _save(rowState.value, undefined, { kanbanClbk, }) reloadTrigger?.trigger() } else { await _save(undefined, undefined, { kanbanClbk, }) _loadRow() reloadTrigger?.trigger() } isUnsavedFormExist.value = false if (props.closeAfterSave) { isExpanded.value = false } emits('createdRecord', _row.value.row) } const isPreventChangeModalOpen = ref(false) const isCloseModalOpen = ref(false) const discardPreventModal = () => { // when user click on next or previous button if (isPreventChangeModalOpen.value) { emits('next') if (_row.value?.rowMeta?.new) emits('cancel') isPreventChangeModalOpen.value = false } // when user click on close button if (isCloseModalOpen.value) { isCloseModalOpen.value = false if (_row.value?.rowMeta?.new) emits('cancel') isExpanded.value = false } // clearing all new modifed change on close clearColumns() } const onNext = async () => { if (changedColumns.value.size > 0) { isPreventChangeModalOpen.value = true return } emits('next') } const copyRecordUrl = async () => { await copy( encodeURI( `${dashboardUrl?.value}#/${route.params.typeOrId}/${route.params.baseId}/${meta.value?.id}${ props.view ? `/${props.view.title}` : '' }?rowId=${primaryKey.value}`, ), ) isRecordLinkCopied.value = true } const saveChanges = async () => { if (isPreventChangeModalOpen.value) { isUnsavedFormExist.value = false await save() emits('next') isPreventChangeModalOpen.value = false } if (isCloseModalOpen.value) { isCloseModalOpen.value = false await save() isExpanded.value = false } } const reloadParentRowHook = inject(ReloadRowDataHookInj, createEventHook()) // override reload trigger and use it to reload grid and the form itself const reloadHook = createEventHook() reloadHook.on(() => { reloadParentRowHook?.trigger(false) if (isNew.value) return _loadRow() }) provide(ReloadRowDataHookInj, reloadHook) if (isKanban.value) { // adding column titles to changedColumns if they are preset for (const [k, v] of Object.entries(_row.value.row)) { if (v) { changedColumns.value.add(k) } } } provide(IsExpandedFormOpenInj, isExpanded) const cellWrapperEl = ref() onMounted(async () => { isRecordLinkCopied.value = false isLoading.value = true const focusFirstCell = !isExpandedFormCommentMode.value if (props.loadRow) { await _loadRow() await loadCommentsAndLogs() } if (props.rowId) { try { await _loadRow(props.rowId) await loadCommentsAndLogs() } catch (e: any) { if (e.response?.status === 404) { message.error(t('msg.noRecordFound')) router.replace({ query: {} }) } else throw e } } isLoading.value = false if (focusFirstCell) { setTimeout(() => { cellWrapperEl.value?.$el?.querySelector('input,select,textarea')?.focus() }, 300) } }) const addNewRow = () => { setTimeout(async () => { _row.value = { row: {}, oldRow: {}, rowMeta: { new: true }, } rowState.value = {} key.value++ isExpanded.value = true }, 500) } // attach keyboard listeners to switch between rows // using alt + left/right arrow keys useActiveKeyupListener( isExpanded, async (e: KeyboardEvent) => { if (!e.altKey) return if (e.key === 'ArrowLeft') { e.stopPropagation() emits('prev') } else if (e.key === 'ArrowRight') { e.stopPropagation() onNext() } // on alt + s save record else if (e.code === 'KeyS') { // remove focus from the active input if any ;(document.activeElement as HTMLElement)?.blur() e.stopPropagation() if (isNew.value) { await _save(rowState.value) reloadHook?.trigger(null) } else { await save() reloadHook?.trigger(null) } if (!saveRowAndStay.value) { onClose() } // on alt + n create new record } else if (e.code === 'KeyN') { // remove focus from the active input if any to avoid unwanted input ;(document.activeElement as HTMLInputElement)?.blur?.() if (changedColumns.value.size > 0) { await Modal.confirm({ title: t('msg.saveChanges'), okText: t('general.save'), cancelText: t('labels.discard'), onOk: async () => { await save() reloadHook?.trigger(null) addNewRow() }, onCancel: () => { addNewRow() }, }) } else if (isNew.value) { await Modal.confirm({ title: 'Do you want to save the record?', okText: t('general.save'), cancelText: t('labels.discard'), onOk: async () => { await _save(rowState.value) reloadHook?.trigger(null) addNewRow() }, onCancel: () => { addNewRow() }, }) } else { addNewRow() } } }, { immediate: true }, ) const showDeleteRowModal = ref(false) const onDeleteRowClick = () => { showDeleteRowModal.value = true } const onConfirmDeleteRowClick = async () => { showDeleteRowModal.value = false await deleteRowById(primaryKey.value) message.success(t('msg.rowDeleted')) reloadTrigger.trigger() onClose() showDeleteRowModal.value = false } watch(rowId, async (nRow) => { await _loadRow(nRow) await loadCommentsAndLogs() }) const showRightSections = computed(() => { return !isNew.value && commentsDrawer.value && isUIAllowed('commentList') }) const preventModalStatus = computed({ get: () => isCloseModalOpen.value || isPreventChangeModalOpen.value, set: (v) => { isCloseModalOpen.value = v }, }) const onIsExpandedUpdate = (v: boolean) => { let isDropdownOpen = false document.querySelectorAll('.ant-select-dropdown').forEach((el) => { isDropdownOpen = isDropdownOpen || el.checkVisibility() }) if (isDropdownOpen) return if (changedColumns.value.size === 0 && !isUnsavedFormExist.value) { isExpanded.value = v } else if (!v) { preventModalStatus.value = true } else { isExpanded.value = v } } const isReadOnlyVirtualCell = (column: ColumnType) => { return isRollup(column) || isFormula(column) || isBarcode(column) || isLookup(column) || isQrCode(column) } // Small hack. We need to scroll to the bottom of the form after its mounted and back to top. // So that tab to next row works properly, as otherwise browser will focus to save button // when we reach to the bottom of the visual scrollable area, not the actual bottom of the form watch([expandedFormScrollWrapper, isLoading], () => { if (isMobileMode.value) return if (expandedFormScrollWrapper.value && !isLoading.value) { const height = expandedFormScrollWrapper.value.scrollHeight expandedFormScrollWrapper.value.scrollTop = height setTimeout(() => { expandedFormScrollWrapper.value.scrollTop = 0 }, 125) } }) </script> <script lang="ts"> export default { name: 'ExpandedForm', } </script> <template> <NcModal :visible="isExpanded" :footer="null" :width="commentsDrawer && isUIAllowed('commentList') ? 'min(80vw,1280px)' : 'min(80vw,1280px)'" :body-style="{ padding: 0 }" :closable="false" size="small" class="nc-drawer-expanded-form" :class="{ active: isExpanded }" @update:visible="onIsExpandedUpdate" > <div class="h-[85vh] xs:(max-h-full) max-h-215 flex flex-col p-6"> <div class="flex h-9.5 flex-shrink-0 w-full items-center nc-expanded-form-header relative mb-4 justify-between"> <template v-if="!isMobileMode"> <div class="flex gap-3 w-100"> <div class="flex gap-2"> <NcButton v-if="props.showNextPrevIcons" :disabled="isFirstRow" type="secondary" class="nc-prev-arrow !w-10" @click="$emit('prev')" > <MdiChevronUp class="text-md" /> </NcButton> <NcButton v-if="props.showNextPrevIcons" :disabled="islastRow" type="secondary" class="nc-next-arrow !w-10" @click="onNext" > <MdiChevronDown class="text-md" /> </NcButton> </div> <div v-if="isLoading"> <a-skeleton-input class="!h-8 !sm:mr-14 !w-52 mt-1 !rounded-md !overflow-hidden" active size="small" /> </div> <div v-if="row.rowMeta?.new || props.newRecordHeader" class="flex items-center truncate font-bold text-gray-800 text-xl" > {{ props.newRecordHeader ?? $t('activity.newRecord') }} </div> <div v-else-if="displayValue && !row.rowMeta?.new" class="flex items-center font-bold text-gray-800 text-xl w-64"> <span class="truncate"> {{ displayValue }} </span> </div> </div> <div class="flex gap-2"> <NcButton v-if="!isNew" type="secondary" class="!xs:hidden text-gray-700" @click="!isNew ? copyRecordUrl() : () => {}" > <div v-e="['c:row-expand:copy-url']" data-testid="nc-expanded-form-copy-url" class="flex gap-2 items-center"> <component :is="iconMap.check" v-if="isRecordLinkCopied" class="cursor-pointer nc-duplicate-row" /> <component :is="iconMap.link" v-else class="cursor-pointer nc-duplicate-row" /> {{ isRecordLinkCopied ? $t('labels.copiedRecordURL') : $t('labels.copyRecordURL') }} </div> </NcButton> <NcDropdown v-if="!isNew" placement="bottomRight"> <NcButton type="secondary" class="nc-expand-form-more-actions w-10"> <GeneralIcon icon="threeDotVertical" class="text-md text-gray-700" /> </NcButton> <template #overlay> <NcMenu> <NcMenuItem v-if="!isNew" class="text-gray-700" @click="_loadRow()"> <div v-e="['c:row-expand:reload']" class="flex gap-2 items-center" data-testid="nc-expanded-form-reload"> <component :is="iconMap.reload" class="cursor-pointer" /> {{ $t('general.reload') }} </div> </NcMenuItem> <NcMenuItem v-if="!isNew && isMobileMode" class="text-gray-700" @click="!isNew ? copyRecordUrl() : () => {}"> <div v-e="['c:row-expand:copy-url']" data-testid="nc-expanded-form-copy-url" class="flex gap-2 items-center"> <component :is="iconMap.link" class="cursor-pointer nc-duplicate-row" /> {{ $t('labels.copyRecordURL') }} </div> </NcMenuItem> <NcMenuItem v-if="isUIAllowed('dataEdit') && !isNew" class="text-gray-700" @click="!isNew ? onDuplicateRow() : () => {}" > <div v-e="['c:row-expand:duplicate']" data-testid="nc-expanded-form-duplicate" class="flex gap-2 items-center" > <component :is="iconMap.copy" class="cursor-pointer nc-duplicate-row" /> <span class="-ml-0.25"> {{ $t('labels.duplicateRecord') }} </span> </div> </NcMenuItem> <NcDivider v-if="isUIAllowed('dataEdit') && !isNew" /> <NcMenuItem v-if="isUIAllowed('dataEdit') && !isNew" class="!text-red-500 !hover:bg-red-50" @click="!isNew && onDeleteRowClick()" > <div v-e="['c:row-expand:delete']" data-testid="nc-expanded-form-delete" class="flex gap-2 items-center"> <component :is="iconMap.delete" class="cursor-pointer nc-delete-row" /> <span class="-ml-0.25"> {{ $t('activity.deleteRecord') }} </span> </div> </NcMenuItem> </NcMenu> </template> </NcDropdown> <NcButton type="secondary" class="nc-expand-form-close-btn w-10" data-testid="nc-expanded-form-close" @click="onClose" > <GeneralIcon icon="close" class="text-md text-gray-700" /> </NcButton> </div> </template> <template v-else> <div class="flex flex-row w-full"> <NcButton v-if="props.showNextPrevIcons && !isFirstRow" v-e="['c:row-expand:prev']" type="secondary" class="nc-prev-arrow !w-10" @click="$emit('prev')" > <GeneralIcon icon="arrowLeft" class="text-lg text-gray-700" /> </NcButton> <div v-else class="min-w-10.5"></div> <div class="flex flex-grow justify-center items-center font-semibold text-lg"> <div>{{ meta.title }}</div> </div> <NcButton v-if="props.showNextPrevIcons && !islastRow" v-e="['c:row-expand:next']" type="secondary" class="nc-next-arrow !w-10" @click="onNext" > <GeneralIcon icon="arrowRight" class="text-lg text-gray-700" /> </NcButton> <div v-else class="min-w-10.5"></div> </div> </template> </div> <div ref="wrapper" class="flex flex-grow flex-row h-[calc(100%-4rem)] w-full gap-4"> <div class="flex xs:w-full flex-col border-1 rounded-xl overflow-hidden border-gray-200 xs:(border-0 rounded-none)" :class="{ 'w-full': !showRightSections, 'w-2/3': showRightSections, }" > <div ref="expandedFormScrollWrapper" class="flex flex-col flex-grow mt-2 h-full max-h-full nc-scrollbar-md pb-6 items-center w-full bg-white p-4 xs:p-0" > <div v-for="(col, i) of fields" v-show="isFormula(col) || !isVirtualCol(col) || !isNew || isLinksOrLTAR(col)" :key="col.title" class="nc-expanded-form-row mt-2 py-2 xs:w-full" :class="`nc-expand-col-${col.title}`" :col-id="col.id" :data-testid="`nc-expand-col-${col.title}`" > <div class="flex items-start flex-row sm:(gap-x-6) xs:(flex-col w-full) nc-expanded-cell min-h-10"> <div class="w-48 xs:(w-full) mt-0.25 !h-[35px]"> <LazySmartsheetHeaderVirtualCell v-if="isVirtualCol(col)" class="nc-expanded-cell-header h-full" :column="col" /> <LazySmartsheetHeaderCell v-else class="nc-expanded-cell-header" :column="col" /> </div> <template v-if="isLoading"> <div v-if="isMobileMode" class="!h-8.5 !xs:h-12 !xs:bg-white sm:mr-21 w-60 mt-0.75 !rounded-lg !overflow-hidden" ></div> <a-skeleton-input v-else class="!h-8.5 !xs:h-9.5 !xs:bg-white sm:mr-21 !w-60 mt-0.75 !rounded-lg !overflow-hidden" active size="small" /> </template> <template v-else> <SmartsheetDivDataCell v-if="col.title" :ref="i ? null : (el: any) => (cellWrapperEl = el)" class="bg-white w-80 xs:w-full px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative" :class="{ '!bg-gray-50 !px-0 !select-text': isReadOnlyVirtualCell(col), }" > <LazySmartsheetVirtualCell v-if="isVirtualCol(col)" v-model="_row.row[col.title]" :row="_row" :column="col" :class="{ 'px-1': isReadOnlyVirtualCell(col), }" :read-only="readOnly" /> <LazySmartsheetCell v-else v-model="_row.row[col.title]" :column="col" :edit-enabled="true" :active="true" :read-only="readOnly" @update:model-value="changedColumns.add(col.title)" /> </SmartsheetDivDataCell> </template> </div> </div> <div v-if="hiddenFields.length > 0" class="flex w-full sm:px-12 xs:(px-1 mt-2) items-center py-3"> <div class="flex-grow h-px mr-1 bg-gray-100"></div> <NcButton type="secondary" :size="isMobileMode ? 'medium' : 'small'" class="flex-shrink-1 !text-sm" @click="toggleHiddenFields" > {{ showHiddenFields ? `Hide ${hiddenFields.length} hidden` : `Show ${hiddenFields.length} hidden` }} {{ hiddenFields.length > 1 ? `fields` : `field` }} <MdiChevronDown class="ml-1" :class="showHiddenFields ? 'transform rotate-180' : ''" /> </NcButton> <div class="flex-grow h-px ml-1 bg-gray-100"></div> </div> <div v-if="hiddenFields.length > 0 && showHiddenFields" class="flex flex-col w-full mb-3 items-center"> <div v-for="(col, i) of hiddenFields" v-show="isFormula(col) || !isVirtualCol(col) || !isNew || isLinksOrLTAR(col)" :key="col.title" class="sm:(mt-2) py-2 xs:w-full" :class="`nc-expand-col-${col.title}`" :data-testid="`nc-expand-col-${col.title}`" > <div class="sm:gap-x-6 flex sm:flex-row xs:(flex-col) items-start min-h-10"> <div class="sm:w-48 xs:w-full scale-110 !h-[35px]"> <LazySmartsheetHeaderVirtualCell v-if="isVirtualCol(col)" :column="col" class="nc-expanded-cell-header" /> <LazySmartsheetHeaderCell v-else class="nc-expanded-cell-header" :column="col" /> </div> <template v-if="isLoading"> <div v-if="isMobileMode" class="!h-8.5 !xs:h-9.5 !xs:bg-white sm:mr-21 w-60 mt-0.75 !rounded-lg !overflow-hidden" ></div> <a-skeleton-input v-else class="!h-8.5 !xs:h-12 !xs:bg-white sm:mr-21 w-60 mt-0.75 !rounded-lg !overflow-hidden" active size="small" /> </template> <template v-else> <LazySmartsheetDivDataCell v-if="col.title" :ref="i ? null : (el: any) => (cellWrapperEl = el)" class="bg-white rounded-lg w-80 border-1 overflow-hidden border-gray-200 px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative" > <LazySmartsheetVirtualCell v-if="isVirtualCol(col)" v-model="_row.row[col.title]" :row="_row" :column="col" :read-only="readOnly" /> <LazySmartsheetCell v-else v-model="_row.row[col.title]" :column="col" :edit-enabled="true" :active="true" :read-only="readOnly" @update:model-value="changedColumns.add(col.title)" /> </LazySmartsheetDivDataCell> </template> </div> </div> </div> </div> <div v-if="isUIAllowed('dataEdit')" class="w-full h-16 border-t-1 border-gray-200 bg-white flex items-center justify-end p-3 xs:(p-0 mt-4 border-t-0 gap-x-4 justify-between)" > <NcDropdown v-if="!isNew && isMobileMode" placement="bottomRight"> <NcButton type="secondary" class="nc-expand-form-more-actions w-10"> <GeneralIcon icon="threeDotVertical" class="text-md text-gray-700" /> </NcButton> <template #overlay> <NcMenu> <NcMenuItem v-if="!isNew" class="text-gray-700" @click="_loadRow()"> <div v-e="['c:row-expand:reload']" class="flex gap-2 items-center" data-testid="nc-expanded-form-reload"> <component :is="iconMap.reload" class="cursor-pointer" /> {{ $t('general.reload') }} </div> </NcMenuItem> <NcDivider /> <NcMenuItem v-if="isUIAllowed('dataEdit') && !isNew" v-e="['c:row-expand:delete']" class="!text-red-500 !hover:bg-red-50" @click="!isNew && onDeleteRowClick()" > <div data-testid="nc-expanded-form-delete"> <component :is="iconMap.delete" class="cursor-pointer nc-delete-row" /> Delete record </div> </NcMenuItem> </NcMenu> </template> </NcDropdown> <div class="flex flex-row gap-x-3"> <NcButton v-if="isMobileMode" type="secondary" size="medium" data-testid="nc-expanded-form-save" class="nc-expand-form-save-btn !xs:(text-base)" @click="onClose" > <div class="px-1">Close</div> </NcButton> <NcButton v-e="['c:row-expand:save']" data-testid="nc-expanded-form-save" type="primary" size="medium" class="nc-expand-form-save-btn !xs:(text-base)" :disabled="changedColumns.size === 0 && !isUnsavedFormExist" @click="save" > <div class="xs:px-1">Save</div> </NcButton> </div> </div> </div> <div v-if="showRightSections" class="nc-comments-drawer border-1 relative border-gray-200 w-1/3 max-w-125 bg-gray-50 rounded-xl min-w-0 overflow-hidden h-full xs:hidden" :class="{ active: commentsDrawer && isUIAllowed('commentList') }" > <SmartsheetExpandedFormComments :loading="isLoading" /> </div> </div> </div> </NcModal> <GeneralDeleteModal v-model:visible="showDeleteRowModal" entity-name="Record" :on-delete="() => onConfirmDeleteRowClick()"> <template #entity-preview> <span> <div class="flex flex-row items-center py-2.25 px-2.5 bg-gray-50 rounded-lg text-gray-700 mb-4"> <div class="capitalize text-ellipsis overflow-hidden select-none w-full pl-1.75 break-keep whitespace-nowrap"> {{ displayValue }} </div> </div> </span> </template> </GeneralDeleteModal> <!-- Prevent unsaved change modal --> <NcModal v-model:visible="preventModalStatus" size="small"> <div class=""> <div class="flex flex-row items-center gap-x-2 text-base font-bold"> {{ $t('tooltip.saveChanges') }} </div> <div class="flex font-medium mt-2"> {{ $t('activity.doYouWantToSaveTheChanges') }} </div> <div class="flex flex-row justify-end gap-x-2 mt-5"> <NcButton type="secondary" @click="discardPreventModal">{{ $t('labels.discard') }}</NcButton> <NcButton key="submit" type="primary" label="Rename Table" loading-label="Renaming Table" @click="saveChanges"> {{ $t('tooltip.saveChanges') }} </NcButton> </div> </div> </NcModal> </template> <style lang="scss"> .nc-drawer-expanded-form { @apply xs:my-0; } .nc-expanded-cell { input { @apply xs:(h-12 text-base); } } .nc-expanded-cell-header { @apply w-full text-gray-500 xs:(text-gray-600 mb-2); } .nc-expanded-cell-header > :nth-child(2) { @apply !text-sm !xs:text-base; } .nc-expanded-cell-header > :first-child { @apply !text-xl; } .nc-drawer-expanded-form .nc-modal { @apply !p-0; } </style> <style lang="scss" scoped> :deep(.ant-select-selector) { @apply !xs:(h-full); } :deep(.ant-select-selection-item) { @apply !xs:(mt-1.75 ml-1); } .nc-data-cell:focus-within { @apply !border-1 !border-brand-500 !rounded-lg !shadow-none !ring-0; } </style>
packages/nc-gui/components/smartsheet/expanded-form/index.vue
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.9981666803359985, 0.08616288751363754, 0.00016679584223311394, 0.00017166725592687726, 0.2771674394607544 ]
{ "id": 3, "code_window": [ " (event: 'close'): void\n", "\n", " (event: 'open'): void\n", "}\n", "\n", "const { transition = true, teleportDisabled = false, inline = false, target, zIndex = 100, ...rest } = defineProps<Props>()\n", "\n", "const emits = defineEmits<Emits>()\n", "\n", "const vModel = useVModel(rest, 'modelValue', emits)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { transition, teleportDisabled, inline, target, zIndex, ...rest } = withDefaults(defineProps<Props>(), {\n", " transition: true,\n", " teleportDisabled: false,\n", " inline: false,\n", " zIndex: 100,\n", "})\n" ], "file_path": "packages/nc-gui/components/general/Overlay.vue", "type": "replace", "edit_start_line_idx": 24 }
import { Test } from '@nestjs/testing'; import { DataAliasNestedController } from './data-alias-nested.controller'; import type { TestingModule } from '@nestjs/testing'; describe('DataAliasNestedController', () => { let controller: DataAliasNestedController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [DataAliasNestedController], }).compile(); controller = module.get<DataAliasNestedController>( DataAliasNestedController, ); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
packages/nocodb/src/controllers/data-alias-nested.controller.spec.ts
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00017442021635361016, 0.00017370765272062272, 0.00017235382983926684, 0.0001743488828651607, 9.577333912602626e-7 ]
{ "id": 3, "code_window": [ " (event: 'close'): void\n", "\n", " (event: 'open'): void\n", "}\n", "\n", "const { transition = true, teleportDisabled = false, inline = false, target, zIndex = 100, ...rest } = defineProps<Props>()\n", "\n", "const emits = defineEmits<Emits>()\n", "\n", "const vModel = useVModel(rest, 'modelValue', emits)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { transition, teleportDisabled, inline, target, zIndex, ...rest } = withDefaults(defineProps<Props>(), {\n", " transition: true,\n", " teleportDisabled: false,\n", " inline: false,\n", " zIndex: 100,\n", "})\n" ], "file_path": "packages/nc-gui/components/general/Overlay.vue", "type": "replace", "edit_start_line_idx": 24 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M6 14H2V10" stroke="#374151" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M2 14L6.66667 9.33337" stroke="#374151" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10 2H14V6" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M13.9999 2L9.33325 6.66667" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> </svg>
packages/nc-gui/assets/nc-icons/maximize.svg
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.0001744671317283064, 0.0001744671317283064, 0.0001744671317283064, 0.0001744671317283064, 0 ]
{ "id": 4, "code_window": [ " css?: string\n", " iconClass?: string\n", " width?: string\n", "}\n", "\n", "const {\n", " url,\n", " socialMedias,\n", " title = 'NocoDB',\n", " summary,\n", " hashTags = '',\n", " css = '',\n", " iconClass = '',\n", " width = '45px',\n", "} = defineProps<Props>()\n", "\n", "const summaryArr = [\n", " 'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',\n", " 'Instantly generate #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb',\n", " 'Instant #serverless Rest & #GraphQL APIs on any Database #nocodb',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { url, socialMedias, title, summary, hashTags, css, iconClass, width } = withDefaults(defineProps<Props>(), {\n", " title: 'NocoDB',\n", " hashTags: '',\n", " css: '',\n", " iconClass: '',\n", " width: '45px',\n", "})\n" ], "file_path": "packages/nc-gui/components/general/Share.vue", "type": "replace", "edit_start_line_idx": 14 }
<script setup lang="ts"> import type { TableType } from 'nocodb-sdk' import type { UploadChangeParam, UploadFile } from 'ant-design-vue' import { Upload } from 'ant-design-vue' import { toRaw, unref } from '@vue/runtime-core' import type { ImportWorkerPayload, importFileList, streamImportFileList } from '#imports' import { BASE_FALLBACK_URL, CSVTemplateAdapter, ExcelTemplateAdapter, ExcelUrlTemplateAdapter, Form, ImportSource, ImportType, ImportWorkerOperations, ImportWorkerResponse, JSONTemplateAdapter, JSONUrlTemplateAdapter, computed, extractSdkResponseErrorMsg, fieldRequiredValidator, iconMap, importCsvUrlValidator, importExcelUrlValidator, importUrlValidator, initWorker, message, reactive, ref, storeToRefs, useBase, useGlobal, useI18n, useNuxtApp, useVModel, } from '#imports' // import worker script according to the doc of Vite import importWorkerUrl from '~/workers/importWorker?worker&url' interface Props { modelValue: boolean importType: 'csv' | 'json' | 'excel' sourceId: string importDataOnly?: boolean } const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const { $api } = useNuxtApp() const { appInfo } = useGlobal() const config = useRuntimeConfig() const isWorkerSupport = typeof Worker !== 'undefined' let importWorker: Worker | null const { t } = useI18n() const progressMsg = ref('Parsing Data ...') const { tables } = storeToRefs(useBase()) const activeKey = ref('uploadTab') const jsonEditorRef = ref() const templateEditorRef = ref() const preImportLoading = ref(false) const importLoading = ref(false) const templateData = ref() const importData = ref() const importColumns = ref([]) const templateEditorModal = ref(false) const isParsingData = ref(false) const useForm = Form.useForm const defaultImportState = { fileList: [] as importFileList | streamImportFileList, url: '', jsonEditor: {}, parserConfig: { maxRowsToParse: 500, normalizeNested: true, autoSelectFieldTypes: true, firstRowAsHeaders: true, shouldImportData: true, }, } const importState = reactive(defaultImportState) const { token } = useGlobal() const isImportTypeJson = computed(() => importType === 'json') const isImportTypeCsv = computed(() => importType === 'csv') const IsImportTypeExcel = computed(() => importType === 'excel') const validators = computed(() => ({ url: [fieldRequiredValidator(), importUrlValidator, isImportTypeCsv.value ? importCsvUrlValidator : importExcelUrlValidator], maxRowsToParse: [fieldRequiredValidator()], })) const { validate, validateInfos } = useForm(importState, validators) const importMeta = computed(() => { if (IsImportTypeExcel.value) { return { header: `${t('title.quickImportExcel')}`, uploadHint: t('msg.info.excelSupport'), urlInputLabel: t('msg.info.excelURL'), loadUrlDirective: ['c:quick-import:excel:load-url'], acceptTypes: '.xls, .xlsx, .xlsm, .ods, .ots', } } else if (isImportTypeCsv.value) { return { header: `${t('title.quickImportCSV')}`, uploadHint: '', urlInputLabel: t('msg.info.csvURL'), loadUrlDirective: ['c:quick-import:csv:load-url'], acceptTypes: '.csv', } } else if (isImportTypeJson.value) { return { header: `${t('title.quickImportJSON')}`, uploadHint: '', acceptTypes: '.json', } } return {} }) const dialogShow = useVModel(rest, 'modelValue', emit) // watch dialogShow to init or terminate worker if (isWorkerSupport) { watch( dialogShow, async (val) => { if (val) { importWorker = await initWorker(importWorkerUrl) } else { importWorker?.terminate() } }, { immediate: true }, ) } const disablePreImportButton = computed(() => { if (activeKey.value === 'uploadTab') { return !(importState.fileList.length > 0) } else if (activeKey.value === 'urlTab') { if (!validateInfos.url.validateStatus) return true return validateInfos.url.validateStatus === 'error' } else if (activeKey.value === 'jsonEditorTab') { return !jsonEditorRef.value?.isValid } }) const isError = ref(false) const disableImportButton = computed(() => !templateEditorRef.value?.isValid || isError.value) const disableFormatJsonButton = computed(() => !jsonEditorRef.value?.isValid) const modalWidth = computed(() => { if (importType === 'excel' && templateEditorModal.value) { return 'max(90vw, 600px)' } return 'max(60vw, 600px)' }) let templateGenerator: CSVTemplateAdapter | JSONTemplateAdapter | ExcelTemplateAdapter | null async function handlePreImport() { preImportLoading.value = true isParsingData.value = true if (activeKey.value === 'uploadTab') { if (isImportTypeCsv.value || (isWorkerSupport && importWorker)) { await parseAndExtractData(importState.fileList as streamImportFileList) } else { await parseAndExtractData((importState.fileList as importFileList)[0].data) } } else if (activeKey.value === 'urlTab') { try { await validate() await parseAndExtractData(importState.url) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } } else if (activeKey.value === 'jsonEditorTab') { await parseAndExtractData(JSON.stringify(importState.jsonEditor)) } } async function handleImport() { try { if (!templateGenerator && !importWorker) { message.error(t('msg.error.templateGeneratorNotFound')) return } importLoading.value = true await templateEditorRef.value.importTemplate() } catch (e: any) { return message.error(await extractSdkResponseErrorMsg(e)) } finally { importLoading.value = false templateEditorModal.value = false Object.assign(importState, defaultImportState) } dialogShow.value = false } function rejectDrop(fileList: UploadFile[]) { fileList.map((file) => { return message.error(`${t('msg.error.fileUploadFailed')} ${file.name}`) }) } function handleChange(info: UploadChangeParam) { const status = info.file.status if (status && status !== 'uploading' && status !== 'removed') { if (isImportTypeCsv.value || (isWorkerSupport && importWorker)) { if (!importState.fileList.find((f) => f.uid === info.file.uid)) { ;(importState.fileList as streamImportFileList).push({ ...info.file, status: 'done', }) } } else { const reader = new FileReader() reader.onload = (e: ProgressEvent<FileReader>) => { const target = (importState.fileList as importFileList).find((f) => f.uid === info.file.uid) if (e.target && e.target.result) { /** if the file was pushed into the list by `<a-upload-dragger>` we just add the data to the file */ if (target) { target.data = e.target.result } else if (!target) { /** if the file was added programmatically and not with d&d, we create file infos and push it into the list */ importState.fileList.push({ ...info.file, status: 'done', data: e.target.result, }) } } } reader.readAsArrayBuffer(info.file.originFileObj!) } } if (status === 'done') { message.success(`Uploaded file ${info.file.name} successfully`) } else if (status === 'error') { message.error(`${t('msg.error.fileUploadFailed')} ${info.file.name}`) } } function formatJson() { jsonEditorRef.value?.format() } function populateUniqueTableName(tn: string) { let c = 1 while ( tables.value.some((t: TableType) => { const s = t.table_name.split('___') let target = t.table_name if (s.length > 1) target = s[1] return target === `${tn}` }) ) { tn = `${tn}_${c++}` } return tn } function getAdapter(val: any) { if (isImportTypeCsv.value) { switch (activeKey.value) { case 'uploadTab': return new CSVTemplateAdapter(val, { ...importState.parserConfig, importFromURL: false, }) case 'urlTab': return new CSVTemplateAdapter(val, { ...importState.parserConfig, importFromURL: true, }) } } else if (IsImportTypeExcel.value) { switch (activeKey.value) { case 'uploadTab': return new ExcelTemplateAdapter(val, importState.parserConfig) case 'urlTab': return new ExcelUrlTemplateAdapter(val, importState.parserConfig, $api) } } else if (isImportTypeJson.value) { switch (activeKey.value) { case 'uploadTab': return new JSONTemplateAdapter(val, importState.parserConfig) case 'urlTab': return new JSONUrlTemplateAdapter(val, importState.parserConfig, $api) case 'jsonEditorTab': return new JSONTemplateAdapter(val, importState.parserConfig) } } return null } defineExpose({ handleChange, }) /** a workaround to override default antd upload api call */ const customReqCbk = (customReqArgs: { file: any; onSuccess: () => void }) => { importState.fileList.forEach((f) => { if (f.uid === customReqArgs.file.uid) { f.status = 'done' handleChange({ file: f, fileList: importState.fileList }) } }) customReqArgs.onSuccess() } /** check if the file size exceeds the limit */ const beforeUpload = (file: UploadFile) => { const exceedLimit = file.size! / 1024 / 1024 > 5 if (exceedLimit) { message.error(`File ${file.name} is too big. The accepted file size is less than 5MB.`) } return !exceedLimit || Upload.LIST_IGNORE } // UploadFile[] for csv import (streaming) // ArrayBuffer for excel import function extractImportWorkerPayload(value: UploadFile[] | ArrayBuffer | string) { let payload: ImportWorkerPayload if (isImportTypeCsv.value) { switch (activeKey.value) { case 'uploadTab': payload = { config: { ...importState.parserConfig, importFromURL: false, }, value, importType: ImportType.CSV, importSource: ImportSource.FILE, } break case 'urlTab': payload = { config: { ...importState.parserConfig, importFromURL: true, }, value, importType: ImportType.CSV, importSource: ImportSource.FILE, } break } } else if (IsImportTypeExcel.value) { switch (activeKey.value) { case 'uploadTab': payload = { config: toRaw(importState.parserConfig), value, importType: ImportType.EXCEL, importSource: ImportSource.FILE, } break case 'urlTab': payload = { config: toRaw(importState.parserConfig), value, importType: ImportType.EXCEL, importSource: ImportSource.URL, } break } } else if (isImportTypeJson.value) { switch (activeKey.value) { case 'uploadTab': payload = { config: toRaw(importState.parserConfig), value, importType: ImportType.JSON, importSource: ImportSource.FILE, } break case 'urlTab': payload = { config: toRaw(importState.parserConfig), value, importType: ImportType.JSON, importSource: ImportSource.URL, } break case 'jsonEditorTab': payload = { config: toRaw(importState.parserConfig), value, importType: ImportType.JSON, importSource: ImportSource.STRING, } break } } return payload } // string for json import async function parseAndExtractData(val: UploadFile[] | ArrayBuffer | string) { templateData.value = null importData.value = null importColumns.value = [] try { // if the browser supports web worker, use it to parse the file and process the data if (isWorkerSupport && importWorker) { importWorker.postMessage([ ImportWorkerOperations.INIT_SDK, { baseURL: config.public.ncBackendUrl || appInfo.value.ncSiteUrl || BASE_FALLBACK_URL, token: token.value, }, ]) let value = toRaw(val) // if array, iterate and unwrap proxy if (Array.isArray(value)) value = value.map((v) => toRaw(v)) const payload = extractImportWorkerPayload(value) importWorker.postMessage([ ImportWorkerOperations.SET_TABLES, unref(tables).map((t) => ({ table_name: t.table_name, title: t.title, })), ]) importWorker.postMessage([ ImportWorkerOperations.SET_CONFIG, { importDataOnly, importColumns: !!importColumns.value, importData: !!importData.value, }, ]) const response: { templateData: any importColumns: any importData: any } = await new Promise((resolve, reject) => { const handler = (e: MessageEvent) => { const [type, payload] = e.data switch (type) { case ImportWorkerResponse.PROCESSED_DATA: resolve(payload) importWorker?.removeEventListener('message', handler, false) break case ImportWorkerResponse.PROGRESS: progressMsg.value = payload break case ImportWorkerResponse.ERROR: reject(payload) importWorker?.removeEventListener('message', handler, false) break } } importWorker?.addEventListener('message', handler, false) importWorker?.postMessage([ImportWorkerOperations.PROCESS, payload]) }) templateData.value = response.templateData importColumns.value = response.importColumns importData.value = response.importData } // otherwise, use the main thread to parse the file and process the data else { templateGenerator = getAdapter(val) if (!templateGenerator) { message.error(t('msg.error.templateGeneratorNotFound')) return } await templateGenerator.init() await templateGenerator.parse() templateData.value = templateGenerator!.getTemplate() if (importDataOnly) importColumns.value = templateGenerator!.getColumns() else { // ensure the target table name not exist in current table list templateData.value.tables = templateData.value.tables.map((table: Record<string, any>) => ({ ...table, table_name: populateUniqueTableName(table.table_name), })) } importData.value = templateGenerator!.getData() } templateEditorModal.value = true } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } finally { isParsingData.value = false preImportLoading.value = false } } const onError = () => { isError.value = true } const onChange = () => { isError.value = false } </script> <template> <a-modal v-model:visible="dialogShow" :class="{ active: dialogShow }" :width="modalWidth" wrap-class-name="nc-modal-quick-import" @keydown.esc="dialogShow = false" > <a-spin :spinning="isParsingData" :tip="progressMsg" size="large"> <div class="px-5"> <div class="prose-xl font-weight-bold my-5">{{ importMeta.header }}</div> <div class="mt-5"> <LazyTemplateEditor v-if="templateEditorModal" ref="templateEditorRef" :base-template="templateData" :import-data="importData" :import-columns="importColumns" :import-data-only="importDataOnly" :quick-import-type="importType" :max-rows-to-parse="importState.parserConfig.maxRowsToParse" :source-id="sourceId" :import-worker="importWorker" class="nc-quick-import-template-editor" @import="handleImport" @error="onError" @change="onChange" /> <a-tabs v-else v-model:activeKey="activeKey" hide-add type="editable-card" tab-position="top"> <a-tab-pane key="uploadTab" :closable="false"> <template #tab> <!-- Upload --> <div class="flex items-center gap-2"> <component :is="iconMap.fileUpload" /> {{ $t('general.upload') }} </div> </template> <div class="py-6"> <a-upload-dragger v-model:fileList="importState.fileList" name="file" class="nc-input-import !scrollbar-thin-dull" list-type="picture" :accept="importMeta.acceptTypes" :max-count="isImportTypeCsv ? 5 : 1" :multiple="true" :custom-request="customReqCbk" :before-upload="beforeUpload" @change="handleChange" @reject="rejectDrop" > <component :is="iconMap.plusCircle" size="large" /> <!-- Click or drag file to this area to upload --> <p class="ant-upload-text">{{ $t('msg.info.import.clickOrDrag') }}</p> <p class="ant-upload-hint"> {{ importMeta.uploadHint }} </p> </a-upload-dragger> </div> </a-tab-pane> <a-tab-pane v-if="isImportTypeJson" key="jsonEditorTab" :closable="false"> <template #tab> <span class="flex items-center gap-2"> <component :is="iconMap.json" /> {{ $t('title.jsonEditor') }} </span> </template> <div class="pb-3 pt-3"> <LazyMonacoEditor ref="jsonEditorRef" v-model="importState.jsonEditor" class="min-h-60 max-h-80" /> </div> </a-tab-pane> <a-tab-pane v-else key="urlTab" :closable="false"> <template #tab> <span class="flex items-center gap-2"> <component :is="iconMap.link" /> {{ $t('datatype.URL') }} </span> </template> <div class="pr-10 pt-5"> <a-form :model="importState" name="quick-import-url-form" layout="vertical" class="mb-0"> <a-form-item :label="importMeta.urlInputLabel" v-bind="validateInfos.url"> <a-input v-model:value="importState.url" size="large" /> </a-form-item> </a-form> </div> </a-tab-pane> </a-tabs> </div> <div v-if="!templateEditorModal"> <a-divider /> <div class="mb-4"> <!-- Advanced Settings --> <span class="prose-lg">{{ $t('title.advancedSettings') }}</span> <a-form-item class="!my-2" :label="t('msg.info.footMsg')" v-bind="validateInfos.maxRowsToParse"> <a-input-number v-model:value="importState.parserConfig.maxRowsToParse" :min="1" :max="50000" /> </a-form-item> <a-form-item v-if="!importDataOnly" class="!my-2"> <a-checkbox v-model:checked="importState.parserConfig.autoSelectFieldTypes"> <span class="caption">{{ $t('labels.autoSelectFieldTypes') }}</span> </a-checkbox> </a-form-item> <a-form-item v-if="isImportTypeCsv || IsImportTypeExcel" class="!my-2"> <a-checkbox v-model:checked="importState.parserConfig.firstRowAsHeaders"> <span class="caption">{{ $t('labels.firstRowAsHeaders') }}</span> </a-checkbox> </a-form-item> <!-- Flatten nested --> <a-form-item v-if="isImportTypeJson" class="!my-2"> <a-checkbox v-model:checked="importState.parserConfig.normalizeNested"> <span class="caption">{{ $t('labels.flattenNested') }}</span> </a-checkbox> </a-form-item> <!-- Import Data --> <a-form-item v-if="!importDataOnly" class="!my-2"> <a-checkbox v-model:checked="importState.parserConfig.shouldImportData">{{ $t('labels.importData') }} </a-checkbox> </a-form-item> </div> </div> </div> </a-spin> <template #footer> <a-button v-if="templateEditorModal" key="back" class="!rounded-md" @click="templateEditorModal = false" >{{ $t('general.back') }} </a-button> <a-button v-else key="cancel" class="!rounded-md" @click="dialogShow = false">{{ $t('general.cancel') }} </a-button> <a-button v-if="activeKey === 'jsonEditorTab' && !templateEditorModal" key="format" class="!rounded-md" :disabled="disableFormatJsonButton" @click="formatJson" > {{ $t('labels.formatJson') }} </a-button> <a-button v-if="!templateEditorModal" key="pre-import" type="primary" class="nc-btn-import !rounded-md" :loading="preImportLoading" :disabled="disablePreImportButton" @click="handlePreImport" > {{ $t('activity.import') }} </a-button> <a-button v-else key="import" type="primary" class="!rounded-md" :loading="importLoading" :disabled="disableImportButton" @click="handleImport" > {{ $t('activity.import') }} </a-button> </template> </a-modal> </template>
packages/nc-gui/components/dlg/QuickImport.vue
1
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.0025702824350446463, 0.00020589135237969458, 0.0001635311054997146, 0.00017342602950520813, 0.0002786579425446689 ]
{ "id": 4, "code_window": [ " css?: string\n", " iconClass?: string\n", " width?: string\n", "}\n", "\n", "const {\n", " url,\n", " socialMedias,\n", " title = 'NocoDB',\n", " summary,\n", " hashTags = '',\n", " css = '',\n", " iconClass = '',\n", " width = '45px',\n", "} = defineProps<Props>()\n", "\n", "const summaryArr = [\n", " 'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',\n", " 'Instantly generate #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb',\n", " 'Instant #serverless Rest & #GraphQL APIs on any Database #nocodb',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { url, socialMedias, title, summary, hashTags, css, iconClass, width } = withDefaults(defineProps<Props>(), {\n", " title: 'NocoDB',\n", " hashTags: '',\n", " css: '',\n", " iconClass: '',\n", " width: '45px',\n", "})\n" ], "file_path": "packages/nc-gui/components/general/Share.vue", "type": "replace", "edit_start_line_idx": 14 }
<script lang="ts" setup> import OnetoOneIcon from '~icons/nc-icons/onetoone' import InfoIcon from '~icons/nc-icons/info' import FileIcon from '~icons/nc-icons/file' import { iconMap } from '#imports' const { relation, relatedTableTitle, displayValue, header, tableTitle } = defineProps<{ relation: string header?: string | null tableTitle: string relatedTableTitle: string displayValue?: string }>() const { isMobileMode } = useGlobal() const { t } = useI18n() const relationMeta = computed(() => { if (relation === 'hm') { return { title: t('msg.hm.title'), icon: iconMap.hm, tooltip_desc: t('msg.hm.tooltip_desc'), tooltip_desc2: t('msg.hm.tooltip_desc2'), } } else if (relation === 'mm') { return { title: t('msg.mm.title'), icon: iconMap.mm, tooltip_desc: t('msg.mm.tooltip_desc'), tooltip_desc2: t('msg.mm.tooltip_desc2'), } } else if (relation === 'bt') { return { title: t('msg.bt.title'), icon: iconMap.bt, tooltip_desc: t('msg.bt.tooltip_desc'), tooltip_desc2: t('msg.bt.tooltip_desc2'), } } else { return { title: t('msg.oo.title'), icon: OnetoOneIcon, tooltip_desc: t('msg.oo.tooltip_desc'), tooltip_desc2: t('msg.oo.tooltip_desc2'), } } }) </script> <template> <div class="flex sm:justify-between relative pb-2 items-center"> <div v-if="!isMobileMode" class="flex text-base font-bold justify-start items-center min-w-36"> {{ header ?? '' }} </div> <div class="flex flex-row sm:w-[calc(100%-16rem)] xs:w-full items-center justify-center gap-2 xs:(h-full)"> <div class="flex sm:justify-end w-[calc(50%-1.5rem)] xs:(w-[calc(50%-1.5rem)] h-full)"> <div class="flex max-w-full xs:w-full flex-shrink-0 xs:(h-full) rounded-md gap-1 text-gray-700 items-center bg-gray-100 px-2 py-1" > <FileIcon class="w-4 h-4 min-w-4" /> <span class="truncate"> {{ displayValue }} </span> </div> </div> <NcTooltip class="flex-shrink-0"> <template #title> {{ relationMeta.title }} </template> <component :is="relationMeta.icon" class="w-7 h-7 p-1 rounded-md" :class="{ '!bg-orange-500': relation === 'hm', '!bg-pink-500': relation === 'mm', '!bg-blue-500': relation === 'bt', }" /> </NcTooltip> <div class="flex justify-start xs:w-[calc(50%-1.5rem)] w-[calc(50%-1.5rem)] xs:justify-start"> <div class="flex rounded-md max-w-full flex-shrink-0 gap-1 items-center px-2 py-1 xs:w-full overflow-hidden" :class="{ '!bg-orange-50 !text-orange-500': relation === 'hm', '!bg-pink-50 !text-pink-500': relation === 'mm', '!bg-blue-50 !text-blue-500': relation === 'bt', }" > <MdiFileDocumentMultipleOutline class="w-4 h-4 min-w-4" :class="{ '!text-orange-500': relation === 'hm', '!text-pink-500': relation === 'mm', '!text-blue-500': relation === 'bt', }" /> <span class="truncate"> {{ relatedTableTitle }} Records </span> </div> </div> </div> <div v-if="!isMobileMode" class="flex flex-row justify-end w-36"> <NcTooltip class="z-10" placement="bottom"> <template #title> <div class="p-1"> <h1 class="text-white font-bold">{{ relationMeta.title }}</h1> <div class="text-white"> {{ relationMeta.tooltip_desc }} <span class="bg-gray-700 px-2 rounded-md"> {{ tableTitle }} </span> {{ relationMeta.tooltip_desc2 }} <span class="bg-gray-700 px-2 rounded-md"> {{ relatedTableTitle }} </span> </div> </div> </template> <InfoIcon class="w-4 h-4" /> </NcTooltip> </div> </div> </template>
packages/nc-gui/components/virtual-cell/components/Header.vue
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00017552469216752797, 0.00017157243564724922, 0.00016568167484365404, 0.00017235135601367801, 0.0000028693455078609986 ]
{ "id": 4, "code_window": [ " css?: string\n", " iconClass?: string\n", " width?: string\n", "}\n", "\n", "const {\n", " url,\n", " socialMedias,\n", " title = 'NocoDB',\n", " summary,\n", " hashTags = '',\n", " css = '',\n", " iconClass = '',\n", " width = '45px',\n", "} = defineProps<Props>()\n", "\n", "const summaryArr = [\n", " 'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',\n", " 'Instantly generate #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb',\n", " 'Instant #serverless Rest & #GraphQL APIs on any Database #nocodb',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { url, socialMedias, title, summary, hashTags, css, iconClass, width } = withDefaults(defineProps<Props>(), {\n", " title: 'NocoDB',\n", " hashTags: '',\n", " css: '',\n", " iconClass: '',\n", " width: '45px',\n", "})\n" ], "file_path": "packages/nc-gui/components/general/Share.vue", "type": "replace", "edit_start_line_idx": 14 }
<script setup lang="ts"> import { useColumnCreateStoreOrThrow, useVModel } from '#imports' const props = defineProps<{ value: any }>() const emit = defineEmits(['update:value']) const { t } = useI18n() const vModel = useVModel(props, 'value', emit) const { validateInfos, setAdditionalValidations } = useColumnCreateStoreOrThrow() setAdditionalValidations({ 'meta.singular': [ { validator: (_, value: string) => { return new Promise((resolve, reject) => { if (value?.length > 59) { return reject(t('msg.length59Required')) } resolve(true) }) }, }, ], 'meta.plural': [ { validator: (_, value: string) => { return new Promise((resolve, reject) => { if (value?.length > 59) { return reject(t('msg.length59Required')) } resolve(true) }) }, }, ], }) // set default value vModel.value.meta = { singular: '', plural: '', ...vModel.value.meta, } </script> <template> <a-row class="my-2" gutter="8"> <a-col :span="12"> <a-form-item v-bind="validateInfos['meta.singular']" :label="$t('labels.singularLabel')"> <a-input v-model:value="vModel.meta.singular" :placeholder="$t('general.link')" class="!w-full nc-link-singular" /> </a-form-item> </a-col> <a-col :span="12"> <a-form-item v-bind="validateInfos['meta.plural']" :label="$t('labels.pluralLabel')"> <a-input v-model:value="vModel.meta.plural" :placeholder="$t('general.links')" class="!w-full nc-link-plural" /> </a-form-item> </a-col> </a-row> </template>
packages/nc-gui/components/smartsheet/column/LinkOptions.vue
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.0021282131783664227, 0.00045225484063848853, 0.00016913989384192973, 0.00017278478480875492, 0.0006842102156952024 ]
{ "id": 4, "code_window": [ " css?: string\n", " iconClass?: string\n", " width?: string\n", "}\n", "\n", "const {\n", " url,\n", " socialMedias,\n", " title = 'NocoDB',\n", " summary,\n", " hashTags = '',\n", " css = '',\n", " iconClass = '',\n", " width = '45px',\n", "} = defineProps<Props>()\n", "\n", "const summaryArr = [\n", " 'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',\n", " 'Instantly generate #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb',\n", " 'Instant #serverless Rest & #GraphQL APIs on any Database #nocodb',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { url, socialMedias, title, summary, hashTags, css, iconClass, width } = withDefaults(defineProps<Props>(), {\n", " title: 'NocoDB',\n", " hashTags: '',\n", " css: '',\n", " iconClass: '',\n", " width: '45px',\n", "})\n" ], "file_path": "packages/nc-gui/components/general/Share.vue", "type": "replace", "edit_start_line_idx": 14 }
<script lang="ts" setup> interface Props { modelValue: boolean } const props = defineProps<Props>() const emits = defineEmits(['update:modelValue']) const { activeTable } = storeToRefs(useTablesStore()) const vModel = useVModel(props, 'modelValue', emits) </script> <template> <a-modal v-model:visible="vModel" :class="{ active: vModel }" size="small" :footer="null" width="max(900px,60vw)" :closable="false" wrap-class-name="erd-single-table-modal" transition-name="fade" :destroy-on-close="true" > <div class="flex justify-between w-full items-start pb-4 border-b-1 border-gray-50 mb-4"> <div class="select-none text-gray-900 font-medium text-lg"> {{ `ERD for "${activeTable?.title}"` }} </div> </div> <div class="w-full h-70vh"> <LazyErdView :table="activeTable" :source-id="activeTable?.source_id" /> </div> </a-modal> </template> <style> .erd-single-table-modal { .ant-modal { @apply !top-[50px]; } .ant-modal-body { @apply !p-0; } } </style>
packages/nc-gui/components/smartsheet/toolbar/Erd.vue
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.0020317912567406893, 0.0005432170582935214, 0.000169604696566239, 0.00017224031034857035, 0.0007442882633768022 ]
{ "id": 5, "code_window": [ "interface Props {\n", " nav?: boolean\n", "}\n", "\n", "const { nav = false } = defineProps<Props>()\n", "</script>\n", "\n", "<template>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const { nav } = withDefaults(defineProps<Props>(), { nav: false })\n" ], "file_path": "packages/nc-gui/components/general/Sponsors.vue", "type": "replace", "edit_start_line_idx": 5 }
<script setup lang="ts"> import type { VNodeRef } from '@vue/runtime-core' import { ColumnInj, EditColumnInj, EditModeInj, IsExpandedFormOpenInj, IsFormInj, computed, convertDurationToSeconds, convertMS2Duration, durationOptions, inject, parseProp, ref, } from '#imports' interface Props { modelValue: number | string | null | undefined showValidationError?: boolean } const { modelValue, showValidationError = true } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const { t } = useI18n() const { showNull } = useGlobal() const column = inject(ColumnInj) const editEnabled = inject(EditModeInj) const showWarningMessage = ref(false) const durationInMS = ref(0) const isEdited = ref(false) const isEditColumn = inject(EditColumnInj, ref(false)) const durationType = computed(() => parseProp(column?.value?.meta)?.duration || 0) const durationPlaceholder = computed(() => isEditColumn.value ? `(${t('labels.optional')})` : durationOptions[durationType.value].title, ) const localState = computed({ get: () => convertMS2Duration(modelValue, durationType.value), set: (val) => { isEdited.value = true const res = convertDurationToSeconds(val, durationType.value) if (res._isValid) { durationInMS.value = res._sec } }, }) const checkDurationFormat = (evt: KeyboardEvent) => { evt = evt || window.event const charCode = evt.which ? evt.which : evt.keyCode // ref: http://www.columbia.edu/kermit/ascii.html const PRINTABLE_CTL_RANGE = charCode > 31 const NON_DIGIT = charCode < 48 || charCode > 57 const NON_COLON = charCode !== 58 const NON_PERIOD = charCode !== 46 if (PRINTABLE_CTL_RANGE && NON_DIGIT && NON_COLON && NON_PERIOD) { showWarningMessage.value = true evt.preventDefault() } else { showWarningMessage.value = false // only allow digits, '.' and ':' (without quotes) return true } } const submitDuration = () => { if (isEdited.value) { emit('update:modelValue', durationInMS.value) } isEdited.value = false } const isExpandedFormOpen = inject(IsExpandedFormOpenInj, ref(false))! const isForm = inject(IsFormInj)! const focus: VNodeRef = (el) => !isExpandedFormOpen.value && !isEditColumn.value && !isForm.value && (el as HTMLInputElement)?.focus() </script> <template> <div class="duration-cell-wrapper"> <input v-if="editEnabled" :ref="focus" v-model="localState" class="w-full !border-none !outline-none py-1" :class="isExpandedFormOpen ? 'px-2' : 'px-0'" :placeholder="durationPlaceholder" @blur="submitDuration" @keypress="checkDurationFormat($event)" @keydown.enter="submitDuration" @keydown.down.stop @keydown.left.stop @keydown.right.stop @keydown.up.stop @keydown.delete.stop @selectstart.capture.stop @mousedown.stop /> <span v-else-if="modelValue === null && showNull" class="nc-null capitalize">{{ $t('general.null') }}</span> <span v-else> {{ localState }}</span> <div v-if="showWarningMessage && showValidationError" class="duration-warning"> {{ $t('msg.plsEnterANumber') }} </div> </div> </template> <style scoped> .duration-warning { @apply text-left mt-[10px] text-[#e65100]; } </style> <!-- -->
packages/nc-gui/components/cell/Duration.vue
1
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.9925820827484131, 0.07208884507417679, 0.0001657515240367502, 0.000173829379491508, 0.2553248405456543 ]
{ "id": 5, "code_window": [ "interface Props {\n", " nav?: boolean\n", "}\n", "\n", "const { nav = false } = defineProps<Props>()\n", "</script>\n", "\n", "<template>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const { nav } = withDefaults(defineProps<Props>(), { nav: false })\n" ], "file_path": "packages/nc-gui/components/general/Sponsors.vue", "type": "replace", "edit_start_line_idx": 5 }
name: "Publish : Docs search index (Typesense)" on: # Triggered manually workflow_dispatch: jobs: doc-indexer: runs-on: ubuntu-latest steps: - name: Checkout Repository uses: actions/checkout@v3 # You MUST checkout your repository first! - name: Run DocSearch Scraper uses: celsiusnarhwal/typesense-scraper@v2 with: # The secret containing your Typesense API key. Required. api-key: ${{ secrets.TYPESENSE_API_KEY }} # The hostname or IP address of your Typesense server. Required. host: ${{ secrets.TYPESENSE_HOST }} # The port on which your Typesense server is listening. Optional. Default: 8108. port: 443 # The protocol to use when connecting to your Typesense server. Optional. Default: http. protocol: https # The path to your DocSearch config file. Optional. Default: docsearch.config.json. config: ./packages/noco-docs/typesense-scrape-config.json
.github/workflows/publish-docs-index-typesense.yml
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00017314877186436206, 0.0001723559689708054, 0.00017164992459584028, 0.00017226921045221388, 6.149693945189938e-7 ]
{ "id": 5, "code_window": [ "interface Props {\n", " nav?: boolean\n", "}\n", "\n", "const { nav = false } = defineProps<Props>()\n", "</script>\n", "\n", "<template>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const { nav } = withDefaults(defineProps<Props>(), { nav: false })\n" ], "file_path": "packages/nc-gui/components/general/Sponsors.vue", "type": "replace", "edit_start_line_idx": 5 }
<svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path fill="currentColor" d="M298.001-610.001h363.998v-51.998H298.001v51.998Zm0 312h267.998v-51.998H298.001v51.998Zm0-156h363.998v-51.998H298.001v51.998Zm-69.692 290q-27.008 0-45.658-18.65-18.65-18.65-18.65-45.658v-503.382q0-27.008 18.65-45.658 18.65-18.65 45.658-18.65h503.382q27.008 0 45.658 18.65 18.65 18.65 18.65 45.658v503.382q0 27.008-18.65 45.658-18.65 18.65-45.658 18.65H228.309Zm0-51.999h503.382q4.616 0 8.463-3.846 3.846-3.847 3.846-8.463v-503.382q0-4.616-3.846-8.463-3.847-3.846-8.463-3.846H228.309q-4.616 0-8.463 3.846-3.846 3.847-3.846 8.463v503.382q0 4.616 3.846 8.463 3.847 3.846 8.463 3.846ZM216-744v528-528Z"/></svg>
packages/nc-gui/assets/nc-icons/article.svg
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00016444193897768855, 0.00016444193897768855, 0.00016444193897768855, 0.00016444193897768855, 0 ]
{ "id": 5, "code_window": [ "interface Props {\n", " nav?: boolean\n", "}\n", "\n", "const { nav = false } = defineProps<Props>()\n", "</script>\n", "\n", "<template>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const { nav } = withDefaults(defineProps<Props>(), { nav: false })\n" ], "file_path": "packages/nc-gui/components/general/Sponsors.vue", "type": "replace", "edit_start_line_idx": 5 }
import { computed, ref } from '#imports' interface UseLoadingIndicatorProps { duration?: number throttle?: number } export function useLoadingIndicator({ duration = 2000, throttle = 200 }: UseLoadingIndicatorProps) { const progress = ref(0) const isLoading = ref(false) const step = computed(() => 10000 / duration) let _timer: any = null let _throttle: any = null function start() { clear() progress.value = 0 isLoading.value = true if (throttle) { if (process.client) { _throttle = setTimeout(_startTimer, throttle) } } else { _startTimer() } } function finish() { progress.value = 100 _hide() } function clear() { clearInterval(_timer) clearTimeout(_throttle) _timer = null _throttle = null } function _increase(num: number) { progress.value = Math.min(100, progress.value + num) } function _hide() { clear() if (process.client) { setTimeout(() => { isLoading.value = false setTimeout(() => { progress.value = 0 }, 400) }, 500) } } function _startTimer() { if (process.client) { _timer = setInterval(() => { _increase(step.value) }, 100) } } return { progress, isLoading, start, finish, clear, } }
packages/nc-gui/composables/useLoadingIndicator/index.ts
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.00026572158094495535, 0.00018276830087415874, 0.00016820339078549296, 0.00017009924340527505, 0.000031516730814473704 ]
{ "id": 6, "code_window": [ " length?: number\n", "}\n", "\n", "const { placement = 'bottom', length = 20 } = defineProps<Props>()\n", "\n", "const text = ref<HTMLDivElement>()\n", "\n", "const enableTooltip = computed(() => text.value?.textContent?.length && text.value?.textContent?.length > length)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { placement, length } = withDefaults(defineProps<Props>(), { placement: 'bottom', length: 20 })\n" ], "file_path": "packages/nc-gui/components/general/TruncateText.vue", "type": "replace", "edit_start_line_idx": 20 }
<script setup lang="ts"> import dayjs from 'dayjs' import { ActiveCellInj, EditColumnInj, IsExpandedFormOpenInj, ReadonlyInj, computed, inject, onClickOutside, ref, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: number | string | null isPk?: boolean } const { modelValue, isPk = false } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const { showNull } = useGlobal() const readOnly = inject(ReadonlyInj, ref(false)) const active = inject(ActiveCellInj, ref(false)) const editable = inject(EditModeInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isExpandedFormOpen = inject(IsExpandedFormOpenInj, ref(false))! const isYearInvalid = ref(false) const { t } = useI18n() const localState = computed({ get() { if (!modelValue) { return undefined } const yearDate = dayjs(modelValue.toString(), 'YYYY') if (!yearDate.isValid()) { isYearInvalid.value = true return undefined } return yearDate }, set(val?: dayjs.Dayjs) { if (!val) { emit('update:modelValue', null) return } if (val?.isValid()) { emit('update:modelValue', val.format('YYYY')) } }, }) const open = ref<boolean>(false) const randomClass = `picker_${Math.floor(Math.random() * 99999)}` watch( open, (next) => { if (next) { onClickOutside(document.querySelector(`.${randomClass}`)! as HTMLDivElement, () => (open.value = false)) } else { editable.value = false } }, { flush: 'post' }, ) const placeholder = computed(() => { if (isEditColumn.value && (modelValue === '' || modelValue === null)) { return t('labels.optional') } else if (modelValue === null && showNull.value) { return t('general.null') } else if (isYearInvalid.value) { return t('msg.invalidTime') } else { return '' } }) const isOpen = computed(() => { if (readOnly.value) return false return (readOnly.value || (localState.value && isPk)) && !active.value && !editable.value ? false : open.value }) useSelectedCellKeyupListener(active, (e: KeyboardEvent) => { switch (e.key) { case 'Enter': e.stopPropagation() open.value = true break case 'Escape': if (open.value) { e.stopPropagation() open.value = false } break } }) </script> <template> <a-date-picker v-model:value="localState" :tabindex="0" picker="year" :bordered="false" class="!w-full !py-1 !border-none" :class="{ 'nc-null': modelValue === null && showNull, '!px-2': isExpandedFormOpen, '!px-0': !isExpandedFormOpen }" :placeholder="placeholder" :allow-clear="(!readOnly && !localState && !isPk) || isEditColumn" :input-read-only="true" :open="isOpen" :dropdown-class-name="`${randomClass} nc-picker-year children:border-1 children:border-gray-200 ${open ? 'active' : ''}`" @click="open = (active || editable) && !open" @change="open = (active || editable) && !open" @ok="open = !open" @keydown.enter="open = !open" > <template #suffixIcon></template> </a-date-picker> </template> <style scoped> :deep(.ant-picker-input > input[disabled]) { @apply !text-current; } </style>
packages/nc-gui/components/cell/YearPicker.vue
1
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.0033582313917577267, 0.0005422236281447113, 0.00016394064004998654, 0.00017349267727695405, 0.0009066619677469134 ]
{ "id": 6, "code_window": [ " length?: number\n", "}\n", "\n", "const { placement = 'bottom', length = 20 } = defineProps<Props>()\n", "\n", "const text = ref<HTMLDivElement>()\n", "\n", "const enableTooltip = computed(() => text.value?.textContent?.length && text.value?.textContent?.length > length)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "const { placement, length } = withDefaults(defineProps<Props>(), { placement: 'bottom', length: 20 })\n" ], "file_path": "packages/nc-gui/components/general/TruncateText.vue", "type": "replace", "edit_start_line_idx": 20 }
import { ViewTypes } from 'nocodb-sdk' import type { FilterType, KanbanType, SortType, TableType, ViewType } from 'nocodb-sdk' import type { Ref } from 'vue' import { computed, ref, storeToRefs, unref, useBase, useEventBus, useFieldQuery, useInjectionState, useNuxtApp } from '#imports' import type { SmartsheetStoreEvents } from '#imports' const [useProvideSmartsheetStore, useSmartsheetStore] = useInjectionState( ( // _view is deprecated, we use viewsStore instead _view: Ref<ViewType | undefined>, meta: Ref<TableType | KanbanType | undefined>, shared = false, initialSorts?: Ref<SortType[]>, initialFilters?: Ref<FilterType[]>, ) => { const { $api } = useNuxtApp() const { activeView: view, activeNestedFilters, activeSorts } = storeToRefs(useViewsStore()) const baseStore = useBase() const { sqlUis } = storeToRefs(baseStore) const sqlUi = ref( (meta.value as TableType)?.source_id ? sqlUis.value[(meta.value as TableType).source_id!] : Object.values(sqlUis.value)[0], ) const { search } = useFieldQuery() const eventBus = useEventBus<SmartsheetStoreEvents>(Symbol('SmartsheetStore')) const isLocked = computed(() => view.value?.lock_type === 'locked') const isPkAvail = computed(() => (meta.value as TableType)?.columns?.some((c) => c.pk)) const isGrid = computed(() => view.value?.type === ViewTypes.GRID) const isForm = computed(() => view.value?.type === ViewTypes.FORM) const isGallery = computed(() => view.value?.type === ViewTypes.GALLERY) const isKanban = computed(() => view.value?.type === ViewTypes.KANBAN) const isMap = computed(() => view.value?.type === ViewTypes.MAP) const isSharedForm = computed(() => isForm.value && shared) const xWhere = computed(() => { let where const col = (meta.value as TableType)?.columns?.find(({ id }) => id === search.value.field) || (meta.value as TableType)?.columns?.find((v) => v.pv) if (!col) return if (!search.value.query.trim()) return if (['text', 'string'].includes(sqlUi.value.getAbstractType(col)) && col.dt !== 'bigint') { where = `(${col.title},like,%${search.value.query.trim()}%)` } else { where = `(${col.title},eq,${search.value.query.trim()})` } return where }) const isSqlView = computed(() => (meta.value as TableType)?.type === 'view') const sorts = ref<SortType[]>(unref(initialSorts) ?? []) const nestedFilters = ref<FilterType[]>(unref(initialFilters) ?? []) watch( sorts, () => { activeSorts.value = sorts.value }, { immediate: true, }, ) watch( nestedFilters, () => { activeNestedFilters.value = nestedFilters.value }, { immediate: true, }, ) return { view, meta, isLocked, $api, xWhere, isPkAvail, isForm, isGrid, isGallery, isKanban, isMap, isSharedForm, sorts, nestedFilters, isSqlView, eventBus, sqlUi, } }, 'smartsheet-store', ) export { useProvideSmartsheetStore } export function useSmartsheetStoreOrThrow() { const state = useSmartsheetStore() if (!state) throw new Error('Please call `useProvideSmartsheetStore` on the appropriate parent component') return state }
packages/nc-gui/composables/useSmartsheetStore.ts
0
https://github.com/nocodb/nocodb/commit/4443800682333f3f613113c355708773806cbadd
[ 0.0006703243125230074, 0.00023603939916938543, 0.0001659341505728662, 0.00017101515550166368, 0.0001529676519567147 ]