Skip to content
Open
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
209 changes: 54 additions & 155 deletions chatbot/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ import { credentialHint, openCredentialSettings } from "./credentials";
import { groupSessionHistory, scheduledSession, sessionProjectName } from "./session-history.js";
import { runSessionState, sessionReplyStatus, sessionTooltip, sidebarReplyStatus } from "./session-status.js";
import { unreadReply, useReadReplies } from "./session-unread.js";
import MentionPicker from "./MentionPicker";
import ReferenceInput from "./ReferenceInput";
import Participants, { Avatar, authorFor } from "./Participants";
import IssueContext from "./IssueContext";
import { mentionAt, insertMention } from "./mentions.js";
import { insertMention } from "./mentions.js";
import { elementTitle } from "./element-context.js";
import HarnessIcon from "./HarnessIcon";
import QueuedMessages from "./QueuedMessages";
Expand Down Expand Up @@ -365,9 +365,9 @@ export default function App() {
chat.newChat();
}
const input = useRef(),
referenceInput = useRef(),
sessionPress = useRef(null),
sessionClickSuppressed = useRef(null),
mentionPicker = useRef(),
projectPicker = useRef(null),
headerProjectPicker = useRef(null),
fileInput = useRef(),
Expand Down Expand Up @@ -667,11 +667,13 @@ export default function App() {
setText(value.text);
setReferences([ref]);
setMention(null);
const editor = input.current;
requestAnimationFrame(() => {
// Preserve the user’s focus if they interacted during the handoff.
if (draftReady.current !== draftKey || document.activeElement !== focusBeforeHandoff) return;
input.current?.focus();
input.current?.setSelectionRange(value.caret, value.caret);
if (draftReady.current !== draftKey || !editor?.isConnected || editor.value !== value.text) return;
if (document.activeElement !== focusBeforeHandoff) return;
editor.focus();
editor.setSelectionRange(value.caret, value.caret);
});
})
.catch((e) => current && chat.setError(e.message))
Expand Down Expand Up @@ -981,18 +983,6 @@ export default function App() {
setUploading(false);
}
}
function openReferences() {
const caret = input.current?.selectionStart ?? text.length;
setMention(
mentionAt(text, caret, references) || {
start: caret,
end: caret,
query: "",
},
);
closeMenu();
input.current?.focus();
}
// addElementReference takes an element picked in the native preview: it
// rides along as a reference chip, without a token in the text.
function addElementReference(ref) {
Expand All @@ -1003,27 +993,6 @@ export default function App() {
setReferences((old) => [...old, ref]);
requestAnimationFrame(() => input.current?.focus());
}
function addReference(ref) {
if (
references.length >= 12 &&
!references.some((x) => x.type === ref.type && x.id === ref.id)
) {
chat.setError("每轮最多引用 12 个对象。");
return;
}
const value = insertMention(text, mention, ref);
setText(value.text);
setReferences((old) =>
old.some((x) => x.type === ref.type && x.id === ref.id)
? old
: [...old, ref],
);
setMention(null);
requestAnimationFrame(() => {
input.current?.focus();
input.current?.setSelectionRange(value.caret, value.caret);
});
}
const sidebarSections = splitSidebarSections(chat.sessions, chat.projects, {
archived,
mineOnly,
Expand Down Expand Up @@ -1985,22 +1954,7 @@ export default function App() {
onSendNow={chat.sendNow}
/>
<div className="composer">
<MentionPicker
ref={mentionPicker}
key={chat.projectId}
projectId={chat.projectId}
trigger={mention}
editor={input}
onSelect={addReference}
onClose={() => setMention(null)}
issueId={chat.issueId}
canManageIssue={!!chat.projectId && !chat.busy && (!chat.activeId || !!chat.session) && !chat.session?.shared && !chat.readOnly}
onManageIssue={() => {
setMention(null);
setIssueContextOpen(true);
}}
/>
{attachments.length || pendingAttachments.length || references.length ? (
{attachments.length || pendingAttachments.length ? (
<div className="composer-attachments">
{pendingAttachments.map((a) => (
<span
Expand Down Expand Up @@ -2061,109 +2015,51 @@ export default function App() {
</span>
);
})}
{references.map((ref) => (
<span
key={ref.type + ref.id}
className={`composer-attachment-file${ref.type === "element" ? " is-element" : ""}`}
title={ref.type === "element" ? elementTitle(ref) : undefined}
>
{ref.type === "element" ? (
<HarnessIcon name="crosshair" size={13} />
) : (
"@"
)}
{ref.name || ref.id}
<button
aria-label={`移除引用 ${ref.name || ref.id}`}
onClick={() => {
setReferences((old) =>
old.filter(
(x) => x.id !== ref.id || x.type !== ref.type,
),
);
setText((old) =>
old.replace(`@${ref.name || ref.id} `, ""),
);
setMention(null);
}}
>
<HarnessIcon name="close" size={13} />
</button>
</span>
))}
</div>
) : null}
<textarea
ref={input}
aria-label="消息"
rows={2}
placeholder={
chat.activeId
? "告诉我接下来想做点什么"
: "聊聊你的想法,或交给我一件事"
}
value={text}
aria-expanded={!!mention}
onChange={(e) => {
setText(e.target.value);
setReferences((old) =>
old.filter(
(ref) =>
!text.includes(`@${ref.name || ref.id}`) ||
e.target.value.includes(`@${ref.name || ref.id}`),
),
);
setMention(
e.nativeEvent.isComposing
? null
: mentionAt(
e.target.value,
e.target.selectionStart,
references,
),
);
e.target.style.height = "auto";
e.target.style.height =
Math.min(e.target.scrollHeight, 220) + "px";
<ReferenceInput
ref={referenceInput}
editorRef={input}
projectId={chat.projectId}
text={text}
references={references}
mention={mention}
onMentionChange={setMention}
onChange={({ text: nextText, references: nextReferences }) => {
setText(nextText);
setReferences(nextReferences);
}}
onCompositionEnd={(e) =>
setMention(
mentionAt(
e.target.value,
e.target.selectionStart,
references,
),
)
}
onClick={(e) =>
setMention(
mentionAt(
e.target.value,
e.target.selectionStart,
references,
),
)
}
onPaste={(e) => {
const files = [...e.clipboardData.items]
.filter((i) => i.kind === "file")
.map((i) => i.getAsFile())
.filter(Boolean);
if (files.length) {
e.preventDefault();
void upload(files);
}
onError={(message) => chat.setError(message)}
issueId={chat.issueId}
canManageIssue={!!chat.projectId && !chat.busy && (!chat.activeId || !!chat.session) && !chat.session?.shared && !chat.readOnly}
onManageIssue={() => {
setMention(null);
setIssueContextOpen(true);
}}
onKeyDown={(e) => {
if (mention && mentionPicker.current?.keyDown(e)) return;
if (
e.key === "Enter" &&
!e.shiftKey &&
!e.nativeEvent.isComposing
) {
e.preventDefault();
void submit();
}
textareaProps={{
"aria-label": "消息",
rows: 2,
placeholder: chat.activeId ? "告诉我接下来想做点什么" : "聊聊你的想法,或交给我一件事",
onInput: (e) => {
e.target.style.height = "auto";
e.target.style.height = Math.min(e.target.scrollHeight, 220) + "px";
},
onPaste: (e) => {
const files = [...e.clipboardData.items]
.filter((i) => i.kind === "file")
.map((i) => i.getAsFile())
.filter(Boolean);
if (files.length) {
e.preventDefault();
void upload(files);
}
},
onKeyDown: (e) => {
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
void submit();
}
},
}}
/>
<footer className="composer-toolbar">
Expand Down Expand Up @@ -2195,7 +2091,10 @@ export default function App() {
<HarnessIcon name="paperclip" size={15} />
上传图片或文件
</button>
<button role="menuitem" onClick={openReferences}>
<button role="menuitem" onClick={() => {
referenceInput.current?.openReferences();
closeMenu();
}}>
<HarnessIcon name="connector" size={15} />
引用项目资产
</button>
Expand Down
62 changes: 44 additions & 18 deletions chatbot/src/MentionPicker.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export default forwardRef(function MentionPicker(
trigger,
onSelect,
onClose,
onRestoreFocus,
editor,
issueId,
onManageIssue,
Expand Down Expand Up @@ -75,9 +76,10 @@ export default forwardRef(function MentionPicker(
}),
);
if (version !== request.current || !openRef.current) return;
setRows((old) =>
offset ? [...old, ...(data.items || data)] : data.items || data,
const items = (data.items || data).filter((item) =>
referenceTypes.some((reference) => reference.type === item.type),
);
setRows((old) => offset ? [...old, ...items] : items);
setNext(data.nextOffset || 0);
} catch (e) {
if (version === request.current && openRef.current) setError(e.message);
Expand All @@ -104,10 +106,8 @@ export default forwardRef(function MentionPicker(
useEffect(() => {
if (!open) return;
function outside(event) {
if (
!root.current?.contains(event.target) &&
event.target !== editor.current
)
const target = event.composedPath?.()[0] || event.target;
if (!root.current?.contains(target) && target !== editor.current)
onClose();
}
document.addEventListener("pointerdown", outside);
Expand All @@ -126,12 +126,13 @@ export default forwardRef(function MentionPicker(
}
function keyDown(event) {
if (!open) return false;
if (event.nativeEvent?.isComposing) return false;
if (event.nativeEvent?.isComposing || event.isComposing || event.keyCode === 229) return false;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
onClose();
editor.current?.focus();
if (onRestoreFocus) onRestoreFocus();
else editor.current?.focus({ preventScroll: true });
return true;
}
if (["ArrowDown", "ArrowUp"].includes(event.key)) {
Expand Down Expand Up @@ -167,30 +168,55 @@ export default forwardRef(function MentionPicker(
const node = root.current;
if (!open || !node) return undefined;
const fit = () => {
const box = node.getBoundingClientRect();
let top = 12;
const anchor = node.parentElement.getBoundingClientRect();
const viewport = window.visualViewport;
let top = (viewport?.offsetTop || 0) + 8,
bottom = (viewport?.offsetTop || 0) + (viewport?.height || window.innerHeight) - 8,
left = (viewport?.offsetLeft || 0) + 8,
right = (viewport?.offsetLeft || 0) + (viewport?.width || window.innerWidth) - 8;
for (
let parent = node.parentElement;
parent;
parent = parent.parentElement
parent = parent.parentElement || parent.getRootNode()?.host
) {
const style = getComputedStyle(parent);
const clips = [style.overflowY, style.overflowX].some((value) =>
["auto", "scroll", "hidden", "clip"].includes(value),
);
if (!clips) continue;
top = Math.max(top, parent.getBoundingClientRect().top + 8);
const clip = parent.getBoundingClientRect();
top = Math.max(top, clip.top + 8);
bottom = Math.min(bottom, clip.bottom - 8);
left = Math.max(left, clip.left + 8);
right = Math.min(right, clip.right - 8);
}
const above = anchor.top - top - 8, below = bottom - anchor.bottom - 8;
const up = above >= below;
let room = Math.max(above, below), y = up ? anchor.top - 8 : anchor.bottom + 8;
// On short screens the picker overlays the editor rather than escaping
// its scroll container or shrinking the results to an unusable sliver.
if (room < 160) {
room = Math.max(0, bottom - top);
y = up ? bottom : top;
}
const room = box.bottom - top;
node.style.maxHeight = `${Math.min(440, Math.max(80, room))}px`;
node.style.top = up ? "auto" : `${y - anchor.top}px`;
node.style.bottom = up ? `${anchor.bottom - y}px` : "auto";
node.style.left = `${Math.max(left, Math.min(anchor.left, right - anchor.width)) - anchor.left}px`;
node.style.right = "auto";
node.style.width = `${Math.max(0, Math.min(anchor.width, right - left))}px`;
node.style.maxHeight = `${Math.max(0, Math.min(440, room))}px`;
node.dataset.placement = up ? "above" : "below";
};
fit();
window.addEventListener("resize", fit);
const scroller = node.closest(".empty-conversation, .message-scroll");
scroller?.addEventListener("scroll", fit, { passive: true });
document.addEventListener("scroll", fit, true);
window.visualViewport?.addEventListener("resize", fit);
window.visualViewport?.addEventListener("scroll", fit);
return () => {
window.removeEventListener("resize", fit);
scroller?.removeEventListener("scroll", fit);
document.removeEventListener("scroll", fit, true);
window.visualViewport?.removeEventListener("resize", fit);
window.visualViewport?.removeEventListener("scroll", fit);
};
}, [open, presence.phase, options.length, categories]);
if (!presence.mounted) return null;
Expand Down Expand Up @@ -227,7 +253,7 @@ export default forwardRef(function MentionPicker(
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button type="button" onClick={() => { onClose(); editor.current?.focus({ preventScroll: true }); }} className="mention-close">
<button type="button" onClick={() => { onClose(); if (onRestoreFocus) onRestoreFocus(); else editor.current?.focus({ preventScroll: true }); }} className="mention-close">
关闭
</button>
</header>
Expand Down
Loading