index int64 0 0 | repo_id stringclasses 596 values | file_path stringlengths 31 168 | content stringlengths 1 6.2M |
|---|---|---|---|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/canvas/canvas.tsx | "use client";
import { ArtifactRenderer } from "@/components/artifacts/ArtifactRenderer";
import { ContentComposerChatInterface } from "./content-composer";
import { ALL_MODEL_NAMES } from "@/constants";
import { useToast } from "@/hooks/use-toast";
import { getLanguageTemplate } from "@/lib/get_language_template";
import { cn } from "@/lib/utils";
import {
ArtifactCodeV3,
ArtifactMarkdownV3,
ArtifactV3,
ProgrammingLanguageOptions,
} from "@/types";
import { useEffect, useState } from "react";
import { useGraphContext } from "@/contexts/GraphContext";
import React from "react";
export function CanvasComponent() {
const { threadData, graphData, userData } = useGraphContext();
const { user } = userData;
const { threadId, clearThreadsWithNoValues, setModelName } = threadData;
const { setArtifact } = graphData;
const { toast } = useToast();
const [chatStarted, setChatStarted] = useState(false);
const [isEditing, setIsEditing] = useState(false);
useEffect(() => {
if (!threadId || !user) return;
// Clear threads with no values
clearThreadsWithNoValues(user.id);
}, [threadId, user]);
const handleQuickStart = (
type: "text" | "code",
language?: ProgrammingLanguageOptions
) => {
if (type === "code" && !language) {
toast({
title: "Language not selected",
description: "Please select a language to continue",
duration: 5000,
});
return;
}
setChatStarted(true);
let artifactContent: ArtifactCodeV3 | ArtifactMarkdownV3;
if (type === "code" && language) {
artifactContent = {
index: 1,
type: "code",
title: `Quick start ${type}`,
code: getLanguageTemplate(language),
language,
};
} else {
artifactContent = {
index: 1,
type: "text",
title: `Quick start ${type}`,
fullMarkdown: "",
};
}
const newArtifact: ArtifactV3 = {
currentIndex: 1,
contents: [artifactContent],
};
// Do not worry about existing items in state. This should
// never occur since this action can only be invoked if
// there are no messages/artifacts in the thread.
setArtifact(newArtifact);
setIsEditing(true);
};
return (
<main className="h-screen flex flex-row">
<div
className={cn(
"transition-all duration-700",
chatStarted ? "w-[35%]" : "w-full",
"h-full mr-auto bg-gray-50/70 shadow-inner-right"
)}
>
<ContentComposerChatInterface
switchSelectedThreadCallback={(thread) => {
// Chat should only be "started" if there are messages present
if ((thread.values as Record<string, any>)?.messages?.length) {
setChatStarted(true);
setModelName(
thread?.metadata?.customModelName as ALL_MODEL_NAMES
);
} else {
setChatStarted(false);
}
}}
setChatStarted={setChatStarted}
hasChatStarted={chatStarted}
handleQuickStart={handleQuickStart}
/>
</div>
{chatStarted && (
<div className="w-full ml-auto">
<ArtifactRenderer setIsEditing={setIsEditing} isEditing={isEditing} />
</div>
)}
</main>
);
}
export const Canvas = React.memo(CanvasComponent);
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/canvas/content-composer.tsx | "use client";
import { useToast } from "@/hooks/use-toast";
import {
convertLangchainMessages,
convertToOpenAIFormat,
} from "@/lib/convert_messages";
import { ProgrammingLanguageOptions } from "@/types";
import {
AppendMessage,
AssistantRuntimeProvider,
useExternalMessageConverter,
useExternalStoreRuntime,
} from "@assistant-ui/react";
import { BaseMessage, HumanMessage } from "@langchain/core/messages";
import { Thread as ThreadType } from "@langchain/langgraph-sdk";
import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { Toaster } from "../ui/toaster";
import { Thread } from "@/components/chat-interface";
import { useGraphContext } from "@/contexts/GraphContext";
export interface ContentComposerChatInterfaceProps {
switchSelectedThreadCallback: (thread: ThreadType) => void;
setChatStarted: React.Dispatch<React.SetStateAction<boolean>>;
hasChatStarted: boolean;
handleQuickStart: (
type: "text" | "code",
language?: ProgrammingLanguageOptions
) => void;
}
export function ContentComposerChatInterfaceComponent(
props: ContentComposerChatInterfaceProps
): React.ReactElement {
const { toast } = useToast();
const { userData, graphData, threadData } = useGraphContext();
const { messages, setMessages, streamMessage } = graphData;
const { getUserThreads } = threadData;
const [isRunning, setIsRunning] = useState(false);
async function onNew(message: AppendMessage): Promise<void> {
if (!userData.user) {
toast({
title: "User not found",
variant: "destructive",
duration: 5000,
});
return;
}
if (message.content?.[0]?.type !== "text") {
toast({
title: "Only text messages are supported",
variant: "destructive",
duration: 5000,
});
return;
}
props.setChatStarted(true);
setIsRunning(true);
try {
const humanMessage = new HumanMessage({
content: message.content[0].text,
id: uuidv4(),
});
setMessages((prevMessages) => [...prevMessages, humanMessage]);
await streamMessage({
messages: [convertToOpenAIFormat(humanMessage)],
});
} finally {
setIsRunning(false);
// Re-fetch threads so that the current thread's title is updated.
await getUserThreads(userData.user.id);
}
}
const threadMessages = useExternalMessageConverter<BaseMessage>({
callback: convertLangchainMessages,
messages: messages,
isRunning,
});
const runtime = useExternalStoreRuntime({
messages: threadMessages,
isRunning,
onNew,
});
return (
<div className="h-full">
<AssistantRuntimeProvider runtime={runtime}>
<Thread
userId={userData?.user?.id}
setChatStarted={props.setChatStarted}
handleQuickStart={props.handleQuickStart}
hasChatStarted={props.hasChatStarted}
switchSelectedThreadCallback={props.switchSelectedThreadCallback}
/>
</AssistantRuntimeProvider>
<Toaster />
</div>
);
}
export const ContentComposerChatInterface = React.memo(
ContentComposerChatInterfaceComponent
);
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/canvas/canavas-loading.tsx | import { Skeleton } from "../ui/skeleton";
export function CanvasLoading() {
return (
<>
<div className="hidden md:flex flex-col items-center w-full h-screen">
<div className="flex items-center justify-between w-full pt-4 px-4">
<div className="flex items-center">
<Skeleton className="w-[175px] h-7 rounded-md" />
</div>
<div className="flex items-center gap-2">
<Skeleton className="w-[80px] h-7 rounded-md" />
<Skeleton className="w-[40px] h-7 rounded-md" />
<Skeleton className="w-[40px] h-7 rounded-md" />
</div>
</div>
<div className="flex flex-col gap-2 items-center mx-auto mt-32">
<Skeleton className="w-12 h-12 rounded-full" />
<Skeleton className="w-[300px] h-7 rounded-md" />
</div>
<div className="flex w-full gap-2 items-center justify-center mt-auto mb-3">
<Skeleton className="w-[650px] h-12 rounded-md" />
<Skeleton className="w-[50px] h-12 rounded-md" />
</div>
</div>
<div className="flex md:hidden flex-col items-center w-full h-screen">
<div className="flex items-center justify-between w-full pt-4 px-4">
<div className="flex items-center">
<Skeleton className="w-[125px] h-7 rounded-md" />
</div>
<div className="flex items-center gap-2">
<Skeleton className="w-[60px] h-7 rounded-md" />
<Skeleton className="w-[30px] h-7 rounded-md" />
<Skeleton className="w-[30px] h-7 rounded-md" />
</div>
</div>
<div className="flex flex-col gap-2 items-center mx-auto mt-32">
<Skeleton className="w-12 h-12 rounded-full" />
<Skeleton className="w-[300px] h-7 rounded-md" />
</div>
<div className="flex w-full gap-2 items-center justify-center mt-auto mb-3">
<Skeleton className="w-[70%] h-12 rounded-md" />
<Skeleton className="w-[10%] h-12 rounded-md" />
</div>
</div>
</>
);
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/canvas/index.ts | export * from "./canvas";
export * from "./canavas-loading";
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/chat-interface/thread.tsx | import { ThreadPrimitive } from "@assistant-ui/react";
import { ArrowDownIcon, SquarePen } from "lucide-react";
import { Dispatch, FC, SetStateAction } from "react";
import { TooltipIconButton } from "../ui/assistant-ui/tooltip-icon-button";
import { ProgrammingLanguageOptions } from "@/types";
import ModelSelector from "./model-selector";
import { ReflectionsDialog } from "../reflections-dialog/ReflectionsDialog";
import { ThreadHistory } from "./thread-history";
import { TighterText } from "../ui/header";
import { Thread as ThreadType } from "@langchain/langgraph-sdk";
import { ThreadWelcome } from "./welcome";
import { Composer } from "./composer";
import { AssistantMessage, UserMessage } from "./messages";
import { useToast } from "@/hooks/use-toast";
import { useLangSmithLinkToolUI } from "../tool-hooks/LangSmithLinkToolUI";
import { useGraphContext } from "@/contexts/GraphContext";
const ThreadScrollToBottom: FC = () => {
return (
<ThreadPrimitive.ScrollToBottom asChild>
<TooltipIconButton
tooltip="Scroll to bottom"
variant="outline"
className="absolute -top-8 rounded-full disabled:invisible"
>
<ArrowDownIcon />
</TooltipIconButton>
</ThreadPrimitive.ScrollToBottom>
);
};
export interface ThreadProps {
userId: string | undefined;
hasChatStarted: boolean;
handleQuickStart: (
type: "text" | "code",
language?: ProgrammingLanguageOptions
) => void;
setChatStarted: Dispatch<SetStateAction<boolean>>;
switchSelectedThreadCallback: (thread: ThreadType) => void;
}
export const Thread: FC<ThreadProps> = (props: ThreadProps) => {
const {
setChatStarted,
hasChatStarted,
handleQuickStart,
switchSelectedThreadCallback,
} = props;
const { toast } = useToast();
const {
userData: { user },
threadData: { createThread, modelName, setModelName },
assistantsData: { selectedAssistant },
graphData: { clearState, runId, feedbackSubmitted, setFeedbackSubmitted },
} = useGraphContext();
useLangSmithLinkToolUI();
const handleCreateThread = async () => {
if (!user) {
toast({
title: "User not found",
description: "Failed to create thread without user",
duration: 5000,
variant: "destructive",
});
return;
}
setModelName(modelName);
clearState();
setChatStarted(false);
const thread = await createThread(modelName, user.id);
if (!thread) {
toast({
title: "Failed to create a new thread",
duration: 5000,
variant: "destructive",
});
}
};
return (
<ThreadPrimitive.Root className="flex flex-col h-full">
<div className="pr-3 pl-6 pt-3 pb-2 flex flex-row gap-4 items-center justify-between">
<div className="flex items-center justify-start gap-2 text-gray-600">
<ThreadHistory
switchSelectedThreadCallback={switchSelectedThreadCallback}
/>
<TighterText className="text-xl">Open Canvas</TighterText>
{!hasChatStarted && (
<ModelSelector
chatStarted={false}
modelName={modelName}
setModelName={setModelName}
/>
)}
</div>
{hasChatStarted ? (
<TooltipIconButton
tooltip="New chat"
variant="ghost"
className="w-fit h-fit p-2"
delayDuration={400}
onClick={handleCreateThread}
>
<SquarePen className="w-6 h-6 text-gray-600" />
</TooltipIconButton>
) : (
<div className="flex flex-row gap-2 items-center">
<ReflectionsDialog selectedAssistant={selectedAssistant} />
</div>
)}
</div>
<ThreadPrimitive.Viewport className="flex-1 overflow-y-auto scroll-smooth bg-inherit px-4 pt-8">
{!hasChatStarted && (
<ThreadWelcome
handleQuickStart={handleQuickStart}
composer={<Composer chatStarted={false} userId={props.userId} />}
/>
)}
<ThreadPrimitive.Messages
components={{
UserMessage: UserMessage,
AssistantMessage: (prop) => (
<AssistantMessage
{...prop}
feedbackSubmitted={feedbackSubmitted}
setFeedbackSubmitted={setFeedbackSubmitted}
runId={runId}
/>
),
}}
/>
</ThreadPrimitive.Viewport>
<div className="mt-4 flex w-full flex-col items-center justify-end rounded-t-lg bg-inherit pb-4 px-4">
<ThreadScrollToBottom />
<div className="w-full max-w-2xl">
{hasChatStarted && (
<div className="flex flex-col space-y-2">
<ModelSelector
chatStarted={true}
modelName={modelName}
setModelName={setModelName}
/>
<Composer chatStarted={true} userId={props.userId} />
</div>
)}
</div>
</div>
</ThreadPrimitive.Root>
);
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/chat-interface/welcome.tsx | import { ProgrammingLanguageOptions } from "@/types";
import { ThreadPrimitive, useThreadRuntime } from "@assistant-ui/react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { FC } from "react";
import { TighterText } from "../ui/header";
import { NotebookPen } from "lucide-react";
import { ProgrammingLanguagesDropdown } from "../ui/programming-lang-dropdown";
import { Button } from "../ui/button";
interface QuickStartButtonsProps {
handleQuickStart: (
type: "text" | "code",
language?: ProgrammingLanguageOptions
) => void;
composer: React.ReactNode;
}
const QuickStartPrompts = () => {
const threadRuntime = useThreadRuntime();
const handleClick = (text: string) => {
threadRuntime.append({
role: "user",
content: [{ type: "text", text }],
});
};
return (
<div className="flex flex-col w-full gap-2 text-gray-700">
<div className="flex gap-2 w-full">
<Button
onClick={(e) =>
handleClick((e.target as HTMLButtonElement).textContent || "")
}
variant="outline"
className="flex-1"
>
<TighterText>Write me a TODO app in React</TighterText>
</Button>
<Button
onClick={(e) =>
handleClick((e.target as HTMLButtonElement).textContent || "")
}
variant="outline"
className="flex-1"
>
<TighterText>
Explain why the sky is blue in a short essay
</TighterText>
</Button>
</div>
<div className="flex gap-2 w-full">
<Button
onClick={(e) =>
handleClick((e.target as HTMLButtonElement).textContent || "")
}
variant="outline"
className="flex-1"
>
<TighterText>
Help me draft an email to my professor Craig
</TighterText>
</Button>
<Button
onClick={(e) =>
handleClick((e.target as HTMLButtonElement).textContent || "")
}
variant="outline"
className="flex-1"
>
<TighterText>Write a web scraping program in Python</TighterText>
</Button>
</div>
</div>
);
};
const QuickStartButtons = (props: QuickStartButtonsProps) => {
const handleLanguageSubmit = (language: ProgrammingLanguageOptions) => {
props.handleQuickStart("code", language);
};
return (
<div className="flex flex-col gap-8 items-center justify-center w-full">
<div className="flex flex-col gap-6">
<p className="text-gray-600 text-sm">Start with a blank canvas</p>
<div className="flex flex-row gap-1 items-center justify-center w-full">
<Button
variant="outline"
className="transition-colors text-gray-600 flex items-center justify-center gap-2 w-[250px] h-[64px]"
onClick={() => props.handleQuickStart("text")}
>
<TighterText>New Markdown</TighterText>
<NotebookPen />
</Button>
<ProgrammingLanguagesDropdown handleSubmit={handleLanguageSubmit} />
</div>
</div>
<div className="flex flex-col gap-6 mt-2 w-full">
<p className="text-gray-600 text-sm">or with a message</p>
<QuickStartPrompts />
{props.composer}
</div>
</div>
);
};
interface ThreadWelcomeProps {
handleQuickStart: (
type: "text" | "code",
language?: ProgrammingLanguageOptions
) => void;
composer: React.ReactNode;
}
export const ThreadWelcome: FC<ThreadWelcomeProps> = (
props: ThreadWelcomeProps
) => {
return (
<ThreadPrimitive.Empty>
<div className="flex items-center justify-center mt-16 w-full">
<div className="text-center max-w-3xl w-full">
<Avatar className="mx-auto">
<AvatarImage src="/lc_logo.jpg" alt="LangChain Logo" />
<AvatarFallback>LC</AvatarFallback>
</Avatar>
<TighterText className="mt-4 text-lg font-medium">
What would you like to write today?
</TighterText>
<div className="mt-8 w-full">
<QuickStartButtons
composer={props.composer}
handleQuickStart={props.handleQuickStart}
/>
</div>
</div>
</div>
</ThreadPrimitive.Empty>
);
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/chat-interface/feedback.tsx | import { useToast } from "@/hooks/use-toast";
import { FeedbackResponse } from "@/hooks/useFeedback";
import { ThumbsUpIcon, ThumbsDownIcon } from "lucide-react";
import { Dispatch, FC, SetStateAction } from "react";
import { cn } from "@/lib/utils";
import { TooltipIconButton } from "../ui/assistant-ui/tooltip-icon-button";
interface FeedbackButtonProps {
runId: string;
setFeedbackSubmitted: Dispatch<SetStateAction<boolean>>;
sendFeedback: (
runId: string,
feedbackKey: string,
score: number,
comment?: string
) => Promise<FeedbackResponse | undefined>;
feedbackValue: number;
icon: "thumbs-up" | "thumbs-down";
isLoading: boolean;
}
export const FeedbackButton: FC<FeedbackButtonProps> = ({
runId,
setFeedbackSubmitted,
sendFeedback,
isLoading,
feedbackValue,
icon,
}) => {
const { toast } = useToast();
const handleClick = async () => {
try {
const res = await sendFeedback(runId, "feedback", feedbackValue);
if (res?.success) {
setFeedbackSubmitted(true);
} else {
toast({
title: "Failed to submit feedback",
description: "Please try again later.",
variant: "destructive",
});
}
} catch (_) {
toast({
title: "Failed to submit feedback",
description: "Please try again later.",
variant: "destructive",
});
}
};
const tooltip = `Give ${icon === "thumbs-up" ? "positive" : "negative"} feedback on this run`;
return (
<TooltipIconButton
variant="ghost"
size="icon"
onClick={handleClick}
aria-label={tooltip}
tooltip={tooltip}
disabled={isLoading}
>
{icon === "thumbs-up" ? (
<ThumbsUpIcon className={cn("size-4", isLoading && "text-gray-300")} />
) : (
<ThumbsDownIcon
className={cn("size-4", isLoading && "text-gray-300")}
/>
)}
</TooltipIconButton>
);
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/chat-interface/messages.tsx | "use client";
import {
ActionBarPrimitive,
MessagePrimitive,
useMessage,
} from "@assistant-ui/react";
import React, { Dispatch, SetStateAction, type FC } from "react";
import { MarkdownText } from "@/components/ui/assistant-ui/markdown-text";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { FeedbackButton } from "./feedback";
import { TighterText } from "../ui/header";
import { useFeedback } from "@/hooks/useFeedback";
interface AssistantMessageProps {
runId: string | undefined;
feedbackSubmitted: boolean;
setFeedbackSubmitted: Dispatch<SetStateAction<boolean>>;
}
export const AssistantMessage: FC<AssistantMessageProps> = ({
runId,
feedbackSubmitted,
setFeedbackSubmitted,
}) => {
const isLast = useMessage().isLast;
return (
<MessagePrimitive.Root className="relative grid w-full max-w-2xl grid-cols-[auto_auto_1fr] grid-rows-[auto_1fr] py-4">
<Avatar className="col-start-1 row-span-full row-start-1 mr-4">
<AvatarFallback>A</AvatarFallback>
</Avatar>
<div className="text-foreground col-span-2 col-start-2 row-start-1 my-1.5 max-w-xl break-words leading-7">
<MessagePrimitive.Content components={{ Text: MarkdownText }} />
{isLast && runId && (
<MessagePrimitive.If lastOrHover assistant>
<AssistantMessageBar
feedbackSubmitted={feedbackSubmitted}
setFeedbackSubmitted={setFeedbackSubmitted}
runId={runId}
/>
</MessagePrimitive.If>
)}
</div>
</MessagePrimitive.Root>
);
};
export const UserMessage: FC = () => {
return (
<MessagePrimitive.Root className="grid w-full max-w-2xl auto-rows-auto grid-cols-[minmax(72px,1fr)_auto] gap-y-2 py-4">
<div className="bg-muted text-foreground col-start-2 row-start-1 max-w-xl break-words rounded-3xl px-5 py-2.5">
<MessagePrimitive.Content />
</div>
</MessagePrimitive.Root>
);
};
interface AssistantMessageBarProps {
runId: string;
feedbackSubmitted: boolean;
setFeedbackSubmitted: Dispatch<SetStateAction<boolean>>;
}
const AssistantMessageBarComponent = ({
runId,
feedbackSubmitted,
setFeedbackSubmitted,
}: AssistantMessageBarProps) => {
const { isLoading, sendFeedback } = useFeedback();
return (
<ActionBarPrimitive.Root
hideWhenRunning
autohide="not-last"
className="flex items-center mt-2"
>
{feedbackSubmitted ? (
<TighterText className="text-gray-500 text-sm">
Feedback received! Thank you!
</TighterText>
) : (
<>
<ActionBarPrimitive.FeedbackPositive asChild>
<FeedbackButton
isLoading={isLoading}
sendFeedback={sendFeedback}
setFeedbackSubmitted={setFeedbackSubmitted}
runId={runId}
feedbackValue={1.0}
icon="thumbs-up"
/>
</ActionBarPrimitive.FeedbackPositive>
<ActionBarPrimitive.FeedbackNegative asChild>
<FeedbackButton
isLoading={isLoading}
sendFeedback={sendFeedback}
setFeedbackSubmitted={setFeedbackSubmitted}
runId={runId}
feedbackValue={0.0}
icon="thumbs-down"
/>
</ActionBarPrimitive.FeedbackNegative>
</>
)}
</ActionBarPrimitive.Root>
);
};
const AssistantMessageBar = React.memo(AssistantMessageBarComponent);
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/chat-interface/thread-history.tsx | import { isToday, isYesterday, isWithinInterval, subDays } from "date-fns";
import { TooltipIconButton } from "../ui/assistant-ui/tooltip-icon-button";
import { Button } from "../ui/button";
import { Trash2 } from "lucide-react";
import { Sheet, SheetContent, SheetTrigger } from "../ui/sheet";
import { Skeleton } from "../ui/skeleton";
import { useEffect, useState } from "react";
import { Thread } from "@langchain/langgraph-sdk";
import { PiChatsCircleLight } from "react-icons/pi";
import { TighterText } from "../ui/header";
import { useGraphContext } from "@/contexts/GraphContext";
import { useToast } from "@/hooks/use-toast";
import React from "react";
interface ThreadHistoryProps {
switchSelectedThreadCallback: (thread: Thread) => void;
}
interface ThreadProps {
id: string;
onClick: () => void;
onDelete: () => void;
label: string;
createdAt: Date;
}
const ThreadItem = (props: ThreadProps) => {
const [isHovering, setIsHovering] = useState(false);
return (
<div
className="flex flex-row gap-0 items-center justify-start w-full"
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
>
<Button
className="px-2 justify-start items-center flex-grow min-w-[191px] pr-0"
size="sm"
variant="ghost"
onClick={props.onClick}
>
<TighterText className="truncate text-sm font-light w-full text-left">
{props.label}
</TighterText>
</Button>
{isHovering && (
<TooltipIconButton
tooltip="Delete thread"
variant="ghost"
onClick={props.onDelete}
>
<Trash2 className="w-12 h-12 text-[#575757] hover:text-red-500 transition-colors ease-in" />
</TooltipIconButton>
)}
</div>
);
};
const LoadingThread = () => <Skeleton className="w-full h-8" />;
const convertThreadActualToThreadProps = (
thread: Thread,
switchSelectedThreadCallback: (thread: Thread) => void,
deleteThread: (id: string) => void
): ThreadProps => ({
id: thread.thread_id,
label:
thread.metadata?.thread_title ??
((thread.values as Record<string, any>)?.messages?.[0]?.content ||
"Untitled"),
createdAt: new Date(thread.created_at),
onClick: () => {
return switchSelectedThreadCallback(thread);
},
onDelete: () => {
return deleteThread(thread.thread_id);
},
});
const groupThreads = (
threads: Thread[],
switchSelectedThreadCallback: (thread: Thread) => void,
deleteThread: (id: string) => void
) => {
const today = new Date();
const yesterday = subDays(today, 1);
const sevenDaysAgo = subDays(today, 7);
return {
today: threads
.filter((thread) => isToday(new Date(thread.created_at)))
.sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
)
.map((t) =>
convertThreadActualToThreadProps(
t,
switchSelectedThreadCallback,
deleteThread
)
),
yesterday: threads
.filter((thread) => isYesterday(new Date(thread.created_at)))
.sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
)
.map((t) =>
convertThreadActualToThreadProps(
t,
switchSelectedThreadCallback,
deleteThread
)
),
lastSevenDays: threads
.filter((thread) =>
isWithinInterval(new Date(thread.created_at), {
start: sevenDaysAgo,
end: yesterday,
})
)
.sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
)
.map((t) =>
convertThreadActualToThreadProps(
t,
switchSelectedThreadCallback,
deleteThread
)
),
older: threads
.filter((thread) => new Date(thread.created_at) < sevenDaysAgo)
.sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
)
.map((t) =>
convertThreadActualToThreadProps(
t,
switchSelectedThreadCallback,
deleteThread
)
),
};
};
const prettifyDateLabel = (group: string): string => {
switch (group) {
case "today":
return "Today";
case "yesterday":
return "Yesterday";
case "lastSevenDays":
return "Last 7 days";
case "older":
return "Older";
default:
return group;
}
};
interface ThreadsListProps {
groupedThreads: {
today: ThreadProps[];
yesterday: ThreadProps[];
lastSevenDays: ThreadProps[];
older: ThreadProps[];
};
}
function ThreadsList(props: ThreadsListProps) {
return (
<div className="flex flex-col pt-3 gap-4">
{Object.entries(props.groupedThreads).map(([group, threads]) =>
threads.length > 0 ? (
<div key={group}>
<TighterText className="text-sm font-medium mb-1 pl-2">
{prettifyDateLabel(group)}
</TighterText>
<div className="flex flex-col gap-1">
{threads.map((thread) => (
<ThreadItem key={thread.id} {...thread} />
))}
</div>
</div>
) : null
)}
</div>
);
}
export function ThreadHistoryComponent(props: ThreadHistoryProps) {
const { toast } = useToast();
const {
userData: { user },
threadData: {
deleteThread,
getUserThreads,
userThreads,
isUserThreadsLoading,
},
graphData: { setMessages, switchSelectedThread },
} = useGraphContext();
const [open, setOpen] = useState(false);
useEffect(() => {
if (typeof window == "undefined" || userThreads.length || !user) return;
getUserThreads(user.id);
}, [user]);
const handleDeleteThread = async (id: string) => {
if (!user) {
toast({
title: "Failed to delete thread",
description: "User not found",
duration: 5000,
variant: "destructive",
});
return;
}
await deleteThread(id, user.id, () => setMessages([]));
};
const groupedThreads = groupThreads(
userThreads,
(thread) => {
switchSelectedThread(thread);
props.switchSelectedThreadCallback(thread);
setOpen(false);
},
handleDeleteThread
);
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<TooltipIconButton
tooltip="New chat"
variant="ghost"
className="w-fit h-fit p-2"
>
<PiChatsCircleLight
className="w-6 h-6 text-gray-600"
strokeWidth={8}
/>
</TooltipIconButton>
</SheetTrigger>
<SheetContent
side="left"
className="border-none overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100"
>
<TighterText className="px-2 text-lg text-gray-600">
Chat History
</TighterText>
{isUserThreadsLoading && !userThreads.length ? (
<div className="flex flex-col gap-1 px-2 pt-3">
{Array.from({ length: 25 }).map((_, i) => (
<LoadingThread key={`loading-thread-${i}`} />
))}
</div>
) : !userThreads.length ? (
<p className="px-3 text-gray-500">No items found in history.</p>
) : (
<ThreadsList groupedThreads={groupedThreads} />
)}
</SheetContent>
</Sheet>
);
}
export const ThreadHistory = React.memo(ThreadHistoryComponent);
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/chat-interface/composer.tsx | "use client";
import { ComposerPrimitive, ThreadPrimitive } from "@assistant-ui/react";
import { type FC } from "react";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import { SendHorizontalIcon } from "lucide-react";
import { AssistantSelect } from "../assistant-select";
const CircleStopIcon = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
width="16"
height="16"
>
<rect width="10" height="10" x="3" y="3" rx="2" />
</svg>
);
};
interface ComposerProps {
chatStarted: boolean;
userId: string | undefined;
}
export const Composer: FC<ComposerProps> = (props: ComposerProps) => {
return (
<ComposerPrimitive.Root className="focus-within:border-aui-ring/20 flex w-full min-h-[64px] flex-wrap items-center rounded-lg border px-2.5 shadow-sm transition-colors ease-in bg-white">
<AssistantSelect userId={props.userId} chatStarted={props.chatStarted} />
<ComposerPrimitive.Input
autoFocus
placeholder="Write a message..."
rows={1}
className="placeholder:text-muted-foreground max-h-40 flex-grow resize-none border-none bg-transparent px-2 py-4 text-sm outline-none focus:ring-0 disabled:cursor-not-allowed"
/>
<ThreadPrimitive.If running={false}>
<ComposerPrimitive.Send asChild>
<TooltipIconButton
tooltip="Send"
variant="default"
className="my-2.5 size-8 p-2 transition-opacity ease-in"
>
<SendHorizontalIcon />
</TooltipIconButton>
</ComposerPrimitive.Send>
</ThreadPrimitive.If>
<ThreadPrimitive.If running>
<ComposerPrimitive.Cancel asChild>
<TooltipIconButton
tooltip="Cancel"
variant="default"
className="my-2.5 size-8 p-2 transition-opacity ease-in"
>
<CircleStopIcon />
</TooltipIconButton>
</ComposerPrimitive.Cancel>
</ThreadPrimitive.If>
</ComposerPrimitive.Root>
);
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/chat-interface/index.tsx | export * from "./thread";
|
0 | lc_public_repos/open-canvas/src/components/chat-interface | lc_public_repos/open-canvas/src/components/chat-interface/model-selector/alert-new-model-selector.tsx | "use client";
import { motion, AnimatePresence } from "framer-motion";
import LLMIcon from "@/components/icons/svg/LLMIcon.svg";
import NextImage from "next/image";
import { LS_HAS_SEEN_MODEL_DROPDOWN_ALERT } from "@/constants";
import { Dispatch, SetStateAction, useEffect } from "react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { ExternalLink, X } from "lucide-react";
import { TighterText } from "@/components/ui/header";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
export const AlertNewModelSelectorFeature = ({
chatStarted,
showAlert,
setShowAlert,
}: {
chatStarted: boolean;
showAlert: boolean;
setShowAlert: Dispatch<SetStateAction<boolean>>;
}) => {
useEffect(() => {
if (typeof window === "undefined") return;
const hasSeenAlert = localStorage.getItem(LS_HAS_SEEN_MODEL_DROPDOWN_ALERT);
if (!hasSeenAlert) {
setShowAlert(true);
}
}, []);
const handleCloseAlert = () => {
setShowAlert(false);
// Wait for animation to complete before setting localStorage
setTimeout(() => {
localStorage.setItem(LS_HAS_SEEN_MODEL_DROPDOWN_ALERT, "true");
}, 300);
};
if (!showAlert || chatStarted) {
return <AnimatePresence />; // Keep AnimatePresence mounted to enable fading out
}
return (
<AnimatePresence mode="wait">
{showAlert && (
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2 }}
>
<div className="relative p-[0px] rounded-lg bg-gradient-to-r from-pink-500/50 via-purple-500/50 to-pink-500/50 animate-gradient-xy shadow-[0_0_25px_rgba(236,72,153,0.3)] before:absolute before:inset-0 before:rounded-lg before:p-[12px] before:bg-gradient-to-r before:from-pink-500/20 before:via-purple-500/20 before:to-pink-500/20 before:blur-xl before:-z-10 before:animate-gradient-xy-enhanced">
<Alert className="max-w-xl bg-white rounded-lg hover:bg-gray-50 transition-colors duration-300 ease-in-out">
<AlertTitle className="flex justify-between items-center">
<div className="flex items-center justify-start gap-1">
<NextImage
alt="Model icon"
src={LLMIcon}
width={16}
height={16}
/>
<TighterText>Customize your LLM model!</TighterText>
</div>
<TooltipIconButton
tooltip="Close alert"
variant="ghost"
delayDuration={400}
onClick={handleCloseAlert}
size="sm"
>
<X className="w-4 h-4 text-gray-600" />
</TooltipIconButton>
</AlertTitle>
<AlertDescription className="inline-flex items-center gap-1 flex-wrap mt-2">
<p>
Open Canvas now supports customizing your LLM model! Click the
dropdown above to pick a model from{" "}
<a
href="https://fireworks.ai/"
target="_blank"
className="inline-flex items-baseline gap-[2px]"
>
<ExternalLink size={12} />
Fireworks AI
</a>
,{" "}
<a
href="https://anthropic.com/"
target="_blank"
className="inline-flex items-baseline gap-[2px]"
>
<ExternalLink size={12} />
Anthropic
</a>
, or{" "}
<a
href="https://openai.com/"
target="_blank"
className="inline-flex items-baseline gap-[2px]"
>
<ExternalLink size={12} />
OpenAI
</a>
.
</p>
</AlertDescription>
</Alert>
</div>
</motion.div>
)}
</AnimatePresence>
);
};
|
0 | lc_public_repos/open-canvas/src/components/chat-interface | lc_public_repos/open-canvas/src/components/chat-interface/model-selector/index.tsx | "use client";
import LLMIcon from "@/components/icons/svg/LLMIcon.svg";
import NextImage from "next/image";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
ALL_MODEL_NAMES,
ANTHROPIC_MODELS,
OPENAI_MODELS,
FIREWORKS_MODELS,
GEMINI_MODELS,
LS_HAS_SEEN_MODEL_DROPDOWN_ALERT,
AZURE_MODELS,
} from "@/constants";
import { Dispatch, SetStateAction, useState } from "react";
import { AlertNewModelSelectorFeature } from "./alert-new-model-selector";
import { IsNewBadge } from "./new-badge";
const allModels = [
...ANTHROPIC_MODELS,
...OPENAI_MODELS,
...FIREWORKS_MODELS,
...GEMINI_MODELS,
...AZURE_MODELS,
];
const modelNameToLabel = (modelName: ALL_MODEL_NAMES) => {
const model = allModels.find((m) => m.name === modelName);
return model?.label ?? modelName;
};
interface ModelSelectorProps {
modelName: ALL_MODEL_NAMES;
setModelName: Dispatch<SetStateAction<ALL_MODEL_NAMES>>;
chatStarted: boolean;
}
export default function ModelSelector(props: ModelSelectorProps) {
const { modelName, setModelName } = props;
const [showAlert, setShowAlert] = useState(false);
const isSelectedModelNew = !!allModels.find(
(model) => model.name === modelName && model.isNew
);
const handleModelChange = async (newModel: ALL_MODEL_NAMES) => {
// Create a new thread with the new model
setModelName(newModel);
if (showAlert) {
// Ensure the model is closed if the user selects a model
setShowAlert(false);
localStorage.setItem(LS_HAS_SEEN_MODEL_DROPDOWN_ALERT, "true");
}
};
const allAllowedModels = allModels.filter((model) => {
if (
model.name.includes("fireworks/") &&
process.env.NEXT_PUBLIC_FIREWORKS_ENABLED === "false"
) {
return false;
}
if (
model.name.includes("claude-") &&
process.env.NEXT_PUBLIC_ANTHROPIC_ENABLED === "false"
) {
return false;
}
if (
model.name.includes("gpt-") &&
process.env.NEXT_PUBLIC_OPENAI_ENABLED === "false"
) {
return false;
}
if (
model.name.includes("azure/") &&
process.env.NEXT_PUBLIC_AZURE_ENABLED === "false"
) {
return false;
}
if (
model.name.includes("gemini-") &&
process.env.NEXT_PUBLIC_GEMINI_ENABLED === "false"
) {
return false;
}
// By default, return true if the environment variable is not set or is set to true
return true;
});
return (
<div className="relative">
<Select value={modelName} onValueChange={handleModelChange}>
<SelectTrigger className="min-w-[180px] w-[250px] bg-transparent shadow-none text-sm focus:outline-none cursor-pointer hover:bg-gray-100 rounded transition-colors border-none text-gray-600">
<SelectValue>
<div className="flex items-center pr-2 truncate">
<NextImage
alt="Model icon"
src={LLMIcon}
width={14}
height={14}
className="mr-2"
/>
<span className="flex flex-row items-center justify-start gap-2">
{modelNameToLabel(modelName)}
{isSelectedModelNew && <IsNewBadge />}
</span>
</div>
</SelectValue>
</SelectTrigger>
<SelectContent>
{allAllowedModels.map((model) => (
<SelectItem key={model.name} value={model.name} className="mr-2">
<span className="flex flex-row w-full items-center justify-start gap-2">
{model.label}
{model.isNew && <IsNewBadge />}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
<div className="absolute top-full -left-10 pt-2 w-max min-w-full">
<AlertNewModelSelectorFeature
showAlert={showAlert}
setShowAlert={setShowAlert}
chatStarted={props.chatStarted}
/>
</div>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/chat-interface | lc_public_repos/open-canvas/src/components/chat-interface/model-selector/new-badge.tsx | import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
export function IsNewBadge() {
return (
<div
className={cn(
"before:absolute relative p-[1px] before:p-[4px] rounded-md before:rounded-md before:shadow-[0_0_4px_rgba(236,72,153,0.2)] w-[58px]",
"animate-gradient-xy before:animate-gradient-xy-enhanced",
"before:inset-0 before:blur-sm before:-z-10 ",
"from-pink-500/50 before:from-pink-500/20",
"bg-gradient-to-r before:bg-gradient-to-r ",
"via-purple-500/50 before:via-purple-500/20",
"to-pink-500/50 before:to-pink-500/20"
)}
>
<Badge
className={cn(
"bg-gradient-to-r from-pink-50 via-purple-50 to-pink-50",
"animate-gradient-x",
"rounded-md transition-colors duration-300 ease-in-out",
"text-gray-700 text-xs w-14",
"hover:from-pink-100 hover:via-purple-100 hover:to-pink-100"
)}
>
New!
</Badge>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/auth | lc_public_repos/open-canvas/src/components/auth/login/user-auth-form-login.tsx | "use client";
import * as React from "react";
import { cn } from "@/lib/utils";
import { Input } from "../../ui/input";
import { Button } from "../../ui/button";
import { Icons } from "../../ui/icons";
import { Label } from "../../ui/label";
import { LoginWithEmailInput } from "./Login";
import { useState } from "react";
import { PasswordInput } from "../../ui/password-input";
interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {
onLoginWithEmail: (input: LoginWithEmailInput) => Promise<void>;
onLoginWithOauth: (provider: "google" | "github") => Promise<void>;
}
export function UserAuthForm({
className,
onLoginWithEmail,
onLoginWithOauth,
...props
}: UserAuthFormProps) {
const [isEmailPasswordLoading, setEmailPasswordIsLoading] = useState(false);
const [isGoogleLoading, setGoogleIsLoading] = useState(false);
const [isGithubLoading, setGithubIsLoading] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [showPasswordField, setShowPasswordField] = useState(false);
const isLoading =
isEmailPasswordLoading || isGoogleLoading || isGithubLoading;
async function onSubmit(event: React.SyntheticEvent) {
event.preventDefault();
setEmailPasswordIsLoading(true);
await onLoginWithEmail({ email, password });
setEmailPasswordIsLoading(false);
}
return (
<div className={cn("grid gap-6", className)} {...props}>
<form onSubmit={onSubmit}>
<div className="grid gap-2">
<div className="grid gap-1">
<div className="pt-1 pb-[2px] px-1">
<Label className="sr-only" htmlFor="email">
Email
</Label>
<Input
id="email"
placeholder="name@example.com"
type="email"
autoCapitalize="none"
autoComplete="email"
autoCorrect="off"
disabled={isLoading}
value={email}
onChange={(e) => {
setEmail(e.target.value);
if (!showPasswordField) {
setShowPasswordField(true);
}
}}
/>
</div>
<div
className={cn(
"overflow-hidden transition-all duration-300 ease-in-out pt-[2px] pb-1 px-1",
showPasswordField ? "max-h-20 opacity-100" : "max-h-0 opacity-0"
)}
>
<Label className="sr-only" htmlFor="password">
Password
</Label>
<PasswordInput
id="password"
autoComplete="new-password"
autoCorrect="off"
disabled={isLoading}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<Button disabled={isLoading}>
{isLoading && (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
)}
Login with Email
</Button>
</div>
</form>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">
Or continue with
</span>
</div>
</div>
<Button
onClick={async () => {
setGoogleIsLoading(true);
await onLoginWithOauth("google");
setGoogleIsLoading(false);
}}
variant="outline"
type="button"
disabled={isLoading}
>
{isLoading ? (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icons.google className="mr-2 h-4 w-4" />
)}{" "}
Google
</Button>
<Button
onClick={async () => {
setGithubIsLoading(true);
await onLoginWithOauth("github");
setGithubIsLoading(false);
}}
variant="outline"
type="button"
disabled={isLoading}
>
{isLoading ? (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icons.gitHub className="mr-2 h-4 w-4" />
)}{" "}
GitHub
</Button>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/auth | lc_public_repos/open-canvas/src/components/auth/login/Login.tsx | import { cn } from "@/lib/utils";
import NextImage from "next/image";
import Link from "next/link";
import { buttonVariants } from "../../ui/button";
import { UserAuthForm } from "./user-auth-form-login";
import { login } from "./actions";
import { createSupabaseClient } from "@/lib/supabase/client";
import { useSearchParams, useRouter } from "next/navigation";
import { useState, useEffect } from "react";
export interface LoginWithEmailInput {
email: string;
password: string;
}
export function Login() {
const [isError, setIsError] = useState(false);
const searchParams = useSearchParams();
const router = useRouter();
useEffect(() => {
const error = searchParams.get("error");
if (error === "true") {
setIsError(true);
// Remove the error parameter from the URL
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete("error");
router.replace(
`${window.location.pathname}?${newSearchParams.toString()}`,
{ scroll: false }
);
}
}, [searchParams, router]);
const onLoginWithEmail = async (
input: LoginWithEmailInput
): Promise<void> => {
setIsError(false);
await login(input);
};
const onLoginWithOauth = async (
provider: "google" | "github"
): Promise<void> => {
setIsError(false);
const client = createSupabaseClient();
const currentOrigin =
typeof window !== "undefined" ? window.location.origin : "";
await client.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${currentOrigin}/auth/callback`,
},
});
};
return (
<div className="container relative h-full flex-col items-center justify-center md:grid lg:max-w-none lg:grid-cols-2 lg:px-0">
<Link
href="/auth/signup"
className={cn(
buttonVariants({ variant: "ghost" }),
"absolute md:flex hidden right-4 top-4 md:right-8 md:top-8"
)}
>
Signup
</Link>
<div className="relative hidden h-full flex-col bg-muted p-10 text-white dark:border-r lg:flex">
<div className="absolute inset-0 bg-zinc-900" />
<div className="relative z-20 flex gap-1 items-center text-lg font-medium">
<NextImage
src="/lc_logo.jpg"
width={36}
height={36}
alt="LangChain Logo"
className="rounded-full"
/>
Open Canvas
</div>
</div>
<div className="lg:p-8">
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
<div className="flex flex-col space-y-2 text-center">
<h1 className="text-2xl font-semibold tracking-tight">Login</h1>
<Link
href="/auth/signup"
className={cn(
buttonVariants({ variant: "ghost" }),
"md:hidden flex"
)}
>
Signup
</Link>
</div>
<UserAuthForm
onLoginWithEmail={onLoginWithEmail}
onLoginWithOauth={onLoginWithOauth}
/>
{isError && (
<p className="text-red-500 text-sm text-center">
There was an error signing into your account. Please try again.
</p>
)}
</div>
</div>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/auth | lc_public_repos/open-canvas/src/components/auth/login/actions.ts | "use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { LoginWithEmailInput } from "./Login";
export async function login(input: LoginWithEmailInput) {
const supabase = createClient();
const data = {
email: input.email,
password: input.password,
};
const { error } = await supabase.auth.signInWithPassword(data);
if (error) {
console.error(error);
redirect("/auth/login?error=true");
}
revalidatePath("/", "layout");
redirect("/");
}
|
0 | lc_public_repos/open-canvas/src/components/auth | lc_public_repos/open-canvas/src/components/auth/signup/Signup.tsx | import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
import NextImage from "next/image";
import Link from "next/link";
import { buttonVariants } from "../../ui/button";
import { UserAuthForm } from "./user-auth-form-signup";
import { signup } from "./actions";
import { createSupabaseClient } from "@/lib/supabase/client";
import { useSearchParams, useRouter } from "next/navigation";
export interface SignupWithEmailInput {
email: string;
password: string;
}
export function Signup() {
const [isError, setIsError] = useState(false);
const searchParams = useSearchParams();
const router = useRouter();
useEffect(() => {
const error = searchParams.get("error");
if (error === "true") {
setIsError(true);
// Remove the error parameter from the URL
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete("error");
router.replace(
`${window.location.pathname}?${newSearchParams.toString()}`,
{ scroll: false }
);
}
}, [searchParams, router]);
const onSignupWithEmail = async (
input: SignupWithEmailInput
): Promise<void> => {
setIsError(false);
await signup(input, window.location.origin);
};
const onSignupWithOauth = async (
provider: "google" | "github"
): Promise<void> => {
setIsError(false);
const client = createSupabaseClient();
const currentOrigin =
typeof window !== "undefined" ? window.location.origin : "";
await client.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${currentOrigin}/auth/callback`,
},
});
};
return (
<div className="container relative h-full flex-col items-center justify-center md:grid lg:max-w-none lg:grid-cols-2 lg:px-0">
<Link
href="/auth/login"
className={cn(
buttonVariants({ variant: "ghost" }),
"absolute md:flex hidden right-4 top-4 md:right-8 md:top-8"
)}
>
Login
</Link>
<div className="relative hidden h-full flex-col bg-muted p-10 text-white dark:border-r lg:flex">
<div className="absolute inset-0 bg-zinc-900" />
<div className="relative z-20 flex gap-1 items-center text-lg font-medium">
<NextImage
src="/lc_logo.jpg"
width={36}
height={36}
alt="LangChain Logo"
className="rounded-full"
/>
Open Canvas
</div>
</div>
<div className="lg:p-8">
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
<div className="flex flex-col space-y-2 text-center">
<h1 className="text-2xl font-semibold tracking-tight">
Create an account
</h1>
<Link
href="/auth/login"
className={cn(
buttonVariants({ variant: "ghost" }),
"md:hidden flex"
)}
>
Login
</Link>
<p className="text-sm text-muted-foreground">
Enter your email below to create your account
</p>
</div>
<UserAuthForm
onSignupWithEmail={onSignupWithEmail}
onSignupWithOauth={onSignupWithOauth}
/>
{isError && (
<p className="text-red-500 text-sm text-center">
There was an error creating your account. Please try again.
</p>
)}
</div>
</div>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/auth | lc_public_repos/open-canvas/src/components/auth/signup/user-auth-form-signup.tsx | "use client";
import * as React from "react";
import { cn } from "@/lib/utils";
import { Input } from "../../ui/input";
import { Button } from "../../ui/button";
import { Icons } from "../../ui/icons";
import { Label } from "../../ui/label";
import { SignupWithEmailInput } from "./Signup";
import { useState } from "react";
import { PasswordInput } from "../../ui/password-input";
interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {
onSignupWithEmail: (input: SignupWithEmailInput) => Promise<void>;
onSignupWithOauth: (provider: "google" | "github") => Promise<void>;
}
export function UserAuthForm({
className,
onSignupWithEmail,
onSignupWithOauth,
...props
}: UserAuthFormProps) {
const [isEmailPasswordLoading, setEmailPasswordIsLoading] = useState(false);
const [isGoogleLoading, setGoogleIsLoading] = useState(false);
const [isGithubLoading, setGithubIsLoading] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [showPasswordField, setShowPasswordField] = useState(false);
const isLoading =
isEmailPasswordLoading || isGoogleLoading || isGithubLoading;
async function onSubmit(event: React.SyntheticEvent) {
event.preventDefault();
setEmailPasswordIsLoading(true);
await onSignupWithEmail({ email, password });
setEmailPasswordIsLoading(false);
}
return (
<div className={cn("grid gap-6", className)} {...props}>
<form onSubmit={onSubmit}>
<div className="grid gap-2">
<div className="grid gap-1">
<div className="pt-1 pb-[2px] px-1">
<Label className="sr-only" htmlFor="email">
Email
</Label>
<Input
id="email"
placeholder="name@example.com"
type="email"
autoCapitalize="none"
autoComplete="email"
autoCorrect="off"
disabled={isLoading}
value={email}
onChange={(e) => {
setEmail(e.target.value);
if (!showPasswordField) {
setShowPasswordField(true);
}
}}
/>
</div>
<div
className={cn(
"overflow-hidden transition-all duration-300 ease-in-out pt-[2px] pb-1 px-1",
showPasswordField ? "max-h-20 opacity-100" : "max-h-0 opacity-0"
)}
>
<Label className="sr-only" htmlFor="password">
Password
</Label>
<PasswordInput
id="password"
autoComplete="new-password"
autoCorrect="off"
disabled={isLoading}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<Button disabled={isLoading}>
{isLoading && (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
)}
Sign Up with Email
</Button>
</div>
</form>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">
Or continue with
</span>
</div>
</div>
<Button
onClick={async () => {
setGoogleIsLoading(true);
await onSignupWithOauth("google");
setGoogleIsLoading(false);
}}
variant="outline"
type="button"
disabled={isLoading}
>
{isLoading ? (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icons.google className="mr-2 h-4 w-4" />
)}{" "}
Google
</Button>
<Button
onClick={async () => {
setGithubIsLoading(true);
await onSignupWithOauth("github");
setGithubIsLoading(false);
}}
variant="outline"
type="button"
disabled={isLoading}
>
{isLoading ? (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icons.gitHub className="mr-2 h-4 w-4" />
)}{" "}
GitHub
</Button>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/auth | lc_public_repos/open-canvas/src/components/auth/signup/actions.ts | "use server";
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { SignupWithEmailInput } from "./Signup";
export async function signup(input: SignupWithEmailInput, baseUrl: string) {
const supabase = createClient();
const data = {
email: input.email,
password: input.password,
// Not possible to set this when signing up with OAuth, so for now we'll omit.
// data: {
// is_open_canvas: true,
// },
options: {
emailRedirectTo: `${baseUrl}/auth/confirm`,
},
};
const { error } = await supabase.auth.signUp(data);
if (error) {
console.error(error);
redirect("/auth/signup?error=true");
}
// Users still need to confirm their email address.
// This page will show a message to check their email.
redirect("/auth/signup/success");
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/badge.tsx | import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/textarea.tsx | import * as React from "react";
import { cn } from "@/lib/utils";
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
);
}
);
Textarea.displayName = "Textarea";
export { Textarea };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/select.tsx | "use client";
import * as React from "react";
import {
CaretSortIcon,
CheckIcon,
ChevronDownIcon,
ChevronUpIcon,
} from "@radix-ui/react-icons";
import * as SelectPrimitive from "@radix-ui/react-select";
import { cn } from "@/lib/utils";
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<CaretSortIcon className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold", className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/hover-card.tsx | "use client";
import * as React from "react";
import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { cn } from "@/lib/utils";
const HoverCard = HoverCardPrimitive.Root;
const HoverCardTrigger = HoverCardPrimitive.Trigger;
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
));
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName;
export { HoverCard, HoverCardTrigger, HoverCardContent };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/programming-lang-dropdown.tsx | import { ProgrammingLanguageOptions } from "@/types";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from "./dropdown-menu";
import { Code } from "lucide-react";
import { Button } from "./button";
import { TooltipIconButton } from "./assistant-ui/tooltip-icon-button";
import { TighterText } from "./header";
interface ProgrammingLanguageListProps {
handleSubmit: (portLanguage: ProgrammingLanguageOptions) => Promise<void>;
}
export function ProgrammingLanguageList(
props: Readonly<ProgrammingLanguageListProps>
) {
return (
<div className="flex flex-col gap-3 items-center w-full text-left">
<TooltipIconButton
tooltip="PHP"
variant="ghost"
className="transition-colors w-full h-fit"
delayDuration={400}
onClick={async () => await props.handleSubmit("php")}
>
<p>PHP</p>
</TooltipIconButton>
<TooltipIconButton
tooltip="TypeScript"
variant="ghost"
className="transition-colors w-full h-fit px-1 py-1"
delayDuration={400}
onClick={async () => await props.handleSubmit("typescript")}
>
<p>TypeScript</p>
</TooltipIconButton>
<TooltipIconButton
tooltip="JavaScript"
variant="ghost"
className="transition-colors w-full h-fit"
delayDuration={400}
onClick={async () => await props.handleSubmit("javascript")}
>
<p>JavaScript</p>
</TooltipIconButton>
<TooltipIconButton
tooltip="C++"
variant="ghost"
className="transition-colors w-full h-fit"
delayDuration={400}
onClick={async () => await props.handleSubmit("cpp")}
>
<p>C++</p>
</TooltipIconButton>
<TooltipIconButton
tooltip="Java"
variant="ghost"
className="transition-colors w-full h-fit"
delayDuration={400}
onClick={async () => await props.handleSubmit("java")}
>
<p>Java</p>
</TooltipIconButton>
<TooltipIconButton
tooltip="Python"
variant="ghost"
className="transition-colors w-full h-fit"
delayDuration={400}
onClick={async () => await props.handleSubmit("python")}
>
<p>Python</p>
</TooltipIconButton>
<TooltipIconButton
tooltip="HTML"
variant="ghost"
className="transition-colors w-full h-fit"
delayDuration={400}
onClick={async () => await props.handleSubmit("html")}
>
<p>HTML</p>
</TooltipIconButton>
<TooltipIconButton
tooltip="SQL"
variant="ghost"
className="transition-colors w-full h-fit"
delayDuration={400}
onClick={async () => await props.handleSubmit("sql")}
>
<p>SQL</p>
</TooltipIconButton>
</div>
);
}
const LANGUAGES: Array<{ label: string; key: ProgrammingLanguageOptions }> = [
{ label: "PHP", key: "php" },
{ label: "TypeScript", key: "typescript" },
{ label: "JavaScript", key: "javascript" },
{ label: "C++", key: "cpp" },
{ label: "Java", key: "java" },
{ label: "Python", key: "python" },
{ label: "HTML", key: "html" },
{ label: "SQL", key: "sql" },
];
export const ProgrammingLanguagesDropdown = ({
handleSubmit,
}: {
handleSubmit: (portLanguage: ProgrammingLanguageOptions) => void;
}) => {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className="transition-colors text-gray-600 flex items-center justify-center gap-2 w-[250px] h-[64px]"
>
<TighterText>New Code File</TighterText>
<Code />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="max-h-[600px] w-[250px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
<DropdownMenuLabel>Languages</DropdownMenuLabel>
{LANGUAGES.map((lang) => (
<DropdownMenuItem
key={lang.key}
onSelect={() => handleSubmit(lang.key)}
className="flex items-center justify-start gap-1"
>
{lang.label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/progress.tsx | "use client";
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "@/lib/utils";
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
"relative h-2 w-full overflow-hidden rounded-full bg-primary/20",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
));
Progress.displayName = ProgressPrimitive.Root.displayName;
export { Progress };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/password-input.tsx | "use client";
import * as React from "react";
import { cn } from "@/lib/utils";
import { Input, InputProps } from "./input";
import { Button } from "./button";
import { EyeIcon, EyeOffIcon } from "lucide-react";
export const PasswordInput = React.forwardRef<HTMLInputElement, InputProps>(
({ className, ...props }, ref) => {
const [showPassword, setShowPassword] = React.useState(false);
const disabled =
props.value === "" || props.value === undefined || props.disabled;
return (
<div className="relative">
<Input
type={showPassword ? "text" : "password"}
className={cn("hide-password-toggle pr-10", className)}
ref={ref}
{...props}
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowPassword((prev) => !prev)}
disabled={disabled}
>
{showPassword && !disabled ? (
<EyeIcon className="h-4 w-4" aria-hidden="true" />
) : (
<EyeOffIcon className="h-4 w-4" aria-hidden="true" />
)}
<span className="sr-only">
{showPassword ? "Hide password" : "Show password"}
</span>
</Button>
{/* hides browsers password toggles */}
<style>{`
.hide-password-toggle::-ms-reveal,
.hide-password-toggle::-ms-clear {
visibility: hidden;
pointer-events: none;
display: none;
}
`}</style>
</div>
);
}
);
PasswordInput.displayName = "PasswordInput";
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/skeleton.tsx | import { cn } from "@/lib/utils";
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-primary/10", className)}
{...props}
/>
);
}
export { Skeleton };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/sheet.tsx | "use client";
import * as React from "react";
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { Cross2Icon } from "@radix-ui/react-icons";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const Sheet = SheetPrimitive.Root;
const SheetTrigger = SheetPrimitive.Trigger;
const SheetClose = SheetPrimitive.Close;
const SheetPortal = SheetPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
));
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
}
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
ref={ref}
className={cn(sheetVariants({ side }), className)}
{...props}
>
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
<Cross2Icon className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
{children}
</SheetPrimitive.Content>
</SheetPortal>
));
SheetContent.displayName = SheetPrimitive.Content.displayName;
const SheetHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
);
SheetHeader.displayName = "SheetHeader";
const SheetFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
);
SheetFooter.displayName = "SheetFooter";
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-foreground", className)}
{...props}
/>
));
SheetTitle.displayName = SheetPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
SheetDescription.displayName = SheetPrimitive.Description.displayName;
export {
Sheet,
SheetPortal,
SheetOverlay,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/header.tsx | import { cn } from "@/lib/utils";
export function TighterText({
className,
children,
}: {
className?: string;
children: React.ReactNode;
}) {
return <p className={cn("tracking-tighter", className)}>{children}</p>;
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/icons.tsx | type IconProps = React.HTMLAttributes<SVGElement>;
export const Icons = {
logo: (props: IconProps) => (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" {...props}>
<rect width="256" height="256" fill="none" />
<line
x1="208"
y1="128"
x2="128"
y2="208"
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="16"
/>
<line
x1="192"
y1="40"
x2="40"
y2="192"
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="16"
/>
</svg>
),
twitter: (props: IconProps) => (
<svg
{...props}
height="23"
viewBox="0 0 1200 1227"
width="23"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M714.163 519.284L1160.89 0H1055.03L667.137 450.887L357.328 0H0L468.492 681.821L0 1226.37H105.866L515.491 750.218L842.672 1226.37H1200L714.137 519.284H714.163ZM569.165 687.828L521.697 619.934L144.011 79.6944H306.615L611.412 515.685L658.88 583.579L1055.08 1150.3H892.476L569.165 687.854V687.828Z" />
</svg>
),
gitHub: (props: IconProps) => (
<svg viewBox="0 0 438.549 438.549" {...props}>
<path
fill="currentColor"
d="M409.132 114.573c-19.608-33.596-46.205-60.194-79.798-79.8-33.598-19.607-70.277-29.408-110.063-29.408-39.781 0-76.472 9.804-110.063 29.408-33.596 19.605-60.192 46.204-79.8 79.8C9.803 148.168 0 184.854 0 224.63c0 47.78 13.94 90.745 41.827 128.906 27.884 38.164 63.906 64.572 108.063 79.227 5.14.954 8.945.283 11.419-1.996 2.475-2.282 3.711-5.14 3.711-8.562 0-.571-.049-5.708-.144-15.417a2549.81 2549.81 0 01-.144-25.406l-6.567 1.136c-4.187.767-9.469 1.092-15.846 1-6.374-.089-12.991-.757-19.842-1.999-6.854-1.231-13.229-4.086-19.13-8.559-5.898-4.473-10.085-10.328-12.56-17.556l-2.855-6.57c-1.903-4.374-4.899-9.233-8.992-14.559-4.093-5.331-8.232-8.945-12.419-10.848l-1.999-1.431c-1.332-.951-2.568-2.098-3.711-3.429-1.142-1.331-1.997-2.663-2.568-3.997-.572-1.335-.098-2.43 1.427-3.289 1.525-.859 4.281-1.276 8.28-1.276l5.708.853c3.807.763 8.516 3.042 14.133 6.851 5.614 3.806 10.229 8.754 13.846 14.842 4.38 7.806 9.657 13.754 15.846 17.847 6.184 4.093 12.419 6.136 18.699 6.136 6.28 0 11.704-.476 16.274-1.423 4.565-.952 8.848-2.383 12.847-4.285 1.713-12.758 6.377-22.559 13.988-29.41-10.848-1.14-20.601-2.857-29.264-5.14-8.658-2.286-17.605-5.996-26.835-11.14-9.235-5.137-16.896-11.516-22.985-19.126-6.09-7.614-11.088-17.61-14.987-29.979-3.901-12.374-5.852-26.648-5.852-42.826 0-23.035 7.52-42.637 22.557-58.817-7.044-17.318-6.379-36.732 1.997-58.24 5.52-1.715 13.706-.428 24.554 3.853 10.85 4.283 18.794 7.952 23.84 10.994 5.046 3.041 9.089 5.618 12.135 7.708 17.705-4.947 35.976-7.421 54.818-7.421s37.117 2.474 54.823 7.421l10.849-6.849c7.419-4.57 16.18-8.758 26.262-12.565 10.088-3.805 17.802-4.853 23.134-3.138 8.562 21.509 9.325 40.922 2.279 58.24 15.036 16.18 22.559 35.787 22.559 58.817 0 16.178-1.958 30.497-5.853 42.966-3.9 12.471-8.941 22.457-15.125 29.979-6.191 7.521-13.901 13.85-23.131 18.986-9.232 5.14-18.182 8.85-26.84 11.136-8.662 2.286-18.415 4.004-29.263 5.146 9.894 8.562 14.842 22.077 14.842 40.539v60.237c0 3.422 1.19 6.279 3.572 8.562 2.379 2.279 6.136 2.95 11.276 1.995 44.163-14.653 80.185-41.062 108.068-79.226 27.88-38.161 41.825-81.126 41.825-128.906-.01-39.771-9.818-76.454-29.414-110.049z"
></path>
</svg>
),
radix: (props: IconProps) => (
<svg viewBox="0 0 25 25" fill="none" {...props}>
<path
d="M12 25C7.58173 25 4 21.4183 4 17C4 12.5817 7.58173 9 12 9V25Z"
fill="currentcolor"
></path>
<path d="M12 0H4V8H12V0Z" fill="currentcolor"></path>
<path
d="M17 8C19.2091 8 21 6.20914 21 4C21 1.79086 19.2091 0 17 0C14.7909 0 13 1.79086 13 4C13 6.20914 14.7909 8 17 8Z"
fill="currentcolor"
></path>
</svg>
),
aria: (props: IconProps) => (
<svg role="img" viewBox="0 0 24 24" fill="currentColor" {...props}>
<path d="M13.966 22.624l-1.69-4.281H8.122l3.892-9.144 5.662 13.425zM8.884 1.376H0v21.248zm15.116 0h-8.884L24 22.624Z" />
</svg>
),
npm: (props: IconProps) => (
<svg viewBox="0 0 24 24" {...props}>
<path
d="M1.763 0C.786 0 0 .786 0 1.763v20.474C0 23.214.786 24 1.763 24h20.474c.977 0 1.763-.786 1.763-1.763V1.763C24 .786 23.214 0 22.237 0zM5.13 5.323l13.837.019-.009 13.836h-3.464l.01-10.382h-3.456L12.04 19.17H5.113z"
fill="currentColor"
/>
</svg>
),
yarn: (props: IconProps) => (
<svg viewBox="0 0 24 24" {...props}>
<path
d="M12 0C5.375 0 0 5.375 0 12s5.375 12 12 12 12-5.375 12-12S18.625 0 12 0zm.768 4.105c.183 0 .363.053.525.157.125.083.287.185.755 1.154.31-.088.468-.042.551-.019.204.056.366.19.463.375.477.917.542 2.553.334 3.605-.241 1.232-.755 2.029-1.131 2.576.324.329.778.899 1.117 1.825.278.774.31 1.478.273 2.015a5.51 5.51 0 0 0 .602-.329c.593-.366 1.487-.917 2.553-.931.714-.009 1.269.445 1.353 1.103a1.23 1.23 0 0 1-.945 1.362c-.649.158-.95.278-1.821.843-1.232.797-2.539 1.242-3.012 1.39a1.686 1.686 0 0 1-.704.343c-.737.181-3.266.315-3.466.315h-.046c-.783 0-1.214-.241-1.45-.491-.658.329-1.51.19-2.122-.134a1.078 1.078 0 0 1-.58-1.153 1.243 1.243 0 0 1-.153-.195c-.162-.25-.528-.936-.454-1.946.056-.723.556-1.367.88-1.71a5.522 5.522 0 0 1 .408-2.256c.306-.727.885-1.348 1.32-1.737-.32-.537-.644-1.367-.329-2.21.227-.602.412-.936.82-1.08h-.005c.199-.074.389-.153.486-.259a3.418 3.418 0 0 1 2.298-1.103c.037-.093.079-.185.125-.283.31-.658.639-1.029 1.024-1.168a.94.94 0 0 1 .328-.06zm.006.7c-.507.016-1.001 1.519-1.001 1.519s-1.27-.204-2.266.871c-.199.218-.468.334-.746.44-.079.028-.176.023-.417.672-.371.991.625 2.094.625 2.094s-1.186.839-1.626 1.881c-.486 1.144-.338 2.261-.338 2.261s-.843.732-.899 1.487c-.051.663.139 1.2.343 1.515.227.343.51.176.51.176s-.561.653-.037.931c.477.25 1.283.394 1.71-.037.31-.31.371-1.001.486-1.283.028-.065.12.111.209.199.097.093.264.195.264.195s-.755.324-.445 1.066c.102.246.468.403 1.066.398.222-.005 2.664-.139 3.313-.296.375-.088.505-.283.505-.283s1.566-.431 2.998-1.357c.917-.598 1.293-.76 2.034-.936.612-.148.57-1.098-.241-1.084-.839.009-1.575.44-2.196.825-1.163.718-1.742.672-1.742.672l-.018-.032c-.079-.13.371-1.293-.134-2.678-.547-1.515-1.413-1.881-1.344-1.997.297-.5 1.038-1.297 1.334-2.78.176-.899.13-2.377-.269-3.151-.074-.144-.732.241-.732.241s-.616-1.371-.788-1.483a.271.271 0 0 0-.157-.046z"
fill="currentColor"
/>
</svg>
),
pnpm: (props: IconProps) => (
<svg viewBox="0 0 24 24" {...props}>
<path
d="M0 0v7.5h7.5V0zm8.25 0v7.5h7.498V0zm8.25 0v7.5H24V0zM8.25 8.25v7.5h7.498v-7.5zm8.25 0v7.5H24v-7.5zM0 16.5V24h7.5v-7.5zm8.25 0V24h7.498v-7.5zm8.25 0V24H24v-7.5z"
fill="currentColor"
/>
</svg>
),
react: (props: IconProps) => (
<svg viewBox="0 0 24 24" {...props}>
<path
d="M14.23 12.004a2.236 2.236 0 0 1-2.235 2.236 2.236 2.236 0 0 1-2.236-2.236 2.236 2.236 0 0 1 2.235-2.236 2.236 2.236 0 0 1 2.236 2.236zm2.648-10.69c-1.346 0-3.107.96-4.888 2.622-1.78-1.653-3.542-2.602-4.887-2.602-.41 0-.783.093-1.106.278-1.375.793-1.683 3.264-.973 6.365C1.98 8.917 0 10.42 0 12.004c0 1.59 1.99 3.097 5.043 4.03-.704 3.113-.39 5.588.988 6.38.32.187.69.275 1.102.275 1.345 0 3.107-.96 4.888-2.624 1.78 1.654 3.542 2.603 4.887 2.603.41 0 .783-.09 1.106-.275 1.374-.792 1.683-3.263.973-6.365C22.02 15.096 24 13.59 24 12.004c0-1.59-1.99-3.097-5.043-4.032.704-3.11.39-5.587-.988-6.38-.318-.184-.688-.277-1.092-.278zm-.005 1.09v.006c.225 0 .406.044.558.127.666.382.955 1.835.73 3.704-.054.46-.142.945-.25 1.44-.96-.236-2.006-.417-3.107-.534-.66-.905-1.345-1.727-2.035-2.447 1.592-1.48 3.087-2.292 4.105-2.295zm-9.77.02c1.012 0 2.514.808 4.11 2.28-.686.72-1.37 1.537-2.02 2.442-1.107.117-2.154.298-3.113.538-.112-.49-.195-.964-.254-1.42-.23-1.868.054-3.32.714-3.707.19-.09.4-.127.563-.132zm4.882 3.05c.455.468.91.992 1.36 1.564-.44-.02-.89-.034-1.345-.034-.46 0-.915.01-1.36.034.44-.572.895-1.096 1.345-1.565zM12 8.1c.74 0 1.477.034 2.202.093.406.582.802 1.203 1.183 1.86.372.64.71 1.29 1.018 1.946-.308.655-.646 1.31-1.013 1.95-.38.66-.773 1.288-1.18 1.87-.728.063-1.466.098-2.21.098-.74 0-1.477-.035-2.202-.093-.406-.582-.802-1.204-1.183-1.86-.372-.64-.71-1.29-1.018-1.946.303-.657.646-1.313 1.013-1.954.38-.66.773-1.286 1.18-1.868.728-.064 1.466-.098 2.21-.098zm-3.635.254c-.24.377-.48.763-.704 1.16-.225.39-.435.782-.635 1.174-.265-.656-.49-1.31-.676-1.947.64-.15 1.315-.283 2.015-.386zm7.26 0c.695.103 1.365.23 2.006.387-.18.632-.405 1.282-.66 1.933-.2-.39-.41-.783-.64-1.174-.225-.392-.465-.774-.705-1.146zm3.063.675c.484.15.944.317 1.375.498 1.732.74 2.852 1.708 2.852 2.476-.005.768-1.125 1.74-2.857 2.475-.42.18-.88.342-1.355.493-.28-.958-.646-1.956-1.1-2.98.45-1.017.81-2.01 1.085-2.964zm-13.395.004c.278.96.645 1.957 1.1 2.98-.45 1.017-.812 2.01-1.086 2.964-.484-.15-.944-.318-1.37-.5-1.732-.737-2.852-1.706-2.852-2.474 0-.768 1.12-1.742 2.852-2.476.42-.18.88-.342 1.356-.494zm11.678 4.28c.265.657.49 1.312.676 1.948-.64.157-1.316.29-2.016.39.24-.375.48-.762.705-1.158.225-.39.435-.788.636-1.18zm-9.945.02c.2.392.41.783.64 1.175.23.39.465.772.705 1.143-.695-.102-1.365-.23-2.006-.386.18-.63.406-1.282.66-1.933zM17.92 16.32c.112.493.2.968.254 1.423.23 1.868-.054 3.32-.714 3.708-.147.09-.338.128-.563.128-1.012 0-2.514-.807-4.11-2.28.686-.72 1.37-1.536 2.02-2.44 1.107-.118 2.154-.3 3.113-.54zm-11.83.01c.96.234 2.006.415 3.107.532.66.905 1.345 1.727 2.035 2.446-1.595 1.483-3.092 2.295-4.11 2.295-.22-.005-.406-.05-.553-.132-.666-.38-.955-1.834-.73-3.703.054-.46.142-.944.25-1.438zm4.56.64c.44.02.89.034 1.345.034.46 0 .915-.01 1.36-.034-.44.572-.895 1.095-1.345 1.565-.455-.47-.91-.993-1.36-1.565z"
fill="currentColor"
/>
</svg>
),
tailwind: (props: IconProps) => (
<svg viewBox="0 0 24 24" {...props}>
<path
d="M12.001,4.8c-3.2,0-5.2,1.6-6,4.8c1.2-1.6,2.6-2.2,4.2-1.8c0.913,0.228,1.565,0.89,2.288,1.624 C13.666,10.618,15.027,12,18.001,12c3.2,0,5.2-1.6,6-4.8c-1.2,1.6-2.6,2.2-4.2,1.8c-0.913-0.228-1.565-0.89-2.288-1.624 C16.337,6.182,14.976,4.8,12.001,4.8z M6.001,12c-3.2,0-5.2,1.6-6,4.8c1.2-1.6,2.6-2.2,4.2-1.8c0.913,0.228,1.565,0.89,2.288,1.624 c1.177,1.194,2.538,2.576,5.512,2.576c3.2,0,5.2-1.6,6-4.8c-1.2,1.6-2.6,2.2-4.2,1.8c-0.913-0.228-1.565-0.89-2.288-1.624 C10.337,13.382,8.976,12,6.001,12z"
fill="currentColor"
/>
</svg>
),
google: (props: IconProps) => (
<svg role="img" viewBox="0 0 24 24" {...props}>
<path
fill="currentColor"
d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"
/>
</svg>
),
apple: (props: IconProps) => (
<svg role="img" viewBox="0 0 24 24" {...props}>
<path
d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"
fill="currentColor"
/>
</svg>
),
paypal: (props: IconProps) => (
<svg role="img" viewBox="0 0 24 24" {...props}>
<path
d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.106zm14.146-14.42a3.35 3.35 0 0 0-.607-.541c-.013.076-.026.175-.041.254-.93 4.778-4.005 7.201-9.138 7.201h-2.19a.563.563 0 0 0-.556.479l-1.187 7.527h-.506l-.24 1.516a.56.56 0 0 0 .554.647h3.882c.46 0 .85-.334.922-.788.06-.26.76-4.852.816-5.09a.932.932 0 0 1 .923-.788h.58c3.76 0 6.705-1.528 7.565-5.946.36-1.847.174-3.388-.777-4.471z"
fill="currentColor"
/>
</svg>
),
spinner: (props: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
{...props}
>
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
),
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/slider.tsx | "use client";
import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
import { cn } from "@/lib/utils";
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, orientation = "horizontal", ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
orientation={orientation}
className={cn(
"relative flex touch-none select-none",
orientation === "horizontal"
? "w-full items-center"
: "h-full flex-col items-center",
className
)}
{...props}
>
<SliderPrimitive.Track
className={cn(
"relative grow overflow-hidden rounded-full bg-gray-200",
orientation === "horizontal" ? "h-1.5 w-full" : "h-full w-1.5"
)}
>
<SliderPrimitive.Range
className="absolute bg-gray-500"
style={
orientation === "horizontal" ? { height: "100%" } : { width: "100%" }
}
/>
</SliderPrimitive.Track>
{[1, 2, 3, 4, 5].map((tick) => (
<div
key={tick}
className="absolute h-2 w-2 rounded-full bg-gray-500"
style={
orientation === "horizontal"
? {
left: `${((tick - 1) / 4) * 100}%`,
transform: "translateX(-50%)",
}
: {
bottom: `${((tick - 1) / 4) * 100}%`,
transform: "translateY(50%)",
}
}
/>
))}
<SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-gray-500 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
));
Slider.displayName = SliderPrimitive.Root.displayName;
export { Slider };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/inline-context-tooltip.tsx | import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card";
import { cn } from "@/lib/utils";
import { CircleHelp } from "lucide-react";
export function InlineContextTooltip({
cardContentClassName,
children,
}: {
cardContentClassName?: string;
children: React.ReactNode;
}) {
return (
<HoverCard>
<HoverCardTrigger asChild>
<span className="inline-flex items-center ml-1">
<CircleHelp className="w-3 h-3 text-gray-600" />
</span>
</HoverCardTrigger>
<HoverCardContent
className={cn(cardContentClassName, "w-[300px] text-wrap")}
>
<p className="text-black font-medium">What's this?</p>
{children}
</HoverCardContent>
</HoverCard>
);
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/toaster.tsx | "use client";
import { useToast } from "@/hooks/use-toast";
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast";
export function Toaster() {
const { toasts } = useToast();
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
);
})}
<ToastViewport />
</ToastProvider>
);
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/toast.tsx | "use client";
import * as React from "react";
import { Cross2Icon } from "@radix-ui/react-icons";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
);
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
);
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
));
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<Cross2Icon className="h-4 w-4" />
</ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold [&+div]:text-xs", className)}
{...props}
/>
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/input.tsx | import * as React from "react";
import { cn } from "@/lib/utils";
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = "Input";
export { Input };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/avatar.tsx | "use client";
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "@/lib/utils";
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/alert.tsx | import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/label.tsx | "use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/button.tsx | import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
}
);
Button.displayName = "Button";
export { Button, buttonVariants };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/dropdown-menu.tsx | "use client";
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import {
CheckIcon,
ChevronRightIcon,
DotFilledIcon,
} from "@radix-ui/react-icons";
import { cn } from "@/lib/utils";
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<DotFilledIcon className="h-4 w-4 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
);
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/dialog.tsx | "use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { Cross2Icon } from "@radix-ui/react-icons";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
hideCloseIcon?: boolean;
}
>(({ className, children, hideCloseIcon = false, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
{!hideCloseIcon && (
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<Cross2Icon className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/tooltip.tsx | "use client";
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-[9999] overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
));
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/ui/checkbox.tsx | "use client";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { CheckIcon } from "@radix-ui/react-icons";
import { cn } from "@/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<CheckIcon className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
|
0 | lc_public_repos/open-canvas/src/components/ui | lc_public_repos/open-canvas/src/components/ui/assistant-ui/tooltip-icon-button.tsx | "use client";
import { forwardRef } from "react";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { Button, ButtonProps } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export type TooltipIconButtonProps = ButtonProps & {
tooltip: string | React.ReactNode;
side?: "top" | "bottom" | "left" | "right";
/**
* @default 700
*/
delayDuration?: number;
};
export const TooltipIconButton = forwardRef<
HTMLButtonElement,
TooltipIconButtonProps
>(
(
{ children, tooltip, side = "bottom", className, delayDuration, ...rest },
ref
) => {
return (
<TooltipProvider>
<Tooltip delayDuration={delayDuration ?? 700}>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
{...rest}
className={cn("size-6 p-1", className)}
ref={ref}
>
{children}
<span className="sr-only">{tooltip}</span>
</Button>
</TooltipTrigger>
<TooltipContent side={side}>{tooltip}</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
);
TooltipIconButton.displayName = "TooltipIconButton";
|
0 | lc_public_repos/open-canvas/src/components/ui | lc_public_repos/open-canvas/src/components/ui/assistant-ui/syntax-highlighter.tsx | import { PrismAsyncLight } from "react-syntax-highlighter";
import { makePrismAsyncLightSyntaxHighlighter } from "@assistant-ui/react-syntax-highlighter";
import tsx from "react-syntax-highlighter/dist/esm/languages/prism/tsx";
import python from "react-syntax-highlighter/dist/esm/languages/prism/python";
import { coldarkDark } from "react-syntax-highlighter/dist/cjs/styles/prism";
// register languages you want to support
PrismAsyncLight.registerLanguage("js", tsx);
PrismAsyncLight.registerLanguage("jsx", tsx);
PrismAsyncLight.registerLanguage("ts", tsx);
PrismAsyncLight.registerLanguage("tsx", tsx);
PrismAsyncLight.registerLanguage("python", python);
export const SyntaxHighlighter = makePrismAsyncLightSyntaxHighlighter({
style: coldarkDark,
customStyle: {
margin: 0,
width: "100%",
background: "transparent",
padding: "1.5rem 1rem",
},
});
|
0 | lc_public_repos/open-canvas/src/components/ui | lc_public_repos/open-canvas/src/components/ui/assistant-ui/markdown-text.tsx | "use client";
import {
CodeHeaderProps,
MarkdownTextPrimitive,
useIsMarkdownCodeBlock,
} from "@assistant-ui/react-markdown";
import remarkGfm from "remark-gfm";
import rehypeKatex from "rehype-katex";
import remarkMath from "remark-math";
import { FC, memo, useState } from "react";
import { CheckIcon, CopyIcon } from "lucide-react";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import { SyntaxHighlighter } from "@/components/ui/assistant-ui/syntax-highlighter";
import { cn } from "@/lib/utils";
import "katex/dist/katex.min.css";
const MarkdownTextImpl = () => {
return (
<MarkdownTextPrimitive
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeKatex]}
components={{
h1: ({ node: _node, className, ...props }) => (
<h1
className={cn(
"mb-8 scroll-m-20 text-4xl font-extrabold tracking-tight last:mb-0",
className
)}
{...props}
/>
),
h2: ({ node: _node, className, ...props }) => (
<h2
className={cn(
"mb-4 mt-8 scroll-m-20 text-3xl font-semibold tracking-tight first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
h3: ({ node: _node, className, ...props }) => (
<h3
className={cn(
"mb-4 mt-6 scroll-m-20 text-2xl font-semibold tracking-tight first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
h4: ({ node: _node, className, ...props }) => (
<h4
className={cn(
"mb-4 mt-6 scroll-m-20 text-xl font-semibold tracking-tight first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
h5: ({ node: _node, className, ...props }) => (
<h5
className={cn(
"my-4 text-lg font-semibold first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
h6: ({ node: _node, className, ...props }) => (
<h6
className={cn("my-4 font-semibold first:mt-0 last:mb-0", className)}
{...props}
/>
),
p: ({ node: _node, className, ...props }) => (
<p
className={cn(
"mb-5 mt-5 leading-7 first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
a: ({ node: _node, className, ...props }) => (
<a
target="_blank"
className={cn(
"text-primary font-medium underline underline-offset-4",
className
)}
{...props}
/>
),
blockquote: ({ node: _node, className, ...props }) => (
<blockquote
className={cn("border-l-2 pl-6 italic", className)}
{...props}
/>
),
ul: ({ node: _node, className, ...props }) => (
<ul
className={cn("my-5 ml-6 list-disc [&>li]:mt-2", className)}
{...props}
/>
),
ol: ({ node: _node, className, ...props }) => (
<ol
className={cn("my-5 ml-6 list-decimal [&>li]:mt-2", className)}
{...props}
/>
),
hr: ({ node: _node, className, ...props }) => (
<hr className={cn("my-5 border-b", className)} {...props} />
),
table: ({ node: _node, className, ...props }) => (
<table
className={cn(
"my-5 w-full border-separate border-spacing-0 overflow-y-auto",
className
)}
{...props}
/>
),
th: ({ node: _node, className, ...props }) => (
<th
className={cn(
"bg-muted px-4 py-2 text-left font-bold first:rounded-tl-lg last:rounded-tr-lg [&[align=center]]:text-center [&[align=right]]:text-right",
className
)}
{...props}
/>
),
td: ({ node: _node, className, ...props }) => (
<td
className={cn(
"border-b border-l px-4 py-2 text-left last:border-r [&[align=center]]:text-center [&[align=right]]:text-right",
className
)}
{...props}
/>
),
tr: ({ node: _node, className, ...props }) => (
<tr
className={cn(
"m-0 border-b p-0 first:border-t [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg",
className
)}
{...props}
/>
),
sup: ({ node: _node, className, ...props }) => (
<sup
className={cn("[&>a]:text-xs [&>a]:no-underline", className)}
{...props}
/>
),
pre: ({ node: _node, className, ...props }) => (
<pre
className={cn(
"overflow-x-auto rounded-b-lg bg-black p-4 text-white",
className
)}
{...props}
/>
),
code: function Code({ node: _node, className, ...props }) {
const isCodeBlock = useIsMarkdownCodeBlock();
return (
<code
className={cn(
!isCodeBlock && "bg-aui-muted rounded border font-semibold",
className
)}
{...props}
/>
);
},
CodeHeader,
SyntaxHighlighter,
}}
/>
);
};
export const MarkdownText = memo(MarkdownTextImpl);
const CodeHeader: FC<CodeHeaderProps> = ({ language, code }) => {
const { isCopied, copyToClipboard } = useCopyToClipboard();
const onCopy = () => {
if (!code || isCopied) return;
copyToClipboard(code);
};
return (
<div className="flex items-center justify-between gap-4 rounded-t-lg bg-zinc-900 px-4 py-2 text-sm font-semibold text-white">
<span className="lowercase [&>span]:text-xs">{language}</span>
<TooltipIconButton tooltip="Copy" onClick={onCopy}>
{!isCopied && <CopyIcon />}
{isCopied && <CheckIcon />}
</TooltipIconButton>
</div>
);
};
const useCopyToClipboard = ({
copiedDuration = 3000,
}: {
copiedDuration?: number;
} = {}) => {
const [isCopied, setIsCopied] = useState<boolean>(false);
const copyToClipboard = (value: string) => {
if (!value) return;
navigator.clipboard.writeText(value).then(() => {
setIsCopied(true);
setTimeout(() => setIsCopied(false), copiedDuration);
});
};
return { isCopied, copyToClipboard };
};
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/tool-hooks/LangSmithLinkToolUI.tsx | import { ExternalLink } from "lucide-react";
import { LangSmithSVG } from "../icons/langsmith";
import { TooltipIconButton } from "../ui/assistant-ui/tooltip-icon-button";
import { useAssistantToolUI } from "@assistant-ui/react";
import { useCallback } from "react";
export const useLangSmithLinkToolUI = () =>
useAssistantToolUI({
toolName: "langsmith_tool_ui",
render: useCallback((input) => {
return (
<TooltipIconButton
tooltip="View run in LangSmith"
variant="ghost"
className="transition-colors w-4 h-3 ml-3 mt-2 mb-[-8px]"
delayDuration={400}
onClick={() => window.open(input.args.sharedRunURL, "_blank")}
>
<span className="flex flex-row items-center gap-1 w-11 h-7">
<ExternalLink />
<LangSmithSVG className="text-[#CA632B] hover:text-[#CA632B]/95" />
</span>
</TooltipIconButton>
);
}, []),
});
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/reflections-dialog/ConfirmClearDialog.tsx | import { useState } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogDescription,
DialogTrigger,
} from "../ui/dialog";
import { Button } from "../ui/button";
import { TighterText } from "../ui/header";
export interface ReflectionsProps {
handleDeleteReflections: () => Promise<boolean>;
}
export function ConfirmClearDialog(props: ReflectionsProps) {
const { handleDeleteReflections } = props;
const [open, setOpen] = useState(false);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button onClick={() => setOpen(true)} variant="destructive">
<TighterText>Clear reflections</TighterText>
</Button>
</DialogTrigger>
<DialogContent className="max-w-xl p-8 bg-white rounded-lg shadow-xl">
<DialogHeader>
<DialogDescription className="mt-2 text-md text-center font-light text-red-500">
<TighterText>
Are you sure you want to clear all reflections? This action can
not be undone.
</TighterText>
</DialogDescription>
</DialogHeader>
<Button
onClick={async () => {
setOpen(false);
await handleDeleteReflections();
}}
variant="destructive"
>
<TighterText>Clear reflections</TighterText>
</Button>
<div className="mt-6 flex justify-end">
<Button onClick={() => setOpen(false)} variant="outline">
<TighterText>Cancel</TighterText>
</Button>
</div>
</DialogContent>
</Dialog>
);
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/reflections-dialog/ReflectionsDialog.tsx | import { useEffect, useState } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogTrigger,
} from "../ui/dialog";
import { Button } from "../ui/button";
import { BrainCog, Loader } from "lucide-react";
import { ConfirmClearDialog } from "./ConfirmClearDialog";
import { TooltipIconButton } from "../ui/assistant-ui/tooltip-icon-button";
import { TighterText } from "../ui/header";
import { useStore } from "@/hooks/useStore";
import { useToast } from "@/hooks/use-toast";
import { Assistant } from "@langchain/langgraph-sdk";
import { Badge } from "../ui/badge";
import { getIcon } from "../assistant-select/utils";
export interface NoReflectionsProps {
selectedAssistant: Assistant | undefined;
getReflections: (assistantId: string) => Promise<void>;
}
function NoReflections(props: NoReflectionsProps) {
const { selectedAssistant } = props;
const { toast } = useToast();
const getReflections = async () => {
if (!selectedAssistant) {
toast({
title: "Error",
description: "Assistant ID not found.",
variant: "destructive",
duration: 5000,
});
return;
}
await props.getReflections(selectedAssistant.assistant_id);
};
return (
<div className="flex flex-col items-center mt-6 mb-[-24px] gap-3">
<TighterText>No reflections have been generated yet.</TighterText>
<TighterText className="text-sm text-gray-500">
Reflections generate after 30s of inactivity. If none appear, try again
later.
</TighterText>
<Button onClick={getReflections} variant="secondary" size="sm">
<TighterText>Search for reflections</TighterText>
</Button>
</div>
);
}
interface ReflectionsDialogProps {
selectedAssistant: Assistant | undefined;
}
export function ReflectionsDialog(props: ReflectionsDialogProps) {
const { toast } = useToast();
const [open, setOpen] = useState(false);
const { selectedAssistant } = props;
const {
isLoadingReflections,
reflections,
getReflections,
deleteReflections,
} = useStore();
useEffect(() => {
if (!selectedAssistant || typeof window === "undefined") return;
// Don't re-fetch reflections if they already exist & are for the same assistant
if (
(reflections?.content || reflections?.styleRules) &&
reflections.assistantId === selectedAssistant.assistant_id
)
return;
getReflections(selectedAssistant.assistant_id);
}, [selectedAssistant]);
const handleDelete = async () => {
if (!selectedAssistant) {
toast({
title: "Error",
description: "Assistant ID not found.",
variant: "destructive",
duration: 5000,
});
return false;
}
setOpen(false);
return await deleteReflections(selectedAssistant.assistant_id);
};
const iconData = (selectedAssistant?.metadata as Record<string, any>)
?.iconData;
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<TooltipIconButton
tooltip="Reflections"
variant="ghost"
className="w-fit h-fit p-2"
onClick={() => setOpen(true)}
>
<BrainCog className="w-6 h-6 text-gray-600" />
</TooltipIconButton>
</DialogTrigger>
<DialogContent className="max-w-xl p-8 bg-white rounded-lg shadow-xl">
<DialogHeader>
<DialogTitle className="flex items-center justify-between">
<TighterText className="text-3xl font-light text-gray-800">
Reflections
</TighterText>
{selectedAssistant && (
<Badge
style={{
...(iconData
? {
color: iconData.iconColor,
backgroundColor: `${iconData.iconColor}20`, // 33 in hex is ~20% opacity
}
: {
color: "#000000",
backgroundColor: "#00000020",
}),
}}
className="flex items-center justify-center gap-2 px-2 py-1"
>
<span className="flex items-center justify-start w-4 h-4">
{getIcon(
(selectedAssistant?.metadata as Record<string, any>)
?.iconData?.iconName
)}
</span>
{selectedAssistant?.name}
</Badge>
)}
</DialogTitle>
<DialogDescription className="mt-2 text-md font-light text-gray-600">
<TighterText>
{isLoadingReflections ? (
"Loading reflections..."
) : reflections?.content || reflections?.styleRules ? (
"Current reflections generated by the assistant for content generation."
) : (
<NoReflections
selectedAssistant={selectedAssistant}
getReflections={getReflections}
/>
)}
</TighterText>
</DialogDescription>
</DialogHeader>
<div className="mt-6 max-h-[60vh] overflow-y-auto pr-4 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
{isLoadingReflections ? (
<div className="flex justify-center items-center h-32">
<Loader className="h-8 w-8 animate-spin" />
</div>
) : reflections?.content || reflections?.styleRules ? (
<>
{reflections?.styleRules && (
<div className="mb-6">
<TighterText className="text-xl font-light text-gray-800 sticky top-0 bg-white py-2 mb-3">
Style Reflections:
</TighterText>
<ul className="list-disc list-inside space-y-2">
{reflections.styleRules?.map((rule, index) => (
<li key={index} className="flex items-baseline">
<span className="mr-2">•</span>
<TighterText className="text-gray-600 font-light">
{rule}
</TighterText>
</li>
))}
</ul>
</div>
)}
{reflections?.content && (
<div className="mb-6">
<TighterText className="text-xl font-light text-gray-800 sticky top-0 bg-white py-2 mb-3">
Content Reflections:
</TighterText>
<ul className="list-disc list-inside space-y-2">
{reflections.content.map((rule, index) => (
<li key={index} className="flex items-baseline">
<span className="mr-2">•</span>
<TighterText className="text-gray-600 font-light">
{rule}
</TighterText>
</li>
))}
</ul>
</div>
)}
</>
) : null}
</div>
<div className="mt-6 flex justify-between">
{reflections?.content || reflections?.styleRules ? (
<ConfirmClearDialog handleDeleteReflections={handleDelete} />
) : null}
<Button
onClick={() => setOpen(false)}
className="bg-black hover:bg-gray-800 text-white px-4 py-2 rounded shadow transition"
>
<TighterText>Close</TighterText>
</Button>
</div>
</DialogContent>
</Dialog>
);
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/icons/flags.tsx | export const UsaFlag = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 32 32"
>
<rect x="1" y="4" width="30" height="24" rx="4" ry="4" fill="#fff"></rect>
<path
d="M1.638,5.846H30.362c-.711-1.108-1.947-1.846-3.362-1.846H5c-1.414,0-2.65,.738-3.362,1.846Z"
fill="#a62842"
></path>
<path
d="M2.03,7.692c-.008,.103-.03,.202-.03,.308v1.539H31v-1.539c0-.105-.022-.204-.03-.308H2.03Z"
fill="#a62842"
></path>
<path fill="#a62842" d="M2 11.385H31V13.231H2z"></path>
<path fill="#a62842" d="M2 15.077H31V16.923000000000002H2z"></path>
<path fill="#a62842" d="M1 18.769H31V20.615H1z"></path>
<path
d="M1,24c0,.105,.023,.204,.031,.308H30.969c.008-.103,.031-.202,.031-.308v-1.539H1v1.539Z"
fill="#a62842"
></path>
<path
d="M30.362,26.154H1.638c.711,1.108,1.947,1.846,3.362,1.846H27c1.414,0,2.65-.738,3.362-1.846Z"
fill="#a62842"
></path>
<path d="M5,4h11v12.923H1V8c0-2.208,1.792-4,4-4Z" fill="#102d5e"></path>
<path
d="M27,4H5c-2.209,0-4,1.791-4,4V24c0,2.209,1.791,4,4,4H27c2.209,0,4-1.791,4-4V8c0-2.209-1.791-4-4-4Zm3,20c0,1.654-1.346,3-3,3H5c-1.654,0-3-1.346-3-3V8c0-1.654,1.346-3,3-3H27c1.654,0,3,1.346,3,3V24Z"
opacity=".15"
></path>
<path
d="M27,5H5c-1.657,0-3,1.343-3,3v1c0-1.657,1.343-3,3-3H27c1.657,0,3,1.343,3,3v-1c0-1.657-1.343-3-3-3Z"
fill="#fff"
opacity=".2"
></path>
<path
fill="#fff"
d="M4.601 7.463L5.193 7.033 4.462 7.033 4.236 6.338 4.01 7.033 3.279 7.033 3.87 7.463 3.644 8.158 4.236 7.729 4.827 8.158 4.601 7.463z"
></path>
<path
fill="#fff"
d="M7.58 7.463L8.172 7.033 7.441 7.033 7.215 6.338 6.989 7.033 6.258 7.033 6.849 7.463 6.623 8.158 7.215 7.729 7.806 8.158 7.58 7.463z"
></path>
<path
fill="#fff"
d="M10.56 7.463L11.151 7.033 10.42 7.033 10.194 6.338 9.968 7.033 9.237 7.033 9.828 7.463 9.603 8.158 10.194 7.729 10.785 8.158 10.56 7.463z"
></path>
<path
fill="#fff"
d="M6.066 9.283L6.658 8.854 5.927 8.854 5.701 8.158 5.475 8.854 4.744 8.854 5.335 9.283 5.109 9.979 5.701 9.549 6.292 9.979 6.066 9.283z"
></path>
<path
fill="#fff"
d="M9.046 9.283L9.637 8.854 8.906 8.854 8.68 8.158 8.454 8.854 7.723 8.854 8.314 9.283 8.089 9.979 8.68 9.549 9.271 9.979 9.046 9.283z"
></path>
<path
fill="#fff"
d="M12.025 9.283L12.616 8.854 11.885 8.854 11.659 8.158 11.433 8.854 10.702 8.854 11.294 9.283 11.068 9.979 11.659 9.549 12.251 9.979 12.025 9.283z"
></path>
<path
fill="#fff"
d="M6.066 12.924L6.658 12.494 5.927 12.494 5.701 11.799 5.475 12.494 4.744 12.494 5.335 12.924 5.109 13.619 5.701 13.19 6.292 13.619 6.066 12.924z"
></path>
<path
fill="#fff"
d="M9.046 12.924L9.637 12.494 8.906 12.494 8.68 11.799 8.454 12.494 7.723 12.494 8.314 12.924 8.089 13.619 8.68 13.19 9.271 13.619 9.046 12.924z"
></path>
<path
fill="#fff"
d="M12.025 12.924L12.616 12.494 11.885 12.494 11.659 11.799 11.433 12.494 10.702 12.494 11.294 12.924 11.068 13.619 11.659 13.19 12.251 13.619 12.025 12.924z"
></path>
<path
fill="#fff"
d="M13.539 7.463L14.13 7.033 13.399 7.033 13.173 6.338 12.947 7.033 12.216 7.033 12.808 7.463 12.582 8.158 13.173 7.729 13.765 8.158 13.539 7.463z"
></path>
<path
fill="#fff"
d="M4.601 11.104L5.193 10.674 4.462 10.674 4.236 9.979 4.01 10.674 3.279 10.674 3.87 11.104 3.644 11.799 4.236 11.369 4.827 11.799 4.601 11.104z"
></path>
<path
fill="#fff"
d="M7.58 11.104L8.172 10.674 7.441 10.674 7.215 9.979 6.989 10.674 6.258 10.674 6.849 11.104 6.623 11.799 7.215 11.369 7.806 11.799 7.58 11.104z"
></path>
<path
fill="#fff"
d="M10.56 11.104L11.151 10.674 10.42 10.674 10.194 9.979 9.968 10.674 9.237 10.674 9.828 11.104 9.603 11.799 10.194 11.369 10.785 11.799 10.56 11.104z"
></path>
<path
fill="#fff"
d="M13.539 11.104L14.13 10.674 13.399 10.674 13.173 9.979 12.947 10.674 12.216 10.674 12.808 11.104 12.582 11.799 13.173 11.369 13.765 11.799 13.539 11.104z"
></path>
<path
fill="#fff"
d="M4.601 14.744L5.193 14.315 4.462 14.315 4.236 13.619 4.01 14.315 3.279 14.315 3.87 14.744 3.644 15.44 4.236 15.01 4.827 15.44 4.601 14.744z"
></path>
<path
fill="#fff"
d="M7.58 14.744L8.172 14.315 7.441 14.315 7.215 13.619 6.989 14.315 6.258 14.315 6.849 14.744 6.623 15.44 7.215 15.01 7.806 15.44 7.58 14.744z"
></path>
<path
fill="#fff"
d="M10.56 14.744L11.151 14.315 10.42 14.315 10.194 13.619 9.968 14.315 9.237 14.315 9.828 14.744 9.603 15.44 10.194 15.01 10.785 15.44 10.56 14.744z"
></path>
<path
fill="#fff"
d="M13.539 14.744L14.13 14.315 13.399 14.315 13.173 13.619 12.947 14.315 12.216 14.315 12.808 14.744 12.582 15.44 13.173 15.01 13.765 15.44 13.539 14.744z"
></path>
</svg>
);
export const ChinaFlag = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 32 32"
>
<rect
x="1"
y="4"
width="30"
height="24"
rx="4"
ry="4"
fill="#db362f"
></rect>
<path
d="M27,4H5c-2.209,0-4,1.791-4,4V24c0,2.209,1.791,4,4,4H27c2.209,0,4-1.791,4-4V8c0-2.209-1.791-4-4-4Zm3,20c0,1.654-1.346,3-3,3H5c-1.654,0-3-1.346-3-3V8c0-1.654,1.346-3,3-3H27c1.654,0,3,1.346,3,3V24Z"
opacity=".15"
></path>
<path
fill="#ff0"
d="M7.958 10.152L7.19 7.786 6.421 10.152 3.934 10.152 5.946 11.614 5.177 13.979 7.19 12.517 9.202 13.979 8.433 11.614 10.446 10.152 7.958 10.152z"
></path>
<path
fill="#ff0"
d="M12.725 8.187L13.152 8.898 13.224 8.072 14.032 7.886 13.269 7.562 13.342 6.736 12.798 7.361 12.035 7.037 12.461 7.748 11.917 8.373 12.725 8.187z"
></path>
<path
fill="#ff0"
d="M14.865 10.372L14.982 11.193 15.37 10.46 16.187 10.602 15.61 10.007 15.997 9.274 15.253 9.639 14.675 9.044 14.793 9.865 14.048 10.23 14.865 10.372z"
></path>
<path
fill="#ff0"
d="M15.597 13.612L16.25 13.101 15.421 13.13 15.137 12.352 14.909 13.149 14.081 13.179 14.769 13.642 14.541 14.439 15.194 13.928 15.881 14.391 15.597 13.612z"
></path>
<path
fill="#ff0"
d="M13.26 15.535L13.298 14.707 12.78 15.354 12.005 15.062 12.46 15.754 11.942 16.402 12.742 16.182 13.198 16.875 13.236 16.047 14.036 15.827 13.26 15.535z"
></path>
<path
d="M27,5H5c-1.657,0-3,1.343-3,3v1c0-1.657,1.343-3,3-3H27c1.657,0,3,1.343,3,3v-1c0-1.657-1.343-3-3-3Z"
fill="#fff"
opacity=".2"
></path>
</svg>
);
export const IndiaFlag = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 32 32"
>
<path fill="#fff" d="M1 11H31V21H1z"></path>
<path
d="M5,4H27c2.208,0,4,1.792,4,4v4H1v-4c0-2.208,1.792-4,4-4Z"
fill="#e06535"
></path>
<path
d="M5,20H27c2.208,0,4,1.792,4,4v4H1v-4c0-2.208,1.792-4,4-4Z"
transform="rotate(180 16 24)"
fill="#2c6837"
></path>
<path
d="M27,4H5c-2.209,0-4,1.791-4,4V24c0,2.209,1.791,4,4,4H27c2.209,0,4-1.791,4-4V8c0-2.209-1.791-4-4-4Zm3,20c0,1.654-1.346,3-3,3H5c-1.654,0-3-1.346-3-3V8c0-1.654,1.346-3,3-3H27c1.654,0,3,1.346,3,3V24Z"
opacity=".15"
></path>
<path
d="M16,12.292c-2.048,0-3.708,1.66-3.708,3.708s1.66,3.708,3.708,3.708,3.708-1.66,3.708-3.708-1.66-3.708-3.708-3.708Zm3.041,4.109c-.01,.076,.042,.145,.117,.157-.033,.186-.08,.367-.143,.54-.071-.028-.152,.006-.181,.077-.029,.071,.004,.151,.073,.182-.04,.085-.083,.167-.13,.248l-1.611-1.069-.592-.249c.013-.026,.024-.053,.034-.081l.595,.242,1.895,.383-1.833-.616-.636-.087c.006-.028,.009-.057,.011-.087l.638,.08,1.93-.12-1.93-.12-.638,.08c-.002-.03-.005-.059-.011-.087l.636-.087,1.833-.616-1.895,.383-.595,.242c-.009-.028-.021-.055-.034-.081l.592-.249,1.611-1.069c.047,.081,.09,.163,.13,.248-.07,.031-.103,.111-.073,.182,.029,.071,.11,.105,.181,.077,.063,.173,.111,.354,.143,.54-.075,.012-.127,.081-.117,.157,.01,.076,.078,.129,.154,.121,.008,.092,.013,.185,.013,.279s-.005,.187-.013,.279c-.075-.008-.144,.045-.154,.121Zm-.584-2.462c-.059,.048-.07,.134-.023,.194,.046,.06,.132,.072,.194,.028,.053,.076,.104,.155,.15,.236l-1.731,.861-.512,.388c-.016-.024-.034-.047-.054-.069l.508-.394,1.28-1.45-1.45,1.28-.394,.508c-.022-.019-.045-.038-.069-.054l.388-.512,.861-1.731c.081,.047,.16,.097,.236,.15-.045,.061-.033,.147,.028,.194,.061,.046,.147,.036,.194-.023,.071,.06,.141,.123,.207,.189,.066,.066,.129,.135,.189,.207Zm-2.177-1.133c-.008,.075,.045,.144,.121,.154,.076,.01,.145-.042,.157-.117,.186,.033,.367,.08,.54,.143-.028,.071,.006,.152,.077,.181,.071,.029,.151-.004,.182-.073,.085,.04,.167,.083,.248,.13l-1.069,1.611-.249,.592c-.026-.013-.053-.024-.081-.034l.242-.595,.383-1.895-.616,1.833-.087,.636c-.028-.006-.057-.009-.087-.011l.08-.638-.12-1.93-.12,1.93,.08,.638c-.03,.002-.059,.005-.087,.011l-.087-.636-.616-1.833,.383,1.895,.242,.595c-.028,.009-.055,.021-.081,.034l-.249-.592-1.069-1.611c.081-.047,.163-.09,.248-.13,.031,.07,.111,.103,.182,.073,.071-.029,.105-.11,.077-.181,.173-.063,.354-.111,.54-.143,.012,.075,.081,.127,.157,.117,.076-.01,.129-.078,.121-.154,.092-.008,.185-.013,.279-.013s.187,.005,.279,.013Zm-3.113,4.368c-.029-.071-.11-.105-.181-.077-.063-.173-.111-.354-.143-.54,.075-.012,.127-.081,.117-.157-.01-.076-.078-.129-.154-.121-.008-.092-.013-.185-.013-.279s.005-.187,.013-.279c.075,.008,.144-.045,.154-.121,.01-.076-.042-.145-.117-.157,.033-.186,.08-.367,.143-.54,.071,.028,.152-.006,.181-.077,.029-.071-.004-.151-.073-.182,.04-.085,.083-.167,.13-.248l1.611,1.069,.592,.249c-.013,.026-.024,.053-.034,.081l-.595-.242-1.895-.383,1.833,.616,.636,.087c-.006,.028-.009,.057-.011,.087l-.638-.08-1.93,.12,1.93,.12,.638-.08c.002,.03,.005,.059,.011,.087l-.636,.087-1.833,.616,1.895-.383,.595-.242c.009,.028,.021,.055,.034,.081l-.592,.249-1.611,1.069c-.047-.081-.09-.163-.13-.248,.07-.031,.103-.111,.073-.182Zm.772-3.63c.048,.059,.134,.07,.194,.023,.06-.046,.072-.132,.028-.194,.076-.053,.155-.104,.236-.15l.861,1.731,.388,.512c-.024,.016-.047,.034-.069,.054l-.394-.508-1.45-1.28,1.28,1.45,.508,.394c-.019,.022-.038,.045-.054,.069l-.512-.388-1.731-.861c.047-.081,.097-.16,.15-.236,.061,.045,.147,.033,.194-.028,.046-.061,.036-.147-.023-.194,.06-.071,.123-.141,.189-.207s.135-.129,.207-.189Zm-.395,4.518c.059-.048,.07-.134,.023-.194-.046-.06-.132-.072-.194-.028-.053-.076-.104-.155-.15-.236l1.731-.861,.512-.388c.016,.024,.034,.047,.054,.069l-.508,.394-1.28,1.45,1.45-1.28,.394-.508c.022,.019,.045,.038,.069,.054l-.388,.512-.861,1.731c-.081-.047-.16-.097-.236-.15,.045-.061,.033-.147-.028-.194-.061-.046-.147-.036-.194,.023-.071-.06-.141-.123-.207-.189-.066-.066-.129-.135-.189-.207Zm2.177,1.133c.008-.075-.045-.144-.121-.154-.076-.01-.145,.042-.157,.117-.186-.033-.367-.08-.54-.143,.028-.071-.006-.152-.077-.181-.071-.029-.151,.004-.182,.073-.085-.04-.167-.083-.248-.13l1.069-1.611,.249-.592c.026,.013,.053,.024,.081,.034l-.242,.595-.383,1.895,.616-1.833,.087-.636c.028,.006,.057,.009,.087,.011l-.08,.638,.12,1.93,.12-1.93-.08-.638c.03-.002,.059-.005,.087-.011l.087,.636,.616,1.833-.383-1.895-.242-.595c.028-.009,.055-.021,.081-.034l.249,.592,1.069,1.611c-.081,.047-.163,.09-.248,.13-.031-.07-.111-.103-.182-.073-.071,.029-.105,.11-.077,.181-.173,.063-.354,.111-.54,.143-.012-.075-.081-.127-.157-.117-.076,.01-.129,.078-.121,.154-.092,.008-.185,.013-.279,.013s-.187-.005-.279-.013Zm2.341-.738c-.048-.059-.134-.07-.194-.023-.06,.046-.072,.132-.028,.194-.076,.053-.155,.104-.236,.15l-.861-1.731-.388-.512c.024-.016,.047-.034,.069-.054l.394,.508,1.45,1.28-1.28-1.45-.508-.394c.019-.022,.038-.045,.054-.069l.512,.388,1.731,.861c-.047,.081-.097,.16-.15,.236-.061-.045-.147-.033-.194,.028-.046,.061-.036,.147,.023,.194-.06,.071-.123,.141-.189,.207s-.135,.129-.207,.189Z"
fill="#2c2c6b"
></path>
<path
d="M27,5H5c-1.657,0-3,1.343-3,3v1c0-1.657,1.343-3,3-3H27c1.657,0,3,1.343,3,3v-1c0-1.657-1.343-3-3-3Z"
fill="#fff"
opacity=".2"
></path>
</svg>
);
export const FrenchFlag = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 32 32"
>
<path fill="#fff" d="M10 4H22V28H10z"></path>
<path
d="M5,4h6V28H5c-2.208,0-4-1.792-4-4V8c0-2.208,1.792-4,4-4Z"
fill="#092050"
></path>
<path
d="M25,4h6V28h-6c-2.208,0-4-1.792-4-4V8c0-2.208,1.792-4,4-4Z"
transform="rotate(180 26 16)"
fill="#be2a2c"
></path>
<path
d="M27,4H5c-2.209,0-4,1.791-4,4V24c0,2.209,1.791,4,4,4H27c2.209,0,4-1.791,4-4V8c0-2.209-1.791-4-4-4Zm3,20c0,1.654-1.346,3-3,3H5c-1.654,0-3-1.346-3-3V8c0-1.654,1.346-3,3-3H27c1.654,0,3,1.346,3,3V24Z"
opacity=".15"
></path>
<path
d="M27,5H5c-1.657,0-3,1.343-3,3v1c0-1.657,1.343-3,3-3H27c1.657,0,3,1.343,3,3v-1c0-1.657-1.343-3-3-3Z"
fill="#fff"
opacity=".2"
></path>
</svg>
);
export const SpanishFlag = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 32 32"
>
<path fill="#f1c142" d="M1 10H31V22H1z"></path>
<path
d="M5,4H27c2.208,0,4,1.792,4,4v3H1v-3c0-2.208,1.792-4,4-4Z"
fill="#a0251e"
></path>
<path
d="M5,21H27c2.208,0,4,1.792,4,4v3H1v-3c0-2.208,1.792-4,4-4Z"
transform="rotate(180 16 24.5)"
fill="#a0251e"
></path>
<path
d="M27,4H5c-2.209,0-4,1.791-4,4V24c0,2.209,1.791,4,4,4H27c2.209,0,4-1.791,4-4V8c0-2.209-1.791-4-4-4Zm3,20c0,1.654-1.346,3-3,3H5c-1.654,0-3-1.346-3-3V8c0-1.654,1.346-3,3-3H27c1.654,0,3,1.346,3,3V24Z"
opacity=".15"
></path>
<path
d="M27,5H5c-1.657,0-3,1.343-3,3v1c0-1.657,1.343-3,3-3H27c1.657,0,3,1.343,3,3v-1c0-1.657-1.343-3-3-3Z"
fill="#fff"
opacity=".2"
></path>
<path
d="M12.614,13.091c.066-.031,.055-.14-.016-.157,.057-.047,.02-.15-.055-.148,.04-.057-.012-.144-.082-.13,.021-.062-.042-.127-.104-.105,.01-.068-.071-.119-.127-.081,.004-.068-.081-.112-.134-.069-.01-.071-.11-.095-.15-.035-.014-.068-.111-.087-.149-.028-.027-.055-.114-.057-.144-.004-.03-.047-.107-.045-.136,.002-.018-.028-.057-.044-.09-.034,.009-.065-.066-.115-.122-.082,.002-.07-.087-.111-.138-.064-.013-.064-.103-.087-.144-.036-.02-.063-.114-.075-.148-.017-.036-.056-.129-.042-.147,.022-.041-.055-.135-.031-.146,.036-.011-.008-.023-.014-.037-.016,.006-.008,.01-.016,.015-.025h.002c.058-.107,.004-.256-.106-.298v-.098h.099v-.154h-.099v-.101h-.151v.101h-.099v.154h.099v.096c-.113,.04-.169,.191-.11,.299h.002c.004,.008,.009,.017,.014,.024-.015,.002-.029,.008-.04,.017-.011-.067-.106-.091-.146-.036-.018-.064-.111-.078-.147-.022-.034-.057-.128-.046-.148,.017-.041-.052-.131-.028-.144,.036-.051-.047-.139-.006-.138,.064-.056-.033-.131,.017-.122,.082-.034-.01-.072,.006-.091,.034-.029-.047-.106-.049-.136-.002-.03-.054-.117-.051-.143,.004-.037-.059-.135-.04-.149,.028-.039-.06-.14-.037-.15,.035-.053-.043-.138,0-.134,.069-.056-.038-.137,.013-.127,.081-.062-.021-.125,.044-.104,.105-.05-.009-.096,.033-.096,.084h0c0,.017,.005,.033,.014,.047-.075-.002-.111,.101-.055,.148-.071,.017-.082,.125-.016,.157-.061,.035-.047,.138,.022,.154-.013,.015-.021,.034-.021,.055h0c0,.042,.03,.077,.069,.084-.023,.048,.009,.11,.06,.118-.013,.03-.012,.073-.012,.106,.09-.019,.2,.006,.239,.11-.015,.068,.065,.156,.138,.146,.06,.085,.133,.165,.251,.197-.021,.093,.064,.093,.123,.118-.013,.016-.043,.063-.055,.081,.024,.013,.087,.041,.113,.051,.005,.019,.004,.028,.004,.031,.091,.501,2.534,.502,2.616-.001v-.002s.004,.003,.004,.004c0-.003-.001-.011,.004-.031l.118-.042-.062-.09c.056-.028,.145-.025,.123-.119,.119-.032,.193-.112,.253-.198,.073,.01,.153-.078,.138-.146,.039-.104,.15-.129,.239-.11,0-.035,.002-.078-.013-.109,.044-.014,.07-.071,.049-.115,.062-.009,.091-.093,.048-.139,.069-.016,.083-.12,.022-.154Zm-.296-.114c0,.049-.012,.098-.034,.141-.198-.137-.477-.238-.694-.214-.002-.009-.006-.017-.011-.024,0,0,0-.001,0-.002,.064-.021,.074-.12,.015-.153,0,0,0,0,0,0,.048-.032,.045-.113-.005-.141,.328-.039,.728,.09,.728,.393Zm-.956-.275c0,.063-.02,.124-.054,.175-.274-.059-.412-.169-.717-.185-.007-.082-.005-.171-.011-.254,.246-.19,.81-.062,.783,.264Zm-1.191-.164c-.002,.05-.003,.102-.007,.151-.302,.013-.449,.122-.719,.185-.26-.406,.415-.676,.73-.436-.002,.033-.005,.067-.004,.101Zm-1.046,.117c0,.028,.014,.053,.034,.069,0,0,0,0,0,0-.058,.033-.049,.132,.015,.152,0,0,0,.001,0,.002-.005,.007-.008,.015-.011,.024-.219-.024-.495,.067-.698,.206-.155-.377,.323-.576,.698-.525-.023,.015-.039,.041-.039,.072Zm3.065-.115s0,0,0,0c0,0,0,0,0,0,0,0,0,0,0,0Zm-3.113,1.798v.002s-.002,0-.003,.002c0-.001,.002-.003,.003-.003Z"
fill="#9b8028"
></path>
<path
d="M14.133,16.856c.275-.65,.201-.508-.319-.787v-.873c.149-.099-.094-.121,.05-.235h.072v-.339h-.99v.339h.075c.136,.102-.091,.146,.05,.235v.76c-.524-.007-.771,.066-.679,.576h.039s0,0,0,0l.016,.036c.14-.063,.372-.107,.624-.119v.224c-.384,.029-.42,.608,0,.8v1.291c-.053,.017-.069,.089-.024,.123,.007,.065-.058,.092-.113,.083,0,.026,0,.237,0,.269-.044,.024-.113,.03-.17,.028v.108s0,0,0,0v.107s0,0,0,0v.107s0,0,0,0v.108s0,0,0,0v.186c.459-.068,.895-.068,1.353,0v-.616c-.057,.002-.124-.004-.17-.028,0-.033,0-.241,0-.268-.054,.008-.118-.017-.113-.081,.048-.033,.034-.108-.021-.126v-.932c.038,.017,.073,.035,.105,.053-.105,.119-.092,.326,.031,.429l.057-.053c.222-.329,.396-.743-.193-.896v-.35c.177-.019,.289-.074,.319-.158Z"
fill="#9b8028"
></path>
<path
d="M8.36,16.058c-.153-.062-.39-.098-.653-.102v-.76c.094-.041,.034-.115-.013-.159,.02-.038,.092-.057,.056-.115h.043v-.261h-.912v.261h.039c-.037,.059,.039,.078,.057,.115-.047,.042-.108,.118-.014,.159v.873c-.644,.133-.611,.748,0,.945v.35c-.59,.154-.415,.567-.193,.896l.057,.053c.123-.103,.136-.31,.031-.429,.032-.018,.067-.036,.105-.053v.932c-.055,.018-.069,.093-.021,.126,.005,.064-.059,.089-.113,.081,0,.026,0,.236,0,.268-.045,.024-.113,.031-.17,.028v.401h0v.215c.459-.068,.895-.068,1.352,0v-.186s0,0,0,0v-.108s0,0,0,0v-.107s0,0,0,0v-.107s0,0,0,0v-.108c-.056,.002-.124-.004-.169-.028,0-.033,0-.241,0-.269-.055,.008-.119-.018-.113-.083,.045-.034,.03-.107-.024-.124v-1.29c.421-.192,.383-.772,0-.8v-.224c.575,.035,.796,.314,.653-.392Z"
fill="#9b8028"
></path>
<path
d="M12.531,14.533h-4.28l.003,2.572v1.485c0,.432,.226,.822,.591,1.019,.473,.252,1.024,.391,1.552,.391s1.064-.135,1.544-.391c.364-.197,.591-.587,.591-1.019v-4.057Z"
fill="#a0251e"
></path>
</svg>
);
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/icons/langsmith.tsx | export const LangSmithSVG = ({ className }: { className?: string }) => (
<svg
width="48"
height="24"
viewBox="0 0 48 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className={className}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M48 12C48 18.6163 42.5277 24 35.8024 24H12.1976C5.47233 24 0 18.6173 0 12C0 5.38272 5.47233 0 12.1976 0H35.8024C42.5286 0 48 5.38368 48 12ZM19.7123 11.4817C20.7324 12.7095 21.5077 14.1636 22.1424 15.6141C22.246 15.8062 22.301 16.0576 22.3633 16.2666C22.4568 16.5804 22.5007 16.8897 22.7315 17.1366C22.7871 17.2094 22.964 17.3017 23.0997 17.4266C23.4252 17.7262 23.8302 18.1273 23.6888 18.2965C23.7324 18.3897 23.9035 18.477 24.057 18.5865C24.3119 18.7685 24.5388 18.9438 24.3515 19.094C23.9457 19.1763 23.4835 19.1965 23.1733 18.8765C23.0815 19.0852 22.9108 19.0662 22.7315 19.0215C22.6884 19.0108 22.6244 18.9558 22.5842 18.949C22.5649 19.0022 22.6025 19.0419 22.5842 19.094C21.8997 19.1392 21.3653 18.4557 21.0378 17.934C20.7232 17.7663 20.3441 17.6359 20.0068 17.4991C19.6484 17.3537 19.317 17.2506 18.9759 17.0641C18.9684 17.1804 18.9769 17.3031 18.9759 17.4266C18.9715 17.9366 18.9239 18.4206 18.4604 18.7315C18.4451 19.347 18.9923 19.3897 19.4914 19.384C19.9228 19.3791 20.3732 19.3498 20.4487 19.7465C20.4154 19.7499 20.3355 19.7463 20.3014 19.7465L20.2995 19.7465C20.2043 19.7472 20.1559 19.7476 20.0805 19.819C19.838 20.0519 19.5414 19.9964 19.2704 19.8915C19.021 19.795 18.792 19.6637 18.5341 19.819C18.3017 19.9347 18.0919 20.0121 17.9449 20.109C17.6359 20.3128 17.4456 20.4937 16.8404 20.544C16.7905 20.4708 16.7976 20.4431 16.8404 20.399C16.9237 20.3039 17.0059 20.2059 17.0613 20.109C17.1736 19.9126 17.215 19.6835 17.5031 19.6015C17.1157 19.5418 16.7986 19.7181 16.4722 19.8915C16.4257 19.9162 16.3712 19.9402 16.3249 19.964C16.1218 20.0461 16.0057 20.0315 15.883 19.964C15.7133 19.8707 15.5794 19.7611 15.1467 20.0365C15.0643 19.9703 15.0999 19.8702 15.1467 19.819C15.3358 19.5913 15.5287 19.5885 15.8094 19.6015C15.0767 19.1984 14.6179 19.442 14.1893 19.674C13.8095 19.8797 13.4585 20.0685 13.1584 19.674C13.0222 19.7096 12.9396 19.7958 12.8638 19.8915C12.8327 19.9309 12.8255 20.0014 12.7902 20.0365C12.7171 19.9566 12.6982 19.8402 12.7166 19.7465C12.7242 19.7073 12.789 19.7134 12.7902 19.674C12.7719 19.6657 12.7355 19.6092 12.7166 19.6015C12.6057 19.5563 12.4644 19.5519 12.4956 19.384C12.2637 19.3071 12.1513 19.4 11.9802 19.529C11.9704 19.5364 11.9163 19.5217 11.9065 19.529C11.7944 19.4432 11.8938 19.3437 11.9802 19.239C12.02 19.1908 12.0378 19.1352 12.0538 19.094C12.1332 18.9576 12.2888 18.9526 12.422 18.949C12.5346 18.946 12.6388 18.9597 12.7166 18.8765C12.9947 18.7205 13.3292 18.795 13.6739 18.8765C13.9253 18.936 14.1786 18.9803 14.4103 18.949C14.8334 19.0022 15.3602 18.5789 15.1467 18.1515C14.7592 17.6641 14.7757 17.0781 14.7785 16.4841C14.7789 16.3826 14.7799 16.2936 14.7785 16.1941C14.7462 15.9688 14.4418 15.6581 14.1157 15.3966C13.8667 15.1969 13.5741 15.0025 13.453 14.8166C13.1185 14.4429 12.9036 14.0108 12.6429 13.5841C12.6349 13.571 12.5773 13.5973 12.5693 13.5841C12.1276 12.7402 12.0105 11.7794 11.8329 10.8292C11.6195 9.68758 11.3966 8.58029 10.7283 7.63924C10.174 7.94118 9.43899 7.7545 8.96097 7.34925C8.71062 7.57283 8.68582 7.90832 8.66642 8.21923C8.04804 7.60834 8.09747 6.43438 8.59278 5.75428C8.79517 5.48645 9.05863 5.29539 9.32917 5.10179C9.38917 5.05866 9.40484 5.025 9.40281 4.95679C9.89201 2.78508 13.2073 3.20155 14.263 4.7393C14.6117 5.17006 14.9089 5.62293 15.1467 6.11677C15.431 6.70738 15.7051 7.30513 16.1776 7.78424C16.6349 8.27771 17.0947 8.76368 17.5767 9.23421C18.3264 9.96597 19.0561 10.6642 19.7123 11.4817ZM28.1808 15.7591C28.8714 15.1352 29.5728 14.4611 29.5799 14.4541C29.627 14.4149 30.4062 13.735 31.5682 12.4242L32.9673 14.2366C32.341 15.0057 31.9743 15.4912 31.6418 15.9766C30.642 17.4371 29.809 18.648 29.8008 18.659C29.7968 18.6671 29.146 19.6015 28.1808 19.6015C28.0343 19.6015 27.8996 19.5792 27.7389 19.529C27.2029 19.3605 26.8113 19.0763 26.6344 18.659C26.4045 18.1194 26.5591 17.573 26.6344 17.4266C26.9069 16.8969 27.5034 16.371 28.1808 15.7591ZM39.0793 17.7166C39.2584 17.9162 39.3739 18.1747 39.3739 18.4415V18.5865C39.3739 18.8313 39.3015 19.0535 39.153 19.239C38.9465 19.4918 38.5988 19.674 38.2693 19.674C38.1981 19.674 38.0794 19.645 38.0082 19.632L37.9011 19.6015C37.6265 19.5494 37.3315 19.3882 37.1647 19.1665C36.6623 18.4985 35.5739 17.0117 34.5874 15.6866C34.1687 15.124 33.8028 14.5934 33.4828 14.1641C33.3674 14.0094 33.2073 13.8535 33.1146 13.7291C32.9051 13.4483 32.1449 12.4745 31.9364 12.2067C30.842 10.7953 30.1035 9.96723 30.0954 9.9592C30.0079 9.85387 29.7361 9.6268 29.5063 9.59671C29.1411 9.61276 28.7135 9.38924 28.6962 9.37921C28.5355 9.29896 28.3891 9.23421 28.328 9.23421C28.2009 9.31446 28.1757 9.35769 28.1808 9.52421C28.1808 9.54161 28.1804 9.57814 28.1808 9.59671C28.1815 9.63594 28.1828 9.62291 28.1808 9.66921C28.1716 9.90594 27.9822 10.0861 27.9598 10.1042C27.9598 10.1042 27.7115 10.3539 27.3707 10.6117C26.9558 10.9247 26.6466 10.6942 26.6344 10.6842C26.6079 10.6621 26.0979 10.2217 25.8243 9.8867C25.5548 9.55568 25.4718 9.44705 25.1616 9.01672C24.8036 8.52069 25.0752 8.16153 25.0879 8.14673L25.677 7.63924L25.6797 7.63712C25.7699 7.56636 26.1769 7.24701 26.4134 7.42175C26.6107 7.55516 26.8471 7.42676 26.8553 7.42175C26.8634 7.41673 26.9716 7.32608 26.9289 7.05925C26.8628 6.64899 27.1386 6.34731 27.1498 6.33427C27.158 6.32825 27.953 5.67875 28.9172 4.8843C30.3918 3.92958 32.2223 4.29896 32.9423 4.44426L32.9673 4.4493C33.4779 4.55262 34.0277 4.79256 33.9983 5.02929C33.9922 5.07844 33.9909 5.25582 33.7773 5.24679C32.1429 5.17958 31.0419 5.94251 30.7581 6.18927C30.7429 6.20231 30.7602 6.24271 30.7581 6.26177V6.33427C30.7561 6.34731 30.7531 6.39473 30.7581 6.40677L31.1263 7.27675C31.2148 7.4854 31.2736 7.70254 31.2736 7.92924V8.50923L31.4209 8.87172C31.5399 9.02419 32.9397 10.8507 34.2192 12.2792C35.2383 13.4167 37.912 16.3585 38.9321 17.4991L39.0793 17.7166ZM40.0367 6.26177L40.2576 6.47927C40.3369 6.55751 40.3587 6.73443 40.3312 6.84176L39.963 8.29173C39.9427 8.36395 39.4308 10.017 37.9011 10.3942C37.3469 10.5311 36.9805 10.5302 36.7229 10.5392C36.3043 10.5532 36.1952 10.5667 35.692 11.1192C35.588 11.2338 35.4395 11.3591 35.3238 11.4817C35.1326 11.6841 34.9595 11.8755 34.7346 12.1342L33.1882 10.3942C33.232 10.3431 33.2963 10.2907 33.3355 10.2492C33.4064 10.174 33.4647 10.0839 33.5564 9.9592C33.8351 9.59207 34.0418 9.3523 34.1455 9.16171C34.2299 9.00824 34.2283 8.82575 34.2192 8.65422L34.2183 8.6388C34.1937 8.1989 34.1488 7.39707 34.2192 6.91426C34.3158 6.2472 34.8854 5.53112 35.692 5.10179C36.258 4.79926 37.0596 4.49896 37.3781 4.37962L37.3857 4.3768C37.5118 4.32966 37.6664 4.42049 37.7538 4.5218L37.9011 4.6668C38.0018 4.78517 38.0008 4.91093 37.9011 5.02929L36.5756 6.62426C36.54 6.66639 36.4999 6.71409 36.502 6.76926V7.13175C36.504 7.19595 36.5258 7.30712 36.5756 7.34925L37.3857 8.00174C37.4335 8.04086 37.4709 8.00776 37.5329 8.00174H38.0484C38.1074 7.99572 38.157 7.97438 38.1957 7.92924L39.5212 6.33427C39.5792 6.26606 39.6526 6.19328 39.7421 6.18927C39.8316 6.18225 39.9736 6.19958 40.0367 6.26177Z"
fill="currentColor"
></path>
<path
d="M15.6621 18.5865C15.593 18.9527 15.8816 19.1389 16.1776 19.0215C16.4715 18.8881 16.6681 19.0738 16.7667 19.3115C17.2203 19.3767 17.8459 19.1887 17.8713 18.659C17.3315 18.3521 17.1396 17.8263 16.914 17.2816C16.899 17.2452 16.8553 17.173 16.8404 17.1366C16.806 17.0531 16.7286 17.0019 16.6931 16.9191C16.6878 16.9068 16.6984 16.8588 16.6931 16.8466C16.6654 16.9532 16.6451 17.0843 16.6194 17.2091C16.4924 17.8258 16.357 18.5607 15.6621 18.5865Z"
fill="currentColor"
></path>
<path
d="M28.549 18.659C28.4096 18.8877 28.0223 18.9432 27.6653 18.7315C27.4822 18.6232 27.2967 18.459 27.2235 18.2965C27.1563 18.1491 27.1594 18.0394 27.2235 17.934C27.2967 17.8137 27.4863 17.7166 27.6653 17.7166C27.826 17.7166 28.0119 17.7612 28.1808 17.8616C28.5378 18.0732 28.6883 18.4303 28.549 18.659Z"
fill="currentColor"
></path>
</svg>
);
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/icons/magic_pencil.tsx | import { cn } from "@/lib/utils";
export const MagicPencilSVG = ({ className }: { className?: string }) => (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className={cn("text-token-primary m-auto icon-lg", className)}
>
<path
d="M2.5 5.5C4.3 5.2 5.2 4 5.5 2.5C5.8 4 6.7 5.2 8.5 5.5C6.7 5.8 5.8 7 5.5 8.5C5.2 7 4.3 5.8 2.5 5.5Z"
fill="currentColor"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
></path>
<path
d="M5.66282 16.5231L5.18413 19.3952C5.12203 19.7678 5.09098 19.9541 5.14876 20.0888C5.19933 20.2067 5.29328 20.3007 5.41118 20.3512C5.54589 20.409 5.73218 20.378 6.10476 20.3159L8.97693 19.8372C9.72813 19.712 10.1037 19.6494 10.4542 19.521C10.7652 19.407 11.0608 19.2549 11.3343 19.068C11.6425 18.8575 11.9118 18.5882 12.4503 18.0497L20 10.5C21.3807 9.11929 21.3807 6.88071 20 5.5C18.6193 4.11929 16.3807 4.11929 15 5.5L7.45026 13.0497C6.91175 13.5882 6.6425 13.8575 6.43197 14.1657C6.24513 14.4392 6.09299 14.7348 5.97903 15.0458C5.85062 15.3963 5.78802 15.7719 5.66282 16.5231Z"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
></path>
<path
d="M14.5 7L18.5 11"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
></path>{" "}
</svg>
);
|
0 | lc_public_repos/open-canvas/src/components/icons | lc_public_repos/open-canvas/src/components/icons/svg/LLMIcon.svg | <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M6.65548 2.10715C7.57127 1.394 8.76885 1 9.95872 1C10.6709 1 11.2466 1.24432 11.6835 1.63282C11.8013 1.73737 11.9059 1.85073 11.9995 1.96738C12.093 1.85073 12.1976 1.73737 12.3154 1.63282C12.7523 1.24432 13.328 1 14.0402 1C15.2301 1 16.4287 1.394 17.3423 2.10715C18.0556 2.66073 18.6136 3.42561 18.8327 4.34897C19.295 4.42601 19.7056 4.66153 20.038 4.97299C20.5663 5.46933 20.9439 6.18689 21.1805 6.92536C21.4216 7.67484 21.5416 8.51676 21.5052 9.32566C21.4865 9.73947 21.426 10.1621 21.3104 10.566L21.3819 10.599C21.7892 10.7905 22.1194 11.0909 22.3671 11.4904C22.8349 12.2443 23 13.3295 23 14.7129C23 16.3032 22.3913 17.3828 21.6098 18.053C21.2027 18.4021 20.7263 18.6609 20.2119 18.8124C20.0252 19.6724 19.6417 20.4775 19.0914 21.1643C18.2955 22.1592 17.0583 23 15.3963 23C14.0644 23 13.0154 22.2626 12.3418 21.5583C12.2223 21.4324 12.1085 21.3013 12.0006 21.1654C11.8923 21.301 11.778 21.4317 11.6582 21.5572C10.9846 22.2637 9.93561 23 8.60374 23C6.94056 23 5.70336 22.1592 4.90864 21.1643C4.35749 20.4777 3.97317 19.6726 3.78591 18.8124C3.27188 18.6608 2.79582 18.402 2.3891 18.053C1.6076 17.3817 1 16.3032 1 14.7129C1 13.3295 1.16511 12.2443 1.63181 11.4904C1.87942 11.08 2.24876 10.7569 2.6885 10.566C2.57541 10.1616 2.51002 9.74528 2.49367 9.32566C2.45735 8.51676 2.57733 7.67484 2.81838 6.92536C3.05504 6.18799 3.43148 5.46933 3.96092 4.97299C4.29205 4.65028 4.71153 4.43311 5.16621 4.34897C5.38635 3.42451 5.94331 2.66073 6.65548 2.10715ZM7.67034 3.4091C7.06935 3.87684 6.71712 4.49975 6.71712 5.21731C6.71702 5.34803 6.68587 5.47685 6.62623 5.59318C6.5666 5.70951 6.48019 5.81001 6.37411 5.88642C6.26803 5.96282 6.14531 6.01294 6.01607 6.03266C5.88683 6.05237 5.75475 6.04111 5.63071 5.9998C5.47991 5.94917 5.32031 5.96128 5.09136 6.17699C4.83599 6.41581 4.57733 6.84832 4.3902 7.42941C4.20302 8.01805 4.11959 8.63473 4.14364 9.25193C4.17116 9.86383 4.31646 10.3723 4.5454 10.7157C4.58329 10.7725 4.61397 10.8339 4.63676 10.8983H5.82774C6.62021 10.8982 7.38339 11.1979 7.9639 11.7373C8.54441 12.2767 8.89924 13.0158 8.95707 13.806C9.43124 13.9952 9.82491 14.3432 10.0707 14.7906C10.3165 15.238 10.3991 15.7569 10.3045 16.2585C10.2098 16.7601 9.94372 17.2132 9.55176 17.5403C9.1598 17.8673 8.66633 18.048 8.15582 18.0514C7.64531 18.0548 7.14949 17.8807 6.75323 17.5588C6.35696 17.237 6.08489 16.7875 5.98357 16.2872C5.88225 15.7869 5.95799 15.2669 6.19783 14.8163C6.43766 14.3657 6.82668 14.0125 7.29829 13.817C7.24601 13.4645 7.06873 13.1425 6.79878 12.9097C6.52882 12.677 6.18419 12.549 5.82774 12.5492H2.93836C2.77325 12.9322 2.65107 13.5936 2.65107 14.7129C2.65107 15.8365 3.05944 16.4528 3.4645 16.8006C3.90809 17.1803 4.39571 17.2793 4.5366 17.2793C4.75555 17.2793 4.96552 17.3663 5.12034 17.5211C5.27516 17.6759 5.36214 17.8858 5.36214 18.1048C5.36214 18.567 5.6175 19.4067 6.19868 20.1331C6.75784 20.8341 7.55476 21.3492 8.60374 21.3492C9.3049 21.3492 9.94992 20.9552 10.464 20.4181C10.7127 20.1562 10.9064 19.8843 11.0341 19.6642C11.0824 19.5819 11.1247 19.4962 11.1607 19.4078L11.1673 19.3924V8.97239H10.1811C9.98949 9.44592 9.63915 9.83808 9.1901 10.0817C8.74105 10.3253 8.22125 10.4051 7.71978 10.3075C7.2183 10.21 6.76638 9.94105 6.44146 9.54687C6.11654 9.15268 5.93886 8.65778 5.93886 8.14697C5.93886 7.63617 6.11654 7.14127 6.44146 6.74708C6.76638 6.3529 7.2183 6.08398 7.71978 5.9864C8.22125 5.88883 8.74105 5.96868 9.1901 6.21227C9.63915 6.45587 9.98949 6.84803 10.1811 7.32156H11.1673V4.52836L11.164 4.46563C11.1452 4.12668 11.0785 3.7921 10.9659 3.47184C10.8668 3.2077 10.738 3.0019 10.5861 2.86653C10.4507 2.74547 10.2636 2.65083 9.95872 2.65083C9.11558 2.65083 8.28013 2.93477 7.66924 3.41021M12.8327 17.5017V19.3924L12.8382 19.4078C12.8602 19.4661 12.902 19.5531 12.9659 19.6642C13.0925 19.8843 13.2862 20.1562 13.536 20.4181C14.049 20.9552 14.6951 21.3492 15.3963 21.3492C16.4441 21.3492 17.2411 20.8341 17.8013 20.1331C18.3814 19.4067 18.6379 18.5659 18.6379 18.1048C18.6379 17.8858 18.7248 17.6759 18.8797 17.5211C19.0345 17.3663 19.2445 17.2793 19.4634 17.2793C19.6043 17.2793 20.0908 17.1803 20.5355 16.8006C20.9395 16.4528 21.3478 15.8365 21.3478 14.7129C21.3478 13.3834 21.1739 12.6988 20.9637 12.361C20.8979 12.2441 20.7981 12.1501 20.6775 12.0913C20.5663 12.0385 20.399 11.9989 20.1403 11.9989C19.9909 11.9989 19.8443 11.9583 19.7161 11.8816C19.588 11.8048 19.483 11.6947 19.4125 11.563C19.342 11.4312 19.3086 11.2829 19.3158 11.1336C19.323 10.9844 19.3706 10.84 19.4535 10.7157C19.6824 10.3723 19.8277 9.86383 19.8564 9.25193C19.88 8.63466 19.7962 8.01798 19.6087 7.42941C19.4216 6.84832 19.1629 6.41691 18.9086 6.17699C18.6786 5.96128 18.519 5.94917 18.3693 5.9998C18.2452 6.04132 18.113 6.05275 17.9836 6.03314C17.8542 6.01353 17.7313 5.96345 17.6251 5.88702C17.5189 5.81059 17.4324 5.71 17.3727 5.59356C17.313 5.47712 17.2818 5.34816 17.2818 5.21731C17.2818 4.49975 16.9296 3.87684 16.3286 3.4091C15.7199 2.93477 14.8833 2.64972 14.0391 2.64972C13.7353 2.64972 13.5493 2.74547 13.4128 2.86543C13.2404 3.03441 13.1107 3.24186 13.0341 3.47074C12.9107 3.8102 12.8427 4.1673 12.8327 4.52836V15.8508H13.5327C13.9268 15.8508 14.3048 15.6943 14.5835 15.4157C14.8622 15.137 15.0187 14.7591 15.0187 14.3651V12.3896C14.5451 12.198 14.1529 11.8478 13.9093 11.3988C13.6656 10.9498 13.5858 10.4301 13.6834 9.92867C13.7809 9.42727 14.0499 8.97542 14.4441 8.65055C14.8384 8.32568 15.3334 8.14802 15.8442 8.14802C16.3551 8.14802 16.8501 8.32568 17.2444 8.65055C17.6386 8.97542 17.9076 9.42727 18.0051 9.92867C18.1027 10.4301 18.0229 10.9498 17.7792 11.3988C17.5356 11.8478 17.1434 12.198 16.6698 12.3896V14.3651C16.6698 15.197 16.3393 15.9948 15.751 16.583C15.1627 17.1712 14.3647 17.5017 13.5327 17.5017H12.8327ZM8.13924 7.5967C7.99328 7.5967 7.85329 7.65467 7.75008 7.75787C7.64687 7.86107 7.58888 8.00103 7.58888 8.14697C7.58888 8.29292 7.64687 8.43288 7.75008 8.53608C7.85329 8.63927 7.99328 8.69725 8.13924 8.69725C8.2852 8.69725 8.42519 8.63927 8.5284 8.53608C8.63162 8.43288 8.6896 8.29292 8.6896 8.14697C8.6896 8.00103 8.63162 7.86107 8.5284 7.75787C8.42519 7.65467 8.2852 7.5967 8.13924 7.5967ZM7.58888 15.8508C7.58888 15.9968 7.64687 16.1367 7.75008 16.2399C7.85329 16.3431 7.99328 16.4011 8.13924 16.4011C8.2852 16.4011 8.42519 16.3431 8.5284 16.2399C8.63162 16.1367 8.6896 15.9968 8.6896 15.8508C8.6896 15.7049 8.63162 15.5649 8.5284 15.4617C8.42519 15.3585 8.2852 15.3005 8.13924 15.3005C7.99328 15.3005 7.85329 15.3585 7.75008 15.4617C7.64687 15.5649 7.58888 15.7049 7.58888 15.8508ZM15.2939 10.3481C15.2939 10.494 15.3519 10.634 15.4551 10.7372C15.5583 10.8404 15.6983 10.8983 15.8442 10.8983C15.9902 10.8983 16.1302 10.8404 16.2334 10.7372C16.3366 10.634 16.3946 10.494 16.3946 10.3481C16.3946 10.2021 16.3366 10.0622 16.2334 9.95897C16.1302 9.85577 15.9902 9.7978 15.8442 9.7978C15.6983 9.7978 15.5583 9.85577 15.4551 9.95897C15.3519 10.0622 15.2939 10.2021 15.2939 10.3481Z"
fill="#4b5563" />
</svg>
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/artifacts/CodeRenderer.module.css | .codeMirrorCustom {
height: 100vh !important;
overflow: hidden;
}
.codeMirrorCustom :global(.cm-editor) {
height: 100% !important;
border: none !important;
}
.codeMirrorCustom :global(.cm-scroller) {
overflow: auto;
}
.codeMirrorCustom :global(.cm-gutters) {
height: 100% !important;
border-right: none !important;
}
.codeMirrorCustom :global(.cm-focused) {
outline: none !important;
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/artifacts/ArtifactLoading.tsx | import { cn } from "@/lib/utils";
import { Skeleton } from "../ui/skeleton";
export function ArtifactLoading() {
return (
<div className="w-full h-full flex flex-col">
<div className="flex items-center justify-between m-4">
<Skeleton className="w-56 h-10" />
<div className="flex items-center justify-center gap-2">
<Skeleton className="w-6 h-6" />
<Skeleton className="w-16 h-6" />
<Skeleton className="w-6 h-6" />
</div>
<div className="flex items-center justify-end gap-2">
<Skeleton className="w-10 h-10 rounded-md" />
<Skeleton className="w-10 h-10 rounded-md" />
</div>
</div>
<div className="flex flex-col gap-1 m-4">
{Array.from({ length: 25 }).map((_, i) => (
<Skeleton
key={i}
className={cn(
"h-5",
["w-1/4", "w-1/3", "w-2/5", "w-1/2", "w-3/5", "w-2/3", "w-3/4"][
Math.floor(Math.random() * 7)
]
)}
/>
))}
</div>
<div className="flex items-center justify-end gap-2 mt-auto m-4">
<Skeleton className="w-12 h-12 rounded-2xl" />
<Skeleton className="w-12 h-12 rounded-2xl" />
</div>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/artifacts/TextRenderer.module.css | .mdEditorCustom {
height: 100% !important;
overflow: hidden;
border-radius: 0%;
}
.mdEditorCustom :global(.w-md-editor) {
height: 100% !important;
border: none !important;
}
.mdEditorCustom :global(.w-md-editor-content) {
height: 100% !important;
}
.mdEditorCustom :global(.w-md-editor-text),
.mdEditorCustom :global(.w-md-editor-text-pre),
.mdEditorCustom :global(.w-md-editor-text-input) {
min-height: 100% !important;
height: 100% !important;
}
.mdEditorCustom :global(.w-md-editor-preview) {
box-shadow: none !important;
}
.mdEditorCustom :global(.w-md-editor-toolbar) {
border-bottom: none !important;
}
/* Force full height for text area */
.fullHeightTextArea :global(.w-md-editor-text-input) {
min-height: 100vh !important;
height: 100% !important;
}
.lightModeOnly {
--color-canvas-default: #ffffff;
--color-canvas-subtle: #f6f8fa;
--color-border-default: #d0d7de;
--color-border-muted: #d8dee4;
--color-neutral-muted: rgba(175, 184, 193, 0.2);
--color-accent-fg: #0969da;
--color-accent-emphasis: #0969da;
--color-attention-subtle: #fff8c5;
--color-danger-fg: #cf222e;
}
.lightModeOnly :global(.wmde-markdown),
.lightModeOnly :global(.wmde-markdown-var) {
background-color: #ffffff;
color: #24292f;
}
.lightModeOnly :global(.w-md-editor-text-pre > code),
.lightModeOnly :global(.w-md-editor-text-input) {
color: #24292f !important;
}
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/artifacts/TextRenderer.tsx | import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
import { ArtifactMarkdownV3 } from "@/types";
import "@blocknote/core/fonts/inter.css";
import {
getDefaultReactSlashMenuItems,
SuggestionMenuController,
useCreateBlockNote,
} from "@blocknote/react";
import { BlockNoteView } from "@blocknote/shadcn";
import "@blocknote/shadcn/style.css";
import { isArtifactMarkdownContent } from "@/lib/artifact_content_types";
import { CopyText } from "./components/CopyText";
import { getArtifactContent } from "@/contexts/utils";
import { useGraphContext } from "@/contexts/GraphContext";
import React from "react";
import { TooltipIconButton } from "../ui/assistant-ui/tooltip-icon-button";
import { Eye, EyeOff } from "lucide-react";
import { motion } from "framer-motion";
import { Textarea } from "../ui/textarea";
const cleanText = (text: string) => {
return text.replaceAll("\\\n", "\n");
};
function ViewRawText({
isRawView,
setIsRawView,
}: {
isRawView: boolean;
setIsRawView: Dispatch<SetStateAction<boolean>>;
}) {
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2 }}
>
<TooltipIconButton
tooltip={`View ${isRawView ? "rendered" : "raw"} markdown`}
variant="outline"
delayDuration={400}
onClick={() => setIsRawView((p) => !p)}
>
{isRawView ? (
<EyeOff className="w-5 h-5 text-gray-600" />
) : (
<Eye className="w-5 h-5 text-gray-600" />
)}
</TooltipIconButton>
</motion.div>
);
}
export interface TextRendererProps {
isEditing: boolean;
isHovering: boolean;
isInputVisible: boolean;
}
export function TextRendererComponent(props: TextRendererProps) {
const editor = useCreateBlockNote({});
const { graphData } = useGraphContext();
const {
artifact,
isStreaming,
updateRenderedArtifactRequired,
firstTokenReceived,
setArtifact,
setSelectedBlocks,
setUpdateRenderedArtifactRequired,
} = graphData;
const [rawMarkdown, setRawMarkdown] = useState("");
const [isRawView, setIsRawView] = useState(false);
const [manuallyUpdatingArtifact, setManuallyUpdatingArtifact] =
useState(false);
useEffect(() => {
const selectedText = editor.getSelectedText();
const selection = editor.getSelection();
if (selectedText && selection) {
if (!artifact) {
console.error("Artifact not found");
return;
}
const currentBlockIdx = artifact.currentIndex;
const currentContent = artifact.contents.find(
(c) => c.index === currentBlockIdx
);
if (!currentContent) {
console.error("Current content not found");
return;
}
if (!isArtifactMarkdownContent(currentContent)) {
console.error("Current content is not markdown");
return;
}
(async () => {
const [markdownBlock, fullMarkdown] = await Promise.all([
editor.blocksToMarkdownLossy(selection.blocks),
editor.blocksToMarkdownLossy(editor.document),
]);
setSelectedBlocks({
fullMarkdown: cleanText(fullMarkdown),
markdownBlock: cleanText(markdownBlock),
selectedText: cleanText(selectedText),
});
})();
}
}, [editor.getSelectedText()]);
useEffect(() => {
if (!props.isInputVisible) {
setSelectedBlocks(undefined);
}
}, [props.isInputVisible]);
useEffect(() => {
if (!artifact) {
return;
}
if (
!isStreaming &&
!manuallyUpdatingArtifact &&
!updateRenderedArtifactRequired
) {
console.error("Can only update via useEffect when streaming");
return;
}
try {
const currentIndex = artifact.currentIndex;
const currentContent = artifact.contents.find(
(c) => c.index === currentIndex && c.type === "text"
) as ArtifactMarkdownV3 | undefined;
if (!currentContent) return;
// Blocks are not found in the artifact, so once streaming is done we should update the artifact state with the blocks
(async () => {
const markdownAsBlocks = await editor.tryParseMarkdownToBlocks(
currentContent.fullMarkdown
);
editor.replaceBlocks(editor.document, markdownAsBlocks);
setUpdateRenderedArtifactRequired(false);
setManuallyUpdatingArtifact(false);
})();
} finally {
setManuallyUpdatingArtifact(false);
setUpdateRenderedArtifactRequired(false);
}
}, [artifact, updateRenderedArtifactRequired]);
useEffect(() => {
if (isRawView) {
editor.blocksToMarkdownLossy(editor.document).then(setRawMarkdown);
} else if (!isRawView && rawMarkdown) {
try {
(async () => {
setManuallyUpdatingArtifact(true);
const markdownAsBlocks =
await editor.tryParseMarkdownToBlocks(rawMarkdown);
editor.replaceBlocks(editor.document, markdownAsBlocks);
setManuallyUpdatingArtifact(false);
})();
} catch (_) {
setManuallyUpdatingArtifact(false);
}
}
}, [isRawView, editor]);
const isComposition = useRef(false);
const onChange = async () => {
if (
isStreaming ||
manuallyUpdatingArtifact ||
updateRenderedArtifactRequired
)
return;
const fullMarkdown = await editor.blocksToMarkdownLossy(editor.document);
setArtifact((prev) => {
if (!prev) {
return {
currentIndex: 1,
contents: [
{
index: 1,
fullMarkdown: fullMarkdown,
title: "Untitled",
type: "text",
},
],
};
} else {
return {
...prev,
contents: prev.contents.map((c) => {
if (c.index === prev.currentIndex) {
return {
...c,
fullMarkdown: fullMarkdown,
};
}
return c;
}),
};
}
});
};
const onChangeRawMarkdown = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newRawMarkdown = e.target.value;
setRawMarkdown(newRawMarkdown);
setArtifact((prev) => {
if (!prev) {
return {
currentIndex: 1,
contents: [
{
index: 1,
fullMarkdown: newRawMarkdown,
title: "Untitled",
type: "text",
},
],
};
} else {
return {
...prev,
contents: prev.contents.map((c) => {
if (c.index === prev.currentIndex) {
return {
...c,
fullMarkdown: newRawMarkdown,
};
}
return c;
}),
};
}
});
};
return (
<div className="w-full h-full mt-2 flex flex-col border-t-[1px] border-gray-200 overflow-y-auto py-5 relative">
{props.isHovering && artifact && (
<div className="absolute flex gap-2 top-2 right-4 z-10">
<CopyText currentArtifactContent={getArtifactContent(artifact)} />
<ViewRawText isRawView={isRawView} setIsRawView={setIsRawView} />
</div>
)}
{isRawView ? (
<Textarea
className="whitespace-pre-wrap font-mono text-sm px-[54px] border-0 shadow-none h-full outline-none ring-0 rounded-none focus-visible:ring-0 focus-visible:ring-offset-0"
value={rawMarkdown}
onChange={onChangeRawMarkdown}
/>
) : (
<>
<style jsx global>{`
.pulse-text .bn-block-group {
animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.3;
}
}
`}</style>
<BlockNoteView
theme="light"
formattingToolbar={false}
slashMenu={false}
onCompositionStartCapture={() => (isComposition.current = true)}
onCompositionEndCapture={() => (isComposition.current = false)}
onChange={onChange}
editable={
!isStreaming || props.isEditing || !manuallyUpdatingArtifact
}
editor={editor}
className={isStreaming && !firstTokenReceived ? "pulse-text" : ""}
>
<SuggestionMenuController
getItems={async () =>
getDefaultReactSlashMenuItems(editor).filter(
(z) => z.group !== "Media"
)
}
triggerCharacter={"/"}
/>
</BlockNoteView>
</>
)}
</div>
);
}
export const TextRenderer = React.memo(TextRendererComponent);
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/artifacts/CodeRenderer.tsx | import { ArtifactCodeV3 } from "@/types";
import React, { MutableRefObject, useEffect } from "react";
import CodeMirror, { EditorView } from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { cpp } from "@codemirror/lang-cpp";
import { java } from "@codemirror/lang-java";
import { php } from "@codemirror/lang-php";
import { python } from "@codemirror/lang-python";
import { html } from "@codemirror/lang-html";
import { sql } from "@codemirror/lang-sql";
import { json } from "@codemirror/lang-json";
import { rust } from "@codemirror/lang-rust";
import { xml } from "@codemirror/lang-xml";
import { clojure } from "@nextjournal/lang-clojure";
import { csharp } from "@replit/codemirror-lang-csharp";
import styles from "./CodeRenderer.module.css";
import { cleanContent } from "@/lib/normalize_string";
import { cn } from "@/lib/utils";
import { CopyText } from "./components/CopyText";
import { getArtifactContent } from "@/contexts/utils";
import { useGraphContext } from "@/contexts/GraphContext";
export interface CodeRendererProps {
editorRef: MutableRefObject<EditorView | null>;
isHovering: boolean;
}
const getLanguageExtension = (language: string) => {
switch (language) {
case "javascript":
return javascript({ jsx: true, typescript: false });
case "typescript":
return javascript({ jsx: true, typescript: true });
case "cpp":
return cpp();
case "java":
return java();
case "php":
return php();
case "python":
return python();
case "html":
return html();
case "sql":
return sql();
case "json":
return json();
case "rust":
return rust();
case "xml":
return xml();
case "clojure":
return clojure();
case "csharp":
return csharp();
default:
return [];
}
};
export function CodeRendererComponent(props: Readonly<CodeRendererProps>) {
const { graphData } = useGraphContext();
const {
artifact,
isStreaming,
updateRenderedArtifactRequired,
firstTokenReceived,
setArtifactContent,
setUpdateRenderedArtifactRequired,
} = graphData;
useEffect(() => {
if (updateRenderedArtifactRequired) {
setUpdateRenderedArtifactRequired(false);
}
}, [updateRenderedArtifactRequired]);
if (!artifact) {
return null;
}
const artifactContent = getArtifactContent(artifact) as ArtifactCodeV3;
const extensions = [getLanguageExtension(artifactContent.language)];
if (!artifactContent.code) {
return null;
}
const isEditable = !isStreaming;
return (
<div className="relative">
<style jsx global>{`
.pulse-code .cm-content {
animation: codePulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
@keyframes codePulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.3;
}
}
`}</style>
{props.isHovering && (
<div className="absolute top-0 right-4 z-10">
<CopyText currentArtifactContent={artifactContent} />
</div>
)}
<CodeMirror
editable={isEditable}
className={cn(
"w-full min-h-full",
styles.codeMirrorCustom,
isStreaming && !firstTokenReceived ? "pulse-code" : ""
)}
value={cleanContent(artifactContent.code)}
height="800px"
extensions={extensions}
onChange={(c) => setArtifactContent(artifactContent.index, c)}
onCreateEditor={(view) => {
props.editorRef.current = view;
}}
/>
</div>
);
}
export const CodeRenderer = React.memo(CodeRendererComponent);
|
0 | lc_public_repos/open-canvas/src/components | lc_public_repos/open-canvas/src/components/artifacts/ArtifactRenderer.tsx | import { convertToOpenAIFormat } from "@/lib/convert_messages";
import { cn } from "@/lib/utils";
import {
ArtifactCodeV3,
ArtifactMarkdownV3,
ProgrammingLanguageOptions,
} from "@/types";
import { EditorView } from "@codemirror/view";
import { HumanMessage } from "@langchain/core/messages";
import { Forward, LoaderCircle, CircleCheck } from "lucide-react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { ReflectionsDialog } from "../reflections-dialog/ReflectionsDialog";
import { TooltipIconButton } from "../ui/assistant-ui/tooltip-icon-button";
import { ActionsToolbar, CodeToolBar } from "./actions_toolbar";
import { CodeRenderer } from "./CodeRenderer";
import { TextRenderer } from "./TextRenderer";
import { CustomQuickActions } from "./actions_toolbar/custom";
import { getArtifactContent } from "@/contexts/utils";
import { ArtifactLoading } from "./ArtifactLoading";
import { AskOpenCanvas } from "./components/AskOpenCanvas";
import { useGraphContext } from "@/contexts/GraphContext";
export interface ArtifactRendererProps {
isEditing: boolean;
setIsEditing: React.Dispatch<React.SetStateAction<boolean>>;
}
interface SelectionBox {
top: number;
left: number;
text: string;
}
interface ArtifactTitleProps {
title: string;
isArtifactSaved: boolean;
}
function ArtifactTitle(props: ArtifactTitleProps) {
return (
<>
<h1 className="text-xl font-medium text-gray-600 ">{props.title}</h1>
<span className="mt-auto">
{props.isArtifactSaved ? (
<span className="flex items-center justify-start gap-1 text-gray-400">
<p className="text-xs font-light">Saved</p>
<CircleCheck className="w-[10px] h-[10px]" />
</span>
) : (
<span className="flex items-center justify-start gap-1 text-gray-400">
<p className="text-xs font-light">Saving</p>
<LoaderCircle className="animate-spin w-[10px] h-[10px]" />
</span>
)}
</span>
</>
);
}
interface NavigateArtifactHistoryProps {
isBackwardsDisabled: boolean;
isForwardDisabled: boolean;
setSelectedArtifact: (prevState: number) => void;
currentArtifactContent: ArtifactCodeV3 | ArtifactMarkdownV3;
totalArtifactVersions: number;
}
function NavigateArtifactHistory(props: NavigateArtifactHistoryProps) {
return (
<>
<TooltipIconButton
tooltip="Previous"
side="left"
variant="ghost"
className="transition-colors w-fit h-fit p-2"
delayDuration={400}
onClick={() => {
if (!props.isBackwardsDisabled) {
props.setSelectedArtifact(props.currentArtifactContent.index - 1);
}
}}
disabled={props.isBackwardsDisabled}
>
<Forward
aria-disabled={props.isBackwardsDisabled}
className="w-6 h-6 text-gray-600 scale-x-[-1]"
/>
</TooltipIconButton>
<div className="flex items-center justify-center gap-1">
<p className="text-xs pt-1">
{props.currentArtifactContent.index} / {props.totalArtifactVersions}
</p>
</div>
<TooltipIconButton
tooltip="Next"
variant="ghost"
side="right"
className="transition-colors w-fit h-fit p-2"
delayDuration={400}
onClick={() => {
if (!props.isForwardDisabled) {
props.setSelectedArtifact(props.currentArtifactContent.index + 1);
}
}}
disabled={props.isForwardDisabled}
>
<Forward
aria-disabled={props.isForwardDisabled}
className="w-6 h-6 text-gray-600"
/>
</TooltipIconButton>
</>
);
}
function ArtifactRendererComponent(props: ArtifactRendererProps) {
const {
graphData,
assistantsData: { selectedAssistant },
userData: { user },
} = useGraphContext();
const {
artifact,
selectedBlocks,
isStreaming,
isArtifactSaved,
setSelectedArtifact,
setMessages,
streamMessage,
setSelectedBlocks,
} = graphData;
const editorRef = useRef<EditorView | null>(null);
const artifactContentRef = useRef<HTMLDivElement>(null);
const highlightLayerRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const selectionBoxRef = useRef<HTMLDivElement>(null);
const [selectionBox, setSelectionBox] = useState<SelectionBox>();
const [selectionIndexes, setSelectionIndexes] = useState<{
start: number;
end: number;
}>();
const [isInputVisible, setIsInputVisible] = useState(false);
const [isSelectionActive, setIsSelectionActive] = useState(false);
const [inputValue, setInputValue] = useState("");
const [isHoveringOverArtifact, setIsHoveringOverArtifact] = useState(false);
const handleMouseUp = useCallback(() => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0 && contentRef.current) {
const range = selection.getRangeAt(0);
const selectedText = range.toString().trim();
if (selectedText) {
const rects = range.getClientRects();
const firstRect = rects[0];
const lastRect = rects[rects.length - 1];
const contentRect = contentRef.current.getBoundingClientRect();
const boxWidth = 400; // Approximate width of the selection box
let left = lastRect.right - contentRect.left - boxWidth;
// Ensure the box doesn't go beyond the left edge
if (left < 0) {
left = Math.min(0, firstRect.left - contentRect.left);
}
setSelectionBox({
top: lastRect.bottom - contentRect.top,
left: left,
text: selectedText,
});
setIsInputVisible(false);
setIsSelectionActive(true);
}
}
}, []);
const handleCleanupState = () => {
setIsInputVisible(false);
setSelectionBox(undefined);
setSelectionIndexes(undefined);
setIsSelectionActive(false);
setInputValue("");
};
const handleDocumentMouseDown = useCallback(
(event: MouseEvent) => {
if (
isSelectionActive &&
selectionBoxRef.current &&
!selectionBoxRef.current.contains(event.target as Node)
) {
handleCleanupState();
}
},
[isSelectionActive]
);
const handleSelectionBoxMouseDown = useCallback((event: React.MouseEvent) => {
event.stopPropagation();
}, []);
const handleSubmit = async (content: string) => {
const humanMessage = new HumanMessage({
content,
id: uuidv4(),
});
setMessages((prevMessages) => [...prevMessages, humanMessage]);
handleCleanupState();
await streamMessage({
messages: [convertToOpenAIFormat(humanMessage)],
...(selectionIndexes && {
highlightedCode: {
startCharIndex: selectionIndexes.start,
endCharIndex: selectionIndexes.end,
},
}),
});
};
useEffect(() => {
document.addEventListener("mouseup", handleMouseUp);
document.addEventListener("mousedown", handleDocumentMouseDown);
return () => {
document.removeEventListener("mouseup", handleMouseUp);
document.removeEventListener("mousedown", handleDocumentMouseDown);
};
}, [handleMouseUp, handleDocumentMouseDown]);
useEffect(() => {
try {
if (artifactContentRef.current && highlightLayerRef.current) {
const content = artifactContentRef.current;
const highlightLayer = highlightLayerRef.current;
// Clear existing highlights
highlightLayer.innerHTML = "";
if (isSelectionActive && selectionBox) {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
if (content.contains(range.commonAncestorContainer)) {
const rects = range.getClientRects();
const layerRect = highlightLayer.getBoundingClientRect();
// Calculate start and end indexes
let startIndex = 0;
let endIndex = 0;
let currentArtifactContent:
| ArtifactCodeV3
| ArtifactMarkdownV3
| undefined = undefined;
try {
currentArtifactContent = artifact
? getArtifactContent(artifact)
: undefined;
} catch (_) {
console.error(
"[ArtifactRenderer.tsx L229]\n\nERROR NO ARTIFACT CONTENT FOUND\n\n",
artifact
);
// no-op
}
if (currentArtifactContent?.type === "code") {
if (editorRef.current) {
const from = editorRef.current.posAtDOM(
range.startContainer,
range.startOffset
);
const to = editorRef.current.posAtDOM(
range.endContainer,
range.endOffset
);
startIndex = from;
endIndex = to;
}
setSelectionIndexes({ start: startIndex, end: endIndex });
}
for (let i = 0; i < rects.length; i++) {
const rect = rects[i];
const highlightEl = document.createElement("div");
highlightEl.className =
"absolute bg-[#3597934d] pointer-events-none";
// Adjust the positioning and size
const verticalPadding = 3;
highlightEl.style.left = `${rect.left - layerRect.left}px`;
highlightEl.style.top = `${rect.top - layerRect.top - verticalPadding}px`;
highlightEl.style.width = `${rect.width}px`;
highlightEl.style.height = `${rect.height + verticalPadding * 2}px`;
highlightLayer.appendChild(highlightEl);
}
}
}
}
}
} catch (e) {
console.error("Failed to get artifact selection", e);
}
}, [isSelectionActive, selectionBox]);
useEffect(() => {
if (!!selectedBlocks && !isSelectionActive) {
// Selection is not active but selected blocks are present. Clear them.
setSelectedBlocks(undefined);
}
}, [selectedBlocks, isSelectionActive]);
const currentArtifactContent = artifact
? getArtifactContent(artifact)
: undefined;
if (!artifact && isStreaming) {
return <ArtifactLoading />;
}
if (!artifact || !currentArtifactContent) {
return <div className="w-full h-full"></div>;
}
const isBackwardsDisabled =
artifact.contents.length === 1 ||
currentArtifactContent.index === 1 ||
isStreaming;
const isForwardDisabled =
artifact.contents.length === 1 ||
currentArtifactContent.index === artifact.contents.length ||
isStreaming;
return (
<div className="relative w-full h-full max-h-screen overflow-auto">
<div className="flex flex-row items-center justify-between">
<div className="pl-[6px] pt-3 flex flex-col items-start justify-start ml-[6px] gap-1">
<ArtifactTitle
title={currentArtifactContent.title}
isArtifactSaved={isArtifactSaved}
/>
</div>
<div className="absolute left-1/2 transform -translate-x-1/2 flex items-center justify-center gap-3 text-gray-600">
<NavigateArtifactHistory
isBackwardsDisabled={isBackwardsDisabled}
isForwardDisabled={isForwardDisabled}
setSelectedArtifact={setSelectedArtifact}
currentArtifactContent={currentArtifactContent}
totalArtifactVersions={artifact.contents.length}
/>
</div>
<div className="ml-auto mt-[10px] mr-[6px]">
<ReflectionsDialog selectedAssistant={selectedAssistant} />
</div>
</div>
<div
ref={contentRef}
className={cn(
"flex justify-center h-full",
currentArtifactContent.type === "code" ? "pt-[10px]" : ""
)}
>
<div
className={cn(
"relative min-h-full",
currentArtifactContent.type === "code" ? "min-w-full" : "min-w-full"
)}
>
<div
className="h-full"
ref={artifactContentRef}
onMouseEnter={() => setIsHoveringOverArtifact(true)}
onMouseLeave={() => setIsHoveringOverArtifact(false)}
>
{currentArtifactContent.type === "text" ? (
<TextRenderer
isInputVisible={isInputVisible}
isEditing={props.isEditing}
isHovering={isHoveringOverArtifact}
/>
) : null}
{currentArtifactContent.type === "code" ? (
<CodeRenderer
editorRef={editorRef}
isHovering={isHoveringOverArtifact}
/>
) : null}
</div>
<div
ref={highlightLayerRef}
className="absolute top-0 left-0 w-full h-full pointer-events-none"
/>
</div>
{selectionBox && isSelectionActive && (
<AskOpenCanvas
ref={selectionBoxRef}
inputValue={inputValue}
setInputValue={setInputValue}
isInputVisible={isInputVisible}
selectionBox={selectionBox}
setIsInputVisible={setIsInputVisible}
handleSubmitMessage={handleSubmit}
handleSelectionBoxMouseDown={handleSelectionBoxMouseDown}
artifact={artifact}
selectionIndexes={selectionIndexes}
handleCleanupState={handleCleanupState}
/>
)}
</div>
<CustomQuickActions
streamMessage={streamMessage}
assistantId={selectedAssistant?.assistant_id}
user={user}
isTextSelected={isSelectionActive || selectedBlocks !== undefined}
/>
{currentArtifactContent.type === "text" ? (
<ActionsToolbar
streamMessage={streamMessage}
isTextSelected={isSelectionActive || selectedBlocks !== undefined}
/>
) : null}
{currentArtifactContent.type === "code" ? (
<CodeToolBar
streamMessage={streamMessage}
isTextSelected={isSelectionActive || selectedBlocks !== undefined}
language={
currentArtifactContent.language as ProgrammingLanguageOptions
}
/>
) : null}
</div>
);
}
export const ArtifactRenderer = React.memo(ArtifactRendererComponent);
|
0 | lc_public_repos/open-canvas/src/components/artifacts | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/index.tsx | export * from "./text";
export * from "./code";
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/text/ReadingLevelOptions.tsx | import {
Baby,
GraduationCap,
PersonStanding,
School,
Swords,
} from "lucide-react";
import { ReadingLevelOptions as ReadingLevelOptionsType } from "@/types";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import { GraphInput } from "@/contexts/GraphContext";
export interface ReadingLevelOptionsProps {
streamMessage: (params: GraphInput) => Promise<void>;
handleClose: () => void;
}
export function ReadingLevelOptions(props: ReadingLevelOptionsProps) {
const { streamMessage } = props;
const handleSubmit = async (readingLevel: ReadingLevelOptionsType) => {
props.handleClose();
await streamMessage({
readingLevel,
});
};
return (
<div className="flex flex-col gap-3 items-center w-full">
<TooltipIconButton
tooltip="PhD"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("phd")}
>
<GraduationCap />
</TooltipIconButton>
<TooltipIconButton
tooltip="College"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("college")}
>
<School />
</TooltipIconButton>
<TooltipIconButton
tooltip="Teenager"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("teenager")}
>
<PersonStanding />
</TooltipIconButton>
<TooltipIconButton
tooltip="Child"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("child")}
>
<Baby />
</TooltipIconButton>
<TooltipIconButton
tooltip="Pirate"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("pirate")}
>
<Swords />
</TooltipIconButton>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/text/LengthOptions.tsx | import { cn } from "@/lib/utils";
import { useState } from "react";
import { ArtifactLengthOptions } from "@/types";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { Slider } from "@/components/ui/slider";
import { GraphInput } from "@/contexts/GraphContext";
export interface LengthOptionsProps {
streamMessage: (params: GraphInput) => Promise<void>;
handleClose: () => void;
}
const lengthOptions = [
{ value: 1, label: "Shortest" },
{ value: 2, label: "Shorter" },
{ value: 3, label: "Current length" },
{ value: 4, label: "Long" },
{ value: 5, label: "Longest" },
];
export function LengthOptions(props: LengthOptionsProps) {
const { streamMessage } = props;
const [open, setOpen] = useState(false);
const [value, setValue] = useState([3]);
const handleSubmit = async (artifactLength: ArtifactLengthOptions) => {
props.handleClose();
await streamMessage({
artifactLength,
});
};
return (
<div className="h-[200px] flex items-center justify-center px-4">
<TooltipProvider>
<Tooltip open={open}>
<TooltipTrigger asChild>
<Slider
defaultValue={[3]}
max={5}
min={1}
step={1}
value={value}
onValueChange={(newValue) => {
setValue(newValue);
setOpen(true);
}}
onValueCommit={async (v) => {
setOpen(false);
switch (v[0]) {
case 1:
await handleSubmit("shortest");
break;
case 2:
await handleSubmit("short");
break;
case 3:
// Same length, do nothing.
break;
case 4:
await handleSubmit("long");
break;
case 5:
await handleSubmit("longest");
break;
}
}}
orientation="vertical"
color="black"
className={cn("h-[180px] w-[26px]")}
/>
</TooltipTrigger>
<TooltipContent side="right">
{lengthOptions.find((option) => option.value === value[0])?.label}
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/text/index.tsx | import { useEffect, useRef, useState } from "react";
import { Languages, BookOpen, SlidersVertical, SmilePlus } from "lucide-react";
import { cn } from "@/lib/utils";
import { ReadingLevelOptions } from "./ReadingLevelOptions";
import { TranslateOptions } from "./TranslateOptions";
import { LengthOptions } from "./LengthOptions";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import { MagicPencilSVG } from "@/components/icons/magic_pencil";
import { GraphInput } from "@/contexts/GraphContext";
type SharedComponentProps = {
streamMessage: (params: GraphInput) => Promise<void>;
handleClose: () => void;
};
type ToolbarOption = {
id: string;
tooltip: string;
icon: React.ReactNode;
component: ((props: SharedComponentProps) => React.ReactNode) | null;
};
export interface ActionsToolbarProps {
streamMessage: (params: GraphInput) => Promise<void>;
isTextSelected: boolean;
}
const toolbarOptions: ToolbarOption[] = [
{
id: "translate",
tooltip: "Translate",
icon: <Languages className="w-[26px] h-[26px]" />,
component: (props: SharedComponentProps) => <TranslateOptions {...props} />,
},
{
id: "readingLevel",
tooltip: "Reading level",
icon: <BookOpen className="w-[26px] h-[26px]" />,
component: (props: SharedComponentProps) => (
<ReadingLevelOptions {...props} />
),
},
{
id: "adjustLength",
tooltip: "Adjust the length",
icon: <SlidersVertical className="w-[26px] h-[26px]" />,
component: (props: SharedComponentProps) => <LengthOptions {...props} />,
},
{
id: "addEmojis",
tooltip: "Add emojis",
icon: <SmilePlus className="w-[26px] h-[26px]" />,
component: null,
},
];
export function ActionsToolbar(props: ActionsToolbarProps) {
const { streamMessage } = props;
const [isExpanded, setIsExpanded] = useState(false);
const [activeOption, setActiveOption] = useState<string | null>(null);
const toolbarRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
toolbarRef.current &&
!toolbarRef.current.contains(event.target as Node)
) {
setIsExpanded(false);
setActiveOption(null);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
const toggleExpand = (event: React.MouseEvent) => {
event.stopPropagation();
if (props.isTextSelected) return;
setIsExpanded(!isExpanded);
setActiveOption(null);
};
const handleOptionClick = async (
event: React.MouseEvent,
optionId: string
) => {
event.stopPropagation();
if (optionId === "addEmojis") {
setIsExpanded(false);
setActiveOption(null);
await streamMessage({
regenerateWithEmojis: true,
});
} else {
setActiveOption(optionId);
}
};
const handleClose = () => {
setIsExpanded(false);
setActiveOption(null);
};
return (
<div
ref={toolbarRef}
className={cn(
"fixed bottom-4 right-4 transition-all duration-300 ease-in-out text-black flex flex-col items-center justify-center bg-white",
isExpanded
? "w-fit-content min-h-fit rounded-3xl"
: "w-12 h-12 rounded-full"
)}
onClick={toggleExpand}
>
{isExpanded ? (
<div className="flex flex-col gap-3 items-center w-full border-[1px] border-gray-200 rounded-3xl py-4 px-3">
{activeOption && activeOption !== "addEmojis"
? toolbarOptions
.find((option) => option.id === activeOption)
?.component?.({
...props,
handleClose,
})
: toolbarOptions.map((option) => (
<TooltipIconButton
key={option.id}
tooltip={option.tooltip}
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async (e) => await handleOptionClick(e, option.id)}
>
{option.icon}
</TooltipIconButton>
))}
</div>
) : (
<TooltipIconButton
tooltip={
props.isTextSelected
? "Quick actions disabled while text is selected"
: "Writing tools"
}
variant="outline"
className={cn(
"transition-colors w-[48px] h-[48px] p-0 rounded-xl",
props.isTextSelected
? "cursor-default opacity-50 text-gray-400 hover:bg-background"
: "cursor-pointer"
)}
delayDuration={400}
>
<MagicPencilSVG
className={cn(
"w-[26px] h-[26px]",
props.isTextSelected
? "text-gray-400"
: "hover:text-gray-900 transition-colors"
)}
/>
</TooltipIconButton>
)}
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/text/TranslateOptions.tsx | import {
UsaFlag,
ChinaFlag,
IndiaFlag,
SpanishFlag,
FrenchFlag,
} from "@/components/icons/flags";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import { GraphInput } from "@/contexts/GraphContext";
import { LanguageOptions } from "@/types";
export interface TranslateOptionsProps {
streamMessage: (params: GraphInput) => Promise<void>;
handleClose: () => void;
}
export function TranslateOptions(props: TranslateOptionsProps) {
const { streamMessage } = props;
const handleSubmit = async (language: LanguageOptions) => {
props.handleClose();
await streamMessage({
language,
});
};
return (
<div className="flex flex-col gap-3 items-center w-full">
<TooltipIconButton
tooltip="English"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("english")}
>
<UsaFlag />
</TooltipIconButton>
<TooltipIconButton
tooltip="Mandarin"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("mandarin")}
>
<ChinaFlag />
</TooltipIconButton>
<TooltipIconButton
tooltip="Hindi"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("hindi")}
>
<IndiaFlag />
</TooltipIconButton>
<TooltipIconButton
tooltip="Spanish"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("spanish")}
>
<SpanishFlag />
</TooltipIconButton>
<TooltipIconButton
tooltip="French"
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async () => await handleSubmit("french")}
>
<FrenchFlag />
</TooltipIconButton>
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/code/PortToLanguage.tsx | import { ProgrammingLanguageOptions } from "@/types";
import { useToast } from "@/hooks/use-toast";
import { ProgrammingLanguageList } from "@/components/ui/programming-lang-dropdown";
import { GraphInput } from "@/contexts/GraphContext";
export interface PortToLanguageOptionsProps {
streamMessage: (params: GraphInput) => Promise<void>;
handleClose: () => void;
language: ProgrammingLanguageOptions;
}
const prettifyLanguage = (language: ProgrammingLanguageOptions) => {
switch (language) {
case "php":
return "PHP";
case "typescript":
return "TypeScript";
case "javascript":
return "JavaScript";
case "cpp":
return "C++";
case "java":
return "Java";
case "python":
return "Python";
case "html":
return "HTML";
case "sql":
return "SQL";
default:
return language;
}
};
export function PortToLanguageOptions(props: PortToLanguageOptionsProps) {
const { streamMessage } = props;
const { toast } = useToast();
const handleSubmit = async (portLanguage: ProgrammingLanguageOptions) => {
if (portLanguage === props.language) {
toast({
title: "Port language error",
description: `The code is already in ${prettifyLanguage(portLanguage)}`,
duration: 5000,
});
props.handleClose();
return;
}
props.handleClose();
await streamMessage({
portLanguage,
});
};
return <ProgrammingLanguageList handleSubmit={handleSubmit} />;
}
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/code/index.tsx | import { useEffect, useRef, useState } from "react";
import { MessageCircleCode, Code, ScrollText, Bug, BookA } from "lucide-react";
import { cn } from "@/lib/utils";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import { PortToLanguageOptions } from "./PortToLanguage";
import { ProgrammingLanguageOptions } from "@/types";
import { GraphInput } from "@/contexts/GraphContext";
type SharedComponentProps = {
handleClose: () => void;
streamMessage: (params: GraphInput) => Promise<void>;
language: ProgrammingLanguageOptions;
};
type ToolbarOption = {
id: string;
tooltip: string;
icon: React.ReactNode;
component: ((props: SharedComponentProps) => React.ReactNode) | null;
};
export interface CodeToolbarProps {
streamMessage: (params: GraphInput) => Promise<void>;
isTextSelected: boolean;
language: ProgrammingLanguageOptions;
}
const toolbarOptions: ToolbarOption[] = [
{
id: "addComments",
tooltip: "Add comments",
icon: <MessageCircleCode className="w-[26px] h-[26px]" />,
component: null,
},
{
id: "addLogs",
tooltip: "Add logs",
icon: <ScrollText className="w-[26px] h-[26px]" />,
component: null,
},
{
id: "portLanguage",
tooltip: "Port language",
icon: <BookA className="w-[26px] h-[26px]" />,
component: (
props: SharedComponentProps & { language: ProgrammingLanguageOptions }
) => <PortToLanguageOptions {...props} />,
},
{
id: "fixBugs",
tooltip: "Fix bugs",
icon: <Bug className="w-[26px] h-[26px]" />,
component: null,
},
];
export function CodeToolBar(props: CodeToolbarProps) {
const { streamMessage } = props;
const [isExpanded, setIsExpanded] = useState(false);
const [activeOption, setActiveOption] = useState<string | null>(null);
const toolbarRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
toolbarRef.current &&
!toolbarRef.current.contains(event.target as Node)
) {
setIsExpanded(false);
setActiveOption(null);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
const toggleExpand = (event: React.MouseEvent) => {
event.stopPropagation();
if (props.isTextSelected) return;
setIsExpanded(!isExpanded);
setActiveOption(null);
};
const handleOptionClick = async (
event: React.MouseEvent,
optionId: string
) => {
event.stopPropagation();
if (optionId === "portLanguage") {
setActiveOption(optionId);
return;
}
setIsExpanded(false);
setActiveOption(null);
if (optionId === "addComments") {
await streamMessage({
addComments: true,
});
} else if (optionId === "addLogs") {
await streamMessage({
addLogs: true,
});
} else if (optionId === "fixBugs") {
await streamMessage({
fixBugs: true,
});
}
};
const handleClose = () => {
setIsExpanded(false);
setActiveOption(null);
};
return (
<div
ref={toolbarRef}
className={cn(
"fixed bottom-4 right-4 transition-all duration-300 ease-in-out text-black flex flex-col items-center justify-center bg-white",
isExpanded ? "w-26 min-h-fit rounded-3xl" : "w-12 h-12 rounded-full"
)}
onClick={toggleExpand}
>
{isExpanded ? (
<div className="flex flex-col gap-3 items-center w-full border-[1px] border-gray-200 rounded-3xl py-4 px-3">
{activeOption && activeOption !== "addEmojis"
? toolbarOptions
.find((option) => option.id === activeOption)
?.component?.({
...props,
handleClose,
})
: toolbarOptions.map((option) => (
<TooltipIconButton
key={option.id}
tooltip={option.tooltip}
variant="ghost"
className="transition-colors w-[36px] h-[36px]"
delayDuration={400}
onClick={async (e) => await handleOptionClick(e, option.id)}
>
{option.icon}
</TooltipIconButton>
))}
</div>
) : (
<TooltipIconButton
tooltip={
props.isTextSelected
? "Quick actions disabled while text is selected"
: "Code tools"
}
variant="outline"
className={cn(
"transition-colors w-[48px] h-[48px] p-0 rounded-xl",
props.isTextSelected
? "cursor-default opacity-50 text-gray-400 hover:bg-background"
: "cursor-pointer"
)}
delayDuration={400}
>
<Code
className={cn(
"w-[26px] h-[26px]",
props.isTextSelected
? "text-gray-400"
: "hover:text-gray-900 transition-colors"
)}
/>
</TooltipIconButton>
)}
</div>
);
}
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/custom/NewCustomQuickActionDialog.tsx | import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Eye, EyeOff } from "lucide-react";
import {
Dispatch,
FormEvent,
SetStateAction,
useEffect,
useState,
} from "react";
import { FullPrompt } from "./FullPrompt";
import { InlineContextTooltip } from "@/components/ui/inline-context-tooltip";
import { useStore } from "@/hooks/useStore";
import { useToast } from "@/hooks/use-toast";
import { v4 as uuidv4 } from "uuid";
import { CustomQuickAction } from "@/types";
import { TighterText } from "@/components/ui/header";
import { User } from "@supabase/supabase-js";
const CUSTOM_INSTRUCTIONS_TOOLTIP_TEXT = `This field contains the custom instructions you set, which will then be used to instruct the LLM on how to re-generate the selected artifact.`;
const FULL_PROMPT_TOOLTIP_TEXT = `This is the full prompt that will be set to the LLM when you invoke this quick action, including your custom instructions and other default context.`;
interface NewCustomQuickActionDialogProps {
user: User | undefined;
isEditing: boolean;
allQuickActions: CustomQuickAction[];
customQuickAction?: CustomQuickAction;
getAndSetCustomQuickActions: (userId: string) => Promise<void>;
open: boolean;
onOpenChange: (open: boolean) => void;
}
interface ViewOrHidePromptIconProps {
showFullPrompt: boolean;
setShowFullPrompt: Dispatch<SetStateAction<boolean>>;
}
const ViewOrHidePromptIcon = (props: ViewOrHidePromptIconProps) => (
<TooltipIconButton
tooltip={props.showFullPrompt ? "Hide prompt" : "View prompt"}
variant="ghost"
className="transition-colors"
delayDuration={400}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
props.setShowFullPrompt((p) => !p);
}}
>
{props.showFullPrompt ? (
<EyeOff className="w-4 h-4 text-gray-600" />
) : (
<Eye className="w-4 h-4 text-gray-600" />
)}
</TooltipIconButton>
);
export function NewCustomQuickActionDialog(
props: NewCustomQuickActionDialogProps
) {
const { toast } = useToast();
const { user } = props;
const { createCustomQuickAction, editCustomQuickAction } = useStore();
const [isSubmitLoading, setIsSubmitLoading] = useState(false);
const [name, setName] = useState("");
const [prompt, setPrompt] = useState("");
const [includeReflections, setIncludeReflections] = useState(true);
const [includePrefix, setIncludePrefix] = useState(true);
const [includeRecentHistory, setIncludeRecentHistory] = useState(true);
const [showFullPrompt, setShowFullPrompt] = useState(true);
useEffect(() => {
if (props.customQuickAction) {
setName(props.customQuickAction.title || "");
setPrompt(props.customQuickAction.prompt || "");
setIncludeReflections(props.customQuickAction.includeReflections ?? true);
setIncludePrefix(props.customQuickAction.includePrefix ?? true);
setIncludeRecentHistory(
props.customQuickAction.includeRecentHistory ?? true
);
}
}, [props.customQuickAction]);
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!user) {
toast({
title: "User not found",
variant: "destructive",
duration: 5000,
});
return;
}
setIsSubmitLoading(true);
try {
let success = false;
if (props.isEditing && props.customQuickAction) {
success = await editCustomQuickAction(
{
id: props.customQuickAction.id,
title: name,
prompt,
includePrefix,
includeRecentHistory,
includeReflections,
},
props.allQuickActions,
user.id
);
} else {
success = await createCustomQuickAction(
{
id: uuidv4(),
title: name,
prompt,
includePrefix,
includeRecentHistory,
includeReflections,
},
props.allQuickActions,
user.id
);
}
if (success) {
toast({
title: `Custom quick action ${props.isEditing ? "edited" : "created"} successfully`,
});
handleClearState();
props.onOpenChange(false);
// Re-fetch after creating a new custom quick action to update the list
await props.getAndSetCustomQuickActions(user.id);
} else {
toast({
title: `Failed to ${props.isEditing ? "edit" : "create"} custom quick action`,
variant: "destructive",
});
}
} finally {
setIsSubmitLoading(false);
}
};
const handleClearState = () => {
setName("");
setPrompt("");
setIncludeReflections(true);
setIncludePrefix(true);
setIncludeRecentHistory(true);
setShowFullPrompt(true);
};
return (
<Dialog
open={props.open}
onOpenChange={(change) => {
if (!change) {
handleClearState();
}
props.onOpenChange(change);
}}
>
<DialogContent className="max-w-xl p-8 bg-white rounded-lg shadow-xl min-w-[70vw]">
<DialogHeader>
<DialogTitle className="text-3xl font-light text-gray-800">
<TighterText>
{props.isEditing ? "Edit" : "Create"} Quick Action
</TighterText>
</DialogTitle>
<DialogDescription className="mt-2 text-md font-light text-gray-600">
<TighterText>
Custom quick actions are a way to create your own actions to take
against the selected artifact.
</TighterText>
</DialogDescription>
</DialogHeader>
<form
onSubmit={handleSubmit}
className="flex flex-col items-start justify-start gap-4 w-full"
>
<Label htmlFor="name">
<TighterText>
Name <span className="text-red-500">*</span>
</TighterText>
</Label>
<Input
disabled={isSubmitLoading}
required
id="name"
placeholder="Check for spelling errors"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<div className="flex flex-col gap-1 w-full">
<Label
htmlFor="prompt"
className="flex items-center justify-between w-full"
>
<TighterText>
Prompt <span className="text-red-500 mr-2">*</span>
</TighterText>
<ViewOrHidePromptIcon
showFullPrompt={showFullPrompt}
setShowFullPrompt={setShowFullPrompt}
/>
</Label>
<TighterText className="text-gray-500 text-sm whitespace-normal">
The full prompt includes predefined variables in curly braces
(e.g., <code className="inline-code">{`{artifactContent}`}</code>)
that will be replaced at runtime. Custom variables are not
supported yet.
</TighterText>
<span className="my-1" />
<div className="flex items-center justify-center w-full h-[350px] gap-2 transition-all duration-300 ease-in-out">
<div className="w-full h-full flex flex-col gap-1">
<TighterText className="text-gray-500 text-sm flex items-center">
Custom instructions
<InlineContextTooltip>
<p className="text-sm text-gray-600">
{CUSTOM_INSTRUCTIONS_TOOLTIP_TEXT}
</p>
</InlineContextTooltip>
</TighterText>
<Textarea
disabled={isSubmitLoading}
required
id="prompt"
placeholder="Given the following text..."
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
className="w-full h-full resize-none"
/>
</div>
{showFullPrompt && (
<div className="w-full h-full flex flex-col gap-1">
<TighterText className="text-gray-500 text-sm flex items-center">
Full prompt
<InlineContextTooltip>
<p className="text-sm text-gray-600">
{FULL_PROMPT_TOOLTIP_TEXT}
</p>
</InlineContextTooltip>
</TighterText>
<FullPrompt
customQuickAction={{
title: name,
prompt,
includePrefix,
includeReflections,
includeRecentHistory,
}}
setIncludePrefix={setIncludePrefix}
setIncludeRecentHistory={setIncludeRecentHistory}
setIncludeReflections={setIncludeReflections}
/>
</div>
)}
</div>
</div>
<div className="flex items-center space-x-2">
<Checkbox
disabled={isSubmitLoading}
checked={includePrefix}
onCheckedChange={(c) => setIncludePrefix(!!c)}
id="includeReflections"
/>
<label
htmlFor="includeReflections"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
<TighterText>Include prefix in prompt</TighterText>
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
disabled={isSubmitLoading}
checked={includeReflections}
onCheckedChange={(c) => setIncludeReflections(!!c)}
id="includeReflections"
/>
<label
htmlFor="includeReflections"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
<TighterText>Include reflections in prompt</TighterText>
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
disabled={isSubmitLoading}
checked={includeRecentHistory}
onCheckedChange={(c) => setIncludeRecentHistory(!!c)}
id="includeReflections"
/>
<label
htmlFor="includeReflections"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
<TighterText>Include recent history in prompt</TighterText>
</label>
</div>
<div className="flex items-center justify-center w-full mt-4 gap-3">
<Button disabled={isSubmitLoading} className="w-full" type="submit">
<TighterText>Save</TighterText>
</Button>
<Button
disabled={isSubmitLoading}
onClick={() => {
handleClearState();
props.onOpenChange(false);
}}
variant="destructive"
className="w-[20%]"
type="button"
>
<TighterText>Cancel</TighterText>
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/custom/FullPrompt.tsx | import {
CUSTOM_QUICK_ACTION_ARTIFACT_CONTENT_PROMPT,
CUSTOM_QUICK_ACTION_ARTIFACT_PROMPT_PREFIX,
CUSTOM_QUICK_ACTION_CONVERSATION_CONTEXT,
REFLECTIONS_QUICK_ACTION_PROMPT,
} from "@/agent/open-canvas/prompts";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { CustomQuickAction } from "@/types";
import { Dispatch, SetStateAction, useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
interface FullPromptProps {
customQuickAction: Omit<CustomQuickAction, "id">;
setIncludeReflections: Dispatch<SetStateAction<boolean>>;
setIncludePrefix: Dispatch<SetStateAction<boolean>>;
setIncludeRecentHistory: Dispatch<SetStateAction<boolean>>;
}
interface HighlightToDeleteTextProps {
text: string;
onClick: () => void;
highlight?: boolean;
isVisible: boolean;
}
const HighlightToDeleteText = (props: HighlightToDeleteTextProps) => {
const [isInitialLoad, setIsInitialLoad] = useState(true);
const [isDeleting, setIsDeleting] = useState(false);
const [isHighlighted, setIsHighlighted] = useState(false);
useEffect(() => {
if (isInitialLoad) {
setIsInitialLoad(false);
} else if (props.highlight) {
setIsHighlighted(true);
const timer = setTimeout(() => {
setIsHighlighted(false);
}, 1250);
return () => clearTimeout(timer);
}
}, [props.highlight]);
const handleClick = () => {
setIsDeleting(true);
setTimeout(() => {
props.onClick();
}, 300);
};
return (
<AnimatePresence>
{props.isVisible && (
<TooltipProvider>
<Tooltip delayDuration={100}>
<TooltipTrigger asChild>
<motion.span
layout
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.8 }}
transition={{
opacity: { duration: 0.2 },
scale: { duration: 0.2 },
layout: { duration: 0.3, ease: "easeInOut" },
}}
className={cn(
"inline-block cursor-pointer transition-colors duration-300 ease-in-out hover:bg-red-100",
isDeleting ? "opacity-0 scale-95" : "opacity-100 scale-100",
isHighlighted ? "bg-green-100" : ""
)}
onClick={handleClick}
>
{props.text}
</motion.span>
</TooltipTrigger>
<TooltipContent>Click to delete</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</AnimatePresence>
);
};
export const FullPrompt = (props: FullPromptProps) => {
const [highlightPrefix, setHighlightPrefix] = useState(
props.customQuickAction.includePrefix
);
const [highlightReflections, setHighlightReflections] = useState(
props.customQuickAction.includeReflections
);
const [highlightRecentHistory, setHighlightRecentHistory] = useState(
props.customQuickAction.includeRecentHistory
);
useEffect(() => {
setHighlightPrefix(props.customQuickAction.includePrefix);
}, [props.customQuickAction.includePrefix]);
useEffect(() => {
setHighlightReflections(props.customQuickAction.includeReflections);
}, [props.customQuickAction.includeReflections]);
useEffect(() => {
setHighlightRecentHistory(props.customQuickAction.includeRecentHistory);
}, [props.customQuickAction.includeRecentHistory]);
return (
<div className="border-[1px] bg-gray-50 border-gray-200 rounded-md text-wrap overflow-y-auto w-full h-full text-sm px-3 py-2">
<p className="whitespace-pre-wrap">
<HighlightToDeleteText
text={`${CUSTOM_QUICK_ACTION_ARTIFACT_PROMPT_PREFIX}\n\n`}
onClick={() => props.setIncludePrefix(false)}
highlight={highlightPrefix}
isVisible={props.customQuickAction.includePrefix}
/>
{`<custom-instructions>`}
<br />
{props.customQuickAction.prompt}
<br />
{`</custom-instructions>`}
<HighlightToDeleteText
text={`\n\n${REFLECTIONS_QUICK_ACTION_PROMPT}`}
onClick={() => props.setIncludeReflections(false)}
highlight={highlightReflections}
isVisible={props.customQuickAction.includeReflections}
/>
<HighlightToDeleteText
text={`\n\n${CUSTOM_QUICK_ACTION_CONVERSATION_CONTEXT}`}
onClick={() => props.setIncludeRecentHistory(false)}
highlight={highlightRecentHistory}
isVisible={props.customQuickAction.includeRecentHistory}
/>
{`\n\n`}
{CUSTOM_QUICK_ACTION_ARTIFACT_CONTENT_PROMPT}
</p>
</div>
);
};
|
0 | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar | lc_public_repos/open-canvas/src/components/artifacts/actions_toolbar/custom/index.tsx | import {
CirclePlus,
WandSparkles,
Trash2,
LoaderCircle,
Pencil,
} from "lucide-react";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { CustomQuickAction } from "@/types";
import { NewCustomQuickActionDialog } from "./NewCustomQuickActionDialog";
import { useEffect, useState } from "react";
import { useStore } from "@/hooks/useStore";
import { cn } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";
import { TighterText } from "@/components/ui/header";
import { GraphInput } from "@/contexts/GraphContext";
import { User } from "@supabase/supabase-js";
export interface CustomQuickActionsProps {
isTextSelected: boolean;
assistantId: string | undefined;
user: User | undefined;
streamMessage: (params: GraphInput) => Promise<void>;
}
const DropdownMenuItemWithDelete = ({
disabled,
title,
onDelete,
onEdit,
onClick,
}: {
disabled: boolean;
title: string;
onDelete: () => Promise<void>;
onEdit: () => void;
onClick: () => Promise<void>;
}) => {
const [isHovering, setIsHovering] = useState(false);
return (
<div
className="flex flex-row gap-0 items-center justify-between w-full"
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
>
<DropdownMenuItem
disabled={disabled}
onSelect={onClick}
className="w-full truncate"
>
{title}
</DropdownMenuItem>
<TooltipIconButton
disabled={disabled}
tooltip="Edit action"
variant="ghost"
onClick={onEdit}
className={cn("ml-1", isHovering ? "visible" : "invisible")}
>
<Pencil className="text-[#575757] hover:text-black transition-colors ease-in" />
</TooltipIconButton>
<TooltipIconButton
disabled={disabled}
tooltip="Delete action"
variant="ghost"
onClick={onDelete}
className={cn(isHovering ? "visible" : "invisible")}
>
<Trash2 className="text-[#575757] hover:text-red-500 transition-colors ease-in" />
</TooltipIconButton>
</div>
);
};
export function CustomQuickActions(props: CustomQuickActionsProps) {
const { user, assistantId, streamMessage } = props;
const {
getCustomQuickActions,
deleteCustomQuickAction,
isLoadingQuickActions,
} = useStore();
const { toast } = useToast();
const [open, setOpen] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [isEditingId, setIsEditingId] = useState<string>();
const [customQuickActions, setCustomQuickActions] =
useState<CustomQuickAction[]>();
const openEditDialog = (id: string) => {
setIsEditing(true);
setDialogOpen(true);
setIsEditingId(id);
};
const getAndSetCustomQuickActions = async (userId: string) => {
const actions = await getCustomQuickActions(userId);
setCustomQuickActions(actions);
};
useEffect(() => {
if (typeof window === undefined || !assistantId || !user) return;
getAndSetCustomQuickActions(user.id);
}, [assistantId, user]);
const handleNewActionClick = (e: Event) => {
e.preventDefault();
e.stopPropagation();
setIsEditing(false);
setIsEditingId(undefined);
setDialogOpen(true);
};
const handleQuickActionClick = async (id: string): Promise<void> => {
setOpen(false);
setIsEditing(false);
setIsEditingId(undefined);
await streamMessage({
customQuickActionId: id,
});
};
const handleDelete = async (id: string) => {
if (!user) {
toast({
title: "Failed to delete",
description: "User not found",
variant: "destructive",
duration: 5000,
});
return;
}
try {
const deletionSuccess = await deleteCustomQuickAction(
id,
customQuickActions || [],
user.id
);
if (deletionSuccess) {
toast({
title: "Custom quick action deleted successfully",
});
setCustomQuickActions((actions) => {
if (!actions) return actions;
return actions.filter((action) => action.id !== id);
});
} else {
toast({
title: "Failed to delete custom quick action",
variant: "destructive",
});
}
} catch (_) {
toast({
title: "Failed to delete custom quick action",
variant: "destructive",
});
}
};
return (
<DropdownMenu
open={open}
onOpenChange={(o) => {
if (props.isTextSelected) return;
setOpen(o);
}}
>
<DropdownMenuTrigger className="fixed bottom-4 right-20" asChild>
<TooltipIconButton
tooltip={
props.isTextSelected
? "Quick actions disabled while text is selected"
: "Custom quick actions"
}
variant="outline"
className={cn(
"transition-colors w-[48px] h-[48px] p-0 rounded-xl",
props.isTextSelected
? "cursor-default opacity-50 text-gray-400 hover:bg-background"
: "cursor-pointer"
)}
delayDuration={400}
>
<WandSparkles
className={cn(
"w-[26px] h-[26px]",
props.isTextSelected
? "text-gray-400"
: "hover:text-gray-900 transition-colors"
)}
/>
</TooltipIconButton>
</DropdownMenuTrigger>
<DropdownMenuContent className="max-h-[600px] max-w-[300px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
<DropdownMenuLabel>
<TighterText>Custom Quick Actions</TighterText>
</DropdownMenuLabel>
<DropdownMenuSeparator />
{isLoadingQuickActions && !customQuickActions?.length ? (
<span className="text-sm text-gray-600 flex items-center justify-start gap-1 p-2">
Loading
<LoaderCircle className="w-4 h-4 animate-spin" />
</span>
) : !customQuickActions?.length ? (
<TighterText className="text-sm text-gray-600 p-2">
No custom quick actions found.
</TighterText>
) : (
<div className="max-h-[450px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
{customQuickActions.map((action) => (
<DropdownMenuItemWithDelete
key={action.id}
disabled={props.isTextSelected}
onDelete={async () => await handleDelete(action.id)}
title={action.title}
onClick={async () => await handleQuickActionClick(action.id)}
onEdit={() => openEditDialog(action.id)}
/>
))}
</div>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
disabled={props.isTextSelected}
onSelect={handleNewActionClick}
className="flex items-center justify-start gap-1"
>
<CirclePlus className="w-4 h-4" />
<TighterText className="font-medium">New</TighterText>
</DropdownMenuItem>
</DropdownMenuContent>
<NewCustomQuickActionDialog
user={user}
allQuickActions={customQuickActions || []}
isEditing={isEditing}
open={dialogOpen}
onOpenChange={(c) => {
setDialogOpen(c);
if (!c) {
setIsEditing(false);
}
}}
customQuickAction={
isEditing && isEditingId
? customQuickActions?.find((a) => a.id === isEditingId)
: undefined
}
getAndSetCustomQuickActions={getAndSetCustomQuickActions}
/>
</DropdownMenu>
);
}
|
0 | lc_public_repos/open-canvas/src/components/artifacts | lc_public_repos/open-canvas/src/components/artifacts/components/AskOpenCanvas.tsx | import { Dispatch, FormEvent, forwardRef, SetStateAction } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { CircleArrowUp } from "lucide-react";
import { cn } from "@/lib/utils";
import { ArtifactV3 } from "@/types";
import { getArtifactContent } from "@/contexts/utils";
import { isArtifactCodeContent } from "@/lib/artifact_content_types";
import { useToast } from "@/hooks/use-toast";
interface AskOpenCanvasProps {
isInputVisible: boolean;
selectionBox: { top: number; left: number };
setIsInputVisible: (visible: boolean) => void;
handleSubmitMessage: (inputValue: string) => Promise<void>;
handleSelectionBoxMouseDown: (e: React.MouseEvent) => void;
artifact: ArtifactV3;
selectionIndexes: { start: number; end: number } | undefined;
handleCleanupState: () => void;
inputValue: string;
setInputValue: Dispatch<SetStateAction<string>>;
}
export const AskOpenCanvas = forwardRef<HTMLDivElement, AskOpenCanvasProps>(
(props, ref) => {
const { toast } = useToast();
const {
isInputVisible,
selectionBox,
selectionIndexes,
inputValue,
setInputValue,
setIsInputVisible,
handleSubmitMessage,
handleSelectionBoxMouseDown,
handleCleanupState,
} = props;
const handleSubmit = async (
e:
| FormEvent<HTMLFormElement>
| React.MouseEvent<HTMLButtonElement, MouseEvent>
) => {
e.preventDefault();
const artifactContent = props.artifact
? getArtifactContent(props.artifact)
: undefined;
if (
!selectionIndexes &&
artifactContent &&
isArtifactCodeContent(artifactContent)
) {
toast({
title: "Selection error",
description:
"Failed to get start/end indexes of the selected text. Please try again.",
duration: 5000,
});
handleCleanupState();
return;
}
if (selectionBox && props.artifact) {
await handleSubmitMessage(inputValue);
} else {
toast({
title: "Selection error",
description: "Failed to get selection box. Please try again.",
duration: 5000,
});
handleCleanupState();
}
};
return (
<div
ref={ref}
className={cn(
"absolute bg-white border border-gray-200 shadow-md p-2 flex gap-2",
isInputVisible ? "rounded-3xl" : "rounded-md"
)}
style={{
top: `${selectionBox.top + 60}px`,
left: `${selectionBox.left}px`,
width: isInputVisible ? "400px" : "250px",
marginLeft: isInputVisible ? "0" : "150px",
}}
onMouseDown={handleSelectionBoxMouseDown}
>
{isInputVisible ? (
<form
onSubmit={handleSubmit}
className="relative w-full overflow-hidden flex flex-row items-center gap-1"
>
<Input
className="w-full transition-all duration-300 focus:ring-0 ease-in-out p-1 focus:outline-none border-0 focus-visible:ring-0"
placeholder="Ask Open Canvas..."
autoFocus
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<Button
onClick={(e) => handleSubmit(e)}
type="submit"
variant="ghost"
size="icon"
>
<CircleArrowUp
className="cursor-pointer"
fill="black"
stroke="white"
size={30}
/>
</Button>
</form>
) : (
<Button
variant="ghost"
onClick={() => setIsInputVisible(true)}
className="transition-all duration-300 ease-in-out w-full"
>
Ask Open Canvas
</Button>
)}
</div>
);
}
);
AskOpenCanvas.displayName = "AskOpenCanvas";
|
0 | lc_public_repos/open-canvas/src/components/artifacts | lc_public_repos/open-canvas/src/components/artifacts/components/CopyText.tsx | import { motion } from "framer-motion";
import { TooltipIconButton } from "@/components/ui/assistant-ui/tooltip-icon-button";
import { useToast } from "@/hooks/use-toast";
import { isArtifactCodeContent } from "@/lib/artifact_content_types";
import { ArtifactCodeV3, ArtifactMarkdownV3 } from "@/types";
import { Copy } from "lucide-react";
interface CopyTextProps {
currentArtifactContent: ArtifactCodeV3 | ArtifactMarkdownV3;
}
export function CopyText(props: CopyTextProps) {
const { toast } = useToast();
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2 }}
>
<TooltipIconButton
tooltip="Copy"
variant="outline"
className="transition-colors"
delayDuration={400}
onClick={() => {
try {
const text = isArtifactCodeContent(props.currentArtifactContent)
? props.currentArtifactContent.code
: props.currentArtifactContent.fullMarkdown;
navigator.clipboard.writeText(text).then(() => {
toast({
title: "Copied to clipboard",
description: "The canvas content has been copied.",
duration: 5000,
});
});
} catch (_) {
toast({
title: "Copy error",
description:
"Failed to copy the canvas content. Please try again.",
duration: 5000,
});
}
}}
>
<Copy className="w-5 h-5 text-gray-600" />
</TooltipIconButton>
</motion.div>
);
}
|
0 | lc_public_repos/open-canvas/src | lc_public_repos/open-canvas/src/agent/utils.ts | import { isArtifactCodeContent } from "@/lib/artifact_content_types";
import { BaseStore, LangGraphRunnableConfig } from "@langchain/langgraph";
import { ArtifactCodeV3, ArtifactMarkdownV3, Reflections } from "../types";
import { initChatModel } from "langchain/chat_models/universal";
export const formatReflections = (
reflections: Reflections,
extra?: {
/**
* Will only include the style guidelines in the output.
* If this is set to true, you may not specify `onlyContent` as `true`.
*/
onlyStyle?: boolean;
/**
* Will only include the content in the output.
* If this is set to true, you may not specify `onlyStyle` as `true`.
*/
onlyContent?: boolean;
}
): string => {
if (extra?.onlyStyle && extra?.onlyContent) {
throw new Error(
"Cannot specify both `onlyStyle` and `onlyContent` as true."
);
}
let styleRulesArr = reflections.styleRules;
let styleRulesStr = "No style guidelines found.";
if (!Array.isArray(styleRulesArr)) {
try {
styleRulesArr = JSON.parse(styleRulesArr);
styleRulesStr = styleRulesArr.join("\n- ");
} catch (_) {
console.error(
"FAILED TO PARSE STYLE RULES. \n\ntypeof:",
typeof styleRulesArr,
"\n\nstyleRules:",
styleRulesArr
);
}
}
let contentRulesArr = reflections.content;
let contentRulesStr = "No memories/facts found.";
if (!Array.isArray(contentRulesArr)) {
try {
contentRulesArr = JSON.parse(contentRulesArr);
contentRulesStr = contentRulesArr.join("\n- ");
} catch (_) {
console.error(
"FAILED TO PARSE CONTENT RULES. \n\ntypeof:",
typeof contentRulesArr,
"\ncontentRules:",
contentRulesArr
);
}
}
const styleString = `The following is a list of style guidelines previously generated by you:
<style-guidelines>
- ${styleRulesStr}
</style-guidelines>`;
const contentString = `The following is a list of memories/facts you previously generated about the user:
<user-facts>
- ${contentRulesStr}
</user-facts>`;
if (extra?.onlyStyle) {
return styleString;
}
if (extra?.onlyContent) {
return contentString;
}
return styleString + "\n\n" + contentString;
};
export async function getFormattedReflections(
config: LangGraphRunnableConfig
): Promise<string> {
const store = ensureStoreInConfig(config);
const assistantId = config.configurable?.assistant_id;
if (!assistantId) {
throw new Error("`assistant_id` not found in configurable");
}
const memoryNamespace = ["memories", assistantId];
const memoryKey = "reflection";
const memories = await store.get(memoryNamespace, memoryKey);
const memoriesAsString = memories?.value
? formatReflections(memories.value as Reflections)
: "No reflections found.";
return memoriesAsString;
}
export const ensureStoreInConfig = (
config: LangGraphRunnableConfig
): BaseStore => {
if (!config.store) {
throw new Error("`store` not found in config");
}
return config.store;
};
export const formatArtifactContent = (
content: ArtifactMarkdownV3 | ArtifactCodeV3,
shortenContent?: boolean
): string => {
let artifactContent: string;
if (isArtifactCodeContent(content)) {
artifactContent = shortenContent
? content.code?.slice(0, 500)
: content.code;
} else {
artifactContent = shortenContent
? content.fullMarkdown?.slice(0, 500)
: content.fullMarkdown;
}
return `Title: ${content.title}\nArtifact type: ${content.type}\nContent: ${artifactContent}`;
};
export const formatArtifactContentWithTemplate = (
template: string,
content: ArtifactMarkdownV3 | ArtifactCodeV3,
shortenContent?: boolean
): string => {
return template.replace(
"{artifact}",
formatArtifactContent(content, shortenContent)
);
};
export const getModelConfig = (
config: LangGraphRunnableConfig
): {
modelName: string;
modelProvider: string;
azureConfig?: {
azureOpenAIApiKey: string;
azureOpenAIApiInstanceName: string;
azureOpenAIApiDeploymentName: string;
azureOpenAIApiVersion: string;
azureOpenAIBasePath?: string;
};
} => {
const customModelName = config.configurable?.customModelName as string;
if (!customModelName) {
throw new Error("Model name is missing in config.");
}
if (customModelName.startsWith("azure/")) {
const actualModelName = customModelName.replace("azure/", "");
return {
modelName: actualModelName,
modelProvider: "azure_openai",
azureConfig: {
azureOpenAIApiKey: process.env._AZURE_OPENAI_API_KEY || "",
azureOpenAIApiInstanceName:
process.env._AZURE_OPENAI_API_INSTANCE_NAME || "",
azureOpenAIApiDeploymentName:
process.env._AZURE_OPENAI_API_DEPLOYMENT_NAME || "",
azureOpenAIApiVersion:
process.env._AZURE_OPENAI_API_VERSION || "2024-08-01-preview",
azureOpenAIBasePath: process.env._AZURE_OPENAI_API_BASE_PATH,
},
};
}
if (customModelName.includes("gpt-")) {
return {
modelName: customModelName,
modelProvider: "openai",
};
}
if (customModelName.includes("claude-")) {
return {
modelName: customModelName,
modelProvider: "anthropic",
};
}
if (customModelName.includes("fireworks/")) {
return {
modelName: customModelName,
modelProvider: "fireworks",
};
}
if (customModelName.includes("gemini-")) {
return {
modelName: customModelName,
modelProvider: "google-genai",
};
}
throw new Error("Unknown model provider");
};
export function optionallyGetSystemPromptFromConfig(
config: LangGraphRunnableConfig
): string | undefined {
return config.configurable?.systemPrompt as string | undefined;
}
export async function getModelFromConfig(
config: LangGraphRunnableConfig,
extra?: {
temperature?: number;
maxTokens?: number;
}
) {
const { temperature = 0.5, maxTokens } = extra || {};
const { modelName, modelProvider, azureConfig } = getModelConfig(config);
return await initChatModel(modelName, {
modelProvider,
temperature,
maxTokens,
...(azureConfig != null
? {
azureOpenAIApiKey: azureConfig.azureOpenAIApiKey,
azureOpenAIApiInstanceName: azureConfig.azureOpenAIApiInstanceName,
azureOpenAIApiDeploymentName:
azureConfig.azureOpenAIApiDeploymentName,
azureOpenAIApiVersion: azureConfig.azureOpenAIApiVersion,
azureOpenAIBasePath: azureConfig.azureOpenAIBasePath,
}
: {}),
});
}
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/thread-title/index.ts | import {
type LangGraphRunnableConfig,
START,
StateGraph,
} from "@langchain/langgraph";
import { Client } from "@langchain/langgraph-sdk";
import { ChatOpenAI } from "@langchain/openai";
import { z } from "zod";
import { getArtifactContent } from "../../contexts/utils";
import { isArtifactMarkdownContent } from "../../lib/artifact_content_types";
import { TITLE_SYSTEM_PROMPT, TITLE_USER_PROMPT } from "./prompts";
import { TitleGenerationAnnotation, TitleGenerationReturnType } from "./state";
export const generateTitle = async (
state: typeof TitleGenerationAnnotation.State,
config: LangGraphRunnableConfig
): Promise<TitleGenerationReturnType> => {
const threadId = config.configurable?.open_canvas_thread_id;
if (!threadId) {
throw new Error("open_canvas_thread_id not found in configurable");
}
const generateTitleTool = {
name: "generate_title",
description: "Generate a concise title for the conversation.",
schema: z.object({
title: z.string().describe("The generated title for the conversation."),
}),
};
const model = new ChatOpenAI({
model: "gpt-4o-mini",
temperature: 0,
}).bindTools([generateTitleTool], {
tool_choice: "generate_title",
});
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
const artifactContent = currentArtifactContent
? isArtifactMarkdownContent(currentArtifactContent)
? currentArtifactContent.fullMarkdown
: currentArtifactContent.code
: undefined;
const artifactContext = artifactContent
? `An artifact was generated during this conversation:\n\n${artifactContent}`
: "No artifact was generated during this conversation.";
const formattedUserPrompt = TITLE_USER_PROMPT.replace(
"{conversation}",
state.messages
.map((msg) => `<${msg.getType()}>\n${msg.content}\n</${msg.getType()}>`)
.join("\n\n")
).replace("{artifact_context}", artifactContext);
const result = await model.invoke([
{
role: "system",
content: TITLE_SYSTEM_PROMPT,
},
{
role: "user",
content: formattedUserPrompt,
},
]);
const titleToolCall = result.tool_calls?.[0];
if (!titleToolCall) {
console.error("FAILED TO GENERATE TOOL CALL", result);
throw new Error("Title generation tool call failed.");
}
const langGraphClient = new Client({
apiUrl: `http://localhost:${process.env.PORT}`,
defaultHeaders: {
"X-API-KEY": process.env.LANGCHAIN_API_KEY,
},
});
// Update thread metadata with the generated title
await langGraphClient.threads.update(threadId, {
metadata: {
thread_title: titleToolCall.args.title,
},
});
return {};
};
const builder = new StateGraph(TitleGenerationAnnotation)
.addNode("title", generateTitle)
.addEdge(START, "title");
export const graph = builder.compile().withConfig({ runName: "thread_title" });
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/thread-title/state.ts | import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
import { ArtifactV3 } from "../../types";
export const TitleGenerationAnnotation = Annotation.Root({
/**
* The chat history to generate a title for
*/
...MessagesAnnotation.spec,
/**
* The artifact that was generated/updated (if any)
*/
artifact: Annotation<ArtifactV3 | undefined>,
});
export type TitleGenerationReturnType = Partial<
typeof TitleGenerationAnnotation.State
>;
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/thread-title/prompts.ts | export const TITLE_SYSTEM_PROMPT = `You are tasked with generating a concise, descriptive title for a conversation between a user and an AI assistant. The title should capture the main topic or purpose of the conversation.
Guidelines for title generation:
- Keep titles extremely short (ideally 2-5 words)
- Focus on the main topic or goal of the conversation
- Use natural, readable language
- Avoid unnecessary articles (a, an, the) when possible
- Do not include quotes or special characters
- Capitalize important words
Use the 'generate_title' tool to output your title.`;
export const TITLE_USER_PROMPT = `Based on the following conversation, generate a very short and descriptive title for:
{conversation}
{artifact_context}`;
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/reflection/index.ts | import { ChatAnthropic } from "@langchain/anthropic";
import {
type LangGraphRunnableConfig,
StateGraph,
START,
} from "@langchain/langgraph";
import { ReflectionGraphAnnotation, ReflectionGraphReturnType } from "./state";
import { Reflections } from "../../types";
import { REFLECT_SYSTEM_PROMPT, REFLECT_USER_PROMPT } from "./prompts";
import { z } from "zod";
import { ensureStoreInConfig, formatReflections } from "../utils";
import { getArtifactContent } from "../../contexts/utils";
import { isArtifactMarkdownContent } from "../../lib/artifact_content_types";
export const reflect = async (
state: typeof ReflectionGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<ReflectionGraphReturnType> => {
const store = ensureStoreInConfig(config);
const assistantId = config.configurable?.open_canvas_assistant_id;
if (!assistantId) {
throw new Error("`open_canvas_assistant_id` not found in configurable");
}
const memoryNamespace = ["memories", assistantId];
const memoryKey = "reflection";
const memories = await store.get(memoryNamespace, memoryKey);
const memoriesAsString = memories?.value
? formatReflections(memories.value as Reflections)
: "No reflections found.";
const generateReflectionTool = {
name: "generate_reflections",
description: "Generate reflections based on the context provided.",
schema: z.object({
styleRules: z
.array(z.string())
.describe("The complete new list of style rules and guidelines."),
content: z
.array(z.string())
.describe("The complete new list of memories/facts about the user."),
}),
};
const model = new ChatAnthropic({
model: "claude-3-5-sonnet-20240620",
temperature: 0,
}).bindTools([generateReflectionTool], {
tool_choice: "generate_reflections",
});
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
const artifactContent = currentArtifactContent
? isArtifactMarkdownContent(currentArtifactContent)
? currentArtifactContent.fullMarkdown
: currentArtifactContent.code
: undefined;
const formattedSystemPrompt = REFLECT_SYSTEM_PROMPT.replace(
"{artifact}",
artifactContent ?? "No artifact found."
).replace("{reflections}", memoriesAsString);
const formattedUserPrompt = REFLECT_USER_PROMPT.replace(
"{conversation}",
state.messages
.map((msg) => `<${msg.getType()}>\n${msg.content}\n</${msg.getType()}>`)
.join("\n\n")
);
const result = await model.invoke([
{
role: "system",
content: formattedSystemPrompt,
},
{
role: "user",
content: formattedUserPrompt,
},
]);
const reflectionToolCall = result.tool_calls?.[0];
if (!reflectionToolCall) {
console.error("FAILED TO GENERATE TOOL CALL", result);
throw new Error("Reflection tool call failed.");
}
const newMemories = {
styleRules: reflectionToolCall.args.styleRules,
content: reflectionToolCall.args.content,
};
await store.put(memoryNamespace, memoryKey, newMemories);
return {};
};
const builder = new StateGraph(ReflectionGraphAnnotation)
.addNode("reflect", reflect)
.addEdge(START, "reflect");
export const graph = builder.compile().withConfig({ runName: "reflection" });
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/reflection/state.ts | import { ArtifactV3 } from "../../types";
import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
export const ReflectionGraphAnnotation = Annotation.Root({
/**
* The chat history to reflect on.
*/
...MessagesAnnotation.spec,
/**
* The artifact to reflect on.
*/
artifact: Annotation<ArtifactV3 | undefined>,
});
export type ReflectionGraphReturnType = Partial<
typeof ReflectionGraphAnnotation.State
>;
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/reflection/prompts.ts | export const REFLECT_SYSTEM_PROMPT = `You are an expert assistant, and writer. You are tasked with reflecting on the following conversation between a user and an AI assistant.
You are also provided with an 'artifact' the user and assistant worked together on to write. Artifacts can be code, creative writing, emails, or any other form of written content.
<artifact>
{artifact}
</artifact>
You have also previously generated the following reflections about the user. Your reflections are broken down into two categories:
1. Style Guidelines: These are the style guidelines you have generated for the user. Style guidelines can be anything from writing style, to code style, to design style.
They should be general, and apply to the all the users work, including the conversation and artifact generated.
2. Content: These are general memories, facts, and insights you generate about the user. These can be anything from the users interests, to their goals, to their personality traits.
Ensure you think carefully about what goes in here, as the assistant will use these when generating future responses or artifacts for the user.
<reflections>
{reflections}
</reflections>
Your job is to take all of the context and existing reflections and re-generate all. Use these guidelines when generating the new set of reflections:
<system-guidelines>
- Ensure your reflections are relevant to the conversation and artifact.
- Remove duplicate reflections, or combine multiple reflections into one if they are duplicating content.
- Do not remove reflections unless the conversation/artifact clearly demonstrates they should no longer be included.
This does NOT mean remove reflections if you see no evidence of them in the conversation/artifact, but instead remove them if the user indicates they are no longer relevant.
- Keep the rules you list high signal-to-noise - don't include unnecessary reflections, but make sure the ones you do add are descriptive.
This is very important. We do NOT want to confuse the assistant in future interactions by having lots and lots of rules and memories.
- Your reflections should be very descriptive and detailed, ensuring they are clear and will not be misinterpreted.
- Keep the total number of style and user facts low. It's better to have individual rules be more detailed, than to have many rules that are vague.
- Do NOT generate rules off of suspicions. Your rules should be based on cold hard facts from the conversation, and changes to the artifact the user has requested.
You must be able to provide evidence and sources for each rule you generate if asked, so don't make assumptions.
- Content reflections should be based on the user's messages, not the generated artifacts. Ensure you follow this rule closely to ensure you do not record things generated by the assistant as facts about the user.
</system-guidelines>
I'll reiterate one final time: ensure the reflections you generate are kept at a reasonable length, are descriptive, and are based on the conversation and artifact provided.
Finally, use the 'generate_reflections' tool to generate the new, full list of reflections.`;
export const REFLECT_USER_PROMPT = `Here is my conversation:
{conversation}`;
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/open-canvas/index.ts | import { END, Send, START, StateGraph } from "@langchain/langgraph";
import { DEFAULT_INPUTS } from "../../constants";
import { customAction } from "./nodes/customAction";
import { generateArtifact } from "./nodes/generate-artifact";
import { generateFollowup } from "./nodes/generateFollowup";
import { generatePath } from "./nodes/generatePath";
import { reflectNode } from "./nodes/reflect";
import { rewriteArtifact } from "./nodes/rewrite-artifact";
import { rewriteArtifactTheme } from "./nodes/rewriteArtifactTheme";
import { updateArtifact } from "./nodes/updateArtifact";
import { replyToGeneralInput } from "./nodes/replyToGeneralInput";
import { rewriteCodeArtifactTheme } from "./nodes/rewriteCodeArtifactTheme";
import { generateTitleNode } from "./nodes/generateTitle";
import { updateHighlightedText } from "./nodes/updateHighlightedText";
import { OpenCanvasGraphAnnotation } from "./state";
const routeNode = (state: typeof OpenCanvasGraphAnnotation.State) => {
if (!state.next) {
throw new Error("'next' state field not set.");
}
return new Send(state.next, {
...state,
});
};
const cleanState = (_: typeof OpenCanvasGraphAnnotation.State) => {
return {
...DEFAULT_INPUTS,
};
};
/**
* Conditionally route to the "generateTitle" node if there are only
* two messages in the conversation. This node generates a concise title
* for the conversation which is displayed in the thread history.
*/
const conditionallyGenerateTitle = (
state: typeof OpenCanvasGraphAnnotation.State
) => {
if (state.messages.length > 2) {
// Do not generate if there are more than two messages (meaning it's not the first human-AI conversation)
return END;
}
return "generateTitle";
};
const builder = new StateGraph(OpenCanvasGraphAnnotation)
// Start node & edge
.addNode("generatePath", generatePath)
.addEdge(START, "generatePath")
// Nodes
.addNode("replyToGeneralInput", replyToGeneralInput)
.addNode("rewriteArtifact", rewriteArtifact)
.addNode("rewriteArtifactTheme", rewriteArtifactTheme)
.addNode("rewriteCodeArtifactTheme", rewriteCodeArtifactTheme)
.addNode("updateArtifact", updateArtifact)
.addNode("updateHighlightedText", updateHighlightedText)
.addNode("generateArtifact", generateArtifact)
.addNode("customAction", customAction)
.addNode("generateFollowup", generateFollowup)
.addNode("cleanState", cleanState)
.addNode("reflect", reflectNode)
.addNode("generateTitle", generateTitleNode)
// Initial router
.addConditionalEdges("generatePath", routeNode, [
"updateArtifact",
"rewriteArtifactTheme",
"rewriteCodeArtifactTheme",
"replyToGeneralInput",
"generateArtifact",
"rewriteArtifact",
"customAction",
"updateHighlightedText",
])
// Edges
.addEdge("generateArtifact", "generateFollowup")
.addEdge("updateArtifact", "generateFollowup")
.addEdge("updateHighlightedText", "generateFollowup")
.addEdge("rewriteArtifact", "generateFollowup")
.addEdge("rewriteArtifactTheme", "generateFollowup")
.addEdge("rewriteCodeArtifactTheme", "generateFollowup")
.addEdge("customAction", "generateFollowup")
// End edges
.addEdge("replyToGeneralInput", "cleanState")
// Only reflect if an artifact was generated/updated.
.addEdge("generateFollowup", "reflect")
.addEdge("reflect", "cleanState")
.addConditionalEdges("cleanState", conditionallyGenerateTitle, [
END,
"generateTitle",
])
.addEdge("generateTitle", END);
export const graph = builder.compile().withConfig({ runName: "open_canvas" });
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/open-canvas/state.ts | import {
ArtifactLengthOptions,
LanguageOptions,
ProgrammingLanguageOptions,
ReadingLevelOptions,
CodeHighlight,
ArtifactV3,
TextHighlight,
} from "../../types";
import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
export const OpenCanvasGraphAnnotation = Annotation.Root({
...MessagesAnnotation.spec,
/**
* The part of the artifact the user highlighted. Use the `selectedArtifactId`
* to determine which artifact the highlight belongs to.
*/
highlightedCode: Annotation<CodeHighlight | undefined>,
/**
* The highlighted text. This includes the markdown blocks which the highlighted
* text belongs to, along with the entire plain text content of highlight.
*/
highlightedText: Annotation<TextHighlight | undefined>,
/**
* The artifacts that have been generated in the conversation.
*/
artifact: Annotation<ArtifactV3>,
/**
* The next node to route to. Only used for the first routing node/conditional edge.
*/
next: Annotation<string | undefined>,
/**
* The language to translate the artifact to.
*/
language: Annotation<LanguageOptions | undefined>,
/**
* The length of the artifact to regenerate to.
*/
artifactLength: Annotation<ArtifactLengthOptions | undefined>,
/**
* Whether or not to regenerate with emojis.
*/
regenerateWithEmojis: Annotation<boolean | undefined>,
/**
* The reading level to adjust the artifact to.
*/
readingLevel: Annotation<ReadingLevelOptions | undefined>,
/**
* Whether or not to add comments to the code artifact.
*/
addComments: Annotation<boolean | undefined>,
/**
* Whether or not to add logs to the code artifact.
*/
addLogs: Annotation<boolean | undefined>,
/**
* The programming language to port the code artifact to.
*/
portLanguage: Annotation<ProgrammingLanguageOptions | undefined>,
/**
* Whether or not to fix bugs in the code artifact.
*/
fixBugs: Annotation<boolean | undefined>,
/**
* The ID of the custom quick action to use.
*/
customQuickActionId: Annotation<string | undefined>,
});
export type OpenCanvasGraphReturnType = Partial<
typeof OpenCanvasGraphAnnotation.State
>;
|
0 | lc_public_repos/open-canvas/src/agent | lc_public_repos/open-canvas/src/agent/open-canvas/prompts.ts | const DEFAULT_CODE_PROMPT_RULES = `- Do NOT include triple backticks when generating code. The code should be in plain text.`;
const APP_CONTEXT = `
<app-context>
The name of the application is "Open Canvas". Open Canvas is a web application where users have a chat window and a canvas to display an artifact.
Artifacts can be any sort of writing content, emails, code, or other creative writing work. Think of artifacts as content, or writing you might find on you might find on a blog, Google doc, or other writing platform.
Users only have a single artifact per conversation, however they have the ability to go back and fourth between artifact edits/revisions.
If a user asks you to generate something completely different from the current artifact, you may do this, as the UI displaying the artifacts will be updated to show whatever they've requested.
Even if the user goes from a 'text' artifact to a 'code' artifact.
</app-context>
`;
export const NEW_ARTIFACT_PROMPT = `You are an AI assistant tasked with generating a new artifact based on the users request.
Ensure you use markdown syntax when appropriate, as the text you generate will be rendered in markdown.
Use the full chat history as context when generating the artifact.
Follow these rules and guidelines:
<rules-guidelines>
- Do not wrap it in any XML tags you see in this prompt.
- If writing code, do not add inline comments unless the user has specifically requested them. This is very important as we don't want to clutter the code.
${DEFAULT_CODE_PROMPT_RULES}
</rules-guidelines>
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
{disableChainOfThought}`;
export const UPDATE_HIGHLIGHTED_ARTIFACT_PROMPT = `You are an AI assistant, and the user has requested you make an update to a specific part of an artifact you generated in the past.
Here is the relevant part of the artifact, with the highlighted text between <highlight> tags:
{beforeHighlight}<highlight>{highlightedText}</highlight>{afterHighlight}
Please update the highlighted text based on the user's request.
Follow these rules and guidelines:
<rules-guidelines>
- ONLY respond with the updated text, not the entire artifact.
- Do not include the <highlight> tags, or extra content in your response.
- Do not wrap it in any XML tags you see in this prompt.
- Do NOT wrap in markdown blocks (e.g triple backticks) unless the highlighted text ALREADY contains markdown syntax.
If you insert markdown blocks inside the highlighted text when they are already defined outside the text, you will break the markdown formatting.
- You should use proper markdown syntax when appropriate, as the text you generate will be rendered in markdown.
- NEVER generate content that is not included in the highlighted text. Whether the highlighted text be a single character, split a single word,
an incomplete sentence, or an entire paragraph, you should ONLY generate content that is within the highlighted text.
${DEFAULT_CODE_PROMPT_RULES}
</rules-guidelines>
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
Use the user's recent message below to make the edit.`;
export const GET_TITLE_TYPE_REWRITE_ARTIFACT = `You are an AI assistant who has been tasked with analyzing the users request to rewrite an artifact.
Your task is to determine what the title and type of the artifact should be based on the users request.
You should NOT modify the title unless the users request indicates the artifact subject/topic has changed.
You do NOT need to change the type unless it is clear the user is asking for their artifact to be a different type.
Use this context about the application when making your decision:
${APP_CONTEXT}
The types you can choose from are:
- 'text': This is a general text artifact. This could be a poem, story, email, or any other type of writing.
- 'code': This is a code artifact. This could be a code snippet, a full program, or any other type of code.
Be careful when selecting the type, as this will update how the artifact is displayed in the UI.
Remember, if you change the type from 'text' to 'code' you must also define the programming language the code should be written in.
Here is the current artifact (only the first 500 characters, or less if the artifact is shorter):
<artifact>
{artifact}
</artifact>
The users message below is the most recent message they sent. Use this to determine what the title and type of the artifact should be.`;
export const OPTIONALLY_UPDATE_META_PROMPT = `It has been pre-determined based on the users message and other context that the type of the artifact should be:
{artifactType}
{artifactTitle}
You should use this as context when generating your response.`;
export const UPDATE_ENTIRE_ARTIFACT_PROMPT = `You are an AI assistant, and the user has requested you make an update to an artifact you generated in the past.
Here is the current content of the artifact:
<artifact>
{artifactContent}
</artifact>
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
Please update the artifact based on the user's request.
Follow these rules and guidelines:
<rules-guidelines>
- You should respond with the ENTIRE updated artifact, with no additional text before and after.
- Do not wrap it in any XML tags you see in this prompt.
- You should use proper markdown syntax when appropriate, as the text you generate will be rendered in markdown. UNLESS YOU ARE WRITING CODE.
- When you generate code, a markdown renderer is NOT used so if you respond with code in markdown syntax, or wrap the code in tipple backticks it will break the UI for the user.
- If generating code, it is imperative you never wrap it in triple backticks, or prefix/suffix it with plain text. Ensure you ONLY respond with the code.
${DEFAULT_CODE_PROMPT_RULES}
</rules-guidelines>
{updateMetaPrompt}
Ensure you ONLY reply with the rewritten artifact and NO other content.
`;
// ----- Text modification prompts -----
export const CHANGE_ARTIFACT_LANGUAGE_PROMPT = `You are tasked with changing the language of the following artifact to {newLanguage}.
Here is the current content of the artifact:
<artifact>
{artifactContent}
</artifact>
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
Rules and guidelines:
<rules-guidelines>
- ONLY change the language and nothing else.
- Respond with ONLY the updated artifact, and no additional text before or after.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated artifact.
</rules-guidelines>`;
export const CHANGE_ARTIFACT_READING_LEVEL_PROMPT = `You are tasked with re-writing the following artifact to be at a {newReadingLevel} reading level.
Ensure you do not change the meaning or story behind the artifact, simply update the language to be of the appropriate reading level for a {newReadingLevel} audience.
Here is the current content of the artifact:
<artifact>
{artifactContent}
</artifact>
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
Rules and guidelines:
<rules-guidelines>
- Respond with ONLY the updated artifact, and no additional text before or after.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated artifact.
</rules-guidelines>`;
export const CHANGE_ARTIFACT_TO_PIRATE_PROMPT = `You are tasked with re-writing the following artifact to sound like a pirate.
Ensure you do not change the meaning or story behind the artifact, simply update the language to sound like a pirate.
Here is the current content of the artifact:
<artifact>
{artifactContent}
</artifact>
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
Rules and guidelines:
<rules-guidelines>
- Respond with ONLY the updated artifact, and no additional text before or after.
- Ensure you respond with the entire updated artifact, and not just the new content.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated artifact.
</rules-guidelines>`;
export const CHANGE_ARTIFACT_LENGTH_PROMPT = `You are tasked with re-writing the following artifact to be {newLength}.
Ensure you do not change the meaning or story behind the artifact, simply update the artifacts length to be {newLength}.
Here is the current content of the artifact:
<artifact>
{artifactContent}
</artifact>
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
Rules and guidelines:
</rules-guidelines>
- Respond with ONLY the updated artifact, and no additional text before or after.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated artifact.
</rules-guidelines>`;
export const ADD_EMOJIS_TO_ARTIFACT_PROMPT = `You are tasked with revising the following artifact by adding emojis to it.
Ensure you do not change the meaning or story behind the artifact, simply include emojis throughout the text where appropriate.
Here is the current content of the artifact:
<artifact>
{artifactContent}
</artifact>
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
Rules and guidelines:
</rules-guidelines>
- Respond with ONLY the updated artifact, and no additional text before or after.
- Ensure you respond with the entire updated artifact, including the emojis.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated artifact.
</rules-guidelines>`;
// ----- End text modification prompts -----
export const ROUTE_QUERY_OPTIONS_HAS_ARTIFACTS = `
- 'rewriteArtifact': The user has requested some sort of change, or revision to the artifact, or to write a completely new artifact independent of the current artifact. Use their recent message and the currently selected artifact (if any) to determine what to do. You should ONLY select this if the user has clearly requested a change to the artifact, otherwise you should lean towards either generating a new artifact or responding to their query.
It is very important you do not edit the artifact unless clearly requested by the user.
- 'replyToGeneralInput': The user submitted a general input which does not require making an update, edit or generating a new artifact. This should ONLY be used if you are ABSOLUTELY sure the user does NOT want to make an edit, update or generate a new artifact.`;
export const ROUTE_QUERY_OPTIONS_NO_ARTIFACTS = `
- 'generateArtifact': The user has inputted a request which requires generating an artifact.
- 'replyToGeneralInput': The user submitted a general input which does not require making an update, edit or generating a new artifact. This should ONLY be used if you are ABSOLUTELY sure the user does NOT want to make an edit, update or generate a new artifact.`;
export const CURRENT_ARTIFACT_PROMPT = `This artifact is the one the user is currently viewing.
<artifact>
{artifact}
</artifact>`;
export const NO_ARTIFACT_PROMPT = `The user has not generated an artifact yet.`;
export const ROUTE_QUERY_PROMPT = `You are an assistant tasked with routing the users query based on their most recent message.
You should look at this message in isolation and determine where to best route there query.
Use this context about the application and its features when determining where to route to:
${APP_CONTEXT}
Your options are as follows:
<options>
{artifactOptions}
</options>
A few of the recent messages in the chat history are:
<recent-messages>
{recentMessages}
</recent-messages>
{currentArtifactPrompt}`;
export const FOLLOWUP_ARTIFACT_PROMPT = `You are an AI assistant tasked with generating a followup to the artifact the user just generated.
The context is you're having a conversation with the user, and you've just generated an artifact for them. Now you should follow up with a message that notifies them you're done. Make this message creative!
I've provided some examples of what your followup might be, but please feel free to get creative here!
<examples>
<example id="1">
Here's a comedic twist on your poem about Bernese Mountain dogs. Let me know if this captures the humor you were aiming for, or if you'd like me to adjust anything!
</example>
<example id="2">
Here's a poem celebrating the warmth and gentle nature of pandas. Let me know if you'd like any adjustments or a different style!
</example>
<example id="3">
Does this capture what you had in mind, or is there a different direction you'd like to explore?
</example>
</examples>
Here is the artifact you generated:
<artifact>
{artifactContent}
</artifact>
You also have the following reflections on general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
Finally, here is the chat history between you and the user:
<conversation>
{conversation}
</conversation>
This message should be very short. Never generate more than 2-3 short sentences. Your tone should be somewhat formal, but still friendly. Remember, you're an AI assistant.
Do NOT include any tags, or extra text before or after your response. Do NOT prefix your response. Your response to this message should ONLY contain the description/followup message.`;
export const ADD_COMMENTS_TO_CODE_ARTIFACT_PROMPT = `You are an expert software engineer, tasked with updating the following code by adding comments to it.
Ensure you do NOT modify any logic or functionality of the code, simply add comments to explain the code.
Your comments should be clear and concise. Do not add unnecessary or redundant comments.
Here is the code to add comments to
<code>
{artifactContent}
</code>
Rules and guidelines:
</rules-guidelines>
- Respond with ONLY the updated code, and no additional text before or after.
- Ensure you respond with the entire updated code, including the comments. Do not leave out any code from the original input.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated code.
${DEFAULT_CODE_PROMPT_RULES}
</rules-guidelines>`;
export const ADD_LOGS_TO_CODE_ARTIFACT_PROMPT = `You are an expert software engineer, tasked with updating the following code by adding log statements to it.
Ensure you do NOT modify any logic or functionality of the code, simply add logs throughout the code to help with debugging.
Your logs should be clear and concise. Do not add redundant logs.
Here is the code to add logs to
<code>
{artifactContent}
</code>
Rules and guidelines:
<rules-guidelines>
- Respond with ONLY the updated code, and no additional text before or after.
- Ensure you respond with the entire updated code, including the logs. Do not leave out any code from the original input.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated code.
${DEFAULT_CODE_PROMPT_RULES}
</rules-guidelines>`;
export const FIX_BUGS_CODE_ARTIFACT_PROMPT = `You are an expert software engineer, tasked with fixing any bugs in the following code.
Read through all the code carefully before making any changes. Think through the logic, and ensure you do not introduce new bugs.
Before updating the code, ask yourself:
- Does this code contain logic or syntax errors?
- From what you can infer, does it have missing business logic?
- Can you improve the code's performance?
- How can you make the code more clear and concise?
Here is the code to potentially fix bugs in:
<code>
{artifactContent}
</code>
Rules and guidelines:
<rules-guidelines>
- Respond with ONLY the updated code, and no additional text before or after.
- Ensure you respond with the entire updated code. Do not leave out any code from the original input.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated code
- Ensure you are not making meaningless changes.
${DEFAULT_CODE_PROMPT_RULES}
</rules-guidelines>`;
export const PORT_LANGUAGE_CODE_ARTIFACT_PROMPT = `You are an expert software engineer, tasked with re-writing the following code in {newLanguage}.
Read through all the code carefully before making any changes. Think through the logic, and ensure you do not introduce bugs.
Here is the code to port to {newLanguage}:
<code>
{artifactContent}
</code>
Rules and guidelines:
<rules-guidelines>
- Respond with ONLY the updated code, and no additional text before or after.
- Ensure you respond with the entire updated code. Your user expects a fully translated code snippet.
- Do not wrap it in any XML tags you see in this prompt. Ensure it's just the updated code
- Ensure you do not port over language specific modules. E.g if the code contains imports from Node's fs module, you must use the closest equivalent in {newLanguage}.
${DEFAULT_CODE_PROMPT_RULES}
</rules-guidelines>`;
export const REFLECTIONS_QUICK_ACTION_PROMPT = `The following are reflections on the user's style guidelines and general memories/facts about the user.
Use these reflections as context when generating your response.
<reflections>
{reflections}
</reflections>`;
export const CUSTOM_QUICK_ACTION_ARTIFACT_PROMPT_PREFIX = `You are an AI assistant tasked with rewriting a users generated artifact.
They have provided custom instructions on how you should manage rewriting the artifact. The custom instructions are wrapped inside the <custom-instructions> tags.
Use this context about the application the user is interacting with when generating your response:
<app-context>
The name of the application is "Open Canvas". Open Canvas is a web application where users have a chat window and a canvas to display an artifact.
Artifacts can be any sort of writing content, emails, code, or other creative writing work. Think of artifacts as content, or writing you might find on you might find on a blog, Google doc, or other writing platform.
Users only have a single artifact per conversation, however they have the ability to go back and fourth between artifact edits/revisions.
</app-context>`;
export const CUSTOM_QUICK_ACTION_CONVERSATION_CONTEXT = `Here is the last 5 (or less) messages in the chat history between you and the user:
<conversation>
{conversation}
</conversation>`;
export const CUSTOM_QUICK_ACTION_ARTIFACT_CONTENT_PROMPT = `Here is the full artifact content the user has generated, and is requesting you rewrite according to their custom instructions:
<artifact>
{artifactContent}
</artifact>`;
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/rewriteArtifactTheme.ts | import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { getModelFromConfig } from "../../utils";
import { getArtifactContent } from "../../../contexts/utils";
import { isArtifactMarkdownContent } from "../../../lib/artifact_content_types";
import { ArtifactV3, Reflections } from "../../../types";
import { ensureStoreInConfig, formatReflections } from "../../utils";
import {
ADD_EMOJIS_TO_ARTIFACT_PROMPT,
CHANGE_ARTIFACT_LANGUAGE_PROMPT,
CHANGE_ARTIFACT_LENGTH_PROMPT,
CHANGE_ARTIFACT_READING_LEVEL_PROMPT,
CHANGE_ARTIFACT_TO_PIRATE_PROMPT,
} from "../prompts";
import { OpenCanvasGraphAnnotation, OpenCanvasGraphReturnType } from "../state";
export const rewriteArtifactTheme = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
const smallModel = await getModelFromConfig(config);
const store = ensureStoreInConfig(config);
const assistantId = config.configurable?.assistant_id;
if (!assistantId) {
throw new Error("`assistant_id` not found in configurable");
}
const memoryNamespace = ["memories", assistantId];
const memoryKey = "reflection";
const memories = await store.get(memoryNamespace, memoryKey);
const memoriesAsString = memories?.value
? formatReflections(memories.value as Reflections)
: "No reflections found.";
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
if (!currentArtifactContent) {
throw new Error("No artifact found");
}
if (!isArtifactMarkdownContent(currentArtifactContent)) {
throw new Error("Current artifact content is not markdown");
}
let formattedPrompt = "";
if (state.language) {
formattedPrompt = CHANGE_ARTIFACT_LANGUAGE_PROMPT.replace(
"{newLanguage}",
state.language
).replace("{artifactContent}", currentArtifactContent.fullMarkdown);
} else if (state.readingLevel && state.readingLevel !== "pirate") {
let newReadingLevel = "";
switch (state.readingLevel) {
case "child":
newReadingLevel = "elementary school student";
break;
case "teenager":
newReadingLevel = "high school student";
break;
case "college":
newReadingLevel = "college student";
break;
case "phd":
newReadingLevel = "PhD student";
break;
}
formattedPrompt = CHANGE_ARTIFACT_READING_LEVEL_PROMPT.replace(
"{newReadingLevel}",
newReadingLevel
).replace("{artifactContent}", currentArtifactContent.fullMarkdown);
} else if (state.readingLevel && state.readingLevel === "pirate") {
formattedPrompt = CHANGE_ARTIFACT_TO_PIRATE_PROMPT.replace(
"{artifactContent}",
currentArtifactContent.fullMarkdown
);
} else if (state.artifactLength) {
let newLength = "";
switch (state.artifactLength) {
case "shortest":
newLength = "much shorter than it currently is";
break;
case "short":
newLength = "slightly shorter than it currently is";
break;
case "long":
newLength = "slightly longer than it currently is";
break;
case "longest":
newLength = "much longer than it currently is";
break;
}
formattedPrompt = CHANGE_ARTIFACT_LENGTH_PROMPT.replace(
"{newLength}",
newLength
).replace("{artifactContent}", currentArtifactContent.fullMarkdown);
} else if (state.regenerateWithEmojis) {
formattedPrompt = ADD_EMOJIS_TO_ARTIFACT_PROMPT.replace(
"{artifactContent}",
currentArtifactContent.fullMarkdown
);
} else {
throw new Error("No theme selected");
}
formattedPrompt = formattedPrompt.replace("{reflections}", memoriesAsString);
const newArtifactValues = await smallModel.invoke([
{ role: "user", content: formattedPrompt },
]);
const newArtifact: ArtifactV3 = {
...state.artifact,
currentIndex: state.artifact.contents.length + 1,
contents: [
...state.artifact.contents,
{
...currentArtifactContent,
index: state.artifact.contents.length + 1,
fullMarkdown: newArtifactValues.content as string,
},
],
};
return {
artifact: newArtifact,
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/generateFollowup.ts | import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { getModelFromConfig } from "../../utils";
import { getArtifactContent } from "../../../contexts/utils";
import { isArtifactMarkdownContent } from "../../../lib/artifact_content_types";
import { Reflections } from "../../../types";
import { ensureStoreInConfig, formatReflections } from "../../utils";
import { FOLLOWUP_ARTIFACT_PROMPT } from "../prompts";
import { OpenCanvasGraphAnnotation, OpenCanvasGraphReturnType } from "../state";
/**
* Generate a followup message after generating or updating an artifact.
*/
export const generateFollowup = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
const smallModel = await getModelFromConfig(config, {
maxTokens: 250,
});
const store = ensureStoreInConfig(config);
const assistantId = config.configurable?.assistant_id;
if (!assistantId) {
throw new Error("`assistant_id` not found in configurable");
}
const memoryNamespace = ["memories", assistantId];
const memoryKey = "reflection";
const memories = await store.get(memoryNamespace, memoryKey);
const memoriesAsString = memories?.value
? formatReflections(memories.value as Reflections, {
onlyContent: true,
})
: "No reflections found.";
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
const artifactContent = currentArtifactContent
? isArtifactMarkdownContent(currentArtifactContent)
? currentArtifactContent.fullMarkdown
: currentArtifactContent.code
: undefined;
const formattedPrompt = FOLLOWUP_ARTIFACT_PROMPT.replace(
"{artifactContent}",
artifactContent || "No artifacts generated yet."
)
.replace("{reflections}", memoriesAsString)
.replace(
"{conversation}",
state.messages
.map((msg) => `<${msg.getType()}>\n${msg.content}\n</${msg.getType()}>`)
.join("\n\n")
);
// TODO: Include the chat history as well.
const response = await smallModel.invoke([
{ role: "user", content: formattedPrompt },
]);
return {
messages: [response],
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/generateTitle.ts | import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { Client } from "@langchain/langgraph-sdk";
import { OpenCanvasGraphAnnotation } from "../state";
export const generateTitleNode = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
) => {
if (state.messages.length > 2) {
// Skip if it's not first human ai conversation. Should never occur in practice
// due to the conditional edge which is called before this node.
return {};
}
const langGraphClient = new Client({
apiUrl: `http://localhost:${process.env.PORT}`,
defaultHeaders: {
"X-API-KEY": process.env.LANGCHAIN_API_KEY,
},
});
const titleInput = {
messages: state.messages,
artifact: state.artifact,
};
const titleConfig = {
configurable: {
open_canvas_thread_id: config.configurable?.thread_id,
},
};
// Create a new thread for title generation
const newThread = await langGraphClient.threads.create();
// Create a new title generation run in the background
await langGraphClient.runs.create(newThread.thread_id, "thread_title", {
input: titleInput,
config: titleConfig,
multitaskStrategy: "enqueue",
afterSeconds: 0,
});
return {};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/reflect.ts | import { Client } from "@langchain/langgraph-sdk";
import { OpenCanvasGraphAnnotation } from "../state";
import { LangGraphRunnableConfig } from "@langchain/langgraph";
export const reflectNode = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
) => {
const langGraphClient = new Client({
apiUrl: `http://localhost:${process.env.PORT}`,
defaultHeaders: {
"X-API-KEY": process.env.LANGCHAIN_API_KEY,
},
});
const reflectionInput = {
messages: state.messages,
artifact: state.artifact,
};
const reflectionConfig = {
configurable: {
// Ensure we pass in the current graph's assistant ID as this is
// how we fetch & store the memories.
open_canvas_assistant_id: config.configurable?.assistant_id,
},
};
const newThread = await langGraphClient.threads.create();
// Create a new reflection run, but do not `wait` for it to finish.
// Intended to be a background run.
await langGraphClient.runs.create(
// We enqueue the memory formation process on the same thread.
// This means that IF this thread doesn't receive more messages before `afterSeconds`,
// it will read from the shared state and extract memories for us.
// If a new request comes in for this thread before the scheduled run is executed,
// that run will be canceled, and a **new** one will be scheduled once
// this node is executed again.
newThread.thread_id,
// Pass the name of the graph to run.
"reflection",
{
input: reflectionInput,
config: reflectionConfig,
// This memory-formation run will be enqueued and run later
// If a new run comes in before it is scheduled, it will be cancelled,
// then when this node is executed again, a *new* run will be scheduled
multitaskStrategy: "enqueue",
// This lets us "debounce" repeated requests to the memory graph
// if the user is actively engaging in a conversation. This saves us $$ and
// can help reduce the occurrence of duplicate memories.
afterSeconds: 15,
}
);
return {};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/customAction.ts | import { BaseMessage } from "@langchain/core/messages";
import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { getModelFromConfig } from "../../utils";
import { getArtifactContent } from "../../../contexts/utils";
import { isArtifactMarkdownContent } from "../../../lib/artifact_content_types";
import {
ArtifactCodeV3,
ArtifactMarkdownV3,
ArtifactV3,
CustomQuickAction,
Reflections,
} from "../../../types";
import { ensureStoreInConfig, formatReflections } from "../../utils";
import {
CUSTOM_QUICK_ACTION_ARTIFACT_CONTENT_PROMPT,
CUSTOM_QUICK_ACTION_ARTIFACT_PROMPT_PREFIX,
CUSTOM_QUICK_ACTION_CONVERSATION_CONTEXT,
REFLECTIONS_QUICK_ACTION_PROMPT,
} from "../prompts";
import { OpenCanvasGraphAnnotation, OpenCanvasGraphReturnType } from "../state";
const formatMessages = (messages: BaseMessage[]): string =>
messages
.map(
(msg) =>
`<${msg.getType()}>\n${msg.content as string}\n</${msg.getType()}>`
)
.join("\n");
export const customAction = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
if (!state.customQuickActionId) {
throw new Error("No custom quick action ID found.");
}
const smallModel = await getModelFromConfig(config, {
temperature: 0.5,
});
const store = ensureStoreInConfig(config);
const assistantId = config.configurable?.assistant_id;
const userId = config.configurable?.supabase_user_id;
if (!assistantId) {
throw new Error("`assistant_id` not found in configurable");
}
if (!userId) {
throw new Error("`supabase_user_id` not found in configurable");
}
const customActionsNamespace = ["custom_actions", userId];
const actionsKey = "actions";
const memoryNamespace = ["memories", assistantId];
const memoryKey = "reflection";
const [customActionsItem, memories] = await Promise.all([
store.get(customActionsNamespace, actionsKey),
store.get(memoryNamespace, memoryKey),
]);
if (!customActionsItem?.value) {
throw new Error("No custom actions found.");
}
const customQuickAction = customActionsItem.value[
state.customQuickActionId
] as CustomQuickAction | undefined;
if (!customQuickAction) {
throw new Error(
`No custom quick action found from ID ${state.customQuickActionId}`
);
}
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
let formattedPrompt = `<custom-instructions>\n${customQuickAction.prompt}\n</custom-instructions>`;
if (customQuickAction.includeReflections && memories?.value) {
const memoriesAsString = formatReflections(memories.value as Reflections);
const reflectionsPrompt = REFLECTIONS_QUICK_ACTION_PROMPT.replace(
"{reflections}",
memoriesAsString
);
formattedPrompt += `\n\n${reflectionsPrompt}`;
}
if (customQuickAction.includePrefix) {
formattedPrompt = `${CUSTOM_QUICK_ACTION_ARTIFACT_PROMPT_PREFIX}\n\n${formattedPrompt}`;
}
if (customQuickAction.includeRecentHistory) {
const formattedConversationHistory =
CUSTOM_QUICK_ACTION_CONVERSATION_CONTEXT.replace(
"{conversation}",
formatMessages(state.messages.slice(-5))
);
formattedPrompt += `\n\n${formattedConversationHistory}`;
}
const artifactContent = isArtifactMarkdownContent(currentArtifactContent)
? currentArtifactContent.fullMarkdown
: currentArtifactContent?.code;
formattedPrompt += `\n\n${CUSTOM_QUICK_ACTION_ARTIFACT_CONTENT_PROMPT.replace("{artifactContent}", artifactContent || "No artifacts generated yet.")}`;
const newArtifactValues = await smallModel.invoke([
{ role: "user", content: formattedPrompt },
]);
if (!currentArtifactContent) {
console.error("No current artifact content found.");
return {};
}
const newArtifactContent: ArtifactCodeV3 | ArtifactMarkdownV3 = {
...currentArtifactContent,
index: state.artifact.contents.length + 1,
...(isArtifactMarkdownContent(currentArtifactContent)
? { fullMarkdown: newArtifactValues.content as string }
: { code: newArtifactValues.content as string }),
};
const newArtifact: ArtifactV3 = {
...state.artifact,
currentIndex: state.artifact.contents.length + 1,
contents: [...state.artifact.contents, newArtifactContent],
};
return {
artifact: newArtifact,
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/replyToGeneralInput.ts | import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { getModelFromConfig } from "../../utils";
import { getArtifactContent } from "../../../contexts/utils";
import { Reflections } from "../../../types";
import {
ensureStoreInConfig,
formatArtifactContentWithTemplate,
formatReflections,
} from "../../utils";
import { CURRENT_ARTIFACT_PROMPT, NO_ARTIFACT_PROMPT } from "../prompts";
import { OpenCanvasGraphAnnotation, OpenCanvasGraphReturnType } from "../state";
/**
* Generate responses to questions. Does not generate artifacts.
*/
export const replyToGeneralInput = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
const smallModel = await getModelFromConfig(config);
const prompt = `You are an AI assistant tasked with responding to the users question.
The user has generated artifacts in the past. Use the following artifacts as context when responding to the users question.
You also have the following reflections on style guidelines and general memories/facts about the user to use when generating your response.
<reflections>
{reflections}
</reflections>
{currentArtifactPrompt}`;
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
const store = ensureStoreInConfig(config);
const assistantId = config.configurable?.assistant_id;
if (!assistantId) {
throw new Error("`assistant_id` not found in configurable");
}
const memoryNamespace = ["memories", assistantId];
const memoryKey = "reflection";
const memories = await store.get(memoryNamespace, memoryKey);
const memoriesAsString = memories?.value
? formatReflections(memories.value as Reflections)
: "No reflections found.";
const formattedPrompt = prompt
.replace("{reflections}", memoriesAsString)
.replace(
"{currentArtifactPrompt}",
currentArtifactContent
? formatArtifactContentWithTemplate(
CURRENT_ARTIFACT_PROMPT,
currentArtifactContent
)
: NO_ARTIFACT_PROMPT
);
const response = await smallModel.invoke([
{ role: "system", content: formattedPrompt },
...state.messages,
]);
return {
messages: [response],
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/generatePath.ts | import {
CURRENT_ARTIFACT_PROMPT,
NO_ARTIFACT_PROMPT,
ROUTE_QUERY_OPTIONS_HAS_ARTIFACTS,
ROUTE_QUERY_OPTIONS_NO_ARTIFACTS,
ROUTE_QUERY_PROMPT,
} from "../prompts";
import { OpenCanvasGraphAnnotation } from "../state";
import { z } from "zod";
import { formatArtifactContentWithTemplate } from "../../utils";
import { getArtifactContent } from "../../../contexts/utils";
import { getModelFromConfig } from "../../utils";
import { LangGraphRunnableConfig } from "@langchain/langgraph";
/**
* Routes to the proper node in the graph based on the user's query.
*/
export const generatePath = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
) => {
console.log("config.configurable!!", config.configurable);
if (state.highlightedCode) {
return {
next: "updateArtifact",
};
}
if (state.highlightedText) {
return {
next: "updateHighlightedText",
};
}
if (
state.language ||
state.artifactLength ||
state.regenerateWithEmojis ||
state.readingLevel
) {
return {
next: "rewriteArtifactTheme",
};
}
if (
state.addComments ||
state.addLogs ||
state.portLanguage ||
state.fixBugs
) {
return {
next: "rewriteCodeArtifactTheme",
};
}
if (state.customQuickActionId) {
return {
next: "customAction",
};
}
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
// Call model and decide if we need to respond to a users query, or generate a new artifact
const formattedPrompt = ROUTE_QUERY_PROMPT.replace(
"{artifactOptions}",
currentArtifactContent
? ROUTE_QUERY_OPTIONS_HAS_ARTIFACTS
: ROUTE_QUERY_OPTIONS_NO_ARTIFACTS
)
.replace(
"{recentMessages}",
state.messages
.slice(-3)
.map((message) => `${message.getType()}: ${message.content}`)
.join("\n\n")
)
.replace(
"{currentArtifactPrompt}",
currentArtifactContent
? formatArtifactContentWithTemplate(
CURRENT_ARTIFACT_PROMPT,
currentArtifactContent
)
: NO_ARTIFACT_PROMPT
);
const artifactRoute = currentArtifactContent
? "rewriteArtifact"
: "generateArtifact";
const model = await getModelFromConfig(config, {
temperature: 0,
});
const modelWithTool = model.withStructuredOutput(
z.object({
route: z
.enum(["replyToGeneralInput", artifactRoute])
.describe("The route to take based on the user's query."),
}),
{
name: "route_query",
}
);
const result = await modelWithTool.invoke([
{
role: "user",
content: formattedPrompt,
},
]);
return {
next: result.route,
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/updateArtifact.ts | import { OpenCanvasGraphAnnotation, OpenCanvasGraphReturnType } from "../state";
import { UPDATE_HIGHLIGHTED_ARTIFACT_PROMPT } from "../prompts";
import {
ensureStoreInConfig,
formatReflections,
getModelConfig,
getModelFromConfig,
} from "../../utils";
import { ArtifactCodeV3, ArtifactV3, Reflections } from "../../../types";
import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { getArtifactContent } from "../../../contexts/utils";
import { isArtifactCodeContent } from "../../../lib/artifact_content_types";
/**
* Update an existing artifact based on the user's query.
*/
export const updateArtifact = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
const { modelProvider } = getModelConfig(config);
let smallModel: Awaited<ReturnType<typeof getModelFromConfig>>;
if (modelProvider.includes("openai")) {
// Custom model is OpenAI/Azure OpenAI
smallModel = await getModelFromConfig(config, {
temperature: 0,
});
} else {
// Custom model is not set to OpenAI/Azure OpenAI. Use GPT-4o
smallModel = await getModelFromConfig(
{
...config,
configurable: {
customModelName: "gpt-4o",
},
},
{
temperature: 0,
}
);
}
const store = ensureStoreInConfig(config);
const assistantId = config.configurable?.assistant_id;
if (!assistantId) {
throw new Error("`assistant_id` not found in configurable");
}
const memoryNamespace = ["memories", assistantId];
const memoryKey = "reflection";
const memories = await store.get(memoryNamespace, memoryKey);
const memoriesAsString = memories?.value
? formatReflections(memories.value as Reflections)
: "No reflections found.";
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
if (!currentArtifactContent) {
throw new Error("No artifact found");
}
if (!isArtifactCodeContent(currentArtifactContent)) {
throw new Error("Current artifact content is not markdown");
}
if (!state.highlightedCode) {
throw new Error(
"Can not partially regenerate an artifact without a highlight"
);
}
// Highlighted text is present, so we need to update the highlighted text.
const start = Math.max(0, state.highlightedCode.startCharIndex - 500);
const end = Math.min(
currentArtifactContent.code.length,
state.highlightedCode.endCharIndex + 500
);
const beforeHighlight = currentArtifactContent.code.slice(
start,
state.highlightedCode.startCharIndex
) as string;
const highlightedText = currentArtifactContent.code.slice(
state.highlightedCode.startCharIndex,
state.highlightedCode.endCharIndex
) as string;
const afterHighlight = currentArtifactContent.code.slice(
state.highlightedCode.endCharIndex,
end
) as string;
const formattedPrompt = UPDATE_HIGHLIGHTED_ARTIFACT_PROMPT.replace(
"{highlightedText}",
highlightedText
)
.replace("{beforeHighlight}", beforeHighlight)
.replace("{afterHighlight}", afterHighlight)
.replace("{reflections}", memoriesAsString);
const recentHumanMessage = state.messages.findLast(
(message) => message.getType() === "human"
);
if (!recentHumanMessage) {
throw new Error("No recent human message found");
}
const updatedArtifact = await smallModel.invoke([
{ role: "system", content: formattedPrompt },
recentHumanMessage,
]);
const entireTextBefore = currentArtifactContent.code.slice(
0,
state.highlightedCode.startCharIndex
);
const entireTextAfter = currentArtifactContent.code.slice(
state.highlightedCode.endCharIndex
);
const entireUpdatedContent = `${entireTextBefore}${updatedArtifact.content}${entireTextAfter}`;
const newArtifactContent: ArtifactCodeV3 = {
...currentArtifactContent,
index: state.artifact.contents.length + 1,
code: entireUpdatedContent,
};
const newArtifact: ArtifactV3 = {
...state.artifact,
currentIndex: state.artifact.contents.length + 1,
contents: [...state.artifact.contents, newArtifactContent],
};
return {
artifact: newArtifact,
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/rewriteCodeArtifactTheme.ts | import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { getModelFromConfig } from "../../utils";
import { getArtifactContent } from "../../../contexts/utils";
import { isArtifactCodeContent } from "../../../lib/artifact_content_types";
import { ArtifactCodeV3, ArtifactV3 } from "../../../types";
import {
ADD_COMMENTS_TO_CODE_ARTIFACT_PROMPT,
ADD_LOGS_TO_CODE_ARTIFACT_PROMPT,
FIX_BUGS_CODE_ARTIFACT_PROMPT,
PORT_LANGUAGE_CODE_ARTIFACT_PROMPT,
} from "../prompts";
import { OpenCanvasGraphAnnotation, OpenCanvasGraphReturnType } from "../state";
export const rewriteCodeArtifactTheme = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
const smallModel = await getModelFromConfig(config);
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
if (!currentArtifactContent) {
throw new Error("No artifact found");
}
if (!isArtifactCodeContent(currentArtifactContent)) {
throw new Error("Current artifact content is not code");
}
let formattedPrompt = "";
if (state.addComments) {
formattedPrompt = ADD_COMMENTS_TO_CODE_ARTIFACT_PROMPT;
} else if (state.portLanguage) {
let newLanguage = "";
switch (state.portLanguage) {
case "typescript":
newLanguage = "TypeScript";
break;
case "javascript":
newLanguage = "JavaScript";
break;
case "cpp":
newLanguage = "C++";
break;
case "java":
newLanguage = "Java";
break;
case "php":
newLanguage = "PHP";
break;
case "python":
newLanguage = "Python";
break;
case "html":
newLanguage = "HTML";
break;
case "sql":
newLanguage = "SQL";
break;
}
formattedPrompt = PORT_LANGUAGE_CODE_ARTIFACT_PROMPT.replace(
"{newLanguage}",
newLanguage
);
} else if (state.addLogs) {
formattedPrompt = ADD_LOGS_TO_CODE_ARTIFACT_PROMPT;
} else if (state.fixBugs) {
formattedPrompt = FIX_BUGS_CODE_ARTIFACT_PROMPT;
} else {
throw new Error("No theme selected");
}
// Insert the code into the artifact placeholder in the prompt
formattedPrompt = formattedPrompt.replace(
"{artifactContent}",
currentArtifactContent.code
);
const newArtifactValues = await smallModel.invoke([
{ role: "user", content: formattedPrompt },
]);
const newArtifactContent: ArtifactCodeV3 = {
index: state.artifact.contents.length + 1,
type: "code",
title: currentArtifactContent.title,
// Ensure the new artifact's language is updated, if necessary
language: state.portLanguage || currentArtifactContent.language,
code: newArtifactValues.content as string,
};
const newArtifact: ArtifactV3 = {
...state.artifact,
currentIndex: state.artifact.contents.length + 1,
contents: [...state.artifact.contents, newArtifactContent],
};
return {
artifact: newArtifact,
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/updateHighlightedText.ts | import { OpenCanvasGraphAnnotation, OpenCanvasGraphReturnType } from "../state";
import { ArtifactMarkdownV3 } from "../../../types";
import { getArtifactContent } from "../../../contexts/utils";
import { isArtifactMarkdownContent } from "../../../lib/artifact_content_types";
import { getModelConfig, getModelFromConfig } from "@/agent/utils";
import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { RunnableBinding } from "@langchain/core/runnables";
import { BaseLanguageModelInput } from "@langchain/core/language_models/base";
import { AIMessageChunk } from "@langchain/core/messages";
import { ConfigurableChatModelCallOptions } from "langchain/chat_models/universal";
const PROMPT = `You are an expert AI writing assistant, tasked with rewriting some text a user has selected. The selected text is nested inside a larger 'block'. You should always respond with ONLY the updated text block in accordance with the user's request.
You should always respond with the full markdown text block, as it will simply replace the existing block in the artifact.
The blocks will be joined later on, so you do not need to worry about the formatting of the blocks, only make sure you keep the formatting and structure of the block you are updating.
# Selected text
{highlightedText}
# Text block
{textBlocks}
Your task is to rewrite the sourounding content to fulfill the users request. The selected text content you are provided above has had the markdown styling removed, so you can focus on the text itself.
However, ensure you ALWAYS respond with the full markdown text block, including any markdown syntax.
NEVER wrap your response in any additional markdown syntax, as this will be handled by the system. Do NOT include a triple backtick wrapping the text block, unless it was present in the original text block.
You should NOT change anything EXCEPT the selected text. The ONLY instance where you may update the sourounding text is if it is necessary to make the selected text make sense.
You should ALWAYS respond with the full, updated text block, including any formatting, e.g newlines, indents, markdown syntax, etc. NEVER add extra syntax or formatting unless the user has specifically requested it.
If you observe partial markdown, this is OKAY because you are only updating a partial piece of the text.
Ensure you reply with the FULL text block, including the updated selected text. NEVER include only the updated selected text, or additional prefixes or suffixes.`;
/**
* Update an existing artifact based on the user's query.
*/
export const updateHighlightedText = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
const { modelProvider } = getModelConfig(config);
let model: RunnableBinding<
BaseLanguageModelInput,
AIMessageChunk,
ConfigurableChatModelCallOptions
>;
if (modelProvider.includes("openai")) {
// Custom model is OpenAI/Azure OpenAI
model = (
await getModelFromConfig(config, {
temperature: 0,
})
).withConfig({ runName: "update_highlighted_markdown" });
} else {
// Custom model is not set to OpenAI/Azure OpenAI. Use GPT-4o
model = (
await getModelFromConfig(
{
...config,
configurable: {
customModelName: "gpt-4o",
},
},
{
temperature: 0,
}
)
).withConfig({ runName: "update_highlighted_markdown" });
}
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
if (!currentArtifactContent) {
throw new Error("No artifact found");
}
if (!isArtifactMarkdownContent(currentArtifactContent)) {
throw new Error("Artifact is not markdown content");
}
if (!state.highlightedText) {
throw new Error(
"Can not partially regenerate an artifact without a highlight"
);
}
const { markdownBlock, selectedText, fullMarkdown } = state.highlightedText;
const formattedPrompt = PROMPT.replace(
"{highlightedText}",
selectedText
).replace("{textBlocks}", markdownBlock);
const recentUserMessage = state.messages[state.messages.length - 1];
if (recentUserMessage.getType() !== "human") {
throw new Error("Expected a human message");
}
const response = await model.invoke([
{
role: "system",
content: formattedPrompt,
},
recentUserMessage,
]);
const responseContent = response.content as string;
const newCurrIndex = state.artifact.contents.length + 1;
const prevContent = state.artifact.contents.find(
(c) => c.index === state.artifact.currentIndex && c.type === "text"
) as ArtifactMarkdownV3 | undefined;
if (!prevContent) {
throw new Error("Previous content not found");
}
if (!fullMarkdown.includes(markdownBlock)) {
throw new Error("Selected text not found in current content");
}
const newFullMarkdown = fullMarkdown.replace(markdownBlock, responseContent);
const updatedArtifactContent: ArtifactMarkdownV3 = {
...prevContent,
index: newCurrIndex,
fullMarkdown: newFullMarkdown,
};
return {
artifact: {
...state.artifact,
currentIndex: newCurrIndex,
contents: [...state.artifact.contents, updatedArtifactContent],
},
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas/nodes | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/generate-artifact/schemas.ts | import { PROGRAMMING_LANGUAGES } from "@/types";
import { z } from "zod";
export const ARTIFACT_TOOL_SCHEMA = z.object({
type: z
.enum(["code", "text"])
.describe("The content type of the artifact generated."),
language: z
.enum(
PROGRAMMING_LANGUAGES.map((lang) => lang.language) as [
string,
...string[],
]
)
.optional()
.describe(
"The language/programming language of the artifact generated.\n" +
"If generating code, it should be one of the options, or 'other'.\n" +
"If not generating code, the language should ALWAYS be 'other'."
),
isValidReact: z
.boolean()
.optional()
.describe(
"Whether or not the generated code is valid React code. Only populate this field if generating code."
),
artifact: z.string().describe("The content of the artifact to generate."),
title: z
.string()
.describe(
"A short title to give to the artifact. Should be less than 5 words."
),
});
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas/nodes | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/generate-artifact/index.ts | import {
OpenCanvasGraphAnnotation,
OpenCanvasGraphReturnType,
} from "../../state";
import { LangGraphRunnableConfig } from "@langchain/langgraph";
import {
getFormattedReflections,
getModelFromConfig,
getModelConfig,
optionallyGetSystemPromptFromConfig,
} from "@/agent/utils";
import { ARTIFACT_TOOL_SCHEMA } from "./schemas";
import { ArtifactV3 } from "@/types";
import { createArtifactContent, formatNewArtifactPrompt } from "./utils";
/**
* Generate a new artifact based on the user's query.
*/
export const generateArtifact = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
const { modelName } = getModelConfig(config);
const smallModel = await getModelFromConfig(config, {
temperature: 0.5,
});
const modelWithArtifactTool = smallModel.bindTools(
[
{
name: "generate_artifact",
schema: ARTIFACT_TOOL_SCHEMA,
},
],
{ tool_choice: "generate_artifact" }
);
const memoriesAsString = await getFormattedReflections(config);
const formattedNewArtifactPrompt = formatNewArtifactPrompt(
memoriesAsString,
modelName
);
const userSystemPrompt = optionallyGetSystemPromptFromConfig(config);
const fullSystemPrompt = userSystemPrompt
? `${userSystemPrompt}\n${formattedNewArtifactPrompt}`
: formattedNewArtifactPrompt;
const response = await modelWithArtifactTool.invoke(
[{ role: "system", content: fullSystemPrompt }, ...state.messages],
{ runName: "generate_artifact" }
);
const newArtifactContent = createArtifactContent(response.tool_calls?.[0]);
const newArtifact: ArtifactV3 = {
currentIndex: 1,
contents: [newArtifactContent],
};
return {
artifact: newArtifact,
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas/nodes | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/generate-artifact/utils.ts | import { NEW_ARTIFACT_PROMPT } from "../../prompts";
import { ArtifactCodeV3, ArtifactMarkdownV3 } from "@/types";
import { ToolCall } from "@langchain/core/messages/tool";
export const formatNewArtifactPrompt = (
memoriesAsString: string,
modelName: string
): string => {
return NEW_ARTIFACT_PROMPT.replace("{reflections}", memoriesAsString).replace(
"{disableChainOfThought}",
modelName.includes("claude")
? "\n\nIMPORTANT: Do NOT preform chain of thought beforehand. Instead, go STRAIGHT to generating the tool response. This is VERY important."
: ""
);
};
export const createArtifactContent = (
toolCall: ToolCall | undefined
): ArtifactCodeV3 | ArtifactMarkdownV3 => {
const toolArgs = toolCall?.args;
const artifactType = toolArgs?.type;
if (artifactType === "code") {
return {
index: 1,
type: "code",
title: toolArgs?.title,
code: toolArgs?.artifact,
language: toolArgs?.language,
};
}
return {
index: 1,
type: "text",
title: toolArgs?.title,
fullMarkdown: toolArgs?.artifact,
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas/nodes | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/rewrite-artifact/schemas.ts | import { PROGRAMMING_LANGUAGES } from "@/types";
import { z } from "zod";
export const OPTIONALLY_UPDATE_ARTIFACT_META_SCHEMA = z.object({
type: z.enum(["text", "code"]).describe("The type of the artifact content."),
title: z
.string()
.optional()
.describe(
"The new title to give the artifact. ONLY update this if the user is making a request which changes the subject/topic of the artifact."
),
language: z
.enum(
PROGRAMMING_LANGUAGES.map((lang) => lang.language) as [
string,
...string[],
]
)
.describe(
"The language of the code artifact. This should be populated with the programming language if the user is requesting code to be written, or 'other', in all other cases."
),
});
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas/nodes | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/rewrite-artifact/update-meta.ts | import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { OpenCanvasGraphAnnotation } from "../../state";
import { formatArtifactContent, getModelFromConfig } from "@/agent/utils";
import { getArtifactContent } from "@/contexts/utils";
import { GET_TITLE_TYPE_REWRITE_ARTIFACT } from "../../prompts";
import { OPTIONALLY_UPDATE_ARTIFACT_META_SCHEMA } from "./schemas";
import { ToolCall } from "@langchain/core/messages/tool";
import { getFormattedReflections } from "../../../utils";
export async function optionallyUpdateArtifactMeta(
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<ToolCall | undefined> {
const toolCallingModel = (await getModelFromConfig(config))
.bindTools(
[
{
name: "optionallyUpdateArtifactMeta",
schema: OPTIONALLY_UPDATE_ARTIFACT_META_SCHEMA,
description: "Update the artifact meta information, if necessary.",
},
],
{ tool_choice: "optionallyUpdateArtifactMeta" }
)
.withConfig({ runName: "optionally_update_artifact_meta" });
const memoriesAsString = await getFormattedReflections(config);
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
if (!currentArtifactContent) {
throw new Error("No artifact found");
}
const optionallyUpdateArtifactMetaPrompt =
GET_TITLE_TYPE_REWRITE_ARTIFACT.replace(
"{artifact}",
formatArtifactContent(currentArtifactContent, true)
).replace("{reflections}", memoriesAsString);
const recentHumanMessage = state.messages.findLast(
(message) => message.getType() === "human"
);
if (!recentHumanMessage) {
throw new Error("No recent human message found");
}
const optionallyUpdateArtifactResponse = await toolCallingModel.invoke([
{ role: "system", content: optionallyUpdateArtifactMetaPrompt },
recentHumanMessage,
]);
return optionallyUpdateArtifactResponse.tool_calls?.[0];
}
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas/nodes | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/rewrite-artifact/index.ts | import {
OpenCanvasGraphAnnotation,
OpenCanvasGraphReturnType,
} from "../../state";
import { LangGraphRunnableConfig } from "@langchain/langgraph";
import { optionallyUpdateArtifactMeta } from "./update-meta";
import { buildPrompt, createNewArtifactContent, validateState } from "./utils";
import {
getFormattedReflections,
getModelFromConfig,
optionallyGetSystemPromptFromConfig,
} from "@/agent/utils";
import { isArtifactMarkdownContent } from "@/lib/artifact_content_types";
export const rewriteArtifact = async (
state: typeof OpenCanvasGraphAnnotation.State,
config: LangGraphRunnableConfig
): Promise<OpenCanvasGraphReturnType> => {
const smallModelWithConfig = (await getModelFromConfig(config)).withConfig({
runName: "rewrite_artifact_model_call",
});
const memoriesAsString = await getFormattedReflections(config);
const { currentArtifactContent, recentHumanMessage } = validateState(state);
const artifactMetaToolCall = await optionallyUpdateArtifactMeta(
state,
config
);
const artifactType = artifactMetaToolCall?.args?.type;
const isNewType = artifactType !== currentArtifactContent.type;
const artifactContent = isArtifactMarkdownContent(currentArtifactContent)
? currentArtifactContent.fullMarkdown
: currentArtifactContent.code;
const formattedPrompt = buildPrompt({
artifactContent,
memoriesAsString,
isNewType,
artifactMetaToolCall,
});
const userSystemPrompt = optionallyGetSystemPromptFromConfig(config);
const fullSystemPrompt = userSystemPrompt
? `${userSystemPrompt}\n${formattedPrompt}`
: formattedPrompt;
const newArtifactResponse = await smallModelWithConfig.invoke([
{ role: "system", content: fullSystemPrompt },
recentHumanMessage,
]);
const newArtifactContent = createNewArtifactContent({
artifactType,
state,
currentArtifactContent,
artifactMetaToolCall,
newContent: newArtifactResponse.content as string,
});
return {
artifact: {
...state.artifact,
currentIndex: state.artifact.contents.length + 1,
contents: [...state.artifact.contents, newArtifactContent],
},
};
};
|
0 | lc_public_repos/open-canvas/src/agent/open-canvas/nodes | lc_public_repos/open-canvas/src/agent/open-canvas/nodes/rewrite-artifact/utils.ts | import { getArtifactContent } from "@/contexts/utils";
import { isArtifactCodeContent } from "@/lib/artifact_content_types";
import { ArtifactCodeV3, ArtifactMarkdownV3 } from "@/types";
import {
OPTIONALLY_UPDATE_META_PROMPT,
UPDATE_ENTIRE_ARTIFACT_PROMPT,
} from "../../prompts";
import { OpenCanvasGraphAnnotation } from "../../state";
import { ToolCall } from "@langchain/core/messages/tool";
export const validateState = (
state: typeof OpenCanvasGraphAnnotation.State
) => {
const currentArtifactContent = state.artifact
? getArtifactContent(state.artifact)
: undefined;
if (!currentArtifactContent) {
throw new Error("No artifact found");
}
const recentHumanMessage = state.messages.findLast(
(message) => message.getType() === "human"
);
if (!recentHumanMessage) {
throw new Error("No recent human message found");
}
return { currentArtifactContent, recentHumanMessage };
};
const buildMetaPrompt = (artifactMetaToolCall: ToolCall | undefined) => {
const titleSection =
artifactMetaToolCall?.args?.title &&
artifactMetaToolCall?.args?.type !== "code"
? `And its title is (do NOT include this in your response):\n${artifactMetaToolCall.args.title}`
: "";
return OPTIONALLY_UPDATE_META_PROMPT.replace(
"{artifactType}",
artifactMetaToolCall?.args?.type
).replace("{artifactTitle}", titleSection);
};
interface BuildPromptArgs {
artifactContent: string;
memoriesAsString: string;
isNewType: boolean;
artifactMetaToolCall: ToolCall | undefined;
}
export const buildPrompt = ({
artifactContent,
memoriesAsString,
isNewType,
artifactMetaToolCall,
}: BuildPromptArgs) => {
const metaPrompt = isNewType ? buildMetaPrompt(artifactMetaToolCall) : "";
return UPDATE_ENTIRE_ARTIFACT_PROMPT.replace(
"{artifactContent}",
artifactContent
)
.replace("{reflections}", memoriesAsString)
.replace("{updateMetaPrompt}", metaPrompt);
};
interface CreateNewArtifactContentArgs {
artifactType: string;
state: typeof OpenCanvasGraphAnnotation.State;
currentArtifactContent: ArtifactCodeV3 | ArtifactMarkdownV3;
artifactMetaToolCall: ToolCall | undefined;
newContent: string;
}
export const createNewArtifactContent = ({
artifactType,
state,
currentArtifactContent,
artifactMetaToolCall,
newContent,
}: CreateNewArtifactContentArgs): ArtifactCodeV3 | ArtifactMarkdownV3 => {
const baseContent = {
index: state.artifact.contents.length + 1,
title: artifactMetaToolCall?.args?.title || currentArtifactContent.title,
};
if (artifactType === "code") {
return {
...baseContent,
type: "code",
language: getLanguage(artifactMetaToolCall, currentArtifactContent),
code: newContent,
};
}
return {
...baseContent,
type: "text",
fullMarkdown: newContent,
};
};
const getLanguage = (
artifactMetaToolCall: ToolCall | undefined,
currentArtifactContent: ArtifactCodeV3 | ArtifactMarkdownV3 // Replace 'any' with proper type
) =>
artifactMetaToolCall?.args?.programmingLanguage ||
(isArtifactCodeContent(currentArtifactContent)
? currentArtifactContent.language
: "other");
|
0 | lc_public_repos/open-canvas/src | lc_public_repos/open-canvas/src/lib/normalize_string.ts | const actualNewline = `
`;
export const cleanContent = (content: string): string => {
return content ? content.replaceAll("\n", actualNewline) : "";
};
export const reverseCleanContent = (content: string): string => {
return content ? content.replaceAll(actualNewline, "\n") : "";
};
export const newlineToCarriageReturn = (str: string) =>
// str.replace(actualNewline, "\r\n");
str.replace(actualNewline, [actualNewline, actualNewline].join(""));
export const emptyLineCount = (content: string): number => {
const liens = content.split("\n");
return liens.filter((line) => line.trim() == "").length;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.