Merge pull request #3947 from shermanhuman/s-inline-keyboard-shortcuts

Shortcuts component for inline keyboard shortcuts
This commit is contained in:
Patrick Erichsen 2025-03-03 19:09:22 -08:00 • committed by GitHub
commit 838bc039c8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 485 additions and 16 deletions

Binary file not shown.

View file

@ -0,0 +1,92 @@
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View file

@ -0,0 +1,10 @@
# This is the official list of project authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS.txt file.
# See the latter for an explanation.
#
# Names should be added to this file as:
# Name or Organization <email address>
JetBrains <>
Philipp Nurullin <philipp.nurullin@jetbrains.com>
Konstantin Bulenkov <kb@jetbrains.com>

View file

@ -0,0 +1,93 @@
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View file

@ -1,6 +1,7 @@
import { SessionMetadata } from "core";
import MiniSearch from "minisearch";
import React, { Fragment, useEffect, useMemo, useRef, useState } from "react";
import Shortcut from '../gui/Shortcut';
import { getFontSize, getMetaKeyLabel } from "../../util";
import { HistoryTableRow } from "./HistoryTableRow";
@ -99,10 +100,9 @@ export function History() {
{filteredAndSortedSessions.length === 0 && (
<div className="m-4 text-center">
No past sessions found. To start a new session, either click the "+"
button or use the keyboard shortcut: <code>{getMetaKeyLabel()}</code>
{` `}
<code>L</code>
button or use the keyboard shortcut: <Shortcut>meta L</Shortcut>
</div>
)}
<table className="w-full border-collapse border-spacing-0">

View file

@ -0,0 +1,23 @@
.keyboard-key {
letter-spacing: 0.06rem;
color: var(--vscode-editor-foreground);
padding: 1px 4px;
margin: 0.08rem 0.08rem;
}
.keyboard-key-normal {
font-family: "JetBrains Mono", "SF Mono", Monaco, Menlo, Consolas, "Ubuntu Mono", "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace;
font-weight: 300;
}
.keyboard-key-special {
font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif;
font-weight: 300;
}
.separator {
position: relative;
top: 0.1rem;
margin: 0 0.1rem;
color: var(--vscode-editor-foreground);
}

View file

@ -0,0 +1,127 @@
import { render } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as util from "../../util";
import { Platform } from "../../util";
import Shortcut from "./Shortcut";
vi.mock("../../util", () => ({
...vi.importActual("../../util"),
getPlatform: vi.fn(),
getMetaKeyLabel: vi.fn(),
getAltKeyLabel: vi.fn(),
getFontSize: vi.fn(),
}));
describe("Shortcut component", () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(util.getPlatform).mockReturnValue("windows");
vi.mocked(util.getFontSize).mockReturnValue(14);
});
describe("Meta key rendering across platforms", () => {
const metaKeyInputs = ["meta", "cmd", "ctrl", "^", "⌘"];
const platforms: Platform[] = ["windows", "mac", "linux"];
platforms.forEach((platform) => {
metaKeyInputs.forEach((metaKey) => {
it(`should render "${metaKey}" as "${
platform === "mac" ? "⌘" : "Ctrl"
}" on ${platform}`, () => {
vi.mocked(util.getPlatform).mockReturnValue(platform);
vi.mocked(util.getMetaKeyLabel).mockImplementation(() => {
if (platform === "mac") return "⌘";
return "Ctrl";
});
const { container } = render(<Shortcut>{metaKey}</Shortcut>);
const kbdElement = container.querySelector("kbd");
expect(kbdElement?.textContent).toBe(
platform === "mac" ? "⌘" : "Ctrl",
);
});
});
});
});
describe("Font class application", () => {
it("should apply 'keyboard-key-normal' class for single characters", () => {
const { container } = render(<Shortcut>a</Shortcut>);
const kbdElement = container.querySelector("kbd");
expect(kbdElement).toHaveClass("keyboard-key-normal");
});
it("should apply 'keyboard-key-special' class for special keys", () => {
const { container } = render(<Shortcut>Enter</Shortcut>);
const kbdElement = container.querySelector("kbd");
expect(kbdElement).toHaveClass("keyboard-key-special");
});
});
describe("Delete key rendering across platforms", () => {
const deleteKeyInputs = ["backspace", "delete", "⌫"];
const platforms: Platform[] = ["windows", "mac", "linux"];
platforms.forEach((platform) => {
deleteKeyInputs.forEach((deleteKey) => {
it(`should render "${deleteKey}" correctly on ${platform}`, () => {
vi.mocked(util.getPlatform).mockReturnValue(platform);
const { container } = render(<Shortcut>{deleteKey}</Shortcut>);
const kbdElement = container.querySelector("kbd");
const expectedText = platform === "mac" ? "Delete ⌫" : "Backspace ⌫";
expect(kbdElement?.textContent).toBe(expectedText);
expect(kbdElement).toHaveClass("keyboard-key-special");
});
});
});
});
describe("Invalid input handling", () => {
it("should render error for empty shortcut string", () => {
const { container } = render(<Shortcut>{""}</Shortcut>);
expect(container.textContent).toBe("Error: Invalid shortcut key");
});
it("should render error for null input", () => {
const { container } = render(<Shortcut>{null as any}</Shortcut>);
expect(container.textContent).toBe("Error: Invalid shortcut key");
});
it("should gracefully handle invalid formatted input", () => {
const { container } = render(<Shortcut>{"abc ,, def"}</Shortcut>);
expect(container.querySelectorAll("kbd").length).toBeGreaterThan(0);
});
});
describe("Option/Alt key rendering across platforms", () => {
const optionKeyInputs = ["⌥", "option", "opt", "alt"];
const platforms: util.Platform[] = ["windows", "mac"];
platforms.forEach((platform) => {
optionKeyInputs.forEach((optionKey) => {
it(`should render "${optionKey}" correctly on ${platform}`, () => {
vi.mocked(util.getPlatform).mockReturnValue(platform);
vi.mocked(util.getAltKeyLabel).mockImplementation(() => {
return platform === "mac" ? "Option ⌥" : "Alt";
});
const { container } = render(<Shortcut>{optionKey}</Shortcut>);
const kbdElement = container.querySelector("kbd");
const expectedText = platform === "mac" ? "Option ⌥" : "Alt";
expect(kbdElement?.textContent).toBe(expectedText);
expect(kbdElement).toHaveClass("keyboard-key-special");
});
});
});
});
describe("Font class application for option/alt key", () => {
it("should apply 'keyboard-key-special' class for option/alt key", () => {
vi.mocked(util.getPlatform).mockReturnValue("windows");
vi.mocked(util.getFontSize).mockReturnValue(14);
vi.mocked(util.getAltKeyLabel).mockImplementation(() => "Alt");
const { container } = render(<Shortcut>alt</Shortcut>);
const kbdElement = container.querySelector("kbd");
expect(kbdElement).toHaveClass("keyboard-key-special");
});
});
});

