code editor header controls (#117)

This commit is contained in:
Red J Adaya 2024-07-18 14:41:33 +08:00 committed by GitHub
parent 9792184722
commit 2a81f19b15
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 280 additions and 102 deletions

View File

@ -149,7 +149,6 @@
border-radius: 3px;
align-items: center;
padding-left: 7px;
background: rgba(255, 255, 255, 0.1);
&.hovered {
background: rgba(255, 255, 255, 0.2);
@ -175,9 +174,16 @@
overflow: hidden;
text-overflow: ellipsis;
box-sizing: border-box;
opacity: 0.7;
font-weight: 500;
}
}
.button {
margin-left: 3px;
}
// webview specific. for refresh button
.block-frame-header-iconbutton {
height: 100%;
width: 27px;
@ -186,6 +192,14 @@
justify-content: center;
}
}
.block-frame-div-url {
background: rgba(255, 255, 255, 0.1);
input {
opacity: 1;
}
}
}
.block-frame-end-icons {

View File

@ -2,7 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
import { useLongClick } from "@/app/hook/useLongClick";
import { CodeEdit } from "@/app/view/codeedit/codeedit";
import { CodeEditor } from "@/app/view/codeeditor/codeeditor";
import { Button } from "@/element/button";
import { ErrorBoundary } from "@/element/errorboundary";
import { CenteredDiv } from "@/element/quickelems";
import { ContextMenuModel } from "@/store/contextmenu";
@ -222,11 +223,12 @@ const IconButton = React.memo(({ decl, className }: { decl: HeaderIconButton; cl
});
const Input = React.memo(({ decl, className }: { decl: HeaderInput; className: string }) => {
const { value, ref, onChange, onKeyDown, onFocus, onBlur } = decl;
const { value, ref, isDisabled, onChange, onKeyDown, onFocus, onBlur } = decl;
return (
<div className="input-wrapper">
<input
ref={ref}
disabled={isDisabled}
className={className}
value={value}
onChange={(e) => onChange(e)}
@ -327,6 +329,16 @@ const BlockFrame_Default_Component = ({
{elem.text}
</div>
);
} else if (elem.elemtype == "textbutton") {
return (
<Button
key={key}
className={clsx("border-radius-4 vertical-padding-3", elem.className)}
onClick={(e) => elem.onClick(e)}
>
{elem.text}
</Button>
);
} else if (elem.elemtype == "div") {
return (
<div
@ -495,7 +507,7 @@ function getViewElemAndModel(
} else if (blockView === "plot") {
viewElem = <PlotView key={blockId} />;
} else if (blockView === "codeedit") {
viewElem = <CodeEdit key={blockId} text={null} filename={null} />;
viewElem = <CodeEditor key={blockId} text={null} filename={null} />;
} else if (blockView === "web") {
const webviewModel = makeWebViewModel(blockId);
viewElem = <WebView key={blockId} parentRef={blockRef} model={webviewModel} />;

View File

@ -37,6 +37,11 @@
background: var(--error-color);
}
&.primary.warning {
background: #e6ba1e;
color: #000000;
}
&.primary.outlined,
&.primary.greyoutlined {
background: none;
@ -126,7 +131,16 @@
opacity: 0.5;
}
&.link-button {
&.link {
cursor: pointer;
}
}
.border-radius-4 {
border-radius: 4px;
}
.vertical-padding-3 {
padding-top: 3px;
padding-bottom: 3px;
}

View File

@ -4,9 +4,10 @@ import "./button.less";
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
className?: string;
children?: React.ReactNode;
}
const Button: React.FC<ButtonProps> = React.memo(({ className = "primary", children, disabled, ...props }) => {
const Button = React.memo(({ className = "primary", children, disabled, ...props }: ButtonProps) => {
const hasIcon = React.Children.toArray(children).some(
(child) => React.isValidElement(child) && (child as React.ReactElement).type === "svg"
);

View File

@ -61,6 +61,9 @@ class FileServiceType {
RemoveWidget(arg1: number): Promise<void> {
return WOS.callBackendService("file", "RemoveWidget", Array.from(arguments))
}
SaveFile(arg1: string, arg2: string): Promise<void> {
return WOS.callBackendService("file", "SaveFile", Array.from(arguments))
}
StatFile(arg1: string): Promise<FileInfo> {
return WOS.callBackendService("file", "StatFile", Array.from(arguments))
}

View File

@ -1,9 +0,0 @@
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
.codeedit {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
}

View File

@ -0,0 +1,29 @@
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
.code-editor-wrapper {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
overflow: hidden;
align-items: center;
justify-content: center;
.code-editor {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
.monaco-editor .slider {
background: rgba(255, 255, 255, 0.4);
border-radius: 4px;
transition: background 0.2s ease;
&:hover {
background: rgba(255, 255, 255, 0.6);
}
}
}
}

View File

@ -1,14 +1,14 @@
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
import "./codeedit.less";
import { globalStore } from "@/store/global";
import loader from "@monaco-editor/loader";
import { Editor, Monaco } from "@monaco-editor/react";
import * as jotai from "jotai";
import type * as MonacoTypes from "monaco-editor/esm/vs/editor/editor.api";
import * as React from "react";
import { useEffect, useRef, useState } from "react";
import "./codeeditor.less";
// there is a global monaco variable (TODO get the correct TS type)
declare var monaco: Monaco;
@ -53,6 +53,12 @@ function defaultEditorOptions(): MonacoTypes.editor.IEditorOptions {
scrollBeyondLastLine: false,
fontSize: 12,
fontFamily: "Hack",
smoothScrolling: true,
scrollbar: {
useShadows: false,
verticalScrollbarSize: 5,
horizontalScrollbarSize: 5,
},
};
return opts;
}
@ -62,23 +68,33 @@ interface CodeEditProps {
text: string;
language?: string;
filename: string;
onChange?: (text: string) => void;
}
export function CodeEdit({ readonly = false, text, language, filename }: CodeEditProps) {
const divRef = React.useRef<HTMLDivElement>(null);
const monacoRef = React.useRef<MonacoTypes.editor.IStandaloneCodeEditor | null>(null);
const theme = "wave-theme-dark";
const [divDims, setDivDims] = React.useState(null);
export function CodeEditor({ readonly = false, text, language, filename, onChange }: CodeEditProps) {
const [divDims, setDivDims] = useState(null);
const monacoLoaded = jotai.useAtomValue(monacoLoadedAtom);
React.useEffect(() => {
const monacoRef = useRef<MonacoTypes.editor.IStandaloneCodeEditor | null>(null);
const divRef = useRef<HTMLDivElement>(null);
const monacoLoadedRef = useRef<boolean | null>(null);
const theme = "wave-theme-dark";
useEffect(() => {
if (!divRef.current) {
return;
}
const height = divRef.current.clientHeight;
const width = divRef.current.clientWidth;
setDivDims({ height, width });
}, [divRef.current]);
}, []);
useEffect(() => {
if (monacoLoadedRef.current === null) {
monacoLoadedRef.current = monacoLoaded;
}
}, [monacoLoaded]);
function handleEditorMount(editor: MonacoTypes.editor.IStandaloneCodeEditor) {
monacoRef.current = editor;
@ -86,16 +102,16 @@ export function CodeEdit({ readonly = false, text, language, filename }: CodeEdi
//monaco.editor.setModelLanguage(monacoModel, "text/markdown");
}
function handleEditorChange(newText: string, ev: MonacoTypes.editor.IModelContentChangedEvent) {
// TODO
function handleEditorChange(text: string, ev: MonacoTypes.editor.IModelContentChangedEvent) {
onChange(text);
}
const editorOpts = defaultEditorOptions();
editorOpts.readOnly = readonly;
return (
<div className="view-codeedit">
<div className="codeedit" ref={divRef}>
<div className="code-editor-wrapper">
<div className="code-editor" ref={divRef}>
{divDims != null && monacoLoaded ? (
<Editor
theme={theme}

View File

@ -1,16 +1,6 @@
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
.view-codeedit {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
overflow: hidden;
align-items: center;
justify-content: center;
}
.view-preview {
display: flex;
flex-direction: row;

View File

@ -11,12 +11,13 @@ import * as util from "@/util/util";
import clsx from "clsx";
import * as jotai from "jotai";
import { loadable } from "jotai/utils";
import { useRef } from "react";
import { useEffect, useRef } from "react";
import { CenteredDiv } from "../element/quickelems";
import { CodeEdit } from "./codeedit/codeedit";
import { CodeEditor } from "./codeeditor/codeeditor";
import { CSVView } from "./csvview";
import { DirectoryPreview } from "./directorypreview";
import "./view.less";
import "./preview.less";
const MaxFileSize = 1024 * 1024 * 10; // 10MB
const MaxCSVSize = 1024 * 1024 * 1; // 1MB
@ -36,9 +37,11 @@ export class PreviewModel implements ViewModel {
blockAtom: jotai.Atom<Block>;
viewIcon: jotai.Atom<string | HeaderIconButton>;
viewName: jotai.Atom<string>;
viewText: jotai.Atom<string>;
viewText: jotai.Atom<HeaderElem[]>;
preIconButton: jotai.Atom<HeaderIconButton>;
endIconButtons: jotai.Atom<HeaderIconButton[]>;
ceReadOnly: jotai.PrimitiveAtom<boolean>;
isCeView: jotai.PrimitiveAtom<boolean>;
fileName: jotai.WritableAtom<string, [string], void>;
statFile: jotai.Atom<Promise<FileInfo>>;
@ -46,6 +49,7 @@ export class PreviewModel implements ViewModel {
fileMimeType: jotai.Atom<Promise<string>>;
fileMimeTypeLoadable: jotai.Atom<Loadable<string>>;
fileContent: jotai.Atom<Promise<string>>;
newFileContent: jotai.PrimitiveAtom<string>;
showHiddenFiles: jotai.PrimitiveAtom<boolean>;
refreshVersion: jotai.PrimitiveAtom<number>;
@ -59,6 +63,8 @@ export class PreviewModel implements ViewModel {
this.blockId = blockId;
this.showHiddenFiles = jotai.atom(true);
this.refreshVersion = jotai.atom(0);
this.ceReadOnly = jotai.atom(true);
this.isCeView = jotai.atom(false);
this.blockAtom = WOS.getWaveObjectAtom<Block>(`block:${blockId}`);
this.viewIcon = jotai.atom((get) => {
let blockData = get(this.blockAtom);
@ -95,8 +101,46 @@ export class PreviewModel implements ViewModel {
});
this.viewName = jotai.atom("Preview");
this.viewText = jotai.atom((get) => {
return get(this.fileName);
const viewTextChildren: HeaderElem[] = [
{
elemtype: "input",
value: get(this.fileName),
isDisabled: true,
},
];
if (get(this.isCeView)) {
if (get(this.ceReadOnly) == false) {
viewTextChildren.push(
{
elemtype: "textbutton",
text: "Save",
className: "primary warning",
onClick: this.handleFileSave.bind(this),
},
{
elemtype: "textbutton",
text: "Cancel",
className: "secondary",
onClick: () => this.toggleCodeEditorReadOnly(true),
}
);
} else {
viewTextChildren.push({
elemtype: "textbutton",
text: "Edit",
className: "secondary",
onClick: () => this.toggleCodeEditorReadOnly(false),
});
}
return [
{
elemtype: "div",
children: viewTextChildren,
},
] as HeaderElem[];
}
});
this.preIconButton = jotai.atom((get) => {
const mimeType = util.jotaiLoadableValue(get(this.fileMimeTypeLoadable), "");
if (mimeType == "directory") {
@ -105,7 +149,7 @@ export class PreviewModel implements ViewModel {
return {
elemtype: "iconbutton",
icon: "chevron-left",
click: this.onBack.bind(this),
click: this.handleBack.bind(this),
};
});
this.endIconButtons = jotai.atom((get) => {
@ -166,11 +210,12 @@ export class PreviewModel implements ViewModel {
const fullFile = await get(this.fullFile);
return util.base64ToString(fullFile?.data64);
});
this.newFileContent = jotai.atom("");
this.onBack = this.onBack.bind(this);
this.handleBack = this.handleBack.bind(this);
}
onBack() {
handleBack() {
const fileName = globalStore.get(this.fileName);
if (fileName == null) {
return;
@ -183,6 +228,21 @@ export class PreviewModel implements ViewModel {
globalStore.set(this.fileName, newPath);
}
toggleCodeEditorReadOnly(readOnly: boolean) {
globalStore.set(this.ceReadOnly, readOnly);
}
async handleFileSave() {
const fileName = globalStore.get(this.fileName);
const newFileContent = globalStore.get(this.newFileContent);
try {
services.FileService.SaveFile(fileName, util.stringToBase64(newFileContent));
this.toggleCodeEditorReadOnly(true);
} catch (error) {
console.error("Error saving file:", error);
}
}
getSettingsMenuItems(): ContextMenuItem[] {
const menuItems: ContextMenuItem[] = [];
menuItems.push({
@ -315,13 +375,34 @@ function CodeEditPreview({
contentAtom,
filename,
readonly,
isCeViewAtom,
newFileContentAtom,
}: {
contentAtom: jotai.Atom<Promise<string>>;
filename: string;
readonly: boolean;
isCeViewAtom: jotai.PrimitiveAtom<boolean>;
newFileContentAtom: jotai.PrimitiveAtom<string>;
}) {
const fileContent = jotai.useAtomValue(contentAtom);
return <CodeEdit readonly={true} text={fileContent} filename={filename} />;
const setIsCeView = jotai.useSetAtom(isCeViewAtom);
const setNewFileContent = jotai.useSetAtom(newFileContentAtom);
useEffect(() => {
setIsCeView(true);
return () => {
setIsCeView(false);
};
}, [setIsCeView]);
return (
<CodeEditor
readonly={readonly}
text={fileContent}
filename={filename}
onChange={(text) => setNewFileContent(text)}
/>
);
}
function CSVViewPreview({
@ -374,67 +455,78 @@ function iconForFile(mimeType: string, fileName: string): string {
function PreviewView({ blockId, model }: { blockId: string; model: PreviewModel }) {
const contentRef = useRef<HTMLDivElement>(null);
const blockAtom = WOS.getWaveObjectAtom<Block>(`block:${blockId}`);
const fileNameAtom = model.fileName;
const statFileAtom = model.statFile;
const fullFileAtom = model.fullFile;
const fileMimeTypeAtom = model.fileMimeType;
const fileContentAtom = model.fileContent;
let mimeType = jotai.useAtomValue(fileMimeTypeAtom);
if (mimeType == null) {
mimeType = "";
}
let fileName = jotai.useAtomValue(fileNameAtom);
const fileInfo = jotai.useAtomValue(statFileAtom);
const newFileContentAtom = model.newFileContent;
const ceReadOnlyAtom = model.ceReadOnly;
const isCeViewAtom = model.isCeView;
// handle streaming files here
let specializedView: React.ReactNode;
const mimeType = jotai.useAtomValue(fileMimeTypeAtom) || "";
const fileName = jotai.useAtomValue(fileNameAtom);
const fileInfo = jotai.useAtomValue(statFileAtom);
const ceReadOnly = jotai.useAtomValue(ceReadOnlyAtom);
let blockIcon = iconForFile(mimeType, fileName);
if (
mimeType == "application/pdf" ||
mimeType.startsWith("video/") ||
mimeType.startsWith("audio/") ||
mimeType.startsWith("image/")
) {
specializedView = <StreamingPreview fileInfo={fileInfo} />;
} else if (fileInfo == null) {
specializedView = (
<CenteredDiv>File Not Found{util.isBlank(fileName) ? null : JSON.stringify(fileName)}</CenteredDiv>
);
} else if (fileInfo.size > MaxFileSize) {
specializedView = <CenteredDiv>File Too Large to Preview</CenteredDiv>;
} else if (mimeType === "text/markdown") {
specializedView = <MarkdownPreview contentAtom={fileContentAtom} />;
} else if (mimeType === "text/csv") {
if (fileInfo.size > MaxCSVSize) {
specializedView = <CenteredDiv>CSV File Too Large to Preview (1MB Max)</CenteredDiv>;
} else {
specializedView = (
<CSVViewPreview
parentRef={contentRef}
// ensure consistent hook calls
const specializedView = (() => {
let view: React.ReactNode = null;
blockIcon = iconForFile(mimeType, fileName);
if (
mimeType === "application/pdf" ||
mimeType.startsWith("video/") ||
mimeType.startsWith("audio/") ||
mimeType.startsWith("image/")
) {
view = <StreamingPreview fileInfo={fileInfo} />;
} else if (!fileInfo) {
view = <CenteredDiv>File Not Found{util.isBlank(fileName) ? null : JSON.stringify(fileName)}</CenteredDiv>;
} else if (fileInfo.size > MaxFileSize) {
view = <CenteredDiv>File Too Large to Preview</CenteredDiv>;
} else if (mimeType === "text/markdown") {
view = <MarkdownPreview contentAtom={fileContentAtom} />;
} else if (mimeType === "text/csv") {
if (fileInfo.size > MaxCSVSize) {
view = <CenteredDiv>CSV File Too Large to Preview (1MB Max)</CenteredDiv>;
} else {
view = (
<CSVViewPreview
parentRef={contentRef}
contentAtom={fileContentAtom}
filename={fileName}
readonly={true}
/>
);
}
} else if (isTextFile(mimeType)) {
view = (
<CodeEditPreview
readonly={ceReadOnly}
contentAtom={fileContentAtom}
filename={fileName}
readonly={true}
isCeViewAtom={isCeViewAtom}
newFileContentAtom={newFileContentAtom}
/>
);
} else if (mimeType === "directory") {
view = <DirectoryPreview fileNameAtom={fileNameAtom} model={model} />;
} else {
view = (
<div className="view-preview">
<div>Preview ({mimeType})</div>
</div>
);
}
} else if (isTextFile(mimeType)) {
specializedView = <CodeEditPreview readonly={true} contentAtom={fileContentAtom} filename={fileName} />;
} else if (mimeType === "directory") {
specializedView = <DirectoryPreview fileNameAtom={fileNameAtom} model={model} />;
} else {
specializedView = (
<div className="view-preview">
<div>Preview ({mimeType})</div>
</div>
);
}
setTimeout(() => {
return view;
})();
useEffect(() => {
const blockIconOverrideAtom = useBlockAtom<string>(blockId, "blockicon:override", () => {
return jotai.atom<string>(null);
}) as jotai.PrimitiveAtom<string>;
globalStore.set(blockIconOverrideAtom, blockIcon);
}, 10);
}, [blockId, blockIcon]);
return (
<div className="full-preview scrollbar-hide-until-hover">

View File

@ -4,9 +4,9 @@
import { getApi } from "@/app/store/global";
import { WOS, globalStore } from "@/store/global";
import * as services from "@/store/services";
import clsx from "clsx";
import { WebviewTag } from "electron";
import * as jotai from "jotai";
import React, { memo, useEffect } from "react";
import "./webview.less";
@ -17,8 +17,6 @@ export class WebViewModel implements ViewModel {
viewIcon: jotai.Atom<string | HeaderIconButton>;
viewName: jotai.Atom<string>;
viewText: jotai.Atom<HeaderElem[]>;
preIconButton: jotai.Atom<HeaderIconButton>;
endIconButtons: jotai.Atom<HeaderIconButton[]>;
url: jotai.PrimitiveAtom<string>;
urlInput: jotai.PrimitiveAtom<string>;
urlInputFocused: jotai.PrimitiveAtom<boolean>;
@ -77,7 +75,7 @@ export class WebViewModel implements ViewModel {
},
{
elemtype: "div",
className: get(this.urlWrapperClassName),
className: clsx("block-frame-div-url", get(this.urlWrapperClassName)),
onMouseOver: this.handleUrlWrapperMouseOver.bind(this),
onMouseOut: this.handleUrlWrapperMouseOut.bind(this),
children: [

View File

@ -103,7 +103,7 @@ declare global {
type SubjectWithRef<T> = rxjs.Subject<T> & { refCount: number; release: () => void };
type HeaderElem = HeaderIconButton | HeaderText | HeaderInput | HeaderDiv;
type HeaderElem = HeaderIconButton | HeaderText | HeaderInput | HeaderDiv | HeaderTextButton;
type HeaderIconButton = {
elemtype: "iconbutton";
@ -114,6 +114,13 @@ declare global {
longClick?: (e: React.MouseEvent<any>) => void;
};
type HeaderTextButton = {
elemtype: "textbutton";
text: string;
className?: string;
onClick?: (e: React.MouseEvent<any>) => void;
};
type HeaderText = {
elemtype: "text";
text: string;
@ -123,6 +130,7 @@ declare global {
elemtype: "input";
value: string;
className?: string;
isDisabled?: boolean;
ref?: React.MutableRefObject<HTMLInputElement>;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;

View File

@ -1,6 +1,3 @@
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
package fileservice
import (
@ -41,6 +38,19 @@ type FullFile struct {
Data64 string `json:"data64"` // base64 encoded
}
func (fs *FileService) SaveFile(path string, data64 string) error {
cleanedPath := filepath.Clean(wavebase.ExpandHomeDir(path))
data, err := base64.StdEncoding.DecodeString(data64)
if err != nil {
return fmt.Errorf("failed to decode base64 data: %w", err)
}
err = os.WriteFile(cleanedPath, data, 0644)
if err != nil {
return fmt.Errorf("failed to write file %q: %w", path, err)
}
return nil
}
func (fs *FileService) StatFile(path string) (*FileInfo, error) {
cleanedPath := filepath.Clean(wavebase.ExpandHomeDir(path))
finfo, err := os.Stat(cleanedPath)