Merge pull request #2573 from continuedev/pe/jb-input-bugfixes

bugfix(jb): handle metakey backspace + highlights
This commit is contained in:
Patrick Erichsen 2024-10-18 16:54:42 -07:00 • committed by GitHub
commit 770bc90d54
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 406 additions and 360 deletions

View file

@ -1,6 +1,7 @@
# Contributing to Continue (JetBrains extension) <!-- omit in toc -->
This file is for contribution guidelines specific to the JetBrains extension. See the root [`CONTRIBUTING.md`](../../CONTRIBUTING.md) for general contribution guidelines.
This file is for contribution guidelines specific to the JetBrains extension. See the root [
`CONTRIBUTING.md`](../../CONTRIBUTING.md) for general contribution guidelines.
## Table of Contents <!-- omit in toc -->
@ -13,11 +14,10 @@ This file is for contribution guidelines specific to the JetBrains extension. Se
- [Misc](#misc)
- [Development Workflow](#development-workflow)
- [Running the extension](#running-the-extension)
- [Available Gradle tasks](#available-gradle-tasks)
- [Debugging](#debugging)
- [Reloading changes](#reloading-changes)
- [Setting breakpoints](#setting-breakpoints)
- [Packaging](#packaging)
- [Available Gradle tasks](#available-gradle-tasks)
- [Packaging](#packaging)
## Architecture Overview
@ -57,13 +57,31 @@ This project requires Node.js version 20.11.0 (LTS) or higher. You have two opti
## Development Workflow
Because the `gui` and `core` are written in TypeScript, our development workflow is built around the assumption that you have VS Code installed.
### Running the extension
- Select the "Run Continue" Gradle configuration in the top-right corner of the IDE
- Click the "Run" or "Debug" button
- The first time running this will install the IDE version specified by the `platformVersion` property in [`./run/Run Continue.run.xml`](./.run/Run%20Continue.run.xml). This will take a moment as the installation size can be close to 1GB.
- Open the project in VS Code and star the `Core binary` task
- Switch back to Intellij and select the "Run Continue" configuration in the top-right corner of the IDE
- Click the "Debug" button
- The first time running this will install the IDE version specified by the `platformVersion` property in [`./run/Run Extension.run.xml`](./.run/Run%20Extension.run.xml). This will take a moment as the installation size can be close to 1GB.
![run-extension-screenshot](../../media/run-intellij-extension.png)
![run-extension-screenshot](../../media/run-intellij-extension.png)\
This should open a new instance on IntelliJ with the extension installed and connected via TCP to the server started through the `Core binary` task.
### Reloading changes
- `extensions/intellij`: Attempt to reload changed classes by selecting `Run | Debugging Actions | Reload Changed Classes`
- This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension
- `gui`: Changes will be reloaded automatically
- `core`: Run `npm run build` from the `binary` directory and restart the `Core binary` task in VS Code
### Setting breakpoints
- `extensions/intellij`: Breakpoints can be set in Intellij
- `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools
- `core`: Breakpoints can be set in VS Code
### Available Gradle tasks
@ -83,30 +101,10 @@ runIde - Runs the IDE instance with the developed plugin installed.
verifyPluginConfiguration - Checks if Java and Kotlin compilers configuration meet IntelliJ SDK requirements
```
## Debugging
### Reloading changes
- `extensions/intellij`: Attempt to reload changed classes by selecting
`Run | Debugging Actions | Reload Changed Classes`
- This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension
- `gui`: Run `npm run build` from the `gui` directory
- `core`: Run `npm run build` from the `binary` directory
### Setting breakpoints
- `extensions/intellij`: Run the extension in debug mode
- `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools
- `core`: To set breakpoints in `core`, we need to start `binary` in a debug configuration
- Select the "Run Continue (TCP)" task in the top right corner
- Open the project in a VS Code window (we recommend this for a preconfigured Typescript debugging experience)
- Select the "Core Binary" task from the Run and Debug panel
- You can now set breakpoints in `core`. Note that if you make changes, you'll need to restart the "Core Binary"
task and reload changes classes in Intellij.
## Packaging
### Packaging
- Unix: `./gradlew build`
- Windows: `./gradlew.bat build`
This will generate a .zip file in `./build/distributions` with the version defined in [`./gradle.properties`](./gradle.properties)
This will generate a .zip file in `./build/distributions` with the version defined in [
`./gradle.properties`](./gradle.properties)

View file

@ -1,19 +1,19 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.services.TelemetryService
import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.google.gson.Gson
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import kotlinx.coroutines.*
import java.io.*
import java.net.Socket
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
import kotlinx.coroutines.*
class CoreMessenger(
private val project: Project,
@ -22,235 +22,218 @@ class CoreMessenger(
private val ideProtocolClient: IdeProtocolClient,
coroutineScope: CoroutineScope
) {
private var writer: Writer? = null
private var reader: BufferedReader? = null
private var process: Process? = null
private val gson = Gson()
private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false
private var writer: Writer? = null
private var reader: BufferedReader? = null
private var process: Process? = null
private val gson = Gson()
private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false
private fun write(message: String) {
try {
writer?.write(message + "\r\n")
writer?.flush()
} catch (e: Exception) {
println("Error writing to Continue core: $e")
}
private fun write(message: String) {
try {
writer?.write(message + "\r\n")
writer?.flush()
} catch (e: Exception) {
println("Error writing to Continue core: $e")
}
}
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
val id = messageId ?: uuid()
val message = gson.toJson(
mapOf(
"messageId" to id,
"messageType" to messageType,
"data" to data
)
)
responseListeners[id] = onResponse
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
val id = messageId ?: uuid()
val message =
gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
responseListeners[id] = onResponse
write(message)
}
private fun handleMessage(json: String) {
val responseMap = gson.fromJson(json, Map::class.java)
val messageId = responseMap["messageId"].toString()
val messageType = responseMap["messageType"].toString()
val data = responseMap["data"]
// IDE listeners
if (MessageTypes.ideMessageTypes.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message =
gson.toJson(
mapOf("messageId" to messageId, "messageType" to messageType, "data" to data))
write(message)
}
}
private fun handleMessage(json: String) {
val responseMap = gson.fromJson(json, Map::class.java)
val messageId = responseMap["messageId"].toString()
val messageType = responseMap["messageType"].toString()
val data = responseMap["data"]
// IDE listeners
if (MessageTypes.ideMessageTypes.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message = gson.toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
)
)
write(message)
};
}
// Forward to webview
if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
// TODO: Currently we aren't set up to receive a response back from the webview
// Can circumvent for getDefaultsModelTitle here for now
if (messageType == "getDefaultModelTitle") {
val continueSettingsService = service<ContinueExtensionSettings>()
val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel;
val message = gson.toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to defaultModelTitle
)
)
write(message)
}
val continuePluginService = project.service<ContinuePluginService>()
continuePluginService.sendToWebview(messageType, responseMap["data"], messageType)
}
// Responses for messageId
responseListeners[messageId]?.let { listener ->
listener(data)
if (MessageTypes.generatorTypes.contains(messageType)) {
val done = (data as Map<String, Boolean?>)["done"]
if (done == true) {
responseListeners.remove(messageId)
} else {
}
} else {
responseListeners.remove(messageId)
}
}
// Forward to webview
if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
// TODO: Currently we aren't set up to receive a response back from the webview
// Can circumvent for getDefaultsModelTitle here for now
if (messageType == "getDefaultModelTitle") {
val continueSettingsService = service<ContinueExtensionSettings>()
val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel
val message =
gson.toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to defaultModelTitle))
write(message)
}
val continuePluginService = project.service<ContinuePluginService>()
continuePluginService.sendToWebview(messageType, responseMap["data"], messageType)
}
private fun setPermissions(destination: String) {
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {
ProcessBuilder(
"xattr",
"-dr",
"com.apple.quarantine",
destination
).start()
setFilePermissions(destination, "rwxr-xr-x")
} else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
setFilePermissions(destination, "rwxr-xr-x")
}
// Responses for messageId
responseListeners[messageId]?.let { listener ->
listener(data)
if (MessageTypes.generatorTypes.contains(messageType)) {
val done = (data as Map<String, Boolean?>)["done"]
if (done == true) {
responseListeners.remove(messageId)
} else {}
} else {
responseListeners.remove(messageId)
}
}
}
private fun setFilePermissions(path: String, posixPermissions: String) {
val perms = HashSet<PosixFilePermission>()
if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
Files.setPosixFilePermissions(Paths.get(path), perms)
private fun setPermissions(destination: String) {
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {
ProcessBuilder("xattr", "-dr", "com.apple.quarantine", destination).start()
setFilePermissions(destination, "rwxr-xr-x")
} else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
setFilePermissions(destination, "rwxr-xr-x")
}
}
private val exitCallbacks: MutableList<() -> Unit> = mutableListOf()
fun onDidExit(callback: () -> Unit) {
exitCallbacks.add(callback)
}
private fun setFilePermissions(path: String, posixPermissions: String) {
val perms = HashSet<PosixFilePermission>()
if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
Files.setPosixFilePermissions(Paths.get(path), perms)
}
init {
if (useTcp) {
try {
val socket = Socket("127.0.0.1", 3000)
val writer = PrintWriter(socket.getOutputStream(), true)
this.writer = writer
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
this.reader = reader
private val exitCallbacks: MutableList<() -> Unit> = mutableListOf()
Thread {
fun onDidExit(callback: () -> Unit) {
exitCallbacks.add(callback)
}
init {
if (useTcp) {
try {
val socket = Socket("127.0.0.1", 3000)
val writer = PrintWriter(socket.getOutputStream(), true)
this.writer = writer
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
this.reader = reader
Thread {
try {
while (true) {
val line = reader.readLine()
if (line != null && line.isNotEmpty()) {
try {
while (true) {
val line = reader.readLine()
if (line != null && line.isNotEmpty()) {
try {
handleMessage(line)
} catch (e: Exception) {
println("Error handling message: $line")
println(e)
}
} else {
Thread.sleep(100)
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
reader.close()
writer.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}.start()
} catch (e: Exception) {
println("An error occurred: ${e.message}")
}
} else {
// Set proper permissions
coroutineScope.launch(Dispatchers.IO) {
setPermissions(continueCorePath)
setPermissions(esbuildPath)
}
// Start the subprocess
val processBuilder = ProcessBuilder(continueCorePath)
.directory(File(continueCorePath).parentFile)
process = processBuilder.start()
val outputStream = process!!.outputStream
val inputStream = process!!.inputStream
writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8)
reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
process!!.onExit().thenRun {
exitCallbacks.forEach { it() }
var err = process?.errorStream?.bufferedReader()?.readText()?.trim()
if (err != null) {
// There are often "⚡️Done in Xms" messages, and we want everything after the last one
val delimiter = "⚡ Done in"
val doneIndex = err.lastIndexOf(delimiter)
if (doneIndex != -1) {
err = err.substring(doneIndex + delimiter.length)
handleMessage(line)
} catch (e: Exception) {
println("Error handling message: $line")
println(e)
}
} else {
Thread.sleep(100)
}
}
println("Core process exited with output: $err")
CoroutineScope(Dispatchers.Main).launch {
ideProtocolClient.showToast("error", "Core process exited with output: $err")
}
// Log the cause of the failure
val telemetryService = service<TelemetryService>()
telemetryService.capture(
"jetbrains_core_exit", mapOf(
"error" to err
)
)
// Clean up all resources
writer?.close()
reader?.close()
process?.destroy()
}
coroutineScope.launch(Dispatchers.IO) {
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
while (true) {
val line = reader?.readLine()
if (line != null && line.isNotEmpty()) {
try {
handleMessage(line)
} catch (e: Exception) {
println("Error handling message: $line")
println(e)
}
} else {
delay(100)
}
}
reader.close()
writer.close()
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
reader?.close()
writer?.close()
outputStream.close()
inputStream.close()
process?.destroy()
} catch (e: IOException) {
e.printStackTrace()
}
e.printStackTrace()
}
}
}
.start()
} catch (e: Exception) {
println("TCP Connection Error: Unable to connect to 127.0.0.1:3000")
println("Reason: ${e.message}")
e.printStackTrace()
}
} else {
// Set proper permissions
coroutineScope.launch(Dispatchers.IO) {
setPermissions(continueCorePath)
setPermissions(esbuildPath)
}
// Start the subprocess
val processBuilder =
ProcessBuilder(continueCorePath).directory(File(continueCorePath).parentFile)
process = processBuilder.start()
val outputStream = process!!.outputStream
val inputStream = process!!.inputStream
writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8)
reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
process!!.onExit().thenRun {
exitCallbacks.forEach { it() }
var err = process?.errorStream?.bufferedReader()?.readText()?.trim()
if (err != null) {
// There are often "⚡️Done in Xms" messages, and we want everything after the last one
val delimiter = "⚡ Done in"
val doneIndex = err.lastIndexOf(delimiter)
if (doneIndex != -1) {
err = err.substring(doneIndex + delimiter.length)
}
}
println("Core process exited with output: $err")
CoroutineScope(Dispatchers.Main).launch {
ideProtocolClient.showToast("error", "Core process exited with output: $err")
}
// Log the cause of the failure
val telemetryService = service<TelemetryService>()
telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
// Clean up all resources
writer?.close()
reader?.close()
process?.destroy()
}
coroutineScope.launch(Dispatchers.IO) {
try {
while (true) {
val line = reader?.readLine()
if (line != null && line.isNotEmpty()) {
try {
handleMessage(line)
} catch (e: Exception) {
println("Error handling message: $line")
println(e)
}
} else {
delay(100)
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
reader?.close()
writer?.close()
outputStream.close()
inputStream.close()
process?.destroy()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
}
}

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.219",
"version": "0.9.220",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.219",
"version": "0.9.220",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -116,6 +116,7 @@
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"google-auth-library": "^9.14.2",
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.219",
"version": "0.9.220",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -49,7 +49,10 @@ const HoverItem = styled.span<{ isActive?: boolean }>`
padding-top: 2px;
padding-bottom: 2px;
cursor: pointer;
transition: color 200ms, background-color 200ms, box-shadow 200ms;
transition:
color 200ms,
background-color 200ms,
box-shadow 200ms;
`;
const EnterButton = styled.button`
@ -99,9 +102,9 @@ function InputToolbar(props: InputToolbarProps) {
id="input-toolbar"
className="flex"
>
<div className="flex gap-2 items-center whitespace-nowrap justify-start">
<div className="flex items-center justify-start gap-2 whitespace-nowrap">
<ModelSelect />
<div className="items-center hidden xs:flex gap-1 text-gray-400 transition-colors duration-200 -mb-1">
<div className="xs:flex -mb-1 hidden items-center gap-1 text-gray-400 transition-colors duration-200">
{supportsImages && (
<>
<input
@ -139,8 +142,8 @@ function InputToolbar(props: InputToolbarProps) {
</div>
</div>
<div className="flex items-center gap-2 whitespace-nowrap text-gray-400 ">
<div className="hidden sm:flex transition-colors duration-200 hover:underline">
<div className="flex items-center gap-2 whitespace-nowrap text-gray-400">
<div className="hidden transition-colors duration-200 hover:underline sm:flex">
{props.activeKey === "Alt" ? (
<HoverItem className="underline">
{`${getAltKeyLabel()}⏎
@ -169,7 +172,7 @@ function InputToolbar(props: InputToolbarProps) {
<EnterButton
onClick={(e) => {
props.onEnter({
useCodebase: isMetaEquivalentKeyPressed(e),
useCodebase: isMetaEquivalentKeyPressed(e as any),
noContext: useActiveFile ? e.altKey : !e.altKey,
});
}}

View file

@ -1,3 +1,4 @@
import { KeyboardEvent } from "react";
import Document from "@tiptap/extension-document";
import History from "@tiptap/extension-history";
import Image from "@tiptap/extension-image";
@ -44,6 +45,7 @@ import {
import { RootState } from "../../redux/store";
import {
getFontSize,
getPlatform,
isJetBrains,
isMetaEquivalentKeyPressed,
isWebEnvironment,
@ -58,6 +60,7 @@ import {
getSlashCommandDropdownOptions,
} from "./getSuggestion";
import { ComboBoxItem } from "./types";
import { handleMetaKeyPressJetBrains } from "../../util/handleMetaKeyPressJetBrains";
const InputBoxDiv = styled.div`
resize: none;
@ -532,78 +535,84 @@ function TipTapEditor(props: TipTapEditorProps) {
const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]);
useEffect(() => {
if (isJetBrains()) {
// This is only for VS Code .ipynb files
return;
}
/**
* This handles various issues with meta key actions
* - In JetBrains, when using "off screen rendering", there is a bug where using the meta key to
* highlight code using arrow keys is not working
* - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect
* the actual notebook cells, even when performing them in our GUI
*/
const handleKeyDown = async (e: KeyboardEvent<HTMLDivElement>) => {
if (!editor || !editorFocusedRef.current) return;
if (isWebEnvironment()) {
const handleKeyDown = async (event: KeyboardEvent) => {
if (!editor || !editorFocusedRef.current) return;
if ((event.metaKey || event.ctrlKey) && event.key === "x") {
// Cut
const selectedText = editor.state.doc.textBetween(
editor.state.selection.from,
editor.state.selection.to,
);
navigator.clipboard.writeText(selectedText);
editor.commands.deleteSelection();
event.preventDefault();
} else if ((event.metaKey || event.ctrlKey) && event.key === "c") {
// Copy
const selectedText = editor.state.doc.textBetween(
editor.state.selection.from,
editor.state.selection.to,
);
navigator.clipboard.writeText(selectedText);
event.preventDefault();
} else if ((event.metaKey || event.ctrlKey) && event.key === "v") {
// Paste
event.preventDefault(); // Prevent default paste behavior
const clipboardText = await navigator.clipboard.readText();
editor.commands.insertContent(clipboardText);
setActiveKey(e.key);
if (isMetaEquivalentKeyPressed(e)) {
e.stopPropagation();
e.preventDefault();
const { key, code } = e;
const isWebEnv = isWebEnvironment();
const text = editor.state.doc.textBetween(
editor.state.selection.from,
editor.state.selection.to,
);
if (isJetBrains()) {
if (code === "KeyJ") {
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
}
};
document.addEventListener("keydown", handleKeyDown);
if (isMetaEquivalentKeyPressed(e)) {
handleMetaKeyPressJetBrains(e, text, editor.commands.setContent);
}
} else {
if (code === "KeyL") {
debugger;
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
return;
}
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}
const handleKeyDown = async (event: KeyboardEvent) => {
if (!editor || !editorFocusedRef.current) return;
if (event.metaKey && event.key === "x") {
document.execCommand("cut");
event.stopPropagation();
event.preventDefault();
} else if (event.metaKey && event.key === "v") {
document.execCommand("paste");
event.stopPropagation();
event.preventDefault();
} else if (event.metaKey && event.key === "c") {
document.execCommand("copy");
event.stopPropagation();
event.preventDefault();
switch (key) {
case "x":
if (isWebEnv) {
await navigator.clipboard.writeText(text);
editor.commands.deleteSelection();
} else {
document.execCommand("cut");
}
break;
case "c":
if (isWebEnv) {
await navigator.clipboard.writeText(text);
} else {
document.execCommand("copy");
}
break;
case "v":
if (isWebEnv) {
const clipboardText = await navigator.clipboard.readText();
editor.commands.insertContent(clipboardText);
} else {
document.execCommand("paste");
}
break;
}
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [editor, editorFocusedRef]);
useEffect(() => {
if (mainEditorContent && editor) {
editor.commands.setContent(mainEditorContent);
dispatch(consumeMainEditorContent());
} else if (e.key === "Escape") {
ideMessenger.post("focusEditor", undefined);
}
}, [mainEditorContent, editor]);
};
const handleKeyUp = () => {
setActiveKey(null);
};
const onEnterRef = useUpdatingRef(
(modifiers: InputModifiers) => {
@ -632,28 +641,6 @@ function TipTapEditor(props: TipTapEditorProps) {
// This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview
const [ignoreHighlightedCode, setIgnoreHighlightedCode] = useState(false);
useEffect(() => {
const handleKeyDown = (event: any) => {
if (
isMetaEquivalentKeyPressed(event) &&
(isJetBrains() ? event.code === "KeyJ" : event.code === "KeyL")
) {
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
} else if (event.key === "Escape") {
ideMessenger.post("focusEditor", undefined);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, []);
// Re-focus main input after done generating
useEffect(() => {
if (editor && !active && props.isMainInput && document.hasFocus()) {
@ -849,12 +836,8 @@ function TipTapEditor(props: TipTapEditorProps) {
return (
<InputBoxDiv
onKeyDown={(e) => {
setActiveKey(e.key);
}}
onKeyUp={(e) => {
setActiveKey(null);
}}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
className="cursor-text"
onClick={() => {
editor && editor.commands.focus();

View file

@ -188,20 +188,20 @@ function ModelOption({
onMouseLeave={() => setHovered(false)}
onClick={handleOptionClick}
>
<div className="flex flex-col w-full gap-0.5">
<div className="flex items-center justify-between w-full">
<div className="flex items-center flex-grow">
<CubeIcon className="w-4 h-4 mr-2 flex-shrink-0" />
<div className="flex w-full flex-col gap-0.5">
<div className="flex w-full items-center justify-between">
<div className="flex flex-grow items-center">
<CubeIcon className="mr-2 h-4 w-4 flex-shrink-0" />
<span className="flex-grow">
{option.title}
{showMissingApiKeyMsg && (
<span className="ml-2 italic text-[10px]">
<span className="ml-2 text-[10px] italic">
(Missing API key)
</span>
)}
</span>
</div>
<div className="flex items-center ml-5">
<div className="ml-5 flex items-center">
<StyledCog6ToothIcon hovered={hovered} onClick={onClickGear} />
{showDelete && (
<StyledTrashIcon hovered={hovered} onClick={onClickDelete} />
@ -258,7 +258,7 @@ function ModelSelect() {
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "'" && isMetaEquivalentKeyPressed(event)) {
if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) {
const direction = event.shiftKey ? -1 : 1;
const currentIndex = options.findIndex(
(option) => option.value === defaultModel?.title,
@ -319,7 +319,7 @@ function ModelSelect() {
style={{ padding: 0 }}
onClick={calculatePosition}
>
<div className="text-gray-400 transition-colors duration-200 flex items-center gap-0.5 max-w-[33vw]">
<div className="flex max-w-[33vw] items-center gap-0.5 text-gray-400 transition-colors duration-200">
<span className="truncate">
{modelSelectTitle(defaultModel) || "Select model"}{" "}
</span>
@ -354,7 +354,7 @@ function ModelSelect() {
value={"addModel" as any}
>
<div className="flex items-center py-0.5">
<PlusIcon className="w-4 h-4 mr-2" />
<PlusIcon className="mr-2 h-4 w-4" />
Add Chat model
</div>
</StyledListboxOption>

View file

@ -0,0 +1,77 @@
import { KeyboardEvent } from "react";
import { getPlatform } from ".";
export const handleMetaKeyPressJetBrains = (
e: KeyboardEvent,
text: string,
setText: (text: string) => void,
) => {
const { selectionStart, selectionEnd } = e.target as HTMLTextAreaElement;
if (e.key === "Backspace") {
handleMetaBackspace(e, text, setText, selectionStart, selectionEnd);
}
if (getPlatform() === "mac") {
if (e.key === "ArrowLeft") {
handleMacArrowLeftKey(e);
} else if (e.key === "ArrowRight") {
handleMacArrowRightKey(e);
}
}
};
const handleMetaBackspace = (
e: KeyboardEvent,
text: string,
setText: (text: string) => void,
start: number,
end: number,
) => {
const target = e.target as HTMLTextAreaElement;
let newStart = start;
if (start !== end) {
setText(text.slice(0, start) + text.slice(end));
} else {
newStart =
getPlatform() === "mac"
? text.lastIndexOf("\n", start - 1) + 1
: text.slice(0, start).trimEnd().lastIndexOf(" ") + 1;
setText(text.slice(0, newStart) + text.slice(start));
}
target.setSelectionRange(newStart, newStart);
};
const handleMacArrowLeftKey = (e: KeyboardEvent) => {
const target = e.target as HTMLDivElement;
const selection = window.getSelection();
const range = document.createRange();
if (e.shiftKey) {
selection.modify("extend", "backward", "character");
} else {
range.setStart(target.firstChild, 0);
range.setEnd(target.firstChild, 0);
selection.removeAllRanges();
selection.addRange(range);
}
};
const handleMacArrowRightKey = (e: KeyboardEvent) => {
const selection = window.getSelection();
const range = document.createRange();
const target = e.target as HTMLDivElement;
if (e.shiftKey) {
selection.modify("extend", "forward", "character");
} else {
range.selectNodeContents(target);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
};

View file

@ -1,5 +1,6 @@
import _ from "lodash";
import { getLocalStorage } from "./localStorage";
import { KeyboardEvent } from "react";
type Platform = "mac" | "linux" | "windows" | "unknown";
@ -16,19 +17,19 @@ export function getPlatform(): Platform {
}
}
export function isMetaEquivalentKeyPressed(event: {
metaKey: boolean;
ctrlKey: boolean;
}): boolean {
export function isMetaEquivalentKeyPressed({
metaKey,
ctrlKey,
}: KeyboardEvent): boolean {
const platform = getPlatform();
switch (platform) {
case "mac":
return event.metaKey;
return metaKey;
case "linux":
case "windows":
return event.ctrlKey;
return ctrlKey;
default:
return event.metaKey;
return metaKey;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB