Faisal Amir 852ea84cd8
epic: Jan with new UI/UX (#4964)
* chore: initial new FE setup

* chore: update namespace text-left-panel foreground variable

* chore: enable dynamic mainview color

* chore: remove greetings new chat

* chore: fix chat input style

* chore: simplify hook useAppearance

* chore: enable internationalization

* chore: prepare vn locale

* chore: keyboardshortcut layout

* chore: update keyboard shortcut exclude pathname

* chore: update state active setting route

* chore: fix update theme by system

* chore: handle dynamic primary color

* chore: fix left panel navigation active state and styled item privacy analytic

* chore: reorder general setting being a first

* chore: add function reset appearance

* chore: update scrollbar

* chore: update delete thread with dialog confirmation

* chore: update state dialog inside dropdown menu

* chore: wip thread detail or chat page

* chore: wip model dropdown

* chore: prepare model dropdown select

* chore: update model providers setting

* chore: show provider on model dropdown based isActive toogle

* chore: update layout model provider

* chore: update state active on storage

* chore: update gap of item dropdown model

* chore: update select model base on id

* chore: update edit model capabilities

* chore: add dialog to add model

* chore: update sheet for model setting

* chore: add sheet setting each model

* chore: make dynamic syntax highlight

* chore: fix menu setting appearance theme

* chore: markdown render support emoji

* chore: markdown support latex

* chore: change codeblock default theme

* chore: update ui codeblock

* chore: custom render link taget new window

* chore: fix copy button codeblock

* chore: update accent and desctructive color

* chore: setup user chat message

* chore: prepare some page settings

* chore: simple list extension and prepare mcp, local api, and hardware

* chore: mcp-serve

* chore: MCP server UI

* chore: update local api server config

* chore: adjust chat input

* chore: update local api server log

* chore: prepare hub page

* chore: remove help page

* chore: update mock

* chore: prepare http proxy setting UI

* chore: adjust local api server and title every action

* fix: chore FE package (#4962)

* fix: update command which referred to non-existent web app

* fix: added commented out macos platform for now

* fix: remove the platform name as macos

* fix: remove unnecessary line for platform name in HeaderPage component

* fix: update dev script to specify port 3000 for Vite

* feat: model providers and chat completion

* enhancement: threads performance

* fix: thread content update

* chore: clean up threads

* fix: performance issue with streaming and state loop

* fix: streaming

* fix: react markdow

* feat: extension manager

* chore: add nodePolyfills include path

* chore: improve performance avoid unhandle rejection

* chore: update pre margin bottom

* chore: swith thread should be deafult scroll to bottom

* chore: wip scroll to bottom

* chore: add model loader

* chore: add platform utils

* feat: threads functionality

* chore: setup toaster

* chore: persist threads deletion

* fix: create thread with new message

* chore: create new thread should change route path

* chore: navigate after delet dialog thread

* chore: thread favorites and orders

* chore: dismiss deleting modal on delete

* chore: remove undefined properties

* chore: remove deprecated run step

* chore: fix delete thread

* chore: create empty thread content on started streaming

* chore: correct messages store key

* chore: stuck at generating state

* chore: preapre chat toolbar

* chore: introduce in-memory app state

* chore: update extensions migration logic

* chore: remove redundant extensions migration gate

* chore: message toolbar user and assistant

* chore: add logo gemini

* feat: remote providers with model capabilities

* chore: maintain provider settings

* chore: move speed token into chat input

* chore: temp harcoded model loader

* chore: make chat text selectable and truncate model list

* chore: update shortcut UI

* Feat/implement threads (#4977)

* chore: add fuse.js library for enhanced search functionality

* feat: implement thread filtering with Fuse.js for improved search capabilities

* fix: update the fuseOptions

* feat: add search functionality to LeftPanel and refactor thread retrieval logic

* refactor: optimize thread filtering and improve search functionality in LeftPanel

* fix: more edits

* refactor: remove duplicate import of useAppState in StreamingContent component

* chore: update navigate after delete all thread

* chore: pass prop speedToken from new chat input

* chore: persist provider general settings

* chore: styling search left panel

* chore: cleanup margin

* chore: update size icon

* chore: improve chat input

* chore: imprve list markdown

* chore: animate border

* feat: local model provider work

* chore: persist manually added model

* chore: prepare download management ui and show version on general setting

* chore: improve pre tag

* chore: remove buton install extension and improve light theme download

* chore: add missing hardware information handler

* chore: cleanup small ui

* chore: update default provider settings

* fix: missing fs commands

* chore: correct provider models

* chore: prepare delete model

* chore: handle thinking block

* chore: fix conditional message toolbar

* chore: pophover download select none

* enhancement: add prune mode

* chore: model settings

* chore: bump engine version tauri

* chore: update style thinking

* chore: add indicator and toogle mcp server

* chore: wip hub

* chore: update model settings

* chore: mvp hub

* chore: add function rename title

* chore: update function delete message

* chore: update rename title

* chore: update model settings

* chore: persist MCP configs

* refactor: clean up utils

* chore: add tools to completion request

* chore: clean up

* chore: ignore assets

---------

Co-authored-by: Ivan Leo <ivanleomk@gmail.com>
Co-authored-by: Louis <louis@jan.ai>
2025-05-15 19:38:59 +07:00

409 lines
12 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
import {
useCallback,
useEffect,
useMemo,
useRef,
ClipboardEvent,
useContext,
} from 'react'
import { MessageStatus } from '@janhq/core'
import { useAtom, useAtomValue } from 'jotai'
import { BaseEditor, createEditor, Editor, Range, Transforms } from 'slate'
import { withHistory } from 'slate-history' // Import withHistory
import {
Editable,
ReactEditor,
Slate,
withReact,
RenderLeafProps,
} from 'slate-react'
import { twMerge } from 'tailwind-merge'
import { currentPromptAtom } from '@/containers/Providers/Jotai'
import { useActiveModel } from '@/hooks/useActiveModel'
import useSendChatMessage from '@/hooks/useSendChatMessage'
import { ChatContext } from '../../ThreadCenterPanel'
import { ChatContext } from '../../ThreadCenterPanel'
import { getCurrentChatMessagesAtom } from '@/helpers/atoms/ChatMessage.atom'
import { selectedModelAtom } from '@/helpers/atoms/Model.atom'
import {
getActiveThreadIdAtom,
activeSettingInputBoxAtom,
} from '@/helpers/atoms/Thread.atom'
type CustomElement = {
type: 'paragraph' | 'code' | null
children: CustomText[]
language?: string // Store the language for code blocks
}
type CustomText = {
text: string
code?: boolean
language?: string
className?: string
type?: 'paragraph' | 'code' // Add the type property
format?: 'bold' | 'italic'
}
declare module 'slate' {
interface CustomTypes {
Editor: BaseEditor & ReactEditor
Element: CustomElement
Text: CustomText
}
}
const initialValue: CustomElement[] = [
{
type: 'paragraph',
children: [{ text: '' }],
},
]
type RichTextEditorProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
const RichTextEditor = ({
className,
style,
disabled,
placeholder,
spellCheck,
}: RichTextEditorProps) => {
const editor = useMemo(() => withHistory(withReact(createEditor())), [])
const currentLanguage = useRef<string>('plaintext')
const hasStartBackticks = useRef<boolean>(false)
const hasEndBackticks = useRef<boolean>(false)
const [currentPrompt, setCurrentPrompt] = useAtom(currentPromptAtom)
const textareaRef = useRef<HTMLDivElement>(null)
const activeThreadId = useAtomValue(getActiveThreadIdAtom)
const activeSettingInputBox = useAtomValue(activeSettingInputBoxAtom)
const messages = useAtomValue(getCurrentChatMessagesAtom)
const { showApprovalModal } = useContext(ChatContext)
const { sendChatMessage } = useSendChatMessage(showApprovalModal)
const { stopInference } = useActiveModel()
const selectedModel = useAtomValue(selectedModelAtom)
const largeContentThreshold = 1000
// The decorate function identifies code blocks and marks the ranges
const decorate = useCallback(
(entry: [any, any]) => {
const ranges: any[] = []
const [node, path] = entry
if (Editor.isBlock(editor, node) && node.type === 'paragraph') {
node.children.forEach((child: { text: any }, childIndex: number) => {
const text = child.text
// Match bold text pattern *text*
const boldMatches = [...text.matchAll(/(\*.*?\*)/g)] // Find bold patterns
boldMatches.forEach((match) => {
const startOffset = match.index + 1 || 0
const length = match[0].length - 2
ranges.push({
anchor: { path: [...path, childIndex], offset: startOffset },
focus: {
path: [...path, childIndex],
offset: startOffset + length,
},
format: 'italic',
className: 'italic',
})
})
})
}
if (Editor.isBlock(editor, node) && node.type === 'paragraph') {
node.children.forEach((child: { text: any }, childIndex: number) => {
const text = child.text
// Match bold text pattern **text**
const boldMatches = [...text.matchAll(/(\*\*.*?\*\*)/g)] // Find bold patterns
boldMatches.forEach((match) => {
const startOffset = match.index + 2 || 0
const length = match[0].length - 4
ranges.push({
anchor: { path: [...path, childIndex], offset: startOffset },
focus: {
path: [...path, childIndex],
offset: startOffset + length,
},
format: 'bold',
className: 'font-bold',
})
})
})
}
return ranges
},
[editor]
)
// RenderLeaf applies the decoration styles
const renderLeaf = useCallback(
({ attributes, children, leaf }: RenderLeafProps) => {
if (leaf.format === 'italic') {
return (
<i className={leaf.className} {...attributes}>
{children}
</i>
)
}
if (leaf.format === 'bold') {
return (
<strong className={leaf.className} {...attributes}>
{children}
</strong>
)
}
if (leaf.code) {
// Apply syntax highlighting to code blocks
return (
<code className={leaf.className} {...attributes}>
{children}
</code>
)
}
return <span {...attributes}>{children}</span>
},
[]
)
useEffect(() => {
if (!ReactEditor.isFocused(editor)) {
ReactEditor.focus(editor)
}
if (textareaRef.current) {
textareaRef.current.focus()
}
}, [activeThreadId, editor])
useEffect(() => {
if (textareaRef.current?.clientHeight) {
textareaRef.current.style.height = activeSettingInputBox
? '100px'
: '40px'
textareaRef.current.style.height =
textareaRef.current.scrollHeight + 2 + 'px'
textareaRef.current.style.overflow =
textareaRef.current.clientHeight >= 390 ? 'auto' : 'hidden'
}
if (currentPrompt.length === 0) {
resetEditor()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [textareaRef.current?.clientHeight, currentPrompt, activeSettingInputBox])
const onStopInferenceClick = async () => {
stopInference()
}
const resetEditor = useCallback(() => {
Transforms.delete(editor, {
at: {
anchor: Editor.start(editor, []),
focus: Editor.end(editor, []),
},
})
// Adjust the height of the textarea to its initial state
if (textareaRef.current) {
textareaRef.current.style.height = activeSettingInputBox
? '100px'
: '44px'
textareaRef.current.style.overflow = 'hidden' // Reset overflow style
}
// Ensure the editor re-renders decorations
editor.onChange()
}, [activeSettingInputBox, editor])
const handleKeyDown = useCallback(
(event: React.KeyboardEvent) => {
if (
event.key === 'Enter' &&
!event.shiftKey &&
event.nativeEvent.isComposing === false
) {
event.preventDefault()
if (messages[messages.length - 1]?.status !== MessageStatus.Pending) {
sendChatMessage(currentPrompt)
if (selectedModel) {
resetEditor()
}
} else onStopInferenceClick()
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[currentPrompt, editor, messages]
)
const handlePaste = (event: ClipboardEvent<HTMLDivElement>) => {
const clipboardData = event.clipboardData || (window as any).clipboardData
const pastedData = clipboardData.getData('text')
if (pastedData.length > largeContentThreshold) {
event.preventDefault() // Prevent the default paste behavior
Transforms.insertText(editor, pastedData) // Insert the content directly into the editor
}
}
return (
<Slate
editor={editor}
initialValue={initialValue}
onChange={(value) => {
const combinedText = value
.map((block) => {
if ('children' in block) {
return block.children.map((child) => child.text).join('')
}
return ''
})
.join('\n')
setCurrentPrompt(combinedText)
if (combinedText.trim() === '') {
currentLanguage.current = 'plaintext'
}
const hasCodeBlockStart = combinedText.match(/^```(\w*)/m)
const hasCodeBlockEnd = combinedText.match(/^```$/m)
// Set language to plaintext if no code block with language identifier is found
if (!hasCodeBlockStart) {
currentLanguage.current = 'plaintext'
hasStartBackticks.current = false
} else {
hasStartBackticks.current = true
}
if (!hasCodeBlockEnd) {
currentLanguage.current = 'plaintext'
hasEndBackticks.current = false
} else {
hasEndBackticks.current = true
}
}}
>
<Editable
ref={textareaRef}
decorate={(entry) => {
// Skip decorate if content exceeds threshold
if (
currentPrompt.length > largeContentThreshold ||
!currentPrompt.length
)
return []
return decorate(entry)
}}
renderLeaf={renderLeaf} // Pass the renderLeaf function
scrollSelectionIntoView={scrollSelectionIntoView}
onKeyDown={handleKeyDown}
onPaste={handlePaste} // Add the custom paste handler
className={twMerge(
className,
disabled &&
'cursor-not-allowed border-none bg-[hsla(var(--disabled-bg))] text-[hsla(var(--disabled-fg))]'
)}
placeholder={placeholder}
style={style}
disabled={disabled}
readOnly={disabled}
spellCheck={spellCheck}
/>
</Slate>
)
function scrollSelectionIntoView(
editor: ReactEditor,
domRange: globalThis.Range
) {
// This was affecting the selection of multiple blocks and dragging behavior,
// so enabled only if the selection has been collapsed.
if (editor.selection && Range.isExpanded(editor.selection)) return
const minTop = 80 // sticky header height
const leafEl = domRange.startContainer.parentElement
const scrollParent = getScrollParent(leafEl)
// Check if browser supports getBoundingClientRect
if (typeof domRange.getBoundingClientRect !== 'function') return
const { top: elementTop, height: elementHeight } =
domRange.getBoundingClientRect()
const { height: parentHeight } = scrollParent.getBoundingClientRect()
const isChildAboveViewport = elementTop < minTop
const isChildBelowViewport = elementTop + elementHeight > parentHeight
if (isChildAboveViewport && isChildBelowViewport) {
// Child spans through all visible area which means it's already in view.
return
}
if (isChildAboveViewport) {
const y = scrollParent.scrollTop + elementTop - minTop
scrollParent.scroll({ left: scrollParent.scrollLeft, top: y })
return
}
if (isChildBelowViewport) {
const y = Math.min(
scrollParent.scrollTop + elementTop - minTop,
scrollParent.scrollTop + elementTop + elementHeight - parentHeight
)
scrollParent.scroll({ left: scrollParent.scrollLeft, top: y })
}
}
function getScrollParent(element: any) {
const elementStyle = window.getComputedStyle(element)
const excludeStaticParent = elementStyle.position === 'absolute'
if (elementStyle.position === 'fixed') {
return document.body
}
let parent = element
while (parent) {
const parentStyle = window.getComputedStyle(parent)
if (parentStyle.position !== 'static' || !excludeStaticParent) {
const overflowAttributes = [
parentStyle.overflow,
parentStyle.overflowY,
parentStyle.overflowX,
]
if (
overflowAttributes.includes('auto') ||
overflowAttributes.includes('hidden')
) {
return parent
}
}
parent = parent.parentElement
}
return document.documentElement
}
}
export default RichTextEditor