View file

@ -0,0 +1,108 @@
import React from "react";
import "../../../src/index.css";
import {
getAltKeyLabel,
getFontSize,
getMetaKeyLabel,
getPlatform,
} from "../../util";
import "./Shortcut.css";
interface ShortcutProps {
children: string;
}
const fontSize = getFontSize();
const metaKeys = ["meta", "⌘", "ctrl", "cmd", "^"];
const altKeys = ["alt", "option", "opt", "⌥"];
const modifierKeys = [...metaKeys, ...altKeys];
const getSpecialKeyMap = (platform: string): Record<string, string> => ({
uparrow: "UpArrow ↑",
downarrow: "DownArrow ↓",
leftarrow: "LeftArrow ←",
rightarrow: "RightArrow →",
enter: "Enter ⏎",
esc: "Esc",
backspace: platform === "mac" ? "Delete ⌫" : "Backspace ⌫",
delete: platform === "mac" ? "Delete ⌫" : "Backspace ⌫",
"⌫": platform === "mac" ? "Delete ⌫" : "Backspace ⌫",
});
const parseShortcut = (shortcut: string, platform: string) => {
if (!shortcut || typeof shortcut !== "string") {
console.warn("Invalid shortcut provided:", shortcut);
return [];
}
const specialKeyMap = getSpecialKeyMap(platform);
return shortcut
.split(",")
.map((combo) =>
combo
.trim()
.split(" ")
.filter((key) => key)
.map((key) => {
const lowerKey = key.toLowerCase();
if (metaKeys.includes(lowerKey)) return getMetaKeyLabel();
if (altKeys.includes(lowerKey)) return getAltKeyLabel();
return specialKeyMap[lowerKey] || capitalizeKey(key);
}),
)
.filter((combo) => combo.length > 0);
};
const capitalizeKey = (key: string) =>
key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
const isSingleCharNonModifier = (key: string) =>
key && key.length === 1 && /^[a-zA-Z0-9]$/.test(key);
const Shortcut: React.FC<ShortcutProps> = ({ children }) => {
const platform = getPlatform();
if (!children || typeof children !== "string") {
return <span>Error: Invalid shortcut key</span>;
}
const shortcuts = parseShortcut(children, platform);
return (
<>
{shortcuts.map((combo, comboIndex) => (
<React.Fragment key={comboIndex}>
{combo.map((key, keyIndex) => (
<React.Fragment key={keyIndex}>
<kbd
className={`keyboard-key ${
!isSingleCharNonModifier(key) || key === "⌫"
? "keyboard-key-special"
: "keyboard-key-normal"
}`}
style={{
fontSize:
key &&
modifierKeys.includes(key.toLowerCase()) &&
platform === "mac"
? `${fontSize - 2}px`
: `${fontSize - 3}px`,
}}
>
{key || "?"}
</kbd>
{keyIndex < combo.length - 1 && (
<span className="separator">+</span>
)}
</React.Fragment>
))}
{comboIndex < shortcuts.length - 1 && (
<span className="separator">,</span>
)}
</React.Fragment>
))}
</>
);
};
export default Shortcut;

