gui: improve codeblock styling

This commit is contained in:
Test 2024-09-24 17:06:32 -07:00
parent 5ef1753b6e
commit 28c92eea4a
4 changed files with 14 additions and 308 deletions

View file

@ -5,7 +5,7 @@ import {
XMarkIcon,
} from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
import { getMarkdownLanguageTagForFile } from "core/util";
import { dedent, getMarkdownLanguageTagForFile } from "core/util";
import React, { useContext } from "react";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscEditorBackground } from "..";
@ -66,18 +66,14 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
const [collapsed, setCollapsed] = React.useState(true);
const [hovered, setHovered] = React.useState(false);
const content = dedent`${props.item.content}`;
const fence = React.useMemo(() => {
const backticks = props.item.content.match(backticksRegex);
const backticks = content.match(backticksRegex);
return backticks ? backticks.sort().at(-1) + "`" : "```";
}, [props.item.content]);
const codeBlockRef = React.useRef<HTMLDivElement>(null);
const codeBlockHeight = `${Math.min(
MAX_PREVIEW_HEIGHT,
codeBlockRef.current?.scrollHeight ??
// Best estimate of height I currently could find
props.item.content.split("\n").length * 18 + 36,
)}px`;
return (
<PreviewMarkdownDiv
@ -105,8 +101,8 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
);
} else {
ideMessenger.post("showVirtualFile", {
content,
name: props.item.name,
content: props.item.content,
});
}
}}
@ -142,36 +138,32 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
</PreviewMarkdownHeader>
<div
contentEditable={false}
className="m-0"
className={
collapsed ? "max-h-[33vh] overflow-hidden m-0" : "overflow-auto m-0"
}
ref={codeBlockRef}
style={{
height: collapsed ? codeBlockHeight : undefined,
overflow: collapsed ? "hidden" : "auto",
}}
>
<StyledMarkdownPreview
source={`${fence}${getMarkdownLanguageTagForFile(
props.item.description,
)}\n${props.item.content.trimEnd()}\n${fence}`}
)}\n${content}\n${fence}`}
showCodeBorder={false}
/>
</div>
{(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && (
<ButtonWithTooltip
className="bottom-1 right-1 absolute"
className="bottom-1 right-2 absolute"
text={collapsed ? "Expand" : "Collapse"}
>
{collapsed ? (
<ChevronDownIcon
width="1.2em"
height="1.2em"
className="h-5 w-5"
onClick={() => setCollapsed(false)}
/>
) : (
<ChevronUpIcon
width="1.2em"
height="1.2em"
className="h-5 w-5"
onClick={() => setCollapsed(true)}
/>
)}

View file

@ -1,281 +0,0 @@
export {};
// import { wireTmGrammars } from "monaco-editor-textmate";
// import { Registry } from "monaco-textmate";
// import { useEffect, useMemo, useRef } from "react";
// import MonacoEditor, { monaco } from "react-monaco-editor";
// import styled from "styled-components";
// import {
// VSC_EDITOR_BACKGROUND_VAR,
// defaultBorderRadius,
// parseColorForHex,
// } from "..";
// import { useAppendedString } from "../../hooks/useAppendedString";
// import "./monaco.css";
// const fetchTextMateGrammar = async (lang: string): Promise<string> => {
// return (
// await fetch(`${(window as any).vscMediaUrl}/textmate-syntaxes/${lang}`)
// ).text();
// };
// const supportedLanguages = {
// "source.ts": ["typescript", "TypeScript.tmLanguage.json"],
// "source.js": ["javascript", "JavaScript.tmLanguage.json"],
// "source.rust": ["rust", "rust.json"],
// // "source.batchfile": ["batchfile", "Batch File.tmLanguage"],
// "source.c": ["c", "c.json"],
// "source.cpp": ["cpp", "c++.json"],
// // "source.clojure": ["clojure", "Clojure.tmLanguage"],
// // "source.coffeescript": ["coffeescript", "coffeescript.json"],
// // "source.cshtml": ["cshtml", "cshtml.json"],
// // "source.css": ["css", "css.plist"],
// // "source.diff": ["diff", "diff.tmLanguage"],
// // "source.dockerfile": ["dockerfile", "Dockerfile.tmLanguage"],
// // "source.fsharp": ["fsharp", "fsharp.json"],
// // "source.git-commit": ["git-commit", "git-commit.tmLanguage"],
// // "source.git-rebase": ["git-rebase", "git-rebase.tmLanguage"],
// "source.go": ["go", "go.json"],
// // "source.groovy": ["groovy", "Groovy.tmLanguage"],
// // "source.handlebars": ["handlebars", "Handlebars.json"],
// // "source.html": ["html", "html.json"],
// // "source.jade": ["jade", "Jade.json"],
// // "source.java": ["java", "java.json"],
// // "source.javascript": ["javascript", "JavaScript.tmLanguage.json"],
// // // "source.json": ["json", "JSON.tmLanguage"],
// // "source.less": ["less", "less.tmLanguage.json"],
// // "source.lua": ["lua", "lua.json"],
// "source.python": ["python", "MagicPython.tmLanguage.json"],
// // "source.magicregexp": ["magicregexp", "MagicRegExp.tmLanguage.json"],
// // "source.makefile": ["makefile", "Makefile.json"],
// // // "source.markdown": ["markdown", "markdown.tmLanguage"],
// // // "source.objective-c": ["objective-c", "Objective-C.tmLanguage"],
// // // "source.perl6": ["perl6", "Perl 6.tmLanguage"],
// // // "source.perl": ["perl", "Perl.plist"],
// // "source.php": ["php", "php.json"],
// // // "source.platform": ["platform", "Platform.tmLanguage"],
// // // "source.powershell": ["powershell", "PowershellSyntax.tmLanguage"],
// // // "source.properties": ["properties", "properties.plist"],
// // // "source.r": ["r", "R.plist"],
// // // "source.regexp": ["regexp", "Regular Expressions (JavaScript).tmLanguage"],
// // // "source.ruby": ["ruby", "Ruby.plist"],
// // "source.scss": ["scss", "scss.json"],
// // "source.shaderlab": ["shaderlab", "shaderlab.json"],
// // "source.shell-unix-bash": [
// // "shell-unix-bash",
// // "Shell-Unix-Bash.tmLanguage.json",
// // ],
// // // "source.sql": ["sql", "SQL.plist"],
// "source.swift": ["swift", "swift.json"],
// "source.tsx": ["tsx", "TypeScriptReact.tmLanguage.json"],
// // "source.xml": ["xml", "xml.json"],
// // "source.xsl": ["xsl", "xsl.json"],
// "source.yaml": ["yaml", "yaml.json"],
// };
// export const supportedLanguagesArray = Object.keys(supportedLanguages).map(
// (l) => supportedLanguages[l][0]
// );
// const registry = new Registry({
// getGrammarDefinition: async (scopeName) => {
// if (scopeName in supportedLanguages) {
// const [_, tmFilename] = supportedLanguages[scopeName];
// let content;
// try {
// content = await fetchTextMateGrammar(tmFilename);
// } catch (e) {
// console.warn("Error fetching grammar for language", scopeName, e);
// content = await fetchTextMateGrammar("TypeScript.tmLanguage.json");
// }
// return {
// format: "json",
// content,
// };
// } else {
// return null;
// }
// },
// });
// const getThemeFromWindow = () => {
// const colorTheme = (window as any).fullColorTheme;
// return {
// ...colorTheme,
// base: colorTheme.base || "vs-dark",
// inherit: true,
// encodedTokensColors: undefined,
// // rules: [],
// colors: {
// "editor.background": parseColorForHex(VSC_EDITOR_BACKGROUND_VAR),
// },
// };
// };
// const Container = styled.div<{ showBorder: 0 | 1 }>`
// border-radius: ${defaultBorderRadius};
// overflow: hidden;
// margin: 0;
// `;
// interface MonacoCodeBlockProps {
// codeString: string;
// preProps: any;
// language: string;
// showBorder: boolean;
// }
// export const MonacoCodeBlock = (props: MonacoCodeBlockProps) => {
// const monacoRef = useRef(null);
// const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
// /* THEMING */
// const liftOff = async (monaco) => {
// try {
// const grammars = new Map();
// for (const [scopeName, [languageId, _]] of Object.entries(
// supportedLanguages
// )) {
// grammars.set(languageId, scopeName);
// monaco.languages.register({ id: languageId });
// }
// await wireTmGrammars(monaco, registry, grammars, editorRef.current);
// } catch (e) {
// console.error("Error wiring grammars", e);
// }
// };
// const onEditorDidMount = (
// editor: monaco.editor.IStandaloneCodeEditor,
// monaco: any
// ) => {
// monacoRef.current = monaco;
// editorRef.current = editor;
// monacoRef.current.editor.defineTheme("custom-theme", getThemeFromWindow());
// liftOff(monacoRef.current).then(() => {
// monacoRef.current.editor.setTheme("custom-theme");
// });
// editorRef.current.onDidContentSizeChange(() => {
// editorRef.current.layout({
// width: editorRef.current.getLayoutInfo().width,
// height: editorRef.current.getContentHeight(),
// });
// });
// };
// useEffect(() => {
// const listener = (e) => {
// if (e.data.type === "setTheme") {
// (window as any).fullColorTheme = e.data.theme;
// monacoRef.current.editor.defineTheme(
// "custom-theme",
// getThemeFromWindow()
// );
// monacoRef.current.editor.setTheme("custom-theme");
// }
// };
// window.addEventListener("message", listener);
// return () => {
// window.removeEventListener("message", listener);
// };
// }, [monacoRef.current]);
// /* STREAMING UPDATES */
// const appendText = (text: string, lineCount: number) => {
// const editor = editorRef.current;
// const model = editor.getModel();
// if (!model) return;
// const modelLineCount = model.getLineCount();
// lineCount = lineCount === 0 ? 1 : lineCount;
// lineCount = Math.min(lineCount, modelLineCount);
// const lastLineColumn = model.getLineMaxColumn(lineCount);
// const id = { major: 1, minor: 1 };
// const op = {
// identifier: id,
// range: {
// startLineNumber: lineCount,
// startColumn: lastLineColumn,
// endLineNumber: lineCount + 1,
// endColumn: 0,
// },
// text: text,
// forceMoveMarkers: true,
// };
// editor.getModel().applyEdits([op]);
// };
// // useEffect(() => {
// // if (props.codeString === prevFullTextRef.current) return;
// // let newText = props.codeString.slice(prevFullTextRef.current.length);
// // if (newText === "") return;
// // // To avoid the optimistic code block fences. Because the unwanted ones are always at the end of the block, this solves the problem
// // if (newText.endsWith("`") || newText.endsWith("`\n")) {
// // newText = newText.slice(0, newText.indexOf("`"));
// // }
// // appendText(newText);
// // prevFullTextRef.current = props.codeString;
// // }, [props.codeString, prevFullTextRef.current]);
// useAppendedString(props.codeString, appendText);
// const memoizedEditor = useMemo(() => {
// const rootStyle = getComputedStyle(document.documentElement);
// const fontFamily = rootStyle
// .getPropertyValue("--vscode-editor-font-family")
// .trim();
// return (
// <MonacoEditor
// defaultValue={props.codeString}
// editorDidMount={onEditorDidMount}
// language={
// supportedLanguagesArray.includes(props.language)
// ? props.language
// : "typescript"
// }
// theme="vs-dark"
// options={{
// automaticLayout: true,
// readOnly: true,
// minimap: { enabled: false },
// scrollBeyondLastLine: false,
// scrollbar: {
// alwaysConsumeMouseWheel: false,
// verticalScrollbarSize: 4,
// horizontalScrollbarSize: 4,
// },
// hover: {},
// renderWhitespace: "none",
// overviewRulerLanes: 0,
// lineNumbers: "off",
// folding: false,
// guides: {
// indentation: false,
// },
// renderLineHighlight: "none",
// fontLigatures: true,
// fontVariations: true,
// padding: { top: 4, bottom: 4 },
// fontFamily,
// trimAutoWhitespace: false,
// }}
// />
// );
// }, []);
// return (
// <Container showBorder={props.showBorder} {...props.preProps}>
// {memoizedEditor}
// </Container>
// );
// };

View file

@ -20,7 +20,6 @@ import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
const StyledMarkdown = styled.div<{
fontSize?: number;
showBorder?: boolean;
}>`
pre {
background-color: ${vscEditorBackground};
@ -30,7 +29,7 @@ const StyledMarkdown = styled.div<{
overflow-x: scroll;
overflow-y: hidden;
padding: ${(props) => (props.showBorder ? "8px 12px" : "0px 2px")};
padding: 6px;
margin: 0px;
}
@ -180,9 +179,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
}, [props.source]);
return (
<StyledMarkdown fontSize={getFontSize()} showBorder={props.showCodeBorder}>
{reactContent}
</StyledMarkdown>
<StyledMarkdown fontSize={getFontSize()}>{reactContent}</StyledMarkdown>
);
});

View file

@ -344,8 +344,6 @@ function ModelSelect() {
<div className="mt-auto">
{selectedProfileId === "local" && (
<>
{options.length > 0 && <Divider className="!my-0" />}
<StyledListboxOption
key={options.length}
onClick={onClickAddModel}