Skip to content

Commit

Permalink
update sharing using feature
Browse files Browse the repository at this point in the history
  • Loading branch information
zmh-program committed Oct 19, 2023
1 parent 0f345fb commit 9eb021a
Show file tree
Hide file tree
Showing 14 changed files with 227 additions and 106 deletions.
3 changes: 3 additions & 0 deletions adapter/chatgpt/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ func (c *ChatInstance) Test() bool {
Message: []globals.Message{{Role: "user", Content: "hi"}},
Token: 1,
})
if err != nil {
fmt.Println(fmt.Sprintf("%s: test failed (%s)", c.GetApiKey(), err.Error()))
}

return err == nil && len(result) > 0
}
Expand Down
18 changes: 12 additions & 6 deletions app/src/components/home/ConversationSegment.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { toggleConversation } from "../../conversation/history.ts";
import { filterMessage, mobile } from "../../utils.ts";
import { setMenu } from "../../store/menu.ts";
import {MessageSquare, MoreHorizontal, Share2, Trash2} from "lucide-react";
import { MessageSquare, MoreHorizontal, Share2, Trash2 } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
Expand All @@ -16,7 +16,10 @@ import { useState } from "react";
type ConversationSegmentProps = {
conversation: ConversationInstance;
current: number;
operate: (conversation: { target: ConversationInstance, type: string }) => void;
operate: (conversation: {
target: ConversationInstance;
type: string;
}) => void;
};
function ConversationSegment({
conversation,
Expand Down Expand Up @@ -45,10 +48,13 @@ function ConversationSegment({
<MessageSquare className={`h-4 w-4 mr-1`} />
<div className={`title`}>{filterMessage(conversation.name)}</div>
<div className={`id`}>{conversation.id}</div>
<DropdownMenu open={open} onOpenChange={(state: boolean) => {
setOpen(state);
if (state) setOffset(new Date().getTime());
}}>
<DropdownMenu
open={open}
onOpenChange={(state: boolean) => {
setOpen(state);
if (state) setOffset(new Date().getTime());
}}
>
<DropdownMenuTrigger>
<MoreHorizontal className={`more h-5 w-5 p-0.5`} />
</DropdownMenuTrigger>
Expand Down
4 changes: 2 additions & 2 deletions app/src/conf.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from "axios";

export const version = "3.4.2";
export const deploy: boolean = false;
export const version = "3.4.3";
export const deploy: boolean = true;
export let rest_api: string = "http://localhost:8094";
export let ws_api: string = "ws://localhost:8094";

Expand Down
10 changes: 10 additions & 0 deletions app/src/conversation/conversation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ChatProps, Connection, StreamMessage } from "./connection.ts";
import { Message } from "./types.ts";
import { event } from "../events/sharing.ts";

type ConversationCallback = (idx: number, message: Message[]) => void;

Expand All @@ -18,6 +19,15 @@ export class Conversation {
this.id = id;
this.end = true;
this.connection = new Connection(this.id);

if (id === -1 && this.idx === -1) {
event.bind(({ refer, data }) => {
console.log(
`[conversation] load from sharing event (ref: ${refer}, length: ${data.length})`,
);
this.load(data);
});
}
}

public setId(id: number): void {
Expand Down
12 changes: 12 additions & 0 deletions app/src/conversation/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { useShared } from "../utils.ts";
import { ChatProps } from "./connection.ts";
import { supportModelConvertor } from "../conf.ts";
import { AppDispatch } from "../store";
import { event } from "../events/sharing.ts";

export class Manager {
conversations: Record<number, Conversation>;
Expand All @@ -21,6 +22,17 @@ export class Manager {
this.conversations = {};
this.conversations[-1] = this.createConversation(-1);
this.current = -1;

event.addEventListener(async (data) => {
console.debug(`[manager] accept sharing event (refer: ${data.refer})`);

const interval = setInterval(() => {
if (this.dispatch) {
this.toggle(this.dispatch, -1);
clearInterval(interval);
}
}, 100);
});
}

public setDispatch(dispatch: AppDispatch): void {
Expand Down
15 changes: 7 additions & 8 deletions app/src/conversation/sharing.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import axios from "axios";
import {Message} from "./types.ts";
import { Message } from "./types.ts";

export type SharingForm = {
status: boolean;
message: string;
data: string;
}
};

export type ViewData = {
name: string;
Expand All @@ -18,10 +18,11 @@ export type ViewForm = {
status: boolean;
message: string;
data: ViewData | null;
}
};

export async function shareConversation(
id: number, refs: number[] = [-1],
id: number,
refs: number[] = [-1],
): Promise<SharingForm> {
try {
const resp = await axios.post("/conversation/share", { id, refs });
Expand All @@ -31,9 +32,7 @@ export async function shareConversation(
}
}

export async function viewConversation(
hash: string,
): Promise<ViewForm> {
export async function viewConversation(hash: string): Promise<ViewForm> {
try {
const resp = await axios.get(`/conversation/view?hash=${hash}`);
return resp.data as ViewForm;
Expand All @@ -42,6 +41,6 @@ export async function viewConversation(
status: false,
message: (e as Error).message,
data: null,
}
};
}
}
12 changes: 12 additions & 0 deletions app/src/events/sharing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { EventCommitter } from "./struct.ts";
import { Message } from "../conversation/types.ts";

export type SharingEvent = {
refer: string;
data: Message[];
};

export const event = new EventCommitter<SharingEvent>({
name: "sharing",
destroyedAfterTrigger: true,
});
51 changes: 51 additions & 0 deletions app/src/events/struct.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
export type EventCommitterProps = {
name: string;
destroyedAfterTrigger?: boolean;
};

export class EventCommitter<T> {
name: string;
trigger: ((data: T) => void) | undefined;
listeners: ((data: T) => void)[] = [];
destroyedAfterTrigger: boolean;

constructor({ name, destroyedAfterTrigger = false }: EventCommitterProps) {
this.name = name;
this.destroyedAfterTrigger = destroyedAfterTrigger;
}

protected setTrigger(trigger: (data: T) => void) {
this.trigger = trigger;
}

protected clearTrigger() {
this.trigger = undefined;
}

protected triggerEvent(data: T) {
this.trigger && this.trigger(data);
if (this.destroyedAfterTrigger) this.clearTrigger();

this.listeners.forEach((listener) => listener(data));
}

public emit(data: T) {
this.triggerEvent(data);
}

public bind(trigger: (data: T) => void) {
this.setTrigger(trigger);
}

public addEventListener(listener: (data: T) => void) {
this.listeners.push(listener);
}

public removeEventListener(listener: (data: T) => void) {
this.listeners = this.listeners.filter((item) => item !== listener);
}

public clearEventListener() {
this.listeners = [];
}
}
21 changes: 12 additions & 9 deletions app/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,14 +178,15 @@ const resources = {
"share-conversation": "Share Conversation",
description: "Share this conversation with others: ",
"copy-link": "Copy Link",
"view": "View",
view: "View",
success: "Share success",
failed: "Share failed",
copied: "Copied",
"copied-description": "Link has been copied to clipboard",
"not-found": "Conversation not found",
"not-found-description": "Conversation not found, please check if the link is correct or the conversation has been deleted",
}
"not-found-description":
"Conversation not found, please check if the link is correct or the conversation has been deleted",
},
},
},
cn: {
Expand Down Expand Up @@ -350,14 +351,15 @@ const resources = {
"share-conversation": "分享对话",
description: "将此对话与他人分享:",
"copy-link": "复制链接",
"view": "查看",
view: "查看",
success: "分享成功",
failed: "分享失败",
copied: "复制成功",
"copied-description": "链接已复制到剪贴板",
"not-found": "对话未找到",
"not-found-description": "对话未找到,请检查链接是否正确或对话是否已被删除",
}
"not-found-description":
"对话未找到,请检查链接是否正确或对话是否已被删除",
},
},
},
ru: {
Expand Down Expand Up @@ -533,14 +535,15 @@ const resources = {
"share-conversation": "Поделиться разговором",
description: "Поделитесь этим разговором с другими: ",
"copy-link": "Скопировать ссылку",
"view": "Посмотреть",
view: "Посмотреть",
success: "Поделиться успешно",
failed: "Поделиться не удалось",
copied: "Скопировано",
"copied-description": "Ссылка скопирована в буфер обмена",
"not-found": "Разговор не найден",
"not-found-description": "Разговор не найден, пожалуйста, проверьте, правильная ли ссылка или разговор был удален",
}
"not-found-description":
"Разговор не найден, пожалуйста, проверьте, правильная ли ссылка или разговор был удален",
},
},
},
};
Expand Down
2 changes: 1 addition & 1 deletion app/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const router = createBrowserRouter([
id: "share",
path: "/share/:hash",
Component: Sharing,
}
},
]);

export default router;
Loading

0 comments on commit 9eb021a

Please sign in to comment.