Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Design Assistant] Chat UX Copywriter #213

Merged
merged 11 commits into from
Mar 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions app/lib/main/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { PhotoScreen } from "@app/photo-loader";
import { MetaEditorScreen, BatchMetaEditor } from "@app/meta-editor";
import { ExporterScreen } from "@app/export-scene-as-json";
import { DataMapperScreen } from "@app/data-mapper";
import { CopywriterScreen } from "@app/copywriter";
import { CopywriterScreen, ChatScreen } from "@app/copywriter";
import { GlobalizationScreen } from "@app/i18n";
import { ToolboxScreen } from "../pages/tool-box";
import { FontReplacerScreen } from "@toolbox/font-replacer";
Expand Down Expand Up @@ -74,7 +74,8 @@ function Screen(props: { screen: WorkScreen }) {
case WorkScreen.photo:
return <PhotoScreen />;
case WorkScreen.copy:
return <CopywriterScreen />;
// return <CopywriterScreen />;
return <ChatScreen />;
case WorkScreen.lint:
return <LintScreen />;
case WorkScreen.live:
Expand Down
193 changes: 193 additions & 0 deletions packages/app-copywriter/chat.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import React, { useEffect } from "react";
import styled from "@emotion/styled";
import { motion, AnimatePresence } from "framer-motion";
import { Bubble, GroupLabel } from "./components";
import { PromptInputBox } from "@ui/ai";
import { PaperPlaneIcon } from "@radix-ui/react-icons";
import ReactMarkdown from "react-markdown";
import type { Message } from "./core/conversation";
import * as api from "./client";

export function ChatScreen() {
const [busy, setBusy] = React.useState(false);
const [error, setError] = React.useState<Error | null>(null);
const [message, setMessage] = React.useState("");
const [messages, setMessages] = React.useState<Message[]>([]);
const messages_bottom_ref = React.useRef<HTMLDivElement>(null);

const action = () => {
setBusy(true);
setMessage("");

const history = Array.from(messages);

// add user's message
setMessages((l) =>
l.concat({
role: "user",
content: message,
})
);

api
.chat({ content: message, history: history })
.then(({ response }) => {
setMessages((l) =>
l.concat({
role: "assistant",
content: response,
})
);
})
.catch((e) => {
setError(e);
})
.finally(() => {
setBusy(false);
});
};

const scrollToBottom = () => {
messages_bottom_ref.current?.scrollIntoView({ behavior: "smooth" });
};

useEffect(() => {
scrollToBottom();
}, [messages]);

return (
<div
style={{
display: "flex",
flexDirection: "column",
height: "100%",
flex: 1,
}}
>
{messages?.length ? (
<>
<Messages ref={messages_bottom_ref} data={messages} />
</>
) : (
<></>
)}

<motion.div
style={{
padding: 16,
}}
initial={{
opacity: 0.0,
y: 16,
}}
animate={{
y: 0,
opacity: 1,
}}
transition={{
duration: 0.2,
damping: 15,
stiffness: 200,
}}
>
<PromptInputBox
//
canSubmit={message.length > 1}
readonly={busy}
prompting={busy}
onSubmit={action}
value={message}
submit={{
icon: <PaperPlaneIcon />,
}}
onChange={(v) => {
setMessage(v);
}}
style={{
background: "white",
}}
/>
</motion.div>
</div>
);
}

const ResponseItem = ({
children,
delay,
}: React.PropsWithChildren<{
delay: number;
}>) => {
return (
<motion.div
initial={{ y: 16, opacity: 0 }}
animate={{
y: 0,
opacity: 1,
transition: {
delay,
damping: 15,
stiffness: 200,
},
}}
exit={{ y: -16, opacity: 0 }}
transition={{ duration: 0.2 }}
>
{children}
</motion.div>
);
};

const Messages = React.forwardRef(function Messages(
{ data }: { data: Message[] },
bottomRef?: React.Ref<HTMLDivElement>
) {
return (
<>
<div
style={{
flex: 1,
display: "flex",
flexDirection: "column",
overflow: "auto",
gap: 8,
}}
>
{/* @ts-ignore */}
<AnimatePresence>
{data.map(({ content, role }, index) => {
const emoji = role === "user" ? "👨‍💻" : "🤖";

return (
<ResponseItem delay={0.2} key={index}>
<Bubble
style={{
background: role === "user" ? "white" : undefined,
flexDirection: "row",
gap: 12,
borderRadius: 0,
}}
onClick={() => {
// TODO:
}}
>
<div
style={{
fontSize: 21,
}}
>
{emoji}
</div>
<p>
<ReactMarkdown>{content}</ReactMarkdown>
</p>
</Bubble>
</ResponseItem>
);
})}
</AnimatePresence>
<div style={{ float: "left", clear: "both" }} ref={bottomRef} />
</div>
</>
);
});
24 changes: 22 additions & 2 deletions packages/app-copywriter/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Axios from "axios";
import type { Message } from "../core/conversation";

const client = Axios.create({
baseURL: "/api",
Expand All @@ -14,10 +15,29 @@ interface TextPrompt {
q: string;
}

export async function prompt(p: TextPrompt): Promise<TextResponse> {
const { data } = await client.get<TextResponse>("/generative/texts", {
export async function copies(p: TextPrompt): Promise<TextResponse> {
const { data } = await client.get<TextResponse>("/generative/copies", {
params: p,
});

return data;
}

interface ChatPrompt {
content: string;
history: Message[];
}

interface ChatResponse {
q: string;
response: string;
model: string;
}

export async function chat(p: ChatPrompt): Promise<ChatResponse> {
const { data } = await client.post<ChatResponse>("/generative/chat", {
data: p,
});

return data;
}
18 changes: 17 additions & 1 deletion packages/app-copywriter/components/bubble.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@ import styled from "@emotion/styled";
export function Bubble({
onClick,
children,
style = {},
}: React.PropsWithChildren<{
onClick?: () => void;
style?: React.CSSProperties;
}>) {
return <BubbleWrapper onClick={onClick}>{children}</BubbleWrapper>;
return (
<BubbleWrapper style={style} onClick={onClick}>
{children}
</BubbleWrapper>
);
}

const BubbleWrapper = styled.div`
Expand All @@ -18,9 +24,19 @@ const BubbleWrapper = styled.div`
background: rgba(0, 0, 0, 0.02);
border-radius: 8px;

font-family: "Inter", sans-serif;
font-weight: 400;

p {
margin: 0;
font-size: 16px;
line-height: 140%;
color: rgba(0, 0, 0, 0.8);
}

&:hover {
background: rgba(0, 0, 0, 0.08);
}

transition: all 0.05s ease-in-out;
`;
1 change: 0 additions & 1 deletion packages/app-copywriter/components/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from "./bubble";
export * from "./group-label";
export * from "./prompt-input-box";
6 changes: 3 additions & 3 deletions packages/app-copywriter/copywriter.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, { useEffect } from "react";
import styled from "@emotion/styled";
import { motion, AnimatePresence } from "framer-motion";
import { PromptInputBox, Bubble, GroupLabel } from "./components";
import { Bubble, GroupLabel } from "./components";
import { PromptInputBox } from "@ui/ai";
import { LightningBoltIcon, ListBulletIcon } from "@radix-ui/react-icons";
import { EK_APPLY_TEXT_CHARACTERS } from "@core/constant";
import * as api from "./client";
import { useSingleSelection } from "plugin-app";
import { IReflectNodeReference } from "@design-sdk/figma-node";

interface ReplaceTextCharactersProps {
type: "selection" | "id";
Expand Down Expand Up @@ -74,7 +74,7 @@ export function CopywriterScreen() {
setResults([]);

api
.prompt({ q: prompt })
.copies({ q: prompt })
.then(({ texts }) => {
setResults(texts);
})
Expand Down
39 changes: 39 additions & 0 deletions packages/app-copywriter/core/conversation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
export type Message = ResponseMessage | UserMessage;

export interface UserMessage {
role: "user";
content: string;
}

export type ResponseMessage = {
role: "assistant";
content: string;
};

export class Conversation {
_messages: Message[];

constructor() {
this._messages = [];
}

get messages() {
return this._messages;
}

addMessage(message: Message) {
this._messages.push(message);
}

get lastMessage(): Message {
return this._messages[this._messages.length - 1];
}

get lastResponse(): Message {
return this._messages[this._messages.length - 2];
}

get lastUserMessage(): Message {
return this._messages[this._messages.length - 3];
}
}
1 change: 1 addition & 0 deletions packages/app-copywriter/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { CopywriterScreen } from "./copywriter";
export { ChatScreen } from "./chat";
1 change: 1 addition & 0 deletions packages/ui-ai/components/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const dummy = "";
2 changes: 2 additions & 0 deletions packages/ui-ai/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./components";
export * from "./prompt";
24 changes: 24 additions & 0 deletions packages/ui-ai/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "@ui/ai",
"version": "0.0.0",
"private": false,
"license": "Apache-2.0",
"dependencies": {
"@tiptap/core": "^2.0.0-beta.220",
"@tiptap/extension-bullet-list": "^2.0.0-beta.220",
"@tiptap/extension-code-block": "^2.0.0-beta.220",
"@tiptap/extension-code-block-lowlight": "^2.0.0-beta.220",
"@tiptap/extension-document": "^2.0.0-beta.220",
"@tiptap/extension-link": "^2.0.0-beta.220",
"@tiptap/extension-list-item": "^2.0.0-beta.220",
"@tiptap/extension-mention": "^2.0.0-beta.220",
"@tiptap/extension-placeholder": "^2.0.0-beta.220",
"@tiptap/extension-text": "^2.0.0-beta.220",
"@tiptap/pm": "^2.0.0-beta.220",
"@tiptap/react": "^2.0.0-beta.220",
"@tiptap/starter-kit": "^2.0.0-beta.220",
"@tiptap/suggestion": "^2.0.0-beta.220",
"lowlight": "^2.8.1",
"react-markdown": "^8.0.5"
}
}
Loading