Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Add slash command [WIP]

Tomas Valenta63e027a43bad
diff --git a/components/Editor/extensions/SlackCommand/Item.tsx b/components/Editor/extensions/SlackCommand/Item.tsx
new file mode 100644
index 000000000..ee811bd84
--- /dev/null
+++ b/components/Editor/extensions/SlackCommand/Item.tsx
@@ -0,0 +1,53 @@
+import { useLayoutEffect } from 'react'
+import cn from 'clsx'
+
+import useElement from 'hooks/useElement'
+import Text from 'components/Text'
+
+export interface Props {
+ selectItem: () => void
+ isSelected: boolean
+ title: string
+}
+
+function Item({
+ selectItem,
+ isSelected,
+ title,
+}: Props) {
+ const [scrollEl, setScrollRef] = useElement<HTMLDivElement>()
+
+ useLayoutEffect(function scrollToItem() {
+ if (scrollEl && isSelected) {
+ scrollEl.scrollIntoView({
+ block: 'nearest',
+ })
+ }
+ }, [isSelected, scrollEl])
+
+ return (
+ <div
+ ref={setScrollRef}
+ className={cn(
+ 'px-1.5',
+ 'py-0.5',
+ 'flex-shrink-0',
+ 'flex',
+ 'rounded',
+ 'items-center',
+ 'group',
+ 'overflow-ellipsis',
+ 'overflow-hidden',
+ 'cursor-pointer',
+ { 'bg-gray-100 dark:bg-black-900': isSelected },
+ )}
+ onMouseDown={selectItem}
+ >
+ <Text
+ text={title}
+ />
+ </div>
+ )
+}
+
+export default Item
diff --git a/components/Editor/extensions/SlackCommand/index.tsx b/components/Editor/extensions/SlackCommand/index.tsx
new file mode 100644
index 000000000..3a1aebf40
--- /dev/null
+++ b/components/Editor/extensions/SlackCommand/index.tsx
@@ -0,0 +1,157 @@
+import {
+ useImperativeHandle,
+ useState,
+ forwardRef,
+ useCallback,
+} from 'react'
+import { ChainedCommands } from '@tiptap/core'
+
+import { CommandList } from 'components/Editor/extensions/command/CommandListWrapper'
+import { Lang } from 'editor/extensions/codeCell/language'
+
+import Item from './Item'
+
+interface CommandItem {
+ title: string
+ extendCommand: (cmd: ChainedCommands) => ChainedCommands
+}
+
+const items: CommandItem[] = [
+ {
+ title: 'Next.js Code Cell',
+ extendCommand: (cmd) => {
+ return cmd
+ .setCodeCell({
+ templateID: 'nextjs-v11-components',
+ language: Lang.tsx,
+ })
+ },
+ },
+ {
+ title: 'Node.js Code Cell',
+ extendCommand: (cmd) => {
+ return cmd
+ .setCodeCell({
+ templateID: 'nodejs-v16',
+ language: Lang.ts,
+ })
+ },
+ },
+ {
+ title: 'Shell Command (Next.js)',
+ extendCommand: (last) => {
+ return last.setCodeCell({
+ templateID: 'nextjs-v11-components',
+ language: Lang.sh,
+ })
+ },
+ },
+ {
+ title: 'Shell Command (Node.js)',
+ extendCommand: (last) => {
+ return last.setCodeCell({
+ templateID: 'nodejs-v16',
+ language: Lang.sh,
+ })
+ }
+ },
+ {
+ title: 'Iframe Cell',
+ extendCommand: (cmd) => {
+ return cmd
+ .focus()
+ .setIframe({ src: 'https://usedevbook.com' })
+ },
+ },
+ {
+ title: 'Console Cell',
+ extendCommand: (cmd) => {
+ return cmd
+ .focus()
+ .setConsoleCell()
+ },
+ },
+]
+
+const SlashCommand: CommandList = forwardRef(({
+ editor,
+ range,
+}, ref) => {
+ const [selectedIndex, setSelectedIndex] = useState(0)
+
+ const selectItem = useCallback((index: number) => {
+ const cmd = editor
+ .chain()
+ .deleteRange(range)
+
+ items[index]
+ .extendCommand(cmd)
+ .setTextSelection(0)
+ .run()
+ }, [
+ range,
+ editor,
+ ])
+
+ useImperativeHandle(ref, () => ({
+ onKeyDown({ event }) {
+ if (event.key === 'ArrowUp') {
+ setSelectedIndex(i => ((i + items.length) - 1) % items.length)
+ return true
+ }
+ if (event.key === 'ArrowDown') {
+ setSelectedIndex(i => (i + 1) % items.length)
+ return true
+ }
+ if (event.key === 'Enter') {
+ selectItem(selectedIndex)
+ return true
+ }
+ return false
+ },
+ }), [
+ selectedIndex,
+ selectItem,
+ ])
+
+ return (
+ <div
+ className="
+ p-1.5
+ w-56
+ max-h-56
+
+ flex
+ flex-col
+ flex-shrink-0
+
+ overflow-y-auto
+ overscroll-none
+
+ rounded
+
+ border
+ dark:border-black-600
+ border-gray-500
+
+ bg-gray-300
+ dark:bg-black-650
+
+ shadow-lg
+ "
+ >
+ {items.map((item, index) => (
+ <Item
+ key={item.title}
+ title={item.title}
+ isSelected={index === selectedIndex}
+ selectItem={() => selectItem(index)}
+ />
+ ))}
+ </div>
+ )
+})
+
+SlashCommand.displayName = 'SlashCommand'
+
+export default SlashCommand
\ No newline at end of file
diff --git a/components/Editor/extensions/command/CommandListWrapper.tsx b/components/Editor/extensions/command/CommandListWrapper.tsx
new file mode 100644
index 000000000..2fc8f0131
--- /dev/null
+++ b/components/Editor/extensions/command/CommandListWrapper.tsx
@@ -0,0 +1,42 @@
+import {
+ createRef,
+ ForwardRefExoticComponent,
+ Component,
+ createElement,
+ RefAttributes,
+ RefObject,
+} from 'react'
+
+import {
+ SuggestionProps,
+ SuggestionKeyDownProps,
+} from 'editor/extensions/command/suggestion'
+
+type CommandListRef = Partial<HTMLDivElement> & { onKeyDown: (props: SuggestionKeyDownProps) => boolean }
+export interface CommandListProps extends SuggestionProps { }
+
+export type CommandList = ForwardRefExoticComponent<CommandListProps & RefAttributes<CommandListRef>>
+
+export interface CommmandListWrapperProps extends SuggestionProps {
+ list: CommandList
+}
+
+class CommandListWrapper extends Component<CommmandListWrapperProps, {}, {}> {
+ childRef: RefObject<CommandListRef>
+
+ constructor(public props: CommmandListWrapperProps) {
+ super(props)
+ this.childRef = createRef<CommandListRef>()
+ props.list.name
+ }
+
+ onKeyDown(props: SuggestionKeyDownProps) {
+ return this.childRef.current?.onKeyDown(props)
+ }
+
+ render() {
+ return createElement(this.props.list, { ...this.props, ref: this.childRef, }, null)
+ }
+}
+
+export default CommandListWrapper
\ No newline at end of file
diff --git a/editor/extensions/command/findSuggestionMatch.ts b/editor/extensions/command/findSuggestionMatch.ts
new file mode 100644
index 000000000..f6133c6aa
--- /dev/null
+++ b/editor/extensions/command/findSuggestionMatch.ts
@@ -0,0 +1,86 @@
+import { Range } from '@tiptap/core'
+import { ResolvedPos } from 'prosemirror-model'
+
+export interface Trigger {
+ char: string,
+ allowSpaces: boolean,
+ startOfLine: boolean,
+ $position: ResolvedPos,
+}
+
+export type SuggestionMatch = {
+ range: Range,
+ query: string,
+ text: string,
+} | null
+
+export function findSuggestionMatch(config: Trigger): SuggestionMatch {
+ const {
+ char,
+ allowSpaces,
+ startOfLine,
+ $position,
+ } = config
+
+ const textAfterAnchor = $position.nodeAfter?.textContent || ''
+ const whitespaceAfterAnchorIndex = textAfterAnchor.indexOf(' ')
+ const textAfterAnchorUntilWhitespace = whitespaceAfterAnchorIndex < 0
+ ? textAfterAnchor
+ : textAfterAnchor.slice(0, whitespaceAfterAnchorIndex + 1)
+
+ // Matching expressions used for later
+ const escapedChar = char
+ .split('')
+ .map(c => `\\${c}`)
+ .join('')
+ const suffix = new RegExp(`\\s${escapedChar}$`)
+ const prefix = startOfLine ? '^' : ''
+ const regexp = allowSpaces
+ ? new RegExp(`${prefix}${escapedChar}.*?(?=\\s${escapedChar}|$)`, 'gm')
+ : new RegExp(`${prefix}(?:^)?${escapedChar}[^\\s${escapedChar}]*`, 'gm')
+
+ const isTopLevelNode = $position.depth <= 0
+ const textFrom = isTopLevelNode
+ ? 0
+ : $position.before()
+ const textTo = $position.pos
+ const text = $position.doc.textBetween(textFrom, textTo, '\0', '\0') + textAfterAnchorUntilWhitespace
+ const match = Array.from(text.matchAll(regexp)).pop()
+
+ if (!match || match.input === undefined || match.index === undefined) {
+ return null
+ }
+
+ // JavaScript doesn't have lookbehinds; this hacks a check that first character is " "
+ // or the line beginning
+ const matchPrefix = match.input.slice(Math.max(0, match.index - 1), match.index)
+
+ if (!/^[\s\0]?$/.test(matchPrefix)) {
+ return null
+ }
+
+ // The absolute position of the match in the document
+ const from = match.index + $position.start()
+ let to = from + match[0].length
+
+ // Edge case handling; if spaces are allowed and we're directly in between
+ // two triggers
+ if (allowSpaces && suffix.test(text.slice(to - 1, to + 1))) {
+ match[0] += ' '
+ to += 1
+ }
+
+ // If the $position is located within the matched substring, return that range
+ if (from < $position.pos && to >= $position.pos) {
+ return {
+ range: {
+ from,
+ to,
+ },
+ query: match[0].slice(char.length),
+ text: match[0],
+ }
+ }
+
+ return null
+}
diff --git a/editor/extensions/command/index.ts b/editor/extensions/command/index.ts
new file mode 100644
index 000000000..8c01195ee
--- /dev/null
+++ b/editor/extensions/command/index.ts
@@ -0,0 +1,106 @@
+import { Node } from '@tiptap/core'
+import {
+ Editor as ReactEditor,
+ ReactRenderer,
+} from '@tiptap/react'
+import tippy, {
+ Instance,
+ Props,
+} from 'tippy.js'
+import { ComponentClass } from 'react'
+
+import { destroyOnEsc } from 'editor/tippyPlugins'
+
+import { Suggestion, SuggestionOptions } from './suggestion'
+import CommandListWrapper, { CommandList } from 'components/Editor/extensions/command/CommandListWrapper'
+
+export * from './findSuggestionMatch'
+export * from './suggestion'
+
+export type CommandOptions = {
+ list?: CommandList
+ suggestion: Omit<SuggestionOptions, 'editor'>
+}
+
+export const Command = (component: CommandList) => Node.create<CommandOptions>({
+ name: 'command',
+ addOptions() {
+ return {
+ suggestion: {
+ // Check if the cursor is in a paragraph.
+ allow: ({ editor: { state: { doc, selection } } }) => doc.resolve(selection.anchor)?.parent?.type.name === 'paragraph',
+ render: () => {
+ let reactRenderer: any
+ let popup: Instance<Props> | undefined
+ let disabled = false
+
+ return {
+ onStart: props => {
+ disabled = false
+ reactRenderer = new ReactRenderer(CommandListWrapper as unknown as ComponentClass, {
+ editor: props.editor as ReactEditor,
+ props: {
+ ...props,
+ list: component,
+ },
+ })
+
+ const editorElement = props.editor.options.element
+
+ popup = tippy(editorElement, {
+ getReferenceClientRect: props.clientRect,
+ appendTo: () => document.body,
+ content: reactRenderer.element,
+ showOnCreate: true,
+ interactive: true,
+ hideOnClick: true,
+ maxWidth: 'none',
+ trigger: 'manual',
+ animation: false,
+ placement: 'bottom-start',
+ onHide() {
+ disabled = true
+ reactRenderer.destroy()
+ },
+ onDestroy() {
+ disabled = true
+ reactRenderer.destroy()
+ },
+ plugins: [destroyOnEsc],
+ })
+ },
+ onUpdate(props) {
+ if (disabled) return
+ reactRenderer.updateProps(props)
+
+ popup?.setProps({
+ getReferenceClientRect: props.clientRect,
+ })
+ },
+ onKeyDown(props) {
+ if (disabled) return false
+ return reactRenderer?.ref?.onKeyDown(props)
+ },
+ onExit() {
+ // Tippy.js throws the error:
+ // `destroy() was called on an already-destroyed instance. This is a no-op but indicates a potential memory leak.`
+ // only when you refresh the page and not when you navigate to it.
+ // I suspect that the fast refresh in Next.js does not properly handle the popup when you refresh the page.
+ popup?.destroy()
+ reactRenderer.destroy()
+ },
+ }
+ },
+ },
+ }
+ },
+
+ addProseMirrorPlugins() {
+ return [
+ Suggestion({
+ editor: this.editor,
+ ...this.options.suggestion,
+ }),
+ ]
+ },
+})
\ No newline at end of file
diff --git a/editor/extensions/command/suggestion.ts b/editor/extensions/command/suggestion.ts
new file mode 100644
index 000000000..4b6797a3a
--- /dev/null
+++ b/editor/extensions/command/suggestion.ts
@@ -0,0 +1,229 @@
+import { Editor, Range } from '@tiptap/core'
+import { Plugin, PluginKey } from 'prosemirror-state'
+import { Decoration, DecorationSet, EditorView } from 'prosemirror-view'
+import { findSuggestionMatch } from './findSuggestionMatch'
+
+export interface SuggestionOptions<Item = unknown> {
+ editor: Editor,
+ char?: string,
+ startOfLine?: boolean,
+ decorationTag?: string,
+ decorationClass?: string,
+ command?: (props: {
+ editor: Editor,
+ range: Range,
+ props: Item,
+ }) => void,
+ items?: ((query: string) => Item[]) | ((query: string) => Promise<Item[]>),
+ render?: () => {
+ onStart?: (props: SuggestionProps<Item>) => void,
+ onUpdate?: (props: SuggestionProps<Item>) => void,
+ onExit?: (props: SuggestionProps<Item>) => void,
+ onKeyDown?: (props: SuggestionKeyDownProps) => boolean,
+ },
+ allow?: (props: {
+ editor: Editor,
+ range: Range,
+ }) => boolean,
+}
+
+export interface SuggestionProps<Item = unknown> {
+ editor: Editor,
+ range: Range,
+ query: string,
+ text: string,
+ items: Item[],
+ command: (props: Item) => void,
+ decorationNode: Element | null,
+ clientRect: (() => DOMRect) | null,
+}
+
+export interface SuggestionKeyDownProps {
+ view: EditorView,
+ event: KeyboardEvent,
+ range: Range,
+}
+
+export function Suggestion<Item = unknown>({
+ editor,
+ char = '@',
+ startOfLine = false,
+ decorationTag = 'span',
+ decorationClass = 'suggestion',
+ command = () => null,
+ items = () => [],
+ render = () => ({}),
+ allow = () => true,
+}: SuggestionOptions<Item>) {
+ const renderer = render?.()
+
+ const allowSpaces = false
+
+ return new Plugin({
+ key: new PluginKey('suggestion'),
+
+ view() {
+ return {
+ update: async (view, prevState) => {
+ const prev = this.key?.getState(prevState)
+ const next = this.key?.getState(view.state)
+
+ // See how the state changed
+ const moved = prev.active && next.active && prev.range.from !== next.range.from
+ const started = !prev.active && next.active
+ const stopped = prev.active && !next.active
+ const changed = !started && !stopped && prev.query !== next.query
+ const handleStart = started || moved
+ const handleChange = changed && !moved
+ const handleExit = stopped || moved
+
+ // Cancel when suggestion isn't active
+ if (!handleStart && !handleChange && !handleExit) {
+ return
+ }
+
+ const state = handleExit && !handleStart
+ ? prev
+ : next
+ const decorationNode = document.querySelector(`[data-decoration-id="${state.decorationId}"]`)
+ const props: SuggestionProps<Item> = {
+ editor,
+ range: state.range,
+ query: state.query,
+ text: state.text,
+ items: (handleChange || handleStart)
+ ? await items(state.query)
+ : [],
+ command: commandProps => {
+ command({
+ editor,
+ range: state.range,
+ props: commandProps,
+ })
+ },
+ decorationNode,
+ // virtual node for popper.js or tippy.js
+ // this can be used for building popups without a DOM node
+ clientRect: decorationNode
+ ? () => decorationNode.getBoundingClientRect()
+ : null,
+ }
+
+ if (handleExit) {
+ renderer?.onExit?.(props)
+ }
+
+ if (handleChange) {
+ renderer?.onUpdate?.(props)
+ }
+
+ if (handleStart) {
+ renderer?.onStart?.(props)
+ }
+ },
+ }
+ },
+
+ state: {
+ // Initialize the plugin's internal state.
+ init() {
+ return {
+ active: false,
+ range: {},
+ query: null,
+ text: null,
+ wasCharTyped: false,
+ }
+ },
+
+ // Apply changes to the plugin state from a view transaction.
+ apply(transaction, prev) {
+ const { selection } = transaction
+ const next = { ...prev }
+
+ // We can only be suggesting if there is no selection
+ if (!prev.wasCharTyped) {
+ next.active = false
+ } else if (selection.from === selection.to) {
+ // Reset active state if we just left the previous suggestion range
+ if (selection.from < prev.range.from || selection.from > prev.range.to) {
+ next.active = false
+ }
+
+ // Try to match against where our cursor currently is
+ const match = findSuggestionMatch({
+ char,
+ allowSpaces,
+ startOfLine,
+ $position: selection.$from,
+ })
+ const decorationId = `id_${Math.floor(Math.random() * 0xFFFFFFFF)}`
+
+ // If we found a match, update the current state to show it
+ if (match && allow({ editor, range: match.range })) {
+ next.active = true
+ next.decorationId = prev.decorationId ? prev.decorationId : decorationId
+ next.range = match.range
+ next.query = match.query
+ next.text = match.text
+ } else {
+ next.active = false
+ }
+ } else {
+ next.active = false
+ }
+
+ // Make sure to empty the range if suggestion is inactive
+ if (!next.active) {
+ next.wasCharTyped = false
+ next.decorationId = null
+ next.range = {}
+ next.query = null
+ next.text = null
+ }
+
+ return next
+ },
+ },
+
+ props: {
+ handleTextInput(view, from, to, text) {
+ const state = this.getState(view.state)
+ const preceedingChar = view.state.doc.textBetween(from - 1, from)
+
+ if (text === char && (preceedingChar === ' ' || !preceedingChar)) {
+ state.wasCharTyped = true
+ }
+
+ return false
+ },
+ // Call the keydown hook if suggestion is active.
+ handleKeyDown(view, event) {
+ const { active, range } = this.getState(view.state)
+
+ if (!active) {
+ return false
+ }
+
+ return renderer?.onKeyDown?.({ view, event, range }) || false
+ },
+
+ // Setup decorator on the currently active suggestion.
+ decorations(state) {
+ const { active, range, decorationId } = this.getState(state)
+
+ if (!active) {
+ return null
+ }
+
+ return DecorationSet.create(state.doc, [
+ Decoration.inline(range.from, range.to, {
+ nodeName: decorationTag,
+ class: decorationClass,
+ 'data-decoration-id': decorationId,
+ }),
+ ])
+ },
+ },
+ })
+}
diff --git a/editor/extensions/slashCommand.ts b/editor/extensions/slashCommand.ts
new file mode 100644
index 000000000..4678f45e1
--- /dev/null
+++ b/editor/extensions/slashCommand.ts
@@ -0,0 +1,16 @@
+import SlashCommand from 'src/components/Editor/extensions/SlashCommand'
+
+import { Command } from './command'
+
+const SlashCommandName = 'slashCommand'
+
+export default Command(SlashCommand)
+ .extend({
+ name: SlashCommandName,
+ })
+ .configure({
+ suggestion: {
+ char: '/',
+ startOfLine: true,
+ },
+ })
diff --git a/editor/tippyPlugins/destroyOnEsc.ts b/editor/tippyPlugins/destroyOnEsc.ts
new file mode 100644
index 000000000..b4895b8f9
--- /dev/null
+++ b/editor/tippyPlugins/destroyOnEsc.ts
@@ -0,0 +1,20 @@
+export const destroyOnEsc = {
+ name: 'destroyOnEsc',
+
+ defaultValue: true,
+
+ fn({ destroy }: { destroy: () => void }) {
+ function onKeyDown(event: any) {
+ if (event.keyCode === 27) destroy()
+ }
+
+ return {
+ onShow() {
+ document.addEventListener('keydown', onKeyDown)
+ },
+ onHide() {
+ document.removeEventListener('keydown', onKeyDown)
+ },
+ }
+ },
+}
\ No newline at end of file
diff --git a/editor/tippyPlugins/index.ts b/editor/tippyPlugins/index.ts
new file mode 100644
index 000000000..696087ec9
--- /dev/null
+++ b/editor/tippyPlugins/index.ts
@@ -0,0 +1 @@
+export * from './destroyOnEsc'
\ No newline at end of file
diff --git a/hooks/useBlock.tsx b/hooks/useBlock.ts
similarity index 100%
rename from hooks/useBlock.tsx
rename to hooks/useBlock.ts
diff --git a/hooks/useDocEditor.tsx b/hooks/useDocEditor.ts
similarity index 100%
rename from hooks/useDocEditor.tsx
rename to hooks/useDocEditor.ts
diff --git a/hooks/useElement.ts b/hooks/useElement.ts
new file mode 100644
index 000000000..402a1e51b
--- /dev/null
+++ b/hooks/useElement.ts
@@ -0,0 +1,20 @@
+import {
+ useState,
+ useCallback,
+ RefCallback,
+} from 'react'
+
+function useElement<T>(cb?: (element: T) => any): [T | undefined, (instance: T | null) => void] {
+ const [element, setElement] = useState<T>()
+
+ const initElementRef = useCallback<RefCallback<T>>((element) => {
+ if (element !== null) {
+ cb?.(element)
+ setElement(element)
+ }
+ }, [])
+
+ return [element, initElementRef]
+}
+
+export default useElement
diff --git a/hooks/useLatestDeployment.tsx b/hooks/useLatestDeployment.ts
similarity index 100%
rename from hooks/useLatestDeployment.tsx
rename to hooks/useLatestDeployment.ts