DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(web): shared IME-composing hook + citation-anchor helper; symmetric scrollbar gutter
Bingxi Zhao (Frank)b030697df71d
diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsxindex 1c67fcd64..01128c2ff 100644--- a/web/app/(workspace)/book/components/BookChatPanel.tsx+++ b/web/app/(workspace)/book/components/BookChatPanel.tsx@@ -31,6 +31,7 @@ import {readFileAsDataUrl,} from "@/lib/file-attachments";import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";+import { useImeComposing } from "@/lib/use-ime-composing";import { shouldAppendEventContent } from "@/lib/stream";import {UnifiedWSClient,@@ -115,7 +116,8 @@ export default function BookChatPanel({const scrollerRef = useRef<HTMLDivElement | null>(null);const fileInputRef = useRef<HTMLInputElement | null>(null);const dragRef = useRef<{ startX: number; startWidth: number } | null>(null);- const isComposingRef = useRef(false);+ const { isComposingRef, onCompositionStart, onCompositionEnd } =+ useImeComposing();useEffect(() => {const raw = window.localStorage.getItem("deeptutor.bookChat.width");@@ -560,14 +562,8 @@ export default function BookChatPanel({placeholder={t("Ask about this page…")}rows={1}onPaste={handlePaste}- onCompositionStart={() => {- isComposingRef.current = true;- }}- onCompositionEnd={() => {- setTimeout(() => {- isComposingRef.current = false;- }, 0);- }}+ onCompositionStart={onCompositionStart}+ onCompositionEnd={onCompositionEnd}onKeyDown={(e: KeyboardEvent<HTMLTextAreaElement>) => {if (shouldSubmitOnEnter(e, isComposingRef.current)) {e.preventDefault();diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 222ecdb4e..a14a490f3 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -1885,7 +1885,12 @@ export default function ChatPage() {data-chat-scroll-root="true"onScroll={handleMessagesScroll}onClick={handleMessagesClick}- className={`w-full flex-1 min-h-0 overflow-y-auto [scrollbar-gutter:stable] ${hasMessages ? "pt-6" : "pt-2 pb-6"}`}+ // `both-edges` reserves the scrollbar gutter on both sides so+ // the inner mx-auto column centers on the same axis as the+ // header and composer (siblings outside this scrollport) on+ // classic-scrollbar platforms; plain `stable` would shift it+ // ~half a scrollbar-width left of them.+ className={`w-full flex-1 min-h-0 overflow-y-auto [scrollbar-gutter:stable_both-edges] ${hasMessages ? "pt-6" : "pt-2 pb-6"}`}style={hasMessages? (() => {diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex 161dbe841..68fe074c3 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -52,6 +52,7 @@ import { hasVisibleMarkdownContent } from "@/lib/markdown-display";import type { SelectedBookReference } from "@/lib/book-references";import { buildVisiblePath, type SiblingInfo } from "@/lib/message-branches";import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";+import { useImeComposing } from "@/lib/use-ime-composing";import type { SpaceMemoryFile } from "@/lib/space-items";import {AskUserOptions,@@ -877,7 +878,8 @@ const UserMessage = memo(function UserMessage({const { t } = useTranslation();const [editing, setEditing] = useState(false);const [draft, setDraft] = useState(msg.content);- const isComposingRef = useRef(false);+ const { isComposingRef, onCompositionStart, onCompositionEnd } =+ useImeComposing();// Connected subagents ride in knowledge_bases (same selection path) but are// agents, not KBs — this maps a selected name to its backend kind so the// reference chip can badge it with the agent's brand icon.@@ -1042,16 +1044,8 @@ const UserMessage = memo(function UserMessage({submitEdit();}}}- onCompositionStart={() => {- isComposingRef.current = true;- }}- onCompositionEnd={() => {- // Some IMEs fire compositionend before the Enter keydown that confirms- // a candidate, so keep the guard through the current event turn.- setTimeout(() => {- isComposingRef.current = false;- }, 0);- }}+ onCompositionStart={onCompositionStart}+ onCompositionEnd={onCompositionEnd}rows={Math.min(8, Math.max(2, draft.split("\n").length))}className="w-full resize-none border-0 bg-transparent text-[14px] leading-relaxed text-[var(--foreground)] outline-none focus:outline-none"/>diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsxindex 707493e3e..ae1b61a27 100644--- a/web/components/chat/home/ComposerInput.tsx+++ b/web/components/chat/home/ComposerInput.tsx@@ -19,6 +19,7 @@ import ChatSpaceMenu, {import { agentGlyph } from "@/components/agents/agent-icons";import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";+import { useImeComposing } from "@/lib/use-ime-composing";interface ComposerInputProps {textareaRef: RefObject<HTMLTextAreaElement | null>;@@ -178,7 +179,8 @@ export const ComposerInput = memo(// letting `memo` on ChatSpaceMenu actually skip re-renders when// `showAtPopup` doesn't change.const inputRef = useRef("");- const isComposingRef = useRef(false);+ const { isComposingRef, onCompositionStart, onCompositionEnd } =+ useImeComposing();// Helper that always updates state and ref together so they can't drift.const setInputBoth = useCallback((value: string) => {inputRef.current = value;@@ -321,21 +323,10 @@ export const ComposerInput = memo(agentMentionMode,filteredAgents,handleSelectAgentMention,+ isComposingRef,],);- const handleCompositionStart = useCallback(() => {- isComposingRef.current = true;- }, []);-- const handleCompositionEnd = useCallback(() => {- // Some IMEs fire compositionend before the Enter keydown that confirms- // a candidate, so keep the guard through the current event turn.- setTimeout(() => {- isComposingRef.current = false;- }, 0);- }, []);-const handleSelectSpaceItem = useCallback((key:@@ -509,8 +500,8 @@ export const ComposerInput = memo(value={input}onChange={handleInputChange}onKeyDown={handleKeyDown}- onCompositionStart={handleCompositionStart}- onCompositionEnd={handleCompositionEnd}+ onCompositionStart={onCompositionStart}+ onCompositionEnd={onCompositionEnd}onClick={handleTextareaClick}onPaste={onPaste}rows={1}diff --git a/web/components/chat/home/SimpleComposerInput.tsx b/web/components/chat/home/SimpleComposerInput.tsxindex 4d829a058..df9751a03 100644--- a/web/components/chat/home/SimpleComposerInput.tsx+++ b/web/components/chat/home/SimpleComposerInput.tsx@@ -1,9 +1,10 @@"use client";-import { memo, useCallback, useRef, useState, type RefObject } from "react";+import { memo, useCallback, useState, type RefObject } from "react";import { useTranslation } from "react-i18next";import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";+import { useImeComposing } from "@/lib/use-ime-composing";interface SimpleComposerInputProps {textareaRef: RefObject<HTMLTextAreaElement | null>;@@ -18,7 +19,8 @@ export const SimpleComposerInput = memo(function SimpleComposerInput({}: SimpleComposerInputProps) {const { t } = useTranslation();const [input, setInput] = useState("");- const isComposingRef = useRef(false);+ const { isComposingRef, onCompositionStart, onCompositionEnd } =+ useImeComposing();useAutoSizedTextarea(textareaRef, input, { min: 42, max: 200 });@@ -40,29 +42,17 @@ export const SimpleComposerInput = memo(function SimpleComposerInput({}}},- [input, onSend, disabled],+ [input, onSend, disabled, isComposingRef],);- const handleCompositionStart = useCallback(() => {- isComposingRef.current = true;- }, []);-- const handleCompositionEnd = useCallback(() => {- // Some IMEs fire compositionend before the Enter keydown that confirms- // a candidate, so keep the guard through the current event turn.- setTimeout(() => {- isComposingRef.current = false;- }, 0);- }, []);-return (<textarearef={textareaRef}value={input}onChange={handleInputChange}onKeyDown={handleKeyDown}- onCompositionStart={handleCompositionStart}- onCompositionEnd={handleCompositionEnd}+ onCompositionStart={onCompositionStart}+ onCompositionEnd={onCompositionEnd}placeholder={t("Type a message...")}rows={1}// Defensive cap — see ComposerInput for the same guard. Anything beyonddiff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsxindex 57b92c483..36613d8cc 100644--- a/web/components/common/RichMarkdownRenderer.tsx+++ b/web/components/common/RichMarkdownRenderer.tsx@@ -11,6 +11,7 @@ import {convertSequenceFenceToMermaid,processMarkdownContent,} from "@/lib/latex";+import { findCitationAnchor } from "@/lib/markdown-anchors";import {citationAnchorIdFor,escapeUnknownHtmlTagsForDisplay,@@ -581,19 +582,7 @@ export default function RichMarkdownRenderer({const ids = label.split(/\s*,\s*/);const scrollToRef = (event: React.MouseEvent, id?: string) => {event.preventDefault();- const hashTarget =- id && citationAnchorIdFor(id)- ? citationAnchorIdFor(id)- : href?.startsWith("#")- ? safeDecodeURIComponent(href.slice(1))- : "references";- const target =- document.getElementById(hashTarget || "") ??- document.getElementById("references");- const parentDetails = target?.closest("details");- if (parentDetails instanceof HTMLDetailsElement) {- parentDetails.open = true;- }+ const target = findCitationAnchor(href, id);if (target) scrollAnchorIntoView(target);};return (diff --git a/web/components/common/SimpleMarkdownRenderer.tsx b/web/components/common/SimpleMarkdownRenderer.tsxindex ed8bc963e..5f29f48a6 100644--- a/web/components/common/SimpleMarkdownRenderer.tsx+++ b/web/components/common/SimpleMarkdownRenderer.tsx@@ -3,6 +3,7 @@import React, { useMemo } from "react";import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";+import { findCitationAnchor } from "@/lib/markdown-anchors";import {citationAnchorIdFor,markdownUrlTransform,@@ -362,19 +363,7 @@ export default function SimpleMarkdownRenderer({const ids = label.split(/\s*,\s*/);const scrollToRef = (event: React.MouseEvent, id?: string) => {event.preventDefault();- const hashTarget =- id && citationAnchorIdFor(id)- ? citationAnchorIdFor(id)- : href?.startsWith("#")- ? safeDecodeURIComponent(href.slice(1))- : "references";- const target =- document.getElementById(hashTarget || "") ??- document.getElementById("references");- const parentDetails = target?.closest("details");- if (parentDetails instanceof HTMLDetailsElement) {- parentDetails.open = true;- }+ const target = findCitationAnchor(href, id);target?.scrollIntoView({ block: "start", behavior: "smooth" });};return (diff --git a/web/components/partners/PartnerComposer.tsx b/web/components/partners/PartnerComposer.tsxindex e875b2715..2aa51d68f 100644--- a/web/components/partners/PartnerComposer.tsx+++ b/web/components/partners/PartnerComposer.tsx@@ -28,6 +28,7 @@ import {readFileAsDataUrl,} from "@/lib/file-attachments";import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";+import { useImeComposing } from "@/lib/use-ime-composing";export interface PartnerPendingAttachment {type: "image" | "file";@@ -66,7 +67,8 @@ export const PartnerComposer = memo(function PartnerComposer({const fileInputRef = useRef<HTMLInputElement | null>(null);const dragCounterRef = useRef(0);const errorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const isComposingRef = useRef(false);+ const { isComposingRef, onCompositionStart, onCompositionEnd } =+ useImeComposing();useAutoSizedTextarea(textareaRef, input, { min: 24, max: 180 });@@ -230,7 +232,14 @@ export const PartnerComposer = memo(function PartnerComposer({submit();}},- [acceptCommand, boundedSlashIndex, slashMatches, slashOpen, submit],+ [+ acceptCommand,+ boundedSlashIndex,+ slashMatches,+ slashOpen,+ submit,+ isComposingRef,+ ],);const handleInputChange = useCallback(@@ -390,14 +399,8 @@ export const PartnerComposer = memo(function PartnerComposer({onChange={handleInputChange}onKeyDown={handleKeyDown}onPaste={handlePaste}- onCompositionStart={() => {- isComposingRef.current = true;- }}- onCompositionEnd={() => {- setTimeout(() => {- isComposingRef.current = false;- }, 0);- }}+ onCompositionStart={onCompositionStart}+ onCompositionEnd={onCompositionEnd}placeholder={placeholder ?? t("Type a message...")}rows={1}maxLength={32000}diff --git a/web/lib/markdown-anchors.ts b/web/lib/markdown-anchors.tsnew file mode 100644index 000000000..caddc5d86--- /dev/null+++ b/web/lib/markdown-anchors.ts@@ -0,0 +1,39 @@+/**+ * DOM-side citation-anchor resolution shared by RichMarkdownRenderer and+ * SimpleMarkdownRenderer. Deliberately kept out of markdown-display.ts,+ * which is pure string logic exercised by node tests — this helper touches+ * `document`.+ */++import {+ citationAnchorIdFor,+ safeDecodeURIComponent,+} from "@/lib/markdown-display";++/**+ * Resolve the element a citation link should scroll to and auto-open its+ * enclosing `<details>` so the target is actually visible. Fallback chain:+ * the citation id's own anchor, then the link's `#hash`, then the+ * `references` section (also the fallback when the resolved id is missing+ * from the DOM). Returns the target, or null when nothing matched; the+ * caller performs its own scroll.+ */+export function findCitationAnchor(+ href: string | undefined,+ id?: string,+): HTMLElement | null {+ const hashTarget =+ id && citationAnchorIdFor(id)+ ? citationAnchorIdFor(id)+ : href?.startsWith("#")+ ? safeDecodeURIComponent(href.slice(1))+ : "references";+ const target =+ document.getElementById(hashTarget || "") ??+ document.getElementById("references");+ const parentDetails = target?.closest("details");+ if (parentDetails instanceof HTMLDetailsElement) {+ parentDetails.open = true;+ }+ return target;+}diff --git a/web/lib/use-ime-composing.ts b/web/lib/use-ime-composing.tsnew file mode 100644index 000000000..27b205271--- /dev/null+++ b/web/lib/use-ime-composing.ts@@ -0,0 +1,28 @@+/**+ * Shared IME composition guard for chat textareas. While the user is+ * composing (e.g. picking CJK candidates), Enter confirms a candidate+ * rather than submitting — keydown handlers read ``isComposingRef.current``+ * (typically via ``shouldSubmitOnEnter``) to tell the two apart. Sharing+ * one hook keeps the deferred reset below from being "simplified" away+ * at individual call sites, which would break CJK input.+ */++import { useCallback, useRef } from "react";++export function useImeComposing() {+ const isComposingRef = useRef(false);++ const onCompositionStart = useCallback(() => {+ isComposingRef.current = true;+ }, []);++ const onCompositionEnd = useCallback(() => {+ // Some IMEs fire compositionend before the Enter keydown that confirms+ // a candidate, so keep the guard through the current event turn.+ setTimeout(() => {+ isComposingRef.current = false;+ }, 0);+ }, []);++ return { isComposingRef, onCompositionStart, onCompositionEnd };+}