fix: remove monorepo
This commit is contained in:
213
app/components/chat/Artifact.tsx
Normal file
213
app/components/chat/Artifact.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { computed } from 'nanostores';
|
||||
import { memo, useEffect, useRef, useState } from 'react';
|
||||
import { createHighlighter, type BundledLanguage, type BundledTheme, type HighlighterGeneric } from 'shiki';
|
||||
import type { ActionState } from '~/lib/runtime/action-runner';
|
||||
import { workbenchStore } from '~/lib/stores/workbench';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
|
||||
const highlighterOptions = {
|
||||
langs: ['shell'],
|
||||
themes: ['light-plus', 'dark-plus'],
|
||||
};
|
||||
|
||||
const shellHighlighter: HighlighterGeneric<BundledLanguage, BundledTheme> =
|
||||
import.meta.hot?.data.shellHighlighter ?? (await createHighlighter(highlighterOptions));
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.shellHighlighter = shellHighlighter;
|
||||
}
|
||||
|
||||
interface ArtifactProps {
|
||||
messageId: string;
|
||||
}
|
||||
|
||||
export const Artifact = memo(({ messageId }: ArtifactProps) => {
|
||||
const userToggledActions = useRef(false);
|
||||
const [showActions, setShowActions] = useState(false);
|
||||
|
||||
const artifacts = useStore(workbenchStore.artifacts);
|
||||
const artifact = artifacts[messageId];
|
||||
|
||||
const actions = useStore(
|
||||
computed(artifact.runner.actions, (actions) => {
|
||||
return Object.values(actions);
|
||||
}),
|
||||
);
|
||||
|
||||
const toggleActions = () => {
|
||||
userToggledActions.current = true;
|
||||
setShowActions(!showActions);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (actions.length && !showActions && !userToggledActions.current) {
|
||||
setShowActions(true);
|
||||
}
|
||||
}, [actions]);
|
||||
|
||||
return (
|
||||
<div className="artifact border border-bolt-elements-borderColor flex flex-col overflow-hidden rounded-lg w-full transition-border duration-150">
|
||||
<div className="flex">
|
||||
<button
|
||||
className="flex items-stretch bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover w-full overflow-hidden"
|
||||
onClick={() => {
|
||||
const showWorkbench = workbenchStore.showWorkbench.get();
|
||||
workbenchStore.showWorkbench.set(!showWorkbench);
|
||||
}}
|
||||
>
|
||||
<div className="px-5 p-3.5 w-full text-left">
|
||||
<div className="w-full text-bolt-elements-textPrimary font-medium leading-5 text-sm">{artifact?.title}</div>
|
||||
<div className="w-full w-full text-bolt-elements-textSecondary text-xs mt-0.5">Click to open Workbench</div>
|
||||
</div>
|
||||
</button>
|
||||
<div className="bg-bolt-elements-artifacts-borderColor w-[1px]" />
|
||||
<AnimatePresence>
|
||||
{actions.length && (
|
||||
<motion.button
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: 'auto' }}
|
||||
exit={{ width: 0 }}
|
||||
transition={{ duration: 0.15, ease: cubicEasingFn }}
|
||||
className="bg-bolt-elements-artifacts-background hover:bg-bolt-elements-artifacts-backgroundHover"
|
||||
onClick={toggleActions}
|
||||
>
|
||||
<div className="p-4">
|
||||
<div className={showActions ? 'i-ph:caret-up-bold' : 'i-ph:caret-down-bold'}></div>
|
||||
</div>
|
||||
</motion.button>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
<AnimatePresence>
|
||||
{showActions && actions.length > 0 && (
|
||||
<motion.div
|
||||
className="actions"
|
||||
initial={{ height: 0 }}
|
||||
animate={{ height: 'auto' }}
|
||||
exit={{ height: '0px' }}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
<div className="bg-bolt-elements-artifacts-borderColor h-[1px]" />
|
||||
<div className="p-5 text-left bg-bolt-elements-actions-background">
|
||||
<ActionList actions={actions} />
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
interface ShellCodeBlockProps {
|
||||
classsName?: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
function ShellCodeBlock({ classsName, code }: ShellCodeBlockProps) {
|
||||
return (
|
||||
<div
|
||||
className={classNames('text-xs', classsName)}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: shellHighlighter.codeToHtml(code, {
|
||||
lang: 'shell',
|
||||
theme: 'dark-plus',
|
||||
}),
|
||||
}}
|
||||
></div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ActionListProps {
|
||||
actions: ActionState[];
|
||||
}
|
||||
|
||||
const actionVariants = {
|
||||
hidden: { opacity: 0, y: 20 },
|
||||
visible: { opacity: 1, y: 0 },
|
||||
};
|
||||
|
||||
const ActionList = memo(({ actions }: ActionListProps) => {
|
||||
return (
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}>
|
||||
<ul className="list-none space-y-2.5">
|
||||
{actions.map((action, index) => {
|
||||
const { status, type, content } = action;
|
||||
const isLast = index === actions.length - 1;
|
||||
|
||||
return (
|
||||
<motion.li
|
||||
key={index}
|
||||
variants={actionVariants}
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
ease: cubicEasingFn,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 text-sm">
|
||||
<div className={classNames('text-lg', getIconColor(action.status))}>
|
||||
{status === 'running' ? (
|
||||
<div className="i-svg-spinners:90-ring-with-bg"></div>
|
||||
) : status === 'pending' ? (
|
||||
<div className="i-ph:circle-duotone"></div>
|
||||
) : status === 'complete' ? (
|
||||
<div className="i-ph:check"></div>
|
||||
) : status === 'failed' || status === 'aborted' ? (
|
||||
<div className="i-ph:x"></div>
|
||||
) : null}
|
||||
</div>
|
||||
{type === 'file' ? (
|
||||
<div>
|
||||
Create{' '}
|
||||
<code className="bg-bolt-elements-artifacts-inlineCode-background text-bolt-elements-artifacts-inlineCode-text px-1.5 py-1 rounded-md">
|
||||
{action.filePath}
|
||||
</code>
|
||||
</div>
|
||||
) : type === 'shell' ? (
|
||||
<div className="flex items-center w-full min-h-[28px]">
|
||||
<span className="flex-1">Run command</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{type === 'shell' && (
|
||||
<ShellCodeBlock
|
||||
classsName={classNames('mt-1', {
|
||||
'mb-3.5': !isLast,
|
||||
})}
|
||||
code={content}
|
||||
/>
|
||||
)}
|
||||
</motion.li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</motion.div>
|
||||
);
|
||||
});
|
||||
|
||||
function getIconColor(status: ActionState['status']) {
|
||||
switch (status) {
|
||||
case 'pending': {
|
||||
return 'text-bolt-elements-textTertiary';
|
||||
}
|
||||
case 'running': {
|
||||
return 'text-bolt-elements-loader-progress';
|
||||
}
|
||||
case 'complete': {
|
||||
return 'text-bolt-elements-icon-success';
|
||||
}
|
||||
case 'aborted': {
|
||||
return 'text-bolt-elements-textSecondary';
|
||||
}
|
||||
case 'failed': {
|
||||
return 'text-bolt-elements-icon-error';
|
||||
}
|
||||
default: {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
14
app/components/chat/AssistantMessage.tsx
Normal file
14
app/components/chat/AssistantMessage.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import { memo } from 'react';
|
||||
import { Markdown } from './Markdown';
|
||||
|
||||
interface AssistantMessageProps {
|
||||
content: string;
|
||||
}
|
||||
|
||||
export const AssistantMessage = memo(({ content }: AssistantMessageProps) => {
|
||||
return (
|
||||
<div className="overflow-hidden w-full">
|
||||
<Markdown html>{content}</Markdown>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
19
app/components/chat/BaseChat.module.scss
Normal file
19
app/components/chat/BaseChat.module.scss
Normal file
@@ -0,0 +1,19 @@
|
||||
.BaseChat {
|
||||
&[data-chat-visible='false'] {
|
||||
--workbench-inner-width: 100%;
|
||||
--workbench-left: 0;
|
||||
|
||||
.Chat {
|
||||
--at-apply: bolt-ease-cubic-bezier;
|
||||
transition-property: transform, opacity;
|
||||
transition-duration: 0.3s;
|
||||
will-change: transform, opacity;
|
||||
transform: translateX(-50%);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.Chat {
|
||||
opacity: 1;
|
||||
}
|
||||
216
app/components/chat/BaseChat.tsx
Normal file
216
app/components/chat/BaseChat.tsx
Normal file
@@ -0,0 +1,216 @@
|
||||
import type { Message } from 'ai';
|
||||
import React, { type RefCallback } from 'react';
|
||||
import { ClientOnly } from 'remix-utils/client-only';
|
||||
import { Menu } from '~/components/sidebar/Menu.client';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
import { Workbench } from '~/components/workbench/Workbench.client';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { Messages } from './Messages.client';
|
||||
import { SendButton } from './SendButton.client';
|
||||
|
||||
import styles from './BaseChat.module.scss';
|
||||
import { useLoaderData } from '@remix-run/react';
|
||||
|
||||
interface BaseChatProps {
|
||||
textareaRef?: React.RefObject<HTMLTextAreaElement> | undefined;
|
||||
messageRef?: RefCallback<HTMLDivElement> | undefined;
|
||||
scrollRef?: RefCallback<HTMLDivElement> | undefined;
|
||||
showChat?: boolean;
|
||||
chatStarted?: boolean;
|
||||
isStreaming?: boolean;
|
||||
messages?: Message[];
|
||||
enhancingPrompt?: boolean;
|
||||
promptEnhanced?: boolean;
|
||||
input?: string;
|
||||
handleStop?: () => void;
|
||||
sendMessage?: (event: React.UIEvent, messageInput?: string) => void;
|
||||
handleInputChange?: (event: React.ChangeEvent<HTMLTextAreaElement>) => void;
|
||||
enhancePrompt?: () => void;
|
||||
}
|
||||
|
||||
const EXAMPLE_PROMPTS = [
|
||||
{ text: 'Build a todo app in React using Tailwind' },
|
||||
{ text: 'Build a simple blog using Astro' },
|
||||
{ text: 'Create a cookie consent form using Material UI' },
|
||||
{ text: 'Make a space invaders game' },
|
||||
{ text: 'How do I center a div?' },
|
||||
];
|
||||
|
||||
const TEXTAREA_MIN_HEIGHT = 76;
|
||||
|
||||
export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
|
||||
(
|
||||
{
|
||||
textareaRef,
|
||||
messageRef,
|
||||
scrollRef,
|
||||
showChat = true,
|
||||
chatStarted = false,
|
||||
isStreaming = false,
|
||||
enhancingPrompt = false,
|
||||
promptEnhanced = false,
|
||||
messages,
|
||||
input = '',
|
||||
sendMessage,
|
||||
handleInputChange,
|
||||
enhancePrompt,
|
||||
handleStop,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
|
||||
const { avatar } = useLoaderData<{ avatar?: string }>();
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={classNames(
|
||||
styles.BaseChat,
|
||||
'relative flex h-full w-full overflow-hidden bg-bolt-elements-background-depth-1',
|
||||
)}
|
||||
data-chat-visible={showChat}
|
||||
>
|
||||
<ClientOnly>{() => <Menu />}</ClientOnly>
|
||||
<div ref={scrollRef} className="flex overflow-scroll w-full h-full">
|
||||
<div className={classNames(styles.Chat, 'flex flex-col flex-grow min-w-[var(--chat-min-width)] h-full')}>
|
||||
{!chatStarted && (
|
||||
<div id="intro" className="mt-[26vh] max-w-chat mx-auto">
|
||||
<h1 className="text-5xl text-center font-bold text-bolt-elements-textPrimary mb-2">
|
||||
Where ideas begin
|
||||
</h1>
|
||||
<p className="mb-4 text-center text-bolt-elements-textSecondary">
|
||||
Bring ideas to life in seconds or get help on existing projects.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={classNames('pt-6 px-6', {
|
||||
'h-full flex flex-col': chatStarted,
|
||||
})}
|
||||
>
|
||||
<ClientOnly>
|
||||
{() => {
|
||||
return chatStarted ? (
|
||||
<Messages
|
||||
ref={messageRef}
|
||||
className="flex flex-col w-full flex-1 max-w-chat px-4 pb-6 mx-auto z-1"
|
||||
messages={messages}
|
||||
isStreaming={isStreaming}
|
||||
avatar={avatar}
|
||||
/>
|
||||
) : null;
|
||||
}}
|
||||
</ClientOnly>
|
||||
<div
|
||||
className={classNames('relative w-full max-w-chat mx-auto z-prompt', {
|
||||
'sticky bottom-0': chatStarted,
|
||||
})}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
'shadow-sm border border-bolt-elements-borderColor bg-bolt-elements-prompt-background backdrop-filter backdrop-blur-[8px] rounded-lg overflow-hidden',
|
||||
)}
|
||||
>
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className={`w-full pl-4 pt-4 pr-16 focus:outline-none resize-none text-md text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary bg-transparent`}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
if (event.shiftKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
sendMessage?.(event);
|
||||
}
|
||||
}}
|
||||
value={input}
|
||||
onChange={(event) => {
|
||||
handleInputChange?.(event);
|
||||
}}
|
||||
style={{
|
||||
minHeight: TEXTAREA_MIN_HEIGHT,
|
||||
maxHeight: TEXTAREA_MAX_HEIGHT,
|
||||
}}
|
||||
placeholder="How can Bolt help you today?"
|
||||
translate="no"
|
||||
/>
|
||||
<ClientOnly>
|
||||
{() => (
|
||||
<SendButton
|
||||
show={input.length > 0 || isStreaming}
|
||||
isStreaming={isStreaming}
|
||||
onClick={(event) => {
|
||||
if (isStreaming) {
|
||||
handleStop?.();
|
||||
return;
|
||||
}
|
||||
|
||||
sendMessage?.(event);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</ClientOnly>
|
||||
<div className="flex justify-between text-sm p-4 pt-2">
|
||||
<div className="flex gap-1 items-center">
|
||||
<IconButton
|
||||
title="Enhance prompt"
|
||||
disabled={input.length === 0 || enhancingPrompt}
|
||||
className={classNames({
|
||||
'opacity-100!': enhancingPrompt,
|
||||
'text-bolt-elements-item-contentAccent! pr-1.5 enabled:hover:bg-bolt-elements-item-backgroundAccent!':
|
||||
promptEnhanced,
|
||||
})}
|
||||
onClick={() => enhancePrompt?.()}
|
||||
>
|
||||
{enhancingPrompt ? (
|
||||
<>
|
||||
<div className="i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress text-xl"></div>
|
||||
<div className="ml-1.5">Enhancing prompt...</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-bolt:stars text-xl"></div>
|
||||
{promptEnhanced && <div className="ml-1.5">Prompt enhanced</div>}
|
||||
</>
|
||||
)}
|
||||
</IconButton>
|
||||
</div>
|
||||
{input.length > 3 ? (
|
||||
<div className="text-xs text-bolt-elements-textTertiary">
|
||||
Use <kbd className="kdb">Shift</kbd> + <kbd className="kdb">Return</kbd> for a new line
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-bolt-elements-background-depth-1 pb-6">{/* Ghost Element */}</div>
|
||||
</div>
|
||||
</div>
|
||||
{!chatStarted && (
|
||||
<div id="examples" className="relative w-full max-w-xl mx-auto mt-8 flex justify-center">
|
||||
<div className="flex flex-col space-y-2 [mask-image:linear-gradient(to_bottom,black_0%,transparent_180%)] hover:[mask-image:none]">
|
||||
{EXAMPLE_PROMPTS.map((examplePrompt, index) => {
|
||||
return (
|
||||
<button
|
||||
key={index}
|
||||
onClick={(event) => {
|
||||
sendMessage?.(event, examplePrompt.text);
|
||||
}}
|
||||
className="group flex items-center w-full gap-2 justify-center bg-transparent text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary transition-theme"
|
||||
>
|
||||
{examplePrompt.text}
|
||||
<div className="i-ph:arrow-bend-down-left" />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<ClientOnly>{() => <Workbench chatStarted={chatStarted} isStreaming={isStreaming} />}</ClientOnly>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
234
app/components/chat/Chat.client.tsx
Normal file
234
app/components/chat/Chat.client.tsx
Normal file
@@ -0,0 +1,234 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import type { Message } from 'ai';
|
||||
import { useChat } from 'ai/react';
|
||||
import { useAnimate } from 'framer-motion';
|
||||
import { memo, useEffect, useRef, useState } from 'react';
|
||||
import { cssTransition, toast, ToastContainer } from 'react-toastify';
|
||||
import { useMessageParser, usePromptEnhancer, useShortcuts, useSnapScroll } from '~/lib/hooks';
|
||||
import { useChatHistory } from '~/lib/persistence';
|
||||
import { chatStore } from '~/lib/stores/chat';
|
||||
import { workbenchStore } from '~/lib/stores/workbench';
|
||||
import { fileModificationsToHTML } from '~/utils/diff';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
import { createScopedLogger, renderLogger } from '~/utils/logger';
|
||||
import { BaseChat } from './BaseChat';
|
||||
|
||||
const toastAnimation = cssTransition({
|
||||
enter: 'animated fadeInRight',
|
||||
exit: 'animated fadeOutRight',
|
||||
});
|
||||
|
||||
const logger = createScopedLogger('Chat');
|
||||
|
||||
export function Chat() {
|
||||
renderLogger.trace('Chat');
|
||||
|
||||
const { ready, initialMessages, storeMessageHistory } = useChatHistory();
|
||||
|
||||
return (
|
||||
<>
|
||||
{ready && <ChatImpl initialMessages={initialMessages} storeMessageHistory={storeMessageHistory} />}
|
||||
<ToastContainer
|
||||
closeButton={({ closeToast }) => {
|
||||
return (
|
||||
<button className="Toastify__close-button" onClick={closeToast}>
|
||||
<div className="i-ph:x text-lg" />
|
||||
</button>
|
||||
);
|
||||
}}
|
||||
icon={({ type }) => {
|
||||
/**
|
||||
* @todo Handle more types if we need them. This may require extra color palettes.
|
||||
*/
|
||||
switch (type) {
|
||||
case 'success': {
|
||||
return <div className="i-ph:check-bold text-bolt-elements-icon-success text-2xl" />;
|
||||
}
|
||||
case 'error': {
|
||||
return <div className="i-ph:warning-circle-bold text-bolt-elements-icon-error text-2xl" />;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}}
|
||||
position="bottom-right"
|
||||
pauseOnFocusLoss
|
||||
transition={toastAnimation}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface ChatProps {
|
||||
initialMessages: Message[];
|
||||
storeMessageHistory: (messages: Message[]) => Promise<void>;
|
||||
}
|
||||
|
||||
export const ChatImpl = memo(({ initialMessages, storeMessageHistory }: ChatProps) => {
|
||||
useShortcuts();
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const [chatStarted, setChatStarted] = useState(initialMessages.length > 0);
|
||||
|
||||
const { showChat } = useStore(chatStore);
|
||||
|
||||
const [animationScope, animate] = useAnimate();
|
||||
|
||||
const { messages, isLoading, input, handleInputChange, setInput, stop, append } = useChat({
|
||||
api: '/api/chat',
|
||||
onError: (error) => {
|
||||
logger.error('Request failed\n\n', error);
|
||||
toast.error('There was an error processing your request');
|
||||
},
|
||||
onFinish: () => {
|
||||
logger.debug('Finished streaming');
|
||||
},
|
||||
initialMessages,
|
||||
});
|
||||
|
||||
const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
|
||||
const { parsedMessages, parseMessages } = useMessageParser();
|
||||
|
||||
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
|
||||
|
||||
useEffect(() => {
|
||||
chatStore.setKey('started', initialMessages.length > 0);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
parseMessages(messages, isLoading);
|
||||
|
||||
if (messages.length > initialMessages.length) {
|
||||
storeMessageHistory(messages).catch((error) => toast.error(error.message));
|
||||
}
|
||||
}, [messages, isLoading, parseMessages]);
|
||||
|
||||
const scrollTextArea = () => {
|
||||
const textarea = textareaRef.current;
|
||||
|
||||
if (textarea) {
|
||||
textarea.scrollTop = textarea.scrollHeight;
|
||||
}
|
||||
};
|
||||
|
||||
const abort = () => {
|
||||
stop();
|
||||
chatStore.setKey('aborted', true);
|
||||
workbenchStore.abortAllActions();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const textarea = textareaRef.current;
|
||||
|
||||
if (textarea) {
|
||||
textarea.style.height = 'auto';
|
||||
|
||||
const scrollHeight = textarea.scrollHeight;
|
||||
|
||||
textarea.style.height = `${Math.min(scrollHeight, TEXTAREA_MAX_HEIGHT)}px`;
|
||||
textarea.style.overflowY = scrollHeight > TEXTAREA_MAX_HEIGHT ? 'auto' : 'hidden';
|
||||
}
|
||||
}, [input, textareaRef]);
|
||||
|
||||
const runAnimation = async () => {
|
||||
if (chatStarted) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
animate('#examples', { opacity: 0, display: 'none' }, { duration: 0.1 }),
|
||||
animate('#intro', { opacity: 0, flex: 1 }, { duration: 0.2, ease: cubicEasingFn }),
|
||||
]);
|
||||
|
||||
chatStore.setKey('started', true);
|
||||
|
||||
setChatStarted(true);
|
||||
};
|
||||
|
||||
const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
|
||||
const _input = messageInput || input;
|
||||
|
||||
if (_input.length === 0 || isLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* @note (delm) Usually saving files shouldn't take long but it may take longer if there
|
||||
* many unsaved files. In that case we need to block user input and show an indicator
|
||||
* of some kind so the user is aware that something is happening. But I consider the
|
||||
* happy case to be no unsaved files and I would expect users to save their changes
|
||||
* before they send another message.
|
||||
*/
|
||||
await workbenchStore.saveAllFiles();
|
||||
|
||||
const fileModifications = workbenchStore.getFileModifcations();
|
||||
|
||||
chatStore.setKey('aborted', false);
|
||||
|
||||
runAnimation();
|
||||
|
||||
if (fileModifications !== undefined) {
|
||||
const diff = fileModificationsToHTML(fileModifications);
|
||||
|
||||
/**
|
||||
* If we have file modifications we append a new user message manually since we have to prefix
|
||||
* the user input with the file modifications and we don't want the new user input to appear
|
||||
* in the prompt. Using `append` is almost the same as `handleSubmit` except that we have to
|
||||
* manually reset the input and we'd have to manually pass in file attachments. However, those
|
||||
* aren't relevant here.
|
||||
*/
|
||||
append({ role: 'user', content: `${diff}\n\n${_input}` });
|
||||
|
||||
/**
|
||||
* After sending a new message we reset all modifications since the model
|
||||
* should now be aware of all the changes.
|
||||
*/
|
||||
workbenchStore.resetAllFileModifications();
|
||||
} else {
|
||||
append({ role: 'user', content: _input });
|
||||
}
|
||||
|
||||
setInput('');
|
||||
|
||||
resetEnhancer();
|
||||
|
||||
textareaRef.current?.blur();
|
||||
};
|
||||
|
||||
const [messageRef, scrollRef] = useSnapScroll();
|
||||
|
||||
return (
|
||||
<BaseChat
|
||||
ref={animationScope}
|
||||
textareaRef={textareaRef}
|
||||
input={input}
|
||||
showChat={showChat}
|
||||
chatStarted={chatStarted}
|
||||
isStreaming={isLoading}
|
||||
enhancingPrompt={enhancingPrompt}
|
||||
promptEnhanced={promptEnhanced}
|
||||
sendMessage={sendMessage}
|
||||
messageRef={messageRef}
|
||||
scrollRef={scrollRef}
|
||||
handleInputChange={handleInputChange}
|
||||
handleStop={abort}
|
||||
messages={messages.map((message, i) => {
|
||||
if (message.role === 'user') {
|
||||
return message;
|
||||
}
|
||||
|
||||
return {
|
||||
...message,
|
||||
content: parsedMessages[i] || '',
|
||||
};
|
||||
})}
|
||||
enhancePrompt={() => {
|
||||
enhancePrompt(input, (input) => {
|
||||
setInput(input);
|
||||
scrollTextArea();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
});
|
||||
10
app/components/chat/CodeBlock.module.scss
Normal file
10
app/components/chat/CodeBlock.module.scss
Normal file
@@ -0,0 +1,10 @@
|
||||
.CopyButtonContainer {
|
||||
button:before {
|
||||
content: 'Copied';
|
||||
font-size: 12px;
|
||||
position: absolute;
|
||||
left: -53px;
|
||||
padding: 2px 6px;
|
||||
height: 30px;
|
||||
}
|
||||
}
|
||||
82
app/components/chat/CodeBlock.tsx
Normal file
82
app/components/chat/CodeBlock.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import { memo, useEffect, useState } from 'react';
|
||||
import { bundledLanguages, codeToHtml, isSpecialLang, type BundledLanguage, type SpecialLanguage } from 'shiki';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
|
||||
import styles from './CodeBlock.module.scss';
|
||||
|
||||
const logger = createScopedLogger('CodeBlock');
|
||||
|
||||
interface CodeBlockProps {
|
||||
className?: string;
|
||||
code: string;
|
||||
language?: BundledLanguage | SpecialLanguage;
|
||||
theme?: 'light-plus' | 'dark-plus';
|
||||
disableCopy?: boolean;
|
||||
}
|
||||
|
||||
export const CodeBlock = memo(
|
||||
({ className, code, language = 'plaintext', theme = 'dark-plus', disableCopy = false }: CodeBlockProps) => {
|
||||
const [html, setHTML] = useState<string | undefined>(undefined);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const copyToClipboard = () => {
|
||||
if (copied) {
|
||||
return;
|
||||
}
|
||||
|
||||
navigator.clipboard.writeText(code);
|
||||
|
||||
setCopied(true);
|
||||
|
||||
setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (language && !isSpecialLang(language) && !(language in bundledLanguages)) {
|
||||
logger.warn(`Unsupported language '${language}'`);
|
||||
}
|
||||
|
||||
logger.trace(`Language = ${language}`);
|
||||
|
||||
const processCode = async () => {
|
||||
setHTML(await codeToHtml(code, { lang: language, theme }));
|
||||
};
|
||||
|
||||
processCode();
|
||||
}, [code]);
|
||||
|
||||
return (
|
||||
<div className={classNames('relative group text-left', className)}>
|
||||
<div
|
||||
className={classNames(
|
||||
styles.CopyButtonContainer,
|
||||
'bg-white absolute top-[10px] right-[10px] rounded-md z-10 text-lg flex items-center justify-center opacity-0 group-hover:opacity-100',
|
||||
{
|
||||
'rounded-l-0 opacity-100': copied,
|
||||
},
|
||||
)}
|
||||
>
|
||||
{!disableCopy && (
|
||||
<button
|
||||
className={classNames(
|
||||
'flex items-center bg-transparent p-[6px] justify-center before:bg-white before:rounded-l-md before:text-gray-500 before:border-r before:border-gray-300',
|
||||
{
|
||||
'before:opacity-0': !copied,
|
||||
'before:opacity-100': copied,
|
||||
},
|
||||
)}
|
||||
title="Copy Code"
|
||||
onClick={() => copyToClipboard()}
|
||||
>
|
||||
<div className="i-ph:clipboard-text-duotone"></div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div dangerouslySetInnerHTML={{ __html: html ?? '' }}></div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
171
app/components/chat/Markdown.module.scss
Normal file
171
app/components/chat/Markdown.module.scss
Normal file
@@ -0,0 +1,171 @@
|
||||
$font-mono: ui-monospace, 'Fira Code', Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
|
||||
$code-font-size: 13px;
|
||||
|
||||
@mixin not-inside-actions {
|
||||
&:not(:has(:global(.actions)), :global(.actions *)) {
|
||||
@content;
|
||||
}
|
||||
}
|
||||
|
||||
.MarkdownContent {
|
||||
line-height: 1.6;
|
||||
color: var(--bolt-elements-textPrimary);
|
||||
|
||||
> *:not(:last-child) {
|
||||
margin-block-end: 16px;
|
||||
}
|
||||
|
||||
:global(.artifact) {
|
||||
margin: 1.5em 0;
|
||||
}
|
||||
|
||||
:is(h1, h2, h3, h4, h5, h6) {
|
||||
@include not-inside-actions {
|
||||
margin-block-start: 24px;
|
||||
margin-block-end: 16px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
color: var(--bolt-elements-textPrimary);
|
||||
}
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 2em;
|
||||
border-bottom: 1px solid var(--bolt-elements-borderColor);
|
||||
padding-bottom: 0.3em;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.5em;
|
||||
border-bottom: 1px solid var(--bolt-elements-borderColor);
|
||||
padding-bottom: 0.3em;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.25em;
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
h5 {
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
h6 {
|
||||
font-size: 0.85em;
|
||||
color: #6a737d;
|
||||
}
|
||||
|
||||
p {
|
||||
white-space: pre-wrap;
|
||||
|
||||
&:not(:last-of-type) {
|
||||
margin-block-start: 0;
|
||||
margin-block-end: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--bolt-elements-messages-linkColor);
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
:not(pre) > code {
|
||||
font-family: $font-mono;
|
||||
font-size: $code-font-size;
|
||||
|
||||
@include not-inside-actions {
|
||||
border-radius: 6px;
|
||||
padding: 0.2em 0.4em;
|
||||
background-color: var(--bolt-elements-messages-inlineCode-background);
|
||||
color: var(--bolt-elements-messages-inlineCode-text);
|
||||
}
|
||||
}
|
||||
|
||||
pre {
|
||||
padding: 20px 16px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
pre:has(> code) {
|
||||
font-family: $font-mono;
|
||||
font-size: $code-font-size;
|
||||
background: transparent;
|
||||
overflow-x: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
margin: 0;
|
||||
padding: 0 1em;
|
||||
color: var(--bolt-elements-textTertiary);
|
||||
border-left: 0.25em solid var(--bolt-elements-borderColor);
|
||||
}
|
||||
|
||||
:is(ul, ol) {
|
||||
@include not-inside-actions {
|
||||
padding-left: 2em;
|
||||
margin-block-start: 0;
|
||||
margin-block-end: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
ul {
|
||||
@include not-inside-actions {
|
||||
list-style-type: disc;
|
||||
}
|
||||
}
|
||||
|
||||
ol {
|
||||
@include not-inside-actions {
|
||||
list-style-type: decimal;
|
||||
}
|
||||
}
|
||||
|
||||
li {
|
||||
@include not-inside-actions {
|
||||
& + li {
|
||||
margin-block-start: 8px;
|
||||
}
|
||||
|
||||
> *:not(:last-child) {
|
||||
margin-block-end: 16px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
hr {
|
||||
height: 0.25em;
|
||||
padding: 0;
|
||||
margin: 24px 0;
|
||||
background-color: var(--bolt-elements-borderColor);
|
||||
border: 0;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin-block-end: 16px;
|
||||
|
||||
:is(th, td) {
|
||||
padding: 6px 13px;
|
||||
border: 1px solid #dfe2e5;
|
||||
}
|
||||
|
||||
tr:nth-child(2n) {
|
||||
background-color: #f6f8fa;
|
||||
}
|
||||
}
|
||||
}
|
||||
74
app/components/chat/Markdown.tsx
Normal file
74
app/components/chat/Markdown.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
import { memo, useMemo } from 'react';
|
||||
import ReactMarkdown, { type Components } from 'react-markdown';
|
||||
import type { BundledLanguage } from 'shiki';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
import { rehypePlugins, remarkPlugins, allowedHTMLElements } from '~/utils/markdown';
|
||||
import { Artifact } from './Artifact';
|
||||
import { CodeBlock } from './CodeBlock';
|
||||
|
||||
import styles from './Markdown.module.scss';
|
||||
|
||||
const logger = createScopedLogger('MarkdownComponent');
|
||||
|
||||
interface MarkdownProps {
|
||||
children: string;
|
||||
html?: boolean;
|
||||
limitedMarkdown?: boolean;
|
||||
}
|
||||
|
||||
export const Markdown = memo(({ children, html = false, limitedMarkdown = false }: MarkdownProps) => {
|
||||
logger.trace('Render');
|
||||
|
||||
const components = useMemo(() => {
|
||||
return {
|
||||
div: ({ className, children, node, ...props }) => {
|
||||
if (className?.includes('__boltArtifact__')) {
|
||||
const messageId = node?.properties.dataMessageId as string;
|
||||
|
||||
if (!messageId) {
|
||||
logger.error(`Invalid message id ${messageId}`);
|
||||
}
|
||||
|
||||
return <Artifact messageId={messageId} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={className} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
pre: (props) => {
|
||||
const { children, node, ...rest } = props;
|
||||
|
||||
const [firstChild] = node?.children ?? [];
|
||||
|
||||
if (
|
||||
firstChild &&
|
||||
firstChild.type === 'element' &&
|
||||
firstChild.tagName === 'code' &&
|
||||
firstChild.children[0].type === 'text'
|
||||
) {
|
||||
const { className, ...rest } = firstChild.properties;
|
||||
const [, language = 'plaintext'] = /language-(\w+)/.exec(String(className) || '') ?? [];
|
||||
|
||||
return <CodeBlock code={firstChild.children[0].value} language={language as BundledLanguage} {...rest} />;
|
||||
}
|
||||
|
||||
return <pre {...rest}>{children}</pre>;
|
||||
},
|
||||
} satisfies Components;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ReactMarkdown
|
||||
allowedElements={allowedHTMLElements}
|
||||
className={styles.MarkdownContent}
|
||||
components={components}
|
||||
remarkPlugins={remarkPlugins(limitedMarkdown)}
|
||||
rehypePlugins={rehypePlugins(html)}
|
||||
>
|
||||
{children}
|
||||
</ReactMarkdown>
|
||||
);
|
||||
});
|
||||
58
app/components/chat/Messages.client.tsx
Normal file
58
app/components/chat/Messages.client.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import type { Message } from 'ai';
|
||||
import React from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { AssistantMessage } from './AssistantMessage';
|
||||
import { UserMessage } from './UserMessage';
|
||||
|
||||
interface MessagesProps {
|
||||
id?: string;
|
||||
className?: string;
|
||||
isStreaming?: boolean;
|
||||
messages?: Message[];
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export const Messages = React.forwardRef<HTMLDivElement, MessagesProps>((props: MessagesProps, ref) => {
|
||||
const { id, isStreaming = false, messages = [], avatar } = props;
|
||||
|
||||
return (
|
||||
<div id={id} ref={ref} className={props.className}>
|
||||
{messages.length > 0
|
||||
? messages.map((message, index) => {
|
||||
const { role, content } = message;
|
||||
const isUserMessage = role === 'user';
|
||||
const isFirst = index === 0;
|
||||
const isLast = index === messages.length - 1;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={classNames('flex gap-4 p-6 w-full rounded-[calc(0.75rem-1px)]', {
|
||||
'bg-bolt-elements-messages-background': isUserMessage || !isStreaming || (isStreaming && !isLast),
|
||||
'bg-gradient-to-b from-bolt-elements-messages-background from-30% to-transparent':
|
||||
isStreaming && isLast,
|
||||
'mt-4': !isFirst,
|
||||
})}
|
||||
>
|
||||
{isUserMessage && (
|
||||
<div className="flex items-center justify-center w-[34px] h-[34px] overflow-hidden bg-white text-gray-600 rounded-full shrink-0 self-start">
|
||||
{avatar ? (
|
||||
<img className="w-full h-full object-cover" src={avatar} />
|
||||
) : (
|
||||
<div className="i-ph:user-fill text-xl"></div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-col-1 w-full">
|
||||
{isUserMessage ? <UserMessage content={content} /> : <AssistantMessage content={content} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
: null}
|
||||
{isStreaming && (
|
||||
<div className="text-center w-full text-bolt-elements-textSecondary i-svg-spinners:3-dots-fade text-4xl mt-4"></div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
33
app/components/chat/SendButton.client.tsx
Normal file
33
app/components/chat/SendButton.client.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { AnimatePresence, cubicBezier, motion } from 'framer-motion';
|
||||
|
||||
interface SendButtonProps {
|
||||
show: boolean;
|
||||
isStreaming?: boolean;
|
||||
onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
|
||||
}
|
||||
|
||||
const customEasingFn = cubicBezier(0.4, 0, 0.2, 1);
|
||||
|
||||
export function SendButton({ show, isStreaming, onClick }: SendButtonProps) {
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{show ? (
|
||||
<motion.button
|
||||
className="absolute flex justify-center items-center top-[18px] right-[22px] p-1 bg-accent-500 hover:brightness-94 color-white rounded-md w-[34px] h-[34px] transition-theme"
|
||||
transition={{ ease: customEasingFn, duration: 0.17 }}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 10 }}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
onClick?.(event);
|
||||
}}
|
||||
>
|
||||
<div className="text-lg">
|
||||
{!isStreaming ? <div className="i-ph:arrow-right"></div> : <div className="i-ph:stop-circle-bold"></div>}
|
||||
</div>
|
||||
</motion.button>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
18
app/components/chat/UserMessage.tsx
Normal file
18
app/components/chat/UserMessage.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { modificationsRegex } from '~/utils/diff';
|
||||
import { Markdown } from './Markdown';
|
||||
|
||||
interface UserMessageProps {
|
||||
content: string;
|
||||
}
|
||||
|
||||
export function UserMessage({ content }: UserMessageProps) {
|
||||
return (
|
||||
<div className="overflow-hidden pt-[4px]">
|
||||
<Markdown limitedMarkdown>{sanitizeUserMessage(content)}</Markdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function sanitizeUserMessage(content: string) {
|
||||
return content.replace(modificationsRegex, '').trim();
|
||||
}
|
||||
7
app/components/editor/codemirror/BinaryContent.tsx
Normal file
7
app/components/editor/codemirror/BinaryContent.tsx
Normal file
@@ -0,0 +1,7 @@
|
||||
export function BinaryContent() {
|
||||
return (
|
||||
<div className="flex items-center justify-center absolute inset-0 z-10 text-sm bg-tk-elements-app-backgroundColor text-tk-elements-app-textColor">
|
||||
File format cannot be displayed.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
461
app/components/editor/codemirror/CodeMirrorEditor.tsx
Normal file
461
app/components/editor/codemirror/CodeMirrorEditor.tsx
Normal file
@@ -0,0 +1,461 @@
|
||||
import { acceptCompletion, autocompletion, closeBrackets } from '@codemirror/autocomplete';
|
||||
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands';
|
||||
import { bracketMatching, foldGutter, indentOnInput, indentUnit } from '@codemirror/language';
|
||||
import { searchKeymap } from '@codemirror/search';
|
||||
import { Compartment, EditorSelection, EditorState, StateEffect, StateField, type Extension } from '@codemirror/state';
|
||||
import {
|
||||
drawSelection,
|
||||
dropCursor,
|
||||
EditorView,
|
||||
highlightActiveLine,
|
||||
highlightActiveLineGutter,
|
||||
keymap,
|
||||
lineNumbers,
|
||||
scrollPastEnd,
|
||||
showTooltip,
|
||||
tooltips,
|
||||
type Tooltip,
|
||||
} from '@codemirror/view';
|
||||
import { memo, useEffect, useRef, useState, type MutableRefObject } from 'react';
|
||||
import type { Theme } from '~/types/theme';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { debounce } from '~/utils/debounce';
|
||||
import { createScopedLogger, renderLogger } from '~/utils/logger';
|
||||
import { BinaryContent } from './BinaryContent';
|
||||
import { getTheme, reconfigureTheme } from './cm-theme';
|
||||
import { indentKeyBinding } from './indent';
|
||||
import { getLanguage } from './languages';
|
||||
|
||||
const logger = createScopedLogger('CodeMirrorEditor');
|
||||
|
||||
export interface EditorDocument {
|
||||
value: string;
|
||||
isBinary: boolean;
|
||||
filePath: string;
|
||||
scroll?: ScrollPosition;
|
||||
}
|
||||
|
||||
export interface EditorSettings {
|
||||
fontSize?: string;
|
||||
gutterFontSize?: string;
|
||||
tabSize?: number;
|
||||
}
|
||||
|
||||
type TextEditorDocument = EditorDocument & {
|
||||
value: string;
|
||||
};
|
||||
|
||||
export interface ScrollPosition {
|
||||
top: number;
|
||||
left: number;
|
||||
}
|
||||
|
||||
export interface EditorUpdate {
|
||||
selection: EditorSelection;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export type OnChangeCallback = (update: EditorUpdate) => void;
|
||||
export type OnScrollCallback = (position: ScrollPosition) => void;
|
||||
export type OnSaveCallback = () => void;
|
||||
|
||||
interface Props {
|
||||
theme: Theme;
|
||||
id?: unknown;
|
||||
doc?: EditorDocument;
|
||||
editable?: boolean;
|
||||
debounceChange?: number;
|
||||
debounceScroll?: number;
|
||||
autoFocusOnDocumentChange?: boolean;
|
||||
onChange?: OnChangeCallback;
|
||||
onScroll?: OnScrollCallback;
|
||||
onSave?: OnSaveCallback;
|
||||
className?: string;
|
||||
settings?: EditorSettings;
|
||||
}
|
||||
|
||||
type EditorStates = Map<string, EditorState>;
|
||||
|
||||
const readOnlyTooltipStateEffect = StateEffect.define<boolean>();
|
||||
|
||||
const editableTooltipField = StateField.define<readonly Tooltip[]>({
|
||||
create: () => [],
|
||||
update(_tooltips, transaction) {
|
||||
if (!transaction.state.readOnly) {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const effect of transaction.effects) {
|
||||
if (effect.is(readOnlyTooltipStateEffect) && effect.value) {
|
||||
return getReadOnlyTooltip(transaction.state);
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
},
|
||||
provide: (field) => {
|
||||
return showTooltip.computeN([field], (state) => state.field(field));
|
||||
},
|
||||
});
|
||||
|
||||
const editableStateEffect = StateEffect.define<boolean>();
|
||||
|
||||
const editableStateField = StateField.define<boolean>({
|
||||
create() {
|
||||
return true;
|
||||
},
|
||||
update(value, transaction) {
|
||||
for (const effect of transaction.effects) {
|
||||
if (effect.is(editableStateEffect)) {
|
||||
return effect.value;
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
},
|
||||
});
|
||||
|
||||
export const CodeMirrorEditor = memo(
|
||||
({
|
||||
id,
|
||||
doc,
|
||||
debounceScroll = 100,
|
||||
debounceChange = 150,
|
||||
autoFocusOnDocumentChange = false,
|
||||
editable = true,
|
||||
onScroll,
|
||||
onChange,
|
||||
onSave,
|
||||
theme,
|
||||
settings,
|
||||
className = '',
|
||||
}: Props) => {
|
||||
renderLogger.trace('CodeMirrorEditor');
|
||||
|
||||
const [languageCompartment] = useState(new Compartment());
|
||||
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const viewRef = useRef<EditorView>();
|
||||
const themeRef = useRef<Theme>();
|
||||
const docRef = useRef<EditorDocument>();
|
||||
const editorStatesRef = useRef<EditorStates>();
|
||||
const onScrollRef = useRef(onScroll);
|
||||
const onChangeRef = useRef(onChange);
|
||||
const onSaveRef = useRef(onSave);
|
||||
|
||||
/**
|
||||
* This effect is used to avoid side effects directly in the render function
|
||||
* and instead the refs are updated after each render.
|
||||
*/
|
||||
useEffect(() => {
|
||||
onScrollRef.current = onScroll;
|
||||
onChangeRef.current = onChange;
|
||||
onSaveRef.current = onSave;
|
||||
docRef.current = doc;
|
||||
themeRef.current = theme;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const onUpdate = debounce((update: EditorUpdate) => {
|
||||
onChangeRef.current?.(update);
|
||||
}, debounceChange);
|
||||
|
||||
const view = new EditorView({
|
||||
parent: containerRef.current!,
|
||||
dispatchTransactions(transactions) {
|
||||
const previousSelection = view.state.selection;
|
||||
|
||||
view.update(transactions);
|
||||
|
||||
const newSelection = view.state.selection;
|
||||
|
||||
const selectionChanged =
|
||||
newSelection !== previousSelection &&
|
||||
(newSelection === undefined || previousSelection === undefined || !newSelection.eq(previousSelection));
|
||||
|
||||
if (docRef.current && (transactions.some((transaction) => transaction.docChanged) || selectionChanged)) {
|
||||
onUpdate({
|
||||
selection: view.state.selection,
|
||||
content: view.state.doc.toString(),
|
||||
});
|
||||
|
||||
editorStatesRef.current!.set(docRef.current.filePath, view.state);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
viewRef.current = view;
|
||||
|
||||
return () => {
|
||||
viewRef.current?.destroy();
|
||||
viewRef.current = undefined;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!viewRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
viewRef.current.dispatch({
|
||||
effects: [reconfigureTheme(theme)],
|
||||
});
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
editorStatesRef.current = new Map<string, EditorState>();
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
const editorStates = editorStatesRef.current!;
|
||||
const view = viewRef.current!;
|
||||
const theme = themeRef.current!;
|
||||
|
||||
if (!doc) {
|
||||
const state = newEditorState('', theme, settings, onScrollRef, debounceScroll, onSaveRef, [
|
||||
languageCompartment.of([]),
|
||||
]);
|
||||
|
||||
view.setState(state);
|
||||
|
||||
setNoDocument(view);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (doc.isBinary) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (doc.filePath === '') {
|
||||
logger.warn('File path should not be empty');
|
||||
}
|
||||
|
||||
let state = editorStates.get(doc.filePath);
|
||||
|
||||
if (!state) {
|
||||
state = newEditorState(doc.value, theme, settings, onScrollRef, debounceScroll, onSaveRef, [
|
||||
languageCompartment.of([]),
|
||||
]);
|
||||
|
||||
editorStates.set(doc.filePath, state);
|
||||
}
|
||||
|
||||
view.setState(state);
|
||||
|
||||
setEditorDocument(
|
||||
view,
|
||||
theme,
|
||||
editable,
|
||||
languageCompartment,
|
||||
autoFocusOnDocumentChange,
|
||||
doc as TextEditorDocument,
|
||||
);
|
||||
}, [doc?.value, editable, doc?.filePath, autoFocusOnDocumentChange]);
|
||||
|
||||
return (
|
||||
<div className={classNames('relative h-full', className)}>
|
||||
{doc?.isBinary && <BinaryContent />}
|
||||
<div className="h-full overflow-hidden" ref={containerRef} />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export default CodeMirrorEditor;
|
||||
|
||||
CodeMirrorEditor.displayName = 'CodeMirrorEditor';
|
||||
|
||||
function newEditorState(
|
||||
content: string,
|
||||
theme: Theme,
|
||||
settings: EditorSettings | undefined,
|
||||
onScrollRef: MutableRefObject<OnScrollCallback | undefined>,
|
||||
debounceScroll: number,
|
||||
onFileSaveRef: MutableRefObject<OnSaveCallback | undefined>,
|
||||
extensions: Extension[],
|
||||
) {
|
||||
return EditorState.create({
|
||||
doc: content,
|
||||
extensions: [
|
||||
EditorView.domEventHandlers({
|
||||
scroll: debounce((event, view) => {
|
||||
if (event.target !== view.scrollDOM) {
|
||||
return;
|
||||
}
|
||||
|
||||
onScrollRef.current?.({ left: view.scrollDOM.scrollLeft, top: view.scrollDOM.scrollTop });
|
||||
}, debounceScroll),
|
||||
keydown: (event, view) => {
|
||||
if (view.state.readOnly) {
|
||||
view.dispatch({
|
||||
effects: [readOnlyTooltipStateEffect.of(event.key !== 'Escape')],
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
}),
|
||||
getTheme(theme, settings),
|
||||
history(),
|
||||
keymap.of([
|
||||
...defaultKeymap,
|
||||
...historyKeymap,
|
||||
...searchKeymap,
|
||||
{ key: 'Tab', run: acceptCompletion },
|
||||
{
|
||||
key: 'Mod-s',
|
||||
preventDefault: true,
|
||||
run: () => {
|
||||
onFileSaveRef.current?.();
|
||||
return true;
|
||||
},
|
||||
},
|
||||
indentKeyBinding,
|
||||
]),
|
||||
indentUnit.of('\t'),
|
||||
autocompletion({
|
||||
closeOnBlur: false,
|
||||
}),
|
||||
tooltips({
|
||||
position: 'absolute',
|
||||
parent: document.body,
|
||||
tooltipSpace: (view) => {
|
||||
const rect = view.dom.getBoundingClientRect();
|
||||
|
||||
return {
|
||||
top: rect.top - 50,
|
||||
left: rect.left,
|
||||
bottom: rect.bottom,
|
||||
right: rect.right + 10,
|
||||
};
|
||||
},
|
||||
}),
|
||||
closeBrackets(),
|
||||
lineNumbers(),
|
||||
scrollPastEnd(),
|
||||
dropCursor(),
|
||||
drawSelection(),
|
||||
bracketMatching(),
|
||||
EditorState.tabSize.of(settings?.tabSize ?? 2),
|
||||
indentOnInput(),
|
||||
editableTooltipField,
|
||||
editableStateField,
|
||||
EditorState.readOnly.from(editableStateField, (editable) => !editable),
|
||||
highlightActiveLineGutter(),
|
||||
highlightActiveLine(),
|
||||
foldGutter({
|
||||
markerDOM: (open) => {
|
||||
const icon = document.createElement('div');
|
||||
|
||||
icon.className = `fold-icon ${open ? 'i-ph-caret-down-bold' : 'i-ph-caret-right-bold'}`;
|
||||
|
||||
return icon;
|
||||
},
|
||||
}),
|
||||
...extensions,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
function setNoDocument(view: EditorView) {
|
||||
view.dispatch({
|
||||
selection: { anchor: 0 },
|
||||
changes: {
|
||||
from: 0,
|
||||
to: view.state.doc.length,
|
||||
insert: '',
|
||||
},
|
||||
});
|
||||
|
||||
view.scrollDOM.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
function setEditorDocument(
|
||||
view: EditorView,
|
||||
theme: Theme,
|
||||
editable: boolean,
|
||||
languageCompartment: Compartment,
|
||||
autoFocus: boolean,
|
||||
doc: TextEditorDocument,
|
||||
) {
|
||||
if (doc.value !== view.state.doc.toString()) {
|
||||
view.dispatch({
|
||||
selection: { anchor: 0 },
|
||||
changes: {
|
||||
from: 0,
|
||||
to: view.state.doc.length,
|
||||
insert: doc.value,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
view.dispatch({
|
||||
effects: [editableStateEffect.of(editable && !doc.isBinary)],
|
||||
});
|
||||
|
||||
getLanguage(doc.filePath).then((languageSupport) => {
|
||||
if (!languageSupport) {
|
||||
return;
|
||||
}
|
||||
|
||||
view.dispatch({
|
||||
effects: [languageCompartment.reconfigure([languageSupport]), reconfigureTheme(theme)],
|
||||
});
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const currentLeft = view.scrollDOM.scrollLeft;
|
||||
const currentTop = view.scrollDOM.scrollTop;
|
||||
const newLeft = doc.scroll?.left ?? 0;
|
||||
const newTop = doc.scroll?.top ?? 0;
|
||||
|
||||
const needsScrolling = currentLeft !== newLeft || currentTop !== newTop;
|
||||
|
||||
if (autoFocus && editable) {
|
||||
if (needsScrolling) {
|
||||
// we have to wait until the scroll position was changed before we can set the focus
|
||||
view.scrollDOM.addEventListener(
|
||||
'scroll',
|
||||
() => {
|
||||
view.focus();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
} else {
|
||||
// if the scroll position is still the same we can focus immediately
|
||||
view.focus();
|
||||
}
|
||||
}
|
||||
|
||||
view.scrollDOM.scrollTo(newLeft, newTop);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getReadOnlyTooltip(state: EditorState) {
|
||||
if (!state.readOnly) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return state.selection.ranges
|
||||
.filter((range) => {
|
||||
return range.empty;
|
||||
})
|
||||
.map((range) => {
|
||||
return {
|
||||
pos: range.head,
|
||||
above: true,
|
||||
strictSide: true,
|
||||
arrow: true,
|
||||
create: () => {
|
||||
const divElement = document.createElement('div');
|
||||
divElement.className = 'cm-readonly-tooltip';
|
||||
divElement.textContent = 'Cannot edit file while AI response is being generated';
|
||||
|
||||
return { dom: divElement };
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
192
app/components/editor/codemirror/cm-theme.ts
Normal file
192
app/components/editor/codemirror/cm-theme.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import { Compartment, type Extension } from '@codemirror/state';
|
||||
import { EditorView } from '@codemirror/view';
|
||||
import { vscodeDark, vscodeLight } from '@uiw/codemirror-theme-vscode';
|
||||
import type { Theme } from '~/types/theme.js';
|
||||
import type { EditorSettings } from './CodeMirrorEditor.js';
|
||||
|
||||
export const darkTheme = EditorView.theme({}, { dark: true });
|
||||
export const themeSelection = new Compartment();
|
||||
|
||||
export function getTheme(theme: Theme, settings: EditorSettings = {}): Extension {
|
||||
return [
|
||||
getEditorTheme(settings),
|
||||
theme === 'dark' ? themeSelection.of([getDarkTheme()]) : themeSelection.of([getLightTheme()]),
|
||||
];
|
||||
}
|
||||
|
||||
export function reconfigureTheme(theme: Theme) {
|
||||
return themeSelection.reconfigure(theme === 'dark' ? getDarkTheme() : getLightTheme());
|
||||
}
|
||||
|
||||
function getEditorTheme(settings: EditorSettings) {
|
||||
return EditorView.theme({
|
||||
'&': {
|
||||
fontSize: settings.fontSize ?? '12px',
|
||||
},
|
||||
'&.cm-editor': {
|
||||
height: '100%',
|
||||
background: 'var(--cm-backgroundColor)',
|
||||
color: 'var(--cm-textColor)',
|
||||
},
|
||||
'.cm-cursor': {
|
||||
borderLeft: 'var(--cm-cursor-width) solid var(--cm-cursor-backgroundColor)',
|
||||
},
|
||||
'.cm-scroller': {
|
||||
lineHeight: '1.5',
|
||||
'&:focus-visible': {
|
||||
outline: 'none',
|
||||
},
|
||||
},
|
||||
'.cm-line': {
|
||||
padding: '0 0 0 4px',
|
||||
},
|
||||
'&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {
|
||||
backgroundColor: 'var(--cm-selection-backgroundColorFocused) !important',
|
||||
opacity: 'var(--cm-selection-backgroundOpacityFocused, 0.3)',
|
||||
},
|
||||
'&:not(.cm-focused) > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {
|
||||
backgroundColor: 'var(--cm-selection-backgroundColorBlured)',
|
||||
opacity: 'var(--cm-selection-backgroundOpacityBlured, 0.3)',
|
||||
},
|
||||
'&.cm-focused > .cm-scroller .cm-matchingBracket': {
|
||||
backgroundColor: 'var(--cm-matching-bracket)',
|
||||
},
|
||||
'.cm-activeLine': {
|
||||
background: 'var(--cm-activeLineBackgroundColor)',
|
||||
},
|
||||
'.cm-gutters': {
|
||||
background: 'var(--cm-gutter-backgroundColor)',
|
||||
borderRight: 0,
|
||||
color: 'var(--cm-gutter-textColor)',
|
||||
},
|
||||
'.cm-gutter': {
|
||||
'&.cm-lineNumbers': {
|
||||
fontFamily: 'Roboto Mono, monospace',
|
||||
fontSize: settings.gutterFontSize ?? settings.fontSize ?? '12px',
|
||||
minWidth: '40px',
|
||||
},
|
||||
'& .cm-activeLineGutter': {
|
||||
background: 'transparent',
|
||||
color: 'var(--cm-gutter-activeLineTextColor)',
|
||||
},
|
||||
'&.cm-foldGutter .cm-gutterElement > .fold-icon': {
|
||||
cursor: 'pointer',
|
||||
color: 'var(--cm-foldGutter-textColor)',
|
||||
transform: 'translateY(2px)',
|
||||
'&:hover': {
|
||||
color: 'var(--cm-foldGutter-textColorHover)',
|
||||
},
|
||||
},
|
||||
},
|
||||
'.cm-foldGutter .cm-gutterElement': {
|
||||
padding: '0 4px',
|
||||
},
|
||||
'.cm-tooltip-autocomplete > ul > li': {
|
||||
minHeight: '18px',
|
||||
},
|
||||
'.cm-panel.cm-search label': {
|
||||
marginLeft: '2px',
|
||||
fontSize: '12px',
|
||||
},
|
||||
'.cm-panel.cm-search .cm-button': {
|
||||
fontSize: '12px',
|
||||
},
|
||||
'.cm-panel.cm-search .cm-textfield': {
|
||||
fontSize: '12px',
|
||||
},
|
||||
'.cm-panel.cm-search input[type=checkbox]': {
|
||||
position: 'relative',
|
||||
transform: 'translateY(2px)',
|
||||
marginRight: '4px',
|
||||
},
|
||||
'.cm-panels': {
|
||||
borderColor: 'var(--cm-panels-borderColor)',
|
||||
},
|
||||
'.cm-panels-bottom': {
|
||||
borderTop: '1px solid var(--cm-panels-borderColor)',
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
'.cm-panel.cm-search': {
|
||||
background: 'var(--cm-search-backgroundColor)',
|
||||
color: 'var(--cm-search-textColor)',
|
||||
padding: '8px',
|
||||
},
|
||||
'.cm-search .cm-button': {
|
||||
background: 'var(--cm-search-button-backgroundColor)',
|
||||
borderColor: 'var(--cm-search-button-borderColor)',
|
||||
color: 'var(--cm-search-button-textColor)',
|
||||
borderRadius: '4px',
|
||||
'&:hover': {
|
||||
color: 'var(--cm-search-button-textColorHover)',
|
||||
},
|
||||
'&:focus-visible': {
|
||||
outline: 'none',
|
||||
borderColor: 'var(--cm-search-button-borderColorFocused)',
|
||||
},
|
||||
'&:hover:not(:focus-visible)': {
|
||||
background: 'var(--cm-search-button-backgroundColorHover)',
|
||||
borderColor: 'var(--cm-search-button-borderColorHover)',
|
||||
},
|
||||
'&:hover:focus-visible': {
|
||||
background: 'var(--cm-search-button-backgroundColorHover)',
|
||||
borderColor: 'var(--cm-search-button-borderColorFocused)',
|
||||
},
|
||||
},
|
||||
'.cm-panel.cm-search [name=close]': {
|
||||
top: '6px',
|
||||
right: '6px',
|
||||
padding: '0 6px',
|
||||
fontSize: '1rem',
|
||||
backgroundColor: 'var(--cm-search-closeButton-backgroundColor)',
|
||||
color: 'var(--cm-search-closeButton-textColor)',
|
||||
'&:hover': {
|
||||
'border-radius': '6px',
|
||||
color: 'var(--cm-search-closeButton-textColorHover)',
|
||||
backgroundColor: 'var(--cm-search-closeButton-backgroundColorHover)',
|
||||
},
|
||||
},
|
||||
'.cm-search input': {
|
||||
background: 'var(--cm-search-input-backgroundColor)',
|
||||
borderColor: 'var(--cm-search-input-borderColor)',
|
||||
color: 'var(--cm-search-input-textColor)',
|
||||
outline: 'none',
|
||||
borderRadius: '4px',
|
||||
'&:focus-visible': {
|
||||
borderColor: 'var(--cm-search-input-borderColorFocused)',
|
||||
},
|
||||
},
|
||||
'.cm-tooltip': {
|
||||
background: 'var(--cm-tooltip-backgroundColor)',
|
||||
border: '1px solid transparent',
|
||||
borderColor: 'var(--cm-tooltip-borderColor)',
|
||||
color: 'var(--cm-tooltip-textColor)',
|
||||
},
|
||||
'.cm-tooltip.cm-tooltip-autocomplete ul li[aria-selected]': {
|
||||
background: 'var(--cm-tooltip-backgroundColorSelected)',
|
||||
color: 'var(--cm-tooltip-textColorSelected)',
|
||||
},
|
||||
'.cm-searchMatch': {
|
||||
backgroundColor: 'var(--cm-searchMatch-backgroundColor)',
|
||||
},
|
||||
'.cm-tooltip.cm-readonly-tooltip': {
|
||||
padding: '4px',
|
||||
whiteSpace: 'nowrap',
|
||||
backgroundColor: 'var(--bolt-elements-bg-depth-2)',
|
||||
borderColor: 'var(--bolt-elements-borderColorActive)',
|
||||
'& .cm-tooltip-arrow:before': {
|
||||
borderTopColor: 'var(--bolt-elements-borderColorActive)',
|
||||
},
|
||||
'& .cm-tooltip-arrow:after': {
|
||||
borderTopColor: 'transparent',
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function getLightTheme() {
|
||||
return vscodeLight;
|
||||
}
|
||||
|
||||
function getDarkTheme() {
|
||||
return vscodeDark;
|
||||
}
|
||||
68
app/components/editor/codemirror/indent.ts
Normal file
68
app/components/editor/codemirror/indent.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { indentLess } from '@codemirror/commands';
|
||||
import { indentUnit } from '@codemirror/language';
|
||||
import { EditorSelection, EditorState, Line, type ChangeSpec } from '@codemirror/state';
|
||||
import { EditorView, type KeyBinding } from '@codemirror/view';
|
||||
|
||||
export const indentKeyBinding: KeyBinding = {
|
||||
key: 'Tab',
|
||||
run: indentMore,
|
||||
shift: indentLess,
|
||||
};
|
||||
|
||||
function indentMore({ state, dispatch }: EditorView) {
|
||||
if (state.readOnly) {
|
||||
return false;
|
||||
}
|
||||
|
||||
dispatch(
|
||||
state.update(
|
||||
changeBySelectedLine(state, (from, to, changes) => {
|
||||
changes.push({ from, to, insert: state.facet(indentUnit) });
|
||||
}),
|
||||
{ userEvent: 'input.indent' },
|
||||
),
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function changeBySelectedLine(
|
||||
state: EditorState,
|
||||
cb: (from: number, to: number | undefined, changes: ChangeSpec[], line: Line) => void,
|
||||
) {
|
||||
return state.changeByRange((range) => {
|
||||
const changes: ChangeSpec[] = [];
|
||||
|
||||
const line = state.doc.lineAt(range.from);
|
||||
|
||||
// just insert single indent unit at the current cursor position
|
||||
if (range.from === range.to) {
|
||||
cb(range.from, undefined, changes, line);
|
||||
}
|
||||
// handle the case when multiple characters are selected in a single line
|
||||
else if (range.from < range.to && range.to <= line.to) {
|
||||
cb(range.from, range.to, changes, line);
|
||||
} else {
|
||||
let atLine = -1;
|
||||
|
||||
// handle the case when selection spans multiple lines
|
||||
for (let pos = range.from; pos <= range.to; ) {
|
||||
const line = state.doc.lineAt(pos);
|
||||
|
||||
if (line.number > atLine && (range.empty || range.to > line.from)) {
|
||||
cb(line.from, undefined, changes, line);
|
||||
atLine = line.number;
|
||||
}
|
||||
|
||||
pos = line.to + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const changeSet = state.changes(changes);
|
||||
|
||||
return {
|
||||
changes,
|
||||
range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)),
|
||||
};
|
||||
});
|
||||
}
|
||||
105
app/components/editor/codemirror/languages.ts
Normal file
105
app/components/editor/codemirror/languages.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { LanguageDescription } from '@codemirror/language';
|
||||
|
||||
export const supportedLanguages = [
|
||||
LanguageDescription.of({
|
||||
name: 'TS',
|
||||
extensions: ['ts'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-javascript').then((module) => module.javascript({ typescript: true }));
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'JS',
|
||||
extensions: ['js', 'mjs', 'cjs'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-javascript').then((module) => module.javascript());
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'TSX',
|
||||
extensions: ['tsx'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-javascript').then((module) => module.javascript({ jsx: true, typescript: true }));
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'JSX',
|
||||
extensions: ['jsx'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-javascript').then((module) => module.javascript({ jsx: true }));
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'HTML',
|
||||
extensions: ['html'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-html').then((module) => module.html());
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'CSS',
|
||||
extensions: ['css'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-css').then((module) => module.css());
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'SASS',
|
||||
extensions: ['sass'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-sass').then((module) => module.sass({ indented: true }));
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'SCSS',
|
||||
extensions: ['scss'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-sass').then((module) => module.sass({ indented: false }));
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'JSON',
|
||||
extensions: ['json'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-json').then((module) => module.json());
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'Markdown',
|
||||
extensions: ['md'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-markdown').then((module) => module.markdown());
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'Wasm',
|
||||
extensions: ['wat'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-wast').then((module) => module.wast());
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'Python',
|
||||
extensions: ['py'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-python').then((module) => module.python());
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: 'C++',
|
||||
extensions: ['cpp'],
|
||||
async load() {
|
||||
return import('@codemirror/lang-cpp').then((module) => module.cpp());
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export async function getLanguage(fileName: string) {
|
||||
const languageDescription = LanguageDescription.matchFilename(supportedLanguages, fileName);
|
||||
|
||||
if (languageDescription) {
|
||||
return await languageDescription.load();
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
41
app/components/header/Header.tsx
Normal file
41
app/components/header/Header.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { ClientOnly } from 'remix-utils/client-only';
|
||||
import { chatStore } from '~/lib/stores/chat';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { HeaderActionButtons } from './HeaderActionButtons.client';
|
||||
import { ChatDescription } from '~/lib/persistence/ChatDescription.client';
|
||||
|
||||
export function Header() {
|
||||
const chat = useStore(chatStore);
|
||||
|
||||
return (
|
||||
<header
|
||||
className={classNames(
|
||||
'flex items-center bg-bolt-elements-background-depth-1 p-5 border-b h-[var(--header-height)]',
|
||||
{
|
||||
'border-transparent': !chat.started,
|
||||
'border-bolt-elements-borderColor': chat.started,
|
||||
},
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 z-logo text-bolt-elements-textPrimary cursor-pointer">
|
||||
<div className="i-ph:sidebar-simple-duotone text-xl" />
|
||||
<a href="/" className="text-2xl font-semibold text-accent flex items-center">
|
||||
<span className="i-bolt:logo-text?mask w-[46px] inline-block" />
|
||||
</a>
|
||||
</div>
|
||||
<span className="flex-1 px-4 truncate text-center text-bolt-elements-textPrimary">
|
||||
<ClientOnly>{() => <ChatDescription />}</ClientOnly>
|
||||
</span>
|
||||
{chat.started && (
|
||||
<ClientOnly>
|
||||
{() => (
|
||||
<div className="mr-1">
|
||||
<HeaderActionButtons />
|
||||
</div>
|
||||
)}
|
||||
</ClientOnly>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
68
app/components/header/HeaderActionButtons.client.tsx
Normal file
68
app/components/header/HeaderActionButtons.client.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { chatStore } from '~/lib/stores/chat';
|
||||
import { workbenchStore } from '~/lib/stores/workbench';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface HeaderActionButtonsProps {}
|
||||
|
||||
export function HeaderActionButtons({}: HeaderActionButtonsProps) {
|
||||
const showWorkbench = useStore(workbenchStore.showWorkbench);
|
||||
const { showChat } = useStore(chatStore);
|
||||
|
||||
const canHideChat = showWorkbench || !showChat;
|
||||
|
||||
return (
|
||||
<div className="flex">
|
||||
<div className="flex border border-bolt-elements-borderColor rounded-md overflow-hidden">
|
||||
<Button
|
||||
active={showChat}
|
||||
disabled={!canHideChat}
|
||||
onClick={() => {
|
||||
if (canHideChat) {
|
||||
chatStore.setKey('showChat', !showChat);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="i-bolt:chat text-sm" />
|
||||
</Button>
|
||||
<div className="w-[1px] bg-bolt-elements-borderColor" />
|
||||
<Button
|
||||
active={showWorkbench}
|
||||
onClick={() => {
|
||||
if (showWorkbench && !showChat) {
|
||||
chatStore.setKey('showChat', true);
|
||||
}
|
||||
|
||||
workbenchStore.showWorkbench.set(!showWorkbench);
|
||||
}}
|
||||
>
|
||||
<div className="i-ph:code-bold" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ButtonProps {
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
children?: any;
|
||||
onClick?: VoidFunction;
|
||||
}
|
||||
|
||||
function Button({ active = false, disabled = false, children, onClick }: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
className={classNames('flex items-center p-1.5', {
|
||||
'bg-bolt-elements-item-backgroundDefault hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary':
|
||||
!active,
|
||||
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent': active && !disabled,
|
||||
'bg-bolt-elements-item-backgroundDefault text-alpha-gray-20 dark:text-alpha-white-20 cursor-not-allowed':
|
||||
disabled,
|
||||
})}
|
||||
onClick={onClick}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
64
app/components/sidebar/HistoryItem.tsx
Normal file
64
app/components/sidebar/HistoryItem.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import * as Dialog from '@radix-ui/react-dialog';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { type ChatHistoryItem } from '~/lib/persistence';
|
||||
|
||||
interface HistoryItemProps {
|
||||
item: ChatHistoryItem;
|
||||
onDelete?: (event: React.UIEvent) => void;
|
||||
}
|
||||
|
||||
export function HistoryItem({ item, onDelete }: HistoryItemProps) {
|
||||
const [hovering, setHovering] = useState(false);
|
||||
const hoverRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
|
||||
function mouseEnter() {
|
||||
setHovering(true);
|
||||
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
function mouseLeave() {
|
||||
setHovering(false);
|
||||
}
|
||||
|
||||
hoverRef.current?.addEventListener('mouseenter', mouseEnter);
|
||||
hoverRef.current?.addEventListener('mouseleave', mouseLeave);
|
||||
|
||||
return () => {
|
||||
hoverRef.current?.removeEventListener('mouseenter', mouseEnter);
|
||||
hoverRef.current?.removeEventListener('mouseleave', mouseLeave);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={hoverRef}
|
||||
className="group rounded-md text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary hover:bg-bolt-elements-background-depth-3 overflow-hidden flex justify-between items-center px-2 py-1"
|
||||
>
|
||||
<a href={`/chat/${item.urlId}`} className="flex w-full relative truncate block">
|
||||
{item.description}
|
||||
<div className="absolute right-0 z-1 top-0 bottom-0 bg-gradient-to-l from-bolt-elements-background-depth-2 group-hover:from-bolt-elements-background-depth-3 to-transparent w-10 flex justify-end group-hover:w-15 group-hover:from-45%">
|
||||
{hovering && (
|
||||
<div className="flex items-center p-1 text-bolt-elements-textSecondary hover:text-bolt-elements-item-contentDanger">
|
||||
<Dialog.Trigger asChild>
|
||||
<button
|
||||
className="i-ph:trash scale-110"
|
||||
onClick={(event) => {
|
||||
// we prevent the default so we don't trigger the anchor above
|
||||
event.preventDefault();
|
||||
onDelete?.(event);
|
||||
}}
|
||||
/>
|
||||
</Dialog.Trigger>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
179
app/components/sidebar/Menu.client.tsx
Normal file
179
app/components/sidebar/Menu.client.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
import { motion, type Variants } from 'framer-motion';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { Dialog, DialogButton, DialogDescription, DialogRoot, DialogTitle } from '~/components/ui/Dialog';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
import { ThemeSwitch } from '~/components/ui/ThemeSwitch';
|
||||
import { db, deleteById, getAll, chatId, type ChatHistoryItem } from '~/lib/persistence';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
import { logger } from '~/utils/logger';
|
||||
import { HistoryItem } from './HistoryItem';
|
||||
import { binDates } from './date-binning';
|
||||
|
||||
const menuVariants = {
|
||||
closed: {
|
||||
opacity: 0,
|
||||
visibility: 'hidden',
|
||||
left: '-150px',
|
||||
transition: {
|
||||
duration: 0.2,
|
||||
ease: cubicEasingFn,
|
||||
},
|
||||
},
|
||||
open: {
|
||||
opacity: 1,
|
||||
visibility: 'initial',
|
||||
left: 0,
|
||||
transition: {
|
||||
duration: 0.2,
|
||||
ease: cubicEasingFn,
|
||||
},
|
||||
},
|
||||
} satisfies Variants;
|
||||
|
||||
type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null;
|
||||
|
||||
export function Menu() {
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const [list, setList] = useState<ChatHistoryItem[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [dialogContent, setDialogContent] = useState<DialogContent>(null);
|
||||
|
||||
const loadEntries = useCallback(() => {
|
||||
if (db) {
|
||||
getAll(db)
|
||||
.then((list) => list.filter((item) => item.urlId && item.description))
|
||||
.then(setList)
|
||||
.catch((error) => toast.error(error.message));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const deleteItem = useCallback((event: React.UIEvent, item: ChatHistoryItem) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (db) {
|
||||
deleteById(db, item.id)
|
||||
.then(() => {
|
||||
loadEntries();
|
||||
|
||||
if (chatId.get() === item.id) {
|
||||
// hard page navigation to clear the stores
|
||||
window.location.pathname = '/';
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
toast.error('Failed to delete conversation');
|
||||
logger.error(error);
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
const closeDialog = () => {
|
||||
setDialogContent(null);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
loadEntries();
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
const enterThreshold = 40;
|
||||
const exitThreshold = 40;
|
||||
|
||||
function onMouseMove(event: MouseEvent) {
|
||||
if (event.pageX < enterThreshold) {
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
if (menuRef.current && event.clientX > menuRef.current.getBoundingClientRect().right + exitThreshold) {
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('mousemove', onMouseMove);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('mousemove', onMouseMove);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
ref={menuRef}
|
||||
initial="closed"
|
||||
animate={open ? 'open' : 'closed'}
|
||||
variants={menuVariants}
|
||||
className="flex flex-col side-menu fixed top-0 w-[350px] h-full bg-bolt-elements-background-depth-2 border-r rounded-r-3xl border-bolt-elements-borderColor z-sidebar shadow-xl shadow-bolt-elements-sidebar-dropdownShadow text-sm"
|
||||
>
|
||||
<div className="flex items-center h-[var(--header-height)]">{/* Placeholder */}</div>
|
||||
<div className="flex-1 flex flex-col h-full w-full overflow-hidden">
|
||||
<div className="p-4">
|
||||
<a
|
||||
href="/"
|
||||
className="flex gap-2 items-center bg-bolt-elements-sidebar-buttonBackgroundDefault text-bolt-elements-sidebar-buttonText hover:bg-bolt-elements-sidebar-buttonBackgroundHover rounded-md p-2 transition-theme"
|
||||
>
|
||||
<span className="inline-block i-bolt:chat scale-110" />
|
||||
Start new chat
|
||||
</a>
|
||||
</div>
|
||||
<div className="text-bolt-elements-textPrimary font-medium pl-6 pr-5 my-2">Your Chats</div>
|
||||
<div className="flex-1 overflow-scroll pl-4 pr-5 pb-5">
|
||||
{list.length === 0 && <div className="pl-2 text-bolt-elements-textTertiary">No previous conversations</div>}
|
||||
<DialogRoot open={dialogContent !== null}>
|
||||
{binDates(list).map(({ category, items }) => (
|
||||
<div key={category} className="mt-4 first:mt-0 space-y-1">
|
||||
<div className="text-bolt-elements-textTertiary sticky top-0 z-1 bg-bolt-elements-background-depth-2 pl-2 pt-2 pb-1">
|
||||
{category}
|
||||
</div>
|
||||
{items.map((item) => (
|
||||
<HistoryItem key={item.id} item={item} onDelete={() => setDialogContent({ type: 'delete', item })} />
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<Dialog onBackdrop={closeDialog} onClose={closeDialog}>
|
||||
{dialogContent?.type === 'delete' && (
|
||||
<>
|
||||
<DialogTitle>Delete Chat?</DialogTitle>
|
||||
<DialogDescription asChild>
|
||||
<div>
|
||||
<p>
|
||||
You are about to delete <strong>{dialogContent.item.description}</strong>.
|
||||
</p>
|
||||
<p className="mt-1">Are you sure you want to delete this chat?</p>
|
||||
</div>
|
||||
</DialogDescription>
|
||||
<div className="px-5 pb-4 bg-bolt-elements-background-depth-2 flex gap-2 justify-end">
|
||||
<DialogButton type="secondary" onClick={closeDialog}>
|
||||
Cancel
|
||||
</DialogButton>
|
||||
<DialogButton
|
||||
type="danger"
|
||||
onClick={(event) => {
|
||||
deleteItem(event, dialogContent.item);
|
||||
closeDialog();
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</DialogButton>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Dialog>
|
||||
</DialogRoot>
|
||||
</div>
|
||||
<div className="flex items-center border-t border-bolt-elements-borderColor p-4">
|
||||
<a href="/logout">
|
||||
<IconButton className="p-1.5 gap-1.5">
|
||||
<>
|
||||
Logout <span className="i-ph:sign-out text-lg" />
|
||||
</>
|
||||
</IconButton>
|
||||
</a>
|
||||
<ThemeSwitch className="ml-auto" />
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
59
app/components/sidebar/date-binning.ts
Normal file
59
app/components/sidebar/date-binning.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { format, isAfter, isThisWeek, isThisYear, isToday, isYesterday, subDays } from 'date-fns';
|
||||
import type { ChatHistoryItem } from '~/lib/persistence';
|
||||
|
||||
type Bin = { category: string; items: ChatHistoryItem[] };
|
||||
|
||||
export function binDates(_list: ChatHistoryItem[]) {
|
||||
const list = _list.toSorted((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));
|
||||
|
||||
const binLookup: Record<string, Bin> = {};
|
||||
const bins: Array<Bin> = [];
|
||||
|
||||
list.forEach((item) => {
|
||||
const category = dateCategory(new Date(item.timestamp));
|
||||
|
||||
if (!(category in binLookup)) {
|
||||
const bin = {
|
||||
category,
|
||||
items: [item],
|
||||
};
|
||||
|
||||
binLookup[category] = bin;
|
||||
|
||||
bins.push(bin);
|
||||
} else {
|
||||
binLookup[category].items.push(item);
|
||||
}
|
||||
});
|
||||
|
||||
return bins;
|
||||
}
|
||||
|
||||
function dateCategory(date: Date) {
|
||||
if (isToday(date)) {
|
||||
return 'Today';
|
||||
}
|
||||
|
||||
if (isYesterday(date)) {
|
||||
return 'Yesterday';
|
||||
}
|
||||
|
||||
if (isThisWeek(date)) {
|
||||
// e.g., "Monday"
|
||||
return format(date, 'eeee');
|
||||
}
|
||||
|
||||
const thirtyDaysAgo = subDays(new Date(), 30);
|
||||
|
||||
if (isAfter(date, thirtyDaysAgo)) {
|
||||
return 'Last 30 Days';
|
||||
}
|
||||
|
||||
if (isThisYear(date)) {
|
||||
// e.g., "July"
|
||||
return format(date, 'MMMM');
|
||||
}
|
||||
|
||||
// e.g., "July 2023"
|
||||
return format(date, 'MMMM yyyy');
|
||||
}
|
||||
133
app/components/ui/Dialog.tsx
Normal file
133
app/components/ui/Dialog.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import * as RadixDialog from '@radix-ui/react-dialog';
|
||||
import { motion, type Variants } from 'framer-motion';
|
||||
import React, { memo, type ReactNode } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
import { IconButton } from './IconButton';
|
||||
|
||||
export { Close as DialogClose, Root as DialogRoot } from '@radix-ui/react-dialog';
|
||||
|
||||
const transition = {
|
||||
duration: 0.15,
|
||||
ease: cubicEasingFn,
|
||||
};
|
||||
|
||||
export const dialogBackdropVariants = {
|
||||
closed: {
|
||||
opacity: 0,
|
||||
transition,
|
||||
},
|
||||
open: {
|
||||
opacity: 1,
|
||||
transition,
|
||||
},
|
||||
} satisfies Variants;
|
||||
|
||||
export const dialogVariants = {
|
||||
closed: {
|
||||
x: '-50%',
|
||||
y: '-40%',
|
||||
scale: 0.96,
|
||||
opacity: 0,
|
||||
transition,
|
||||
},
|
||||
open: {
|
||||
x: '-50%',
|
||||
y: '-50%',
|
||||
scale: 1,
|
||||
opacity: 1,
|
||||
transition,
|
||||
},
|
||||
} satisfies Variants;
|
||||
|
||||
interface DialogButtonProps {
|
||||
type: 'primary' | 'secondary' | 'danger';
|
||||
children: ReactNode;
|
||||
onClick?: (event: React.UIEvent) => void;
|
||||
}
|
||||
|
||||
export const DialogButton = memo(({ type, children, onClick }: DialogButtonProps) => {
|
||||
return (
|
||||
<button
|
||||
className={classNames(
|
||||
'inline-flex h-[35px] items-center justify-center rounded-lg px-4 text-sm leading-none focus:outline-none',
|
||||
{
|
||||
'bg-bolt-elements-button-primary-background text-bolt-elements-button-primary-text hover:bg-bolt-elements-button-primary-backgroundHover':
|
||||
type === 'primary',
|
||||
'bg-bolt-elements-button-secondary-background text-bolt-elements-button-secondary-text hover:bg-bolt-elements-button-secondary-backgroundHover':
|
||||
type === 'secondary',
|
||||
'bg-bolt-elements-button-danger-background text-bolt-elements-button-danger-text hover:bg-bolt-elements-button-danger-backgroundHover':
|
||||
type === 'danger',
|
||||
},
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
});
|
||||
|
||||
export const DialogTitle = memo(({ className, children, ...props }: RadixDialog.DialogTitleProps) => {
|
||||
return (
|
||||
<RadixDialog.Title
|
||||
className={classNames(
|
||||
'px-5 py-4 flex items-center justify-between border-b border-bolt-elements-borderColor text-lg font-semibold leading-6 text-bolt-elements-textPrimary',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</RadixDialog.Title>
|
||||
);
|
||||
});
|
||||
|
||||
export const DialogDescription = memo(({ className, children, ...props }: RadixDialog.DialogDescriptionProps) => {
|
||||
return (
|
||||
<RadixDialog.Description
|
||||
className={classNames('px-5 py-4 text-bolt-elements-textPrimary text-md', className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</RadixDialog.Description>
|
||||
);
|
||||
});
|
||||
|
||||
interface DialogProps {
|
||||
children: ReactNode | ReactNode[];
|
||||
className?: string;
|
||||
onBackdrop?: (event: React.UIEvent) => void;
|
||||
onClose?: (event: React.UIEvent) => void;
|
||||
}
|
||||
|
||||
export const Dialog = memo(({ className, children, onBackdrop, onClose }: DialogProps) => {
|
||||
return (
|
||||
<RadixDialog.Portal>
|
||||
<RadixDialog.Overlay onClick={onBackdrop} asChild>
|
||||
<motion.div
|
||||
className="bg-black/50 fixed inset-0 z-max"
|
||||
initial="closed"
|
||||
animate="open"
|
||||
exit="closed"
|
||||
variants={dialogBackdropVariants}
|
||||
/>
|
||||
</RadixDialog.Overlay>
|
||||
<RadixDialog.Content asChild>
|
||||
<motion.div
|
||||
className={classNames(
|
||||
'fixed top-[50%] left-[50%] z-max max-h-[85vh] w-[90vw] max-w-[450px] translate-x-[-50%] translate-y-[-50%] border border-bolt-elements-borderColor rounded-lg bg-bolt-elements-background-depth-2 shadow-lg focus:outline-none overflow-hidden',
|
||||
className,
|
||||
)}
|
||||
initial="closed"
|
||||
animate="open"
|
||||
exit="closed"
|
||||
variants={dialogVariants}
|
||||
>
|
||||
{children}
|
||||
<RadixDialog.Close asChild onClick={onClose}>
|
||||
<IconButton icon="i-ph:x" className="absolute top-[10px] right-[10px]" />
|
||||
</RadixDialog.Close>
|
||||
</motion.div>
|
||||
</RadixDialog.Content>
|
||||
</RadixDialog.Portal>
|
||||
);
|
||||
});
|
||||
77
app/components/ui/IconButton.tsx
Normal file
77
app/components/ui/IconButton.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import { memo } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
type IconSize = 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
|
||||
|
||||
interface BaseIconButtonProps {
|
||||
size?: IconSize;
|
||||
className?: string;
|
||||
iconClassName?: string;
|
||||
disabledClassName?: string;
|
||||
title?: string;
|
||||
disabled?: boolean;
|
||||
onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
|
||||
}
|
||||
|
||||
type IconButtonWithoutChildrenProps = {
|
||||
icon: string;
|
||||
children?: undefined;
|
||||
} & BaseIconButtonProps;
|
||||
|
||||
type IconButtonWithChildrenProps = {
|
||||
icon?: undefined;
|
||||
children: string | JSX.Element | JSX.Element[];
|
||||
} & BaseIconButtonProps;
|
||||
|
||||
type IconButtonProps = IconButtonWithoutChildrenProps | IconButtonWithChildrenProps;
|
||||
|
||||
export const IconButton = memo(
|
||||
({
|
||||
icon,
|
||||
size = 'xl',
|
||||
className,
|
||||
iconClassName,
|
||||
disabledClassName,
|
||||
disabled = false,
|
||||
title,
|
||||
onClick,
|
||||
children,
|
||||
}: IconButtonProps) => {
|
||||
return (
|
||||
<button
|
||||
className={classNames(
|
||||
'flex items-center text-bolt-elements-item-contentDefault bg-transparent enabled:hover:text-bolt-elements-item-contentActive rounded-md p-1 enabled:hover:bg-bolt-elements-item-backgroundActive disabled:cursor-not-allowed',
|
||||
{
|
||||
[classNames('opacity-30', disabledClassName)]: disabled,
|
||||
},
|
||||
className,
|
||||
)}
|
||||
title={title}
|
||||
disabled={disabled}
|
||||
onClick={(event) => {
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
onClick?.(event);
|
||||
}}
|
||||
>
|
||||
{children ? children : <div className={classNames(icon, getIconSize(size), iconClassName)}></div>}
|
||||
</button>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
function getIconSize(size: IconSize) {
|
||||
if (size === 'sm') {
|
||||
return 'text-sm';
|
||||
} else if (size === 'md') {
|
||||
return 'text-md';
|
||||
} else if (size === 'lg') {
|
||||
return 'text-lg';
|
||||
} else if (size === 'xl') {
|
||||
return 'text-xl';
|
||||
} else {
|
||||
return 'text-2xl';
|
||||
}
|
||||
}
|
||||
27
app/components/ui/LoadingDots.tsx
Normal file
27
app/components/ui/LoadingDots.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import { memo, useEffect, useState } from 'react';
|
||||
|
||||
interface LoadingDotsProps {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export const LoadingDots = memo(({ text }: LoadingDotsProps) => {
|
||||
const [dotCount, setDotCount] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setDotCount((prevDotCount) => (prevDotCount + 1) % 4);
|
||||
}, 500);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex justify-center items-center h-full">
|
||||
<div className="relative">
|
||||
<span>{text}</span>
|
||||
<span className="absolute left-[calc(100%-12px)]">{'.'.repeat(dotCount)}</span>
|
||||
<span className="invisible">...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
20
app/components/ui/PanelHeader.tsx
Normal file
20
app/components/ui/PanelHeader.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import { memo } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface PanelHeaderProps {
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const PanelHeader = memo(({ className, children }: PanelHeaderProps) => {
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex items-center gap-2 bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary border-b border-bolt-elements-borderColor px-4 py-1 min-h-[34px] text-sm',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
36
app/components/ui/PanelHeaderButton.tsx
Normal file
36
app/components/ui/PanelHeaderButton.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { memo } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface PanelHeaderButtonProps {
|
||||
className?: string;
|
||||
disabledClassName?: string;
|
||||
disabled?: boolean;
|
||||
children: string | JSX.Element | Array<JSX.Element | string>;
|
||||
onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
|
||||
}
|
||||
|
||||
export const PanelHeaderButton = memo(
|
||||
({ className, disabledClassName, disabled = false, children, onClick }: PanelHeaderButtonProps) => {
|
||||
return (
|
||||
<button
|
||||
className={classNames(
|
||||
'flex items-center shrink-0 gap-1.5 px-1.5 rounded-md py-0.5 text-bolt-elements-item-contentDefault bg-transparent enabled:hover:text-bolt-elements-item-contentActive enabled:hover:bg-bolt-elements-item-backgroundActive disabled:cursor-not-allowed',
|
||||
{
|
||||
[classNames('opacity-30', disabledClassName)]: disabled,
|
||||
},
|
||||
className,
|
||||
)}
|
||||
disabled={disabled}
|
||||
onClick={(event) => {
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
onClick?.(event);
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
},
|
||||
);
|
||||
65
app/components/ui/Slider.tsx
Normal file
65
app/components/ui/Slider.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { motion } from 'framer-motion';
|
||||
import { memo } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
import { genericMemo } from '~/utils/react';
|
||||
|
||||
interface SliderOption<T> {
|
||||
value: T;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface SliderOptions<T> {
|
||||
left: SliderOption<T>;
|
||||
right: SliderOption<T>;
|
||||
}
|
||||
|
||||
interface SliderProps<T> {
|
||||
selected: T;
|
||||
options: SliderOptions<T>;
|
||||
setSelected?: (selected: T) => void;
|
||||
}
|
||||
|
||||
export const Slider = genericMemo(<T,>({ selected, options, setSelected }: SliderProps<T>) => {
|
||||
const isLeftSelected = selected === options.left.value;
|
||||
|
||||
return (
|
||||
<div className="flex items-center flex-wrap shrink-0 gap-1 bg-bolt-elements-background-depth-1 overflow-hidden rounded-full p-1">
|
||||
<SliderButton selected={isLeftSelected} setSelected={() => setSelected?.(options.left.value)}>
|
||||
{options.left.text}
|
||||
</SliderButton>
|
||||
<SliderButton selected={!isLeftSelected} setSelected={() => setSelected?.(options.right.value)}>
|
||||
{options.right.text}
|
||||
</SliderButton>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
interface SliderButtonProps {
|
||||
selected: boolean;
|
||||
children: string | JSX.Element | Array<JSX.Element | string>;
|
||||
setSelected: () => void;
|
||||
}
|
||||
|
||||
const SliderButton = memo(({ selected, children, setSelected }: SliderButtonProps) => {
|
||||
return (
|
||||
<button
|
||||
onClick={setSelected}
|
||||
className={classNames(
|
||||
'bg-transparent text-sm px-2.5 py-0.5 rounded-full relative',
|
||||
selected
|
||||
? 'text-bolt-elements-item-contentAccent'
|
||||
: 'text-bolt-elements-item-contentDefault hover:text-bolt-elements-item-contentActive',
|
||||
)}
|
||||
>
|
||||
<span className="relative z-10">{children}</span>
|
||||
{selected && (
|
||||
<motion.span
|
||||
layoutId="pill-tab"
|
||||
transition={{ duration: 0.2, ease: cubicEasingFn }}
|
||||
className="absolute inset-0 z-0 bg-bolt-elements-item-backgroundAccent rounded-full"
|
||||
></motion.span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
});
|
||||
29
app/components/ui/ThemeSwitch.tsx
Normal file
29
app/components/ui/ThemeSwitch.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { memo, useEffect, useState } from 'react';
|
||||
import { themeStore, toggleTheme } from '~/lib/stores/theme';
|
||||
import { IconButton } from './IconButton';
|
||||
|
||||
interface ThemeSwitchProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const ThemeSwitch = memo(({ className }: ThemeSwitchProps) => {
|
||||
const theme = useStore(themeStore);
|
||||
const [domLoaded, setDomLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setDomLoaded(true);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
domLoaded && (
|
||||
<IconButton
|
||||
className={className}
|
||||
icon={theme === 'dark' ? 'i-ph-sun-dim-duotone' : 'i-ph-moon-stars-duotone'}
|
||||
size="xl"
|
||||
title="Toggle Theme"
|
||||
onClick={toggleTheme}
|
||||
/>
|
||||
)
|
||||
);
|
||||
});
|
||||
256
app/components/workbench/EditorPanel.tsx
Normal file
256
app/components/workbench/EditorPanel.tsx
Normal file
@@ -0,0 +1,256 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { memo, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Panel, PanelGroup, PanelResizeHandle, type ImperativePanelHandle } from 'react-resizable-panels';
|
||||
import {
|
||||
CodeMirrorEditor,
|
||||
type EditorDocument,
|
||||
type EditorSettings,
|
||||
type OnChangeCallback as OnEditorChange,
|
||||
type OnSaveCallback as OnEditorSave,
|
||||
type OnScrollCallback as OnEditorScroll,
|
||||
} from '~/components/editor/codemirror/CodeMirrorEditor';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
import { PanelHeader } from '~/components/ui/PanelHeader';
|
||||
import { PanelHeaderButton } from '~/components/ui/PanelHeaderButton';
|
||||
import { shortcutEventEmitter } from '~/lib/hooks';
|
||||
import type { FileMap } from '~/lib/stores/files';
|
||||
import { themeStore } from '~/lib/stores/theme';
|
||||
import { workbenchStore } from '~/lib/stores/workbench';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { WORK_DIR } from '~/utils/constants';
|
||||
import { renderLogger } from '~/utils/logger';
|
||||
import { isMobile } from '~/utils/mobile';
|
||||
import { FileBreadcrumb } from './FileBreadcrumb';
|
||||
import { FileTree } from './FileTree';
|
||||
import { Terminal, type TerminalRef } from './terminal/Terminal';
|
||||
|
||||
interface EditorPanelProps {
|
||||
files?: FileMap;
|
||||
unsavedFiles?: Set<string>;
|
||||
editorDocument?: EditorDocument;
|
||||
selectedFile?: string | undefined;
|
||||
isStreaming?: boolean;
|
||||
onEditorChange?: OnEditorChange;
|
||||
onEditorScroll?: OnEditorScroll;
|
||||
onFileSelect?: (value?: string) => void;
|
||||
onFileSave?: OnEditorSave;
|
||||
onFileReset?: () => void;
|
||||
}
|
||||
|
||||
const MAX_TERMINALS = 3;
|
||||
const DEFAULT_TERMINAL_SIZE = 25;
|
||||
const DEFAULT_EDITOR_SIZE = 100 - DEFAULT_TERMINAL_SIZE;
|
||||
|
||||
const editorSettings: EditorSettings = { tabSize: 2 };
|
||||
|
||||
export const EditorPanel = memo(
|
||||
({
|
||||
files,
|
||||
unsavedFiles,
|
||||
editorDocument,
|
||||
selectedFile,
|
||||
isStreaming,
|
||||
onFileSelect,
|
||||
onEditorChange,
|
||||
onEditorScroll,
|
||||
onFileSave,
|
||||
onFileReset,
|
||||
}: EditorPanelProps) => {
|
||||
renderLogger.trace('EditorPanel');
|
||||
|
||||
const theme = useStore(themeStore);
|
||||
const showTerminal = useStore(workbenchStore.showTerminal);
|
||||
|
||||
const terminalRefs = useRef<Array<TerminalRef | null>>([]);
|
||||
const terminalPanelRef = useRef<ImperativePanelHandle>(null);
|
||||
const terminalToggledByShortcut = useRef(false);
|
||||
|
||||
const [activeTerminal, setActiveTerminal] = useState(0);
|
||||
const [terminalCount, setTerminalCount] = useState(1);
|
||||
|
||||
const activeFileSegments = useMemo(() => {
|
||||
if (!editorDocument) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return editorDocument.filePath.split('/');
|
||||
}, [editorDocument]);
|
||||
|
||||
const activeFileUnsaved = useMemo(() => {
|
||||
return editorDocument !== undefined && unsavedFiles?.has(editorDocument.filePath);
|
||||
}, [editorDocument, unsavedFiles]);
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribeFromEventEmitter = shortcutEventEmitter.on('toggleTerminal', () => {
|
||||
terminalToggledByShortcut.current = true;
|
||||
});
|
||||
|
||||
const unsubscribeFromThemeStore = themeStore.subscribe(() => {
|
||||
for (const ref of Object.values(terminalRefs.current)) {
|
||||
ref?.reloadStyles();
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribeFromEventEmitter();
|
||||
unsubscribeFromThemeStore();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const { current: terminal } = terminalPanelRef;
|
||||
|
||||
if (!terminal) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isCollapsed = terminal.isCollapsed();
|
||||
|
||||
if (!showTerminal && !isCollapsed) {
|
||||
terminal.collapse();
|
||||
} else if (showTerminal && isCollapsed) {
|
||||
terminal.resize(DEFAULT_TERMINAL_SIZE);
|
||||
}
|
||||
|
||||
terminalToggledByShortcut.current = false;
|
||||
}, [showTerminal]);
|
||||
|
||||
const addTerminal = () => {
|
||||
if (terminalCount < MAX_TERMINALS) {
|
||||
setTerminalCount(terminalCount + 1);
|
||||
setActiveTerminal(terminalCount);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PanelGroup direction="vertical">
|
||||
<Panel defaultSize={showTerminal ? DEFAULT_EDITOR_SIZE : 100} minSize={20}>
|
||||
<PanelGroup direction="horizontal">
|
||||
<Panel defaultSize={20} minSize={10} collapsible>
|
||||
<div className="flex flex-col border-r border-bolt-elements-borderColor h-full">
|
||||
<PanelHeader>
|
||||
<div className="i-ph:tree-structure-duotone shrink-0" />
|
||||
Files
|
||||
</PanelHeader>
|
||||
<FileTree
|
||||
className="h-full"
|
||||
files={files}
|
||||
hideRoot
|
||||
unsavedFiles={unsavedFiles}
|
||||
rootFolder={WORK_DIR}
|
||||
selectedFile={selectedFile}
|
||||
onFileSelect={onFileSelect}
|
||||
/>
|
||||
</div>
|
||||
</Panel>
|
||||
<PanelResizeHandle />
|
||||
<Panel className="flex flex-col" defaultSize={80} minSize={20}>
|
||||
<PanelHeader className="overflow-x-auto">
|
||||
{activeFileSegments?.length && (
|
||||
<div className="flex items-center flex-1 text-sm">
|
||||
<FileBreadcrumb pathSegments={activeFileSegments} files={files} onFileSelect={onFileSelect} />
|
||||
{activeFileUnsaved && (
|
||||
<div className="flex gap-1 ml-auto -mr-1.5">
|
||||
<PanelHeaderButton onClick={onFileSave}>
|
||||
<div className="i-ph:floppy-disk-duotone" />
|
||||
Save
|
||||
</PanelHeaderButton>
|
||||
<PanelHeaderButton onClick={onFileReset}>
|
||||
<div className="i-ph:clock-counter-clockwise-duotone" />
|
||||
Reset
|
||||
</PanelHeaderButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</PanelHeader>
|
||||
<div className="h-full flex-1 overflow-hidden">
|
||||
<CodeMirrorEditor
|
||||
theme={theme}
|
||||
editable={!isStreaming && editorDocument !== undefined}
|
||||
settings={editorSettings}
|
||||
doc={editorDocument}
|
||||
autoFocusOnDocumentChange={!isMobile()}
|
||||
onScroll={onEditorScroll}
|
||||
onChange={onEditorChange}
|
||||
onSave={onFileSave}
|
||||
/>
|
||||
</div>
|
||||
</Panel>
|
||||
</PanelGroup>
|
||||
</Panel>
|
||||
<PanelResizeHandle />
|
||||
<Panel
|
||||
ref={terminalPanelRef}
|
||||
defaultSize={showTerminal ? DEFAULT_TERMINAL_SIZE : 0}
|
||||
minSize={10}
|
||||
collapsible
|
||||
onExpand={() => {
|
||||
if (!terminalToggledByShortcut.current) {
|
||||
workbenchStore.toggleTerminal(true);
|
||||
}
|
||||
}}
|
||||
onCollapse={() => {
|
||||
if (!terminalToggledByShortcut.current) {
|
||||
workbenchStore.toggleTerminal(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="h-full">
|
||||
<div className="bg-bolt-elements-terminals-background h-full flex flex-col">
|
||||
<div className="flex items-center bg-bolt-elements-background-depth-2 border-y border-bolt-elements-borderColor gap-1.5 min-h-[34px] p-2">
|
||||
{Array.from({ length: terminalCount }, (_, index) => {
|
||||
const isActive = activeTerminal === index;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={index}
|
||||
className={classNames(
|
||||
'flex items-center text-sm cursor-pointer gap-1.5 px-3 py-2 h-full whitespace-nowrap rounded-full',
|
||||
{
|
||||
'bg-bolt-elements-terminals-buttonBackground text-bolt-elements-textPrimary': isActive,
|
||||
'bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary hover:bg-bolt-elements-terminals-buttonBackground':
|
||||
!isActive,
|
||||
},
|
||||
)}
|
||||
onClick={() => setActiveTerminal(index)}
|
||||
>
|
||||
<div className="i-ph:terminal-window-duotone text-lg" />
|
||||
Terminal {terminalCount > 1 && index + 1}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{terminalCount < MAX_TERMINALS && <IconButton icon="i-ph:plus" size="md" onClick={addTerminal} />}
|
||||
<IconButton
|
||||
className="ml-auto"
|
||||
icon="i-ph:caret-down"
|
||||
title="Close"
|
||||
size="md"
|
||||
onClick={() => workbenchStore.toggleTerminal(false)}
|
||||
/>
|
||||
</div>
|
||||
{Array.from({ length: terminalCount }, (_, index) => {
|
||||
const isActive = activeTerminal === index;
|
||||
|
||||
return (
|
||||
<Terminal
|
||||
key={index}
|
||||
className={classNames('h-full overflow-hidden', {
|
||||
hidden: !isActive,
|
||||
})}
|
||||
ref={(ref) => {
|
||||
terminalRefs.current.push(ref);
|
||||
}}
|
||||
onTerminalReady={(terminal) => workbenchStore.attachTerminal(terminal)}
|
||||
onTerminalResize={(cols, rows) => workbenchStore.onTerminalResize(cols, rows)}
|
||||
theme={theme}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</Panel>
|
||||
</PanelGroup>
|
||||
);
|
||||
},
|
||||
);
|
||||
148
app/components/workbench/FileBreadcrumb.tsx
Normal file
148
app/components/workbench/FileBreadcrumb.tsx
Normal file
@@ -0,0 +1,148 @@
|
||||
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
|
||||
import { AnimatePresence, motion, type Variants } from 'framer-motion';
|
||||
import { memo, useEffect, useRef, useState } from 'react';
|
||||
import type { FileMap } from '~/lib/stores/files';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { WORK_DIR } from '~/utils/constants';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
import { renderLogger } from '~/utils/logger';
|
||||
import FileTree from './FileTree';
|
||||
|
||||
const WORK_DIR_REGEX = new RegExp(`^${WORK_DIR.split('/').slice(0, -1).join('/').replaceAll('/', '\\/')}/`);
|
||||
|
||||
interface FileBreadcrumbProps {
|
||||
files?: FileMap;
|
||||
pathSegments?: string[];
|
||||
onFileSelect?: (filePath: string) => void;
|
||||
}
|
||||
|
||||
const contextMenuVariants = {
|
||||
open: {
|
||||
y: 0,
|
||||
opacity: 1,
|
||||
transition: {
|
||||
duration: 0.15,
|
||||
ease: cubicEasingFn,
|
||||
},
|
||||
},
|
||||
close: {
|
||||
y: 6,
|
||||
opacity: 0,
|
||||
transition: {
|
||||
duration: 0.15,
|
||||
ease: cubicEasingFn,
|
||||
},
|
||||
},
|
||||
} satisfies Variants;
|
||||
|
||||
export const FileBreadcrumb = memo<FileBreadcrumbProps>(({ files, pathSegments = [], onFileSelect }) => {
|
||||
renderLogger.trace('FileBreadcrumb');
|
||||
|
||||
const [activeIndex, setActiveIndex] = useState<number | null>(null);
|
||||
|
||||
const contextMenuRef = useRef<HTMLDivElement | null>(null);
|
||||
const segmentRefs = useRef<(HTMLSpanElement | null)[]>([]);
|
||||
|
||||
const handleSegmentClick = (index: number) => {
|
||||
setActiveIndex((prevIndex) => (prevIndex === index ? null : index));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleOutsideClick = (event: MouseEvent) => {
|
||||
if (
|
||||
activeIndex !== null &&
|
||||
!contextMenuRef.current?.contains(event.target as Node) &&
|
||||
!segmentRefs.current.some((ref) => ref?.contains(event.target as Node))
|
||||
) {
|
||||
setActiveIndex(null);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleOutsideClick);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleOutsideClick);
|
||||
};
|
||||
}, [activeIndex]);
|
||||
|
||||
if (files === undefined || pathSegments.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex">
|
||||
{pathSegments.map((segment, index) => {
|
||||
const isLast = index === pathSegments.length - 1;
|
||||
|
||||
const path = pathSegments.slice(0, index).join('/');
|
||||
|
||||
if (!WORK_DIR_REGEX.test(path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isActive = activeIndex === index;
|
||||
|
||||
return (
|
||||
<div key={index} className="relative flex items-center">
|
||||
<DropdownMenu.Root open={isActive} modal={false}>
|
||||
<DropdownMenu.Trigger asChild>
|
||||
<span
|
||||
ref={(ref) => (segmentRefs.current[index] = ref)}
|
||||
className={classNames('flex items-center gap-1.5 cursor-pointer shrink-0', {
|
||||
'text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary': !isActive,
|
||||
'text-bolt-elements-textPrimary underline': isActive,
|
||||
'pr-4': isLast,
|
||||
})}
|
||||
onClick={() => handleSegmentClick(index)}
|
||||
>
|
||||
{isLast && <div className="i-ph:file-duotone" />}
|
||||
{segment}
|
||||
</span>
|
||||
</DropdownMenu.Trigger>
|
||||
{index > 0 && !isLast && <span className="i-ph:caret-right inline-block mx-1" />}
|
||||
<AnimatePresence>
|
||||
{isActive && (
|
||||
<DropdownMenu.Portal>
|
||||
<DropdownMenu.Content
|
||||
className="z-file-tree-breadcrumb"
|
||||
asChild
|
||||
align="start"
|
||||
side="bottom"
|
||||
avoidCollisions={false}
|
||||
>
|
||||
<motion.div
|
||||
ref={contextMenuRef}
|
||||
initial="close"
|
||||
animate="open"
|
||||
exit="close"
|
||||
variants={contextMenuVariants}
|
||||
>
|
||||
<div className="rounded-lg overflow-hidden">
|
||||
<div className="max-h-[50vh] min-w-[300px] overflow-scroll bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor shadow-sm rounded-lg">
|
||||
<FileTree
|
||||
files={files}
|
||||
hideRoot
|
||||
rootFolder={path}
|
||||
collapsed
|
||||
allowFolderSelection
|
||||
selectedFile={`${path}/${segment}`}
|
||||
onFileSelect={(filePath) => {
|
||||
setActiveIndex(null);
|
||||
onFileSelect?.(filePath);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenu.Arrow className="fill-bolt-elements-borderColor" />
|
||||
</motion.div>
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Portal>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</DropdownMenu.Root>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
409
app/components/workbench/FileTree.tsx
Normal file
409
app/components/workbench/FileTree.tsx
Normal file
@@ -0,0 +1,409 @@
|
||||
import { memo, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import type { FileMap } from '~/lib/stores/files';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { createScopedLogger, renderLogger } from '~/utils/logger';
|
||||
|
||||
const logger = createScopedLogger('FileTree');
|
||||
|
||||
const NODE_PADDING_LEFT = 8;
|
||||
const DEFAULT_HIDDEN_FILES = [/\/node_modules\//, /\/\.next/, /\/\.astro/];
|
||||
|
||||
interface Props {
|
||||
files?: FileMap;
|
||||
selectedFile?: string;
|
||||
onFileSelect?: (filePath: string) => void;
|
||||
rootFolder?: string;
|
||||
hideRoot?: boolean;
|
||||
collapsed?: boolean;
|
||||
allowFolderSelection?: boolean;
|
||||
hiddenFiles?: Array<string | RegExp>;
|
||||
unsavedFiles?: Set<string>;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const FileTree = memo(
|
||||
({
|
||||
files = {},
|
||||
onFileSelect,
|
||||
selectedFile,
|
||||
rootFolder,
|
||||
hideRoot = false,
|
||||
collapsed = false,
|
||||
allowFolderSelection = false,
|
||||
hiddenFiles,
|
||||
className,
|
||||
unsavedFiles,
|
||||
}: Props) => {
|
||||
renderLogger.trace('FileTree');
|
||||
|
||||
const computedHiddenFiles = useMemo(() => [...DEFAULT_HIDDEN_FILES, ...(hiddenFiles ?? [])], [hiddenFiles]);
|
||||
|
||||
const fileList = useMemo(() => {
|
||||
return buildFileList(files, rootFolder, hideRoot, computedHiddenFiles);
|
||||
}, [files, rootFolder, hideRoot, computedHiddenFiles]);
|
||||
|
||||
const [collapsedFolders, setCollapsedFolders] = useState(() => {
|
||||
return collapsed
|
||||
? new Set(fileList.filter((item) => item.kind === 'folder').map((item) => item.fullPath))
|
||||
: new Set<string>();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (collapsed) {
|
||||
setCollapsedFolders(new Set(fileList.filter((item) => item.kind === 'folder').map((item) => item.fullPath)));
|
||||
return;
|
||||
}
|
||||
|
||||
setCollapsedFolders((prevCollapsed) => {
|
||||
const newCollapsed = new Set<string>();
|
||||
|
||||
for (const folder of fileList) {
|
||||
if (folder.kind === 'folder' && prevCollapsed.has(folder.fullPath)) {
|
||||
newCollapsed.add(folder.fullPath);
|
||||
}
|
||||
}
|
||||
|
||||
return newCollapsed;
|
||||
});
|
||||
}, [fileList, collapsed]);
|
||||
|
||||
const filteredFileList = useMemo(() => {
|
||||
const list = [];
|
||||
|
||||
let lastDepth = Number.MAX_SAFE_INTEGER;
|
||||
|
||||
for (const fileOrFolder of fileList) {
|
||||
const depth = fileOrFolder.depth;
|
||||
|
||||
// if the depth is equal we reached the end of the collaped group
|
||||
if (lastDepth === depth) {
|
||||
lastDepth = Number.MAX_SAFE_INTEGER;
|
||||
}
|
||||
|
||||
// ignore collapsed folders
|
||||
if (collapsedFolders.has(fileOrFolder.fullPath)) {
|
||||
lastDepth = Math.min(lastDepth, depth);
|
||||
}
|
||||
|
||||
// ignore files and folders below the last collapsed folder
|
||||
if (lastDepth < depth) {
|
||||
continue;
|
||||
}
|
||||
|
||||
list.push(fileOrFolder);
|
||||
}
|
||||
|
||||
return list;
|
||||
}, [fileList, collapsedFolders]);
|
||||
|
||||
const toggleCollapseState = (fullPath: string) => {
|
||||
setCollapsedFolders((prevSet) => {
|
||||
const newSet = new Set(prevSet);
|
||||
|
||||
if (newSet.has(fullPath)) {
|
||||
newSet.delete(fullPath);
|
||||
} else {
|
||||
newSet.add(fullPath);
|
||||
}
|
||||
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames('text-sm', className)}>
|
||||
{filteredFileList.map((fileOrFolder) => {
|
||||
switch (fileOrFolder.kind) {
|
||||
case 'file': {
|
||||
return (
|
||||
<File
|
||||
key={fileOrFolder.id}
|
||||
selected={selectedFile === fileOrFolder.fullPath}
|
||||
file={fileOrFolder}
|
||||
unsavedChanges={unsavedFiles?.has(fileOrFolder.fullPath)}
|
||||
onClick={() => {
|
||||
onFileSelect?.(fileOrFolder.fullPath);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case 'folder': {
|
||||
return (
|
||||
<Folder
|
||||
key={fileOrFolder.id}
|
||||
folder={fileOrFolder}
|
||||
selected={allowFolderSelection && selectedFile === fileOrFolder.fullPath}
|
||||
collapsed={collapsedFolders.has(fileOrFolder.fullPath)}
|
||||
onClick={() => {
|
||||
toggleCollapseState(fileOrFolder.fullPath);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
default: {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export default FileTree;
|
||||
|
||||
interface FolderProps {
|
||||
folder: FolderNode;
|
||||
collapsed: boolean;
|
||||
selected?: boolean;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
function Folder({ folder: { depth, name }, collapsed, selected = false, onClick }: FolderProps) {
|
||||
return (
|
||||
<NodeButton
|
||||
className={classNames('group', {
|
||||
'bg-transparent text-bolt-elements-item-contentDefault hover:text-bolt-elements-item-contentActive hover:bg-bolt-elements-item-backgroundActive':
|
||||
!selected,
|
||||
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent': selected,
|
||||
})}
|
||||
depth={depth}
|
||||
iconClasses={classNames({
|
||||
'i-ph:caret-right scale-98': collapsed,
|
||||
'i-ph:caret-down scale-98': !collapsed,
|
||||
})}
|
||||
onClick={onClick}
|
||||
>
|
||||
{name}
|
||||
</NodeButton>
|
||||
);
|
||||
}
|
||||
|
||||
interface FileProps {
|
||||
file: FileNode;
|
||||
selected: boolean;
|
||||
unsavedChanges?: boolean;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
function File({ file: { depth, name }, onClick, selected, unsavedChanges = false }: FileProps) {
|
||||
return (
|
||||
<NodeButton
|
||||
className={classNames('group', {
|
||||
'bg-transparent hover:bg-bolt-elements-item-backgroundActive text-bolt-elements-item-contentDefault': !selected,
|
||||
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent': selected,
|
||||
})}
|
||||
depth={depth}
|
||||
iconClasses={classNames('i-ph:file-duotone scale-98', {
|
||||
'group-hover:text-bolt-elements-item-contentActive': !selected,
|
||||
})}
|
||||
onClick={onClick}
|
||||
>
|
||||
<div
|
||||
className={classNames('flex items-center', {
|
||||
'group-hover:text-bolt-elements-item-contentActive': !selected,
|
||||
})}
|
||||
>
|
||||
<div className="flex-1 truncate pr-2">{name}</div>
|
||||
{unsavedChanges && <span className="i-ph:circle-fill scale-68 shrink-0 text-orange-500" />}
|
||||
</div>
|
||||
</NodeButton>
|
||||
);
|
||||
}
|
||||
|
||||
interface ButtonProps {
|
||||
depth: number;
|
||||
iconClasses: string;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
function NodeButton({ depth, iconClasses, onClick, className, children }: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
className={classNames(
|
||||
'flex items-center gap-1.5 w-full pr-2 border-2 border-transparent text-faded py-0.5',
|
||||
className,
|
||||
)}
|
||||
style={{ paddingLeft: `${6 + depth * NODE_PADDING_LEFT}px` }}
|
||||
onClick={() => onClick?.()}
|
||||
>
|
||||
<div className={classNames('scale-120 shrink-0', iconClasses)}></div>
|
||||
<div className="truncate w-full text-left">{children}</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
type Node = FileNode | FolderNode;
|
||||
|
||||
interface BaseNode {
|
||||
id: number;
|
||||
depth: number;
|
||||
name: string;
|
||||
fullPath: string;
|
||||
}
|
||||
|
||||
interface FileNode extends BaseNode {
|
||||
kind: 'file';
|
||||
}
|
||||
|
||||
interface FolderNode extends BaseNode {
|
||||
kind: 'folder';
|
||||
}
|
||||
|
||||
function buildFileList(
|
||||
files: FileMap,
|
||||
rootFolder = '/',
|
||||
hideRoot: boolean,
|
||||
hiddenFiles: Array<string | RegExp>,
|
||||
): Node[] {
|
||||
const folderPaths = new Set<string>();
|
||||
const fileList: Node[] = [];
|
||||
|
||||
let defaultDepth = 0;
|
||||
|
||||
if (rootFolder === '/' && !hideRoot) {
|
||||
defaultDepth = 1;
|
||||
fileList.push({ kind: 'folder', name: '/', depth: 0, id: 0, fullPath: '/' });
|
||||
}
|
||||
|
||||
for (const [filePath, dirent] of Object.entries(files)) {
|
||||
const segments = filePath.split('/').filter((segment) => segment);
|
||||
const fileName = segments.at(-1);
|
||||
|
||||
if (!fileName || isHiddenFile(filePath, fileName, hiddenFiles)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let currentPath = '';
|
||||
|
||||
let i = 0;
|
||||
let depth = 0;
|
||||
|
||||
while (i < segments.length) {
|
||||
const name = segments[i];
|
||||
const fullPath = (currentPath += `/${name}`);
|
||||
|
||||
if (!fullPath.startsWith(rootFolder) || (hideRoot && fullPath === rootFolder)) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i === segments.length - 1 && dirent?.type === 'file') {
|
||||
fileList.push({
|
||||
kind: 'file',
|
||||
id: fileList.length,
|
||||
name,
|
||||
fullPath,
|
||||
depth: depth + defaultDepth,
|
||||
});
|
||||
} else if (!folderPaths.has(fullPath)) {
|
||||
folderPaths.add(fullPath);
|
||||
|
||||
fileList.push({
|
||||
kind: 'folder',
|
||||
id: fileList.length,
|
||||
name,
|
||||
fullPath,
|
||||
depth: depth + defaultDepth,
|
||||
});
|
||||
}
|
||||
|
||||
i++;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
return sortFileList(rootFolder, fileList, hideRoot);
|
||||
}
|
||||
|
||||
function isHiddenFile(filePath: string, fileName: string, hiddenFiles: Array<string | RegExp>) {
|
||||
return hiddenFiles.some((pathOrRegex) => {
|
||||
if (typeof pathOrRegex === 'string') {
|
||||
return fileName === pathOrRegex;
|
||||
}
|
||||
|
||||
return pathOrRegex.test(filePath);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the given list of nodes into a tree structure (still a flat list).
|
||||
*
|
||||
* This function organizes the nodes into a hierarchical structure based on their paths,
|
||||
* with folders appearing before files and all items sorted alphabetically within their level.
|
||||
*
|
||||
* @note This function mutates the given `nodeList` array for performance reasons.
|
||||
*
|
||||
* @param rootFolder - The path of the root folder to start the sorting from.
|
||||
* @param nodeList - The list of nodes to be sorted.
|
||||
*
|
||||
* @returns A new array of nodes sorted in depth-first order.
|
||||
*/
|
||||
function sortFileList(rootFolder: string, nodeList: Node[], hideRoot: boolean): Node[] {
|
||||
logger.trace('sortFileList');
|
||||
|
||||
const nodeMap = new Map<string, Node>();
|
||||
const childrenMap = new Map<string, Node[]>();
|
||||
|
||||
// pre-sort nodes by name and type
|
||||
nodeList.sort((a, b) => compareNodes(a, b));
|
||||
|
||||
for (const node of nodeList) {
|
||||
nodeMap.set(node.fullPath, node);
|
||||
|
||||
const parentPath = node.fullPath.slice(0, node.fullPath.lastIndexOf('/'));
|
||||
|
||||
if (parentPath !== rootFolder.slice(0, rootFolder.lastIndexOf('/'))) {
|
||||
if (!childrenMap.has(parentPath)) {
|
||||
childrenMap.set(parentPath, []);
|
||||
}
|
||||
|
||||
childrenMap.get(parentPath)?.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
const sortedList: Node[] = [];
|
||||
|
||||
const depthFirstTraversal = (path: string): void => {
|
||||
const node = nodeMap.get(path);
|
||||
|
||||
if (node) {
|
||||
sortedList.push(node);
|
||||
}
|
||||
|
||||
const children = childrenMap.get(path);
|
||||
|
||||
if (children) {
|
||||
for (const child of children) {
|
||||
if (child.kind === 'folder') {
|
||||
depthFirstTraversal(child.fullPath);
|
||||
} else {
|
||||
sortedList.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (hideRoot) {
|
||||
// if root is hidden, start traversal from its immediate children
|
||||
const rootChildren = childrenMap.get(rootFolder) || [];
|
||||
|
||||
for (const child of rootChildren) {
|
||||
depthFirstTraversal(child.fullPath);
|
||||
}
|
||||
} else {
|
||||
depthFirstTraversal(rootFolder);
|
||||
}
|
||||
|
||||
return sortedList;
|
||||
}
|
||||
|
||||
function compareNodes(a: Node, b: Node): number {
|
||||
if (a.kind !== b.kind) {
|
||||
return a.kind === 'folder' ? -1 : 1;
|
||||
}
|
||||
|
||||
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
|
||||
}
|
||||
83
app/components/workbench/PortDropdown.tsx
Normal file
83
app/components/workbench/PortDropdown.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import { memo, useEffect, useRef } from 'react';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
import type { PreviewInfo } from '~/lib/stores/previews';
|
||||
|
||||
interface PortDropdownProps {
|
||||
activePreviewIndex: number;
|
||||
setActivePreviewIndex: (index: number) => void;
|
||||
isDropdownOpen: boolean;
|
||||
setIsDropdownOpen: (value: boolean) => void;
|
||||
setHasSelectedPreview: (value: boolean) => void;
|
||||
previews: PreviewInfo[];
|
||||
}
|
||||
|
||||
export const PortDropdown = memo(
|
||||
({
|
||||
activePreviewIndex,
|
||||
setActivePreviewIndex,
|
||||
isDropdownOpen,
|
||||
setIsDropdownOpen,
|
||||
setHasSelectedPreview,
|
||||
previews,
|
||||
}: PortDropdownProps) => {
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// sort previews, preserving original index
|
||||
const sortedPreviews = previews
|
||||
.map((previewInfo, index) => ({ ...previewInfo, index }))
|
||||
.sort((a, b) => a.port - b.port);
|
||||
|
||||
// close dropdown if user clicks outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setIsDropdownOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isDropdownOpen) {
|
||||
window.addEventListener('mousedown', handleClickOutside);
|
||||
} else {
|
||||
window.removeEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [isDropdownOpen]);
|
||||
|
||||
return (
|
||||
<div className="relative z-port-dropdown" ref={dropdownRef}>
|
||||
<IconButton icon="i-ph:plug" onClick={() => setIsDropdownOpen(!isDropdownOpen)} />
|
||||
{isDropdownOpen && (
|
||||
<div className="absolute right-0 mt-2 bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor rounded shadow-sm min-w-[140px] dropdown-animation">
|
||||
<div className="px-4 py-2 border-b border-bolt-elements-borderColor text-sm font-semibold text-bolt-elements-textPrimary">
|
||||
Ports
|
||||
</div>
|
||||
{sortedPreviews.map((preview) => (
|
||||
<div
|
||||
key={preview.port}
|
||||
className="flex items-center px-4 py-2 cursor-pointer hover:bg-bolt-elements-item-backgroundActive"
|
||||
onClick={() => {
|
||||
setActivePreviewIndex(preview.index);
|
||||
setIsDropdownOpen(false);
|
||||
setHasSelectedPreview(true);
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className={
|
||||
activePreviewIndex === preview.index
|
||||
? 'text-bolt-elements-item-contentAccent'
|
||||
: 'text-bolt-elements-item-contentDefault group-hover:text-bolt-elements-item-contentActive'
|
||||
}
|
||||
>
|
||||
{preview.port}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
124
app/components/workbench/Preview.tsx
Normal file
124
app/components/workbench/Preview.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
import { workbenchStore } from '~/lib/stores/workbench';
|
||||
import { PortDropdown } from './PortDropdown';
|
||||
|
||||
export const Preview = memo(() => {
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [activePreviewIndex, setActivePreviewIndex] = useState(0);
|
||||
const [isPortDropdownOpen, setIsPortDropdownOpen] = useState(false);
|
||||
const hasSelectedPreview = useRef(false);
|
||||
const previews = useStore(workbenchStore.previews);
|
||||
const activePreview = previews[activePreviewIndex];
|
||||
|
||||
const [url, setUrl] = useState('');
|
||||
const [iframeUrl, setIframeUrl] = useState<string | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!activePreview) {
|
||||
setUrl('');
|
||||
setIframeUrl(undefined);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const { baseUrl } = activePreview;
|
||||
|
||||
setUrl(baseUrl);
|
||||
setIframeUrl(baseUrl);
|
||||
}, [activePreview, iframeUrl]);
|
||||
|
||||
const validateUrl = useCallback(
|
||||
(value: string) => {
|
||||
if (!activePreview) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { baseUrl } = activePreview;
|
||||
|
||||
if (value === baseUrl) {
|
||||
return true;
|
||||
} else if (value.startsWith(baseUrl)) {
|
||||
return ['/', '?', '#'].includes(value.charAt(baseUrl.length));
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
[activePreview],
|
||||
);
|
||||
|
||||
const findMinPortIndex = useCallback(
|
||||
(minIndex: number, preview: { port: number }, index: number, array: { port: number }[]) => {
|
||||
return preview.port < array[minIndex].port ? index : minIndex;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// when previews change, display the lowest port if user hasn't selected a preview
|
||||
useEffect(() => {
|
||||
if (previews.length > 1 && !hasSelectedPreview.current) {
|
||||
const minPortIndex = previews.reduce(findMinPortIndex, 0);
|
||||
|
||||
setActivePreviewIndex(minPortIndex);
|
||||
}
|
||||
}, [previews]);
|
||||
|
||||
const reloadPreview = () => {
|
||||
if (iframeRef.current) {
|
||||
iframeRef.current.src = iframeRef.current.src;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full h-full flex flex-col">
|
||||
{isPortDropdownOpen && (
|
||||
<div className="z-iframe-overlay w-full h-full absolute" onClick={() => setIsPortDropdownOpen(false)} />
|
||||
)}
|
||||
<div className="bg-bolt-elements-background-depth-2 p-2 flex items-center gap-1.5">
|
||||
<IconButton icon="i-ph:arrow-clockwise" onClick={reloadPreview} />
|
||||
<div
|
||||
className="flex items-center gap-1 flex-grow bg-bolt-elements-preview-addressBar-background border border-bolt-elements-borderColor text-bolt-elements-preview-addressBar-text rounded-full px-3 py-1 text-sm hover:bg-bolt-elements-preview-addressBar-backgroundHover hover:focus-within:bg-bolt-elements-preview-addressBar-backgroundActive focus-within:bg-bolt-elements-preview-addressBar-backgroundActive
|
||||
focus-within-border-bolt-elements-borderColorActive focus-within:text-bolt-elements-preview-addressBar-textActive"
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="w-full bg-transparent outline-none"
|
||||
type="text"
|
||||
value={url}
|
||||
onChange={(event) => {
|
||||
setUrl(event.target.value);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' && validateUrl(url)) {
|
||||
setIframeUrl(url);
|
||||
|
||||
if (inputRef.current) {
|
||||
inputRef.current.blur();
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{previews.length > 1 && (
|
||||
<PortDropdown
|
||||
activePreviewIndex={activePreviewIndex}
|
||||
setActivePreviewIndex={setActivePreviewIndex}
|
||||
isDropdownOpen={isPortDropdownOpen}
|
||||
setHasSelectedPreview={(value) => (hasSelectedPreview.current = value)}
|
||||
setIsDropdownOpen={setIsPortDropdownOpen}
|
||||
previews={previews}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 border-t border-bolt-elements-borderColor">
|
||||
{activePreview ? (
|
||||
<iframe ref={iframeRef} className="border-none w-full h-full bg-white" src={iframeUrl} />
|
||||
) : (
|
||||
<div className="flex w-full h-full justify-center items-center bg-white">No preview available</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
187
app/components/workbench/Workbench.client.tsx
Normal file
187
app/components/workbench/Workbench.client.tsx
Normal file
@@ -0,0 +1,187 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { motion, type HTMLMotionProps, type Variants } from 'framer-motion';
|
||||
import { computed } from 'nanostores';
|
||||
import { memo, useCallback, useEffect } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import {
|
||||
type OnChangeCallback as OnEditorChange,
|
||||
type OnScrollCallback as OnEditorScroll,
|
||||
} from '~/components/editor/codemirror/CodeMirrorEditor';
|
||||
import { IconButton } from '~/components/ui/IconButton';
|
||||
import { PanelHeaderButton } from '~/components/ui/PanelHeaderButton';
|
||||
import { Slider, type SliderOptions } from '~/components/ui/Slider';
|
||||
import { workbenchStore, type WorkbenchViewType } from '~/lib/stores/workbench';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { cubicEasingFn } from '~/utils/easings';
|
||||
import { renderLogger } from '~/utils/logger';
|
||||
import { EditorPanel } from './EditorPanel';
|
||||
import { Preview } from './Preview';
|
||||
|
||||
interface WorkspaceProps {
|
||||
chatStarted?: boolean;
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
const viewTransition = { ease: cubicEasingFn };
|
||||
|
||||
const sliderOptions: SliderOptions<WorkbenchViewType> = {
|
||||
left: {
|
||||
value: 'code',
|
||||
text: 'Code',
|
||||
},
|
||||
right: {
|
||||
value: 'preview',
|
||||
text: 'Preview',
|
||||
},
|
||||
};
|
||||
|
||||
const workbenchVariants = {
|
||||
closed: {
|
||||
width: 0,
|
||||
transition: {
|
||||
duration: 0.2,
|
||||
ease: cubicEasingFn,
|
||||
},
|
||||
},
|
||||
open: {
|
||||
width: 'var(--workbench-width)',
|
||||
transition: {
|
||||
duration: 0.2,
|
||||
ease: cubicEasingFn,
|
||||
},
|
||||
},
|
||||
} satisfies Variants;
|
||||
|
||||
export const Workbench = memo(({ chatStarted, isStreaming }: WorkspaceProps) => {
|
||||
renderLogger.trace('Workbench');
|
||||
|
||||
const hasPreview = useStore(computed(workbenchStore.previews, (previews) => previews.length > 0));
|
||||
const showWorkbench = useStore(workbenchStore.showWorkbench);
|
||||
const selectedFile = useStore(workbenchStore.selectedFile);
|
||||
const currentDocument = useStore(workbenchStore.currentDocument);
|
||||
const unsavedFiles = useStore(workbenchStore.unsavedFiles);
|
||||
const files = useStore(workbenchStore.files);
|
||||
const selectedView = useStore(workbenchStore.currentView);
|
||||
|
||||
const setSelectedView = (view: WorkbenchViewType) => {
|
||||
workbenchStore.currentView.set(view);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (hasPreview) {
|
||||
setSelectedView('preview');
|
||||
}
|
||||
}, [hasPreview]);
|
||||
|
||||
useEffect(() => {
|
||||
workbenchStore.setDocuments(files);
|
||||
}, [files]);
|
||||
|
||||
const onEditorChange = useCallback<OnEditorChange>((update) => {
|
||||
workbenchStore.setCurrentDocumentContent(update.content);
|
||||
}, []);
|
||||
|
||||
const onEditorScroll = useCallback<OnEditorScroll>((position) => {
|
||||
workbenchStore.setCurrentDocumentScrollPosition(position);
|
||||
}, []);
|
||||
|
||||
const onFileSelect = useCallback((filePath: string | undefined) => {
|
||||
workbenchStore.setSelectedFile(filePath);
|
||||
}, []);
|
||||
|
||||
const onFileSave = useCallback(() => {
|
||||
workbenchStore.saveCurrentDocument().catch(() => {
|
||||
toast.error('Failed to update file content');
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onFileReset = useCallback(() => {
|
||||
workbenchStore.resetCurrentDocument();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
chatStarted && (
|
||||
<motion.div
|
||||
initial="closed"
|
||||
animate={showWorkbench ? 'open' : 'closed'}
|
||||
variants={workbenchVariants}
|
||||
className="z-workbench"
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
'fixed top-[calc(var(--header-height)+1.5rem)] bottom-6 w-[var(--workbench-inner-width)] mr-4 z-0 transition-[left,width] duration-200 bolt-ease-cubic-bezier',
|
||||
{
|
||||
'left-[var(--workbench-left)]': showWorkbench,
|
||||
'left-[100%]': !showWorkbench,
|
||||
},
|
||||
)}
|
||||
>
|
||||
<div className="absolute inset-0 px-6">
|
||||
<div className="h-full flex flex-col bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor shadow-sm rounded-lg overflow-hidden">
|
||||
<div className="flex items-center px-3 py-2 border-b border-bolt-elements-borderColor">
|
||||
<Slider selected={selectedView} options={sliderOptions} setSelected={setSelectedView} />
|
||||
<div className="ml-auto" />
|
||||
{selectedView === 'code' && (
|
||||
<PanelHeaderButton
|
||||
className="mr-1 text-sm"
|
||||
onClick={() => {
|
||||
workbenchStore.toggleTerminal(!workbenchStore.showTerminal.get());
|
||||
}}
|
||||
>
|
||||
<div className="i-ph:terminal" />
|
||||
Toggle Terminal
|
||||
</PanelHeaderButton>
|
||||
)}
|
||||
<IconButton
|
||||
icon="i-ph:x-circle"
|
||||
className="-mr-1"
|
||||
size="xl"
|
||||
onClick={() => {
|
||||
workbenchStore.showWorkbench.set(false);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="relative flex-1 overflow-hidden">
|
||||
<View
|
||||
initial={{ x: selectedView === 'code' ? 0 : '-100%' }}
|
||||
animate={{ x: selectedView === 'code' ? 0 : '-100%' }}
|
||||
>
|
||||
<EditorPanel
|
||||
editorDocument={currentDocument}
|
||||
isStreaming={isStreaming}
|
||||
selectedFile={selectedFile}
|
||||
files={files}
|
||||
unsavedFiles={unsavedFiles}
|
||||
onFileSelect={onFileSelect}
|
||||
onEditorScroll={onEditorScroll}
|
||||
onEditorChange={onEditorChange}
|
||||
onFileSave={onFileSave}
|
||||
onFileReset={onFileReset}
|
||||
/>
|
||||
</View>
|
||||
<View
|
||||
initial={{ x: selectedView === 'preview' ? 0 : '100%' }}
|
||||
animate={{ x: selectedView === 'preview' ? 0 : '100%' }}
|
||||
>
|
||||
<Preview />
|
||||
</View>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
interface ViewProps extends HTMLMotionProps<'div'> {
|
||||
children: JSX.Element;
|
||||
}
|
||||
|
||||
const View = memo(({ children, ...props }: ViewProps) => {
|
||||
return (
|
||||
<motion.div className="absolute inset-0" transition={viewTransition} {...props}>
|
||||
{children}
|
||||
</motion.div>
|
||||
);
|
||||
});
|
||||
86
app/components/workbench/terminal/Terminal.tsx
Normal file
86
app/components/workbench/terminal/Terminal.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
import { WebLinksAddon } from '@xterm/addon-web-links';
|
||||
import { Terminal as XTerm } from '@xterm/xterm';
|
||||
import { forwardRef, memo, useEffect, useImperativeHandle, useRef } from 'react';
|
||||
import type { Theme } from '~/lib/stores/theme';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
import { getTerminalTheme } from './theme';
|
||||
|
||||
const logger = createScopedLogger('Terminal');
|
||||
|
||||
export interface TerminalRef {
|
||||
reloadStyles: () => void;
|
||||
}
|
||||
|
||||
export interface TerminalProps {
|
||||
className?: string;
|
||||
theme: Theme;
|
||||
readonly?: boolean;
|
||||
onTerminalReady?: (terminal: XTerm) => void;
|
||||
onTerminalResize?: (cols: number, rows: number) => void;
|
||||
}
|
||||
|
||||
export const Terminal = memo(
|
||||
forwardRef<TerminalRef, TerminalProps>(({ className, theme, readonly, onTerminalReady, onTerminalResize }, ref) => {
|
||||
const terminalElementRef = useRef<HTMLDivElement>(null);
|
||||
const terminalRef = useRef<XTerm>();
|
||||
|
||||
useEffect(() => {
|
||||
const element = terminalElementRef.current!;
|
||||
|
||||
const fitAddon = new FitAddon();
|
||||
const webLinksAddon = new WebLinksAddon();
|
||||
|
||||
const terminal = new XTerm({
|
||||
cursorBlink: true,
|
||||
convertEol: true,
|
||||
disableStdin: readonly,
|
||||
theme: getTerminalTheme(readonly ? { cursor: '#00000000' } : {}),
|
||||
fontSize: 12,
|
||||
fontFamily: 'Menlo, courier-new, courier, monospace',
|
||||
});
|
||||
|
||||
terminalRef.current = terminal;
|
||||
|
||||
terminal.loadAddon(fitAddon);
|
||||
terminal.loadAddon(webLinksAddon);
|
||||
terminal.open(element);
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
fitAddon.fit();
|
||||
onTerminalResize?.(terminal.cols, terminal.rows);
|
||||
});
|
||||
|
||||
resizeObserver.observe(element);
|
||||
|
||||
logger.info('Attach terminal');
|
||||
|
||||
onTerminalReady?.(terminal);
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
terminal.dispose();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const terminal = terminalRef.current!;
|
||||
|
||||
// we render a transparent cursor in case the terminal is readonly
|
||||
terminal.options.theme = getTerminalTheme(readonly ? { cursor: '#00000000' } : {});
|
||||
|
||||
terminal.options.disableStdin = readonly;
|
||||
}, [theme, readonly]);
|
||||
|
||||
useImperativeHandle(ref, () => {
|
||||
return {
|
||||
reloadStyles: () => {
|
||||
const terminal = terminalRef.current!;
|
||||
terminal.options.theme = getTerminalTheme(readonly ? { cursor: '#00000000' } : {});
|
||||
},
|
||||
};
|
||||
}, []);
|
||||
|
||||
return <div className={className} ref={terminalElementRef} />;
|
||||
}),
|
||||
);
|
||||
36
app/components/workbench/terminal/theme.ts
Normal file
36
app/components/workbench/terminal/theme.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { ITheme } from '@xterm/xterm';
|
||||
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
const cssVar = (token: string) => style.getPropertyValue(token) || undefined;
|
||||
|
||||
export function getTerminalTheme(overrides?: ITheme): ITheme {
|
||||
return {
|
||||
cursor: cssVar('--bolt-elements-terminal-cursorColor'),
|
||||
cursorAccent: cssVar('--bolt-elements-terminal-cursorColorAccent'),
|
||||
foreground: cssVar('--bolt-elements-terminal-textColor'),
|
||||
background: cssVar('--bolt-elements-terminal-backgroundColor'),
|
||||
selectionBackground: cssVar('--bolt-elements-terminal-selection-backgroundColor'),
|
||||
selectionForeground: cssVar('--bolt-elements-terminal-selection-textColor'),
|
||||
selectionInactiveBackground: cssVar('--bolt-elements-terminal-selection-backgroundColorInactive'),
|
||||
|
||||
// ansi escape code colors
|
||||
black: cssVar('--bolt-elements-terminal-color-black'),
|
||||
red: cssVar('--bolt-elements-terminal-color-red'),
|
||||
green: cssVar('--bolt-elements-terminal-color-green'),
|
||||
yellow: cssVar('--bolt-elements-terminal-color-yellow'),
|
||||
blue: cssVar('--bolt-elements-terminal-color-blue'),
|
||||
magenta: cssVar('--bolt-elements-terminal-color-magenta'),
|
||||
cyan: cssVar('--bolt-elements-terminal-color-cyan'),
|
||||
white: cssVar('--bolt-elements-terminal-color-white'),
|
||||
brightBlack: cssVar('--bolt-elements-terminal-color-brightBlack'),
|
||||
brightRed: cssVar('--bolt-elements-terminal-color-brightRed'),
|
||||
brightGreen: cssVar('--bolt-elements-terminal-color-brightGreen'),
|
||||
brightYellow: cssVar('--bolt-elements-terminal-color-brightYellow'),
|
||||
brightBlue: cssVar('--bolt-elements-terminal-color-brightBlue'),
|
||||
brightMagenta: cssVar('--bolt-elements-terminal-color-brightMagenta'),
|
||||
brightCyan: cssVar('--bolt-elements-terminal-color-brightCyan'),
|
||||
brightWhite: cssVar('--bolt-elements-terminal-color-brightWhite'),
|
||||
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
7
app/entry.client.tsx
Normal file
7
app/entry.client.tsx
Normal file
@@ -0,0 +1,7 @@
|
||||
import { RemixBrowser } from '@remix-run/react';
|
||||
import { startTransition } from 'react';
|
||||
import { hydrateRoot } from 'react-dom/client';
|
||||
|
||||
startTransition(() => {
|
||||
hydrateRoot(document, <RemixBrowser />);
|
||||
});
|
||||
34
app/entry.server.tsx
Normal file
34
app/entry.server.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { AppLoadContext, EntryContext } from '@remix-run/cloudflare';
|
||||
import { RemixServer } from '@remix-run/react';
|
||||
import { isbot } from 'isbot';
|
||||
import { renderToReadableStream } from 'react-dom/server';
|
||||
|
||||
export default async function handleRequest(
|
||||
request: Request,
|
||||
responseStatusCode: number,
|
||||
responseHeaders: Headers,
|
||||
remixContext: EntryContext,
|
||||
_loadContext: AppLoadContext,
|
||||
) {
|
||||
const body = await renderToReadableStream(<RemixServer context={remixContext} url={request.url} />, {
|
||||
signal: request.signal,
|
||||
onError(error: unknown) {
|
||||
console.error(error);
|
||||
responseStatusCode = 500;
|
||||
},
|
||||
});
|
||||
|
||||
if (isbot(request.headers.get('user-agent') || '')) {
|
||||
await body.allReady;
|
||||
}
|
||||
|
||||
responseHeaders.set('Content-Type', 'text/html');
|
||||
|
||||
responseHeaders.set('Cross-Origin-Embedder-Policy', 'require-corp');
|
||||
responseHeaders.set('Cross-Origin-Opener-Policy', 'same-origin');
|
||||
|
||||
return new Response(body, {
|
||||
headers: responseHeaders,
|
||||
status: responseStatusCode,
|
||||
});
|
||||
}
|
||||
41
app/lib/.server/auth.ts
Normal file
41
app/lib/.server/auth.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { json, redirect, type LoaderFunctionArgs, type TypedResponse } from '@remix-run/cloudflare';
|
||||
import { isAuthenticated, type Session } from './sessions';
|
||||
|
||||
type RequestArgs = Pick<LoaderFunctionArgs, 'request' | 'context'>;
|
||||
|
||||
export async function loadWithAuth<T extends RequestArgs>(
|
||||
args: T,
|
||||
handler: (args: T, session: Session) => Promise<Response>,
|
||||
) {
|
||||
return handleWithAuth(args, handler, (response) => redirect('/login', response));
|
||||
}
|
||||
|
||||
export async function actionWithAuth<T extends RequestArgs>(
|
||||
args: T,
|
||||
handler: (args: T, session: Session) => Promise<TypedResponse>,
|
||||
) {
|
||||
return await handleWithAuth(args, handler, (response) => json({}, { status: 401, ...response }));
|
||||
}
|
||||
|
||||
async function handleWithAuth<T extends RequestArgs, R extends TypedResponse>(
|
||||
args: T,
|
||||
handler: (args: T, session: Session) => Promise<R>,
|
||||
fallback: (partial: ResponseInit) => R,
|
||||
) {
|
||||
const { request, context } = args;
|
||||
const { session, response } = await isAuthenticated(request, context.cloudflare.env);
|
||||
|
||||
if (session == null && !import.meta.env.VITE_DISABLE_AUTH) {
|
||||
return fallback(response);
|
||||
}
|
||||
|
||||
const handlerResponse = await handler(args, session || {});
|
||||
|
||||
if (response) {
|
||||
for (const [key, value] of Object.entries(response.headers)) {
|
||||
handlerResponse.headers.append(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
return handlerResponse;
|
||||
}
|
||||
9
app/lib/.server/llm/api-key.ts
Normal file
9
app/lib/.server/llm/api-key.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { env } from 'node:process';
|
||||
|
||||
export function getAPIKey(cloudflareEnv: Env) {
|
||||
/**
|
||||
* The `cloudflareEnv` is only used when deployed or when previewing locally.
|
||||
* In development the environment variables are available through `env`.
|
||||
*/
|
||||
return env.ANTHROPIC_API_KEY || cloudflareEnv.ANTHROPIC_API_KEY;
|
||||
}
|
||||
5
app/lib/.server/llm/constants.ts
Normal file
5
app/lib/.server/llm/constants.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
// see https://docs.anthropic.com/en/docs/about-claude/models
|
||||
export const MAX_TOKENS = 8192;
|
||||
|
||||
// limits the number of model responses that can be returned in a single request
|
||||
export const MAX_RESPONSE_SEGMENTS = 2;
|
||||
9
app/lib/.server/llm/model.ts
Normal file
9
app/lib/.server/llm/model.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { createAnthropic } from '@ai-sdk/anthropic';
|
||||
|
||||
export function getAnthropicModel(apiKey: string) {
|
||||
const anthropic = createAnthropic({
|
||||
apiKey,
|
||||
});
|
||||
|
||||
return anthropic('claude-3-5-sonnet-20240620');
|
||||
}
|
||||
284
app/lib/.server/llm/prompts.ts
Normal file
284
app/lib/.server/llm/prompts.ts
Normal file
@@ -0,0 +1,284 @@
|
||||
import { MODIFICATIONS_TAG_NAME, WORK_DIR } from '~/utils/constants';
|
||||
import { allowedHTMLElements } from '~/utils/markdown';
|
||||
import { stripIndents } from '~/utils/stripIndent';
|
||||
|
||||
export const getSystemPrompt = (cwd: string = WORK_DIR) => `
|
||||
You are Bolt, an expert AI assistant and exceptional senior software developer with vast knowledge across multiple programming languages, frameworks, and best practices.
|
||||
|
||||
<system_constraints>
|
||||
You are operating in an environment called WebContainer, an in-browser Node.js runtime that emulates a Linux system to some degree. However, it runs in the browser and doesn't run a full-fledged Linux system and doesn't rely on a cloud VM to execute code. All code is executed in the browser. It does come with a shell that emulates zsh. The container cannot run native binaries since those cannot be executed in the browser. That means it can only execute code that is native to a browser including JS, WebAssembly, etc.
|
||||
|
||||
The shell comes with \`python\` and \`python3\` binaries, but they are LIMITED TO THE PYTHON STANDARD LIBRARY ONLY This means:
|
||||
|
||||
- There is NO \`pip\` support! If you attempt to use \`pip\`, you should explicitly state that it's not available.
|
||||
- CRITICAL: Third-party libraries cannot be installed or imported.
|
||||
- Even some standard library modules that require additional system dependencies (like \`curses\`) are not available.
|
||||
- Only modules from the core Python standard library can be used.
|
||||
|
||||
Additionally, there is no \`g++\` or any C/C++ compiler available. WebContainer CANNOT run native binaries or compile C/C++ code!
|
||||
|
||||
Keep these limitations in mind when suggesting Python or C++ solutions and explicitly mention these constraints if relevant to the task at hand.
|
||||
|
||||
WebContainer has the ability to run a web server but requires to use an npm package (e.g., Vite, servor, serve, http-server) or use the Node.js APIs to implement a web server.
|
||||
|
||||
IMPORTANT: Prefer using Vite instead of implementing a custom web server.
|
||||
|
||||
IMPORTANT: Git is NOT available.
|
||||
|
||||
IMPORTANT: Prefer writing Node.js scripts instead of shell scripts. The environment doesn't fully support shell scripts, so use Node.js for scripting tasks whenever possible!
|
||||
|
||||
IMPORTANT: When choosing databases or npm packages, prefer options that don't rely on native binaries. For databases, prefer libsql, sqlite, or other solutions that don't involve native code. WebContainer CANNOT execute arbitrary native binaries.
|
||||
|
||||
Available shell commands: cat, chmod, cp, echo, hostname, kill, ln, ls, mkdir, mv, ps, pwd, rm, rmdir, xxd, alias, cd, clear, curl, env, false, getconf, head, sort, tail, touch, true, uptime, which, code, jq, loadenv, node, python3, wasm, xdg-open, command, exit, export, source
|
||||
</system_constraints>
|
||||
|
||||
<code_formatting_info>
|
||||
Use 2 spaces for code indentation
|
||||
</code_formatting_info>
|
||||
|
||||
<message_formatting_info>
|
||||
You can make the output pretty by using only the following available HTML elements: ${allowedHTMLElements.map((tagName) => `<${tagName}>`).join(', ')}
|
||||
</message_formatting_info>
|
||||
|
||||
<diff_spec>
|
||||
For user-made file modifications, a \`<${MODIFICATIONS_TAG_NAME}>\` section will appear at the start of the user message. It will contain either \`<diff>\` or \`<file>\` elements for each modified file:
|
||||
|
||||
- \`<diff path="/some/file/path.ext">\`: Contains GNU unified diff format changes
|
||||
- \`<file path="/some/file/path.ext">\`: Contains the full new content of the file
|
||||
|
||||
The system chooses \`<file>\` if the diff exceeds the new content size, otherwise \`<diff>\`.
|
||||
|
||||
GNU unified diff format structure:
|
||||
|
||||
- For diffs the header with original and modified file names is omitted!
|
||||
- Changed sections start with @@ -X,Y +A,B @@ where:
|
||||
- X: Original file starting line
|
||||
- Y: Original file line count
|
||||
- A: Modified file starting line
|
||||
- B: Modified file line count
|
||||
- (-) lines: Removed from original
|
||||
- (+) lines: Added in modified version
|
||||
- Unmarked lines: Unchanged context
|
||||
|
||||
Example:
|
||||
|
||||
<${MODIFICATIONS_TAG_NAME}>
|
||||
<diff path="/home/project/src/main.js">
|
||||
@@ -2,7 +2,10 @@
|
||||
return a + b;
|
||||
}
|
||||
|
||||
-console.log('Hello, World!');
|
||||
+console.log('Hello, Bolt!');
|
||||
+
|
||||
function greet() {
|
||||
- return 'Greetings!';
|
||||
+ return 'Greetings!!';
|
||||
}
|
||||
+
|
||||
+console.log('The End');
|
||||
</diff>
|
||||
<file path="/home/project/package.json">
|
||||
// full file content here
|
||||
</file>
|
||||
</${MODIFICATIONS_TAG_NAME}>
|
||||
</diff_spec>
|
||||
|
||||
<artifact_info>
|
||||
Bolt creates a SINGLE, comprehensive artifact for each project. The artifact contains all necessary steps and components, including:
|
||||
|
||||
- Shell commands to run including dependencies to install using a package manager (NPM)
|
||||
- Files to create and their contents
|
||||
- Folders to create if necessary
|
||||
|
||||
<artifact_instructions>
|
||||
1. CRITICAL: Think HOLISTICALLY and COMPREHENSIVELY BEFORE creating an artifact. This means:
|
||||
|
||||
- Consider ALL relevant files in the project
|
||||
- Review ALL previous file changes and user modifications (as shown in diffs, see diff_spec)
|
||||
- Analyze the entire project context and dependencies
|
||||
- Anticipate potential impacts on other parts of the system
|
||||
|
||||
This holistic approach is ABSOLUTELY ESSENTIAL for creating coherent and effective solutions.
|
||||
|
||||
2. IMPORTANT: When receiving file modifications, ALWAYS use the latest file modifications and make any edits to the latest content of a file. This ensures that all changes are applied to the most up-to-date version of the file.
|
||||
|
||||
3. The current working directory is \`${cwd}\`.
|
||||
|
||||
4. Wrap the content in opening and closing \`<boltArtifact>\` tags. These tags contain more specific \`<boltAction>\` elements.
|
||||
|
||||
5. Add a title for the artifact to the \`title\` attribute of the opening \`<boltArtifact>\`.
|
||||
|
||||
6. Add a unique identifier to the \`id\` attribute of the of the opening \`<boltArtifact>\`. For updates, reuse the prior identifier. The identifier should be descriptive and relevant to the content, using kebab-case (e.g., "example-code-snippet"). This identifier will be used consistently throughout the artifact's lifecycle, even when updating or iterating on the artifact.
|
||||
|
||||
7. Use \`<boltAction>\` tags to define specific actions to perform.
|
||||
|
||||
8. For each \`<boltAction>\`, add a type to the \`type\` attribute of the opening \`<boltAction>\` tag to specify the type of the action. Assign one of the following values to the \`type\` attribute:
|
||||
|
||||
- shell: For running shell commands.
|
||||
|
||||
- When Using \`npx\`, ALWAYS provide the \`--yes\` flag.
|
||||
- When running multiple shell commands, use \`&&\` to run them sequentially.
|
||||
- ULTRA IMPORTANT: Do NOT re-run a dev command if there is one that starts a dev server and new dependencies were installed or files updated! If a dev server has started already, assume that installing dependencies will be executed in a different process and will be picked up by the dev server.
|
||||
|
||||
- file: For writing new files or updating existing files. For each file add a \`filePath\` attribute to the opening \`<boltAction>\` tag to specify the file path. The content of the file artifact is the file contents. All file paths MUST BE relative to the current working directory.
|
||||
|
||||
9. The order of the actions is VERY IMPORTANT. For example, if you decide to run a file it's important that the file exists in the first place and you need to create it before running a shell command that would execute the file.
|
||||
|
||||
10. ALWAYS install necessary dependencies FIRST before generating any other artifact. If that requires a \`package.json\` then you should create that first!
|
||||
|
||||
IMPORTANT: Add all required dependencies to the \`package.json\` already and try to avoid \`npm i <pkg>\` if possible!
|
||||
|
||||
11. CRITICAL: Always provide the FULL, updated content of the artifact. This means:
|
||||
|
||||
- Include ALL code, even if parts are unchanged
|
||||
- NEVER use placeholders like "// rest of the code remains the same..." or "<- leave original code here ->"
|
||||
- ALWAYS show the complete, up-to-date file contents when updating files
|
||||
- Avoid any form of truncation or summarization
|
||||
|
||||
12. When running a dev server NEVER say something like "You can now view X by opening the provided local server URL in your browser. The preview will be opened automatically or by the user manually!
|
||||
|
||||
13. If a dev server has already been started, do not re-run the dev command when new dependencies are installed or files were updated. Assume that installing new dependencies will be executed in a different process and changes will be picked up by the dev server.
|
||||
|
||||
14. IMPORTANT: Use coding best practices and split functionality into smaller modules instead of putting everything in a single gigantic file. Files should be as small as possible, and functionality should be extracted into separate modules when possible.
|
||||
|
||||
- Ensure code is clean, readable, and maintainable.
|
||||
- Adhere to proper naming conventions and consistent formatting.
|
||||
- Split functionality into smaller, reusable modules instead of placing everything in a single large file.
|
||||
- Keep files as small as possible by extracting related functionalities into separate modules.
|
||||
- Use imports to connect these modules together effectively.
|
||||
</artifact_instructions>
|
||||
</artifact_info>
|
||||
|
||||
NEVER use the word "artifact". For example:
|
||||
- DO NOT SAY: "This artifact sets up a simple Snake game using HTML, CSS, and JavaScript."
|
||||
- INSTEAD SAY: "We set up a simple Snake game using HTML, CSS, and JavaScript."
|
||||
|
||||
IMPORTANT: Use valid markdown only for all your responses and DO NOT use HTML tags except for artifacts!
|
||||
|
||||
ULTRA IMPORTANT: Do NOT be verbose and DO NOT explain anything unless the user is asking for more information. That is VERY important.
|
||||
|
||||
ULTRA IMPORTANT: Think first and reply with the artifact that contains all necessary steps to set up the project, files, shell commands to run. It is SUPER IMPORTANT to respond with this first.
|
||||
|
||||
Here are some examples of correct usage of artifacts:
|
||||
|
||||
<examples>
|
||||
<example>
|
||||
<user_query>Can you help me create a JavaScript function to calculate the factorial of a number?</user_query>
|
||||
|
||||
<assistant_response>
|
||||
Certainly, I can help you create a JavaScript function to calculate the factorial of a number.
|
||||
|
||||
<boltArtifact id="factorial-function" title="JavaScript Factorial Function">
|
||||
<boltAction type="file" filePath="index.js">
|
||||
function factorial(n) {
|
||||
...
|
||||
}
|
||||
|
||||
...
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="shell">
|
||||
node index.js
|
||||
</boltAction>
|
||||
</boltArtifact>
|
||||
</assistant_response>
|
||||
</example>
|
||||
|
||||
<example>
|
||||
<user_query>Build a snake game</user_query>
|
||||
|
||||
<assistant_response>
|
||||
Certainly! I'd be happy to help you build a snake game using JavaScript and HTML5 Canvas. This will be a basic implementation that you can later expand upon. Let's create the game step by step.
|
||||
|
||||
<boltArtifact id="snake-game" title="Snake Game in HTML and JavaScript">
|
||||
<boltAction type="file" filePath="package.json">
|
||||
{
|
||||
"name": "snake",
|
||||
"scripts": {
|
||||
"dev": "vite"
|
||||
}
|
||||
...
|
||||
}
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="shell">
|
||||
npm install --save-dev vite
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="file" filePath="index.html">
|
||||
...
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="shell">
|
||||
npm run dev
|
||||
</boltAction>
|
||||
</boltArtifact>
|
||||
|
||||
Now you can play the Snake game by opening the provided local server URL in your browser. Use the arrow keys to control the snake. Eat the red food to grow and increase your score. The game ends if you hit the wall or your own tail.
|
||||
</assistant_response>
|
||||
</example>
|
||||
|
||||
<example>
|
||||
<user_query>Make a bouncing ball with real gravity using React</user_query>
|
||||
|
||||
<assistant_response>
|
||||
Certainly! I'll create a bouncing ball with real gravity using React. We'll use the react-spring library for physics-based animations.
|
||||
|
||||
<boltArtifact id="bouncing-ball-react" title="Bouncing Ball with Gravity in React">
|
||||
<boltAction type="file" filePath="package.json">
|
||||
{
|
||||
"name": "bouncing-ball",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-spring": "^9.7.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.0.28",
|
||||
"@types/react-dom": "^18.0.11",
|
||||
"@vitejs/plugin-react": "^3.1.0",
|
||||
"vite": "^4.2.0"
|
||||
}
|
||||
}
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="file" filePath="index.html">
|
||||
...
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="file" filePath="src/main.jsx">
|
||||
...
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="file" filePath="src/index.css">
|
||||
...
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="file" filePath="src/App.jsx">
|
||||
...
|
||||
</boltAction>
|
||||
|
||||
<boltAction type="shell">
|
||||
npm run dev
|
||||
</boltAction>
|
||||
</boltArtifact>
|
||||
|
||||
You can now view the bouncing ball animation in the preview. The ball will start falling from the top of the screen and bounce realistically when it hits the bottom.
|
||||
</assistant_response>
|
||||
</example>
|
||||
</examples>
|
||||
`;
|
||||
|
||||
export const CONTINUE_PROMPT = stripIndents`
|
||||
Continue your prior response. IMPORTANT: Immediately begin from where you left off without any interruptions.
|
||||
Do not repeat any content, including artifact and action tags.
|
||||
`;
|
||||
35
app/lib/.server/llm/stream-text.ts
Normal file
35
app/lib/.server/llm/stream-text.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { streamText as _streamText, convertToCoreMessages } from 'ai';
|
||||
import { getAPIKey } from '~/lib/.server/llm/api-key';
|
||||
import { getAnthropicModel } from '~/lib/.server/llm/model';
|
||||
import { MAX_TOKENS } from './constants';
|
||||
import { getSystemPrompt } from './prompts';
|
||||
|
||||
interface ToolResult<Name extends string, Args, Result> {
|
||||
toolCallId: string;
|
||||
toolName: Name;
|
||||
args: Args;
|
||||
result: Result;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
toolInvocations?: ToolResult<string, unknown, unknown>[];
|
||||
}
|
||||
|
||||
export type Messages = Message[];
|
||||
|
||||
export type StreamingOptions = Omit<Parameters<typeof _streamText>[0], 'model'>;
|
||||
|
||||
export function streamText(messages: Messages, env: Env, options?: StreamingOptions) {
|
||||
return _streamText({
|
||||
model: getAnthropicModel(getAPIKey(env)),
|
||||
system: getSystemPrompt(),
|
||||
maxTokens: MAX_TOKENS,
|
||||
headers: {
|
||||
'anthropic-beta': 'max-tokens-3-5-sonnet-2024-07-15',
|
||||
},
|
||||
messages: convertToCoreMessages(messages),
|
||||
...options,
|
||||
});
|
||||
}
|
||||
66
app/lib/.server/llm/switchable-stream.ts
Normal file
66
app/lib/.server/llm/switchable-stream.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
export default class SwitchableStream extends TransformStream {
|
||||
private _controller: TransformStreamDefaultController | null = null;
|
||||
private _currentReader: ReadableStreamDefaultReader | null = null;
|
||||
private _switches = 0;
|
||||
|
||||
constructor() {
|
||||
let controllerRef: TransformStreamDefaultController | undefined;
|
||||
|
||||
super({
|
||||
start(controller) {
|
||||
controllerRef = controller;
|
||||
},
|
||||
});
|
||||
|
||||
if (controllerRef === undefined) {
|
||||
throw new Error('Controller not properly initialized');
|
||||
}
|
||||
|
||||
this._controller = controllerRef;
|
||||
}
|
||||
|
||||
async switchSource(newStream: ReadableStream) {
|
||||
if (this._currentReader) {
|
||||
await this._currentReader.cancel();
|
||||
}
|
||||
|
||||
this._currentReader = newStream.getReader();
|
||||
|
||||
this._pumpStream();
|
||||
|
||||
this._switches++;
|
||||
}
|
||||
|
||||
private async _pumpStream() {
|
||||
if (!this._currentReader || !this._controller) {
|
||||
throw new Error('Stream is not properly initialized');
|
||||
}
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await this._currentReader.read();
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
this._controller.enqueue(value);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
this._controller.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this._currentReader) {
|
||||
this._currentReader.cancel();
|
||||
}
|
||||
|
||||
this._controller?.terminate();
|
||||
}
|
||||
|
||||
get switches() {
|
||||
return this._switches;
|
||||
}
|
||||
}
|
||||
240
app/lib/.server/sessions.ts
Normal file
240
app/lib/.server/sessions.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
import { createCookieSessionStorage, redirect, type Session as RemixSession } from '@remix-run/cloudflare';
|
||||
import { decodeJwt } from 'jose';
|
||||
import { CLIENT_ID, CLIENT_ORIGIN } from '~/lib/constants';
|
||||
import { request as doRequest } from '~/lib/fetch';
|
||||
import { logger } from '~/utils/logger';
|
||||
import type { Identity } from '~/lib/analytics';
|
||||
import { decrypt, encrypt } from '~/lib/crypto';
|
||||
|
||||
const DEV_SESSION_SECRET = import.meta.env.DEV ? 'LZQMrERo3Ewn/AbpSYJ9aw==' : undefined;
|
||||
const DEV_PAYLOAD_SECRET = import.meta.env.DEV ? '2zAyrhjcdFeXk0YEDzilMXbdrGAiR+8ACIUgFNfjLaI=' : undefined;
|
||||
|
||||
const TOKEN_KEY = 't';
|
||||
const EXPIRES_KEY = 'e';
|
||||
const USER_ID_KEY = 'u';
|
||||
const SEGMENT_KEY = 's';
|
||||
const AVATAR_KEY = 'a';
|
||||
const ENCRYPTED_KEY = 'd';
|
||||
|
||||
interface PrivateSession {
|
||||
[TOKEN_KEY]: string;
|
||||
[EXPIRES_KEY]: number;
|
||||
[USER_ID_KEY]?: string;
|
||||
[SEGMENT_KEY]?: string;
|
||||
}
|
||||
|
||||
interface PublicSession {
|
||||
[ENCRYPTED_KEY]: string;
|
||||
[AVATAR_KEY]?: string;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
userId?: string;
|
||||
segmentWriteKey?: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export async function isAuthenticated(request: Request, env: Env) {
|
||||
const { session, sessionStorage } = await getSession(request, env);
|
||||
|
||||
const sessionData: PrivateSession | null = await decryptSessionData(env, session.get(ENCRYPTED_KEY));
|
||||
|
||||
const header = async (cookie: Promise<string>) => ({ headers: { 'Set-Cookie': await cookie } });
|
||||
const destroy = () => header(sessionStorage.destroySession(session));
|
||||
|
||||
if (sessionData?.[TOKEN_KEY] == null) {
|
||||
return { session: null, response: await destroy() };
|
||||
}
|
||||
|
||||
const expiresAt = sessionData[EXPIRES_KEY] ?? 0;
|
||||
|
||||
if (Date.now() < expiresAt) {
|
||||
return { session: getSessionData(session, sessionData) };
|
||||
}
|
||||
|
||||
logger.debug('Renewing token');
|
||||
|
||||
let data: Awaited<ReturnType<typeof refreshToken>> | null = null;
|
||||
|
||||
try {
|
||||
data = await refreshToken(sessionData[TOKEN_KEY]);
|
||||
} catch (error) {
|
||||
// we can ignore the error here because it's handled below
|
||||
logger.error(error);
|
||||
}
|
||||
|
||||
if (data != null) {
|
||||
const expiresAt = cookieExpiration(data.expires_in, data.created_at);
|
||||
|
||||
const newSessionData = { ...sessionData, [EXPIRES_KEY]: expiresAt };
|
||||
const encryptedData = await encryptSessionData(env, newSessionData);
|
||||
|
||||
session.set(ENCRYPTED_KEY, encryptedData);
|
||||
|
||||
return {
|
||||
session: getSessionData(session, newSessionData),
|
||||
response: await header(sessionStorage.commitSession(session)),
|
||||
};
|
||||
} else {
|
||||
return { session: null, response: await destroy() };
|
||||
}
|
||||
}
|
||||
|
||||
export async function createUserSession(
|
||||
request: Request,
|
||||
env: Env,
|
||||
tokens: { refresh: string; expires_in: number; created_at: number },
|
||||
identity?: Identity,
|
||||
): Promise<ResponseInit> {
|
||||
const { session, sessionStorage } = await getSession(request, env);
|
||||
|
||||
const expiresAt = cookieExpiration(tokens.expires_in, tokens.created_at);
|
||||
|
||||
const sessionData: PrivateSession = {
|
||||
[TOKEN_KEY]: tokens.refresh,
|
||||
[EXPIRES_KEY]: expiresAt,
|
||||
[USER_ID_KEY]: identity?.userId ?? undefined,
|
||||
[SEGMENT_KEY]: identity?.segmentWriteKey ?? undefined,
|
||||
};
|
||||
|
||||
const encryptedData = await encryptSessionData(env, sessionData);
|
||||
session.set(ENCRYPTED_KEY, encryptedData);
|
||||
session.set(AVATAR_KEY, identity?.avatar);
|
||||
|
||||
return {
|
||||
headers: {
|
||||
'Set-Cookie': await sessionStorage.commitSession(session, {
|
||||
maxAge: 3600 * 24 * 30, // 1 month
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getSessionStorage(cloudflareEnv: Env) {
|
||||
return createCookieSessionStorage<PublicSession>({
|
||||
cookie: {
|
||||
name: '__session',
|
||||
httpOnly: true,
|
||||
path: '/',
|
||||
secrets: [DEV_SESSION_SECRET || cloudflareEnv.SESSION_SECRET],
|
||||
secure: import.meta.env.PROD,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function logout(request: Request, env: Env) {
|
||||
const { session, sessionStorage } = await getSession(request, env);
|
||||
|
||||
const sessionData = await decryptSessionData(env, session.get(ENCRYPTED_KEY));
|
||||
|
||||
if (sessionData) {
|
||||
revokeToken(sessionData[TOKEN_KEY]);
|
||||
}
|
||||
|
||||
return redirect('/login', {
|
||||
headers: {
|
||||
'Set-Cookie': await sessionStorage.destroySession(session),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function validateAccessToken(access: string) {
|
||||
const jwtPayload = decodeJwt(access);
|
||||
|
||||
return jwtPayload.bolt === true;
|
||||
}
|
||||
|
||||
function getSessionData(session: RemixSession<PublicSession>, data: PrivateSession): Session {
|
||||
return {
|
||||
userId: data?.[USER_ID_KEY],
|
||||
segmentWriteKey: data?.[SEGMENT_KEY],
|
||||
avatar: session.get(AVATAR_KEY),
|
||||
};
|
||||
}
|
||||
|
||||
async function getSession(request: Request, env: Env) {
|
||||
const sessionStorage = getSessionStorage(env);
|
||||
const cookie = request.headers.get('Cookie');
|
||||
|
||||
return { session: await sessionStorage.getSession(cookie), sessionStorage };
|
||||
}
|
||||
|
||||
async function refreshToken(refresh: string): Promise<{ expires_in: number; created_at: number }> {
|
||||
const response = await doRequest(`${CLIENT_ORIGIN}/oauth/token`, {
|
||||
method: 'POST',
|
||||
body: urlParams({ grant_type: 'refresh_token', client_id: CLIENT_ID, refresh_token: refresh }),
|
||||
headers: {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
});
|
||||
|
||||
const body = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unable to refresh token\n${response.status} ${JSON.stringify(body)}`);
|
||||
}
|
||||
|
||||
const { access_token: access } = body;
|
||||
|
||||
if (!validateAccessToken(access)) {
|
||||
throw new Error('User is no longer authorized for Bolt');
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
function cookieExpiration(expireIn: number, createdAt: number) {
|
||||
return (expireIn + createdAt - 10 * 60) * 1000;
|
||||
}
|
||||
|
||||
async function revokeToken(refresh?: string) {
|
||||
if (refresh == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await doRequest(`${CLIENT_ORIGIN}/oauth/revoke`, {
|
||||
method: 'POST',
|
||||
body: urlParams({
|
||||
token: refresh,
|
||||
token_type_hint: 'refresh_token',
|
||||
client_id: CLIENT_ID,
|
||||
}),
|
||||
headers: {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unable to revoke token: ${response.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.debug(error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function urlParams(data: Record<string, string>) {
|
||||
const encoded = new URLSearchParams();
|
||||
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
encoded.append(key, value);
|
||||
}
|
||||
|
||||
return encoded;
|
||||
}
|
||||
|
||||
async function decryptSessionData(env: Env, encryptedData?: string) {
|
||||
const decryptedData = encryptedData ? await decrypt(payloadSecret(env), encryptedData) : undefined;
|
||||
const sessionData: PrivateSession | null = JSON.parse(decryptedData ?? 'null');
|
||||
|
||||
return sessionData;
|
||||
}
|
||||
|
||||
async function encryptSessionData(env: Env, sessionData: PrivateSession) {
|
||||
return await encrypt(payloadSecret(env), JSON.stringify(sessionData));
|
||||
}
|
||||
|
||||
function payloadSecret(env: Env) {
|
||||
return DEV_PAYLOAD_SECRET || env.PAYLOAD_SECRET;
|
||||
}
|
||||
38
app/lib/analytics.ts
Normal file
38
app/lib/analytics.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { CLIENT_ORIGIN } from '~/lib/constants';
|
||||
import { request as doRequest } from '~/lib/fetch';
|
||||
|
||||
export interface Identity {
|
||||
userId?: string | null;
|
||||
guestId?: string | null;
|
||||
segmentWriteKey?: string | null;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
const MESSAGE_PREFIX = 'Bolt';
|
||||
|
||||
export enum AnalyticsTrackEvent {
|
||||
MessageSent = `${MESSAGE_PREFIX} Message Sent`,
|
||||
MessageComplete = `${MESSAGE_PREFIX} Message Complete`,
|
||||
ChatCreated = `${MESSAGE_PREFIX} Chat Created`,
|
||||
}
|
||||
|
||||
export async function identifyUser(access: string): Promise<Identity | undefined> {
|
||||
const response = await doRequest(`${CLIENT_ORIGIN}/api/identify`, {
|
||||
method: 'GET',
|
||||
headers: { authorization: `Bearer ${access}` },
|
||||
});
|
||||
|
||||
const body = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// convert numerical identity values to strings
|
||||
const stringified = Object.entries(body).map(([key, value]) => [
|
||||
key,
|
||||
typeof value === 'number' ? value.toString() : value,
|
||||
]);
|
||||
|
||||
return Object.fromEntries(stringified) as Identity;
|
||||
}
|
||||
4
app/lib/auth.ts
Normal file
4
app/lib/auth.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export function forgetAuth() {
|
||||
// FIXME: use dedicated method
|
||||
localStorage.removeItem('__wc_api_tokens__');
|
||||
}
|
||||
2
app/lib/constants.ts
Normal file
2
app/lib/constants.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export const CLIENT_ID = 'bolt';
|
||||
export const CLIENT_ORIGIN = import.meta.env.VITE_CLIENT_ORIGIN ?? 'https://stackblitz.com';
|
||||
58
app/lib/crypto.ts
Normal file
58
app/lib/crypto.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
const IV_LENGTH = 16;
|
||||
|
||||
export async function encrypt(key: string, data: string) {
|
||||
const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
|
||||
const cryptoKey = await getKey(key);
|
||||
|
||||
const ciphertext = await crypto.subtle.encrypt(
|
||||
{
|
||||
name: 'AES-CBC',
|
||||
iv,
|
||||
},
|
||||
cryptoKey,
|
||||
encoder.encode(data),
|
||||
);
|
||||
|
||||
const bundle = new Uint8Array(IV_LENGTH + ciphertext.byteLength);
|
||||
|
||||
bundle.set(new Uint8Array(ciphertext));
|
||||
bundle.set(iv, ciphertext.byteLength);
|
||||
|
||||
return decodeBase64(bundle);
|
||||
}
|
||||
|
||||
export async function decrypt(key: string, payload: string) {
|
||||
const bundle = encodeBase64(payload);
|
||||
|
||||
const iv = new Uint8Array(bundle.buffer, bundle.byteLength - IV_LENGTH);
|
||||
const ciphertext = new Uint8Array(bundle.buffer, 0, bundle.byteLength - IV_LENGTH);
|
||||
|
||||
const cryptoKey = await getKey(key);
|
||||
|
||||
const plaintext = await crypto.subtle.decrypt(
|
||||
{
|
||||
name: 'AES-CBC',
|
||||
iv,
|
||||
},
|
||||
cryptoKey,
|
||||
ciphertext,
|
||||
);
|
||||
|
||||
return decoder.decode(plaintext);
|
||||
}
|
||||
|
||||
async function getKey(key: string) {
|
||||
return await crypto.subtle.importKey('raw', encodeBase64(key), { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
|
||||
}
|
||||
|
||||
function decodeBase64(encoded: Uint8Array) {
|
||||
const byteChars = Array.from(encoded, (byte) => String.fromCodePoint(byte));
|
||||
|
||||
return btoa(byteChars.join(''));
|
||||
}
|
||||
|
||||
function encodeBase64(data: string) {
|
||||
return Uint8Array.from(atob(data), (ch) => ch.codePointAt(0)!);
|
||||
}
|
||||
14
app/lib/fetch.ts
Normal file
14
app/lib/fetch.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
type CommonRequest = Omit<RequestInit, 'body'> & { body?: URLSearchParams };
|
||||
|
||||
export async function request(url: string, init?: CommonRequest) {
|
||||
if (import.meta.env.DEV) {
|
||||
const nodeFetch = await import('node-fetch');
|
||||
const https = await import('node:https');
|
||||
|
||||
const agent = url.startsWith('https') ? new https.Agent({ rejectUnauthorized: false }) : undefined;
|
||||
|
||||
return nodeFetch.default(url, { ...init, agent });
|
||||
}
|
||||
|
||||
return fetch(url, init);
|
||||
}
|
||||
4
app/lib/hooks/index.ts
Normal file
4
app/lib/hooks/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export * from './useMessageParser';
|
||||
export * from './usePromptEnhancer';
|
||||
export * from './useShortcuts';
|
||||
export * from './useSnapScroll';
|
||||
66
app/lib/hooks/useMessageParser.ts
Normal file
66
app/lib/hooks/useMessageParser.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import type { Message } from 'ai';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { StreamingMessageParser } from '~/lib/runtime/message-parser';
|
||||
import { workbenchStore } from '~/lib/stores/workbench';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
|
||||
const logger = createScopedLogger('useMessageParser');
|
||||
|
||||
const messageParser = new StreamingMessageParser({
|
||||
callbacks: {
|
||||
onArtifactOpen: (data) => {
|
||||
logger.trace('onArtifactOpen', data);
|
||||
|
||||
workbenchStore.showWorkbench.set(true);
|
||||
workbenchStore.addArtifact(data);
|
||||
},
|
||||
onArtifactClose: (data) => {
|
||||
logger.trace('onArtifactClose');
|
||||
|
||||
workbenchStore.updateArtifact(data, { closed: true });
|
||||
},
|
||||
onActionOpen: (data) => {
|
||||
logger.trace('onActionOpen', data.action);
|
||||
|
||||
// we only add shell actions when when the close tag got parsed because only then we have the content
|
||||
if (data.action.type !== 'shell') {
|
||||
workbenchStore.addAction(data);
|
||||
}
|
||||
},
|
||||
onActionClose: (data) => {
|
||||
logger.trace('onActionClose', data.action);
|
||||
|
||||
if (data.action.type === 'shell') {
|
||||
workbenchStore.addAction(data);
|
||||
}
|
||||
|
||||
workbenchStore.runAction(data);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export function useMessageParser() {
|
||||
const [parsedMessages, setParsedMessages] = useState<{ [key: number]: string }>({});
|
||||
|
||||
const parseMessages = useCallback((messages: Message[], isLoading: boolean) => {
|
||||
let reset = false;
|
||||
|
||||
if (import.meta.env.DEV && !isLoading) {
|
||||
reset = true;
|
||||
messageParser.reset();
|
||||
}
|
||||
|
||||
for (const [index, message] of messages.entries()) {
|
||||
if (message.role === 'assistant') {
|
||||
const newParsedContent = messageParser.parse(message.id, message.content);
|
||||
|
||||
setParsedMessages((prevParsed) => ({
|
||||
...prevParsed,
|
||||
[index]: !reset ? (prevParsed[index] || '') + newParsedContent : newParsedContent,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
return { parsedMessages, parseMessages };
|
||||
}
|
||||
71
app/lib/hooks/usePromptEnhancer.ts
Normal file
71
app/lib/hooks/usePromptEnhancer.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { useState } from 'react';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
|
||||
const logger = createScopedLogger('usePromptEnhancement');
|
||||
|
||||
export function usePromptEnhancer() {
|
||||
const [enhancingPrompt, setEnhancingPrompt] = useState(false);
|
||||
const [promptEnhanced, setPromptEnhanced] = useState(false);
|
||||
|
||||
const resetEnhancer = () => {
|
||||
setEnhancingPrompt(false);
|
||||
setPromptEnhanced(false);
|
||||
};
|
||||
|
||||
const enhancePrompt = async (input: string, setInput: (value: string) => void) => {
|
||||
setEnhancingPrompt(true);
|
||||
setPromptEnhanced(false);
|
||||
|
||||
const response = await fetch('/api/enhancer', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
message: input,
|
||||
}),
|
||||
});
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
|
||||
const originalInput = input;
|
||||
|
||||
if (reader) {
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
let _input = '';
|
||||
let _error;
|
||||
|
||||
try {
|
||||
setInput('');
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
_input += decoder.decode(value);
|
||||
|
||||
logger.trace('Set input', _input);
|
||||
|
||||
setInput(_input);
|
||||
}
|
||||
} catch (error) {
|
||||
_error = error;
|
||||
setInput(originalInput);
|
||||
} finally {
|
||||
if (_error) {
|
||||
logger.error(_error);
|
||||
}
|
||||
|
||||
setEnhancingPrompt(false);
|
||||
setPromptEnhanced(true);
|
||||
|
||||
setTimeout(() => {
|
||||
setInput(_input);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer };
|
||||
}
|
||||
59
app/lib/hooks/useShortcuts.ts
Normal file
59
app/lib/hooks/useShortcuts.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { useEffect } from 'react';
|
||||
import { shortcutsStore, type Shortcuts } from '~/lib/stores/settings';
|
||||
|
||||
class ShortcutEventEmitter {
|
||||
#emitter = new EventTarget();
|
||||
|
||||
dispatch(type: keyof Shortcuts) {
|
||||
this.#emitter.dispatchEvent(new Event(type));
|
||||
}
|
||||
|
||||
on(type: keyof Shortcuts, cb: VoidFunction) {
|
||||
this.#emitter.addEventListener(type, cb);
|
||||
|
||||
return () => {
|
||||
this.#emitter.removeEventListener(type, cb);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const shortcutEventEmitter = new ShortcutEventEmitter();
|
||||
|
||||
export function useShortcuts(): void {
|
||||
const shortcuts = useStore(shortcutsStore);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent): void => {
|
||||
const { key, ctrlKey, shiftKey, altKey, metaKey } = event;
|
||||
|
||||
for (const name in shortcuts) {
|
||||
const shortcut = shortcuts[name as keyof Shortcuts];
|
||||
|
||||
if (
|
||||
shortcut.key.toLowerCase() === key.toLowerCase() &&
|
||||
(shortcut.ctrlOrMetaKey
|
||||
? ctrlKey || metaKey
|
||||
: (shortcut.ctrlKey === undefined || shortcut.ctrlKey === ctrlKey) &&
|
||||
(shortcut.metaKey === undefined || shortcut.metaKey === metaKey)) &&
|
||||
(shortcut.shiftKey === undefined || shortcut.shiftKey === shiftKey) &&
|
||||
(shortcut.altKey === undefined || shortcut.altKey === altKey)
|
||||
) {
|
||||
shortcutEventEmitter.dispatch(name as keyof Shortcuts);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
shortcut.action();
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [shortcuts]);
|
||||
}
|
||||
52
app/lib/hooks/useSnapScroll.ts
Normal file
52
app/lib/hooks/useSnapScroll.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useRef, useCallback } from 'react';
|
||||
|
||||
export function useSnapScroll() {
|
||||
const autoScrollRef = useRef(true);
|
||||
const scrollNodeRef = useRef<HTMLDivElement>();
|
||||
const onScrollRef = useRef<() => void>();
|
||||
const observerRef = useRef<ResizeObserver>();
|
||||
|
||||
const messageRef = useCallback((node: HTMLDivElement | null) => {
|
||||
if (node) {
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (autoScrollRef.current && scrollNodeRef.current) {
|
||||
const { scrollHeight, clientHeight } = scrollNodeRef.current;
|
||||
const scrollTarget = scrollHeight - clientHeight;
|
||||
|
||||
scrollNodeRef.current.scrollTo({
|
||||
top: scrollTarget,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
observer.observe(node);
|
||||
} else {
|
||||
observerRef.current?.disconnect();
|
||||
observerRef.current = undefined;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const scrollRef = useCallback((node: HTMLDivElement | null) => {
|
||||
if (node) {
|
||||
onScrollRef.current = () => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = node;
|
||||
const scrollTarget = scrollHeight - clientHeight;
|
||||
|
||||
autoScrollRef.current = Math.abs(scrollTop - scrollTarget) <= 10;
|
||||
};
|
||||
|
||||
node.addEventListener('scroll', onScrollRef.current);
|
||||
|
||||
scrollNodeRef.current = node;
|
||||
} else {
|
||||
if (onScrollRef.current) {
|
||||
scrollNodeRef.current?.removeEventListener('scroll', onScrollRef.current);
|
||||
}
|
||||
|
||||
scrollNodeRef.current = undefined;
|
||||
onScrollRef.current = undefined;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return [messageRef, scrollRef];
|
||||
}
|
||||
6
app/lib/persistence/ChatDescription.client.tsx
Normal file
6
app/lib/persistence/ChatDescription.client.tsx
Normal file
@@ -0,0 +1,6 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { description } from './useChatHistory';
|
||||
|
||||
export function ChatDescription() {
|
||||
return useStore(description);
|
||||
}
|
||||
160
app/lib/persistence/db.ts
Normal file
160
app/lib/persistence/db.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import type { Message } from 'ai';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
import type { ChatHistoryItem } from './useChatHistory';
|
||||
|
||||
const logger = createScopedLogger('ChatHistory');
|
||||
|
||||
// this is used at the top level and never rejects
|
||||
export async function openDatabase(): Promise<IDBDatabase | undefined> {
|
||||
return new Promise((resolve) => {
|
||||
const request = indexedDB.open('boltHistory', 1);
|
||||
|
||||
request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
|
||||
if (!db.objectStoreNames.contains('chats')) {
|
||||
const store = db.createObjectStore('chats', { keyPath: 'id' });
|
||||
store.createIndex('id', 'id', { unique: true });
|
||||
store.createIndex('urlId', 'urlId', { unique: true });
|
||||
}
|
||||
};
|
||||
|
||||
request.onsuccess = (event: Event) => {
|
||||
resolve((event.target as IDBOpenDBRequest).result);
|
||||
};
|
||||
|
||||
request.onerror = (event: Event) => {
|
||||
resolve(undefined);
|
||||
logger.error((event.target as IDBOpenDBRequest).error);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAll(db: IDBDatabase): Promise<ChatHistoryItem[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('chats', 'readonly');
|
||||
const store = transaction.objectStore('chats');
|
||||
const request = store.getAll();
|
||||
|
||||
request.onsuccess = () => resolve(request.result as ChatHistoryItem[]);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function setMessages(
|
||||
db: IDBDatabase,
|
||||
id: string,
|
||||
messages: Message[],
|
||||
urlId?: string,
|
||||
description?: string,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('chats', 'readwrite');
|
||||
const store = transaction.objectStore('chats');
|
||||
|
||||
const request = store.put({
|
||||
id,
|
||||
messages,
|
||||
urlId,
|
||||
description,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
|
||||
request.onsuccess = () => resolve();
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMessages(db: IDBDatabase, id: string): Promise<ChatHistoryItem> {
|
||||
return (await getMessagesById(db, id)) || (await getMessagesByUrlId(db, id));
|
||||
}
|
||||
|
||||
export async function getMessagesByUrlId(db: IDBDatabase, id: string): Promise<ChatHistoryItem> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('chats', 'readonly');
|
||||
const store = transaction.objectStore('chats');
|
||||
const index = store.index('urlId');
|
||||
const request = index.get(id);
|
||||
|
||||
request.onsuccess = () => resolve(request.result as ChatHistoryItem);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMessagesById(db: IDBDatabase, id: string): Promise<ChatHistoryItem> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('chats', 'readonly');
|
||||
const store = transaction.objectStore('chats');
|
||||
const request = store.get(id);
|
||||
|
||||
request.onsuccess = () => resolve(request.result as ChatHistoryItem);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteById(db: IDBDatabase, id: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('chats', 'readwrite');
|
||||
const store = transaction.objectStore('chats');
|
||||
const request = store.delete(id);
|
||||
|
||||
request.onsuccess = () => resolve(undefined);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function getNextId(db: IDBDatabase): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('chats', 'readonly');
|
||||
const store = transaction.objectStore('chats');
|
||||
const request = store.getAllKeys();
|
||||
|
||||
request.onsuccess = () => {
|
||||
const highestId = request.result.reduce((cur, acc) => Math.max(+cur, +acc), 0);
|
||||
resolve(String(+highestId + 1));
|
||||
};
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUrlId(db: IDBDatabase, id: string): Promise<string> {
|
||||
const idList = await getUrlIds(db);
|
||||
|
||||
if (!idList.includes(id)) {
|
||||
return id;
|
||||
} else {
|
||||
let i = 2;
|
||||
|
||||
while (idList.includes(`${id}-${i}`)) {
|
||||
i++;
|
||||
}
|
||||
|
||||
return `${id}-${i}`;
|
||||
}
|
||||
}
|
||||
|
||||
async function getUrlIds(db: IDBDatabase): Promise<string[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('chats', 'readonly');
|
||||
const store = transaction.objectStore('chats');
|
||||
const idList: string[] = [];
|
||||
|
||||
const request = store.openCursor();
|
||||
|
||||
request.onsuccess = (event: Event) => {
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue>).result;
|
||||
|
||||
if (cursor) {
|
||||
idList.push(cursor.value.urlId);
|
||||
cursor.continue();
|
||||
} else {
|
||||
resolve(idList);
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
}
|
||||
2
app/lib/persistence/index.ts
Normal file
2
app/lib/persistence/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './db';
|
||||
export * from './useChatHistory';
|
||||
109
app/lib/persistence/useChatHistory.ts
Normal file
109
app/lib/persistence/useChatHistory.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import { useLoaderData, useNavigate } from '@remix-run/react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { atom } from 'nanostores';
|
||||
import type { Message } from 'ai';
|
||||
import { toast } from 'react-toastify';
|
||||
import { workbenchStore } from '~/lib/stores/workbench';
|
||||
import { getMessages, getNextId, getUrlId, openDatabase, setMessages } from './db';
|
||||
|
||||
export interface ChatHistoryItem {
|
||||
id: string;
|
||||
urlId?: string;
|
||||
description?: string;
|
||||
messages: Message[];
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
const persistenceEnabled = !import.meta.env.VITE_DISABLE_PERSISTENCE;
|
||||
|
||||
export const db = persistenceEnabled ? await openDatabase() : undefined;
|
||||
|
||||
export const chatId = atom<string | undefined>(undefined);
|
||||
export const description = atom<string | undefined>(undefined);
|
||||
|
||||
export function useChatHistory() {
|
||||
const navigate = useNavigate();
|
||||
const { id: mixedId } = useLoaderData<{ id?: string }>();
|
||||
|
||||
const [initialMessages, setInitialMessages] = useState<Message[]>([]);
|
||||
const [ready, setReady] = useState<boolean>(false);
|
||||
const [urlId, setUrlId] = useState<string | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!db) {
|
||||
setReady(true);
|
||||
|
||||
if (persistenceEnabled) {
|
||||
toast.error(`Chat persistence is unavailable`);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (mixedId) {
|
||||
getMessages(db, mixedId)
|
||||
.then((storedMessages) => {
|
||||
if (storedMessages && storedMessages.messages.length > 0) {
|
||||
setInitialMessages(storedMessages.messages);
|
||||
setUrlId(storedMessages.urlId);
|
||||
description.set(storedMessages.description);
|
||||
chatId.set(storedMessages.id);
|
||||
} else {
|
||||
navigate(`/`, { replace: true });
|
||||
}
|
||||
|
||||
setReady(true);
|
||||
})
|
||||
.catch((error) => {
|
||||
toast.error(error.message);
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
ready: !mixedId || ready,
|
||||
initialMessages,
|
||||
storeMessageHistory: async (messages: Message[]) => {
|
||||
if (!db || messages.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { firstArtifact } = workbenchStore;
|
||||
|
||||
if (!urlId && firstArtifact?.id) {
|
||||
const urlId = await getUrlId(db, firstArtifact.id);
|
||||
|
||||
navigateChat(urlId);
|
||||
setUrlId(urlId);
|
||||
}
|
||||
|
||||
if (!description.get() && firstArtifact?.title) {
|
||||
description.set(firstArtifact?.title);
|
||||
}
|
||||
|
||||
if (initialMessages.length === 0 && !chatId.get()) {
|
||||
const nextId = await getNextId(db);
|
||||
|
||||
chatId.set(nextId);
|
||||
|
||||
if (!urlId) {
|
||||
navigateChat(nextId);
|
||||
}
|
||||
}
|
||||
|
||||
await setMessages(db, chatId.get() as string, messages, urlId, description.get());
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function navigateChat(nextId: string) {
|
||||
/**
|
||||
* FIXME: Using the intended navigate function causes a rerender for <Chat /> that breaks the app.
|
||||
*
|
||||
* `navigate(`/chat/${nextId}`, { replace: true });`
|
||||
*/
|
||||
const url = new URL(window.location.href);
|
||||
url.pathname = `/chat/${nextId}`;
|
||||
|
||||
window.history.replaceState({}, '', url);
|
||||
}
|
||||
220
app/lib/runtime/__snapshots__/message-parser.spec.ts.snap
Normal file
220
app/lib/runtime/__snapshots__/message-parser.spec.ts.snap
Normal file
@@ -0,0 +1,220 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (0) > onActionClose 1`] = `
|
||||
{
|
||||
"action": {
|
||||
"content": "npm install",
|
||||
"type": "shell",
|
||||
},
|
||||
"actionId": "0",
|
||||
"artifactId": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (0) > onActionOpen 1`] = `
|
||||
{
|
||||
"action": {
|
||||
"content": "",
|
||||
"type": "shell",
|
||||
},
|
||||
"actionId": "0",
|
||||
"artifactId": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (0) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (0) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (1) > onActionClose 1`] = `
|
||||
{
|
||||
"action": {
|
||||
"content": "npm install",
|
||||
"type": "shell",
|
||||
},
|
||||
"actionId": "0",
|
||||
"artifactId": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (1) > onActionClose 2`] = `
|
||||
{
|
||||
"action": {
|
||||
"content": "some content
|
||||
",
|
||||
"filePath": "index.js",
|
||||
"type": "file",
|
||||
},
|
||||
"actionId": "1",
|
||||
"artifactId": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (1) > onActionOpen 1`] = `
|
||||
{
|
||||
"action": {
|
||||
"content": "",
|
||||
"type": "shell",
|
||||
},
|
||||
"actionId": "0",
|
||||
"artifactId": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (1) > onActionOpen 2`] = `
|
||||
{
|
||||
"action": {
|
||||
"content": "",
|
||||
"filePath": "index.js",
|
||||
"type": "file",
|
||||
},
|
||||
"actionId": "1",
|
||||
"artifactId": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (1) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts with actions > should correctly parse chunks and strip out bolt artifacts (1) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (0) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (0) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (1) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (1) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (2) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (2) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (3) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (3) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (4) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (4) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (5) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (5) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (6) > onArtifactClose 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`StreamingMessageParser > valid artifacts without actions > should correctly parse chunks and strip out bolt artifacts (6) > onArtifactOpen 1`] = `
|
||||
{
|
||||
"id": "artifact_1",
|
||||
"messageId": "message_1",
|
||||
"title": "Some title",
|
||||
}
|
||||
`;
|
||||
184
app/lib/runtime/action-runner.ts
Normal file
184
app/lib/runtime/action-runner.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import { WebContainer } from '@webcontainer/api';
|
||||
import { map, type MapStore } from 'nanostores';
|
||||
import * as nodePath from 'node:path';
|
||||
import type { BoltAction } from '~/types/actions';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
import { unreachable } from '~/utils/unreachable';
|
||||
import type { ActionCallbackData } from './message-parser';
|
||||
|
||||
const logger = createScopedLogger('ActionRunner');
|
||||
|
||||
export type ActionStatus = 'pending' | 'running' | 'complete' | 'aborted' | 'failed';
|
||||
|
||||
export type BaseActionState = BoltAction & {
|
||||
status: Exclude<ActionStatus, 'failed'>;
|
||||
abort: () => void;
|
||||
executed: boolean;
|
||||
abortSignal: AbortSignal;
|
||||
};
|
||||
|
||||
export type FailedActionState = BoltAction &
|
||||
Omit<BaseActionState, 'status'> & {
|
||||
status: Extract<ActionStatus, 'failed'>;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type ActionState = BaseActionState | FailedActionState;
|
||||
|
||||
type BaseActionUpdate = Partial<Pick<BaseActionState, 'status' | 'abort' | 'executed'>>;
|
||||
|
||||
export type ActionStateUpdate =
|
||||
| BaseActionUpdate
|
||||
| (Omit<BaseActionUpdate, 'status'> & { status: 'failed'; error: string });
|
||||
|
||||
type ActionsMap = MapStore<Record<string, ActionState>>;
|
||||
|
||||
export class ActionRunner {
|
||||
#webcontainer: Promise<WebContainer>;
|
||||
#currentExecutionPromise: Promise<void> = Promise.resolve();
|
||||
|
||||
actions: ActionsMap = map({});
|
||||
|
||||
constructor(webcontainerPromise: Promise<WebContainer>) {
|
||||
this.#webcontainer = webcontainerPromise;
|
||||
}
|
||||
|
||||
addAction(data: ActionCallbackData) {
|
||||
const { actionId } = data;
|
||||
|
||||
const actions = this.actions.get();
|
||||
const action = actions[actionId];
|
||||
|
||||
if (action) {
|
||||
// action already added
|
||||
return;
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
|
||||
this.actions.setKey(actionId, {
|
||||
...data.action,
|
||||
status: 'pending',
|
||||
executed: false,
|
||||
abort: () => {
|
||||
abortController.abort();
|
||||
this.#updateAction(actionId, { status: 'aborted' });
|
||||
},
|
||||
abortSignal: abortController.signal,
|
||||
});
|
||||
|
||||
this.#currentExecutionPromise.then(() => {
|
||||
this.#updateAction(actionId, { status: 'running' });
|
||||
});
|
||||
}
|
||||
|
||||
async runAction(data: ActionCallbackData) {
|
||||
const { actionId } = data;
|
||||
const action = this.actions.get()[actionId];
|
||||
|
||||
if (!action) {
|
||||
unreachable(`Action ${actionId} not found`);
|
||||
}
|
||||
|
||||
if (action.executed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.#updateAction(actionId, { ...action, ...data.action, executed: true });
|
||||
|
||||
this.#currentExecutionPromise = this.#currentExecutionPromise
|
||||
.then(() => {
|
||||
return this.#executeAction(actionId);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Action failed:', error);
|
||||
});
|
||||
}
|
||||
|
||||
async #executeAction(actionId: string) {
|
||||
const action = this.actions.get()[actionId];
|
||||
|
||||
this.#updateAction(actionId, { status: 'running' });
|
||||
|
||||
try {
|
||||
switch (action.type) {
|
||||
case 'shell': {
|
||||
await this.#runShellAction(action);
|
||||
break;
|
||||
}
|
||||
case 'file': {
|
||||
await this.#runFileAction(action);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.#updateAction(actionId, { status: action.abortSignal.aborted ? 'aborted' : 'complete' });
|
||||
} catch (error) {
|
||||
this.#updateAction(actionId, { status: 'failed', error: 'Action failed' });
|
||||
|
||||
// re-throw the error to be caught in the promise chain
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async #runShellAction(action: ActionState) {
|
||||
if (action.type !== 'shell') {
|
||||
unreachable('Expected shell action');
|
||||
}
|
||||
|
||||
const webcontainer = await this.#webcontainer;
|
||||
|
||||
const process = await webcontainer.spawn('jsh', ['-c', action.content]);
|
||||
|
||||
action.abortSignal.addEventListener('abort', () => {
|
||||
process.kill();
|
||||
});
|
||||
|
||||
process.output.pipeTo(
|
||||
new WritableStream({
|
||||
write(data) {
|
||||
console.log(data);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const exitCode = await process.exit;
|
||||
|
||||
logger.debug(`Process terminated with code ${exitCode}`);
|
||||
}
|
||||
|
||||
async #runFileAction(action: ActionState) {
|
||||
if (action.type !== 'file') {
|
||||
unreachable('Expected file action');
|
||||
}
|
||||
|
||||
const webcontainer = await this.#webcontainer;
|
||||
|
||||
let folder = nodePath.dirname(action.filePath);
|
||||
|
||||
// remove trailing slashes
|
||||
folder = folder.replace(/\/+$/g, '');
|
||||
|
||||
if (folder !== '.') {
|
||||
try {
|
||||
await webcontainer.fs.mkdir(folder, { recursive: true });
|
||||
logger.debug('Created folder', folder);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create folder\n\n', error);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await webcontainer.fs.writeFile(action.filePath, action.content);
|
||||
logger.debug(`File written ${action.filePath}`);
|
||||
} catch (error) {
|
||||
logger.error('Failed to write file\n\n', error);
|
||||
}
|
||||
}
|
||||
|
||||
#updateAction(id: string, newState: ActionStateUpdate) {
|
||||
const actions = this.actions.get();
|
||||
|
||||
this.actions.setKey(id, { ...actions[id], ...newState });
|
||||
}
|
||||
}
|
||||
207
app/lib/runtime/message-parser.spec.ts
Normal file
207
app/lib/runtime/message-parser.spec.ts
Normal file
@@ -0,0 +1,207 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { StreamingMessageParser, type ActionCallback, type ArtifactCallback } from './message-parser';
|
||||
|
||||
interface ExpectedResult {
|
||||
output: string;
|
||||
callbacks?: {
|
||||
onArtifactOpen?: number;
|
||||
onArtifactClose?: number;
|
||||
onActionOpen?: number;
|
||||
onActionClose?: number;
|
||||
};
|
||||
}
|
||||
|
||||
describe('StreamingMessageParser', () => {
|
||||
it('should pass through normal text', () => {
|
||||
const parser = new StreamingMessageParser();
|
||||
expect(parser.parse('test_id', 'Hello, world!')).toBe('Hello, world!');
|
||||
});
|
||||
|
||||
it('should allow normal HTML tags', () => {
|
||||
const parser = new StreamingMessageParser();
|
||||
expect(parser.parse('test_id', 'Hello <strong>world</strong>!')).toBe('Hello <strong>world</strong>!');
|
||||
});
|
||||
|
||||
describe('no artifacts', () => {
|
||||
it.each<[string | string[], ExpectedResult | string]>([
|
||||
['Foo bar', 'Foo bar'],
|
||||
['Foo bar <', 'Foo bar '],
|
||||
['Foo bar <p', 'Foo bar <p'],
|
||||
[['Foo bar <', 's', 'p', 'an>some text</span>'], 'Foo bar <span>some text</span>'],
|
||||
])('should correctly parse chunks and strip out bolt artifacts (%#)', (input, expected) => {
|
||||
runTest(input, expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('invalid or incomplete artifacts', () => {
|
||||
it.each<[string | string[], ExpectedResult | string]>([
|
||||
['Foo bar <b', 'Foo bar '],
|
||||
['Foo bar <ba', 'Foo bar <ba'],
|
||||
['Foo bar <bol', 'Foo bar '],
|
||||
['Foo bar <bolt', 'Foo bar '],
|
||||
['Foo bar <bolta', 'Foo bar <bolta'],
|
||||
['Foo bar <boltA', 'Foo bar '],
|
||||
['Foo bar <boltArtifacs></boltArtifact>', 'Foo bar <boltArtifacs></boltArtifact>'],
|
||||
['Before <oltArtfiact>foo</boltArtifact> After', 'Before <oltArtfiact>foo</boltArtifact> After'],
|
||||
['Before <boltArtifactt>foo</boltArtifact> After', 'Before <boltArtifactt>foo</boltArtifact> After'],
|
||||
])('should correctly parse chunks and strip out bolt artifacts (%#)', (input, expected) => {
|
||||
runTest(input, expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('valid artifacts without actions', () => {
|
||||
it.each<[string | string[], ExpectedResult | string]>([
|
||||
[
|
||||
'Some text before <boltArtifact title="Some title" id="artifact_1">foo bar</boltArtifact> Some more text',
|
||||
{
|
||||
output: 'Some text before Some more text',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 0, onActionClose: 0 },
|
||||
},
|
||||
],
|
||||
[
|
||||
['Some text before <boltArti', 'fact', ' title="Some title" id="artifact_1">foo</boltArtifact> Some more text'],
|
||||
{
|
||||
output: 'Some text before Some more text',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 0, onActionClose: 0 },
|
||||
},
|
||||
],
|
||||
[
|
||||
[
|
||||
'Some text before <boltArti',
|
||||
'fac',
|
||||
't title="Some title" id="artifact_1"',
|
||||
' ',
|
||||
'>',
|
||||
'foo</boltArtifact> Some more text',
|
||||
],
|
||||
{
|
||||
output: 'Some text before Some more text',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 0, onActionClose: 0 },
|
||||
},
|
||||
],
|
||||
[
|
||||
[
|
||||
'Some text before <boltArti',
|
||||
'fact',
|
||||
' title="Some title" id="artifact_1"',
|
||||
' >fo',
|
||||
'o</boltArtifact> Some more text',
|
||||
],
|
||||
{
|
||||
output: 'Some text before Some more text',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 0, onActionClose: 0 },
|
||||
},
|
||||
],
|
||||
[
|
||||
[
|
||||
'Some text before <boltArti',
|
||||
'fact tit',
|
||||
'le="Some ',
|
||||
'title" id="artifact_1">fo',
|
||||
'o',
|
||||
'<',
|
||||
'/boltArtifact> Some more text',
|
||||
],
|
||||
{
|
||||
output: 'Some text before Some more text',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 0, onActionClose: 0 },
|
||||
},
|
||||
],
|
||||
[
|
||||
[
|
||||
'Some text before <boltArti',
|
||||
'fact title="Some title" id="artif',
|
||||
'act_1">fo',
|
||||
'o<',
|
||||
'/boltArtifact> Some more text',
|
||||
],
|
||||
{
|
||||
output: 'Some text before Some more text',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 0, onActionClose: 0 },
|
||||
},
|
||||
],
|
||||
[
|
||||
'Before <boltArtifact title="Some title" id="artifact_1">foo</boltArtifact> After',
|
||||
{
|
||||
output: 'Before After',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 0, onActionClose: 0 },
|
||||
},
|
||||
],
|
||||
])('should correctly parse chunks and strip out bolt artifacts (%#)', (input, expected) => {
|
||||
runTest(input, expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('valid artifacts with actions', () => {
|
||||
it.each<[string | string[], ExpectedResult | string]>([
|
||||
[
|
||||
'Before <boltArtifact title="Some title" id="artifact_1"><boltAction type="shell">npm install</boltAction></boltArtifact> After',
|
||||
{
|
||||
output: 'Before After',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 1, onActionClose: 1 },
|
||||
},
|
||||
],
|
||||
[
|
||||
'Before <boltArtifact title="Some title" id="artifact_1"><boltAction type="shell">npm install</boltAction><boltAction type="file" filePath="index.js">some content</boltAction></boltArtifact> After',
|
||||
{
|
||||
output: 'Before After',
|
||||
callbacks: { onArtifactOpen: 1, onArtifactClose: 1, onActionOpen: 2, onActionClose: 2 },
|
||||
},
|
||||
],
|
||||
])('should correctly parse chunks and strip out bolt artifacts (%#)', (input, expected) => {
|
||||
runTest(input, expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function runTest(input: string | string[], outputOrExpectedResult: string | ExpectedResult) {
|
||||
let expected: ExpectedResult;
|
||||
|
||||
if (typeof outputOrExpectedResult === 'string') {
|
||||
expected = { output: outputOrExpectedResult };
|
||||
} else {
|
||||
expected = outputOrExpectedResult;
|
||||
}
|
||||
|
||||
const callbacks = {
|
||||
onArtifactOpen: vi.fn<ArtifactCallback>((data) => {
|
||||
expect(data).toMatchSnapshot('onArtifactOpen');
|
||||
}),
|
||||
onArtifactClose: vi.fn<ArtifactCallback>((data) => {
|
||||
expect(data).toMatchSnapshot('onArtifactClose');
|
||||
}),
|
||||
onActionOpen: vi.fn<ActionCallback>((data) => {
|
||||
expect(data).toMatchSnapshot('onActionOpen');
|
||||
}),
|
||||
onActionClose: vi.fn<ActionCallback>((data) => {
|
||||
expect(data).toMatchSnapshot('onActionClose');
|
||||
}),
|
||||
};
|
||||
|
||||
const parser = new StreamingMessageParser({
|
||||
artifactElement: () => '',
|
||||
callbacks,
|
||||
});
|
||||
|
||||
let message = '';
|
||||
|
||||
let result = '';
|
||||
|
||||
const chunks = Array.isArray(input) ? input : input.split('');
|
||||
|
||||
for (const chunk of chunks) {
|
||||
message += chunk;
|
||||
|
||||
result += parser.parse('message_1', message);
|
||||
}
|
||||
|
||||
for (const name in expected.callbacks) {
|
||||
const callbackName = name;
|
||||
|
||||
expect(callbacks[callbackName as keyof typeof callbacks]).toHaveBeenCalledTimes(
|
||||
expected.callbacks[callbackName as keyof typeof expected.callbacks] ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
expect(result).toEqual(expected.output);
|
||||
}
|
||||
285
app/lib/runtime/message-parser.ts
Normal file
285
app/lib/runtime/message-parser.ts
Normal file
@@ -0,0 +1,285 @@
|
||||
import type { ActionType, BoltAction, BoltActionData, FileAction, ShellAction } from '~/types/actions';
|
||||
import type { BoltArtifactData } from '~/types/artifact';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
import { unreachable } from '~/utils/unreachable';
|
||||
|
||||
const ARTIFACT_TAG_OPEN = '<boltArtifact';
|
||||
const ARTIFACT_TAG_CLOSE = '</boltArtifact>';
|
||||
const ARTIFACT_ACTION_TAG_OPEN = '<boltAction';
|
||||
const ARTIFACT_ACTION_TAG_CLOSE = '</boltAction>';
|
||||
|
||||
const logger = createScopedLogger('MessageParser');
|
||||
|
||||
export interface ArtifactCallbackData extends BoltArtifactData {
|
||||
messageId: string;
|
||||
}
|
||||
|
||||
export interface ActionCallbackData {
|
||||
artifactId: string;
|
||||
messageId: string;
|
||||
actionId: string;
|
||||
action: BoltAction;
|
||||
}
|
||||
|
||||
export type ArtifactCallback = (data: ArtifactCallbackData) => void;
|
||||
export type ActionCallback = (data: ActionCallbackData) => void;
|
||||
|
||||
export interface ParserCallbacks {
|
||||
onArtifactOpen?: ArtifactCallback;
|
||||
onArtifactClose?: ArtifactCallback;
|
||||
onActionOpen?: ActionCallback;
|
||||
onActionClose?: ActionCallback;
|
||||
}
|
||||
|
||||
interface ElementFactoryProps {
|
||||
messageId: string;
|
||||
}
|
||||
|
||||
type ElementFactory = (props: ElementFactoryProps) => string;
|
||||
|
||||
export interface StreamingMessageParserOptions {
|
||||
callbacks?: ParserCallbacks;
|
||||
artifactElement?: ElementFactory;
|
||||
}
|
||||
|
||||
interface MessageState {
|
||||
position: number;
|
||||
insideArtifact: boolean;
|
||||
insideAction: boolean;
|
||||
currentArtifact?: BoltArtifactData;
|
||||
currentAction: BoltActionData;
|
||||
actionId: number;
|
||||
}
|
||||
|
||||
export class StreamingMessageParser {
|
||||
#messages = new Map<string, MessageState>();
|
||||
|
||||
constructor(private _options: StreamingMessageParserOptions = {}) {}
|
||||
|
||||
parse(messageId: string, input: string) {
|
||||
let state = this.#messages.get(messageId);
|
||||
|
||||
if (!state) {
|
||||
state = {
|
||||
position: 0,
|
||||
insideAction: false,
|
||||
insideArtifact: false,
|
||||
currentAction: { content: '' },
|
||||
actionId: 0,
|
||||
};
|
||||
|
||||
this.#messages.set(messageId, state);
|
||||
}
|
||||
|
||||
let output = '';
|
||||
let i = state.position;
|
||||
let earlyBreak = false;
|
||||
|
||||
while (i < input.length) {
|
||||
if (state.insideArtifact) {
|
||||
const currentArtifact = state.currentArtifact;
|
||||
|
||||
if (currentArtifact === undefined) {
|
||||
unreachable('Artifact not initialized');
|
||||
}
|
||||
|
||||
if (state.insideAction) {
|
||||
const closeIndex = input.indexOf(ARTIFACT_ACTION_TAG_CLOSE, i);
|
||||
|
||||
const currentAction = state.currentAction;
|
||||
|
||||
if (closeIndex !== -1) {
|
||||
currentAction.content += input.slice(i, closeIndex);
|
||||
|
||||
let content = currentAction.content.trim();
|
||||
|
||||
if ('type' in currentAction && currentAction.type === 'file') {
|
||||
content += '\n';
|
||||
}
|
||||
|
||||
currentAction.content = content;
|
||||
|
||||
this._options.callbacks?.onActionClose?.({
|
||||
artifactId: currentArtifact.id,
|
||||
messageId,
|
||||
|
||||
/**
|
||||
* We decrement the id because it's been incremented already
|
||||
* when `onActionOpen` was emitted to make sure the ids are
|
||||
* the same.
|
||||
*/
|
||||
actionId: String(state.actionId - 1),
|
||||
|
||||
action: currentAction as BoltAction,
|
||||
});
|
||||
|
||||
state.insideAction = false;
|
||||
state.currentAction = { content: '' };
|
||||
|
||||
i = closeIndex + ARTIFACT_ACTION_TAG_CLOSE.length;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
const actionOpenIndex = input.indexOf(ARTIFACT_ACTION_TAG_OPEN, i);
|
||||
const artifactCloseIndex = input.indexOf(ARTIFACT_TAG_CLOSE, i);
|
||||
|
||||
if (actionOpenIndex !== -1 && (artifactCloseIndex === -1 || actionOpenIndex < artifactCloseIndex)) {
|
||||
const actionEndIndex = input.indexOf('>', actionOpenIndex);
|
||||
|
||||
if (actionEndIndex !== -1) {
|
||||
state.insideAction = true;
|
||||
|
||||
state.currentAction = this.#parseActionTag(input, actionOpenIndex, actionEndIndex);
|
||||
|
||||
this._options.callbacks?.onActionOpen?.({
|
||||
artifactId: currentArtifact.id,
|
||||
messageId,
|
||||
actionId: String(state.actionId++),
|
||||
action: state.currentAction as BoltAction,
|
||||
});
|
||||
|
||||
i = actionEndIndex + 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else if (artifactCloseIndex !== -1) {
|
||||
this._options.callbacks?.onArtifactClose?.({ messageId, ...currentArtifact });
|
||||
|
||||
state.insideArtifact = false;
|
||||
state.currentArtifact = undefined;
|
||||
|
||||
i = artifactCloseIndex + ARTIFACT_TAG_CLOSE.length;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (input[i] === '<' && input[i + 1] !== '/') {
|
||||
let j = i;
|
||||
let potentialTag = '';
|
||||
|
||||
while (j < input.length && potentialTag.length < ARTIFACT_TAG_OPEN.length) {
|
||||
potentialTag += input[j];
|
||||
|
||||
if (potentialTag === ARTIFACT_TAG_OPEN) {
|
||||
const nextChar = input[j + 1];
|
||||
|
||||
if (nextChar && nextChar !== '>' && nextChar !== ' ') {
|
||||
output += input.slice(i, j + 1);
|
||||
i = j + 1;
|
||||
break;
|
||||
}
|
||||
|
||||
const openTagEnd = input.indexOf('>', j);
|
||||
|
||||
if (openTagEnd !== -1) {
|
||||
const artifactTag = input.slice(i, openTagEnd + 1);
|
||||
|
||||
const artifactTitle = this.#extractAttribute(artifactTag, 'title') as string;
|
||||
const artifactId = this.#extractAttribute(artifactTag, 'id') as string;
|
||||
|
||||
if (!artifactTitle) {
|
||||
logger.warn('Artifact title missing');
|
||||
}
|
||||
|
||||
if (!artifactId) {
|
||||
logger.warn('Artifact id missing');
|
||||
}
|
||||
|
||||
state.insideArtifact = true;
|
||||
|
||||
const currentArtifact = {
|
||||
id: artifactId,
|
||||
title: artifactTitle,
|
||||
} satisfies BoltArtifactData;
|
||||
|
||||
state.currentArtifact = currentArtifact;
|
||||
|
||||
this._options.callbacks?.onArtifactOpen?.({ messageId, ...currentArtifact });
|
||||
|
||||
const artifactFactory = this._options.artifactElement ?? createArtifactElement;
|
||||
|
||||
output += artifactFactory({ messageId });
|
||||
|
||||
i = openTagEnd + 1;
|
||||
} else {
|
||||
earlyBreak = true;
|
||||
}
|
||||
|
||||
break;
|
||||
} else if (!ARTIFACT_TAG_OPEN.startsWith(potentialTag)) {
|
||||
output += input.slice(i, j + 1);
|
||||
i = j + 1;
|
||||
break;
|
||||
}
|
||||
|
||||
j++;
|
||||
}
|
||||
|
||||
if (j === input.length && ARTIFACT_TAG_OPEN.startsWith(potentialTag)) {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
output += input[i];
|
||||
i++;
|
||||
}
|
||||
|
||||
if (earlyBreak) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
state.position = i;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.#messages.clear();
|
||||
}
|
||||
|
||||
#parseActionTag(input: string, actionOpenIndex: number, actionEndIndex: number) {
|
||||
const actionTag = input.slice(actionOpenIndex, actionEndIndex + 1);
|
||||
|
||||
const actionType = this.#extractAttribute(actionTag, 'type') as ActionType;
|
||||
|
||||
const actionAttributes = {
|
||||
type: actionType,
|
||||
content: '',
|
||||
};
|
||||
|
||||
if (actionType === 'file') {
|
||||
const filePath = this.#extractAttribute(actionTag, 'filePath') as string;
|
||||
|
||||
if (!filePath) {
|
||||
logger.debug('File path not specified');
|
||||
}
|
||||
|
||||
(actionAttributes as FileAction).filePath = filePath;
|
||||
} else if (actionType !== 'shell') {
|
||||
logger.warn(`Unknown action type '${actionType}'`);
|
||||
}
|
||||
|
||||
return actionAttributes as FileAction | ShellAction;
|
||||
}
|
||||
|
||||
#extractAttribute(tag: string, attributeName: string): string | undefined {
|
||||
const match = tag.match(new RegExp(`${attributeName}="([^"]*)"`, 'i'));
|
||||
return match ? match[1] : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const createArtifactElement: ElementFactory = (props) => {
|
||||
const elementProps = [
|
||||
'class="__boltArtifact__"',
|
||||
...Object.entries(props).map(([key, value]) => {
|
||||
return `data-${camelToDashCase(key)}=${JSON.stringify(value)}`;
|
||||
}),
|
||||
];
|
||||
|
||||
return `<div ${elementProps.join(' ')}></div>`;
|
||||
};
|
||||
|
||||
function camelToDashCase(input: string) {
|
||||
return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
|
||||
}
|
||||
7
app/lib/stores/chat.ts
Normal file
7
app/lib/stores/chat.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { map } from 'nanostores';
|
||||
|
||||
export const chatStore = map({
|
||||
started: false,
|
||||
aborted: false,
|
||||
showChat: true,
|
||||
});
|
||||
95
app/lib/stores/editor.ts
Normal file
95
app/lib/stores/editor.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { atom, computed, map, type MapStore, type WritableAtom } from 'nanostores';
|
||||
import type { EditorDocument, ScrollPosition } from '~/components/editor/codemirror/CodeMirrorEditor';
|
||||
import type { FileMap, FilesStore } from './files';
|
||||
|
||||
export type EditorDocuments = Record<string, EditorDocument>;
|
||||
|
||||
type SelectedFile = WritableAtom<string | undefined>;
|
||||
|
||||
export class EditorStore {
|
||||
#filesStore: FilesStore;
|
||||
|
||||
selectedFile: SelectedFile = import.meta.hot?.data.selectedFile ?? atom<string | undefined>();
|
||||
documents: MapStore<EditorDocuments> = import.meta.hot?.data.documents ?? map({});
|
||||
|
||||
currentDocument = computed([this.documents, this.selectedFile], (documents, selectedFile) => {
|
||||
if (!selectedFile) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return documents[selectedFile];
|
||||
});
|
||||
|
||||
constructor(filesStore: FilesStore) {
|
||||
this.#filesStore = filesStore;
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.documents = this.documents;
|
||||
import.meta.hot.data.selectedFile = this.selectedFile;
|
||||
}
|
||||
}
|
||||
|
||||
setDocuments(files: FileMap) {
|
||||
const previousDocuments = this.documents.value;
|
||||
|
||||
this.documents.set(
|
||||
Object.fromEntries<EditorDocument>(
|
||||
Object.entries(files)
|
||||
.map(([filePath, dirent]) => {
|
||||
if (dirent === undefined || dirent.type === 'folder') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const previousDocument = previousDocuments?.[filePath];
|
||||
|
||||
return [
|
||||
filePath,
|
||||
{
|
||||
value: dirent.content,
|
||||
filePath,
|
||||
scroll: previousDocument?.scroll,
|
||||
},
|
||||
] as [string, EditorDocument];
|
||||
})
|
||||
.filter(Boolean) as Array<[string, EditorDocument]>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
setSelectedFile(filePath: string | undefined) {
|
||||
this.selectedFile.set(filePath);
|
||||
}
|
||||
|
||||
updateScrollPosition(filePath: string, position: ScrollPosition) {
|
||||
const documents = this.documents.get();
|
||||
const documentState = documents[filePath];
|
||||
|
||||
if (!documentState) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.documents.setKey(filePath, {
|
||||
...documentState,
|
||||
scroll: position,
|
||||
});
|
||||
}
|
||||
|
||||
updateFile(filePath: string, newContent: string) {
|
||||
const documents = this.documents.get();
|
||||
const documentState = documents[filePath];
|
||||
|
||||
if (!documentState) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentContent = documentState.value;
|
||||
const contentChanged = currentContent !== newContent;
|
||||
|
||||
if (contentChanged) {
|
||||
this.documents.setKey(filePath, {
|
||||
...documentState,
|
||||
value: newContent,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
220
app/lib/stores/files.ts
Normal file
220
app/lib/stores/files.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import type { PathWatcherEvent, WebContainer } from '@webcontainer/api';
|
||||
import { getEncoding } from 'istextorbinary';
|
||||
import { map, type MapStore } from 'nanostores';
|
||||
import { Buffer } from 'node:buffer';
|
||||
import * as nodePath from 'node:path';
|
||||
import { bufferWatchEvents } from '~/utils/buffer';
|
||||
import { WORK_DIR } from '~/utils/constants';
|
||||
import { computeFileModifications } from '~/utils/diff';
|
||||
import { createScopedLogger } from '~/utils/logger';
|
||||
import { unreachable } from '~/utils/unreachable';
|
||||
|
||||
const logger = createScopedLogger('FilesStore');
|
||||
|
||||
const utf8TextDecoder = new TextDecoder('utf8', { fatal: true });
|
||||
|
||||
export interface File {
|
||||
type: 'file';
|
||||
content: string;
|
||||
isBinary: boolean;
|
||||
}
|
||||
|
||||
export interface Folder {
|
||||
type: 'folder';
|
||||
}
|
||||
|
||||
type Dirent = File | Folder;
|
||||
|
||||
export type FileMap = Record<string, Dirent | undefined>;
|
||||
|
||||
export class FilesStore {
|
||||
#webcontainer: Promise<WebContainer>;
|
||||
|
||||
/**
|
||||
* Tracks the number of files without folders.
|
||||
*/
|
||||
#size = 0;
|
||||
|
||||
/**
|
||||
* @note Keeps track all modified files with their original content since the last user message.
|
||||
* Needs to be reset when the user sends another message and all changes have to be submitted
|
||||
* for the model to be aware of the changes.
|
||||
*/
|
||||
#modifiedFiles: Map<string, string> = import.meta.hot?.data.modifiedFiles ?? new Map();
|
||||
|
||||
/**
|
||||
* Map of files that matches the state of WebContainer.
|
||||
*/
|
||||
files: MapStore<FileMap> = import.meta.hot?.data.files ?? map({});
|
||||
|
||||
get filesCount() {
|
||||
return this.#size;
|
||||
}
|
||||
|
||||
constructor(webcontainerPromise: Promise<WebContainer>) {
|
||||
this.#webcontainer = webcontainerPromise;
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.files = this.files;
|
||||
import.meta.hot.data.modifiedFiles = this.#modifiedFiles;
|
||||
}
|
||||
|
||||
this.#init();
|
||||
}
|
||||
|
||||
getFile(filePath: string) {
|
||||
const dirent = this.files.get()[filePath];
|
||||
|
||||
if (dirent?.type !== 'file') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return dirent;
|
||||
}
|
||||
|
||||
getFileModifications() {
|
||||
return computeFileModifications(this.files.get(), this.#modifiedFiles);
|
||||
}
|
||||
|
||||
resetFileModifications() {
|
||||
this.#modifiedFiles.clear();
|
||||
}
|
||||
|
||||
async saveFile(filePath: string, content: string) {
|
||||
const webcontainer = await this.#webcontainer;
|
||||
|
||||
try {
|
||||
const relativePath = nodePath.relative(webcontainer.workdir, filePath);
|
||||
|
||||
if (!relativePath) {
|
||||
throw new Error(`EINVAL: invalid file path, write '${relativePath}'`);
|
||||
}
|
||||
|
||||
const oldContent = this.getFile(filePath)?.content;
|
||||
|
||||
if (!oldContent) {
|
||||
unreachable('Expected content to be defined');
|
||||
}
|
||||
|
||||
await webcontainer.fs.writeFile(relativePath, content);
|
||||
|
||||
if (!this.#modifiedFiles.has(filePath)) {
|
||||
this.#modifiedFiles.set(filePath, oldContent);
|
||||
}
|
||||
|
||||
// we immediately update the file and don't rely on the `change` event coming from the watcher
|
||||
this.files.setKey(filePath, { type: 'file', content, isBinary: false });
|
||||
|
||||
logger.info('File updated');
|
||||
} catch (error) {
|
||||
logger.error('Failed to update file content\n\n', error);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async #init() {
|
||||
const webcontainer = await this.#webcontainer;
|
||||
|
||||
webcontainer.watchPaths(
|
||||
{ include: [`${WORK_DIR}/**`], exclude: ['**/node_modules', '.git'], includeContent: true },
|
||||
bufferWatchEvents(100, this.#processEventBuffer.bind(this)),
|
||||
);
|
||||
}
|
||||
|
||||
#processEventBuffer(events: Array<[events: PathWatcherEvent[]]>) {
|
||||
const watchEvents = events.flat(2);
|
||||
|
||||
for (const { type, path, buffer } of watchEvents) {
|
||||
// remove any trailing slashes
|
||||
const sanitizedPath = path.replace(/\/+$/g, '');
|
||||
|
||||
switch (type) {
|
||||
case 'add_dir': {
|
||||
// we intentionally add a trailing slash so we can distinguish files from folders in the file tree
|
||||
this.files.setKey(sanitizedPath, { type: 'folder' });
|
||||
break;
|
||||
}
|
||||
case 'remove_dir': {
|
||||
this.files.setKey(sanitizedPath, undefined);
|
||||
|
||||
for (const [direntPath] of Object.entries(this.files)) {
|
||||
if (direntPath.startsWith(sanitizedPath)) {
|
||||
this.files.setKey(direntPath, undefined);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case 'add_file':
|
||||
case 'change': {
|
||||
if (type === 'add_file') {
|
||||
this.#size++;
|
||||
}
|
||||
|
||||
let content = '';
|
||||
|
||||
/**
|
||||
* @note This check is purely for the editor. The way we detect this is not
|
||||
* bullet-proof and it's a best guess so there might be false-positives.
|
||||
* The reason we do this is because we don't want to display binary files
|
||||
* in the editor nor allow to edit them.
|
||||
*/
|
||||
const isBinary = isBinaryFile(buffer);
|
||||
|
||||
if (!isBinary) {
|
||||
content = this.#decodeFileContent(buffer);
|
||||
}
|
||||
|
||||
this.files.setKey(sanitizedPath, { type: 'file', content, isBinary });
|
||||
|
||||
break;
|
||||
}
|
||||
case 'remove_file': {
|
||||
this.#size--;
|
||||
this.files.setKey(sanitizedPath, undefined);
|
||||
break;
|
||||
}
|
||||
case 'update_directory': {
|
||||
// we don't care about these events
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#decodeFileContent(buffer?: Uint8Array) {
|
||||
if (!buffer || buffer.byteLength === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
return utf8TextDecoder.decode(buffer);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isBinaryFile(buffer: Uint8Array | undefined) {
|
||||
if (buffer === undefined) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return getEncoding(convertToBuffer(buffer), { chunkLength: 100 }) === 'binary';
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a `Uint8Array` into a Node.js `Buffer` by copying the prototype.
|
||||
* The goal is to avoid expensive copies. It does create a new typed array
|
||||
* but that's generally cheap as long as it uses the same underlying
|
||||
* array buffer.
|
||||
*/
|
||||
function convertToBuffer(view: Uint8Array): Buffer {
|
||||
const buffer = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
||||
|
||||
Object.setPrototypeOf(buffer, Buffer.prototype);
|
||||
|
||||
return buffer as Buffer;
|
||||
}
|
||||
49
app/lib/stores/previews.ts
Normal file
49
app/lib/stores/previews.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import type { WebContainer } from '@webcontainer/api';
|
||||
import { atom } from 'nanostores';
|
||||
|
||||
export interface PreviewInfo {
|
||||
port: number;
|
||||
ready: boolean;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
export class PreviewsStore {
|
||||
#availablePreviews = new Map<number, PreviewInfo>();
|
||||
#webcontainer: Promise<WebContainer>;
|
||||
|
||||
previews = atom<PreviewInfo[]>([]);
|
||||
|
||||
constructor(webcontainerPromise: Promise<WebContainer>) {
|
||||
this.#webcontainer = webcontainerPromise;
|
||||
|
||||
this.#init();
|
||||
}
|
||||
|
||||
async #init() {
|
||||
const webcontainer = await this.#webcontainer;
|
||||
|
||||
webcontainer.on('port', (port, type, url) => {
|
||||
let previewInfo = this.#availablePreviews.get(port);
|
||||
|
||||
if (type === 'close' && previewInfo) {
|
||||
this.#availablePreviews.delete(port);
|
||||
this.previews.set(this.previews.get().filter((preview) => preview.port !== port));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const previews = this.previews.get();
|
||||
|
||||
if (!previewInfo) {
|
||||
previewInfo = { port, ready: type === 'open', baseUrl: url };
|
||||
this.#availablePreviews.set(port, previewInfo);
|
||||
previews.push(previewInfo);
|
||||
}
|
||||
|
||||
previewInfo.ready = type === 'open';
|
||||
previewInfo.baseUrl = url;
|
||||
|
||||
this.previews.set([...previews]);
|
||||
});
|
||||
}
|
||||
}
|
||||
39
app/lib/stores/settings.ts
Normal file
39
app/lib/stores/settings.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { map } from 'nanostores';
|
||||
import { workbenchStore } from './workbench';
|
||||
|
||||
export interface Shortcut {
|
||||
key: string;
|
||||
ctrlKey?: boolean;
|
||||
shiftKey?: boolean;
|
||||
altKey?: boolean;
|
||||
metaKey?: boolean;
|
||||
ctrlOrMetaKey?: boolean;
|
||||
action: () => void;
|
||||
}
|
||||
|
||||
export interface Shortcuts {
|
||||
toggleTerminal: Shortcut;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
shortcuts: Shortcuts;
|
||||
}
|
||||
|
||||
export const shortcutsStore = map<Shortcuts>({
|
||||
toggleTerminal: {
|
||||
key: 'j',
|
||||
ctrlOrMetaKey: true,
|
||||
action: () => workbenchStore.toggleTerminal(),
|
||||
},
|
||||
});
|
||||
|
||||
export const settingsStore = map<Settings>({
|
||||
shortcuts: shortcutsStore.get(),
|
||||
});
|
||||
|
||||
shortcutsStore.subscribe((shortcuts) => {
|
||||
settingsStore.set({
|
||||
...settingsStore.get(),
|
||||
shortcuts,
|
||||
});
|
||||
});
|
||||
40
app/lib/stores/terminal.ts
Normal file
40
app/lib/stores/terminal.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import type { WebContainer, WebContainerProcess } from '@webcontainer/api';
|
||||
import { atom, type WritableAtom } from 'nanostores';
|
||||
import type { ITerminal } from '~/types/terminal';
|
||||
import { newShellProcess } from '~/utils/shell';
|
||||
import { coloredText } from '~/utils/terminal';
|
||||
|
||||
export class TerminalStore {
|
||||
#webcontainer: Promise<WebContainer>;
|
||||
#terminals: Array<{ terminal: ITerminal; process: WebContainerProcess }> = [];
|
||||
|
||||
showTerminal: WritableAtom<boolean> = import.meta.hot?.data.showTerminal ?? atom(false);
|
||||
|
||||
constructor(webcontainerPromise: Promise<WebContainer>) {
|
||||
this.#webcontainer = webcontainerPromise;
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.showTerminal = this.showTerminal;
|
||||
}
|
||||
}
|
||||
|
||||
toggleTerminal(value?: boolean) {
|
||||
this.showTerminal.set(value !== undefined ? value : !this.showTerminal.get());
|
||||
}
|
||||
|
||||
async attachTerminal(terminal: ITerminal) {
|
||||
try {
|
||||
const shellProcess = await newShellProcess(await this.#webcontainer, terminal);
|
||||
this.#terminals.push({ terminal, process: shellProcess });
|
||||
} catch (error: any) {
|
||||
terminal.write(coloredText.red('Failed to spawn shell\n\n') + error.message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
onTerminalResize(cols: number, rows: number) {
|
||||
for (const { process } of this.#terminals) {
|
||||
process.resize({ cols, rows });
|
||||
}
|
||||
}
|
||||
}
|
||||
35
app/lib/stores/theme.ts
Normal file
35
app/lib/stores/theme.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { atom } from 'nanostores';
|
||||
|
||||
export type Theme = 'dark' | 'light';
|
||||
|
||||
export const kTheme = 'bolt_theme';
|
||||
|
||||
export function themeIsDark() {
|
||||
return themeStore.get() === 'dark';
|
||||
}
|
||||
|
||||
export const DEFAULT_THEME = 'light';
|
||||
|
||||
export const themeStore = atom<Theme>(initStore());
|
||||
|
||||
function initStore() {
|
||||
if (!import.meta.env.SSR) {
|
||||
const persistedTheme = localStorage.getItem(kTheme) as Theme | undefined;
|
||||
const themeAttribute = document.querySelector('html')?.getAttribute('data-theme');
|
||||
|
||||
return persistedTheme ?? (themeAttribute as Theme) ?? DEFAULT_THEME;
|
||||
}
|
||||
|
||||
return DEFAULT_THEME;
|
||||
}
|
||||
|
||||
export function toggleTheme() {
|
||||
const currentTheme = themeStore.get();
|
||||
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
||||
|
||||
themeStore.set(newTheme);
|
||||
|
||||
localStorage.setItem(kTheme, newTheme);
|
||||
|
||||
document.querySelector('html')?.setAttribute('data-theme', newTheme);
|
||||
}
|
||||
276
app/lib/stores/workbench.ts
Normal file
276
app/lib/stores/workbench.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import { atom, map, type MapStore, type ReadableAtom, type WritableAtom } from 'nanostores';
|
||||
import type { EditorDocument, ScrollPosition } from '~/components/editor/codemirror/CodeMirrorEditor';
|
||||
import { ActionRunner } from '~/lib/runtime/action-runner';
|
||||
import type { ActionCallbackData, ArtifactCallbackData } from '~/lib/runtime/message-parser';
|
||||
import { webcontainer } from '~/lib/webcontainer';
|
||||
import type { ITerminal } from '~/types/terminal';
|
||||
import { unreachable } from '~/utils/unreachable';
|
||||
import { EditorStore } from './editor';
|
||||
import { FilesStore, type FileMap } from './files';
|
||||
import { PreviewsStore } from './previews';
|
||||
import { TerminalStore } from './terminal';
|
||||
|
||||
export interface ArtifactState {
|
||||
id: string;
|
||||
title: string;
|
||||
closed: boolean;
|
||||
runner: ActionRunner;
|
||||
}
|
||||
|
||||
export type ArtifactUpdateState = Pick<ArtifactState, 'title' | 'closed'>;
|
||||
|
||||
type Artifacts = MapStore<Record<string, ArtifactState>>;
|
||||
|
||||
export type WorkbenchViewType = 'code' | 'preview';
|
||||
|
||||
export class WorkbenchStore {
|
||||
#previewsStore = new PreviewsStore(webcontainer);
|
||||
#filesStore = new FilesStore(webcontainer);
|
||||
#editorStore = new EditorStore(this.#filesStore);
|
||||
#terminalStore = new TerminalStore(webcontainer);
|
||||
|
||||
artifacts: Artifacts = import.meta.hot?.data.artifacts ?? map({});
|
||||
|
||||
showWorkbench: WritableAtom<boolean> = import.meta.hot?.data.showWorkbench ?? atom(false);
|
||||
currentView: WritableAtom<WorkbenchViewType> = import.meta.hot?.data.currentView ?? atom('code');
|
||||
unsavedFiles: WritableAtom<Set<string>> = import.meta.hot?.data.unsavedFiles ?? atom(new Set<string>());
|
||||
modifiedFiles = new Set<string>();
|
||||
artifactIdList: string[] = [];
|
||||
|
||||
constructor() {
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.artifacts = this.artifacts;
|
||||
import.meta.hot.data.unsavedFiles = this.unsavedFiles;
|
||||
import.meta.hot.data.showWorkbench = this.showWorkbench;
|
||||
import.meta.hot.data.currentView = this.currentView;
|
||||
}
|
||||
}
|
||||
|
||||
get previews() {
|
||||
return this.#previewsStore.previews;
|
||||
}
|
||||
|
||||
get files() {
|
||||
return this.#filesStore.files;
|
||||
}
|
||||
|
||||
get currentDocument(): ReadableAtom<EditorDocument | undefined> {
|
||||
return this.#editorStore.currentDocument;
|
||||
}
|
||||
|
||||
get selectedFile(): ReadableAtom<string | undefined> {
|
||||
return this.#editorStore.selectedFile;
|
||||
}
|
||||
|
||||
get firstArtifact(): ArtifactState | undefined {
|
||||
return this.#getArtifact(this.artifactIdList[0]);
|
||||
}
|
||||
|
||||
get filesCount(): number {
|
||||
return this.#filesStore.filesCount;
|
||||
}
|
||||
|
||||
get showTerminal() {
|
||||
return this.#terminalStore.showTerminal;
|
||||
}
|
||||
|
||||
toggleTerminal(value?: boolean) {
|
||||
this.#terminalStore.toggleTerminal(value);
|
||||
}
|
||||
|
||||
attachTerminal(terminal: ITerminal) {
|
||||
this.#terminalStore.attachTerminal(terminal);
|
||||
}
|
||||
|
||||
onTerminalResize(cols: number, rows: number) {
|
||||
this.#terminalStore.onTerminalResize(cols, rows);
|
||||
}
|
||||
|
||||
setDocuments(files: FileMap) {
|
||||
this.#editorStore.setDocuments(files);
|
||||
|
||||
if (this.#filesStore.filesCount > 0 && this.currentDocument.get() === undefined) {
|
||||
// we find the first file and select it
|
||||
for (const [filePath, dirent] of Object.entries(files)) {
|
||||
if (dirent?.type === 'file') {
|
||||
this.setSelectedFile(filePath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setShowWorkbench(show: boolean) {
|
||||
this.showWorkbench.set(show);
|
||||
}
|
||||
|
||||
setCurrentDocumentContent(newContent: string) {
|
||||
const filePath = this.currentDocument.get()?.filePath;
|
||||
|
||||
if (!filePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
const originalContent = this.#filesStore.getFile(filePath)?.content;
|
||||
const unsavedChanges = originalContent !== undefined && originalContent !== newContent;
|
||||
|
||||
this.#editorStore.updateFile(filePath, newContent);
|
||||
|
||||
const currentDocument = this.currentDocument.get();
|
||||
|
||||
if (currentDocument) {
|
||||
const previousUnsavedFiles = this.unsavedFiles.get();
|
||||
|
||||
if (unsavedChanges && previousUnsavedFiles.has(currentDocument.filePath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newUnsavedFiles = new Set(previousUnsavedFiles);
|
||||
|
||||
if (unsavedChanges) {
|
||||
newUnsavedFiles.add(currentDocument.filePath);
|
||||
} else {
|
||||
newUnsavedFiles.delete(currentDocument.filePath);
|
||||
}
|
||||
|
||||
this.unsavedFiles.set(newUnsavedFiles);
|
||||
}
|
||||
}
|
||||
|
||||
setCurrentDocumentScrollPosition(position: ScrollPosition) {
|
||||
const editorDocument = this.currentDocument.get();
|
||||
|
||||
if (!editorDocument) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { filePath } = editorDocument;
|
||||
|
||||
this.#editorStore.updateScrollPosition(filePath, position);
|
||||
}
|
||||
|
||||
setSelectedFile(filePath: string | undefined) {
|
||||
this.#editorStore.setSelectedFile(filePath);
|
||||
}
|
||||
|
||||
async saveFile(filePath: string) {
|
||||
const documents = this.#editorStore.documents.get();
|
||||
const document = documents[filePath];
|
||||
|
||||
if (document === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.#filesStore.saveFile(filePath, document.value);
|
||||
|
||||
const newUnsavedFiles = new Set(this.unsavedFiles.get());
|
||||
newUnsavedFiles.delete(filePath);
|
||||
|
||||
this.unsavedFiles.set(newUnsavedFiles);
|
||||
}
|
||||
|
||||
async saveCurrentDocument() {
|
||||
const currentDocument = this.currentDocument.get();
|
||||
|
||||
if (currentDocument === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.saveFile(currentDocument.filePath);
|
||||
}
|
||||
|
||||
resetCurrentDocument() {
|
||||
const currentDocument = this.currentDocument.get();
|
||||
|
||||
if (currentDocument === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { filePath } = currentDocument;
|
||||
const file = this.#filesStore.getFile(filePath);
|
||||
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.setCurrentDocumentContent(file.content);
|
||||
}
|
||||
|
||||
async saveAllFiles() {
|
||||
for (const filePath of this.unsavedFiles.get()) {
|
||||
await this.saveFile(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
getFileModifcations() {
|
||||
return this.#filesStore.getFileModifications();
|
||||
}
|
||||
|
||||
resetAllFileModifications() {
|
||||
this.#filesStore.resetFileModifications();
|
||||
}
|
||||
|
||||
abortAllActions() {
|
||||
// TODO: what do we wanna do and how do we wanna recover from this?
|
||||
}
|
||||
|
||||
addArtifact({ messageId, title, id }: ArtifactCallbackData) {
|
||||
const artifact = this.#getArtifact(messageId);
|
||||
|
||||
if (artifact) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.artifactIdList.includes(messageId)) {
|
||||
this.artifactIdList.push(messageId);
|
||||
}
|
||||
|
||||
this.artifacts.setKey(messageId, {
|
||||
id,
|
||||
title,
|
||||
closed: false,
|
||||
runner: new ActionRunner(webcontainer),
|
||||
});
|
||||
}
|
||||
|
||||
updateArtifact({ messageId }: ArtifactCallbackData, state: Partial<ArtifactUpdateState>) {
|
||||
const artifact = this.#getArtifact(messageId);
|
||||
|
||||
if (!artifact) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.artifacts.setKey(messageId, { ...artifact, ...state });
|
||||
}
|
||||
|
||||
async addAction(data: ActionCallbackData) {
|
||||
const { messageId } = data;
|
||||
|
||||
const artifact = this.#getArtifact(messageId);
|
||||
|
||||
if (!artifact) {
|
||||
unreachable('Artifact not found');
|
||||
}
|
||||
|
||||
artifact.runner.addAction(data);
|
||||
}
|
||||
|
||||
async runAction(data: ActionCallbackData) {
|
||||
const { messageId } = data;
|
||||
|
||||
const artifact = this.#getArtifact(messageId);
|
||||
|
||||
if (!artifact) {
|
||||
unreachable('Artifact not found');
|
||||
}
|
||||
|
||||
artifact.runner.runAction(data);
|
||||
}
|
||||
|
||||
#getArtifact(id: string) {
|
||||
const artifacts = this.artifacts.get();
|
||||
return artifacts[id];
|
||||
}
|
||||
}
|
||||
|
||||
export const workbenchStore = new WorkbenchStore();
|
||||
6
app/lib/webcontainer/auth.client.ts
Normal file
6
app/lib/webcontainer/auth.client.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* This client-only module that contains everything related to auth and is used
|
||||
* to avoid importing `@webcontainer/api` in the server bundle.
|
||||
*/
|
||||
|
||||
export { auth, type AuthAPI } from '@webcontainer/api';
|
||||
37
app/lib/webcontainer/index.ts
Normal file
37
app/lib/webcontainer/index.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { WebContainer } from '@webcontainer/api';
|
||||
import { WORK_DIR_NAME } from '~/utils/constants';
|
||||
import { forgetAuth } from '~/lib/auth';
|
||||
|
||||
interface WebContainerContext {
|
||||
loaded: boolean;
|
||||
}
|
||||
|
||||
export const webcontainerContext: WebContainerContext = import.meta.hot?.data.webcontainerContext ?? {
|
||||
loaded: false,
|
||||
};
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.webcontainerContext = webcontainerContext;
|
||||
}
|
||||
|
||||
export let webcontainer: Promise<WebContainer> = new Promise(() => {
|
||||
// noop for ssr
|
||||
});
|
||||
|
||||
if (!import.meta.env.SSR) {
|
||||
webcontainer =
|
||||
import.meta.hot?.data.webcontainer ??
|
||||
Promise.resolve()
|
||||
.then(() => {
|
||||
forgetAuth();
|
||||
return WebContainer.boot({ workdirName: WORK_DIR_NAME });
|
||||
})
|
||||
.then((webcontainer) => {
|
||||
webcontainerContext.loaded = true;
|
||||
return webcontainer;
|
||||
});
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.webcontainer = webcontainer;
|
||||
}
|
||||
}
|
||||
76
app/root.tsx
Normal file
76
app/root.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import type { LinksFunction } from '@remix-run/cloudflare';
|
||||
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from '@remix-run/react';
|
||||
import tailwindReset from '@unocss/reset/tailwind-compat.css?url';
|
||||
import { themeStore } from './lib/stores/theme';
|
||||
import { stripIndents } from './utils/stripIndent';
|
||||
|
||||
import reactToastifyStyles from 'react-toastify/dist/ReactToastify.css?url';
|
||||
import globalStyles from './styles/index.scss?url';
|
||||
import xtermStyles from '@xterm/xterm/css/xterm.css?url';
|
||||
|
||||
import 'virtual:uno.css';
|
||||
|
||||
export const links: LinksFunction = () => [
|
||||
{
|
||||
rel: 'icon',
|
||||
href: '/favicon.svg',
|
||||
type: 'image/svg+xml',
|
||||
},
|
||||
{ rel: 'stylesheet', href: reactToastifyStyles },
|
||||
{ rel: 'stylesheet', href: tailwindReset },
|
||||
{ rel: 'stylesheet', href: globalStyles },
|
||||
{ rel: 'stylesheet', href: xtermStyles },
|
||||
{
|
||||
rel: 'preconnect',
|
||||
href: 'https://fonts.googleapis.com',
|
||||
},
|
||||
{
|
||||
rel: 'preconnect',
|
||||
href: 'https://fonts.gstatic.com',
|
||||
crossOrigin: 'anonymous',
|
||||
},
|
||||
{
|
||||
rel: 'stylesheet',
|
||||
href: 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap',
|
||||
},
|
||||
];
|
||||
|
||||
const inlineThemeCode = stripIndents`
|
||||
setTutorialKitTheme();
|
||||
|
||||
function setTutorialKitTheme() {
|
||||
let theme = localStorage.getItem('bolt_theme');
|
||||
|
||||
if (!theme) {
|
||||
theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
document.querySelector('html')?.setAttribute('data-theme', theme);
|
||||
}
|
||||
`;
|
||||
|
||||
export function Layout({ children }: { children: React.ReactNode }) {
|
||||
const theme = useStore(themeStore);
|
||||
|
||||
return (
|
||||
<html lang="en" data-theme={theme}>
|
||||
<head>
|
||||
<meta charSet="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<Meta />
|
||||
<Links />
|
||||
<script dangerouslySetInnerHTML={{ __html: inlineThemeCode }} />
|
||||
</head>
|
||||
<body>
|
||||
{children}
|
||||
<ScrollRestoration />
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return <Outlet />;
|
||||
}
|
||||
23
app/routes/_index.tsx
Normal file
23
app/routes/_index.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { json, type LoaderFunctionArgs, type MetaFunction } from '@remix-run/cloudflare';
|
||||
import { ClientOnly } from 'remix-utils/client-only';
|
||||
import { BaseChat } from '~/components/chat/BaseChat';
|
||||
import { Chat } from '~/components/chat/Chat.client';
|
||||
import { Header } from '~/components/header/Header';
|
||||
import { loadWithAuth } from '~/lib/.server/auth';
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [{ title: 'Bolt' }, { name: 'description', content: 'Talk with Bolt, an AI assistant from StackBlitz' }];
|
||||
};
|
||||
|
||||
export async function loader(args: LoaderFunctionArgs) {
|
||||
return loadWithAuth(args, async (_args, session) => json({ avatar: session.avatar }));
|
||||
}
|
||||
|
||||
export default function Index() {
|
||||
return (
|
||||
<div className="flex flex-col h-full w-full">
|
||||
<Header />
|
||||
<ClientOnly fallback={<BaseChat />}>{() => <Chat />}</ClientOnly>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
60
app/routes/api.chat.ts
Normal file
60
app/routes/api.chat.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
|
||||
import { actionWithAuth } from '~/lib/.server/auth';
|
||||
import { MAX_RESPONSE_SEGMENTS, MAX_TOKENS } from '~/lib/.server/llm/constants';
|
||||
import { CONTINUE_PROMPT } from '~/lib/.server/llm/prompts';
|
||||
import { streamText, type Messages, type StreamingOptions } from '~/lib/.server/llm/stream-text';
|
||||
import SwitchableStream from '~/lib/.server/llm/switchable-stream';
|
||||
|
||||
export async function action(args: ActionFunctionArgs) {
|
||||
return actionWithAuth(args, chatAction);
|
||||
}
|
||||
|
||||
async function chatAction({ context, request }: ActionFunctionArgs) {
|
||||
const { messages } = await request.json<{ messages: Messages }>();
|
||||
|
||||
const stream = new SwitchableStream();
|
||||
|
||||
try {
|
||||
const options: StreamingOptions = {
|
||||
toolChoice: 'none',
|
||||
onFinish: async ({ text: content, finishReason }) => {
|
||||
if (finishReason !== 'length') {
|
||||
return stream.close();
|
||||
}
|
||||
|
||||
if (stream.switches >= MAX_RESPONSE_SEGMENTS) {
|
||||
throw Error('Cannot continue message: Maximum segments reached');
|
||||
}
|
||||
|
||||
const switchesLeft = MAX_RESPONSE_SEGMENTS - stream.switches;
|
||||
|
||||
console.log(`Reached max token limit (${MAX_TOKENS}): Continuing message (${switchesLeft} switches left)`);
|
||||
|
||||
messages.push({ role: 'assistant', content });
|
||||
messages.push({ role: 'user', content: CONTINUE_PROMPT });
|
||||
|
||||
const result = await streamText(messages, context.cloudflare.env, options);
|
||||
|
||||
return stream.switchSource(result.toAIStream());
|
||||
},
|
||||
};
|
||||
|
||||
const result = await streamText(messages, context.cloudflare.env, options);
|
||||
|
||||
stream.switchSource(result.toAIStream());
|
||||
|
||||
return new Response(stream.readable, {
|
||||
status: 200,
|
||||
headers: {
|
||||
contentType: 'text/plain; charset=utf-8',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
||||
throw new Response(null, {
|
||||
status: 500,
|
||||
statusText: 'Internal Server Error',
|
||||
});
|
||||
}
|
||||
}
|
||||
61
app/routes/api.enhancer.ts
Normal file
61
app/routes/api.enhancer.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
|
||||
import { StreamingTextResponse, parseStreamPart } from 'ai';
|
||||
import { actionWithAuth } from '~/lib/.server/auth';
|
||||
import { streamText } from '~/lib/.server/llm/stream-text';
|
||||
import { stripIndents } from '~/utils/stripIndent';
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
export async function action(args: ActionFunctionArgs) {
|
||||
return actionWithAuth(args, enhancerAction);
|
||||
}
|
||||
|
||||
async function enhancerAction({ context, request }: ActionFunctionArgs) {
|
||||
const { message } = await request.json<{ message: string }>();
|
||||
|
||||
try {
|
||||
const result = await streamText(
|
||||
[
|
||||
{
|
||||
role: 'user',
|
||||
content: stripIndents`
|
||||
I want you to improve the user prompt that is wrapped in \`<original_prompt>\` tags.
|
||||
|
||||
IMPORTANT: Only respond with the improved prompt and nothing else!
|
||||
|
||||
<original_prompt>
|
||||
${message}
|
||||
</original_prompt>
|
||||
`,
|
||||
},
|
||||
],
|
||||
context.cloudflare.env,
|
||||
);
|
||||
|
||||
const transformStream = new TransformStream({
|
||||
transform(chunk, controller) {
|
||||
const processedChunk = decoder
|
||||
.decode(chunk)
|
||||
.split('\n')
|
||||
.filter((line) => line !== '')
|
||||
.map(parseStreamPart)
|
||||
.map((part) => part.value)
|
||||
.join('');
|
||||
|
||||
controller.enqueue(encoder.encode(processedChunk));
|
||||
},
|
||||
});
|
||||
|
||||
const transformedStream = result.toAIStream().pipeThrough(transformStream);
|
||||
|
||||
return new StreamingTextResponse(transformedStream);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
||||
throw new Response(null, {
|
||||
status: 500,
|
||||
statusText: 'Internal Server Error',
|
||||
});
|
||||
}
|
||||
}
|
||||
9
app/routes/chat.$id.tsx
Normal file
9
app/routes/chat.$id.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import { json, type LoaderFunctionArgs } from '@remix-run/cloudflare';
|
||||
import { default as IndexRoute } from './_index';
|
||||
import { loadWithAuth } from '~/lib/.server/auth';
|
||||
|
||||
export async function loader(args: LoaderFunctionArgs) {
|
||||
return loadWithAuth(args, async (_args, session) => json({ id: args.params.id, avatar: session.avatar }));
|
||||
}
|
||||
|
||||
export default IndexRoute;
|
||||
201
app/routes/login.tsx
Normal file
201
app/routes/login.tsx
Normal file
@@ -0,0 +1,201 @@
|
||||
import {
|
||||
json,
|
||||
redirect,
|
||||
redirectDocument,
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
} from '@remix-run/cloudflare';
|
||||
import { useFetcher, useLoaderData } from '@remix-run/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { LoadingDots } from '~/components/ui/LoadingDots';
|
||||
import { createUserSession, isAuthenticated, validateAccessToken } from '~/lib/.server/sessions';
|
||||
import { identifyUser } from '~/lib/analytics';
|
||||
import { CLIENT_ID, CLIENT_ORIGIN } from '~/lib/constants';
|
||||
import { request as doRequest } from '~/lib/fetch';
|
||||
import { auth, type AuthAPI } from '~/lib/webcontainer/auth.client';
|
||||
import { logger } from '~/utils/logger';
|
||||
|
||||
export async function loader({ request, context }: LoaderFunctionArgs) {
|
||||
const { session, response } = await isAuthenticated(request, context.cloudflare.env);
|
||||
|
||||
if (session != null) {
|
||||
return redirect('/', response);
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
|
||||
return json(
|
||||
{
|
||||
redirected: url.searchParams.has('code') || url.searchParams.has('error'),
|
||||
},
|
||||
response,
|
||||
);
|
||||
}
|
||||
|
||||
export async function action({ request, context }: ActionFunctionArgs) {
|
||||
const formData = await request.formData();
|
||||
|
||||
const payload = {
|
||||
access: String(formData.get('access')),
|
||||
refresh: String(formData.get('refresh')),
|
||||
};
|
||||
|
||||
let response: Awaited<ReturnType<typeof doRequest>> | undefined;
|
||||
|
||||
try {
|
||||
response = await doRequest(`${CLIENT_ORIGIN}/oauth/token/info`, {
|
||||
headers: { authorization: `Bearer ${payload.access}` },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await response.json();
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Authentication failed');
|
||||
logger.warn(error);
|
||||
|
||||
return json({ error: 'invalid-token' as const }, { status: 401 });
|
||||
}
|
||||
|
||||
const boltEnabled = validateAccessToken(payload.access);
|
||||
|
||||
if (!boltEnabled) {
|
||||
return json({ error: 'bolt-access' as const }, { status: 401 });
|
||||
}
|
||||
|
||||
const identity = await identifyUser(payload.access);
|
||||
|
||||
const tokenInfo: { expires_in: number; created_at: number } = await response.json();
|
||||
|
||||
const init = await createUserSession(request, context.cloudflare.env, { ...payload, ...tokenInfo }, identity);
|
||||
|
||||
return redirectDocument('/', init);
|
||||
}
|
||||
|
||||
type LoginState =
|
||||
| {
|
||||
kind: 'error';
|
||||
error: string;
|
||||
description: string;
|
||||
}
|
||||
| { kind: 'pending' };
|
||||
|
||||
const ERRORS = {
|
||||
'bolt-access': 'You do not have access to Bolt.',
|
||||
'invalid-token': 'Authentication failed.',
|
||||
};
|
||||
|
||||
export default function Login() {
|
||||
const { redirected } = useLoaderData<typeof loader>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!import.meta.hot?.data.wcAuth) {
|
||||
auth.init({ clientId: CLIENT_ID, scope: 'public', editorOrigin: CLIENT_ORIGIN });
|
||||
}
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.data.wcAuth = true;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
{redirected ? (
|
||||
<LoadingDots text="Authenticating" />
|
||||
) : (
|
||||
<div className="max-w-md w-full space-y-8 p-10 bg-white rounded-lg shadow">
|
||||
<div>
|
||||
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">Login</h2>
|
||||
</div>
|
||||
<LoginForm />
|
||||
<p className="mt-4 text-sm text-center text-gray-600">
|
||||
By using Bolt, you agree to the collection of usage data for analytics.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginForm() {
|
||||
const [login, setLogin] = useState<LoginState | null>(null);
|
||||
|
||||
const fetcher = useFetcher<typeof action>();
|
||||
|
||||
useEffect(() => {
|
||||
auth.logout({ ignoreRevokeError: true });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.error) {
|
||||
auth.logout({ ignoreRevokeError: true });
|
||||
|
||||
setLogin({
|
||||
kind: 'error' as const,
|
||||
...{ error: fetcher.data.error, description: ERRORS[fetcher.data.error] },
|
||||
});
|
||||
}
|
||||
}, [fetcher.data]);
|
||||
|
||||
async function attemptLogin() {
|
||||
startAuthFlow();
|
||||
|
||||
function startAuthFlow() {
|
||||
auth.startAuthFlow({ popup: true });
|
||||
|
||||
Promise.race([authEvent(auth, 'auth-failed'), auth.loggedIn()]).then((error) => {
|
||||
if (error) {
|
||||
setLogin({ kind: 'error', ...error });
|
||||
} else {
|
||||
onTokens();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function onTokens() {
|
||||
const tokens = auth.tokens()!;
|
||||
|
||||
fetcher.submit(tokens, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
setLogin({ kind: 'pending' });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
className="w-full text-white bg-accent-600 hover:bg-accent-700 focus:ring-4 focus:outline-none font-medium rounded-lg text-sm px-5 py-2.5 text-center"
|
||||
onClick={attemptLogin}
|
||||
disabled={login?.kind === 'pending'}
|
||||
>
|
||||
{login?.kind === 'pending' ? 'Authenticating...' : 'Continue with StackBlitz'}
|
||||
</button>
|
||||
{login?.kind === 'error' && (
|
||||
<div>
|
||||
<h2>
|
||||
<code>{login.error}</code>
|
||||
</h2>
|
||||
<p>{login.description}</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface AuthError {
|
||||
error: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
function authEvent(auth: AuthAPI, event: 'logged-out'): Promise<void>;
|
||||
function authEvent(auth: AuthAPI, event: 'auth-failed'): Promise<AuthError>;
|
||||
function authEvent(auth: AuthAPI, event: 'logged-out' | 'auth-failed') {
|
||||
return new Promise((resolve) => {
|
||||
const unsubscribe = auth.on(event as any, (arg: any) => {
|
||||
unsubscribe();
|
||||
resolve(arg);
|
||||
});
|
||||
});
|
||||
}
|
||||
10
app/routes/logout.tsx
Normal file
10
app/routes/logout.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import type { LoaderFunctionArgs } from '@remix-run/cloudflare';
|
||||
import { logout } from '~/lib/.server/sessions';
|
||||
|
||||
export async function loader({ request, context }: LoaderFunctionArgs) {
|
||||
return logout(request, context.cloudflare.env);
|
||||
}
|
||||
|
||||
export default function Logout() {
|
||||
return '';
|
||||
}
|
||||
49
app/styles/animations.scss
Normal file
49
app/styles/animations.scss
Normal file
@@ -0,0 +1,49 @@
|
||||
.animated {
|
||||
animation-fill-mode: both;
|
||||
animation-duration: var(--animate-duration, 0.2s);
|
||||
animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
|
||||
|
||||
&.fadeInRight {
|
||||
animation-name: fadeInRight;
|
||||
}
|
||||
|
||||
&.fadeOutRight {
|
||||
animation-name: fadeOutRight;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeInRight {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate3d(100%, 0, 0);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeOutRight {
|
||||
from {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translate3d(100%, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
.dropdown-animation {
|
||||
opacity: 0;
|
||||
animation: fadeMoveDown 0.15s forwards;
|
||||
animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
@keyframes fadeMoveDown {
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
}
|
||||
9
app/styles/components/code.scss
Normal file
9
app/styles/components/code.scss
Normal file
@@ -0,0 +1,9 @@
|
||||
.actions .shiki {
|
||||
background-color: var(--bolt-elements-actions-code-background) !important;
|
||||
}
|
||||
|
||||
.shiki {
|
||||
&:not(:has(.actions), .actions *) {
|
||||
background-color: var(--bolt-elements-messages-code-background) !important;
|
||||
}
|
||||
}
|
||||
135
app/styles/components/editor.scss
Normal file
135
app/styles/components/editor.scss
Normal file
@@ -0,0 +1,135 @@
|
||||
:root {
|
||||
--cm-backgroundColor: var(--bolt-elements-editor-backgroundColor, var(--bolt-elements-bg-depth-1));
|
||||
--cm-textColor: var(--bolt-elements-editor-textColor, var(--bolt-elements-textPrimary));
|
||||
|
||||
/* Gutter */
|
||||
|
||||
--cm-gutter-backgroundColor: var(--bolt-elements-editor-gutter-backgroundColor, var(--cm-backgroundColor));
|
||||
--cm-gutter-textColor: var(--bolt-elements-editor-gutter-textColor, var(--bolt-elements-textSecondary));
|
||||
--cm-gutter-activeLineTextColor: var(--bolt-elements-editor-gutter-activeLineTextColor, var(--cm-gutter-textColor));
|
||||
|
||||
/* Fold Gutter */
|
||||
|
||||
--cm-foldGutter-textColor: var(--bolt-elements-editor-foldGutter-textColor, var(--cm-gutter-textColor));
|
||||
--cm-foldGutter-textColorHover: var(--bolt-elements-editor-foldGutter-textColorHover, var(--cm-gutter-textColor));
|
||||
|
||||
/* Active Line */
|
||||
|
||||
--cm-activeLineBackgroundColor: var(--bolt-elements-editor-activeLineBackgroundColor, rgb(224 231 235 / 30%));
|
||||
|
||||
/* Cursor */
|
||||
|
||||
--cm-cursor-width: 2px;
|
||||
--cm-cursor-backgroundColor: var(--bolt-elements-editor-cursorColor, var(--bolt-elements-textSecondary));
|
||||
|
||||
/* Matching Brackets */
|
||||
|
||||
--cm-matching-bracket: var(--bolt-elements-editor-matchingBracketBackgroundColor, rgb(50 140 130 / 0.3));
|
||||
|
||||
/* Selection */
|
||||
|
||||
--cm-selection-backgroundColorFocused: var(--bolt-elements-editor-selection-backgroundColor, #42b4ff);
|
||||
--cm-selection-backgroundOpacityFocused: var(--bolt-elements-editor-selection-backgroundOpacity, 0.3);
|
||||
--cm-selection-backgroundColorBlured: var(--bolt-elements-editor-selection-inactiveBackgroundColor, #c9e9ff);
|
||||
--cm-selection-backgroundOpacityBlured: var(--bolt-elements-editor-selection-inactiveBackgroundOpacity, 0.3);
|
||||
|
||||
/* Panels */
|
||||
|
||||
--cm-panels-borderColor: var(--bolt-elements-editor-panels-borderColor, var(--bolt-elements-borderColor));
|
||||
|
||||
/* Search */
|
||||
|
||||
--cm-search-backgroundColor: var(--bolt-elements-editor-search-backgroundColor, var(--cm-backgroundColor));
|
||||
--cm-search-textColor: var(--bolt-elements-editor-search-textColor, var(--bolt-elements-textSecondary));
|
||||
--cm-search-closeButton-backgroundColor: var(--bolt-elements-editor-search-closeButton-backgroundColor, transparent);
|
||||
|
||||
--cm-search-closeButton-backgroundColorHover: var(
|
||||
--bolt-elements-editor-search-closeButton-backgroundColorHover,
|
||||
var(--bolt-elements-item-backgroundActive)
|
||||
);
|
||||
|
||||
--cm-search-closeButton-textColor: var(
|
||||
--bolt-elements-editor-search-closeButton-textColor,
|
||||
var(--bolt-elements-item-contentDefault)
|
||||
);
|
||||
|
||||
--cm-search-closeButton-textColorHover: var(
|
||||
--bolt-elements-editor-search-closeButton-textColorHover,
|
||||
var(--bolt-elements-item-contentActive)
|
||||
);
|
||||
|
||||
--cm-search-button-backgroundColor: var(
|
||||
--bolt-elements-editor-search-button-backgroundColor,
|
||||
var(--bolt-elements-item-backgroundDefault)
|
||||
);
|
||||
|
||||
--cm-search-button-backgroundColorHover: var(
|
||||
--bolt-elements-editor-search-button-backgroundColorHover,
|
||||
var(--bolt-elements-item-backgroundActive)
|
||||
);
|
||||
|
||||
--cm-search-button-textColor: var(--bolt-elements-editor-search-button-textColor, var(--bolt-elements-textSecondary));
|
||||
|
||||
--cm-search-button-textColorHover: var(
|
||||
--bolt-elements-editor-search-button-textColorHover,
|
||||
var(--bolt-elements-textPrimary)
|
||||
);
|
||||
|
||||
--cm-search-button-borderColor: var(--bolt-elements-editor-search-button-borderColor, transparent);
|
||||
--cm-search-button-borderColorHover: var(--bolt-elements-editor-search-button-borderColorHover, transparent);
|
||||
|
||||
--cm-search-button-borderColorFocused: var(
|
||||
--bolt-elements-editor-search-button-borderColorFocused,
|
||||
var(--bolt-elements-borderColorActive)
|
||||
);
|
||||
|
||||
--cm-search-input-backgroundColor: var(--bolt-elements-editor-search-input-backgroundColor, transparent);
|
||||
--cm-search-input-textColor: var(--bolt-elements-editor-search-input-textColor, var(--bolt-elements-textPrimary));
|
||||
--cm-search-input-borderColor: var(--bolt-elements-editor-search-input-borderColor, var(--bolt-elements-borderColor));
|
||||
|
||||
--cm-search-input-borderColorFocused: var(
|
||||
--bolt-elements-editor-search-input-borderColorFocused,
|
||||
var(--bolt-elements-borderColorActive)
|
||||
);
|
||||
|
||||
/* Tooltip */
|
||||
|
||||
--cm-tooltip-backgroundColor: var(--bolt-elements-editor-tooltip-backgroundColor, var(--cm-backgroundColor));
|
||||
--cm-tooltip-textColor: var(--bolt-elements-editor-tooltip-textColor, var(--bolt-elements-textPrimary));
|
||||
|
||||
--cm-tooltip-backgroundColorSelected: var(
|
||||
--bolt-elements-editor-tooltip-backgroundColorSelected,
|
||||
theme('colors.alpha.accent.30')
|
||||
);
|
||||
|
||||
--cm-tooltip-textColorSelected: var(
|
||||
--bolt-elements-editor-tooltip-textColorSelected,
|
||||
var(--bolt-elements-textPrimary)
|
||||
);
|
||||
|
||||
--cm-tooltip-borderColor: var(--bolt-elements-editor-tooltip-borderColor, var(--bolt-elements-borderColor));
|
||||
|
||||
--cm-searchMatch-backgroundColor: var(--bolt-elements-editor-searchMatch-backgroundColor, rgba(234, 92, 0, 0.33));
|
||||
}
|
||||
|
||||
html[data-theme='light'] {
|
||||
--bolt-elements-editor-gutter-textColor: #237893;
|
||||
--bolt-elements-editor-gutter-activeLineTextColor: var(--bolt-elements-textPrimary);
|
||||
--bolt-elements-editor-foldGutter-textColorHover: var(--bolt-elements-textPrimary);
|
||||
--bolt-elements-editor-activeLineBackgroundColor: rgb(50 53 63 / 5%);
|
||||
--bolt-elements-editor-tooltip-backgroundColorSelected: theme('colors.alpha.accent.20');
|
||||
--bolt-elements-editor-search-button-backgroundColor: theme('colors.gray.100');
|
||||
--bolt-elements-editor-search-button-backgroundColorHover: theme('colors.alpha.gray.10');
|
||||
}
|
||||
|
||||
html[data-theme='dark'] {
|
||||
--cm-backgroundColor: var(--bolt-elements-bg-depth-2);
|
||||
--bolt-elements-editor-gutter-textColor: var(--bolt-elements-textTertiary);
|
||||
--bolt-elements-editor-gutter-activeLineTextColor: var(--bolt-elements-textSecondary);
|
||||
--bolt-elements-editor-selection-inactiveBackgroundOpacity: 0.3;
|
||||
--bolt-elements-editor-activeLineBackgroundColor: rgb(50 53 63 / 50%);
|
||||
--bolt-elements-editor-foldGutter-textColorHover: var(--bolt-elements-textPrimary);
|
||||
--bolt-elements-editor-matchingBracketBackgroundColor: rgba(66, 180, 255, 0.3);
|
||||
--bolt-elements-editor-search-button-backgroundColor: theme('colors.gray.800');
|
||||
--bolt-elements-editor-search-button-backgroundColorHover: theme('colors.alpha.white.10');
|
||||
}
|
||||
28
app/styles/components/resize-handle.scss
Normal file
28
app/styles/components/resize-handle.scss
Normal file
@@ -0,0 +1,28 @@
|
||||
[data-resize-handle] {
|
||||
position: relative;
|
||||
|
||||
&[data-panel-group-direction='horizontal']:after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: -6px;
|
||||
right: -5px;
|
||||
z-index: $zIndexMax;
|
||||
}
|
||||
|
||||
&[data-panel-group-direction='vertical']:after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: -5px;
|
||||
bottom: -6px;
|
||||
z-index: $zIndexMax;
|
||||
}
|
||||
|
||||
&[data-resize-handle-state='hover']:after,
|
||||
&[data-resize-handle-state='drag']:after {
|
||||
background-color: #8882;
|
||||
}
|
||||
}
|
||||
3
app/styles/components/terminal.scss
Normal file
3
app/styles/components/terminal.scss
Normal file
@@ -0,0 +1,3 @@
|
||||
.xterm {
|
||||
padding: 1rem;
|
||||
}
|
||||
17
app/styles/components/toast.scss
Normal file
17
app/styles/components/toast.scss
Normal file
@@ -0,0 +1,17 @@
|
||||
.Toastify__toast {
|
||||
--at-apply: shadow-md;
|
||||
|
||||
background-color: var(--bolt-elements-bg-depth-2);
|
||||
color: var(--bolt-elements-textPrimary);
|
||||
border: 1px solid var(--bolt-elements-borderColor);
|
||||
}
|
||||
|
||||
.Toastify__close-button {
|
||||
color: var(--bolt-elements-item-contentDefault);
|
||||
opacity: 1;
|
||||
transition: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--bolt-elements-item-contentActive);
|
||||
}
|
||||
}
|
||||
14
app/styles/index.scss
Normal file
14
app/styles/index.scss
Normal file
@@ -0,0 +1,14 @@
|
||||
@import './variables.scss';
|
||||
@import './z-index.scss';
|
||||
@import './animations.scss';
|
||||
@import './components/terminal.scss';
|
||||
@import './components/resize-handle.scss';
|
||||
@import './components/code.scss';
|
||||
@import './components/editor.scss';
|
||||
@import './components/toast.scss';
|
||||
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
251
app/styles/variables.scss
Normal file
251
app/styles/variables.scss
Normal file
@@ -0,0 +1,251 @@
|
||||
/* Color Tokens Light Theme */
|
||||
:root,
|
||||
:root[data-theme='light'] {
|
||||
--bolt-elements-borderColor: theme('colors.alpha.gray.10');
|
||||
--bolt-elements-borderColorActive: theme('colors.accent.600');
|
||||
|
||||
--bolt-elements-bg-depth-1: theme('colors.white');
|
||||
--bolt-elements-bg-depth-2: theme('colors.gray.50');
|
||||
--bolt-elements-bg-depth-3: theme('colors.gray.200');
|
||||
--bolt-elements-bg-depth-4: theme('colors.alpha.gray.5');
|
||||
|
||||
--bolt-elements-textPrimary: theme('colors.gray.950');
|
||||
--bolt-elements-textSecondary: theme('colors.gray.600');
|
||||
--bolt-elements-textTertiary: theme('colors.gray.500');
|
||||
|
||||
--bolt-elements-code-background: theme('colors.gray.100');
|
||||
--bolt-elements-code-text: theme('colors.gray.950');
|
||||
|
||||
--bolt-elements-button-primary-background: theme('colors.alpha.accent.10');
|
||||
--bolt-elements-button-primary-backgroundHover: theme('colors.alpha.accent.20');
|
||||
--bolt-elements-button-primary-text: theme('colors.accent.500');
|
||||
|
||||
--bolt-elements-button-secondary-background: theme('colors.alpha.gray.5');
|
||||
--bolt-elements-button-secondary-backgroundHover: theme('colors.alpha.gray.10');
|
||||
--bolt-elements-button-secondary-text: theme('colors.gray.950');
|
||||
|
||||
--bolt-elements-button-danger-background: theme('colors.alpha.red.10');
|
||||
--bolt-elements-button-danger-backgroundHover: theme('colors.alpha.red.20');
|
||||
--bolt-elements-button-danger-text: theme('colors.red.500');
|
||||
|
||||
--bolt-elements-item-contentDefault: theme('colors.alpha.gray.50');
|
||||
--bolt-elements-item-contentActive: theme('colors.gray.950');
|
||||
--bolt-elements-item-contentAccent: theme('colors.accent.700');
|
||||
--bolt-elements-item-contentDanger: theme('colors.red.500');
|
||||
--bolt-elements-item-backgroundDefault: rgba(0, 0, 0, 0);
|
||||
--bolt-elements-item-backgroundActive: theme('colors.alpha.gray.5');
|
||||
--bolt-elements-item-backgroundAccent: theme('colors.alpha.accent.10');
|
||||
--bolt-elements-item-backgroundDanger: theme('colors.alpha.red.10');
|
||||
|
||||
--bolt-elements-loader-background: theme('colors.alpha.gray.10');
|
||||
--bolt-elements-loader-progress: theme('colors.accent.500');
|
||||
|
||||
--bolt-elements-artifacts-background: theme('colors.white');
|
||||
--bolt-elements-artifacts-backgroundHover: theme('colors.alpha.gray.2');
|
||||
--bolt-elements-artifacts-borderColor: var(--bolt-elements-borderColor);
|
||||
--bolt-elements-artifacts-inlineCode-background: theme('colors.gray.100');
|
||||
--bolt-elements-artifacts-inlineCode-text: var(--bolt-elements-textPrimary);
|
||||
|
||||
--bolt-elements-actions-background: theme('colors.white');
|
||||
--bolt-elements-actions-code-background: theme('colors.gray.800');
|
||||
|
||||
--bolt-elements-messages-background: theme('colors.gray.100');
|
||||
--bolt-elements-messages-linkColor: theme('colors.accent.500');
|
||||
--bolt-elements-messages-code-background: theme('colors.gray.800');
|
||||
--bolt-elements-messages-inlineCode-background: theme('colors.gray.200');
|
||||
--bolt-elements-messages-inlineCode-text: theme('colors.gray.800');
|
||||
|
||||
--bolt-elements-icon-success: theme('colors.green.500');
|
||||
--bolt-elements-icon-error: theme('colors.red.500');
|
||||
--bolt-elements-icon-primary: theme('colors.gray.950');
|
||||
--bolt-elements-icon-secondary: theme('colors.gray.600');
|
||||
--bolt-elements-icon-tertiary: theme('colors.gray.500');
|
||||
|
||||
--bolt-elements-dividerColor: theme('colors.gray.100');
|
||||
|
||||
--bolt-elements-prompt-background: theme('colors.alpha.white.80');
|
||||
|
||||
--bolt-elements-sidebar-dropdownShadow: theme('colors.alpha.gray.10');
|
||||
--bolt-elements-sidebar-buttonBackgroundDefault: theme('colors.alpha.accent.10');
|
||||
--bolt-elements-sidebar-buttonBackgroundHover: theme('colors.alpha.accent.20');
|
||||
--bolt-elements-sidebar-buttonText: theme('colors.accent.700');
|
||||
|
||||
--bolt-elements-preview-addressBar-background: theme('colors.gray.100');
|
||||
--bolt-elements-preview-addressBar-backgroundHover: theme('colors.alpha.gray.5');
|
||||
--bolt-elements-preview-addressBar-backgroundActive: theme('colors.white');
|
||||
--bolt-elements-preview-addressBar-text: var(--bolt-elements-textSecondary);
|
||||
--bolt-elements-preview-addressBar-textActive: var(--bolt-elements-textPrimary);
|
||||
|
||||
--bolt-elements-terminals-background: theme('colors.white');
|
||||
--bolt-elements-terminals-buttonBackground: var(--bolt-elements-bg-depth-4);
|
||||
|
||||
--bolt-elements-cta-background: theme('colors.gray.100');
|
||||
--bolt-elements-cta-text: theme('colors.gray.950');
|
||||
|
||||
/* Terminal Colors */
|
||||
--bolt-terminal-background: var(--bolt-elements-terminals-background);
|
||||
--bolt-terminal-foreground: #333333;
|
||||
--bolt-terminal-selection-background: #00000040;
|
||||
--bolt-terminal-black: #000000;
|
||||
--bolt-terminal-red: #cd3131;
|
||||
--bolt-terminal-green: #00bc00;
|
||||
--bolt-terminal-yellow: #949800;
|
||||
--bolt-terminal-blue: #0451a5;
|
||||
--bolt-terminal-magenta: #bc05bc;
|
||||
--bolt-terminal-cyan: #0598bc;
|
||||
--bolt-terminal-white: #555555;
|
||||
--bolt-terminal-brightBlack: #686868;
|
||||
--bolt-terminal-brightRed: #cd3131;
|
||||
--bolt-terminal-brightGreen: #00bc00;
|
||||
--bolt-terminal-brightYellow: #949800;
|
||||
--bolt-terminal-brightBlue: #0451a5;
|
||||
--bolt-terminal-brightMagenta: #bc05bc;
|
||||
--bolt-terminal-brightCyan: #0598bc;
|
||||
--bolt-terminal-brightWhite: #a5a5a5;
|
||||
}
|
||||
|
||||
/* Color Tokens Dark Theme */
|
||||
:root,
|
||||
:root[data-theme='dark'] {
|
||||
--bolt-elements-borderColor: theme('colors.alpha.white.10');
|
||||
--bolt-elements-borderColorActive: theme('colors.accent.500');
|
||||
|
||||
--bolt-elements-bg-depth-1: theme('colors.gray.950');
|
||||
--bolt-elements-bg-depth-2: theme('colors.gray.900');
|
||||
--bolt-elements-bg-depth-3: theme('colors.gray.800');
|
||||
--bolt-elements-bg-depth-4: theme('colors.alpha.white.5');
|
||||
|
||||
--bolt-elements-textPrimary: theme('colors.white');
|
||||
--bolt-elements-textSecondary: theme('colors.gray.400');
|
||||
--bolt-elements-textTertiary: theme('colors.gray.500');
|
||||
|
||||
--bolt-elements-code-background: theme('colors.gray.800');
|
||||
--bolt-elements-code-text: theme('colors.white');
|
||||
|
||||
--bolt-elements-button-primary-background: theme('colors.alpha.accent.10');
|
||||
--bolt-elements-button-primary-backgroundHover: theme('colors.alpha.accent.20');
|
||||
--bolt-elements-button-primary-text: theme('colors.accent.500');
|
||||
|
||||
--bolt-elements-button-secondary-background: theme('colors.alpha.white.5');
|
||||
--bolt-elements-button-secondary-backgroundHover: theme('colors.alpha.white.10');
|
||||
--bolt-elements-button-secondary-text: theme('colors.white');
|
||||
|
||||
--bolt-elements-button-danger-background: theme('colors.alpha.red.10');
|
||||
--bolt-elements-button-danger-backgroundHover: theme('colors.alpha.red.20');
|
||||
--bolt-elements-button-danger-text: theme('colors.red.500');
|
||||
|
||||
--bolt-elements-item-contentDefault: theme('colors.alpha.white.50');
|
||||
--bolt-elements-item-contentActive: theme('colors.white');
|
||||
--bolt-elements-item-contentAccent: theme('colors.accent.500');
|
||||
--bolt-elements-item-contentDanger: theme('colors.red.500');
|
||||
--bolt-elements-item-backgroundDefault: rgba(255, 255, 255, 0);
|
||||
--bolt-elements-item-backgroundActive: theme('colors.alpha.white.10');
|
||||
--bolt-elements-item-backgroundAccent: theme('colors.alpha.accent.10');
|
||||
--bolt-elements-item-backgroundDanger: theme('colors.alpha.red.10');
|
||||
|
||||
--bolt-elements-loader-background: theme('colors.alpha.gray.10');
|
||||
--bolt-elements-loader-progress: theme('colors.accent.500');
|
||||
|
||||
--bolt-elements-artifacts-background: theme('colors.gray.900');
|
||||
--bolt-elements-artifacts-backgroundHover: theme('colors.alpha.white.5');
|
||||
--bolt-elements-artifacts-borderColor: var(--bolt-elements-borderColor);
|
||||
--bolt-elements-artifacts-inlineCode-background: theme('colors.gray.800');
|
||||
--bolt-elements-artifacts-inlineCode-text: theme('colors.white');
|
||||
|
||||
--bolt-elements-actions-background: theme('colors.gray.900');
|
||||
--bolt-elements-actions-code-background: theme('colors.gray.800');
|
||||
|
||||
--bolt-elements-messages-background: theme('colors.gray.800');
|
||||
--bolt-elements-messages-linkColor: theme('colors.accent.500');
|
||||
--bolt-elements-messages-code-background: theme('colors.gray.900');
|
||||
--bolt-elements-messages-inlineCode-background: theme('colors.gray.700');
|
||||
--bolt-elements-messages-inlineCode-text: var(--bolt-elements-textPrimary);
|
||||
|
||||
--bolt-elements-icon-success: theme('colors.green.400');
|
||||
--bolt-elements-icon-error: theme('colors.red.400');
|
||||
--bolt-elements-icon-primary: theme('colors.gray.950');
|
||||
--bolt-elements-icon-secondary: theme('colors.gray.600');
|
||||
--bolt-elements-icon-tertiary: theme('colors.gray.500');
|
||||
|
||||
--bolt-elements-dividerColor: theme('colors.gray.100');
|
||||
|
||||
--bolt-elements-prompt-background: theme('colors.alpha.gray.80');
|
||||
|
||||
--bolt-elements-sidebar-dropdownShadow: theme('colors.alpha.gray.30');
|
||||
--bolt-elements-sidebar-buttonBackgroundDefault: theme('colors.alpha.accent.10');
|
||||
--bolt-elements-sidebar-buttonBackgroundHover: theme('colors.alpha.accent.20');
|
||||
--bolt-elements-sidebar-buttonText: theme('colors.accent.500');
|
||||
|
||||
--bolt-elements-preview-addressBar-background: var(--bolt-elements-bg-depth-1);
|
||||
--bolt-elements-preview-addressBar-backgroundHover: theme('colors.alpha.white.5');
|
||||
--bolt-elements-preview-addressBar-backgroundActive: var(--bolt-elements-bg-depth-1);
|
||||
--bolt-elements-preview-addressBar-text: var(--bolt-elements-textSecondary);
|
||||
--bolt-elements-preview-addressBar-textActive: var(--bolt-elements-textPrimary);
|
||||
|
||||
--bolt-elements-terminals-background: var(--bolt-elements-bg-depth-1);
|
||||
--bolt-elements-terminals-buttonBackground: var(--bolt-elements-bg-depth-3);
|
||||
|
||||
--bolt-elements-cta-background: theme('colors.alpha.white.10');
|
||||
--bolt-elements-cta-text: theme('colors.white');
|
||||
|
||||
/* Terminal Colors */
|
||||
--bolt-terminal-background: var(--bolt-elements-terminals-background);
|
||||
--bolt-terminal-foreground: #eff0eb;
|
||||
--bolt-terminal-selection-background: #97979b33;
|
||||
--bolt-terminal-black: #000000;
|
||||
--bolt-terminal-red: #ff5c57;
|
||||
--bolt-terminal-green: #5af78e;
|
||||
--bolt-terminal-yellow: #f3f99d;
|
||||
--bolt-terminal-blue: #57c7ff;
|
||||
--bolt-terminal-magenta: #ff6ac1;
|
||||
--bolt-terminal-cyan: #9aedfe;
|
||||
--bolt-terminal-white: #f1f1f0;
|
||||
--bolt-terminal-brightBlack: #686868;
|
||||
--bolt-terminal-brightRed: #ff5c57;
|
||||
--bolt-terminal-brightGreen: #5af78e;
|
||||
--bolt-terminal-brightYellow: #f3f99d;
|
||||
--bolt-terminal-brightBlue: #57c7ff;
|
||||
--bolt-terminal-brightMagenta: #ff6ac1;
|
||||
--bolt-terminal-brightCyan: #9aedfe;
|
||||
--bolt-terminal-brightWhite: #f1f1f0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Element Tokens
|
||||
*
|
||||
* Hierarchy: Element Token -> (Element Token | Color Tokens) -> Primitives
|
||||
*/
|
||||
:root {
|
||||
--header-height: 54px;
|
||||
--chat-max-width: 37rem;
|
||||
--chat-min-width: 640px;
|
||||
--workbench-width: min(calc(100% - var(--chat-min-width)), 1536px);
|
||||
--workbench-inner-width: var(--workbench-width);
|
||||
--workbench-left: calc(100% - var(--workbench-width));
|
||||
|
||||
/* Toasts */
|
||||
--toastify-color-progress-success: var(--bolt-elements-icon-success);
|
||||
--toastify-color-progress-error: var(--bolt-elements-icon-error);
|
||||
|
||||
/* Terminal */
|
||||
--bolt-elements-terminal-backgroundColor: var(--bolt-terminal-background);
|
||||
--bolt-elements-terminal-textColor: var(--bolt-terminal-foreground);
|
||||
--bolt-elements-terminal-cursorColor: var(--bolt-terminal-foreground);
|
||||
--bolt-elements-terminal-selection-backgroundColor: var(--bolt-terminal-selection-background);
|
||||
--bolt-elements-terminal-color-black: var(--bolt-terminal-black);
|
||||
--bolt-elements-terminal-color-red: var(--bolt-terminal-red);
|
||||
--bolt-elements-terminal-color-green: var(--bolt-terminal-green);
|
||||
--bolt-elements-terminal-color-yellow: var(--bolt-terminal-yellow);
|
||||
--bolt-elements-terminal-color-blue: var(--bolt-terminal-blue);
|
||||
--bolt-elements-terminal-color-magenta: var(--bolt-terminal-magenta);
|
||||
--bolt-elements-terminal-color-cyan: var(--bolt-terminal-cyan);
|
||||
--bolt-elements-terminal-color-white: var(--bolt-terminal-white);
|
||||
--bolt-elements-terminal-color-brightBlack: var(--bolt-terminal-brightBlack);
|
||||
--bolt-elements-terminal-color-brightRed: var(--bolt-terminal-brightRed);
|
||||
--bolt-elements-terminal-color-brightGreen: var(--bolt-terminal-brightGreen);
|
||||
--bolt-elements-terminal-color-brightYellow: var(--bolt-terminal-brightYellow);
|
||||
--bolt-elements-terminal-color-brightBlue: var(--bolt-terminal-brightBlue);
|
||||
--bolt-elements-terminal-color-brightMagenta: var(--bolt-terminal-brightMagenta);
|
||||
--bolt-elements-terminal-color-brightCyan: var(--bolt-terminal-brightCyan);
|
||||
--bolt-elements-terminal-color-brightWhite: var(--bolt-terminal-brightWhite);
|
||||
}
|
||||
33
app/styles/z-index.scss
Normal file
33
app/styles/z-index.scss
Normal file
@@ -0,0 +1,33 @@
|
||||
$zIndexMax: 999;
|
||||
|
||||
.z-logo {
|
||||
z-index: $zIndexMax - 1;
|
||||
}
|
||||
|
||||
.z-sidebar {
|
||||
z-index: $zIndexMax - 2;
|
||||
}
|
||||
|
||||
.z-port-dropdown {
|
||||
z-index: $zIndexMax - 3;
|
||||
}
|
||||
|
||||
.z-iframe-overlay {
|
||||
z-index: $zIndexMax - 4;
|
||||
}
|
||||
|
||||
.z-prompt {
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.z-workbench {
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.z-file-tree-breadcrumb {
|
||||
z-index: $zIndexMax - 1;
|
||||
}
|
||||
|
||||
.z-max {
|
||||
z-index: $zIndexMax;
|
||||
}
|
||||
18
app/types/actions.ts
Normal file
18
app/types/actions.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export type ActionType = 'file' | 'shell';
|
||||
|
||||
export interface BaseAction {
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface FileAction extends BaseAction {
|
||||
type: 'file';
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
export interface ShellAction extends BaseAction {
|
||||
type: 'shell';
|
||||
}
|
||||
|
||||
export type BoltAction = FileAction | ShellAction;
|
||||
|
||||
export type BoltActionData = BoltAction | BaseAction;
|
||||
4
app/types/artifact.ts
Normal file
4
app/types/artifact.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export interface BoltArtifactData {
|
||||
id: string;
|
||||
title: string;
|
||||
}
|
||||
8
app/types/terminal.ts
Normal file
8
app/types/terminal.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export interface ITerminal {
|
||||
readonly cols?: number;
|
||||
readonly rows?: number;
|
||||
|
||||
reset: () => void;
|
||||
write: (data: string) => void;
|
||||
onData: (cb: (data: string) => void) => void;
|
||||
}
|
||||
1
app/types/theme.ts
Normal file
1
app/types/theme.ts
Normal file
@@ -0,0 +1 @@
|
||||
export type Theme = 'dark' | 'light';
|
||||
29
app/utils/buffer.ts
Normal file
29
app/utils/buffer.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export function bufferWatchEvents<T extends unknown[]>(timeInMs: number, cb: (events: T[]) => unknown) {
|
||||
let timeoutId: number | undefined;
|
||||
let events: T[] = [];
|
||||
|
||||
// keep track of the processing of the previous batch so we can wait for it
|
||||
let processing: Promise<unknown> = Promise.resolve();
|
||||
|
||||
const scheduleBufferTick = () => {
|
||||
timeoutId = self.setTimeout(async () => {
|
||||
// we wait until the previous batch is entirely processed so events are processed in order
|
||||
await processing;
|
||||
|
||||
if (events.length > 0) {
|
||||
processing = Promise.resolve(cb(events));
|
||||
}
|
||||
|
||||
timeoutId = undefined;
|
||||
events = [];
|
||||
}, timeInMs);
|
||||
};
|
||||
|
||||
return (...args: T) => {
|
||||
events.push(args);
|
||||
|
||||
if (!timeoutId) {
|
||||
scheduleBufferTick();
|
||||
}
|
||||
};
|
||||
}
|
||||
61
app/utils/classNames.ts
Normal file
61
app/utils/classNames.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Copyright (c) 2018 Jed Watson.
|
||||
* Licensed under the MIT License (MIT), see:
|
||||
*
|
||||
* @link http://jedwatson.github.io/classnames
|
||||
*/
|
||||
|
||||
type ClassNamesArg = undefined | string | Record<string, boolean> | ClassNamesArg[];
|
||||
|
||||
/**
|
||||
* A simple JavaScript utility for conditionally joining classNames together.
|
||||
*
|
||||
* @param args A series of classes or object with key that are class and values
|
||||
* that are interpreted as boolean to decide whether or not the class
|
||||
* should be included in the final class.
|
||||
*/
|
||||
export function classNames(...args: ClassNamesArg[]): string {
|
||||
let classes = '';
|
||||
|
||||
for (const arg of args) {
|
||||
classes = appendClass(classes, parseValue(arg));
|
||||
}
|
||||
|
||||
return classes;
|
||||
}
|
||||
|
||||
function parseValue(arg: ClassNamesArg) {
|
||||
if (typeof arg === 'string' || typeof arg === 'number') {
|
||||
return arg;
|
||||
}
|
||||
|
||||
if (typeof arg !== 'object') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (Array.isArray(arg)) {
|
||||
return classNames(...arg);
|
||||
}
|
||||
|
||||
let classes = '';
|
||||
|
||||
for (const key in arg) {
|
||||
if (arg[key]) {
|
||||
classes = appendClass(classes, key);
|
||||
}
|
||||
}
|
||||
|
||||
return classes;
|
||||
}
|
||||
|
||||
function appendClass(value: string, newClass: string | undefined) {
|
||||
if (!newClass) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (value) {
|
||||
return value + ' ' + newClass;
|
||||
}
|
||||
|
||||
return value + newClass;
|
||||
}
|
||||
3
app/utils/constants.ts
Normal file
3
app/utils/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const WORK_DIR_NAME = 'project';
|
||||
export const WORK_DIR = `/home/${WORK_DIR_NAME}`;
|
||||
export const MODIFICATIONS_TAG_NAME = 'bolt_file_modifications';
|
||||
17
app/utils/debounce.ts
Normal file
17
app/utils/debounce.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
export function debounce<Args extends any[]>(fn: (...args: Args) => void, delay = 100) {
|
||||
if (delay === 0) {
|
||||
return fn;
|
||||
}
|
||||
|
||||
let timer: number | undefined;
|
||||
|
||||
return function <U>(this: U, ...args: Args) {
|
||||
const context = this;
|
||||
|
||||
clearTimeout(timer);
|
||||
|
||||
timer = window.setTimeout(() => {
|
||||
fn.apply(context, args);
|
||||
}, delay);
|
||||
};
|
||||
}
|
||||
108
app/utils/diff.ts
Normal file
108
app/utils/diff.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { createTwoFilesPatch } from 'diff';
|
||||
import type { FileMap } from '~/lib/stores/files';
|
||||
import { MODIFICATIONS_TAG_NAME } from './constants';
|
||||
|
||||
export const modificationsRegex = new RegExp(
|
||||
`^<${MODIFICATIONS_TAG_NAME}>[\\s\\S]*?<\\/${MODIFICATIONS_TAG_NAME}>\\s+`,
|
||||
'g',
|
||||
);
|
||||
|
||||
interface ModifiedFile {
|
||||
type: 'diff' | 'file';
|
||||
content: string;
|
||||
}
|
||||
|
||||
type FileModifications = Record<string, ModifiedFile>;
|
||||
|
||||
export function computeFileModifications(files: FileMap, modifiedFiles: Map<string, string>) {
|
||||
const modifications: FileModifications = {};
|
||||
|
||||
let hasModifiedFiles = false;
|
||||
|
||||
for (const [filePath, originalContent] of modifiedFiles) {
|
||||
const file = files[filePath];
|
||||
|
||||
if (file?.type !== 'file') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const unifiedDiff = diffFiles(filePath, originalContent, file.content);
|
||||
|
||||
if (!unifiedDiff) {
|
||||
// files are identical
|
||||
continue;
|
||||
}
|
||||
|
||||
hasModifiedFiles = true;
|
||||
|
||||
if (unifiedDiff.length > file.content.length) {
|
||||
// if there are lots of changes we simply grab the current file content since it's smaller than the diff
|
||||
modifications[filePath] = { type: 'file', content: file.content };
|
||||
} else {
|
||||
// otherwise we use the diff since it's smaller
|
||||
modifications[filePath] = { type: 'diff', content: unifiedDiff };
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasModifiedFiles) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return modifications;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a diff in the unified format. The only difference is that the header is omitted
|
||||
* because it will always assume that you're comparing two versions of the same file and
|
||||
* it allows us to avoid the extra characters we send back to the llm.
|
||||
*
|
||||
* @see https://www.gnu.org/software/diffutils/manual/html_node/Unified-Format.html
|
||||
*/
|
||||
export function diffFiles(fileName: string, oldFileContent: string, newFileContent: string) {
|
||||
let unifiedDiff = createTwoFilesPatch(fileName, fileName, oldFileContent, newFileContent);
|
||||
|
||||
const patchHeaderEnd = `--- ${fileName}\n+++ ${fileName}\n`;
|
||||
const headerEndIndex = unifiedDiff.indexOf(patchHeaderEnd);
|
||||
|
||||
if (headerEndIndex >= 0) {
|
||||
unifiedDiff = unifiedDiff.slice(headerEndIndex + patchHeaderEnd.length);
|
||||
}
|
||||
|
||||
if (unifiedDiff === '') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return unifiedDiff;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the unified diff to HTML.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```html
|
||||
* <bolt_file_modifications>
|
||||
* <diff path="/home/project/index.js">
|
||||
* - console.log('Hello, World!');
|
||||
* + console.log('Hello, Bolt!');
|
||||
* </diff>
|
||||
* </bolt_file_modifications>
|
||||
* ```
|
||||
*/
|
||||
export function fileModificationsToHTML(modifications: FileModifications) {
|
||||
const entries = Object.entries(modifications);
|
||||
|
||||
if (entries.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const result: string[] = [`<${MODIFICATIONS_TAG_NAME}>`];
|
||||
|
||||
for (const [filePath, { type, content }] of entries) {
|
||||
result.push(`<${type} path=${JSON.stringify(filePath)}>`, content, `</${type}>`);
|
||||
}
|
||||
|
||||
result.push(`</${MODIFICATIONS_TAG_NAME}>`);
|
||||
|
||||
return result.join('\n');
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user