View file

@ -6,10 +6,11 @@ import {
PencilSquareIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { lightGray } from "..";
import { getMetaKeyLabel, isJetBrains } from "../../util";
import { useContext } from "react";
import { lightGray } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { isJetBrains } from "../../util";
import Shortcut from "../gui/Shortcut";
interface TutorialCardProps {
onClose: () => void;
@ -56,8 +57,8 @@ export function TutorialCard({ onClose }: TutorialCardProps) {
<PencilSquareIcon className="h-4 w-4 pr-3 align-middle" />
</div>
<span>
Highlight code and press <kbd>{getMetaKeyLabel()}</kbd> +{" "}
<kbd>I</kbd> to quickly make natural language edits
Highlight code and press <Shortcut>meta I</Shortcut> to quickly make
natural language edits
</span>
</li>
<li className="flex items-start">
@ -65,8 +66,8 @@ export function TutorialCard({ onClose }: TutorialCardProps) {
<ClipboardDocumentIcon className="h-4 w-4 pr-3 align-middle" />
</div>
<span>
Highlight code and press <kbd>{getMetaKeyLabel()}</kbd> +{" "}
<kbd>{jetbrains ? "J" : "L"}</kbd> to add it to the chat window
Highlight code and press <Shortcut>meta L</Shortcut> to add it to
the chat window
</span>
</li>
<li className="flex items-start">
@ -74,8 +75,7 @@ export function TutorialCard({ onClose }: TutorialCardProps) {
<Cog6ToothIcon className="h-4 w-4 pr-3 align-middle" />
</div>
<span>
Click the gear icon at the top of the chat window to configure
Continue
Click the gear icon in the upper right to configure Continue
</span>
</li>
<li className="flex items-start">

View file

@ -26,6 +26,7 @@ import {
} from "../../util";
import ConfirmationDialog from "../dialogs/ConfirmationDialog";
import { Divider } from "./platform/shared";
import Shortcut from '../gui/Shortcut';
interface ModelOptionProps {
option: Option;
@ -368,7 +369,7 @@ function ModelSelect() {
<Divider className="!my-0" />
<span className="block px-3 py-3" style={{ color: lightGray }}>
<code>{getMetaKeyLabel()} + '</code> to toggle
<Shortcut>meta '</Shortcut> to toggle model
</span>
</div>
</StyledListboxOptions>

View file

@ -2,6 +2,20 @@
@tailwind components;
@tailwind utilities;
@font-face {
font-family: "Inter";
src: url("/fonts/Inter/InterDisplay-Light.woff2") format("woff2");
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: "JetBrains Mono";
src: url("/fonts/JetBrainsMono/JetBrainsMono-Light.woff2") format("woff2");
font-weight: 300;
font-style: normal;
}
:root {
--example-var: rgb(30, 30, 30);
}
@ -10,6 +24,7 @@ html,
body,
#root {
height: 100%;
line-height: 1.3;
background-color: var(--vscode-editor-background);
font-family:
system-ui,

View file

@ -1,9 +1,9 @@
import _ from "lodash";
import { getLocalStorage } from "./localStorage";
import { KeyboardEvent } from "react";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import _ from "lodash";
import { KeyboardEvent } from "react";
import { getLocalStorage } from "./localStorage";
type Platform = "mac" | "linux" | "windows" | "unknown";
export type Platform = "mac" | "linux" | "windows" | "unknown";
export function getPlatform(): Platform {
const platform = window.navigator.platform.toUpperCase();