Skip to content

Commit

Permalink
Resolve review
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-on committed Nov 1, 2024
1 parent af59afd commit 291fc67
Show file tree
Hide file tree
Showing 14 changed files with 76 additions and 105 deletions.
2 changes: 1 addition & 1 deletion drizzle/0005_create_template_table.sql
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
CREATE TABLE IF NOT EXISTS "template" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"name" text NOT NULL,
"data" jsonb NOT NULL,
"content" jsonb NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "template_name_unique" UNIQUE("name")
Expand Down
6 changes: 3 additions & 3 deletions drizzle/meta/0005_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"id": "c37a027e-8de9-43c6-b0c7-89771f04f432",
"id": "410315fb-45e8-44ba-91f2-deadeac035d6",
"prevId": "c810ceee-4769-451b-a42b-31afbe8d434b",
"version": "7",
"dialect": "postgresql",
Expand All @@ -21,8 +21,8 @@
"primaryKey": false,
"notNull": true
},
"data": {
"name": "data",
"content": {
"name": "content",
"type": "jsonb",
"primaryKey": false,
"notNull": true
Expand Down
2 changes: 1 addition & 1 deletion drizzle/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
{
"idx": 5,
"version": "7",
"when": 1730363062246,
"when": 1730443763982,
"tag": "0005_create_template_table",
"breakpoints": true
}
Expand Down
4 changes: 1 addition & 3 deletions src/components/chat-view/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@ const Chat = forwardRef<ChatRef, ChatProps>((props, ref) => {
const { settings } = useSettings()
const { ragEngine } = useRAG()

const chatContainerRef = useRef<HTMLDivElement>(null)

const {
createOrUpdateConversation,
deleteConversation,
Expand Down Expand Up @@ -467,7 +465,7 @@ const Chat = forwardRef<ChatRef, ChatProps>((props, ref) => {
}))

return (
<div className="smtcmp-chat-container" ref={chatContainerRef}>
<div className="smtcmp-chat-container">
<div className="smtcmp-chat-header">
<h1 className="smtcmp-chat-header-title">Chat</h1>
<div className="smtcmp-chat-header-buttons">
Expand Down
10 changes: 7 additions & 3 deletions src/components/chat-view/CreateTemplateDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,21 @@ export default function CreateTemplateDialogContent({
if (!editorRef.current) return
const serializedEditorState = editorRef.current.toJSON()
const nodes = serializedEditorState.editorState.root.children
if (nodes.length === 0) return
if (nodes.length === 0) {
new Notice('Please enter a content for your template')
return
}
if (templateName.trim().length === 0) {
new Notice('Please enter a name for your template')
return
}

await templateManager.createTemplate({
name: templateName,
data: { nodes },
content: { nodes },
})
new Notice(`Template created: ${templateName}`)
setTemplateName('')
onClose()
} catch (error) {
if (error instanceof DuplicateTemplateException) {
Expand Down Expand Up @@ -104,7 +108,7 @@ export default function CreateTemplateDialogContent({
initialEditorState={initialEditorState}
editorRef={editorRef}
contentEditableRef={contentEditableRef}
onSubmit={onSubmit}
onEnter={onSubmit}
/>
</div>

Expand Down
4 changes: 2 additions & 2 deletions src/components/chat-view/chat-input/ChatUserInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -260,12 +260,12 @@ const ChatUserInput = forwardRef<ChatUserInputRef, ChatUserInputProps>(
editorRef={editorRef}
contentEditableRef={contentEditableRef}
onChange={onChange}
onSubmit={() => handleSubmit({ useVaultSearch: false })}
onEnter={() => handleSubmit({ useVaultSearch: false })}
onFocus={onFocus}
onMentionNodeMutation={handleMentionNodeMutation}
autoFocus={autoFocus}
plugins={{
vaultChat: {
onEnter: {
onVaultChat: () => {
handleSubmit({ useVaultSearch: true })
},
Expand Down
34 changes: 10 additions & 24 deletions src/components/chat-view/chat-input/LexicalContentEditable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { RefObject, useCallback } from 'react'
import { useApp } from '../../../contexts/app-context'
import { fuzzySearch } from '../../../utils/fuzzy-search'

import OnVaultChatCommandPlugin from './on-vault-chat/OnVaultChatPlugin'
import AutoFocusPlugin from './plugins/auto-focus/AutoFocusPlugin'
import AutoLinkMentionPlugin from './plugins/mention/AutoLinkMentionPlugin'
import { MentionNode } from './plugins/mention/MentionNode'
Expand All @@ -32,13 +31,13 @@ export type LexicalContentEditableProps = {
editorRef: RefObject<LexicalEditor>
contentEditableRef: RefObject<HTMLDivElement>
onChange?: (content: SerializedEditorState) => void
onSubmit?: () => void
onEnter?: (evt: KeyboardEvent) => void
onFocus?: () => void
onMentionNodeMutation?: (mutations: NodeMutations<MentionNode>) => void
initialEditorState?: InitialEditorStateType
autoFocus?: boolean
plugins?: {
vaultChat?: {
onEnter?: {
onVaultChat: () => void
}
templatePopover?: {
Expand All @@ -51,7 +50,7 @@ export default function LexicalContentEditable({
editorRef,
contentEditableRef,
onChange,
onSubmit,
onEnter,
onFocus,
onMentionNodeMutation,
initialEditorState,
Expand All @@ -60,19 +59,11 @@ export default function LexicalContentEditable({
}: LexicalContentEditableProps) {
const app = useApp()

// // initialize editor state
// useEffect(() => {
// if (initialContent) {
// updaterRef.current?.update(initialContent)
// }
// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [])

const initialConfig: InitialConfigType = {
namespace: 'ChatUserInput',
theme: {
root: 'smtcmp-chat-input-root', // FIXME: change class name
paragraph: 'smtcmp-chat-input-paragraph',
root: 'smtcmp-lexical-content-editable-root',
paragraph: 'smtcmp-lexical-content-editable-paragraph',
},
nodes: [MentionNode],
editorState: initialEditorState,
Expand Down Expand Up @@ -117,17 +108,12 @@ export default function LexicalContentEditable({
onChange?.(editorState.toJSON())
}}
/>
{plugins?.vaultChat && (
// This plugin should be registered before OnEnterPlugin
<OnVaultChatCommandPlugin onVaultChat={plugins.vaultChat.onVaultChat} />
{onEnter && (
<OnEnterPlugin
onEnter={onEnter}
onVaultChat={plugins?.onEnter?.onVaultChat}
/>
)}
<OnEnterPlugin
onEnter={(evt) => {
evt.preventDefault()
evt.stopPropagation()
onSubmit?.()
}}
/>
<OnMutationPlugin
nodeClass={MentionNode}
onMutation={(mutations) => {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { COMMAND_PRIORITY_LOW, KEY_ENTER_COMMAND } from 'lexical'
import { Platform } from 'obsidian'
import { useEffect } from 'react'

export default function OnEnterPlugin({
onEnter,
onVaultChat,
}: {
onEnter: (evt: KeyboardEvent) => void
onVaultChat?: () => void
}) {
const [editor] = useLexicalComposerContext()

useEffect(() => {
const removeListener = editor.registerCommand(
KEY_ENTER_COMMAND,
(evt: KeyboardEvent) => {
if (
onVaultChat &&
evt.shiftKey &&
(Platform.isMacOS ? evt.metaKey : evt.ctrlKey)
) {
evt.preventDefault()
evt.stopPropagation()
onVaultChat()
return true
}
if (evt.shiftKey) {
return false
}
evt.preventDefault()
evt.stopPropagation()
onEnter(evt)
return true
},
Expand All @@ -25,7 +40,7 @@ export default function OnEnterPlugin({
return () => {
removeListener()
}
}, [editor, onEnter])
}, [editor, onEnter, onVaultChat])

return null
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { $generateJSONFromSelectedNodes } from '@lexical/clipboard'
import { BaseSerializedNode } from '@lexical/clipboard/clipboard'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import * as Dialog from '@radix-ui/react-dialog'
import { $getSelection } from 'lexical'
import {
$getSelection,
COMMAND_PRIORITY_LOW,
SELECTION_CHANGE_COMMAND,
} from 'lexical'
import { CSSProperties, useCallback, useEffect, useRef, useState } from 'react'

import CreateTemplateDialogContent from '../../../CreateTemplateDialog'
Expand All @@ -19,6 +23,9 @@ export default function CreateTemplatePopoverPlugin({
const [popoverStyle, setPopoverStyle] = useState<CSSProperties | null>(null)
const [isPopoverOpen, setIsPopoverOpen] = useState(false)
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [selectedSerializedNodes, setSelectedSerializedNodes] = useState<
BaseSerializedNode[] | null
>(null)

const popoverRef = useRef<HTMLButtonElement>(null)

Expand Down Expand Up @@ -64,24 +71,22 @@ export default function CreateTemplatePopoverPlugin({
left: finalLeft,
transform: 'translate(-100%, 0)',
})

const selectedNodes = getSelectedSerializedNodes()
if (!selectedNodes) {
setIsPopoverOpen(false)
return
}
setIsPopoverOpen(true)
}, [anchorElement, contentEditableElement, getSelectedSerializedNodes])
}, [anchorElement, contentEditableElement])

useEffect(() => {
const handleSelectionChange = () => {
updatePopoverPosition()
}
document.addEventListener('selectionchange', handleSelectionChange)
const removeSelectionChangeListener = editor.registerCommand(
SELECTION_CHANGE_COMMAND,
() => {
updatePopoverPosition()
return false
},
COMMAND_PRIORITY_LOW,
)
return () => {
document.removeEventListener('selectionchange', handleSelectionChange)
removeSelectionChangeListener()
}
}, [updatePopoverPosition])
}, [editor, updatePopoverPosition])

useEffect(() => {
if (!contentEditableElement) return
Expand All @@ -94,20 +99,17 @@ export default function CreateTemplatePopoverPlugin({
}
}, [contentEditableElement, updatePopoverPosition])

useEffect(() => {
const removeUpdateListener = editor.registerUpdateListener(() => {
updatePopoverPosition()
})
return () => {
removeUpdateListener()
}
}, [editor, updatePopoverPosition])

return (
<Dialog.Root
modal={false}
open={isDialogOpen}
onOpenChange={setIsDialogOpen}
onOpenChange={(open) => {
if (open) {
setSelectedSerializedNodes(getSelectedSerializedNodes())
}
setIsDialogOpen(open)
setIsPopoverOpen(false)
}}
>
<Dialog.Trigger asChild>
<button
Expand All @@ -122,7 +124,7 @@ export default function CreateTemplatePopoverPlugin({
</button>
</Dialog.Trigger>
<CreateTemplateDialogContent
selectedSerializedNodes={getSelectedSerializedNodes()}
selectedSerializedNodes={selectedSerializedNodes}
onClose={() => setIsDialogOpen(false)}
/>
</Dialog.Root>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export default function TemplatePlugin() {
closeMenu: () => void,
) => {
editor.update(() => {
const parsedNodes = selectedOption.template.data.nodes.map((node) =>
const parsedNodes = selectedOption.template.content.nodes.map((node) =>
$parseSerializedNode(node),
)
if (nodeToRemove) {
Expand Down
6 changes: 3 additions & 3 deletions src/database/migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@
},
{
"sql": [
"CREATE TABLE IF NOT EXISTS \"template\" (\n\t\"id\" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,\n\t\"name\" text NOT NULL,\n\t\"data\" jsonb NOT NULL,\n\t\"created_at\" timestamp DEFAULT now() NOT NULL,\n\t\"updated_at\" timestamp DEFAULT now() NOT NULL,\n\tCONSTRAINT \"template_name_unique\" UNIQUE(\"name\")\n);\n"
"CREATE TABLE IF NOT EXISTS \"template\" (\n\t\"id\" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,\n\t\"name\" text NOT NULL,\n\t\"content\" jsonb NOT NULL,\n\t\"created_at\" timestamp DEFAULT now() NOT NULL,\n\t\"updated_at\" timestamp DEFAULT now() NOT NULL,\n\tCONSTRAINT \"template_name_unique\" UNIQUE(\"name\")\n);\n"
],
"bps": true,
"folderMillis": 1730363062246,
"hash": "38448092dc2399d05f6be6c26472434a02d3fa548fcad6cf45a4a377ca8a0fb6"
"folderMillis": 1730443763982,
"hash": "eddf72b8d40619c170b3c12f3d3ce280385b1fc05717f211ab6077c6bea691bf"
}
]
4 changes: 2 additions & 2 deletions src/database/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ export const vectorTable3 = vectorTables[EMBEDDING_MODEL_OPTIONS[3].value]
export const vectorTable4 = vectorTables[EMBEDDING_MODEL_OPTIONS[4].value]

/* Template Table */
export type TemplateData = {
export type TemplateContent = {
nodes: SerializedLexicalNode[]
}

export const templateTable = pgTable('template', {
id: uuid('id').defaultRandom().primaryKey(),
name: text('name').notNull().unique(),
data: jsonb('data').notNull().$type<TemplateData>(),
content: jsonb('content').notNull().$type<TemplateContent>(),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at').defaultNow().notNull(),
})
Expand Down
Loading

0 comments on commit 291fc67

Please sign in to comment.