mirror of
https://github.com/EthanMarti/infio-copilot.git
synced 2026-05-08 16:10:09 +00:00
update template name -> command name
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { BaseSerializedNode } from '@lexical/clipboard/clipboard'
|
||||
import {
|
||||
InitialConfigType,
|
||||
InitialEditorStateType,
|
||||
@@ -26,8 +27,8 @@ import OnEnterPlugin from './plugins/on-enter/OnEnterPlugin'
|
||||
import OnMutationPlugin, {
|
||||
NodeMutations,
|
||||
} from './plugins/on-mutation/OnMutationPlugin'
|
||||
// import CreateTemplatePopoverPlugin from './plugins/template/CreateTemplatePopoverPlugin'
|
||||
// import TemplatePlugin from './plugins/template/TemplatePlugin'
|
||||
import CreateCommandPopoverPlugin from './plugins/command/CreateCommandPopoverPlugin'
|
||||
import CommandPlugin from './plugins/command/CommandPlugin'
|
||||
|
||||
export type LexicalContentEditableProps = {
|
||||
editorRef: RefObject<LexicalEditor>
|
||||
@@ -43,8 +44,9 @@ export type LexicalContentEditableProps = {
|
||||
onEnter?: {
|
||||
onVaultChat: () => void
|
||||
}
|
||||
templatePopover?: {
|
||||
commandPopover?: {
|
||||
anchorElement: HTMLElement | null
|
||||
onCreateCommand: (nodes: BaseSerializedNode[]) => void
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,13 +143,14 @@ export default function LexicalContentEditable({
|
||||
<AutoLinkMentionPlugin />
|
||||
<ImagePastePlugin onCreateImageMentionables={onCreateImageMentionables} />
|
||||
<DragDropPaste onCreateImageMentionables={onCreateImageMentionables} />
|
||||
{/* <TemplatePlugin /> */}
|
||||
{/* {plugins?.templatePopover && (
|
||||
<CreateTemplatePopoverPlugin
|
||||
anchorElement={plugins.templatePopover.anchorElement}
|
||||
<CommandPlugin />
|
||||
{plugins?.commandPopover && (
|
||||
<CreateCommandPopoverPlugin
|
||||
anchorElement={plugins.commandPopover.anchorElement}
|
||||
contentEditableElement={contentEditableRef.current}
|
||||
onCreateCommand={plugins.commandPopover.onCreateCommand}
|
||||
/>
|
||||
)} */}
|
||||
)}
|
||||
</LexicalComposer>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { BaseSerializedNode } from '@lexical/clipboard/clipboard'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { $nodesOfType, LexicalEditor, SerializedEditorState } from 'lexical'
|
||||
import {
|
||||
@@ -30,7 +31,7 @@ import { ImageUploadButton } from './ImageUploadButton'
|
||||
import LexicalContentEditable from './LexicalContentEditable'
|
||||
import MentionableBadge from './MentionableBadge'
|
||||
import { ModelSelect } from './ModelSelect'
|
||||
import { ModeSelect } from './ModeSelect'
|
||||
// import { ModeSelect } from './ModeSelect'
|
||||
import { MentionNode } from './plugins/mention/MentionNode'
|
||||
import { NodeMutations } from './plugins/on-mutation/OnMutationPlugin'
|
||||
import { SubmitButton } from './SubmitButton'
|
||||
@@ -44,6 +45,7 @@ export type ChatUserInputProps = {
|
||||
onChange?: (content: SerializedEditorState) => void
|
||||
onSubmit: (content: SerializedEditorState, useVaultSearch?: boolean) => void
|
||||
onFocus: () => void
|
||||
onCreateCommand: (nodes: BaseSerializedNode[]) => void
|
||||
mentionables: Mentionable[]
|
||||
setMentionables: (mentionables: Mentionable[]) => void
|
||||
autoFocus?: boolean
|
||||
@@ -57,6 +59,7 @@ const PromptInputWithActions = forwardRef<ChatUserInputRef, ChatUserInputProps>(
|
||||
onChange,
|
||||
onSubmit,
|
||||
onFocus,
|
||||
onCreateCommand,
|
||||
mentionables,
|
||||
setMentionables,
|
||||
autoFocus = false,
|
||||
@@ -266,6 +269,10 @@ const PromptInputWithActions = forwardRef<ChatUserInputRef, ChatUserInputProps>(
|
||||
handleSubmit({ useVaultSearch: true })
|
||||
},
|
||||
},
|
||||
commandPopover: {
|
||||
anchorElement: containerRef.current,
|
||||
onCreateCommand: onCreateCommand,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
|
||||
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
$parseSerializedNode,
|
||||
COMMAND_PRIORITY_NORMAL, SerializedLexicalNode, TextNode
|
||||
} from 'lexical'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
|
||||
import { lexicalNodeToPlainText } from '../../../../../components/chat-view/chat-input/utils/editor-state-to-plain-text'
|
||||
import { useDatabase } from '../../../../../contexts/DatabaseContext'
|
||||
import { DBManager } from '../../../../../database/database-manager'
|
||||
import { MenuOption } from '../shared/LexicalMenu'
|
||||
import {
|
||||
LexicalTypeaheadMenuPlugin,
|
||||
useBasicTypeaheadTriggerMatch,
|
||||
} from '../typeahead-menu/LexicalTypeaheadMenuPlugin'
|
||||
|
||||
|
||||
export type Command = {
|
||||
id: string
|
||||
name: string
|
||||
content: { nodes: SerializedLexicalNode[] }
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
|
||||
class CommandTypeaheadOption extends MenuOption {
|
||||
name: string
|
||||
command: Command
|
||||
|
||||
constructor(name: string, command: Command) {
|
||||
super(name)
|
||||
this.name = name
|
||||
this.command = command
|
||||
}
|
||||
}
|
||||
|
||||
function CommandMenuItem({
|
||||
index,
|
||||
isSelected,
|
||||
onClick,
|
||||
onMouseEnter,
|
||||
option,
|
||||
}: {
|
||||
index: number
|
||||
isSelected: boolean
|
||||
onClick: () => void
|
||||
onMouseEnter: () => void
|
||||
option: CommandTypeaheadOption
|
||||
}) {
|
||||
return (
|
||||
<li
|
||||
key={option.key}
|
||||
tabIndex={-1}
|
||||
className={clsx('item', isSelected && 'selected')}
|
||||
ref={(el) => option.setRefElement(el)}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
id={`typeahead-item-${index}`}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onClick={onClick}
|
||||
>
|
||||
<div className="smtcmp-template-menu-item">
|
||||
<div className="text">{option.name}</div>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
export default function CommandPlugin() {
|
||||
const [editor] = useLexicalComposerContext()
|
||||
const [commands, setCommands] = useState<Command[]>([])
|
||||
|
||||
const { getDatabaseManager } = useDatabase()
|
||||
const getManager = useCallback(async (): Promise<DBManager> => {
|
||||
return await getDatabaseManager()
|
||||
}, [getDatabaseManager])
|
||||
|
||||
const fetchCommands = useCallback(async () => {
|
||||
const dbManager = await getManager()
|
||||
dbManager.getCommandManager().getAllCommands((rows) => {
|
||||
setCommands(rows.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
content: row.content,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
})))
|
||||
})
|
||||
}, [getManager])
|
||||
|
||||
useEffect(() => {
|
||||
void fetchCommands()
|
||||
}, [fetchCommands])
|
||||
|
||||
const [queryString, setQueryString] = useState<string | null>(null)
|
||||
const [searchResults, setSearchResults] = useState<Command[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
if (queryString == null) return
|
||||
const filteredCommands = commands.filter(
|
||||
command =>
|
||||
command.name.toLowerCase().includes(queryString.toLowerCase()) ||
|
||||
command.content.nodes.map(lexicalNodeToPlainText).join('').toLowerCase().includes(queryString.toLowerCase())
|
||||
)
|
||||
setSearchResults(filteredCommands)
|
||||
}, [queryString, commands])
|
||||
|
||||
const options = useMemo(
|
||||
() =>
|
||||
searchResults.map(
|
||||
(result) => new CommandTypeaheadOption(result.name, result),
|
||||
),
|
||||
[searchResults],
|
||||
)
|
||||
|
||||
const checkForTriggerMatch = useBasicTypeaheadTriggerMatch('/', {
|
||||
minLength: 0,
|
||||
})
|
||||
|
||||
const onSelectOption = useCallback(
|
||||
(
|
||||
selectedOption: CommandTypeaheadOption,
|
||||
nodeToRemove: TextNode | null,
|
||||
closeMenu: () => void,
|
||||
) => {
|
||||
editor.update(() => {
|
||||
const parsedNodes = selectedOption.command.content.nodes.map((node) =>
|
||||
$parseSerializedNode(node),
|
||||
)
|
||||
if (nodeToRemove) {
|
||||
const parent = nodeToRemove.getParentOrThrow()
|
||||
parent.splice(nodeToRemove.getIndexWithinParent(), 1, parsedNodes)
|
||||
const lastNode = parsedNodes[parsedNodes.length - 1]
|
||||
lastNode.selectEnd()
|
||||
}
|
||||
closeMenu()
|
||||
})
|
||||
},
|
||||
[editor],
|
||||
)
|
||||
|
||||
return (
|
||||
<LexicalTypeaheadMenuPlugin<CommandTypeaheadOption>
|
||||
onQueryChange={setQueryString}
|
||||
onSelectOption={onSelectOption}
|
||||
triggerFn={checkForTriggerMatch}
|
||||
options={options}
|
||||
commandPriority={COMMAND_PRIORITY_NORMAL}
|
||||
menuRenderFn={(
|
||||
anchorElementRef,
|
||||
{ selectedIndex, selectOptionAndCleanUp, setHighlightedIndex },
|
||||
) =>
|
||||
anchorElementRef.current && searchResults.length
|
||||
? createPortal(
|
||||
<div
|
||||
className="smtcmp-popover"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
}}
|
||||
>
|
||||
<ul>
|
||||
{options.map((option, i: number) => (
|
||||
<CommandMenuItem
|
||||
index={i}
|
||||
isSelected={selectedIndex === i}
|
||||
onClick={() => {
|
||||
setHighlightedIndex(i)
|
||||
selectOptionAndCleanUp(option)
|
||||
}}
|
||||
onMouseEnter={() => {
|
||||
setHighlightedIndex(i)
|
||||
}}
|
||||
key={option.key}
|
||||
option={option}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</div>,
|
||||
anchorElementRef.current,
|
||||
)
|
||||
: null
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { $generateJSONFromSelectedNodes } from '@lexical/clipboard'
|
||||
import { BaseSerializedNode } from '@lexical/clipboard/clipboard'
|
||||
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
|
||||
import {
|
||||
$getSelection,
|
||||
COMMAND_PRIORITY_LOW,
|
||||
SELECTION_CHANGE_COMMAND,
|
||||
} from 'lexical'
|
||||
import { CSSProperties, useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
export default function CreateCommandPopoverPlugin({
|
||||
anchorElement,
|
||||
contentEditableElement,
|
||||
onCreateCommand,
|
||||
}: {
|
||||
anchorElement: HTMLElement | null
|
||||
contentEditableElement: HTMLElement | null
|
||||
onCreateCommand: (nodes: BaseSerializedNode[]) => void
|
||||
}): JSX.Element | null {
|
||||
const [editor] = useLexicalComposerContext()
|
||||
|
||||
const [popoverStyle, setPopoverStyle] = useState<CSSProperties | null>(null)
|
||||
const [isPopoverOpen, setIsPopoverOpen] = useState(false)
|
||||
|
||||
const popoverRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
const getSelectedSerializedNodes = useCallback(():
|
||||
| BaseSerializedNode[]
|
||||
| null => {
|
||||
if (!editor) return null
|
||||
let selectedNodes: BaseSerializedNode[] | null = null
|
||||
editor.update(() => {
|
||||
const selection = $getSelection()
|
||||
if (!selection) return
|
||||
selectedNodes = $generateJSONFromSelectedNodes(editor, selection).nodes
|
||||
if (selectedNodes.length === 0) return null
|
||||
})
|
||||
return selectedNodes
|
||||
}, [editor])
|
||||
|
||||
const updatePopoverPosition = useCallback(() => {
|
||||
if (!anchorElement || !contentEditableElement) return
|
||||
const nativeSelection = document.getSelection()
|
||||
const range = nativeSelection?.getRangeAt(0)
|
||||
if (!range || range.collapsed) {
|
||||
setIsPopoverOpen(false)
|
||||
return
|
||||
}
|
||||
if (!contentEditableElement.contains(range.commonAncestorContainer)) {
|
||||
setIsPopoverOpen(false)
|
||||
return
|
||||
}
|
||||
const rects = Array.from(range.getClientRects())
|
||||
if (rects.length === 0) {
|
||||
setIsPopoverOpen(false)
|
||||
return
|
||||
}
|
||||
const anchorRect = anchorElement.getBoundingClientRect()
|
||||
const idealLeft = rects[rects.length - 1].right - anchorRect.left
|
||||
const paddingX = 8
|
||||
const paddingY = 4
|
||||
const minLeft = (popoverRef.current?.offsetWidth ?? 0) + paddingX
|
||||
const finalLeft = Math.max(minLeft, idealLeft)
|
||||
setPopoverStyle({
|
||||
top: rects[rects.length - 1].bottom - anchorRect.top + paddingY,
|
||||
left: finalLeft,
|
||||
transform: 'translate(-100%, 0)',
|
||||
})
|
||||
setIsPopoverOpen(true)
|
||||
}, [anchorElement, contentEditableElement])
|
||||
|
||||
useEffect(() => {
|
||||
const removeSelectionChangeListener = editor.registerCommand(
|
||||
SELECTION_CHANGE_COMMAND,
|
||||
() => {
|
||||
updatePopoverPosition()
|
||||
return false
|
||||
},
|
||||
COMMAND_PRIORITY_LOW,
|
||||
)
|
||||
return () => {
|
||||
removeSelectionChangeListener()
|
||||
}
|
||||
}, [editor, updatePopoverPosition])
|
||||
|
||||
useEffect(() => {
|
||||
// Update popover position when the content is cleared
|
||||
// (Selection change event doesn't fire in this case)
|
||||
if (!isPopoverOpen) return
|
||||
const removeTextContentChangeListener = editor.registerTextContentListener(
|
||||
() => {
|
||||
updatePopoverPosition()
|
||||
},
|
||||
)
|
||||
return () => {
|
||||
removeTextContentChangeListener()
|
||||
}
|
||||
}, [editor, isPopoverOpen, updatePopoverPosition])
|
||||
|
||||
useEffect(() => {
|
||||
if (!contentEditableElement) return
|
||||
const handleScroll = () => {
|
||||
updatePopoverPosition()
|
||||
}
|
||||
contentEditableElement.addEventListener('scroll', handleScroll)
|
||||
return () => {
|
||||
contentEditableElement.removeEventListener('scroll', handleScroll)
|
||||
}
|
||||
}, [contentEditableElement, updatePopoverPosition])
|
||||
|
||||
return (
|
||||
<button
|
||||
ref={popoverRef}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
visibility: isPopoverOpen ? 'visible' : 'hidden',
|
||||
...popoverStyle,
|
||||
}}
|
||||
onClick={() => {
|
||||
onCreateCommand(getSelectedSerializedNodes() ?? [])
|
||||
setIsPopoverOpen(false)
|
||||
}}
|
||||
>
|
||||
create command
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -6,7 +6,7 @@ export function editorStateToPlainText(
|
||||
return lexicalNodeToPlainText(editorState.root)
|
||||
}
|
||||
|
||||
function lexicalNodeToPlainText(node: SerializedLexicalNode): string {
|
||||
export function lexicalNodeToPlainText(node: SerializedLexicalNode): string {
|
||||
if ('children' in node) {
|
||||
// Process children recursively and join their results
|
||||
return (node.children as SerializedLexicalNode[])
|
||||
|
||||
Reference in New Issue
Block a user