diff --git a/app/components/CreateGraph.tsx b/app/components/CreateGraph.tsx index 5afe9ac9..bb54f3d9 100644 --- a/app/components/CreateGraph.tsx +++ b/app/components/CreateGraph.tsx @@ -39,7 +39,8 @@ export default function CreateGraph({ const handleCreateGraph = async (e: React.FormEvent) => { e.preventDefault() - if (!graphName) { + const name = graphName.trim() + if (!name) { toast({ title: "Error", description: "Graph name cannot be empty", @@ -48,13 +49,13 @@ export default function CreateGraph({ return } const q = 'RETURN 1' - const result = await securedFetch(`api/graph/${prepareArg(graphName)}/?query=${prepareArg(q)}`, { + const result = await securedFetch(`api/graph/${prepareArg(name)}/?query=${prepareArg(q)}`, { method: "GET", }, session?.user?.role, toast) if (!result.ok) return - onSetGraphName(graphName) + onSetGraphName(name) setGraphName("") setOpen(false) toast({ diff --git a/app/components/EditorComponent.tsx b/app/components/EditorComponent.tsx index fb5cec1c..12423b7b 100644 --- a/app/components/EditorComponent.tsx +++ b/app/components/EditorComponent.tsx @@ -3,33 +3,27 @@ "use client"; -import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog"; +import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { Editor, Monaco } from "@monaco-editor/react" import { useEffect, useRef, useState } from "react" import * as monaco from "monaco-editor"; -import { prepareArg, securedFetch } from "@/lib/utils"; import { Maximize2 } from "lucide-react"; import { useToast } from "@/components/ui/use-toast"; import { useSession } from "next-auth/react"; +import { prepareArg, securedFetch } from "@/lib/utils"; +import { Session } from "next-auth"; +import { VisuallyHidden } from "@radix-ui/react-visually-hidden"; import { Graph } from "../api/graph/model"; import Button from "./ui/Button"; -type Suggestions = { - keywords: monaco.languages.CompletionItem[], - labels: monaco.languages.CompletionItem[], - relationshipTypes: monaco.languages.CompletionItem[], - propertyKeys: monaco.languages.CompletionItem[], - functions: monaco.languages.CompletionItem[] -} - interface Props { currentQuery: string historyQueries: string[] + setHistoryQueries: (queries: string[]) => void setCurrentQuery: (query: string) => void maximize: boolean runQuery: (query: string) => void graph: Graph - isCollapsed: boolean } const monacoOptions: monaco.editor.IStandaloneEditorConstructionOptions = { @@ -183,53 +177,79 @@ const FUNCTIONS = [ "vec.cosineDistance", ] -const MAX_HEIGHT = 20 -const LINE_HEIGHT = 38 - -const getEmptySuggestions = (): Suggestions => ({ - keywords: KEYWORDS.map(key => ({ +const SUGGESTIONS: monaco.languages.CompletionItem[] = [ + ...KEYWORDS.map(key => ({ insertText: key, label: key, kind: monaco.languages.CompletionItemKind.Keyword, range: new monaco.Range(1, 1, 1, 1), detail: "(keyword)" })), - labels: [], - relationshipTypes: [], - propertyKeys: [], - functions: [] -}) + ...FUNCTIONS.map(f => ({ + insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, + insertText: `${f}(\${0})`, + label: `${f}()`, + kind: monaco.languages.CompletionItemKind.Function, + range: new monaco.Range(1, 1, 1, 1), + detail: "(function)" + })) +] + +const MAX_HEIGHT = 20 +const LINE_HEIGHT = 38 const PLACEHOLDER = "Type your query here to start" -export default function EditorComponent({ currentQuery, historyQueries, setCurrentQuery, maximize, runQuery, graph, isCollapsed }: Props) { +export default function EditorComponent({ currentQuery, historyQueries, setHistoryQueries, setCurrentQuery, maximize, runQuery, graph }: Props) { const [query, setQuery] = useState(currentQuery) const placeholderRef = useRef(null) - const [monacoInstance, setMonacoInstance] = useState() - const [prevGraphName, setPrevGraphName] = useState("") - const [sugProvider, setSugProvider] = useState() - const [suggestions, setSuggestions] = useState(getEmptySuggestions()) - const [lineNumber, setLineNumber] = useState(0) + const [lineNumber, setLineNumber] = useState(1) + const graphIdRef = useRef(graph.Id) + const [blur, setBlur] = useState(false) + const [sugDisposed, setSugDisposed] = useState() + const { toast } = useToast() const submitQuery = useRef(null) const editorRef = useRef(null) - const [blur, setBlur] = useState(false) + const containerRef = useRef(null) const historyRef = useRef({ historyQueries, currentQuery, - historyCounter: historyQueries.length + historyCounter: 0 }) - const { toast } = useToast() const { data: session } = useSession() + + useEffect(() => { + graphIdRef.current = graph.Id + }, [graph.Id]) + + useEffect(() => () => { + sugDisposed?.dispose() + }, [sugDisposed]) + useEffect(() => { historyRef.current.historyQueries = historyQueries }, [historyQueries, currentQuery]) useEffect(() => { - if (!editorRef.current) return - editorRef.current.layout(); - }, [isCollapsed]) + if (!containerRef.current) return + + const handleResize = () => { + editorRef.current?.layout() + } + + window.addEventListener("resize", handleResize) + + const observer = new ResizeObserver(handleResize) + + observer.observe(containerRef.current) + + return () => { + window.removeEventListener("resize", handleResize) + observer.disconnect() + } + }, [containerRef.current]) useEffect(() => { setQuery(currentQuery) @@ -256,136 +276,77 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre 'editorSuggestWidget.hoverBackground': '#28283F', }, }); - } - - const addSuggestions = (MonacoI: Monaco, sug?: monaco.languages.CompletionItem[], procedures?: monaco.languages.CompletionItem[]) => { - - sugProvider?.dispose() - const provider = MonacoI.languages.registerCompletionItemProvider('custom-language', { - triggerCharacters: ["."], - provideCompletionItems: (model, position) => { - const word = model.getWordUntilPosition(position) - const range = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn) - return { - suggestions: [ - ...(sug || []).map(s => ({ ...s, range })), - ...suggestions.keywords.map(s => ({ ...s, range })), - ...(procedures || []).map(s => ({ ...s, range, })) - ] - } - }, - }) - - setSugProvider(provider) + monacoI.editor.setTheme('custom-theme') } - const addLabelsSuggestions = async (sug: monaco.languages.CompletionItem[]) => { - const labelsQuery = `CALL db.labels()` - - await securedFetch(`api/graph/${prepareArg(graph.Id)}/?query=${prepareArg(labelsQuery)}`, { - method: "GET" - }, session?.user?.role, toast).then((res) => res.json()).then((json) => { - json.result.data.forEach(({ label }: { label: string }) => { - sug.push({ - label, - kind: monaco.languages.CompletionItemKind.TypeParameter, - insertText: label, - range: new monaco.Range(1, 1, 1, 1), - detail: "(label)" - }) - }) - }) - } - - const addRelationshipTypesSuggestions = async (sug: monaco.languages.CompletionItem[]) => { - const relationshipTypeQuery = `CALL db.relationshipTypes()` - - await securedFetch(`api/graph/${prepareArg(graph.Id)}/?query=${prepareArg(relationshipTypeQuery)}`, { - method: "GET" - }, session?.user?.role, toast).then((res) => res.json()).then((json) => { - json.result.data.forEach(({ relationshipType }: { relationshipType: string }) => { - sug.push({ - label: relationshipType, - kind: monaco.languages.CompletionItemKind.TypeParameter, - insertText: relationshipType, - range: new monaco.Range(1, 1, 1, 1), - detail: "(relationship type)" - }) - }) - }) - } - - const addPropertyKeysSuggestions = async (sug: monaco.languages.CompletionItem[]) => { - const propertyKeysQuery = `CALL db.propertyKeys()` - - await securedFetch(`api/graph/${prepareArg(graph.Id)}/?query=${prepareArg(propertyKeysQuery)}`, { - method: "GET" - }, session?.user?.role, toast).then((res) => res.json()).then((json) => { - json.result.data.forEach(({ propertyKey }: { propertyKey: string }) => { - sug.push({ - label: propertyKey, - kind: monaco.languages.CompletionItemKind.Property, - insertText: propertyKey, - range: new monaco.Range(1, 1, 1, 1), - detail: "(property)" - }) - }) - }) - } - - const addFunctionsSuggestions = async (functions: monaco.languages.CompletionItem[]) => { - const proceduresQuery = `CALL dbms.procedures() YIELD name` - await securedFetch(`api/graph/${prepareArg(graph.Id)}/?query=${prepareArg(proceduresQuery)}`, { - method: "GET" - }, session?.user?.role, toast).then((res) => res.json()).then((json) => { - [...json.result.data.map(({ name }: { name: string }) => name), ...FUNCTIONS].forEach((name: string) => { - functions.push({ - label: name, - kind: monaco.languages.CompletionItemKind.Function, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, - insertText: `${name}($0)`, - range: new monaco.Range(1, 1, 1, 1), - detail: "(function)" - }) - }) - }) + const fetchSuggestions = async (q: string, detail: string): Promise => { + const result = await securedFetch(`api/graph/${graphIdRef.current}/?query=${prepareArg(q)}`, { + method: 'GET', + }, session?.user.role, toast) + + if (!result) return [] + + const json = await result.json() + + if (json.result.data.length === 0) return [] + + return json.result.data.map(({ sug }: { sug: string }) => ({ + insertTextRules: detail === '(function)' ? monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet : undefined, + insertText: detail === '(function)' ? `${sug}(\${0})` : sug, + label: detail === '(function)' ? `${sug}()` : sug, + kind: (() => { + switch (detail) { + case '(function)': + return monaco.languages.CompletionItemKind.Function; + case '(property key)': + return monaco.languages.CompletionItemKind.Property; + default: + return monaco.languages.CompletionItemKind.Variable; + } + })(), + range: new monaco.Range(1, 1, 1, 1), + detail + })) } - const getSuggestions = async (monacoI?: Monaco) => { - - if (!graph.Id || (!monacoInstance && !monacoI)) return - const m = monacoI || monacoInstance - const sug: Suggestions = getEmptySuggestions() - - sugProvider?.dispose() - - await Promise.all([ - addLabelsSuggestions(sug.labels), - addRelationshipTypesSuggestions(sug.relationshipTypes), - addPropertyKeysSuggestions(sug.propertyKeys), - addFunctionsSuggestions(sug.functions) - ]) - - const namespaces = new Map() - - sug.functions.forEach(({ label }) => { - const names = (label as string).split(".") - names.forEach((name, i) => { - if (i === names.length - 1) return - namespaces.set(name, name) - }) - }) + const getSuggestions = async () => (await Promise.all([ + fetchSuggestions('CALL dbms.procedures() YIELD name as sug', '(function)'), + fetchSuggestions('CALL db.propertyKeys() YIELD propertyKey as sug', '(property key)'), + fetchSuggestions('CALL db.labels() YIELD label as sug', '(label)'), + fetchSuggestions('CALL db.relationshipTypes() YIELD relationshipType as sug', '(relationship type)') + ])).flat() + + const addSuggestions = async (monacoI: Monaco) => { + const sug = [ + ...SUGGESTIONS, + ...(graphIdRef.current ? await getSuggestions() : []) + ]; + + const functions = sug.filter(({ detail }) => detail === "(function)") + + const namespaces = new Set( + functions + .filter(({ label }) => (label as string).includes(".")) + .map(({ label }) => { + const newNamespaces = (label as string).split(".") + newNamespaces.pop() + return newNamespaces + }).flat() + ) - m!.languages.setMonarchTokensProvider('custom-language', { + monacoI.languages.setMonarchTokensProvider('custom-language', { tokenizer: { - root: [ + root: graphIdRef.current ? [ [new RegExp(`\\b(${Array.from(namespaces.keys()).join('|')})\\b`), "keyword"], [new RegExp(`\\b(${KEYWORDS.join('|')})\\b`), "keyword"], [ - new RegExp(`\\b(${sug.functions.map(({ label }) => { - const labels = (label as string).split(".") - return labels[labels.length - 1] + new RegExp(`\\b(${functions.map(({ label }) => { + if ((label as string).includes(".")) { + const labels = (label as string).split(".") + return labels[labels.length - 1] + } + return label }).join('|')})\\b`), "function" ], @@ -396,6 +357,15 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre [/\{/, { token: 'delimiter.curly', next: '@bracketCounting' }], [/\[/, { token: 'delimiter.square', next: '@bracketCounting' }], [/\(/, { token: 'delimiter.parenthesis', next: '@bracketCounting' }], + ] : [ + [new RegExp(`\\b(${KEYWORDS.join('|')})\\b`), "keyword"], + [/"([^"\\]|\\.)*"/, 'string'], + [/'([^'\\]|\\.)*'/, 'string'], + [/\d+/, 'number'], + [/:(\w+)/, 'type'], + [/\{/, { token: 'delimiter.curly', next: '@bracketCounting' }], + [/\[/, { token: 'delimiter.square', next: '@bracketCounting' }], + [/\(/, { token: 'delimiter.parenthesis', next: '@bracketCounting' }], ], bracketCounting: [ [/\{/, 'delimiter.curly', '@bracketCounting'], @@ -410,73 +380,13 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre ignoreCase: true, }) - m!.languages.setLanguageConfiguration('custom-language', { - brackets: [ - ['{', '}'], - ['[', ']'], - ['(', ')'] - ], - autoClosingPairs: [ - { open: '{', close: '}' }, - { open: '[', close: ']' }, - { open: '(', close: ')' }, - { open: '"', close: '"', notIn: ['string'] }, - { open: "'", close: "'", notIn: ['string', 'comment'] } - ], - surroundingPairs: [ - { open: '{', close: '}' }, - { open: '[', close: ']' }, - { open: '(', close: ')' }, - { open: '"', close: '"' }, - { open: "'", close: "'" } - ] - }); - - m!.editor.setTheme('custom-theme'); - - addSuggestions(m!, [...sug.labels, ...sug.propertyKeys, ...sug.relationshipTypes], sug.functions) - - setSuggestions(sug) + return sug } - useEffect(() => { - if (!graph || !monacoInstance || graph.Id !== prevGraphName) return setPrevGraphName(graph.Id) - - const run = async () => { - const sug: Suggestions = getEmptySuggestions() - if (graph.Metadata.length > 0) { - await Promise.all(graph.Metadata.map(async (meta: string) => { - if (meta.includes("Labels")) await addLabelsSuggestions(sug.labels) - if (meta.includes("RelationshipTypes")) await addRelationshipTypesSuggestions(sug.relationshipTypes) - if (meta.includes("PropertyKeys")) await addPropertyKeysSuggestions(sug.propertyKeys) - })) - } - Object.entries(sug).forEach(([key, value]) => { - if (value.length === 0) { - sug[key as keyof Suggestions] = suggestions[key as keyof Suggestions] - } - }) - - addSuggestions(monacoInstance, [...sug.labels, ...sug.propertyKeys, ...sug.relationshipTypes], sug.functions) - - setSuggestions(sug) - } + const handleEditorWillMount = async (monacoI: Monaco) => { - run() - }, [graph]) + monacoI.languages.register({ id: "custom-language" }) - useEffect(() => { - const interval = setInterval(() => { - getSuggestions() - }, 5000) - - return () => { - clearInterval(interval) - sugProvider?.dispose() - } - }, [graph.Id]) - - const handleEditorWillMount = (monacoI: Monaco) => { monacoI.languages.setMonarchTokensProvider('custom-language', { tokenizer: { root: [ @@ -500,9 +410,9 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre ], }, ignoreCase: true, - }); + }) - monacoI.languages.register({ id: 'custom-language' }); + setTheme(monacoI) monacoI.languages.setLanguageConfiguration('custom-language', { brackets: [ @@ -526,18 +436,22 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre ] }); - setTheme(monacoI) + const provider = monacoI.languages.registerCompletionItemProvider("custom-language", { + provideCompletionItems: async (model, position) => { + const word = model.getWordUntilPosition(position) + const range = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn) + return { + suggestions: (await addSuggestions(monacoI)).map(s => ({ ...s, range })) + } + }, + }) - monacoI.editor.setTheme('custom-theme'); + setSugDisposed(provider) + } - if (graph.Id) { - getSuggestions(monacoI) - } else { - addSuggestions(monacoI) - } - }; + const handleEditorDidMount = (e: monaco.editor.IStandaloneCodeEditor) => { + editorRef.current = e - const handleEditorDidMount = (e: monaco.editor.IStandaloneCodeEditor, monacoI: Monaco) => { const updatePlaceholderVisibility = () => { const hasContent = !!e.getValue(); if (placeholderRef.current) { @@ -549,26 +463,16 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre if (placeholderRef.current) { placeholderRef.current.style.display = 'none'; } + setBlur(false) }); e.onDidBlurEditorText(() => { updatePlaceholderVisibility(); + setBlur(true) }); updatePlaceholderVisibility(); - setMonacoInstance(monacoI) - - editorRef.current = e - - e.onDidBlurEditorText(() => { - setBlur(true) - }) - - e.onDidFocusEditorText(() => { - setBlur(false) - }) - const isFirstLine = e.createContextKey('isFirstLine', true); // Update the context key value based on the cursor position @@ -597,9 +501,9 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre contextMenuOrder: 1.5, run: async () => { if (historyRef.current.historyQueries.length === 0) return - const counter = historyRef.current.historyCounter ? historyRef.current.historyCounter - 1 : historyRef.current.historyQueries.length; - historyRef.current.historyCounter = counter; - setQuery(counter ? historyRef.current.historyQueries[counter - 1] : historyRef.current.currentQuery); + const counter = (historyRef.current.historyCounter + 1) % (historyRef.current.historyQueries.length + 1) + historyRef.current.historyCounter = counter + setQuery(counter ? historyRef.current.historyQueries[counter - 1] : historyRef.current.currentQuery) }, precondition: 'isFirstLine && !suggestWidgetVisible', }); @@ -611,14 +515,20 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre contextMenuOrder: 1.5, run: async () => { if (historyRef.current.historyQueries.length === 0) return - const counter = (historyRef.current.historyCounter + 1) % (historyRef.current.historyQueries.length + 1) - historyRef.current.historyCounter = counter - setQuery(counter ? historyRef.current.historyQueries[counter - 1] : historyRef.current.currentQuery) + const counter = historyRef.current.historyCounter ? historyRef.current.historyCounter - 1 : historyRef.current.historyQueries.length; + historyRef.current.historyCounter = counter; + setQuery(counter ? historyRef.current.historyQueries[counter - 1] : historyRef.current.currentQuery); }, precondition: 'isFirstLine && !suggestWidgetVisible', }); } + const handleSetHistoryQuery = (val: string) => { + setQuery(val) + historyRef.current.historyQueries[historyRef.current.historyCounter - 1] = val + setHistoryQueries(historyRef.current.historyQueries) + } + useEffect(() => { setLineNumber(query.split("\n").length) }, [query]) @@ -637,7 +547,7 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre runQuery(query) }} > -
+
document.body.clientHeight / 100 * MAX_HEIGHT ? document.body.clientHeight / 100 * MAX_HEIGHT : lineNumber * LINE_HEIGHT} @@ -647,7 +557,7 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre lineNumbers: lineNumber > 1 ? "on" : "off", }} value={(blur ? query.replace(/\s+/g, ' ').trim() : query)} - onChange={(val) => historyRef.current.historyCounter ? setQuery(val || "") : setCurrentQuery(val || "")} + onChange={(val) => historyRef.current.historyCounter ? handleSetHistoryQuery(val || "") : setCurrentQuery(val || "")} theme="custom-theme" beforeMount={handleEditorWillMount} onMount={handleEditorDidMount} @@ -674,6 +584,10 @@ export default function EditorComponent({ currentQuery, historyQueries, setCurre /> + + + + ( - {option} + {!option ? '""' : option} )) } diff --git a/app/graph/GraphView.tsx b/app/graph/GraphView.tsx index 25a6e068..6bd4f75e 100644 --- a/app/graph/GraphView.tsx +++ b/app/graph/GraphView.tsx @@ -24,13 +24,14 @@ import TableView from "./TableView"; const ForceGraph = dynamic(() => import("../components/ForceGraph"), { ssr: false }); const EditorComponent = dynamic(() => import("../components/EditorComponent"), { ssr: false }) -function GraphView({ graph, selectedElement, setSelectedElement, runQuery, historyQuery, historyQueries, fetchCount, session }: { +function GraphView({ graph, selectedElement, setSelectedElement, runQuery, historyQuery, historyQueries, setHistoryQueries, fetchCount, session }: { graph: Graph selectedElement: Node | Link | undefined setSelectedElement: Dispatch> runQuery: (query: string) => Promise historyQuery: string historyQueries: string[] + setHistoryQueries: (queries: string[]) => void fetchCount: () => void session: Session | null }) { @@ -220,10 +221,10 @@ function GraphView({ graph, selectedElement, setSelectedElement, runQuery, histo > diff --git a/app/graph/Selector.tsx b/app/graph/Selector.tsx index be224c7b..f8fb06d6 100644 --- a/app/graph/Selector.tsx +++ b/app/graph/Selector.tsx @@ -74,6 +74,7 @@ export default function Selector({ onChange, graphName, setGraphName, queries, r } const handleOnChange = async (name: string) => { + const formattedName = name === '""' ? "" : name if (runQuery) { const q = 'MATCH (n)-[e]-(m) return n,e,m' const result = await securedFetch(`api/graph/${prepareArg(name)}_schema/?query=${prepareArg(q)}&create=false`, { @@ -87,7 +88,7 @@ export default function Selector({ onChange, graphName, setGraphName, queries, r setSchema(Graph.create(name, json.result, false, true)) } } - onChange(name) + onChange(formattedName) setSelectedValue(name) } diff --git a/app/graph/page.tsx b/app/graph/page.tsx index 2c8673de..305d11de 100644 --- a/app/graph/page.tsx +++ b/app/graph/page.tsx @@ -129,6 +129,7 @@ export default function Page() { runQuery={runQuery} historyQuery={historyQuery} historyQueries={queries.map(({ text }) => text)} + setHistoryQueries={(queriesArr) => setQueries(queries.map((query, i) => ({ text: queriesArr[i], metadata: query.metadata } as Query)))} fetchCount={fetchCount} session={session} /> diff --git a/app/schema/page.tsx b/app/schema/page.tsx index 56f9dd82..488ef1c1 100644 --- a/app/schema/page.tsx +++ b/app/schema/page.tsx @@ -56,7 +56,7 @@ export default function Page() { return (
-
+
1000) { + toast({ + title: "Error", + description: "Value must be less than 1000", + variant: "destructive" + }); + return false; + } + } + const result = await securedFetch( `api/graph/?config=${prepareArg(name)}&value=${prepareArg(value)}`, { method: 'POST' }, @@ -122,7 +133,7 @@ export default function Configurations() { ); if (!result.ok) return false; - + const configToUpdate = configs.find(row => row.cells[0].value === name); const oldValue = configToUpdate?.cells[2].value;