💄 UI for images in TipTap editor

This commit is contained in:
Nate Sesti 2024-01-19 22:21:58 -08:00
parent 794da496ca
commit 9bf59f0247
11 changed files with 243 additions and 35 deletions

View file

@ -92,7 +92,7 @@ class Ollama extends BaseLLM {
content: stripImages(message.content),
images: message.content
.filter((part) => part.type === "imageUrl")
.map((part) => part.imageUrl?.url.replace("data:", "")),
.map((part) => part.imageUrl?.url.split(",").at(-1)),
};
}

View file

@ -33,7 +33,11 @@ class OpenAI extends BaseLLM {
}
const parts = message.content.map((part) => {
return { type: part.type, text: part.text, image_url: part.imageUrl };
return {
type: part.type,
text: part.text,
image_url: { ...part.imageUrl, detail: "low" },
};
});
return {
...message,

32
gui/package-lock.json generated
View file

@ -12,6 +12,8 @@
"@heroicons/react": "^2.0.18",
"@monaco-editor/react": "^4.6.0",
"@reduxjs/toolkit": "^1.9.3",
"@tiptap/extension-dropcursor": "^2.1.16",
"@tiptap/extension-image": "^2.1.16",
"@tiptap/extension-mention": "^2.1.13",
"@tiptap/extension-placeholder": "^2.1.13",
"@tiptap/pm": "^2.1.13",
@ -1333,9 +1335,9 @@
}
},
"node_modules/@tiptap/extension-dropcursor": {
"version": "2.1.13",
"resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-2.1.13.tgz",
"integrity": "sha512-NAyJi4BJxH7vl/2LNS1X0ndwFKjEtX+cRgshXCnMyh7qNpIRW6Plczapc/W1OiMncOEhZJfpZfkRSfwG01FWFg==",
"version": "2.1.16",
"resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-2.1.16.tgz",
"integrity": "sha512-voWEIAmxV3f9Q0gc3K89HRq8KFeOVtHJBRHYihZwxMnvq2aMIwdpCx0GbiCd4slQaBLd1ASJHz1uAigVhR2+uA==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
@ -1424,6 +1426,18 @@
"@tiptap/pm": "^2.0.0"
}
},
"node_modules/@tiptap/extension-image": {
"version": "2.1.16",
"resolved": "https://registry.npmjs.org/@tiptap/extension-image/-/extension-image-2.1.16.tgz",
"integrity": "sha512-idvmJzdG/u9YDt/GOCvgQMB1p/GZbBqb2Spk8BhXHoBGHR4zFo609ExccXYKR4UWs0iTACDq80VwJvfHa8XYKw==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "^2.0.0"
}
},
"node_modules/@tiptap/extension-italic": {
"version": "2.1.13",
"resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-2.1.13.tgz",
@ -6793,9 +6807,9 @@
"requires": {}
},
"@tiptap/extension-dropcursor": {
"version": "2.1.13",
"resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-2.1.13.tgz",
"integrity": "sha512-NAyJi4BJxH7vl/2LNS1X0ndwFKjEtX+cRgshXCnMyh7qNpIRW6Plczapc/W1OiMncOEhZJfpZfkRSfwG01FWFg==",
"version": "2.1.16",
"resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-2.1.16.tgz",
"integrity": "sha512-voWEIAmxV3f9Q0gc3K89HRq8KFeOVtHJBRHYihZwxMnvq2aMIwdpCx0GbiCd4slQaBLd1ASJHz1uAigVhR2+uA==",
"requires": {}
},
"@tiptap/extension-floating-menu": {
@ -6836,6 +6850,12 @@
"integrity": "sha512-7OgjgNqZXvBejgULNdMSma2M1nzv4bbZG+FT5XMFZmEOxR9IB1x/RzChjPdeicff2ZK2sfhMBc4Y9femF5XkUg==",
"requires": {}
},
"@tiptap/extension-image": {
"version": "2.1.16",
"resolved": "https://registry.npmjs.org/@tiptap/extension-image/-/extension-image-2.1.16.tgz",
"integrity": "sha512-idvmJzdG/u9YDt/GOCvgQMB1p/GZbBqb2Spk8BhXHoBGHR4zFo609ExccXYKR4UWs0iTACDq80VwJvfHa8XYKw==",
"requires": {}
},
"@tiptap/extension-italic": {
"version": "2.1.13",
"resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-2.1.13.tgz",

View file

@ -13,6 +13,8 @@
"@heroicons/react": "^2.0.18",
"@monaco-editor/react": "^4.6.0",
"@reduxjs/toolkit": "^1.9.3",
"@tiptap/extension-dropcursor": "^2.1.16",
"@tiptap/extension-image": "^2.1.16",
"@tiptap/extension-mention": "^2.1.13",
"@tiptap/extension-placeholder": "^2.1.13",
"@tiptap/pm": "^2.1.13",

View file

@ -16,6 +16,7 @@ export const VSC_LIST_ACTIVE_FOREGROUND_VAR =
export const VSC_QUICK_INPUT_BACKGROUND_VAR = "--vscode-quickInput-background";
export const VSC_INPUT_BORDER_VAR = "--vscode-input-border";
export const VSC_INPUT_BORDER_FOCUS_VAR = "--vscode-focusBorder";
export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background";
export const VSC_THEME_COLOR_VARS = [
VSC_INPUT_BACKGROUND_VAR,
@ -29,6 +30,7 @@ export const VSC_THEME_COLOR_VARS = [
VSC_QUICK_INPUT_BACKGROUND_VAR,
VSC_INPUT_BORDER_VAR,
VSC_INPUT_BORDER_FOCUS_VAR,
VSC_BADGE_BACKGROUND_VAR,
];
export const defaultBorderRadius = "5px";
@ -46,6 +48,7 @@ export const vscFocusBorder = `var(${VSC_FOCUS_BORDER}, #1bbe84)`;
export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, ${VSC_FOREGROUND_VAR})`;
export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`;
export const vscInputBorderFocus = `var(${VSC_INPUT_BORDER_FOCUS_VAR}, ${lightGray})`;
export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`;
if (typeof document !== "undefined") {
for (const colorVar of VSC_THEME_COLOR_VARS) {

View file

@ -2,7 +2,7 @@ import { mergeAttributes, Node } from "@tiptap/core";
import { NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { useDispatch, useSelector } from "react-redux";
import { vscFocusBorder } from "..";
import { vscBadgeBackground } from "..";
import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice";
import { RootStore } from "../../redux/store";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
@ -27,7 +27,7 @@ const CodeBlockComponent = ({
item.id === contextItems[0]?.id
? "#d0d"
: selected
? vscFocusBorder
? vscBadgeBackground
: undefined
}
item={item}

View file

@ -1,3 +1,6 @@
import { PhotoIcon as OutlinePhotoIcon } from "@heroicons/react/24/outline";
import { PhotoIcon as SolidPhotoIcon } from "@heroicons/react/24/solid";
import { useRef, useState } from "react";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscInputBackground } from "..";
@ -49,22 +52,65 @@ interface InputToolbarProps {
onClick?: () => void;
onImageFileSelected?: (file: File) => void;
hidden?: boolean;
}
function InputToolbar(props: InputToolbarProps) {
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [fileSelectHovered, setFileSelectHovered] = useState(false);
return (
<StyledDiv hidden={props.hidden} onClick={props.onClick} id="input-toolbar">
<span
style={{
color: lightGray,
}}
onClick={(e) => {
props.onAddContextItem();
}}
className="hover:underline cursor-pointer mr-auto"
>
+ Add Context
<span className="cursor-pointer mr-auto flex items-center">
<span
style={{
color: lightGray,
}}
onClick={(e) => {
props.onAddContextItem();
}}
className="hover:underline cursor-pointer"
>
+ Add Context
</span>
<span
className="ml-1.5 mt-0.5"
onMouseLeave={() => setFileSelectHovered(false)}
onMouseEnter={() => setFileSelectHovered(true)}
>
<input
type="file"
ref={fileInputRef}
style={{ display: "none" }}
accept=".jpg,.jpeg,.png,.gif,.svg,.webp"
onChange={(e) => {
for (const file of e.target.files) {
props.onImageFileSelected(file);
}
}}
/>
{fileSelectHovered ? (
<SolidPhotoIcon
width="1.4em"
height="1.4em"
color={lightGray}
onClick={(e) => {
fileInputRef.current?.click();
}}
/>
) : (
<OutlinePhotoIcon
width="1.4em"
height="1.4em"
color={lightGray}
onClick={(e) => {
fileInputRef.current?.click();
}}
/>
)}
</span>
</span>
<span
style={{

View file

@ -27,3 +27,13 @@
.gap-cursor {
border-top: 1px solid white;
}
.tiptap img {
height: auto;
max-width: 96%;
border: 1px solid transparent;
}
.tiptap img.ProseMirror-selectednode {
border: 1px solid var(--vscode-badge-background, #bfe2b6);
}

View file

@ -1,5 +1,7 @@
import Document from "@tiptap/extension-document";
import Dropcursor from "@tiptap/extension-dropcursor";
import History from "@tiptap/extension-history";
import Image from "@tiptap/extension-image";
import Paragraph from "@tiptap/extension-paragraph";
import Placeholder from "@tiptap/extension-placeholder";
import Text from "@tiptap/extension-text";
@ -23,7 +25,7 @@ import useUpdatingRef from "../../hooks/useUpdatingRef";
import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice";
import { RootStore } from "../../redux/store";
import { isMetaEquivalentKeyPressed } from "../../util";
import { isJetBrains, postToIde } from "../../util/ide";
import { errorPopup, isJetBrains, postToIde } from "../../util/ide";
import CodeBlockExtension from "./CodeBlockExtension";
import { SlashCommand } from "./CommandsExtension";
import InputToolbar from "./InputToolbar";
@ -61,6 +63,25 @@ const InputBoxDiv = styled.div`
position: relative;
`;
function getDataUrlForFile(file: File, img): string {
const targetWidth = 512;
const targetHeight = 512;
const scaleFactor = Math.min(
targetWidth / img.width,
targetHeight / img.height
);
const canvas = document.createElement("canvas");
canvas.width = img.width * scaleFactor;
canvas.height = img.height * scaleFactor;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const downsizedDataUrl = canvas.toDataURL("image/jpeg", 0.7);
return downsizedDataUrl;
}
interface TipTapEditorProps {
availableContextProviders: IContextProvider[];
availableSlashCommands: ComboBoxItem[];
@ -135,10 +156,47 @@ function TipTapEditor(props: TipTapEditorProps) {
props.availableSlashCommands
);
async function handleImageFile(
file: File
): Promise<[HTMLImageElement, string] | undefined> {
let filesize = file.size / 1024 / 1024; // filesize in MB
// check image type and size
if (
(file.type === "image/jpeg" || file.type === "image/png") &&
filesize < 10
) {
// check dimensions
let _URL = window.URL || window.webkitURL;
let img = new window.Image();
img.src = _URL.createObjectURL(file);
console.log(img.src);
return await new Promise((resolve) => {
img.onload = function () {
const dataUrl = getDataUrlForFile(file, img);
let image = new window.Image();
console.log("DATA URL: ", dataUrl.slice(0, 50));
image.src = dataUrl;
image.onload = function () {
resolve([image, dataUrl]);
};
};
});
} else {
errorPopup(
"Images need to be in jpg or png format and less than 10MB in size."
);
}
return undefined;
}
const editor = useEditor({
extensions: [
Document,
History,
Image,
Dropcursor,
Placeholder.configure({
placeholder: () =>
historyLengthRef.current === 0
@ -216,6 +274,32 @@ function TipTapEditor(props: TipTapEditorProps) {
class: "outline-none -mt-1 overflow-hidden",
style: "font-size: 14px;",
},
handleDrop: function (view, event, slice, moved) {
if (
!moved &&
event.dataTransfer &&
event.dataTransfer.files &&
event.dataTransfer.files[0]
) {
let file = event.dataTransfer.files[0];
handleImageFile(file).then(([img, dataUrl]) => {
const { schema } = view.state;
const coordinates = view.posAtCoords({
left: event.clientX,
top: event.clientY,
});
const node = schema.nodes.image.create({ src: dataUrl });
const transaction = view.state.tr.insert(
Math.max(0, coordinates.pos - 1),
[node]
);
return view.dispatch(transaction);
});
return true;
}
return false;
},
},
content: props.editorState || "",
onUpdate: ({ editor, transaction }) => {
@ -386,6 +470,13 @@ function TipTapEditor(props: TipTapEditorProps) {
onEnter={() => {
onEnterRef.current(editor.getJSON());
}}
onImageFileSelected={(file) => {
handleImageFile(file).then(([img, dataUrl]) => {
const { schema } = editor.state;
const node = schema.nodes.image.create({ src: dataUrl });
editor.state.tr.insert(0, node);
});
}}
/>
</InputBoxDiv>
);

View file

@ -4,9 +4,12 @@ import {
EmbeddingsProvider,
IContextProvider,
ILLM,
MessageContent,
MessagePart,
} from "core";
import { ExtensionIde } from "core/ide";
import { ideRequest } from "core/ide/messaging";
import { stripImages } from "core/llm/countTokens";
import { getBasename } from "core/util";
interface MentionAttrs {
@ -28,8 +31,8 @@ async function resolveEditorContent(
contextProviders: IContextProvider[],
llm: ILLM,
embeddingsProvider?: EmbeddingsProvider
): Promise<[ContextItemWithId[], string]> {
let paragraphs = [];
): Promise<[ContextItemWithId[], MessageContent]> {
let parts: MessagePart[] = [];
let contextItemAttrs: MentionAttrs[] = [];
let slashCommand = undefined;
for (const p of editorState?.content) {
@ -41,14 +44,33 @@ async function resolveEditorContent(
if (text === "") {
continue;
}
paragraphs.push(text);
if (parts[parts.length - 1]?.type === "text") {
parts[parts.length - 1].text += "\n" + text;
} else {
parts.push({ type: "text", text });
}
contextItemAttrs.push(...ctxItems);
} else if (p.type === "codeBlock") {
if (!p.attrs.item.editing) {
paragraphs.push(
"```" + p.attrs.item.name + "\n" + p.attrs.item.content + "\n```"
);
const text =
"```" + p.attrs.item.name + "\n" + p.attrs.item.content + "\n```";
if (parts[parts.length - 1]?.type === "text") {
parts[parts.length - 1].text += "\n" + text;
} else {
parts.push({
type: "text",
text,
});
}
}
} else if (p.type === "image") {
parts.push({
type: "imageUrl",
imageUrl: {
url: p.attrs.src,
},
});
} else {
console.warn("Unexpected content type", p.type);
}
@ -76,7 +98,7 @@ async function resolveEditorContent(
const data = {
name: item.id,
query: item.query,
fullInput: paragraphs.join("\n"),
fullInput: stripImages(parts),
};
const { items: resolvedItems } = await ideRequest(
"getContextItems",
@ -93,12 +115,14 @@ async function resolveEditorContent(
contextItemsText += "\n";
}
let finalText = paragraphs.join("\n").trim();
if (slashCommand) {
finalText = `${slashCommand} ${finalText}`;
let firstTextIndex = parts.findIndex((part) => part.type === "text");
parts[
firstTextIndex
].text = `${slashCommand} ${parts[firstTextIndex].text}`;
}
return [contextItems, finalText];
return [contextItems, parts];
}
function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] {

View file

@ -6,11 +6,13 @@ import {
ChatHistoryItem,
ChatMessage,
LLMReturnValue,
MessageContent,
SlashCommand,
} from "core";
import { ExtensionIde } from "core/ide";
import { ideStreamRequest } from "core/ide/messaging";
import { constructMessages } from "core/llm/constructMessages";
import { stripImages } from "core/llm/countTokens";
import { usePostHog } from "posthog-js/react";
import { useEffect, useRef } from "react";
import { useSelector } from "react-redux";
@ -72,12 +74,18 @@ function useChatHandler(dispatch: Dispatch) {
}
const getSlashCommandForInput = (
input: string
input: MessageContent
): [SlashCommand, string] | undefined => {
let slashCommand: SlashCommand | undefined;
let slashCommandName: string | undefined;
if (input.startsWith("/")) {
slashCommandName = input.split(" ")[0].substring(1);
let firstText =
typeof input === "string"
? input
: input.filter((part) => part.type === "text")[0]?.text || "";
if (firstText.startsWith("/")) {
slashCommandName = firstText.split(" ")[0].substring(1);
slashCommand = slashCommands.find(
(command) => command.name === slashCommandName
);
@ -87,7 +95,7 @@ function useChatHandler(dispatch: Dispatch) {
}
// Convert to actual slash command object with runnable function
return [slashCommand, input];
return [slashCommand, stripImages(input)];
};
async function* _streamSlashCommandFromVsCode(