@copilotkit/react-textarea 1.50.0-beta.0 → 1.50.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +95 -0
- package/dist/{chunk-ISKK3RIW.mjs → chunk-4ECCCOFV.mjs} +4 -4
- package/dist/{chunk-5NZNJCP2.mjs → chunk-AT3INWD6.mjs} +25 -25
- package/dist/{chunk-4VCJHANC.mjs → chunk-JVCLCI7G.mjs} +4 -4
- package/dist/chunk-KAU7LAEQ.mjs +60 -0
- package/dist/chunk-KAU7LAEQ.mjs.map +1 -0
- package/dist/{chunk-66KFI242.mjs → chunk-L6JBC3MS.mjs} +2 -2
- package/dist/chunk-MMVDU6DF.mjs +1 -0
- package/dist/{chunk-7VADGLV2.mjs → chunk-PIMJDHZM.mjs} +5 -5
- package/dist/components/base-copilot-textarea/base-copilot-textarea.mjs +19 -19
- package/dist/components/copilot-textarea/copilot-textarea.mjs +30 -77
- package/dist/components/copilot-textarea/copilot-textarea.mjs.map +1 -1
- package/dist/components/hovering-toolbar/hovering-toolbar.mjs +8 -8
- package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.mjs +4 -4
- package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.mjs +5 -5
- package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.mjs +5 -5
- package/dist/components/index.d.ts +11 -2
- package/dist/components/index.js +490 -8
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +33 -21
- package/dist/components/ui/command.d.ts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +327 -59
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +37 -30
- package/dist/types/autosuggestions-config/autosuggestions-config.mjs +2 -2
- package/dist/types/autosuggestions-config/index.mjs +2 -2
- package/dist/types/index.mjs +3 -3
- package/package.json +20 -20
- package/src/components/index.ts +3 -0
- package/dist/chunk-JD7BAH7U.mjs +0 -1
- /package/dist/{chunk-ISKK3RIW.mjs.map → chunk-4ECCCOFV.mjs.map} +0 -0
- /package/dist/{chunk-5NZNJCP2.mjs.map → chunk-AT3INWD6.mjs.map} +0 -0
- /package/dist/{chunk-4VCJHANC.mjs.map → chunk-JVCLCI7G.mjs.map} +0 -0
- /package/dist/{chunk-66KFI242.mjs.map → chunk-L6JBC3MS.mjs.map} +0 -0
- /package/dist/{chunk-JD7BAH7U.mjs.map → chunk-MMVDU6DF.mjs.map} +0 -0
- /package/dist/{chunk-7VADGLV2.mjs.map → chunk-PIMJDHZM.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/index.ts","../../src/components/base-copilot-textarea/base-copilot-textarea.tsx","../../src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts","../../src/lib/debouncer.ts","../../src/lib/utils.ts","../../src/types/base/editor-autocomplete-state.ts","../../src/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.tsx","../../src/lib/slatejs-edits/with-partial-history.ts","../../src/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.ts","../../src/lib/get-text-around-cursor.ts","../../src/lib/slatejs-edits/replace-text.ts","../../src/lib/slatejs-edits/add-autocompletions.ts","../../src/lib/slatejs-edits/clear-autocompletions.ts","../../src/types/base/base-autosuggestions-config.tsx","../../src/components/hovering-toolbar/hovering-toolbar.tsx","../../src/components/hovering-toolbar/hovering-editor-provider.tsx","../../src/components/hovering-toolbar/hovering-toolbar-components.tsx","../../src/hooks/misc/use-autosize-textarea.tsx","../../src/components/source-search-box/source-search-box.tsx","../../src/components/ui/command.tsx","../../src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.tsx","../../src/components/ui/button.tsx","../../src/components/ui/label.tsx","../../src/lib/stream-promise-flatten.ts","../../src/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.tsx","../../src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.tsx","../../src/components/base-copilot-textarea/render-element.tsx","../../src/components/base-copilot-textarea/render-placeholder.tsx","../../src/components/base-copilot-textarea/use-add-branding-css.tsx","../../src/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.tsx","../../src/lib/editor-to-text.ts"],"sourcesContent":["export { BaseCopilotTextarea } from \"./base-copilot-textarea/base-copilot-textarea\";\n","import React, { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Descendant, Editor } from \"slate\";\nimport { Editable, Slate } from \"slate-react\";\nimport { twMerge } from \"tailwind-merge\";\nimport { useAutosuggestions } from \"../../hooks/base-copilot-textarea-implementation/use-autosuggestions\";\nimport { useCopilotTextareaEditor } from \"../../hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor\";\nimport { usePopulateCopilotTextareaRef } from \"../../hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref\";\nimport {\n getFullEditorTextWithNewlines,\n getTextAroundCollapsedCursor,\n} from \"../../lib/get-text-around-cursor\";\nimport { addAutocompletionsToEditor } from \"../../lib/slatejs-edits/add-autocompletions\";\nimport { clearAutocompletionsFromEditor } from \"../../lib/slatejs-edits/clear-autocompletions\";\nimport { replaceEditorText } from \"../../lib/slatejs-edits/replace-text\";\nimport { BaseAutosuggestionsConfig, defaultBaseAutosuggestionsConfig } from \"../../types/base\";\nimport { AutosuggestionState } from \"../../types/base/autosuggestion-state\";\nimport { BaseCopilotTextareaProps } from \"../../types/base/base-copilot-textarea-props\";\nimport \"./base-copilot-textarea.css\";\nimport { HoveringToolbar } from \"../hovering-toolbar/hovering-toolbar\";\nimport { makeRenderElementFunction } from \"./render-element\";\nimport { makeRenderPlaceholderFunction } from \"./render-placeholder\";\nimport { useAddBrandingCss } from \"./use-add-branding-css\";\nimport {\n HoveringEditorProvider,\n useHoveringEditorContext,\n} from \"../hovering-toolbar/hovering-editor-provider\";\nimport { TrackerTextEditedSinceLastCursorMovement } from \"./track-cursor-moved-since-last-text-change\";\n\n/**\n * Purpose: to be used as the `ref` type for `CopilotTextarea` and `BaseCopilotTextarea`.\n *\n * This interface extends `HTMLElement`, and is the subset of `HTMLTextAreaElement` that \"actually matters\".\n * It provides the core functionality that consumers of `HTMLTextAreaElement` need 99.9% of the time:\n * - `value`: the current value of the textarea\n * - `focus`: make the textarea focused\n * - `blur`: make the textarea unfocused\n */\nexport interface HTMLCopilotTextAreaElement extends HTMLElement {\n /**\n * The current value of the textarea.\n */\n value: string;\n\n /**\n * focus on the textarea\n */\n focus: () => void;\n\n /**\n * unfocus the textarea.\n *\n * Called `blur` for syntactic compatibility with `HTMLTextAreaElement`.\n */\n blur: () => void;\n}\n\n/**\n * Not intended for direct use. Use CopilotTextarea instead.\n *\n * The `BaseCopilotTextarea` includes the basic UX component,\n * without the business logic / AI logic that makes the content useful and coherent.\n *\n * It is useful if you want to build your own backend, with fully custom business logic\n * for figuring out which contnet to fill in.\n */\nexport const BaseCopilotTextarea = React.forwardRef(\n (props: BaseCopilotTextareaProps, ref: React.Ref<HTMLCopilotTextAreaElement>) => {\n return (\n <HoveringEditorProvider>\n <BaseCopilotTextareaWithHoveringContext {...props} ref={ref} />\n </HoveringEditorProvider>\n );\n },\n);\n\n/**\n * Not intended for direct use. Use `CopilotTextarea` instead.\n *\n * This is the private core of the `BaseCopilotTextarea` component.\n * For practical purposes the implementation is cleaner assuming containment in a `HoveringEditorProviderContext`.\n *\n * Therefore we separate the core logic into this component,\n * and wrap it in a `HoveringEditorProviderContext` in `BaseCopilotTextarea`.\n */\nconst BaseCopilotTextareaWithHoveringContext = React.forwardRef(\n (props: BaseCopilotTextareaProps, ref: React.Ref<HTMLCopilotTextAreaElement>) => {\n const autosuggestionsConfig: BaseAutosuggestionsConfig = {\n ...defaultBaseAutosuggestionsConfig,\n ...props.baseAutosuggestionsConfig,\n };\n\n const valueOnInitialRender = useMemo(() => props.value ?? \"\", []);\n const [lastKnownFullEditorText, setLastKnownFullEditorText] = useState(valueOnInitialRender);\n const [cursorMovedSinceLastTextChange, setCursorMovedSinceLastTextChange] = useState(false);\n const [isUserInputActive, setIsUserInputActive] = useState(false);\n\n // // When the editor text changes, we want to reset the `textEditedSinceLastCursorMovement` state.\n // useEffect(() => {\n // setCursorMovedSinceLastTextChange(false);\n // }, [lastKnownFullEditorText]);\n\n const initialValue: Descendant[] = useMemo(() => {\n return [\n {\n type: \"paragraph\",\n children: [{ text: valueOnInitialRender }],\n },\n ];\n }, [valueOnInitialRender]);\n\n const editor = useCopilotTextareaEditor();\n\n const { isDisplayed: hoveringEditorIsDisplayed, setIsDisplayed: setHoveringEditorIsDisplayed } =\n useHoveringEditorContext();\n\n const insertText = useCallback(\n (autosuggestion: AutosuggestionState) => {\n Editor.insertText(editor, autosuggestion.text, {\n at: autosuggestion.point,\n });\n },\n [editor],\n );\n\n const shouldDisableAutosuggestions =\n // textarea is manually disabled:\n autosuggestionsConfig.disabled ||\n // hovering editor is displayed:\n hoveringEditorIsDisplayed ||\n // the cursor has moved since the last text change AND we are configured to disable autosuggestions in this case:\n (cursorMovedSinceLastTextChange &&\n autosuggestionsConfig.temporarilyDisableWhenMovingCursorWithoutChangingText) ||\n // not user input and we want to disable non-trusted events (like text insertion from autocomplete plugins):\n (!isUserInputActive && autosuggestionsConfig.temporarilyDisableNotTrustedEvents);\n\n const {\n currentAutocompleteSuggestion,\n onChangeHandler: onChangeHandlerForAutocomplete,\n onKeyDownHandler: onKeyDownHandlerForAutocomplete,\n onTouchStartHandler: onTouchStartHandlerForAutocomplete,\n } = useAutosuggestions(\n autosuggestionsConfig.debounceTime,\n autosuggestionsConfig.shouldAcceptAutosuggestionOnKeyPress,\n autosuggestionsConfig.shouldAcceptAutosuggestionOnTouch,\n autosuggestionsConfig.apiConfig.autosuggestionsFunction,\n insertText,\n autosuggestionsConfig.disableWhenEmpty,\n shouldDisableAutosuggestions,\n );\n\n const onKeyDownHandlerForHoveringEditor = useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (\n autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress(event, props.shortcut ?? \"k\")\n ) {\n event.preventDefault();\n setHoveringEditorIsDisplayed(!hoveringEditorIsDisplayed);\n }\n },\n [\n hoveringEditorIsDisplayed,\n setHoveringEditorIsDisplayed,\n autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress,\n ],\n );\n\n // sync autosuggestions state with the editor\n useEffect(() => {\n clearAutocompletionsFromEditor(editor);\n if (currentAutocompleteSuggestion) {\n addAutocompletionsToEditor(\n editor,\n currentAutocompleteSuggestion.text,\n currentAutocompleteSuggestion.point,\n );\n }\n }, [currentAutocompleteSuggestion]);\n\n const suggestionStyleAugmented: React.CSSProperties = useMemo(() => {\n return {\n fontStyle: \"italic\",\n color: \"gray\",\n ...props.suggestionsStyle,\n };\n }, [props.suggestionsStyle]);\n\n const renderElementMemoized = useMemo(() => {\n return makeRenderElementFunction(suggestionStyleAugmented);\n }, [suggestionStyleAugmented]);\n\n const renderPlaceholderMemoized = useMemo(() => {\n // For some reason slateJS specifies a top value of 0, which makes for strange styling. We override this here.\n const placeholderStyleSlatejsOverrides: React.CSSProperties = {\n top: undefined,\n };\n\n const placeholderStyleAugmented: React.CSSProperties = {\n ...placeholderStyleSlatejsOverrides,\n ...props.placeholderStyle,\n };\n\n return makeRenderPlaceholderFunction(placeholderStyleAugmented);\n }, [props.placeholderStyle]);\n\n // update the editor text, but only when the value changes from outside the component\n useEffect(() => {\n if (props.value === lastKnownFullEditorText) {\n return;\n }\n\n setLastKnownFullEditorText(props.value ?? \"\");\n replaceEditorText(editor, props.value ?? \"\");\n }, [props.value]);\n\n // separate into TextareaHTMLAttributes<HTMLDivElement> and CopilotTextareaProps\n const {\n placeholderStyle,\n value,\n hoverMenuClassname,\n onValueChange,\n baseAutosuggestionsConfig: autosuggestionsConfigFromProps,\n className,\n onChange,\n onKeyDown,\n disableBranding,\n ...propsToForward\n } = props;\n\n useAddBrandingCss(suggestionStyleAugmented, disableBranding);\n usePopulateCopilotTextareaRef(editor, ref);\n\n const moddedClassName = (() => {\n const baseClassName = \"copilot-textarea\";\n const brandingClass = disableBranding ? \"no-branding\" : \"with-branding\";\n const defaultTailwindClassName = \"bg-white overflow-y-auto resize-y\";\n const mergedClassName = twMerge(defaultTailwindClassName, className ?? \"\");\n return `${baseClassName} ${brandingClass} ${mergedClassName}`;\n })();\n\n return (\n <Slate\n editor={editor}\n initialValue={initialValue}\n onChange={(value) => {\n const newEditorState = getTextAroundCollapsedCursor(editor);\n\n const fullEditorText = newEditorState\n ? newEditorState.textBeforeCursor + newEditorState.textAfterCursor\n : getFullEditorTextWithNewlines(editor); // we don't double-parse the editor. When `newEditorState` is null, we didn't parse the editor yet.\n\n setLastKnownFullEditorText((prev) => {\n if (prev !== fullEditorText) {\n setCursorMovedSinceLastTextChange(false);\n }\n return fullEditorText;\n });\n\n onChangeHandlerForAutocomplete(newEditorState);\n\n props.onValueChange?.(fullEditorText);\n props.onChange?.(makeSemiFakeReactTextAreaEvent(fullEditorText));\n }}\n >\n <TrackerTextEditedSinceLastCursorMovement\n setCursorMovedSinceLastTextChange={setCursorMovedSinceLastTextChange}\n />\n <HoveringToolbar\n apiConfig={autosuggestionsConfig.apiConfig}\n contextCategories={autosuggestionsConfig.contextCategories}\n hoverMenuClassname={hoverMenuClassname}\n />\n <Editable\n renderElement={renderElementMemoized}\n renderPlaceholder={renderPlaceholderMemoized}\n onKeyDown={(event) => {\n setIsUserInputActive(true);\n onKeyDownHandlerForHoveringEditor(event); // forward the event for internal use\n onKeyDownHandlerForAutocomplete(event); // forward the event for internal use\n props.onKeyDown?.(event); // forward the event for external use\n }}\n onTouchStart={(event) => {\n onTouchStartHandlerForAutocomplete(event); // forward the event for internal use\n }}\n data-testid=\"copilot-textarea-editable\"\n className={moddedClassName}\n onBlur={(ev) => {\n // clear autocompletion on blur\n props.onBlur?.(ev);\n clearAutocompletionsFromEditor(editor);\n setIsUserInputActive(false);\n }}\n {...propsToForward}\n />\n </Slate>\n );\n },\n);\n\n// Consumers of <textarea> expect a `onChange: (React.ChangeEvent<HTMLTextAreaElement>) => void` event handler to be passed in.\n// This is *extremely* common, and we want to support it.\n//\n// We can't support the full functionality, but in 99% of cases, the consumer only cares about the `event.target.value` property --\n// that's how they get the new value of the textarea.\n//\n// So, the tradeoff we are making is minimizing compiler complaint, with a small chance of runtime error.\n// The alternative would be defining a different onChange entrypoint (we actually do have that in `onValueChange`),\n// And starting to explain subtleties to users the moment they try to use the component for the first time for very basic functionality.\n//\n// If this proves problematic, we can always revisit this decision.\nfunction makeSemiFakeReactTextAreaEvent(\n currentText: string,\n): React.ChangeEvent<HTMLTextAreaElement> {\n return {\n target: {\n value: currentText,\n type: \"copilot-textarea\",\n },\n currentTarget: {\n value: currentText,\n type: \"copilot-textarea\",\n },\n } as React.ChangeEvent<HTMLTextAreaElement>;\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Debouncer } from \"../../lib/debouncer\";\nimport { nullableCompatibleEqualityCheck } from \"../../lib/utils\";\nimport { AutosuggestionsBareFunction } from \"../../types/base\";\nimport { AutosuggestionState } from \"../../types/base/autosuggestion-state\";\nimport {\n EditorAutocompleteState,\n areEqual_autocompleteState,\n} from \"../../types/base/editor-autocomplete-state\";\n\nexport interface UseAutosuggestionsResult {\n currentAutocompleteSuggestion: AutosuggestionState | null;\n onChangeHandler: (newEditorState: EditorAutocompleteState | null) => void;\n onKeyDownHandler: (event: React.KeyboardEvent<HTMLDivElement>) => void;\n onTouchStartHandler: (event: React.TouchEvent<HTMLDivElement>) => void;\n}\n\nexport function useAutosuggestions(\n debounceTime: number,\n shouldAcceptAutosuggestionOnKeyPress: (event: React.KeyboardEvent<HTMLDivElement>) => boolean,\n shouldAcceptAutosuggestionOnTouch: (event: React.TouchEvent<HTMLDivElement>) => boolean,\n autosuggestionFunction: AutosuggestionsBareFunction,\n insertAutocompleteSuggestion: (suggestion: AutosuggestionState) => void,\n disableWhenEmpty: boolean,\n disabled: boolean,\n): UseAutosuggestionsResult {\n const [previousAutocompleteState, setPreviousAutocompleteState] =\n useState<EditorAutocompleteState | null>(null);\n\n const [currentAutocompleteSuggestion, setCurrentAutocompleteSuggestion] =\n useState<AutosuggestionState | null>(null);\n\n const awaitForAndAppendSuggestion: (\n editorAutocompleteState: EditorAutocompleteState,\n abortSignal: AbortSignal,\n ) => Promise<void> = useCallback(\n async (editorAutocompleteState: EditorAutocompleteState, abortSignal: AbortSignal) => {\n // early return if disabled\n if (disabled) {\n return;\n }\n\n if (\n disableWhenEmpty &&\n editorAutocompleteState.textBeforeCursor === \"\" &&\n editorAutocompleteState.textAfterCursor === \"\"\n ) {\n return;\n }\n\n // fetch the suggestion\n const suggestion = await autosuggestionFunction(editorAutocompleteState, abortSignal);\n\n // We'll assume for now that the autocomplete function might or might not respect the abort signal.\n if (!suggestion || abortSignal.aborted) {\n throw new DOMException(\"Aborted\", \"AbortError\");\n }\n\n setCurrentAutocompleteSuggestion({\n text: suggestion,\n point: editorAutocompleteState.cursorPoint,\n });\n },\n [autosuggestionFunction, setCurrentAutocompleteSuggestion, disableWhenEmpty, disabled],\n );\n\n const debouncedFunction = useMemo(\n () => new Debouncer<[editorAutocompleteState: EditorAutocompleteState]>(debounceTime),\n [debounceTime],\n );\n\n // clean current state when unmounting or disabling\n useEffect(() => {\n return () => {\n debouncedFunction.cancel();\n setCurrentAutocompleteSuggestion(null);\n };\n }, [debouncedFunction, disabled]);\n\n const onChange = useCallback(\n (newEditorState: EditorAutocompleteState | null) => {\n const editorStateHasChanged = !nullableCompatibleEqualityCheck(\n areEqual_autocompleteState,\n previousAutocompleteState,\n newEditorState,\n );\n setPreviousAutocompleteState(newEditorState);\n\n // if no change, do nothing\n if (!editorStateHasChanged) {\n return;\n }\n\n // if change, then first null out the current suggestion\n setCurrentAutocompleteSuggestion(null);\n\n // then try to get a new suggestion, debouncing to avoid too many requests while typing\n if (newEditorState) {\n debouncedFunction.debounce(awaitForAndAppendSuggestion, newEditorState);\n } else {\n debouncedFunction.cancel();\n }\n },\n [\n previousAutocompleteState,\n setPreviousAutocompleteState,\n debouncedFunction,\n awaitForAndAppendSuggestion,\n setCurrentAutocompleteSuggestion,\n ],\n );\n\n const keyDownOrTouchHandler = useCallback(\n (event: React.KeyboardEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>) => {\n if (currentAutocompleteSuggestion) {\n const shouldAcceptSuggestion =\n event.type === \"touchstart\"\n ? shouldAcceptAutosuggestionOnTouch(event as React.TouchEvent<HTMLDivElement>)\n : shouldAcceptAutosuggestionOnKeyPress(event as React.KeyboardEvent<HTMLDivElement>);\n\n if (shouldAcceptSuggestion) {\n event.preventDefault();\n insertAutocompleteSuggestion(currentAutocompleteSuggestion);\n setCurrentAutocompleteSuggestion(null);\n }\n }\n },\n [\n currentAutocompleteSuggestion,\n setCurrentAutocompleteSuggestion,\n insertAutocompleteSuggestion,\n shouldAcceptAutosuggestionOnKeyPress,\n ],\n );\n\n return {\n currentAutocompleteSuggestion,\n onChangeHandler: onChange,\n onKeyDownHandler: keyDownOrTouchHandler,\n onTouchStartHandler: keyDownOrTouchHandler,\n };\n}\n","export type AsyncFunction<T extends any[]> = (...args: [...T, AbortSignal]) => Promise<void>;\n\nexport class Debouncer<T extends any[]> {\n private timeoutId?: ReturnType<typeof setTimeout>;\n private activeAbortController?: AbortController;\n\n constructor(private wait: number) {}\n\n debounce = async (func: AsyncFunction<T>, ...args: T) => {\n // Abort the previous promise immediately\n this.cancel();\n\n this.timeoutId = setTimeout(async () => {\n try {\n this.activeAbortController = new AbortController();\n\n // Pass the signal to the async function, assuming it supports it\n await func(...args, this.activeAbortController.signal);\n\n this.activeAbortController = undefined;\n } catch (error) {}\n }, this.wait);\n };\n\n cancel = () => {\n if (this.activeAbortController) {\n this.activeAbortController.abort();\n this.activeAbortController = undefined;\n }\n\n if (this.timeoutId !== undefined) {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n };\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\nexport async function fetcher<JSON = any>(input: RequestInfo, init?: RequestInit): Promise<JSON> {\n const res = await fetch(input, init);\n\n if (!res.ok) {\n const json = await res.json();\n if (json.error) {\n const error = new Error(json.error) as Error & {\n status: number;\n };\n error.status = res.status;\n throw error;\n } else {\n throw new Error(\"An unexpected error occurred\");\n }\n }\n\n return res.json();\n}\n\nexport function formatDate(input: string | number | Date): string {\n const date = new Date(input);\n return date.toLocaleDateString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n });\n}\n\nexport const arraysAreEqual = (arr1: number[], arr2: number[]): boolean =>\n arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);\n\nexport function nullableCompatibleEqualityCheck<T>(\n naiveEqualityCheck: (a: T, b: T) => boolean,\n a: T | null | undefined,\n b: T | null | undefined,\n): boolean {\n if (a === null || a === undefined || b === null || b === undefined) {\n return a === b;\n }\n\n return naiveEqualityCheck(a, b);\n}\n","import { BasePoint } from \"slate\";\nimport { arraysAreEqual } from \"../../lib/utils\";\n\nexport interface EditorAutocompleteState {\n cursorPoint: BasePoint;\n textBeforeCursor: string;\n textAfterCursor: string;\n}\n\nexport function areEqual_autocompleteState(\n prev: EditorAutocompleteState,\n next: EditorAutocompleteState,\n) {\n return (\n prev.cursorPoint.offset === next.cursorPoint.offset &&\n arraysAreEqual(prev.cursorPoint.path, next.cursorPoint.path) &&\n prev.textBeforeCursor === next.textBeforeCursor &&\n prev.textAfterCursor === next.textAfterCursor\n );\n}\n","import { useMemo } from \"react\";\nimport { createEditor, Element } from \"slate\";\nimport { withReact } from \"slate-react\";\nimport {\n defaultShouldSave,\n ShouldSaveToHistory,\n withPartialHistory,\n} from \"../../lib/slatejs-edits/with-partial-history\";\nimport { CustomEditor } from \"../../types/base/custom-editor\";\n\nconst shouldSave: ShouldSaveToHistory = (op, prev) => {\n const excludedNodeType = \"suggestion\";\n // Check if the operation involves the suggestion inline node type\n if (\n op.type === \"insert_node\" &&\n Element.isElement(op.node) &&\n op.node.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"remove_node\" &&\n Element.isElement(op.node) &&\n op.node.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"set_node\" &&\n \"type\" in op.newProperties &&\n op.newProperties.type === excludedNodeType\n ) {\n return false;\n }\n\n if (op.type == \"set_node\" && \"type\" in op.properties && op.properties.type === excludedNodeType) {\n return false;\n }\n\n if (\n op.type === \"merge_node\" &&\n \"type\" in op.properties &&\n op.properties.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"split_node\" &&\n \"type\" in op.properties &&\n op.properties.type === excludedNodeType\n ) {\n return false;\n }\n\n // Otherwise, save the operation to history\n return defaultShouldSave(op, prev);\n};\n\nexport function useCopilotTextareaEditor(): CustomEditor {\n const editor = useMemo(() => {\n const editor = withPartialHistory(withReact(createEditor()), shouldSave);\n\n const { isVoid } = editor;\n editor.isVoid = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return true;\n default:\n return isVoid(element);\n }\n };\n\n const { markableVoid } = editor;\n editor.markableVoid = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return true;\n default:\n return markableVoid(element);\n }\n };\n\n const { isInline } = editor;\n editor.isInline = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return element.inline;\n default:\n return isInline(element);\n }\n };\n\n return editor;\n }, []);\n\n return editor;\n}\n","import { Editor, Operation, Path, Range, Transforms } from \"slate\";\nimport { HistoryEditor } from \"slate-history\";\n\n// Copy-pasted from `https://github.com/ianstormtaylor/slate/blob/main/packages/slate-history/src/with-history.ts`\n// With one exception: the `shouldSave` function is passed in as an argument to `withPartialHistory` instead of being hardcoded\nexport type ShouldSaveToHistory = (op: Operation, prev: Operation | undefined) => boolean;\n\nexport const withPartialHistory = <T extends Editor>(\n editor: T,\n shouldSave: ShouldSaveToHistory,\n) => {\n const e = editor as T & HistoryEditor;\n const { apply } = e;\n e.history = { undos: [], redos: [] };\n\n e.redo = () => {\n const { history } = e;\n const { redos } = history;\n\n if (redos.length > 0) {\n const batch = redos[redos.length - 1];\n\n if (batch.selectionBefore) {\n Transforms.setSelection(e, batch.selectionBefore);\n }\n\n HistoryEditor.withoutSaving(e, () => {\n Editor.withoutNormalizing(e, () => {\n for (const op of batch.operations) {\n e.apply(op);\n }\n });\n });\n\n history.redos.pop();\n e.writeHistory(\"undos\", batch);\n }\n };\n\n e.undo = () => {\n const { history } = e;\n const { undos } = history;\n\n if (undos.length > 0) {\n const batch = undos[undos.length - 1];\n\n HistoryEditor.withoutSaving(e, () => {\n Editor.withoutNormalizing(e, () => {\n const inverseOps = batch.operations.map(Operation.inverse).reverse();\n\n for (const op of inverseOps) {\n e.apply(op);\n }\n if (batch.selectionBefore) {\n Transforms.setSelection(e, batch.selectionBefore);\n }\n });\n });\n\n e.writeHistory(\"redos\", batch);\n history.undos.pop();\n }\n };\n\n e.apply = (op: Operation) => {\n const { operations, history } = e;\n const { undos } = history;\n const lastBatch = undos[undos.length - 1];\n const lastOp = lastBatch && lastBatch.operations[lastBatch.operations.length - 1];\n let save = HistoryEditor.isSaving(e);\n let merge = HistoryEditor.isMerging(e);\n\n if (save == null) {\n save = shouldSave(op, lastOp);\n }\n\n if (save) {\n if (merge == null) {\n if (lastBatch == null) {\n merge = false;\n } else if (operations.length !== 0) {\n merge = true;\n } else {\n merge = shouldMerge(op, lastOp);\n }\n }\n\n if (lastBatch && merge) {\n lastBatch.operations.push(op);\n } else {\n const batch = {\n operations: [op],\n selectionBefore: e.selection,\n };\n e.writeHistory(\"undos\", batch);\n }\n\n while (undos.length > 100) {\n undos.shift();\n }\n\n history.redos = [];\n }\n\n apply(op);\n };\n\n e.writeHistory = (stack: \"undos\" | \"redos\", batch: any) => {\n e.history[stack].push(batch);\n };\n\n return e;\n};\n\n/**\n * Check whether to merge an operation into the previous operation.\n */\n\nconst shouldMerge = (op: Operation, prev: Operation | undefined): boolean => {\n if (\n prev &&\n op.type === \"insert_text\" &&\n prev.type === \"insert_text\" &&\n op.offset === prev.offset + prev.text.length &&\n Path.equals(op.path, prev.path)\n ) {\n return true;\n }\n\n if (\n prev &&\n op.type === \"remove_text\" &&\n prev.type === \"remove_text\" &&\n op.offset + op.text.length === prev.offset &&\n Path.equals(op.path, prev.path)\n ) {\n return true;\n }\n\n return false;\n};\n\nexport const defaultShouldSave = (op: Operation, prev: Operation | undefined): boolean => {\n if (op.type === \"set_selection\") {\n return false;\n }\n\n return true;\n};\n","import React from \"react\";\nimport { Editor } from \"slate\";\nimport { ReactEditor } from \"slate-react\";\nimport { getFullEditorTextWithNewlines } from \"../../lib/get-text-around-cursor\";\nimport { replaceEditorText } from \"../../lib/slatejs-edits/replace-text\";\nimport { HTMLCopilotTextAreaElement } from \"../../types\";\nimport { CustomEditor } from \"../../types/base/custom-editor\";\n\nexport function usePopulateCopilotTextareaRef(\n editor: Editor,\n ref: React.Ref<HTMLCopilotTextAreaElement>,\n) {\n React.useImperativeHandle(ref, () => {\n class Combined {\n constructor(\n private customMethods: CustomMethods,\n private editorHtmlElement: HTMLElement,\n ) {}\n\n [key: string]: any;\n\n get(target: any, propKey: string): any {\n if (this.isKeyOfCustomMethods(propKey)) {\n const value = this.customMethods[propKey];\n if (typeof value === \"function\") {\n return value.bind(this.customMethods);\n }\n return value;\n } else if (this.isKeyOfHTMLElement(propKey)) {\n const value = this.editorHtmlElement[propKey];\n if (typeof value === \"function\") {\n return value.bind(this.editorHtmlElement);\n }\n return value;\n }\n }\n\n set(target: any, propKey: string, value: any): boolean {\n if (this.isKeyOfCustomMethods(propKey)) {\n (this.customMethods as any)[propKey] = value;\n } else if (this.isKeyOfHTMLElement(propKey)) {\n (this.editorHtmlElement as any)[propKey] = value;\n } else {\n // Default behavior (optional)\n target[propKey] = value;\n }\n return true;\n }\n\n private isKeyOfCustomMethods(key: string): key is keyof CustomMethods {\n return key in this.customMethods;\n }\n\n private isKeyOfHTMLElement(key: string): key is keyof HTMLElement {\n return key in this.editorHtmlElement;\n }\n }\n\n const handler = {\n get(target: any, propKey: keyof CustomMethods | keyof HTMLElement) {\n return target.get(target, propKey);\n },\n set(target: any, propKey: keyof CustomMethods | keyof HTMLElement, value: any) {\n return target.set(target, propKey, value);\n },\n };\n\n class CustomMethods {\n constructor(private editor: CustomEditor) {}\n\n focus() {\n ReactEditor.focus(this.editor);\n }\n\n blur() {\n ReactEditor.blur(this.editor);\n }\n\n get value() {\n return getFullEditorTextWithNewlines(this.editor);\n }\n set value(value: string) {\n replaceEditorText(this.editor, value);\n }\n }\n\n const editorHtmlElement = ReactEditor.toDOMNode(editor, editor);\n const customMethods = new CustomMethods(editor);\n\n const combined = new Combined(customMethods, editorHtmlElement);\n return new Proxy(combined, handler);\n }, [editor]);\n}\n","import { Editor, Node, Path, Range, Text, Element, BasePoint, BaseRange, Point } from \"slate\";\nimport { EditorAutocompleteState } from \"../types/base/editor-autocomplete-state\";\n\nexport interface EditorTextState {\n selection: BaseRange;\n\n textBeforeCursor: string;\n selectedText: string;\n textAfterCursor: string;\n}\n\nexport function getTextAroundCollapsedCursor(editor: Editor): EditorAutocompleteState | null {\n const { selection } = editor;\n if (!selection || !Range.isCollapsed(selection)) {\n return null;\n }\n\n const cursorPoint = selection.anchor;\n\n // Create two ranges: one before the anchor and one after\n const beforeRange: Range = {\n anchor: Editor.start(editor, []),\n focus: cursorPoint,\n };\n const afterRange: Range = {\n anchor: cursorPoint,\n focus: Editor.end(editor, []),\n };\n\n // Extract text for these ranges\n const before = extractTextWithNewlines(editor, beforeRange);\n const after = extractTextWithNewlines(editor, afterRange);\n\n return {\n cursorPoint: cursorPoint,\n textBeforeCursor: before,\n textAfterCursor: after,\n };\n}\n\nexport function getTextAroundSelection(editor: Editor): EditorTextState | null {\n const { selection } = editor;\n if (!selection) {\n return null;\n }\n\n const wellOrderedSelection = wellOrderedRange(selection);\n\n // Create two ranges: one before the anchor and one after\n const beforeRange: Range = {\n anchor: Editor.start(editor, []),\n focus: wellOrderedSelection.anchor,\n };\n const afterRange: Range = {\n anchor: wellOrderedSelection.focus,\n focus: Editor.end(editor, []),\n };\n\n // Extract text for these ranges\n const before = extractTextWithNewlines(editor, beforeRange);\n const after = extractTextWithNewlines(editor, afterRange);\n const selectedText = extractTextWithNewlines(editor, wellOrderedSelection);\n\n return {\n selection: wellOrderedSelection,\n textBeforeCursor: before,\n selectedText,\n textAfterCursor: after,\n };\n}\n\nexport function getFullEditorTextWithNewlines(editor: Editor): string {\n const fullDocumentRange: Range = {\n anchor: Editor.start(editor, []),\n focus: Editor.end(editor, []),\n };\n return extractTextWithNewlines(editor, fullDocumentRange);\n}\n\n// Helper function to extract text with newlines\nexport function extractTextWithNewlines(editor: Editor, range: Range): string {\n const voids = false;\n const [start, end] = Range.edges(range);\n let text = \"\";\n let lastBlock: Node | null = null;\n\n for (const [node, path] of Editor.nodes(editor, {\n at: range,\n match: Text.isText,\n voids,\n })) {\n let t = node.text;\n\n // Determine the parent block of the current text node\n const [block] = Editor.above(editor, {\n at: path,\n match: (n) => Element.isElement(n) && n.type === \"paragraph\",\n }) || [null];\n\n // If we encounter a new block, prepend a newline\n if (lastBlock !== block && block) {\n // check that lastBlock is not null to avoid adding a newline at the beginning\n if (lastBlock) {\n text += \"\\n\";\n }\n lastBlock = block;\n }\n\n if (Path.equals(path, end.path)) {\n t = t.slice(0, end.offset);\n }\n\n if (Path.equals(path, start.path)) {\n t = t.slice(start.offset);\n }\n\n text += t;\n }\n\n return text;\n}\n\nfunction wellOrderedRange(range: BaseRange): BaseRange {\n const { anchor, focus } = range;\n // if anchor is before focus, return range as is\n if (Point.isBefore(anchor, focus)) {\n return range;\n }\n\n // if focus is before anchor, return range with anchor and focus swapped\n return {\n anchor: focus,\n focus: anchor,\n };\n}\n","import { Editor, Transforms } from \"slate\";\n\nexport function replaceEditorText(editor: Editor, newText: string) {\n // clear all previous text\n Transforms.delete(editor, {\n at: {\n anchor: Editor.start(editor, []),\n focus: Editor.end(editor, []),\n },\n });\n\n // insert new text\n if (newText && newText !== \"\") {\n // don't insert empty text - results in strange visual behavior\n Transforms.insertNodes(\n editor,\n [\n {\n type: \"paragraph\",\n children: [{ text: newText }],\n },\n ],\n {\n at: [0],\n },\n );\n }\n}\n","import { BasePoint, Transforms } from \"slate\";\nimport { CustomEditor } from \"../../types/base/custom-editor\";\n\nexport function addAutocompletionsToEditor(\n editor: CustomEditor,\n newSuggestion: string,\n point: BasePoint,\n) {\n const editorPosition = editor.selection;\n\n Transforms.insertNodes(\n editor,\n [\n {\n type: \"suggestion\",\n inline: true,\n content: newSuggestion,\n children: [{ text: \"\" }],\n },\n ],\n {\n at: point,\n },\n );\n\n // restore cursor position\n if (editorPosition) {\n editor.selection = editorPosition;\n }\n}\n","import { Element, Node, Path, Transforms } from \"slate\";\nimport { CustomEditor } from \"../../types/base/custom-editor\";\n\nexport function clearAutocompletionsFromEditor(editor: CustomEditor) {\n // clear previous suggestion\n const paths: Path[] = [];\n for (const [node, path] of Node.nodes(editor)) {\n if (Element.isElement(node) && node.type === \"suggestion\") {\n paths.push(path);\n }\n }\n for (const path of paths) {\n try {\n Transforms.removeNodes(editor, { at: path });\n } catch (e) {\n console.log(\"CopilotTextarea.clearAutocompletionsFromEditor: error removing node\", e);\n }\n }\n}\n","import { BaseCopilotTextareaApiConfig } from \"./autosuggestions-bare-function\";\nimport { defaultCopilotContextCategories } from \"@copilotkit/react-core\";\nimport { isMacOS } from \"@copilotkit/shared\";\n\n/**\n * @interface BaseAutosuggestionsConfig\n *\n * @property {string} textareaPurpose - The purpose of the textarea. This is used to guide the autosuggestions.\n *\n * @property {string[]} contextCategories - The categories of context to consider when providing autosuggestions.\n *\n * @property {number} debounceTime - The amount of time (in milliseconds) to wait before triggering autosuggestions after the user has stopped typing.\n *\n * @property {BaseCopilotTextareaApiConfig} apiConfig - The configuration for the API that provides the autosuggestions.\n *\n * @property {boolean} disableWhenEmpty - Whether to disable autosuggestions when the textarea is empty.\n *\n * @property {boolean} disabled - Whether to disable autosuggestions entirely.\n *\n * @property {boolean} temporarilyDisableWhenMovingCursorWithoutChangingText - Whether to temporarily disable autosuggestions when the user moves the cursor without changing the text.\n *\n * @property {boolean} temporarilyDisableNotTrustedEvents - Temporarily disable autosuggestions after change event from non-trusted sources (like text insertion from autocomplete plugins)\n *\n * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldAcceptAutosuggestionOnKeyPress - A function that determines whether to accept the current autosuggestion based on a key press event. By default, the Tab key is used to accept the autosuggestion. Example code:\n *\n * ```typescript\n * const defaultShouldAcceptAutosuggestionOnKeyPress = (event: React.KeyboardEvent<HTMLDivElement>) => {\n * // if tab, accept the autosuggestion\n * if (event.key === \"Tab\") {\n * return true;\n * }\n * return false;\n * }\n * ```\n *\n * @property {(event: React.TouchEvent<HTMLDivElement>) => boolean} shouldAcceptAutosuggestionOnTouch - A function that determines whether to accept the current autosuggestion based on a mobile touch event. By default, the touching the end of a suggestion will accept it. Example code:\n *\n * ```typescript\n * const shouldAcceptAutosuggestionOnTouch = (event: React.TouchEvent<HTMLDivElement>) => {\n * // if tab, accept the autosuggestion\n * if (event.type === \"touchstart\") {\n * return true;\n * }\n * return false;\n * }\n * ```\n *\n * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldToggleHoveringEditorOnKeyPress - A function that determines whether to toggle the hovering editor based on a key press event. By default, the Command + K key combination is used to toggle the hovering editor. Example code:\n *\n * ```typescript\n * const defaultShouldToggleHoveringEditorOnKeyPress = (event: React.KeyboardEvent<HTMLDivElement>) => {\n * // if command-k, toggle the hovering editor\n * if (event.key === \"k\" && event.metaKey) {\n * return true;\n * }\n * return false;\n * }\n * ```\n */\nexport interface BaseAutosuggestionsConfig {\n textareaPurpose: string;\n contextCategories: string[];\n debounceTime: number;\n apiConfig: BaseCopilotTextareaApiConfig;\n\n disableWhenEmpty: boolean;\n disabled: boolean;\n temporarilyDisableWhenMovingCursorWithoutChangingText: boolean;\n temporarilyDisableNotTrustedEvents: boolean;\n shouldAcceptAutosuggestionOnKeyPress: (event: React.KeyboardEvent<HTMLDivElement>) => boolean;\n shouldAcceptAutosuggestionOnTouch: (event: React.TouchEvent<HTMLDivElement>) => boolean;\n shouldToggleHoveringEditorOnKeyPress: (\n event: React.KeyboardEvent<HTMLDivElement>,\n shortcut: string,\n ) => boolean;\n}\n\n// by default, command-k toggles the hovering editor\nconst defaultShouldToggleHoveringEditorOnKeyPress = (\n event: React.KeyboardEvent<HTMLDivElement>,\n shortcut: string,\n) => {\n const isMetaKey = isMacOS() ? event.metaKey : event.ctrlKey;\n\n // if command-k, toggle the hovering editor\n return event.key === shortcut && isMetaKey;\n};\n\nconst defaultShouldAcceptAutosuggestionOnKeyPress = (\n event: React.KeyboardEvent<HTMLDivElement>,\n) => {\n // if tab, accept the autosuggestion\n if (event.key === \"Tab\") {\n return true;\n }\n return false;\n};\n\nconst defaultShouldAcceptAutosuggestionOnTouch = () => false;\n\n/**\n * Default configuration for the BaseAutosuggestions.\n *\n * @property {number} debounceTime - The amount of time to wait before triggering the autosuggestions API call.\n * @property {string[]} contextCategories - The categories to use for context when making the autosuggestions API call.\n * @property {boolean} disableWhenEmpty - Whether to disable the autosuggestions when the textarea is empty.\n * @property {boolean} disabled - Whether to disable the autosuggestions feature entirely.\n * @property {boolean} temporarilyDisableWhenMovingCursorWithoutChangingText - Whether to temporarily disable the autosuggestions when the cursor is moved without changing the text.\n * @property {boolean} temporarilyDisableNotTrustedEvents - Temporarily disable the autosuggestions after change event from non-trusted sources (like text insertion from autocomplete plugins)\n * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldToggleHoveringEditorOnKeyPress - A function that determines whether to toggle the hovering editor based on a key press event.\n * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldAcceptAutosuggestionOnKeyPress - A function that determines whether to accept the autosuggestion based on a key press event.\n * @property {() => boolean} defaultShouldAcceptAutosuggestionOnTouch - A function that determines whether to accept the autosuggestion based on a mobile touch event.\n */\n\nexport const defaultBaseAutosuggestionsConfig: Omit<\n BaseAutosuggestionsConfig,\n \"textareaPurpose\" | \"apiConfig\"\n> = {\n debounceTime: 250,\n contextCategories: defaultCopilotContextCategories,\n disableWhenEmpty: true,\n disabled: false,\n temporarilyDisableWhenMovingCursorWithoutChangingText: true,\n temporarilyDisableNotTrustedEvents: true,\n shouldToggleHoveringEditorOnKeyPress: defaultShouldToggleHoveringEditorOnKeyPress,\n shouldAcceptAutosuggestionOnKeyPress: defaultShouldAcceptAutosuggestionOnKeyPress,\n shouldAcceptAutosuggestionOnTouch: defaultShouldAcceptAutosuggestionOnTouch,\n};\n","import { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { Editor, Location, Transforms } from \"slate\";\nimport { useSlate, useSlateSelection } from \"slate-react\";\nimport {\n getFullEditorTextWithNewlines,\n getTextAroundSelection,\n} from \"../../lib/get-text-around-cursor\";\nimport {\n EditingEditorState,\n InsertionEditorApiConfig,\n} from \"../../types/base/autosuggestions-bare-function\";\nimport { useHoveringEditorContext } from \"./hovering-editor-provider\";\nimport { Menu, Portal } from \"./hovering-toolbar-components\";\nimport { HoveringInsertionPromptBox } from \"./text-insertion-prompt-box\";\n\nexport interface HoveringToolbarProps {\n apiConfig: InsertionEditorApiConfig;\n contextCategories: string[];\n hoverMenuClassname: string | undefined;\n}\n\nexport const HoveringToolbar = (props: HoveringToolbarProps) => {\n const ref = useRef<HTMLDivElement>(null);\n const editor = useSlate();\n const selection = useSlateSelection();\n const { isDisplayed, setIsDisplayed } = useHoveringEditorContext();\n\n // only render on client\n const [isClient, setIsClient] = useState(false);\n useEffect(() => {\n setIsClient(true);\n }, []);\n\n const isShown = isClient && isDisplayed && selection;\n\n useLayoutEffect(() => {\n const el = ref.current;\n const { selection } = editor;\n\n if (!el || !isShown) {\n return;\n }\n\n if (!selection) {\n el.removeAttribute(\"style\");\n return;\n }\n\n const domSelection = window.getSelection();\n if (!domSelection || domSelection.rangeCount === 0) {\n return;\n }\n\n const domRange = domSelection.getRangeAt(0);\n const rect = domRange.getBoundingClientRect();\n\n // We use window = (0,0,0,0) as a signal that the selection is not in the original copilot-textarea,\n // but inside the hovering window.\n //\n // in such case, we simply do nothing.\n if (rect.top === 0 && rect.left === 0 && rect.width === 0 && rect.height === 0) {\n return;\n }\n\n const verticalOffsetFromCorner = 0;\n const horizontalOffsetFromCorner = 0;\n\n // position the toolbar below the selection\n let top = rect.bottom + window.scrollY + verticalOffsetFromCorner;\n\n // no space left at bottom, move up\n if (rect.bottom + el.offsetHeight > window.innerHeight - verticalOffsetFromCorner) {\n top = rect.top + window.scrollY - el.offsetHeight - verticalOffsetFromCorner;\n }\n\n // position the toolbar in the center of the selection\n let left =\n rect.left + window.scrollX - el.offsetWidth / 2 + rect.width / 2 + horizontalOffsetFromCorner;\n\n // no space left at left, move right\n if (left < horizontalOffsetFromCorner) {\n left = horizontalOffsetFromCorner;\n }\n // no space left at right, move left\n else if (left + el.offsetWidth > window.innerWidth - horizontalOffsetFromCorner) {\n left = window.innerWidth - el.offsetWidth - horizontalOffsetFromCorner;\n }\n\n el.style.opacity = \"1\";\n el.style.position = \"absolute\";\n\n el.style.top = `${top}px`;\n el.style.left = `${left}px`;\n }, [isShown]);\n\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (ref.current && !ref.current.contains(event.target as Node)) {\n setIsDisplayed(false);\n }\n };\n\n document.addEventListener(\"mousedown\", handleClickOutside);\n\n return () => {\n document.removeEventListener(\"mousedown\", handleClickOutside);\n };\n }, [ref, setIsDisplayed]);\n\n if (!isShown) {\n return null;\n }\n\n return (\n <Portal>\n <Menu\n ref={ref}\n className={\n \"copilot-kit-textarea-css-scope \" +\n (props.hoverMenuClassname ||\n \"p-2 absolute z-10 top-[-10000px] left-[-10000px] mt-[-6px] opacity-0 transition-opacity duration-700\")\n }\n data-testid=\"hovering-toolbar\"\n >\n <HoveringInsertionPromptBox\n editorState={editorState(editor, selection)}\n apiConfig={props.apiConfig}\n performInsertion={(insertedText) => {\n // replace the selection with the inserted text\n Transforms.delete(editor, { at: selection });\n Transforms.insertText(editor, insertedText, {\n at: selection,\n });\n setIsDisplayed(false);\n }}\n contextCategories={props.contextCategories}\n />\n </Menu>\n </Portal>\n );\n};\n\nfunction editorState(editor: Editor, selection: Location): EditingEditorState {\n const textAroundCursor = getTextAroundSelection(editor);\n if (textAroundCursor) {\n return textAroundCursor;\n }\n\n return {\n textBeforeCursor: getFullEditorTextWithNewlines(editor),\n textAfterCursor: \"\",\n selectedText: \"\",\n };\n}\n","import { createContext, useState, useContext, ReactNode } from \"react\";\n\ninterface HoveringEditorContextProps {\n isDisplayed: boolean;\n setIsDisplayed: (value: boolean) => void;\n}\n\nconst HoveringEditorContext = createContext<HoveringEditorContextProps>({\n isDisplayed: false,\n setIsDisplayed: () => {},\n});\n\nexport interface HoveringEditorProviderProps {\n children: ReactNode;\n}\n\n/**\n * A context provider for the hovering editor over the `CopilotTextarea`\n * (used to edit and insert text into the `CopilotTextarea`).\n */\nexport const HoveringEditorProvider = ({ children }: HoveringEditorProviderProps) => {\n const [isDisplayed, setIsDisplayed] = useState<boolean>(false);\n\n return (\n <HoveringEditorContext.Provider value={{ isDisplayed, setIsDisplayed }}>\n {children}\n </HoveringEditorContext.Provider>\n );\n};\n\nexport const useHoveringEditorContext = () => useContext(HoveringEditorContext);\n","import { css, cx } from \"@emotion/css\";\nimport React, { PropsWithChildren, Ref } from \"react\";\nimport ReactDOM from \"react-dom\";\n\ninterface BaseProps {\n className?: string;\n [key: string]: unknown;\n}\n\nexport const Button = React.forwardRef<\n HTMLSpanElement,\n PropsWithChildren<{ active: boolean; reversed: boolean } & BaseProps>\n>(({ className, active, reversed, ...props }, ref) => (\n <span\n {...props}\n ref={ref}\n className={cx(\n className as string,\n css`\n cursor: pointer;\n color: ${reversed ? (active ? \"white\" : \"#aaa\") : active ? \"black\" : \"#ccc\"};\n `,\n )}\n />\n));\n\nexport const Icon = React.forwardRef<HTMLSpanElement, PropsWithChildren<BaseProps>>(\n ({ className, ...props }, ref) => (\n <span\n {...props}\n ref={ref}\n className={cx(\n \"material-icons\",\n className as string,\n css`\n font-size: 18px;\n vertical-align: text-bottom;\n `,\n )}\n />\n ),\n);\n\nexport const Menu = React.forwardRef<HTMLDivElement, PropsWithChildren<BaseProps>>(\n ({ className, ...props }, ref) => {\n return (\n <div\n {...props}\n data-testid=\"menu\"\n ref={ref}\n className={cx(\n className as string,\n css`\n & > * {\n display: inline-block;\n }\n\n & > * + * {\n margin-left: 15px;\n }\n `,\n )}\n />\n );\n },\n);\nexport const Portal = ({ children }: { children: React.ReactNode }) => {\n return typeof document === \"object\" ? ReactDOM.createPortal(children, document.body) : null;\n};\n\nexport const Toolbar = React.forwardRef<HTMLDivElement, PropsWithChildren<BaseProps>>(\n ({ className, ...props }, ref) => (\n <Menu\n {...props}\n ref={ref}\n className={cx(\n className as string,\n css`\n position: relative;\n padding: 1px 18px 17px;\n margin: 0 -20px;\n border-bottom: 2px solid #eee;\n margin-bottom: 20px;\n `,\n )}\n />\n ),\n);\n","import { Ref, RefObject, useEffect } from \"react\";\n\n// Updates the height of a <textarea> when the value changes.\nconst useAutosizeTextArea = (textAreaRef: RefObject<HTMLTextAreaElement | null>, value: string) => {\n useEffect(() => {\n if (textAreaRef.current !== null) {\n // We need to reset the height momentarily to get the correct scrollHeight for the textarea\n textAreaRef.current.style.height = \"0px\";\n const scrollHeight = textAreaRef.current.scrollHeight;\n\n // We then set the height directly, outside of the render loop\n // Trying to set this with state or a ref will product an incorrect value.\n textAreaRef.current.style.height = scrollHeight + \"px\";\n }\n }, [textAreaRef, value]);\n};\n\nexport default useAutosizeTextArea;\n","import { useState } from \"react\";\nimport {\n Command,\n CommandDialog,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n CommandSeparator,\n CommandShortcut,\n} from \"../ui/command\";\n\nimport { Calculator, Calendar, CreditCard, Settings, Smile, User } from \"lucide-react\";\n\nimport { DocumentPointer } from \"@copilotkit/react-core\";\n\nexport interface SourceSearchBoxProps {\n searchTerm: string;\n suggestedFiles: DocumentPointer[];\n onSelectedFile: (filePointer: DocumentPointer) => void;\n}\n\nexport function SourceSearchBox(props: SourceSearchBoxProps) {\n const [selectedValue, setSelectedValue] = useState<string>(\"\");\n\n return (\n <Command\n className=\"rounded-lg border shadow-md\"\n value={selectedValue}\n onValueChange={(value) => {\n setSelectedValue(value);\n }}\n filter={(value, search) => {\n // if the search term is empty, show all commands\n if (props.searchTerm === \"\") return 1;\n\n // if the search term is a prefix of the command, show it\n if (value.startsWith(props.searchTerm)) return 1;\n\n // otherwise, don't show it\n return 0;\n }}\n >\n <CommandInput\n value={props.searchTerm}\n className=\"rounded-t-lg hidden\"\n placeholder=\"Search for a command...\"\n />\n <CommandList>\n <CommandEmpty>No results found.</CommandEmpty>\n\n <CommandGroup heading=\"Available resources\">\n {props.suggestedFiles.map((filePointer) => {\n return (\n <CommandItem\n key={`word-${filePointer.sourceApplication}.${filePointer.name}`}\n value={filePointer.name}\n onSelect={(value) => {\n props.onSelectedFile(filePointer);\n }}\n >\n <div className=\" px-3 flex flex-row gap-1 items-center\">\n <Logo width=\"20px\" height=\"20px\">\n <img\n src={filePointer.iconImageUri}\n alt={filePointer.sourceApplication}\n className=\"w-full h-full\"\n />\n </Logo>\n {filePointer.name}\n </div>\n </CommandItem>\n );\n })}\n </CommandGroup>\n\n {/* <CommandGroup heading=\"Suggestions\">\n <CommandItem\n onSelect={(value) => {\n console.log(value);\n console.log(value);\n }}\n >\n <Calendar className=\"mr-2 h-4 w-4\" />\n <span>Calendar</span>\n </CommandItem>\n <CommandItem>\n <Smile className=\"mr-2 h-4 w-4\" />\n <span>Search Emoji</span>\n </CommandItem>\n <CommandItem>\n <Calculator className=\"mr-2 h-4 w-4\" />\n <span>Calculator</span>\n </CommandItem>\n </CommandGroup> */}\n <CommandSeparator />\n </CommandList>\n </Command>\n );\n}\n\nexport function Logo({\n children,\n width,\n height,\n}: {\n children: React.ReactNode;\n width: string;\n height: string;\n}) {\n return (\n <div className=\"flex items-center justify-center\" style={{ width: width, height: height }}>\n {children}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { DialogProps } from \"@radix-ui/react-dialog\";\nimport { Command as CommandPrimitive } from \"cmdk\";\nimport { cn } from \"../../lib/utils\";\nimport { Dialog, DialogContent } from \"./dialog\";\n\nconst Command = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive\n ref={ref}\n className={cn(\n \"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground\",\n className,\n )}\n {...props}\n />\n));\nCommand.displayName = CommandPrimitive.displayName;\n\ninterface CommandDialogProps extends DialogProps {}\n\nconst CommandDialog = ({ children, ...props }: CommandDialogProps) => {\n return (\n <Dialog {...props}>\n <DialogContent className=\"overflow-hidden p-0 shadow-lg\">\n <Command className=\"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5\">\n {children}\n </Command>\n </DialogContent>\n </Dialog>\n );\n};\n\nconst CommandInput = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Input>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>\n>(({ className, ...props }, ref) => (\n <div className=\"flex items-center border-b px-3\" cmdk-input-wrapper=\"\">\n {/* <Search className=\"mr-2 h-4 w-4 shrink-0 opacity-50\" /> */}\n <CommandPrimitive.Input\n ref={ref}\n className={cn(\n \"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50\",\n className,\n )}\n {...props}\n />\n </div>\n));\n\nCommandInput.displayName = CommandPrimitive.Input.displayName;\n\nconst CommandList = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.List>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive.List\n ref={ref}\n className={cn(\"max-h-[300px] overflow-y-auto overflow-x-hidden pb-2\", className)}\n {...props}\n />\n));\n\nCommandList.displayName = CommandPrimitive.List.displayName;\n\nconst CommandEmpty = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Empty>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>\n>((props, ref) => (\n <CommandPrimitive.Empty ref={ref} className=\"py-6 text-center text-sm\" {...props} />\n));\n\nCommandEmpty.displayName = CommandPrimitive.Empty.displayName;\n\nconst CommandGroup = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Group>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive.Group\n ref={ref}\n className={cn(\n \"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground\",\n className,\n )}\n {...props}\n />\n));\n\nCommandGroup.displayName = CommandPrimitive.Group.displayName;\n\nconst CommandSeparator = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Separator>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive.Separator\n ref={ref}\n className={cn(\"-mx-1 h-px bg-border\", className)}\n {...props}\n />\n));\nCommandSeparator.displayName = CommandPrimitive.Separator.displayName;\n\nconst CommandItem = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Item>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive.Item\n ref={ref}\n className={cn(\n \"relative flex cursor-default select-none items-center rounded-sm text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n className,\n )}\n {...props}\n />\n));\n\nCommandItem.displayName = CommandPrimitive.Item.displayName;\n\nconst CommandShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {\n return (\n <span\n className={cn(\"ml-auto text-xs tracking-widest text-muted-foreground\", className)}\n {...props}\n />\n );\n};\nCommandShortcut.displayName = \"CommandShortcut\";\n\nexport {\n Command,\n CommandDialog,\n CommandInput,\n CommandList,\n CommandEmpty,\n CommandGroup,\n CommandItem,\n CommandShortcut,\n CommandSeparator,\n};\n","import useAutosizeTextArea from \"../../../hooks/misc/use-autosize-textarea\";\nimport {\n EditingEditorState,\n Generator_InsertionOrEditingSuggestion,\n} from \"../../../types/base/autosuggestions-bare-function\";\nimport { SourceSearchBox } from \"../../source-search-box/source-search-box\";\nimport { DocumentPointer, useCopilotContext } from \"@copilotkit/react-core\";\nimport { Button } from \"../../ui/button\";\nimport { Label } from \"../../ui/label\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { streamPromiseFlatten } from \"../../../lib/stream-promise-flatten\";\nimport { IncludedFilesPreview } from \"./included-files-preview\";\nimport { useHoveringEditorContext } from \"../hovering-editor-provider\";\n\nexport type SuggestionState = {\n editorState: EditingEditorState;\n};\n\nexport interface HoveringInsertionPromptBoxCoreProps {\n state: SuggestionState;\n performInsertion: (insertedText: string) => void;\n insertionOrEditingFunction: Generator_InsertionOrEditingSuggestion;\n contextCategories: string[];\n}\n\nexport const HoveringInsertionPromptBoxCore = ({\n performInsertion,\n state,\n insertionOrEditingFunction,\n contextCategories,\n}: HoveringInsertionPromptBoxCoreProps) => {\n const { getDocumentsContext } = useCopilotContext();\n\n const [editSuggestion, setEditSuggestion] = useState<string>(\"\");\n const [suggestionIsLoading, setSuggestionIsLoading] = useState<boolean>(false);\n\n const [adjustmentPrompt, setAdjustmentPrompt] = useState<string>(\"\");\n\n const [generatingSuggestion, setGeneratingSuggestion] = useState<ReadableStream<string> | null>(\n null,\n );\n\n const adjustmentTextAreaRef = useRef<HTMLTextAreaElement>(null);\n const suggestionTextAreaRef = useRef<HTMLTextAreaElement>(null);\n\n const [filePointers, setFilePointers] = useState<DocumentPointer[]>([]);\n\n const [suggestedFiles, setSuggestedFiles] = useState<DocumentPointer[]>([]);\n useEffect(() => {\n setSuggestedFiles(getDocumentsContext(contextCategories));\n }, [contextCategories, getDocumentsContext]);\n\n useAutosizeTextArea(suggestionTextAreaRef, editSuggestion || \"\");\n useAutosizeTextArea(adjustmentTextAreaRef, adjustmentPrompt || \"\");\n\n // initially focus on the adjustment prompt text area\n useEffect(() => {\n adjustmentTextAreaRef.current?.focus();\n }, []);\n\n // continuously read the generating suggestion stream and update the edit suggestion\n useEffect(() => {\n // if no generating suggestion, do nothing\n if (!generatingSuggestion) {\n return;\n }\n\n // Check if the stream is already locked (i.e. already reading from it)\n if (generatingSuggestion.locked) {\n return;\n }\n\n // reset the edit suggestion\n setEditSuggestion(\"\");\n\n // read the generating suggestion stream and continuously update the edit suggestion\n const reader = generatingSuggestion.getReader();\n const read = async () => {\n setSuggestionIsLoading(true);\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n setEditSuggestion((prev) => {\n const newSuggestion = prev + value;\n\n // Scroll to the bottom of the textarea. We call this here to make sure scroll-to-bottom is synchronous with the state update.\n if (suggestionTextAreaRef.current) {\n suggestionTextAreaRef.current.scrollTop = suggestionTextAreaRef.current.scrollHeight;\n }\n return newSuggestion;\n });\n }\n\n setSuggestionIsLoading(false);\n };\n read();\n\n return () => {\n // release the lock if the reader is not closed on unmount\n const releaseLockIfNotClosed = async () => {\n try {\n await reader.closed;\n } catch {\n reader.releaseLock();\n }\n };\n\n releaseLockIfNotClosed();\n };\n }, [generatingSuggestion]);\n\n // generate an adjustment to the completed text, based on the adjustment prompt\n const beginGeneratingAdjustment = useCallback(async () => {\n // don't generate text if the prompt is empty\n if (!adjustmentPrompt.trim()) {\n return;\n }\n\n // editor state includes the text being edited, and the text before/after the selection\n // if the current edit suggestion is not empty, then use *it* as the \"selected text\" - instead of the editor state's selected text\n let modificationState = state.editorState;\n if (editSuggestion !== \"\") {\n modificationState.selectedText = editSuggestion;\n }\n\n // generate the adjustment suggestion\n const adjustmentSuggestionTextStreamPromise = insertionOrEditingFunction(\n modificationState,\n adjustmentPrompt,\n filePointers,\n new AbortController().signal,\n );\n const adjustmentSuggestionTextStream = streamPromiseFlatten(\n adjustmentSuggestionTextStreamPromise,\n );\n\n setGeneratingSuggestion(adjustmentSuggestionTextStream);\n }, [\n adjustmentPrompt,\n editSuggestion,\n state.editorState,\n insertionOrEditingFunction,\n filePointers,\n ]);\n\n const isLoading = suggestionIsLoading;\n\n const textToEdit = editSuggestion || state.editorState.selectedText;\n const adjustmentLabel =\n textToEdit === \"\"\n ? \"Describe the text you want to insert\"\n : \"Describe adjustments to the suggested text\";\n const placeholder =\n textToEdit === \"\"\n ? \"e.g. 'summarize the client's top 3 pain-points from @CallTranscript'\"\n : \"e.g. 'make it more formal', 'be more specific', ...\";\n\n const { setIsDisplayed } = useHoveringEditorContext();\n\n const AdjustmentPromptComponent = (\n <>\n <Label className=\"\">{adjustmentLabel}</Label>\n <div className=\"relative w-full flex items-center\">\n <textarea\n data-testid=\"adjustment-prompt\"\n disabled={suggestionIsLoading}\n ref={adjustmentTextAreaRef}\n value={adjustmentPrompt}\n onChange={(e) => setAdjustmentPrompt(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && e.shiftKey) {\n e.preventDefault();\n setAdjustmentPrompt(adjustmentPrompt + \"\\n\");\n } else if (e.key === \"Enter\") {\n e.preventDefault();\n beginGeneratingAdjustment();\n }\n }}\n placeholder={placeholder}\n style={{ minHeight: \"3rem\" }}\n className=\"w-full bg-slate-100 h-auto h-min-14 text-sm p-2 rounded-md resize-none overflow-visible focus:outline-none focus:ring-0 focus:border-non pr-[3rem]\"\n rows={1}\n />\n <button\n onClick={beginGeneratingAdjustment}\n className=\"absolute right-2 bg-blue-500 text-white w-8 h-8 rounded-full flex items-center justify-center\"\n data-testid=\"generate-button\"\n >\n <i className=\"material-icons\">arrow_forward</i>\n </button>\n </div>\n </>\n );\n\n const SuggestionComponent = (\n <>\n <div className=\"flex justify-between items-end w-full\">\n <Label className=\"mt-4\">Suggested:</Label>\n <div className=\"ml-auto\">\n {isLoading && (\n <div className=\"flex justify-center items-center\">\n <div\n className=\"inline-block h-4 w-4 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]\"\n role=\"status\"\n >\n <span className=\"!absolute !-m-px !h-px !w-px !overflow-hidden !whitespace-nowrap !border-0 !p-0 ![clip:rect(0,0,0,0)]\">\n Loading...\n </span>\n </div>\n </div>\n )}\n </div>\n </div>\n <textarea\n data-testid=\"suggestion-result\"\n ref={suggestionTextAreaRef}\n value={editSuggestion}\n disabled={suggestionIsLoading}\n onChange={(e) => setEditSuggestion(e.target.value)}\n className=\"w-full text-base p-2 border border-gray-300 rounded-md resize-none bg-green-50\"\n style={{ overflow: \"auto\", maxHeight: \"10em\" }}\n />\n </>\n );\n\n const SubmitComponent = (\n <div className=\"flex w-full gap-4 justify-start\">\n <Button\n data-testid=\"insert-button\"\n className=\" bg-green-700 text-white\"\n onClick={() => {\n performInsertion(editSuggestion);\n }}\n >\n Insert <i className=\"material-icons\">check</i>\n </Button>\n </div>\n );\n\n // show source search if the last word in the adjustment prompt BEGINS with an @\n const sourceSearchCandidate = adjustmentPrompt.split(\" \").pop();\n // if the candidate is @someCandidate, then 'someCandidate', otherwise undefined\n const sourceSearchWord = sourceSearchCandidate?.startsWith(\"@\")\n ? sourceSearchCandidate.slice(1)\n : undefined;\n\n return (\n <div className=\"w-full flex flex-col items-start relative gap-2\">\n {AdjustmentPromptComponent}\n {filePointers.length > 0 && (\n <IncludedFilesPreview includedFiles={filePointers} setIncludedFiles={setFilePointers} />\n )}\n {sourceSearchWord !== undefined && (\n <SourceSearchBox\n searchTerm={sourceSearchWord}\n suggestedFiles={suggestedFiles}\n onSelectedFile={(filePointer) => {\n setAdjustmentPrompt(adjustmentPrompt.replace(new RegExp(`@${sourceSearchWord}$`), \"\"));\n setFilePointers((prev) => [...prev, filePointer]);\n\n // focus back on the adjustment prompt, and move the cursor to the end\n adjustmentTextAreaRef.current?.focus();\n }}\n />\n )}\n {generatingSuggestion ? SuggestionComponent : null}\n {generatingSuggestion ? SubmitComponent : null}\n </div>\n );\n};\n","import * as React from \"react\";\nimport { Slot } from \"@radix-ui/react-slot\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\n\nimport { cn } from \"../../lib/utils\";\n\nconst buttonVariants = cva(\n \"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n destructive: \"bg-destructive text-destructive-foreground hover:bg-destructive/90\",\n outline: \"border border-input bg-background hover:bg-accent hover:text-accent-foreground\",\n secondary: \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n ghost: \"hover:bg-accent hover:text-accent-foreground\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default: \"h-10 px-4 py-2\",\n sm: \"h-9 rounded-md px-3\",\n lg: \"h-11 rounded-md px-8\",\n icon: \"h-10 w-10\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n },\n);\n\nexport interface ButtonProps\n extends React.ButtonHTMLAttributes<HTMLButtonElement>,\n VariantProps<typeof buttonVariants> {\n asChild?: boolean;\n}\n\nconst Button = React.forwardRef<HTMLButtonElement, ButtonProps>(\n ({ className, variant, size, asChild = false, ...props }, ref) => {\n const Comp = asChild ? Slot : \"button\";\n return (\n <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />\n );\n },\n);\nButton.displayName = \"Button\";\n\nexport { Button, buttonVariants };\n","import * as React from \"react\";\nimport * as LabelPrimitive from \"@radix-ui/react-label\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\n\nimport { cn } from \"../../lib/utils\";\n\nconst labelVariants = cva(\n \"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70\",\n);\n\nconst Label = React.forwardRef<\n React.ElementRef<typeof LabelPrimitive.Root>,\n React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>\n>(({ className, ...props }, ref) => (\n <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />\n));\nLabel.displayName = LabelPrimitive.Root.displayName;\n\nexport { Label };\n","/**\n * Flatten a promise of a stream, into a stream.\n *\n * Useful because a stream already includes the notion of async value delivery,\n * so it often makes sense to simply await the values rather than the generator of the values.\n *\n * @param {Promise<ReadableStream<A>>} promise - The promise to flatten.\n * @returns {ReadableStream<A>} - The flattened stream.\n */\n\nexport function streamPromiseFlatten<A>(promise: Promise<ReadableStream<A>>): ReadableStream<A> {\n return new ReadableStream<A>({\n async start(controller) {\n try {\n const stream = await promise;\n const reader = stream.getReader();\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n controller.close();\n return;\n }\n\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n },\n });\n}\n","import { DocumentPointer } from \"@copilotkit/react-core\";\nimport { Label } from \"../../ui/label\";\nimport React from \"react\";\nimport Chip from \"@mui/material/Chip/Chip.js\";\nimport Avatar from \"@mui/material/Avatar/Avatar.js\";\n\nexport interface IncludedFilesPreviewProps {\n includedFiles: DocumentPointer[];\n setIncludedFiles: React.Dispatch<React.SetStateAction<DocumentPointer[]>>;\n}\n\nexport const IncludedFilesPreview = ({\n includedFiles,\n setIncludedFiles,\n}: IncludedFilesPreviewProps) => {\n return (\n <div className=\"flex flex-col gap-2 mt-2\">\n <Label className=\"\">Included context:</Label>\n <div className=\"flex flex-wrap gap-2\">\n {includedFiles.map((filePointer, index) => {\n return (\n <FileChipPreview\n key={`file-${filePointer.sourceApplication}.${filePointer.name}`}\n filePointer={filePointer}\n onDelete={() => {\n setIncludedFiles((prev) => prev.filter((fp) => fp !== filePointer));\n }}\n />\n );\n })}\n </div>\n </div>\n );\n};\n\nexport interface FileChipPreviewProps {\n filePointer: DocumentPointer;\n onDelete: () => void;\n}\n\nexport const FileChipPreview = ({ filePointer, onDelete }: FileChipPreviewProps) => {\n return (\n <Chip\n label={filePointer.name}\n onDelete={onDelete}\n avatar={\n <Avatar\n src={filePointer.iconImageUri}\n alt={filePointer.sourceApplication}\n sx={{ backgroundColor: \"transparent\" }}\n ></Avatar>\n }\n />\n );\n};\n","import { HoveringInsertionPromptBoxCore } from \"./hovering-insertion-prompt-box-core\";\nimport {\n EditingEditorState,\n InsertionEditorApiConfig,\n} from \"../../../types/base/autosuggestions-bare-function\";\n\nexport interface Props {\n editorState: EditingEditorState;\n apiConfig: InsertionEditorApiConfig;\n performInsertion: (insertedText: string) => void;\n contextCategories: string[];\n}\n\nexport const HoveringInsertionPromptBox = (props: Props) => {\n return (\n <div\n className=\"flex flex-col justify-center items-center space-y-4 rounded-md border shadow-lg p-4 border-gray- bg-white\"\n style={{ width: \"35rem\" }}\n >\n <HoveringInsertionPromptBoxCore\n state={{\n editorState: props.editorState,\n }}\n insertionOrEditingFunction={props.apiConfig.insertionOrEditingFunction}\n performInsertion={props.performInsertion}\n contextCategories={props.contextCategories}\n />\n </div>\n );\n};\n","import { RenderElementProps } from \"slate-react\";\nimport React from \"react\";\n\nexport type RenderElementFunction = (props: RenderElementProps) => React.JSX.Element;\n\nexport function makeRenderElementFunction(\n suggestionsStyle: React.CSSProperties,\n): RenderElementFunction {\n return (props: RenderElementProps) => {\n switch (props.element.type) {\n case \"paragraph\":\n return <DefaultElement {...props} />;\n case \"suggestion\":\n return <SuggestionElement {...props} suggestionsStyle={suggestionsStyle} />;\n }\n };\n}\n\nconst DefaultElement = (props: RenderElementProps) => {\n return <div {...props.attributes}>{props.children}</div>;\n};\nconst SuggestionElement = (\n props: RenderElementProps & {\n suggestionsStyle: React.CSSProperties;\n },\n) => {\n return (\n <span\n {...props.attributes}\n style={{\n ...props.suggestionsStyle,\n }}\n data-testid=\"suggestion\"\n contentEditable={false}\n >\n {props.children /* https://github.com/ianstormtaylor/slate/issues/3930 */}\n {props.element.type === \"suggestion\" && props.element.content}\n </span>\n );\n};\n","import { RenderPlaceholderProps } from \"slate-react\";\nimport React from \"react\";\n\nexport type RenderPlaceholderFunction = (props: RenderPlaceholderProps) => React.JSX.Element;\n\nexport function makeRenderPlaceholderFunction(\n placeholderStyle?: React.CSSProperties,\n): RenderPlaceholderFunction {\n return (props: RenderPlaceholderProps) => {\n const { style, ...restAttributes } = props.attributes;\n\n return (\n <div\n {...restAttributes}\n style={{\n ...style,\n ...placeholderStyle,\n }}\n >\n {props.children}\n </div>\n );\n };\n}\n","import { useEffect } from \"react\";\n\nexport function useAddBrandingCss(\n suggestionStyleAugmented: React.CSSProperties,\n disableBranding: boolean | undefined,\n) {\n const cssSelector = \".copilot-textarea.with-branding\";\n useEffect(() => {\n if (disableBranding) {\n return;\n }\n\n // ---\n // 1: Add the CSS to the DOM\n const styleEl = document.createElement(\"style\");\n styleEl.id = \"dynamic-styles\";\n\n // Build the CSS string dynamically\n let dynamicStyles = Object.entries(suggestionStyleAugmented)\n .map(([key, value]) => {\n const kebabCaseKey = key.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, \"$1-$2\").toLowerCase();\n return `${kebabCaseKey}: ${value};`;\n })\n .join(\" \");\n\n // Append overrides for italics and font-size\n dynamicStyles += `font-style: normal; font-size: x-small;`;\n dynamicStyles += `content: \"CopilotKit\";`;\n dynamicStyles += `bottom: 6px;`;\n dynamicStyles += `right: 6px;`;\n dynamicStyles += `pointer-events: none;`;\n dynamicStyles += `font-weight: 200;`;\n dynamicStyles += `padding: 0;`;\n dynamicStyles += `margin: 0;`;\n dynamicStyles += `border: 0;`;\n dynamicStyles += `line-height: 1;`;\n dynamicStyles += `position: absolute;`;\n\n // Append it to the ::after class\n styleEl.innerHTML = `\n ${cssSelector}::after {\n ${dynamicStyles}\n }\n `;\n\n document.head.appendChild(styleEl);\n\n // ---\n // 2: Add the scroll listener (to keep the branding in the bottom right as the textarea scrolls)\n const textarea = document.querySelector(cssSelector);\n const handleScroll = () => {\n const styleEl = document.getElementById(\"dynamic-styles\");\n if (styleEl && textarea) {\n const offsetFromBottom = -textarea.scrollTop + 6;\n const offsetFromRight = -textarea.scrollLeft + 6;\n styleEl.innerHTML = `\n ${cssSelector}::after {\n ${dynamicStyles}\n bottom: ${offsetFromBottom}px;\n right: ${offsetFromRight}px;\n }\n `;\n }\n };\n\n textarea?.addEventListener(\"scroll\", handleScroll);\n\n // Cleanup\n return () => {\n document.getElementById(\"dynamic-styles\")?.remove();\n textarea?.removeEventListener(\"scroll\", handleScroll);\n };\n }, [disableBranding, suggestionStyleAugmented]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { BaseSelection } from \"slate\";\nimport { useSlateSelector } from \"slate-react\";\nimport { Range } from \"slate\";\nimport { editorToText } from \"../../lib/editor-to-text\";\n\ninterface TrackerTextEditedSinceLastCursorMovementProps {\n setCursorMovedSinceLastTextChange: (value: boolean) => void;\n}\nexport function TrackerTextEditedSinceLastCursorMovement(\n props: TrackerTextEditedSinceLastCursorMovementProps,\n) {\n const cursorState: RelevantEditorState = useSlateSelector((state) => ({\n selection: state.selection,\n text: editorToText(state),\n }));\n\n const previousState = usePrevious(cursorState);\n\n useEffect(() => {\n if (!previousState) {\n return;\n }\n\n if (cursorChangedWithoutTextChanged(previousState, cursorState)) {\n props.setCursorMovedSinceLastTextChange(true);\n }\n }, [props.setCursorMovedSinceLastTextChange, cursorState]);\n\n return <></>;\n}\n\ntype RelevantEditorState = {\n selection: BaseSelection;\n text: string;\n};\n\nconst cursorChangedWithoutTextChanged = (\n prev: RelevantEditorState,\n next: RelevantEditorState,\n): boolean => {\n // Check if the selection has changed\n const isSelectionChanged = !isSelectionEqual(prev.selection, next.selection);\n\n // Check if the text content remains the same\n const isTextSame = prev.text === next.text;\n\n return isSelectionChanged && isTextSame;\n};\n\nconst isSelectionEqual = (a: BaseSelection, b: BaseSelection) => {\n if (!a && !b) return true;\n if (!a || !b) return false;\n return Range.equals(a, b);\n};\n\n/**\n * Easily keep track of the *previous* value of a variable.\n *\n * Example:\n * ```\n * const [count, setCount] = useState(0);\n * const prevCount = usePrevious(count);\n *\n * useEffect(() => {\n * if (count > prevCount) {\n * console.log('Now I know that count is bigger than before');\n * }\n * }, [count, prevCount]);\n * ```\n */\nfunction usePrevious<T>(value: T): T | undefined {\n const ref = useRef<T>(undefined!);\n\n useEffect(() => {\n ref.current = value;\n });\n\n return ref.current;\n}\n","import { BaseEditor, Descendant, Element } from \"slate\";\nimport { HistoryEditor } from \"slate-history\";\nimport { ReactEditor } from \"slate-react\";\nimport { SuggestionAwareText } from \"../types/base/custom-editor\";\n\nfunction nodeChildrenToTextComponents(\n editor: BaseEditor & ReactEditor & HistoryEditor,\n nodes: Descendant[],\n): SuggestionAwareText[] {\n // find inlineable elements\n const indeciesOfInlineElements = new Set(\n nodes\n .map((node, index) => {\n if (Element.isElement(node) && editor.isInline(node)) {\n return index;\n }\n return -1;\n })\n .filter((index) => index !== -1),\n );\n\n // ignorable elements = inline elements,\n // or neighbors of inline elements that are {text: \"\"}\n const nonIgnorableItems = nodes.filter((node, index) => {\n const isInline = indeciesOfInlineElements.has(index);\n if (isInline) {\n return false;\n }\n\n const isNeighbourOfInline =\n indeciesOfInlineElements.has(index - 1) || indeciesOfInlineElements.has(index + 1);\n if (isNeighbourOfInline) {\n return (node as any).text !== \"\";\n }\n\n return true;\n });\n\n return nonIgnorableItems\n .map((node) => {\n if (Element.isElement(node)) {\n switch (node.type) {\n case \"paragraph\":\n return nodeChildrenToTextComponents(editor, node.children);\n case \"suggestion\":\n return [];\n }\n } else {\n return [node];\n }\n })\n .reduce((acc, val) => acc.concat(val), []);\n}\n\nexport const editorToText = (editor: BaseEditor & ReactEditor & HistoryEditor) => {\n const flattened = nodeChildrenToTextComponents(editor, editor.children);\n\n const text = flattened.map((textComponent) => textComponent.text).join(\"\\n\");\n\n return text;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAAiE;AACjE,IAAAC,iBAAmC;AACnC,IAAAC,sBAAgC;AAChC,IAAAC,yBAAwB;;;ACHxB,mBAA0D;;;ACEnD,IAAM,YAAN,MAAiC;AAAA,EAItC,YAAoB,MAAc;AAAd;AAEpB,oBAAW,CAAO,SAA2B,SAAY;AAEvD,WAAK,OAAO;AAEZ,WAAK,YAAY,WAAW,MAAY;AACtC,YAAI;AACF,eAAK,wBAAwB,IAAI,gBAAgB;AAGjD,gBAAM,KAAK,GAAG,MAAM,KAAK,sBAAsB,MAAM;AAErD,eAAK,wBAAwB;AAAA,QAC/B,SAAS,OAAP;AAAA,QAAe;AAAA,MACnB,IAAG,KAAK,IAAI;AAAA,IACd;AAEA,kBAAS,MAAM;AACb,UAAI,KAAK,uBAAuB;AAC9B,aAAK,sBAAsB,MAAM;AACjC,aAAK,wBAAwB;AAAA,MAC/B;AAEA,UAAI,KAAK,cAAc,QAAW;AAChC,qBAAa,KAAK,SAAS;AAC3B,aAAK,YAAY;AAAA,MACnB;AAAA,IACF;AAAA,EA5BmC;AA6BrC;;;ACnCA,kBAAsC;AACtC,4BAAwB;AAEjB,SAAS,MAAM,QAAsB;AAC1C,aAAO,mCAAQ,kBAAK,MAAM,CAAC;AAC7B;AA8BO,IAAM,iBAAiB,CAAC,MAAgB,SAC7C,KAAK,WAAW,KAAK,UAA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import_react","import_slate","import_slate_react","import_tailwind_merge","import_react","import_slate","shouldSave","editor","import_react","import_slate_react","import_slate","import_slate","React","customMethods","editorHtmlElement","editor","import_slate","import_slate","import_react","import_slate","import_slate_react","import_react","import_react","import_jsx_runtime","React","ReactDOM","import_react","import_react","React","import_jsx_runtime","CommandPrimitive","CommandPrimitive","import_jsx_runtime","import_react_core","React","import_jsx_runtime","Button","React","import_class_variance_authority","import_jsx_runtime","import_react","import_jsx_runtime","Chip","Avatar","import_jsx_runtime","Button","import_jsx_runtime","import_jsx_runtime","selection","import_jsx_runtime","import_jsx_runtime","import_react","styleEl","import_react","import_slate_react","import_slate","import_slate","import_jsx_runtime","import_jsx_runtime","React","_a","value"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/index.ts","../../src/components/base-copilot-textarea/base-copilot-textarea.tsx","../../src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts","../../src/lib/debouncer.ts","../../src/lib/utils.ts","../../src/types/base/editor-autocomplete-state.ts","../../src/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.tsx","../../src/lib/slatejs-edits/with-partial-history.ts","../../src/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.ts","../../src/lib/get-text-around-cursor.ts","../../src/lib/slatejs-edits/replace-text.ts","../../src/lib/slatejs-edits/add-autocompletions.ts","../../src/lib/slatejs-edits/clear-autocompletions.ts","../../src/types/base/base-autosuggestions-config.tsx","../../src/components/hovering-toolbar/hovering-toolbar.tsx","../../src/components/hovering-toolbar/hovering-editor-provider.tsx","../../src/components/hovering-toolbar/hovering-toolbar-components.tsx","../../src/hooks/misc/use-autosize-textarea.tsx","../../src/components/source-search-box/source-search-box.tsx","../../src/components/ui/command.tsx","../../src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.tsx","../../src/components/ui/button.tsx","../../src/components/ui/label.tsx","../../src/lib/stream-promise-flatten.ts","../../src/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.tsx","../../src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.tsx","../../src/components/base-copilot-textarea/render-element.tsx","../../src/components/base-copilot-textarea/render-placeholder.tsx","../../src/components/base-copilot-textarea/use-add-branding-css.tsx","../../src/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.tsx","../../src/lib/editor-to-text.ts","../../src/components/copilot-textarea/copilot-textarea.tsx","../../src/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.tsx","../../src/lib/retry.tsx","../../src/types/autosuggestions-config/suggestions-api-config.tsx","../../src/types/autosuggestions-config/insertions-api-config.tsx","../../src/types/autosuggestions-config/editing-api-config.tsx","../../src/types/autosuggestions-config/autosuggestions-config.tsx","../../src/hooks/make-autosuggestions-function/use-make-standard-insertion-function.tsx"],"sourcesContent":["export { BaseCopilotTextarea } from \"./base-copilot-textarea/base-copilot-textarea\";\n\nexport { CopilotTextarea } from \"./copilot-textarea/copilot-textarea\";\nexport type { CopilotTextareaProps } from \"./copilot-textarea/copilot-textarea\";\n","import React, { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Descendant, Editor } from \"slate\";\nimport { Editable, Slate } from \"slate-react\";\nimport { twMerge } from \"tailwind-merge\";\nimport { useAutosuggestions } from \"../../hooks/base-copilot-textarea-implementation/use-autosuggestions\";\nimport { useCopilotTextareaEditor } from \"../../hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor\";\nimport { usePopulateCopilotTextareaRef } from \"../../hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref\";\nimport {\n getFullEditorTextWithNewlines,\n getTextAroundCollapsedCursor,\n} from \"../../lib/get-text-around-cursor\";\nimport { addAutocompletionsToEditor } from \"../../lib/slatejs-edits/add-autocompletions\";\nimport { clearAutocompletionsFromEditor } from \"../../lib/slatejs-edits/clear-autocompletions\";\nimport { replaceEditorText } from \"../../lib/slatejs-edits/replace-text\";\nimport { BaseAutosuggestionsConfig, defaultBaseAutosuggestionsConfig } from \"../../types/base\";\nimport { AutosuggestionState } from \"../../types/base/autosuggestion-state\";\nimport { BaseCopilotTextareaProps } from \"../../types/base/base-copilot-textarea-props\";\nimport \"./base-copilot-textarea.css\";\nimport { HoveringToolbar } from \"../hovering-toolbar/hovering-toolbar\";\nimport { makeRenderElementFunction } from \"./render-element\";\nimport { makeRenderPlaceholderFunction } from \"./render-placeholder\";\nimport { useAddBrandingCss } from \"./use-add-branding-css\";\nimport {\n HoveringEditorProvider,\n useHoveringEditorContext,\n} from \"../hovering-toolbar/hovering-editor-provider\";\nimport { TrackerTextEditedSinceLastCursorMovement } from \"./track-cursor-moved-since-last-text-change\";\n\n/**\n * Purpose: to be used as the `ref` type for `CopilotTextarea` and `BaseCopilotTextarea`.\n *\n * This interface extends `HTMLElement`, and is the subset of `HTMLTextAreaElement` that \"actually matters\".\n * It provides the core functionality that consumers of `HTMLTextAreaElement` need 99.9% of the time:\n * - `value`: the current value of the textarea\n * - `focus`: make the textarea focused\n * - `blur`: make the textarea unfocused\n */\nexport interface HTMLCopilotTextAreaElement extends HTMLElement {\n /**\n * The current value of the textarea.\n */\n value: string;\n\n /**\n * focus on the textarea\n */\n focus: () => void;\n\n /**\n * unfocus the textarea.\n *\n * Called `blur` for syntactic compatibility with `HTMLTextAreaElement`.\n */\n blur: () => void;\n}\n\n/**\n * Not intended for direct use. Use CopilotTextarea instead.\n *\n * The `BaseCopilotTextarea` includes the basic UX component,\n * without the business logic / AI logic that makes the content useful and coherent.\n *\n * It is useful if you want to build your own backend, with fully custom business logic\n * for figuring out which contnet to fill in.\n */\nexport const BaseCopilotTextarea = React.forwardRef(\n (props: BaseCopilotTextareaProps, ref: React.Ref<HTMLCopilotTextAreaElement>) => {\n return (\n <HoveringEditorProvider>\n <BaseCopilotTextareaWithHoveringContext {...props} ref={ref} />\n </HoveringEditorProvider>\n );\n },\n);\n\n/**\n * Not intended for direct use. Use `CopilotTextarea` instead.\n *\n * This is the private core of the `BaseCopilotTextarea` component.\n * For practical purposes the implementation is cleaner assuming containment in a `HoveringEditorProviderContext`.\n *\n * Therefore we separate the core logic into this component,\n * and wrap it in a `HoveringEditorProviderContext` in `BaseCopilotTextarea`.\n */\nconst BaseCopilotTextareaWithHoveringContext = React.forwardRef(\n (props: BaseCopilotTextareaProps, ref: React.Ref<HTMLCopilotTextAreaElement>) => {\n const autosuggestionsConfig: BaseAutosuggestionsConfig = {\n ...defaultBaseAutosuggestionsConfig,\n ...props.baseAutosuggestionsConfig,\n };\n\n const valueOnInitialRender = useMemo(() => props.value ?? \"\", []);\n const [lastKnownFullEditorText, setLastKnownFullEditorText] = useState(valueOnInitialRender);\n const [cursorMovedSinceLastTextChange, setCursorMovedSinceLastTextChange] = useState(false);\n const [isUserInputActive, setIsUserInputActive] = useState(false);\n\n // // When the editor text changes, we want to reset the `textEditedSinceLastCursorMovement` state.\n // useEffect(() => {\n // setCursorMovedSinceLastTextChange(false);\n // }, [lastKnownFullEditorText]);\n\n const initialValue: Descendant[] = useMemo(() => {\n return [\n {\n type: \"paragraph\",\n children: [{ text: valueOnInitialRender }],\n },\n ];\n }, [valueOnInitialRender]);\n\n const editor = useCopilotTextareaEditor();\n\n const { isDisplayed: hoveringEditorIsDisplayed, setIsDisplayed: setHoveringEditorIsDisplayed } =\n useHoveringEditorContext();\n\n const insertText = useCallback(\n (autosuggestion: AutosuggestionState) => {\n Editor.insertText(editor, autosuggestion.text, {\n at: autosuggestion.point,\n });\n },\n [editor],\n );\n\n const shouldDisableAutosuggestions =\n // textarea is manually disabled:\n autosuggestionsConfig.disabled ||\n // hovering editor is displayed:\n hoveringEditorIsDisplayed ||\n // the cursor has moved since the last text change AND we are configured to disable autosuggestions in this case:\n (cursorMovedSinceLastTextChange &&\n autosuggestionsConfig.temporarilyDisableWhenMovingCursorWithoutChangingText) ||\n // not user input and we want to disable non-trusted events (like text insertion from autocomplete plugins):\n (!isUserInputActive && autosuggestionsConfig.temporarilyDisableNotTrustedEvents);\n\n const {\n currentAutocompleteSuggestion,\n onChangeHandler: onChangeHandlerForAutocomplete,\n onKeyDownHandler: onKeyDownHandlerForAutocomplete,\n onTouchStartHandler: onTouchStartHandlerForAutocomplete,\n } = useAutosuggestions(\n autosuggestionsConfig.debounceTime,\n autosuggestionsConfig.shouldAcceptAutosuggestionOnKeyPress,\n autosuggestionsConfig.shouldAcceptAutosuggestionOnTouch,\n autosuggestionsConfig.apiConfig.autosuggestionsFunction,\n insertText,\n autosuggestionsConfig.disableWhenEmpty,\n shouldDisableAutosuggestions,\n );\n\n const onKeyDownHandlerForHoveringEditor = useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (\n autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress(event, props.shortcut ?? \"k\")\n ) {\n event.preventDefault();\n setHoveringEditorIsDisplayed(!hoveringEditorIsDisplayed);\n }\n },\n [\n hoveringEditorIsDisplayed,\n setHoveringEditorIsDisplayed,\n autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress,\n ],\n );\n\n // sync autosuggestions state with the editor\n useEffect(() => {\n clearAutocompletionsFromEditor(editor);\n if (currentAutocompleteSuggestion) {\n addAutocompletionsToEditor(\n editor,\n currentAutocompleteSuggestion.text,\n currentAutocompleteSuggestion.point,\n );\n }\n }, [currentAutocompleteSuggestion]);\n\n const suggestionStyleAugmented: React.CSSProperties = useMemo(() => {\n return {\n fontStyle: \"italic\",\n color: \"gray\",\n ...props.suggestionsStyle,\n };\n }, [props.suggestionsStyle]);\n\n const renderElementMemoized = useMemo(() => {\n return makeRenderElementFunction(suggestionStyleAugmented);\n }, [suggestionStyleAugmented]);\n\n const renderPlaceholderMemoized = useMemo(() => {\n // For some reason slateJS specifies a top value of 0, which makes for strange styling. We override this here.\n const placeholderStyleSlatejsOverrides: React.CSSProperties = {\n top: undefined,\n };\n\n const placeholderStyleAugmented: React.CSSProperties = {\n ...placeholderStyleSlatejsOverrides,\n ...props.placeholderStyle,\n };\n\n return makeRenderPlaceholderFunction(placeholderStyleAugmented);\n }, [props.placeholderStyle]);\n\n // update the editor text, but only when the value changes from outside the component\n useEffect(() => {\n if (props.value === lastKnownFullEditorText) {\n return;\n }\n\n setLastKnownFullEditorText(props.value ?? \"\");\n replaceEditorText(editor, props.value ?? \"\");\n }, [props.value]);\n\n // separate into TextareaHTMLAttributes<HTMLDivElement> and CopilotTextareaProps\n const {\n placeholderStyle,\n value,\n hoverMenuClassname,\n onValueChange,\n baseAutosuggestionsConfig: autosuggestionsConfigFromProps,\n className,\n onChange,\n onKeyDown,\n disableBranding,\n ...propsToForward\n } = props;\n\n useAddBrandingCss(suggestionStyleAugmented, disableBranding);\n usePopulateCopilotTextareaRef(editor, ref);\n\n const moddedClassName = (() => {\n const baseClassName = \"copilot-textarea\";\n const brandingClass = disableBranding ? \"no-branding\" : \"with-branding\";\n const defaultTailwindClassName = \"bg-white overflow-y-auto resize-y\";\n const mergedClassName = twMerge(defaultTailwindClassName, className ?? \"\");\n return `${baseClassName} ${brandingClass} ${mergedClassName}`;\n })();\n\n return (\n <Slate\n editor={editor}\n initialValue={initialValue}\n onChange={(value) => {\n const newEditorState = getTextAroundCollapsedCursor(editor);\n\n const fullEditorText = newEditorState\n ? newEditorState.textBeforeCursor + newEditorState.textAfterCursor\n : getFullEditorTextWithNewlines(editor); // we don't double-parse the editor. When `newEditorState` is null, we didn't parse the editor yet.\n\n setLastKnownFullEditorText((prev) => {\n if (prev !== fullEditorText) {\n setCursorMovedSinceLastTextChange(false);\n }\n return fullEditorText;\n });\n\n onChangeHandlerForAutocomplete(newEditorState);\n\n props.onValueChange?.(fullEditorText);\n props.onChange?.(makeSemiFakeReactTextAreaEvent(fullEditorText));\n }}\n >\n <TrackerTextEditedSinceLastCursorMovement\n setCursorMovedSinceLastTextChange={setCursorMovedSinceLastTextChange}\n />\n <HoveringToolbar\n apiConfig={autosuggestionsConfig.apiConfig}\n contextCategories={autosuggestionsConfig.contextCategories}\n hoverMenuClassname={hoverMenuClassname}\n />\n <Editable\n renderElement={renderElementMemoized}\n renderPlaceholder={renderPlaceholderMemoized}\n onKeyDown={(event) => {\n setIsUserInputActive(true);\n onKeyDownHandlerForHoveringEditor(event); // forward the event for internal use\n onKeyDownHandlerForAutocomplete(event); // forward the event for internal use\n props.onKeyDown?.(event); // forward the event for external use\n }}\n onTouchStart={(event) => {\n onTouchStartHandlerForAutocomplete(event); // forward the event for internal use\n }}\n data-testid=\"copilot-textarea-editable\"\n className={moddedClassName}\n onBlur={(ev) => {\n // clear autocompletion on blur\n props.onBlur?.(ev);\n clearAutocompletionsFromEditor(editor);\n setIsUserInputActive(false);\n }}\n {...propsToForward}\n />\n </Slate>\n );\n },\n);\n\n// Consumers of <textarea> expect a `onChange: (React.ChangeEvent<HTMLTextAreaElement>) => void` event handler to be passed in.\n// This is *extremely* common, and we want to support it.\n//\n// We can't support the full functionality, but in 99% of cases, the consumer only cares about the `event.target.value` property --\n// that's how they get the new value of the textarea.\n//\n// So, the tradeoff we are making is minimizing compiler complaint, with a small chance of runtime error.\n// The alternative would be defining a different onChange entrypoint (we actually do have that in `onValueChange`),\n// And starting to explain subtleties to users the moment they try to use the component for the first time for very basic functionality.\n//\n// If this proves problematic, we can always revisit this decision.\nfunction makeSemiFakeReactTextAreaEvent(\n currentText: string,\n): React.ChangeEvent<HTMLTextAreaElement> {\n return {\n target: {\n value: currentText,\n type: \"copilot-textarea\",\n },\n currentTarget: {\n value: currentText,\n type: \"copilot-textarea\",\n },\n } as React.ChangeEvent<HTMLTextAreaElement>;\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Debouncer } from \"../../lib/debouncer\";\nimport { nullableCompatibleEqualityCheck } from \"../../lib/utils\";\nimport { AutosuggestionsBareFunction } from \"../../types/base\";\nimport { AutosuggestionState } from \"../../types/base/autosuggestion-state\";\nimport {\n EditorAutocompleteState,\n areEqual_autocompleteState,\n} from \"../../types/base/editor-autocomplete-state\";\n\nexport interface UseAutosuggestionsResult {\n currentAutocompleteSuggestion: AutosuggestionState | null;\n onChangeHandler: (newEditorState: EditorAutocompleteState | null) => void;\n onKeyDownHandler: (event: React.KeyboardEvent<HTMLDivElement>) => void;\n onTouchStartHandler: (event: React.TouchEvent<HTMLDivElement>) => void;\n}\n\nexport function useAutosuggestions(\n debounceTime: number,\n shouldAcceptAutosuggestionOnKeyPress: (event: React.KeyboardEvent<HTMLDivElement>) => boolean,\n shouldAcceptAutosuggestionOnTouch: (event: React.TouchEvent<HTMLDivElement>) => boolean,\n autosuggestionFunction: AutosuggestionsBareFunction,\n insertAutocompleteSuggestion: (suggestion: AutosuggestionState) => void,\n disableWhenEmpty: boolean,\n disabled: boolean,\n): UseAutosuggestionsResult {\n const [previousAutocompleteState, setPreviousAutocompleteState] =\n useState<EditorAutocompleteState | null>(null);\n\n const [currentAutocompleteSuggestion, setCurrentAutocompleteSuggestion] =\n useState<AutosuggestionState | null>(null);\n\n const awaitForAndAppendSuggestion: (\n editorAutocompleteState: EditorAutocompleteState,\n abortSignal: AbortSignal,\n ) => Promise<void> = useCallback(\n async (editorAutocompleteState: EditorAutocompleteState, abortSignal: AbortSignal) => {\n // early return if disabled\n if (disabled) {\n return;\n }\n\n if (\n disableWhenEmpty &&\n editorAutocompleteState.textBeforeCursor === \"\" &&\n editorAutocompleteState.textAfterCursor === \"\"\n ) {\n return;\n }\n\n // fetch the suggestion\n const suggestion = await autosuggestionFunction(editorAutocompleteState, abortSignal);\n\n // We'll assume for now that the autocomplete function might or might not respect the abort signal.\n if (!suggestion || abortSignal.aborted) {\n throw new DOMException(\"Aborted\", \"AbortError\");\n }\n\n setCurrentAutocompleteSuggestion({\n text: suggestion,\n point: editorAutocompleteState.cursorPoint,\n });\n },\n [autosuggestionFunction, setCurrentAutocompleteSuggestion, disableWhenEmpty, disabled],\n );\n\n const debouncedFunction = useMemo(\n () => new Debouncer<[editorAutocompleteState: EditorAutocompleteState]>(debounceTime),\n [debounceTime],\n );\n\n // clean current state when unmounting or disabling\n useEffect(() => {\n return () => {\n debouncedFunction.cancel();\n setCurrentAutocompleteSuggestion(null);\n };\n }, [debouncedFunction, disabled]);\n\n const onChange = useCallback(\n (newEditorState: EditorAutocompleteState | null) => {\n const editorStateHasChanged = !nullableCompatibleEqualityCheck(\n areEqual_autocompleteState,\n previousAutocompleteState,\n newEditorState,\n );\n setPreviousAutocompleteState(newEditorState);\n\n // if no change, do nothing\n if (!editorStateHasChanged) {\n return;\n }\n\n // if change, then first null out the current suggestion\n setCurrentAutocompleteSuggestion(null);\n\n // then try to get a new suggestion, debouncing to avoid too many requests while typing\n if (newEditorState) {\n debouncedFunction.debounce(awaitForAndAppendSuggestion, newEditorState);\n } else {\n debouncedFunction.cancel();\n }\n },\n [\n previousAutocompleteState,\n setPreviousAutocompleteState,\n debouncedFunction,\n awaitForAndAppendSuggestion,\n setCurrentAutocompleteSuggestion,\n ],\n );\n\n const keyDownOrTouchHandler = useCallback(\n (event: React.KeyboardEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>) => {\n if (currentAutocompleteSuggestion) {\n const shouldAcceptSuggestion =\n event.type === \"touchstart\"\n ? shouldAcceptAutosuggestionOnTouch(event as React.TouchEvent<HTMLDivElement>)\n : shouldAcceptAutosuggestionOnKeyPress(event as React.KeyboardEvent<HTMLDivElement>);\n\n if (shouldAcceptSuggestion) {\n event.preventDefault();\n insertAutocompleteSuggestion(currentAutocompleteSuggestion);\n setCurrentAutocompleteSuggestion(null);\n }\n }\n },\n [\n currentAutocompleteSuggestion,\n setCurrentAutocompleteSuggestion,\n insertAutocompleteSuggestion,\n shouldAcceptAutosuggestionOnKeyPress,\n ],\n );\n\n return {\n currentAutocompleteSuggestion,\n onChangeHandler: onChange,\n onKeyDownHandler: keyDownOrTouchHandler,\n onTouchStartHandler: keyDownOrTouchHandler,\n };\n}\n","export type AsyncFunction<T extends any[]> = (...args: [...T, AbortSignal]) => Promise<void>;\n\nexport class Debouncer<T extends any[]> {\n private timeoutId?: ReturnType<typeof setTimeout>;\n private activeAbortController?: AbortController;\n\n constructor(private wait: number) {}\n\n debounce = async (func: AsyncFunction<T>, ...args: T) => {\n // Abort the previous promise immediately\n this.cancel();\n\n this.timeoutId = setTimeout(async () => {\n try {\n this.activeAbortController = new AbortController();\n\n // Pass the signal to the async function, assuming it supports it\n await func(...args, this.activeAbortController.signal);\n\n this.activeAbortController = undefined;\n } catch (error) {}\n }, this.wait);\n };\n\n cancel = () => {\n if (this.activeAbortController) {\n this.activeAbortController.abort();\n this.activeAbortController = undefined;\n }\n\n if (this.timeoutId !== undefined) {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n };\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\nexport async function fetcher<JSON = any>(input: RequestInfo, init?: RequestInit): Promise<JSON> {\n const res = await fetch(input, init);\n\n if (!res.ok) {\n const json = await res.json();\n if (json.error) {\n const error = new Error(json.error) as Error & {\n status: number;\n };\n error.status = res.status;\n throw error;\n } else {\n throw new Error(\"An unexpected error occurred\");\n }\n }\n\n return res.json();\n}\n\nexport function formatDate(input: string | number | Date): string {\n const date = new Date(input);\n return date.toLocaleDateString(\"en-US\", {\n month: \"long\",\n day: \"numeric\",\n year: \"numeric\",\n });\n}\n\nexport const arraysAreEqual = (arr1: number[], arr2: number[]): boolean =>\n arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);\n\nexport function nullableCompatibleEqualityCheck<T>(\n naiveEqualityCheck: (a: T, b: T) => boolean,\n a: T | null | undefined,\n b: T | null | undefined,\n): boolean {\n if (a === null || a === undefined || b === null || b === undefined) {\n return a === b;\n }\n\n return naiveEqualityCheck(a, b);\n}\n","import { BasePoint } from \"slate\";\nimport { arraysAreEqual } from \"../../lib/utils\";\n\nexport interface EditorAutocompleteState {\n cursorPoint: BasePoint;\n textBeforeCursor: string;\n textAfterCursor: string;\n}\n\nexport function areEqual_autocompleteState(\n prev: EditorAutocompleteState,\n next: EditorAutocompleteState,\n) {\n return (\n prev.cursorPoint.offset === next.cursorPoint.offset &&\n arraysAreEqual(prev.cursorPoint.path, next.cursorPoint.path) &&\n prev.textBeforeCursor === next.textBeforeCursor &&\n prev.textAfterCursor === next.textAfterCursor\n );\n}\n","import { useMemo } from \"react\";\nimport { createEditor, Element } from \"slate\";\nimport { withReact } from \"slate-react\";\nimport {\n defaultShouldSave,\n ShouldSaveToHistory,\n withPartialHistory,\n} from \"../../lib/slatejs-edits/with-partial-history\";\nimport { CustomEditor } from \"../../types/base/custom-editor\";\n\nconst shouldSave: ShouldSaveToHistory = (op, prev) => {\n const excludedNodeType = \"suggestion\";\n // Check if the operation involves the suggestion inline node type\n if (\n op.type === \"insert_node\" &&\n Element.isElement(op.node) &&\n op.node.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"remove_node\" &&\n Element.isElement(op.node) &&\n op.node.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"set_node\" &&\n \"type\" in op.newProperties &&\n op.newProperties.type === excludedNodeType\n ) {\n return false;\n }\n\n if (op.type == \"set_node\" && \"type\" in op.properties && op.properties.type === excludedNodeType) {\n return false;\n }\n\n if (\n op.type === \"merge_node\" &&\n \"type\" in op.properties &&\n op.properties.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"split_node\" &&\n \"type\" in op.properties &&\n op.properties.type === excludedNodeType\n ) {\n return false;\n }\n\n // Otherwise, save the operation to history\n return defaultShouldSave(op, prev);\n};\n\nexport function useCopilotTextareaEditor(): CustomEditor {\n const editor = useMemo(() => {\n const editor = withPartialHistory(withReact(createEditor()), shouldSave);\n\n const { isVoid } = editor;\n editor.isVoid = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return true;\n default:\n return isVoid(element);\n }\n };\n\n const { markableVoid } = editor;\n editor.markableVoid = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return true;\n default:\n return markableVoid(element);\n }\n };\n\n const { isInline } = editor;\n editor.isInline = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return element.inline;\n default:\n return isInline(element);\n }\n };\n\n return editor;\n }, []);\n\n return editor;\n}\n","import { Editor, Operation, Path, Range, Transforms } from \"slate\";\nimport { HistoryEditor } from \"slate-history\";\n\n// Copy-pasted from `https://github.com/ianstormtaylor/slate/blob/main/packages/slate-history/src/with-history.ts`\n// With one exception: the `shouldSave` function is passed in as an argument to `withPartialHistory` instead of being hardcoded\nexport type ShouldSaveToHistory = (op: Operation, prev: Operation | undefined) => boolean;\n\nexport const withPartialHistory = <T extends Editor>(\n editor: T,\n shouldSave: ShouldSaveToHistory,\n) => {\n const e = editor as T & HistoryEditor;\n const { apply } = e;\n e.history = { undos: [], redos: [] };\n\n e.redo = () => {\n const { history } = e;\n const { redos } = history;\n\n if (redos.length > 0) {\n const batch = redos[redos.length - 1];\n\n if (batch.selectionBefore) {\n Transforms.setSelection(e, batch.selectionBefore);\n }\n\n HistoryEditor.withoutSaving(e, () => {\n Editor.withoutNormalizing(e, () => {\n for (const op of batch.operations) {\n e.apply(op);\n }\n });\n });\n\n history.redos.pop();\n e.writeHistory(\"undos\", batch);\n }\n };\n\n e.undo = () => {\n const { history } = e;\n const { undos } = history;\n\n if (undos.length > 0) {\n const batch = undos[undos.length - 1];\n\n HistoryEditor.withoutSaving(e, () => {\n Editor.withoutNormalizing(e, () => {\n const inverseOps = batch.operations.map(Operation.inverse).reverse();\n\n for (const op of inverseOps) {\n e.apply(op);\n }\n if (batch.selectionBefore) {\n Transforms.setSelection(e, batch.selectionBefore);\n }\n });\n });\n\n e.writeHistory(\"redos\", batch);\n history.undos.pop();\n }\n };\n\n e.apply = (op: Operation) => {\n const { operations, history } = e;\n const { undos } = history;\n const lastBatch = undos[undos.length - 1];\n const lastOp = lastBatch && lastBatch.operations[lastBatch.operations.length - 1];\n let save = HistoryEditor.isSaving(e);\n let merge = HistoryEditor.isMerging(e);\n\n if (save == null) {\n save = shouldSave(op, lastOp);\n }\n\n if (save) {\n if (merge == null) {\n if (lastBatch == null) {\n merge = false;\n } else if (operations.length !== 0) {\n merge = true;\n } else {\n merge = shouldMerge(op, lastOp);\n }\n }\n\n if (lastBatch && merge) {\n lastBatch.operations.push(op);\n } else {\n const batch = {\n operations: [op],\n selectionBefore: e.selection,\n };\n e.writeHistory(\"undos\", batch);\n }\n\n while (undos.length > 100) {\n undos.shift();\n }\n\n history.redos = [];\n }\n\n apply(op);\n };\n\n e.writeHistory = (stack: \"undos\" | \"redos\", batch: any) => {\n e.history[stack].push(batch);\n };\n\n return e;\n};\n\n/**\n * Check whether to merge an operation into the previous operation.\n */\n\nconst shouldMerge = (op: Operation, prev: Operation | undefined): boolean => {\n if (\n prev &&\n op.type === \"insert_text\" &&\n prev.type === \"insert_text\" &&\n op.offset === prev.offset + prev.text.length &&\n Path.equals(op.path, prev.path)\n ) {\n return true;\n }\n\n if (\n prev &&\n op.type === \"remove_text\" &&\n prev.type === \"remove_text\" &&\n op.offset + op.text.length === prev.offset &&\n Path.equals(op.path, prev.path)\n ) {\n return true;\n }\n\n return false;\n};\n\nexport const defaultShouldSave = (op: Operation, prev: Operation | undefined): boolean => {\n if (op.type === \"set_selection\") {\n return false;\n }\n\n return true;\n};\n","import React from \"react\";\nimport { Editor } from \"slate\";\nimport { ReactEditor } from \"slate-react\";\nimport { getFullEditorTextWithNewlines } from \"../../lib/get-text-around-cursor\";\nimport { replaceEditorText } from \"../../lib/slatejs-edits/replace-text\";\nimport { HTMLCopilotTextAreaElement } from \"../../types\";\nimport { CustomEditor } from \"../../types/base/custom-editor\";\n\nexport function usePopulateCopilotTextareaRef(\n editor: Editor,\n ref: React.Ref<HTMLCopilotTextAreaElement>,\n) {\n React.useImperativeHandle(ref, () => {\n class Combined {\n constructor(\n private customMethods: CustomMethods,\n private editorHtmlElement: HTMLElement,\n ) {}\n\n [key: string]: any;\n\n get(target: any, propKey: string): any {\n if (this.isKeyOfCustomMethods(propKey)) {\n const value = this.customMethods[propKey];\n if (typeof value === \"function\") {\n return value.bind(this.customMethods);\n }\n return value;\n } else if (this.isKeyOfHTMLElement(propKey)) {\n const value = this.editorHtmlElement[propKey];\n if (typeof value === \"function\") {\n return value.bind(this.editorHtmlElement);\n }\n return value;\n }\n }\n\n set(target: any, propKey: string, value: any): boolean {\n if (this.isKeyOfCustomMethods(propKey)) {\n (this.customMethods as any)[propKey] = value;\n } else if (this.isKeyOfHTMLElement(propKey)) {\n (this.editorHtmlElement as any)[propKey] = value;\n } else {\n // Default behavior (optional)\n target[propKey] = value;\n }\n return true;\n }\n\n private isKeyOfCustomMethods(key: string): key is keyof CustomMethods {\n return key in this.customMethods;\n }\n\n private isKeyOfHTMLElement(key: string): key is keyof HTMLElement {\n return key in this.editorHtmlElement;\n }\n }\n\n const handler = {\n get(target: any, propKey: keyof CustomMethods | keyof HTMLElement) {\n return target.get(target, propKey);\n },\n set(target: any, propKey: keyof CustomMethods | keyof HTMLElement, value: any) {\n return target.set(target, propKey, value);\n },\n };\n\n class CustomMethods {\n constructor(private editor: CustomEditor) {}\n\n focus() {\n ReactEditor.focus(this.editor);\n }\n\n blur() {\n ReactEditor.blur(this.editor);\n }\n\n get value() {\n return getFullEditorTextWithNewlines(this.editor);\n }\n set value(value: string) {\n replaceEditorText(this.editor, value);\n }\n }\n\n const editorHtmlElement = ReactEditor.toDOMNode(editor, editor);\n const customMethods = new CustomMethods(editor);\n\n const combined = new Combined(customMethods, editorHtmlElement);\n return new Proxy(combined, handler);\n }, [editor]);\n}\n","import { Editor, Node, Path, Range, Text, Element, BasePoint, BaseRange, Point } from \"slate\";\nimport { EditorAutocompleteState } from \"../types/base/editor-autocomplete-state\";\n\nexport interface EditorTextState {\n selection: BaseRange;\n\n textBeforeCursor: string;\n selectedText: string;\n textAfterCursor: string;\n}\n\nexport function getTextAroundCollapsedCursor(editor: Editor): EditorAutocompleteState | null {\n const { selection } = editor;\n if (!selection || !Range.isCollapsed(selection)) {\n return null;\n }\n\n const cursorPoint = selection.anchor;\n\n // Create two ranges: one before the anchor and one after\n const beforeRange: Range = {\n anchor: Editor.start(editor, []),\n focus: cursorPoint,\n };\n const afterRange: Range = {\n anchor: cursorPoint,\n focus: Editor.end(editor, []),\n };\n\n // Extract text for these ranges\n const before = extractTextWithNewlines(editor, beforeRange);\n const after = extractTextWithNewlines(editor, afterRange);\n\n return {\n cursorPoint: cursorPoint,\n textBeforeCursor: before,\n textAfterCursor: after,\n };\n}\n\nexport function getTextAroundSelection(editor: Editor): EditorTextState | null {\n const { selection } = editor;\n if (!selection) {\n return null;\n }\n\n const wellOrderedSelection = wellOrderedRange(selection);\n\n // Create two ranges: one before the anchor and one after\n const beforeRange: Range = {\n anchor: Editor.start(editor, []),\n focus: wellOrderedSelection.anchor,\n };\n const afterRange: Range = {\n anchor: wellOrderedSelection.focus,\n focus: Editor.end(editor, []),\n };\n\n // Extract text for these ranges\n const before = extractTextWithNewlines(editor, beforeRange);\n const after = extractTextWithNewlines(editor, afterRange);\n const selectedText = extractTextWithNewlines(editor, wellOrderedSelection);\n\n return {\n selection: wellOrderedSelection,\n textBeforeCursor: before,\n selectedText,\n textAfterCursor: after,\n };\n}\n\nexport function getFullEditorTextWithNewlines(editor: Editor): string {\n const fullDocumentRange: Range = {\n anchor: Editor.start(editor, []),\n focus: Editor.end(editor, []),\n };\n return extractTextWithNewlines(editor, fullDocumentRange);\n}\n\n// Helper function to extract text with newlines\nexport function extractTextWithNewlines(editor: Editor, range: Range): string {\n const voids = false;\n const [start, end] = Range.edges(range);\n let text = \"\";\n let lastBlock: Node | null = null;\n\n for (const [node, path] of Editor.nodes(editor, {\n at: range,\n match: Text.isText,\n voids,\n })) {\n let t = node.text;\n\n // Determine the parent block of the current text node\n const [block] = Editor.above(editor, {\n at: path,\n match: (n) => Element.isElement(n) && n.type === \"paragraph\",\n }) || [null];\n\n // If we encounter a new block, prepend a newline\n if (lastBlock !== block && block) {\n // check that lastBlock is not null to avoid adding a newline at the beginning\n if (lastBlock) {\n text += \"\\n\";\n }\n lastBlock = block;\n }\n\n if (Path.equals(path, end.path)) {\n t = t.slice(0, end.offset);\n }\n\n if (Path.equals(path, start.path)) {\n t = t.slice(start.offset);\n }\n\n text += t;\n }\n\n return text;\n}\n\nfunction wellOrderedRange(range: BaseRange): BaseRange {\n const { anchor, focus } = range;\n // if anchor is before focus, return range as is\n if (Point.isBefore(anchor, focus)) {\n return range;\n }\n\n // if focus is before anchor, return range with anchor and focus swapped\n return {\n anchor: focus,\n focus: anchor,\n };\n}\n","import { Editor, Transforms } from \"slate\";\n\nexport function replaceEditorText(editor: Editor, newText: string) {\n // clear all previous text\n Transforms.delete(editor, {\n at: {\n anchor: Editor.start(editor, []),\n focus: Editor.end(editor, []),\n },\n });\n\n // insert new text\n if (newText && newText !== \"\") {\n // don't insert empty text - results in strange visual behavior\n Transforms.insertNodes(\n editor,\n [\n {\n type: \"paragraph\",\n children: [{ text: newText }],\n },\n ],\n {\n at: [0],\n },\n );\n }\n}\n","import { BasePoint, Transforms } from \"slate\";\nimport { CustomEditor } from \"../../types/base/custom-editor\";\n\nexport function addAutocompletionsToEditor(\n editor: CustomEditor,\n newSuggestion: string,\n point: BasePoint,\n) {\n const editorPosition = editor.selection;\n\n Transforms.insertNodes(\n editor,\n [\n {\n type: \"suggestion\",\n inline: true,\n content: newSuggestion,\n children: [{ text: \"\" }],\n },\n ],\n {\n at: point,\n },\n );\n\n // restore cursor position\n if (editorPosition) {\n editor.selection = editorPosition;\n }\n}\n","import { Element, Node, Path, Transforms } from \"slate\";\nimport { CustomEditor } from \"../../types/base/custom-editor\";\n\nexport function clearAutocompletionsFromEditor(editor: CustomEditor) {\n // clear previous suggestion\n const paths: Path[] = [];\n for (const [node, path] of Node.nodes(editor)) {\n if (Element.isElement(node) && node.type === \"suggestion\") {\n paths.push(path);\n }\n }\n for (const path of paths) {\n try {\n Transforms.removeNodes(editor, { at: path });\n } catch (e) {\n console.log(\"CopilotTextarea.clearAutocompletionsFromEditor: error removing node\", e);\n }\n }\n}\n","import { BaseCopilotTextareaApiConfig } from \"./autosuggestions-bare-function\";\nimport { defaultCopilotContextCategories } from \"@copilotkit/react-core\";\nimport { isMacOS } from \"@copilotkit/shared\";\n\n/**\n * @interface BaseAutosuggestionsConfig\n *\n * @property {string} textareaPurpose - The purpose of the textarea. This is used to guide the autosuggestions.\n *\n * @property {string[]} contextCategories - The categories of context to consider when providing autosuggestions.\n *\n * @property {number} debounceTime - The amount of time (in milliseconds) to wait before triggering autosuggestions after the user has stopped typing.\n *\n * @property {BaseCopilotTextareaApiConfig} apiConfig - The configuration for the API that provides the autosuggestions.\n *\n * @property {boolean} disableWhenEmpty - Whether to disable autosuggestions when the textarea is empty.\n *\n * @property {boolean} disabled - Whether to disable autosuggestions entirely.\n *\n * @property {boolean} temporarilyDisableWhenMovingCursorWithoutChangingText - Whether to temporarily disable autosuggestions when the user moves the cursor without changing the text.\n *\n * @property {boolean} temporarilyDisableNotTrustedEvents - Temporarily disable autosuggestions after change event from non-trusted sources (like text insertion from autocomplete plugins)\n *\n * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldAcceptAutosuggestionOnKeyPress - A function that determines whether to accept the current autosuggestion based on a key press event. By default, the Tab key is used to accept the autosuggestion. Example code:\n *\n * ```typescript\n * const defaultShouldAcceptAutosuggestionOnKeyPress = (event: React.KeyboardEvent<HTMLDivElement>) => {\n * // if tab, accept the autosuggestion\n * if (event.key === \"Tab\") {\n * return true;\n * }\n * return false;\n * }\n * ```\n *\n * @property {(event: React.TouchEvent<HTMLDivElement>) => boolean} shouldAcceptAutosuggestionOnTouch - A function that determines whether to accept the current autosuggestion based on a mobile touch event. By default, the touching the end of a suggestion will accept it. Example code:\n *\n * ```typescript\n * const shouldAcceptAutosuggestionOnTouch = (event: React.TouchEvent<HTMLDivElement>) => {\n * // if tab, accept the autosuggestion\n * if (event.type === \"touchstart\") {\n * return true;\n * }\n * return false;\n * }\n * ```\n *\n * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldToggleHoveringEditorOnKeyPress - A function that determines whether to toggle the hovering editor based on a key press event. By default, the Command + K key combination is used to toggle the hovering editor. Example code:\n *\n * ```typescript\n * const defaultShouldToggleHoveringEditorOnKeyPress = (event: React.KeyboardEvent<HTMLDivElement>) => {\n * // if command-k, toggle the hovering editor\n * if (event.key === \"k\" && event.metaKey) {\n * return true;\n * }\n * return false;\n * }\n * ```\n */\nexport interface BaseAutosuggestionsConfig {\n textareaPurpose: string;\n contextCategories: string[];\n debounceTime: number;\n apiConfig: BaseCopilotTextareaApiConfig;\n\n disableWhenEmpty: boolean;\n disabled: boolean;\n temporarilyDisableWhenMovingCursorWithoutChangingText: boolean;\n temporarilyDisableNotTrustedEvents: boolean;\n shouldAcceptAutosuggestionOnKeyPress: (event: React.KeyboardEvent<HTMLDivElement>) => boolean;\n shouldAcceptAutosuggestionOnTouch: (event: React.TouchEvent<HTMLDivElement>) => boolean;\n shouldToggleHoveringEditorOnKeyPress: (\n event: React.KeyboardEvent<HTMLDivElement>,\n shortcut: string,\n ) => boolean;\n}\n\n// by default, command-k toggles the hovering editor\nconst defaultShouldToggleHoveringEditorOnKeyPress = (\n event: React.KeyboardEvent<HTMLDivElement>,\n shortcut: string,\n) => {\n const isMetaKey = isMacOS() ? event.metaKey : event.ctrlKey;\n\n // if command-k, toggle the hovering editor\n return event.key === shortcut && isMetaKey;\n};\n\nconst defaultShouldAcceptAutosuggestionOnKeyPress = (\n event: React.KeyboardEvent<HTMLDivElement>,\n) => {\n // if tab, accept the autosuggestion\n if (event.key === \"Tab\") {\n return true;\n }\n return false;\n};\n\nconst defaultShouldAcceptAutosuggestionOnTouch = () => false;\n\n/**\n * Default configuration for the BaseAutosuggestions.\n *\n * @property {number} debounceTime - The amount of time to wait before triggering the autosuggestions API call.\n * @property {string[]} contextCategories - The categories to use for context when making the autosuggestions API call.\n * @property {boolean} disableWhenEmpty - Whether to disable the autosuggestions when the textarea is empty.\n * @property {boolean} disabled - Whether to disable the autosuggestions feature entirely.\n * @property {boolean} temporarilyDisableWhenMovingCursorWithoutChangingText - Whether to temporarily disable the autosuggestions when the cursor is moved without changing the text.\n * @property {boolean} temporarilyDisableNotTrustedEvents - Temporarily disable the autosuggestions after change event from non-trusted sources (like text insertion from autocomplete plugins)\n * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldToggleHoveringEditorOnKeyPress - A function that determines whether to toggle the hovering editor based on a key press event.\n * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldAcceptAutosuggestionOnKeyPress - A function that determines whether to accept the autosuggestion based on a key press event.\n * @property {() => boolean} defaultShouldAcceptAutosuggestionOnTouch - A function that determines whether to accept the autosuggestion based on a mobile touch event.\n */\n\nexport const defaultBaseAutosuggestionsConfig: Omit<\n BaseAutosuggestionsConfig,\n \"textareaPurpose\" | \"apiConfig\"\n> = {\n debounceTime: 250,\n contextCategories: defaultCopilotContextCategories,\n disableWhenEmpty: true,\n disabled: false,\n temporarilyDisableWhenMovingCursorWithoutChangingText: true,\n temporarilyDisableNotTrustedEvents: true,\n shouldToggleHoveringEditorOnKeyPress: defaultShouldToggleHoveringEditorOnKeyPress,\n shouldAcceptAutosuggestionOnKeyPress: defaultShouldAcceptAutosuggestionOnKeyPress,\n shouldAcceptAutosuggestionOnTouch: defaultShouldAcceptAutosuggestionOnTouch,\n};\n","import { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { Editor, Location, Transforms } from \"slate\";\nimport { useSlate, useSlateSelection } from \"slate-react\";\nimport {\n getFullEditorTextWithNewlines,\n getTextAroundSelection,\n} from \"../../lib/get-text-around-cursor\";\nimport {\n EditingEditorState,\n InsertionEditorApiConfig,\n} from \"../../types/base/autosuggestions-bare-function\";\nimport { useHoveringEditorContext } from \"./hovering-editor-provider\";\nimport { Menu, Portal } from \"./hovering-toolbar-components\";\nimport { HoveringInsertionPromptBox } from \"./text-insertion-prompt-box\";\n\nexport interface HoveringToolbarProps {\n apiConfig: InsertionEditorApiConfig;\n contextCategories: string[];\n hoverMenuClassname: string | undefined;\n}\n\nexport const HoveringToolbar = (props: HoveringToolbarProps) => {\n const ref = useRef<HTMLDivElement>(null);\n const editor = useSlate();\n const selection = useSlateSelection();\n const { isDisplayed, setIsDisplayed } = useHoveringEditorContext();\n\n // only render on client\n const [isClient, setIsClient] = useState(false);\n useEffect(() => {\n setIsClient(true);\n }, []);\n\n const isShown = isClient && isDisplayed && selection;\n\n useLayoutEffect(() => {\n const el = ref.current;\n const { selection } = editor;\n\n if (!el || !isShown) {\n return;\n }\n\n if (!selection) {\n el.removeAttribute(\"style\");\n return;\n }\n\n const domSelection = window.getSelection();\n if (!domSelection || domSelection.rangeCount === 0) {\n return;\n }\n\n const domRange = domSelection.getRangeAt(0);\n const rect = domRange.getBoundingClientRect();\n\n // We use window = (0,0,0,0) as a signal that the selection is not in the original copilot-textarea,\n // but inside the hovering window.\n //\n // in such case, we simply do nothing.\n if (rect.top === 0 && rect.left === 0 && rect.width === 0 && rect.height === 0) {\n return;\n }\n\n const verticalOffsetFromCorner = 0;\n const horizontalOffsetFromCorner = 0;\n\n // position the toolbar below the selection\n let top = rect.bottom + window.scrollY + verticalOffsetFromCorner;\n\n // no space left at bottom, move up\n if (rect.bottom + el.offsetHeight > window.innerHeight - verticalOffsetFromCorner) {\n top = rect.top + window.scrollY - el.offsetHeight - verticalOffsetFromCorner;\n }\n\n // position the toolbar in the center of the selection\n let left =\n rect.left + window.scrollX - el.offsetWidth / 2 + rect.width / 2 + horizontalOffsetFromCorner;\n\n // no space left at left, move right\n if (left < horizontalOffsetFromCorner) {\n left = horizontalOffsetFromCorner;\n }\n // no space left at right, move left\n else if (left + el.offsetWidth > window.innerWidth - horizontalOffsetFromCorner) {\n left = window.innerWidth - el.offsetWidth - horizontalOffsetFromCorner;\n }\n\n el.style.opacity = \"1\";\n el.style.position = \"absolute\";\n\n el.style.top = `${top}px`;\n el.style.left = `${left}px`;\n }, [isShown]);\n\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (ref.current && !ref.current.contains(event.target as Node)) {\n setIsDisplayed(false);\n }\n };\n\n document.addEventListener(\"mousedown\", handleClickOutside);\n\n return () => {\n document.removeEventListener(\"mousedown\", handleClickOutside);\n };\n }, [ref, setIsDisplayed]);\n\n if (!isShown) {\n return null;\n }\n\n return (\n <Portal>\n <Menu\n ref={ref}\n className={\n \"copilot-kit-textarea-css-scope \" +\n (props.hoverMenuClassname ||\n \"p-2 absolute z-10 top-[-10000px] left-[-10000px] mt-[-6px] opacity-0 transition-opacity duration-700\")\n }\n data-testid=\"hovering-toolbar\"\n >\n <HoveringInsertionPromptBox\n editorState={editorState(editor, selection)}\n apiConfig={props.apiConfig}\n performInsertion={(insertedText) => {\n // replace the selection with the inserted text\n Transforms.delete(editor, { at: selection });\n Transforms.insertText(editor, insertedText, {\n at: selection,\n });\n setIsDisplayed(false);\n }}\n contextCategories={props.contextCategories}\n />\n </Menu>\n </Portal>\n );\n};\n\nfunction editorState(editor: Editor, selection: Location): EditingEditorState {\n const textAroundCursor = getTextAroundSelection(editor);\n if (textAroundCursor) {\n return textAroundCursor;\n }\n\n return {\n textBeforeCursor: getFullEditorTextWithNewlines(editor),\n textAfterCursor: \"\",\n selectedText: \"\",\n };\n}\n","import { createContext, useState, useContext, ReactNode } from \"react\";\n\ninterface HoveringEditorContextProps {\n isDisplayed: boolean;\n setIsDisplayed: (value: boolean) => void;\n}\n\nconst HoveringEditorContext = createContext<HoveringEditorContextProps>({\n isDisplayed: false,\n setIsDisplayed: () => {},\n});\n\nexport interface HoveringEditorProviderProps {\n children: ReactNode;\n}\n\n/**\n * A context provider for the hovering editor over the `CopilotTextarea`\n * (used to edit and insert text into the `CopilotTextarea`).\n */\nexport const HoveringEditorProvider = ({ children }: HoveringEditorProviderProps) => {\n const [isDisplayed, setIsDisplayed] = useState<boolean>(false);\n\n return (\n <HoveringEditorContext.Provider value={{ isDisplayed, setIsDisplayed }}>\n {children}\n </HoveringEditorContext.Provider>\n );\n};\n\nexport const useHoveringEditorContext = () => useContext(HoveringEditorContext);\n","import { css, cx } from \"@emotion/css\";\nimport React, { PropsWithChildren, Ref } from \"react\";\nimport ReactDOM from \"react-dom\";\n\ninterface BaseProps {\n className?: string;\n [key: string]: unknown;\n}\n\nexport const Button = React.forwardRef<\n HTMLSpanElement,\n PropsWithChildren<{ active: boolean; reversed: boolean } & BaseProps>\n>(({ className, active, reversed, ...props }, ref) => (\n <span\n {...props}\n ref={ref}\n className={cx(\n className as string,\n css`\n cursor: pointer;\n color: ${reversed ? (active ? \"white\" : \"#aaa\") : active ? \"black\" : \"#ccc\"};\n `,\n )}\n />\n));\n\nexport const Icon = React.forwardRef<HTMLSpanElement, PropsWithChildren<BaseProps>>(\n ({ className, ...props }, ref) => (\n <span\n {...props}\n ref={ref}\n className={cx(\n \"material-icons\",\n className as string,\n css`\n font-size: 18px;\n vertical-align: text-bottom;\n `,\n )}\n />\n ),\n);\n\nexport const Menu = React.forwardRef<HTMLDivElement, PropsWithChildren<BaseProps>>(\n ({ className, ...props }, ref) => {\n return (\n <div\n {...props}\n data-testid=\"menu\"\n ref={ref}\n className={cx(\n className as string,\n css`\n & > * {\n display: inline-block;\n }\n\n & > * + * {\n margin-left: 15px;\n }\n `,\n )}\n />\n );\n },\n);\nexport const Portal = ({ children }: { children: React.ReactNode }) => {\n return typeof document === \"object\" ? ReactDOM.createPortal(children, document.body) : null;\n};\n\nexport const Toolbar = React.forwardRef<HTMLDivElement, PropsWithChildren<BaseProps>>(\n ({ className, ...props }, ref) => (\n <Menu\n {...props}\n ref={ref}\n className={cx(\n className as string,\n css`\n position: relative;\n padding: 1px 18px 17px;\n margin: 0 -20px;\n border-bottom: 2px solid #eee;\n margin-bottom: 20px;\n `,\n )}\n />\n ),\n);\n","import { Ref, RefObject, useEffect } from \"react\";\n\n// Updates the height of a <textarea> when the value changes.\nconst useAutosizeTextArea = (textAreaRef: RefObject<HTMLTextAreaElement | null>, value: string) => {\n useEffect(() => {\n if (textAreaRef.current !== null) {\n // We need to reset the height momentarily to get the correct scrollHeight for the textarea\n textAreaRef.current.style.height = \"0px\";\n const scrollHeight = textAreaRef.current.scrollHeight;\n\n // We then set the height directly, outside of the render loop\n // Trying to set this with state or a ref will product an incorrect value.\n textAreaRef.current.style.height = scrollHeight + \"px\";\n }\n }, [textAreaRef, value]);\n};\n\nexport default useAutosizeTextArea;\n","import { useState } from \"react\";\nimport {\n Command,\n CommandDialog,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n CommandSeparator,\n CommandShortcut,\n} from \"../ui/command\";\n\nimport { Calculator, Calendar, CreditCard, Settings, Smile, User } from \"lucide-react\";\n\nimport { DocumentPointer } from \"@copilotkit/react-core\";\n\nexport interface SourceSearchBoxProps {\n searchTerm: string;\n suggestedFiles: DocumentPointer[];\n onSelectedFile: (filePointer: DocumentPointer) => void;\n}\n\nexport function SourceSearchBox(props: SourceSearchBoxProps) {\n const [selectedValue, setSelectedValue] = useState<string>(\"\");\n\n return (\n <Command\n className=\"rounded-lg border shadow-md\"\n value={selectedValue}\n onValueChange={(value) => {\n setSelectedValue(value);\n }}\n filter={(value, search) => {\n // if the search term is empty, show all commands\n if (props.searchTerm === \"\") return 1;\n\n // if the search term is a prefix of the command, show it\n if (value.startsWith(props.searchTerm)) return 1;\n\n // otherwise, don't show it\n return 0;\n }}\n >\n <CommandInput\n value={props.searchTerm}\n className=\"rounded-t-lg hidden\"\n placeholder=\"Search for a command...\"\n />\n <CommandList>\n <CommandEmpty>No results found.</CommandEmpty>\n\n <CommandGroup heading=\"Available resources\">\n {props.suggestedFiles.map((filePointer) => {\n return (\n <CommandItem\n key={`word-${filePointer.sourceApplication}.${filePointer.name}`}\n value={filePointer.name}\n onSelect={(value) => {\n props.onSelectedFile(filePointer);\n }}\n >\n <div className=\" px-3 flex flex-row gap-1 items-center\">\n <Logo width=\"20px\" height=\"20px\">\n <img\n src={filePointer.iconImageUri}\n alt={filePointer.sourceApplication}\n className=\"w-full h-full\"\n />\n </Logo>\n {filePointer.name}\n </div>\n </CommandItem>\n );\n })}\n </CommandGroup>\n\n {/* <CommandGroup heading=\"Suggestions\">\n <CommandItem\n onSelect={(value) => {\n console.log(value);\n console.log(value);\n }}\n >\n <Calendar className=\"mr-2 h-4 w-4\" />\n <span>Calendar</span>\n </CommandItem>\n <CommandItem>\n <Smile className=\"mr-2 h-4 w-4\" />\n <span>Search Emoji</span>\n </CommandItem>\n <CommandItem>\n <Calculator className=\"mr-2 h-4 w-4\" />\n <span>Calculator</span>\n </CommandItem>\n </CommandGroup> */}\n <CommandSeparator />\n </CommandList>\n </Command>\n );\n}\n\nexport function Logo({\n children,\n width,\n height,\n}: {\n children: React.ReactNode;\n width: string;\n height: string;\n}) {\n return (\n <div className=\"flex items-center justify-center\" style={{ width: width, height: height }}>\n {children}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { DialogProps } from \"@radix-ui/react-dialog\";\nimport { Command as CommandPrimitive } from \"cmdk\";\nimport { cn } from \"../../lib/utils\";\nimport { Dialog, DialogContent } from \"./dialog\";\n\nconst Command = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive\n ref={ref}\n className={cn(\n \"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground\",\n className,\n )}\n {...props}\n />\n));\nCommand.displayName = CommandPrimitive.displayName;\n\ninterface CommandDialogProps extends DialogProps {}\n\nconst CommandDialog = ({ children, ...props }: CommandDialogProps) => {\n return (\n <Dialog {...props}>\n <DialogContent className=\"overflow-hidden p-0 shadow-lg\">\n <Command className=\"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5\">\n {children}\n </Command>\n </DialogContent>\n </Dialog>\n );\n};\n\nconst CommandInput = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Input>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>\n>(({ className, ...props }, ref) => (\n <div className=\"flex items-center border-b px-3\" cmdk-input-wrapper=\"\">\n {/* <Search className=\"mr-2 h-4 w-4 shrink-0 opacity-50\" /> */}\n <CommandPrimitive.Input\n ref={ref}\n className={cn(\n \"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50\",\n className,\n )}\n {...props}\n />\n </div>\n));\n\nCommandInput.displayName = CommandPrimitive.Input.displayName;\n\nconst CommandList = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.List>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive.List\n ref={ref}\n className={cn(\"max-h-[300px] overflow-y-auto overflow-x-hidden pb-2\", className)}\n {...props}\n />\n));\n\nCommandList.displayName = CommandPrimitive.List.displayName;\n\nconst CommandEmpty = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Empty>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>\n>((props, ref) => (\n <CommandPrimitive.Empty ref={ref} className=\"py-6 text-center text-sm\" {...props} />\n));\n\nCommandEmpty.displayName = CommandPrimitive.Empty.displayName;\n\nconst CommandGroup = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Group>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive.Group\n ref={ref}\n className={cn(\n \"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground\",\n className,\n )}\n {...props}\n />\n));\n\nCommandGroup.displayName = CommandPrimitive.Group.displayName;\n\nconst CommandSeparator = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Separator>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive.Separator\n ref={ref}\n className={cn(\"-mx-1 h-px bg-border\", className)}\n {...props}\n />\n));\nCommandSeparator.displayName = CommandPrimitive.Separator.displayName;\n\nconst CommandItem = React.forwardRef<\n React.ElementRef<typeof CommandPrimitive.Item>,\n React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>\n>(({ className, ...props }, ref) => (\n <CommandPrimitive.Item\n ref={ref}\n className={cn(\n \"relative flex cursor-default select-none items-center rounded-sm text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n className,\n )}\n {...props}\n />\n));\n\nCommandItem.displayName = CommandPrimitive.Item.displayName;\n\nconst CommandShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {\n return (\n <span\n className={cn(\"ml-auto text-xs tracking-widest text-muted-foreground\", className)}\n {...props}\n />\n );\n};\nCommandShortcut.displayName = \"CommandShortcut\";\n\nexport {\n Command,\n CommandDialog,\n CommandInput,\n CommandList,\n CommandEmpty,\n CommandGroup,\n CommandItem,\n CommandShortcut,\n CommandSeparator,\n};\n","import useAutosizeTextArea from \"../../../hooks/misc/use-autosize-textarea\";\nimport {\n EditingEditorState,\n Generator_InsertionOrEditingSuggestion,\n} from \"../../../types/base/autosuggestions-bare-function\";\nimport { SourceSearchBox } from \"../../source-search-box/source-search-box\";\nimport { DocumentPointer, useCopilotContext } from \"@copilotkit/react-core\";\nimport { Button } from \"../../ui/button\";\nimport { Label } from \"../../ui/label\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { streamPromiseFlatten } from \"../../../lib/stream-promise-flatten\";\nimport { IncludedFilesPreview } from \"./included-files-preview\";\nimport { useHoveringEditorContext } from \"../hovering-editor-provider\";\n\nexport type SuggestionState = {\n editorState: EditingEditorState;\n};\n\nexport interface HoveringInsertionPromptBoxCoreProps {\n state: SuggestionState;\n performInsertion: (insertedText: string) => void;\n insertionOrEditingFunction: Generator_InsertionOrEditingSuggestion;\n contextCategories: string[];\n}\n\nexport const HoveringInsertionPromptBoxCore = ({\n performInsertion,\n state,\n insertionOrEditingFunction,\n contextCategories,\n}: HoveringInsertionPromptBoxCoreProps) => {\n const { getDocumentsContext } = useCopilotContext();\n\n const [editSuggestion, setEditSuggestion] = useState<string>(\"\");\n const [suggestionIsLoading, setSuggestionIsLoading] = useState<boolean>(false);\n\n const [adjustmentPrompt, setAdjustmentPrompt] = useState<string>(\"\");\n\n const [generatingSuggestion, setGeneratingSuggestion] = useState<ReadableStream<string> | null>(\n null,\n );\n\n const adjustmentTextAreaRef = useRef<HTMLTextAreaElement>(null);\n const suggestionTextAreaRef = useRef<HTMLTextAreaElement>(null);\n\n const [filePointers, setFilePointers] = useState<DocumentPointer[]>([]);\n\n const [suggestedFiles, setSuggestedFiles] = useState<DocumentPointer[]>([]);\n useEffect(() => {\n setSuggestedFiles(getDocumentsContext(contextCategories));\n }, [contextCategories, getDocumentsContext]);\n\n useAutosizeTextArea(suggestionTextAreaRef, editSuggestion || \"\");\n useAutosizeTextArea(adjustmentTextAreaRef, adjustmentPrompt || \"\");\n\n // initially focus on the adjustment prompt text area\n useEffect(() => {\n adjustmentTextAreaRef.current?.focus();\n }, []);\n\n // continuously read the generating suggestion stream and update the edit suggestion\n useEffect(() => {\n // if no generating suggestion, do nothing\n if (!generatingSuggestion) {\n return;\n }\n\n // Check if the stream is already locked (i.e. already reading from it)\n if (generatingSuggestion.locked) {\n return;\n }\n\n // reset the edit suggestion\n setEditSuggestion(\"\");\n\n // read the generating suggestion stream and continuously update the edit suggestion\n const reader = generatingSuggestion.getReader();\n const read = async () => {\n setSuggestionIsLoading(true);\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n setEditSuggestion((prev) => {\n const newSuggestion = prev + value;\n\n // Scroll to the bottom of the textarea. We call this here to make sure scroll-to-bottom is synchronous with the state update.\n if (suggestionTextAreaRef.current) {\n suggestionTextAreaRef.current.scrollTop = suggestionTextAreaRef.current.scrollHeight;\n }\n return newSuggestion;\n });\n }\n\n setSuggestionIsLoading(false);\n };\n read();\n\n return () => {\n // release the lock if the reader is not closed on unmount\n const releaseLockIfNotClosed = async () => {\n try {\n await reader.closed;\n } catch {\n reader.releaseLock();\n }\n };\n\n releaseLockIfNotClosed();\n };\n }, [generatingSuggestion]);\n\n // generate an adjustment to the completed text, based on the adjustment prompt\n const beginGeneratingAdjustment = useCallback(async () => {\n // don't generate text if the prompt is empty\n if (!adjustmentPrompt.trim()) {\n return;\n }\n\n // editor state includes the text being edited, and the text before/after the selection\n // if the current edit suggestion is not empty, then use *it* as the \"selected text\" - instead of the editor state's selected text\n let modificationState = state.editorState;\n if (editSuggestion !== \"\") {\n modificationState.selectedText = editSuggestion;\n }\n\n // generate the adjustment suggestion\n const adjustmentSuggestionTextStreamPromise = insertionOrEditingFunction(\n modificationState,\n adjustmentPrompt,\n filePointers,\n new AbortController().signal,\n );\n const adjustmentSuggestionTextStream = streamPromiseFlatten(\n adjustmentSuggestionTextStreamPromise,\n );\n\n setGeneratingSuggestion(adjustmentSuggestionTextStream);\n }, [\n adjustmentPrompt,\n editSuggestion,\n state.editorState,\n insertionOrEditingFunction,\n filePointers,\n ]);\n\n const isLoading = suggestionIsLoading;\n\n const textToEdit = editSuggestion || state.editorState.selectedText;\n const adjustmentLabel =\n textToEdit === \"\"\n ? \"Describe the text you want to insert\"\n : \"Describe adjustments to the suggested text\";\n const placeholder =\n textToEdit === \"\"\n ? \"e.g. 'summarize the client's top 3 pain-points from @CallTranscript'\"\n : \"e.g. 'make it more formal', 'be more specific', ...\";\n\n const { setIsDisplayed } = useHoveringEditorContext();\n\n const AdjustmentPromptComponent = (\n <>\n <Label className=\"\">{adjustmentLabel}</Label>\n <div className=\"relative w-full flex items-center\">\n <textarea\n data-testid=\"adjustment-prompt\"\n disabled={suggestionIsLoading}\n ref={adjustmentTextAreaRef}\n value={adjustmentPrompt}\n onChange={(e) => setAdjustmentPrompt(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && e.shiftKey) {\n e.preventDefault();\n setAdjustmentPrompt(adjustmentPrompt + \"\\n\");\n } else if (e.key === \"Enter\") {\n e.preventDefault();\n beginGeneratingAdjustment();\n }\n }}\n placeholder={placeholder}\n style={{ minHeight: \"3rem\" }}\n className=\"w-full bg-slate-100 h-auto h-min-14 text-sm p-2 rounded-md resize-none overflow-visible focus:outline-none focus:ring-0 focus:border-non pr-[3rem]\"\n rows={1}\n />\n <button\n onClick={beginGeneratingAdjustment}\n className=\"absolute right-2 bg-blue-500 text-white w-8 h-8 rounded-full flex items-center justify-center\"\n data-testid=\"generate-button\"\n >\n <i className=\"material-icons\">arrow_forward</i>\n </button>\n </div>\n </>\n );\n\n const SuggestionComponent = (\n <>\n <div className=\"flex justify-between items-end w-full\">\n <Label className=\"mt-4\">Suggested:</Label>\n <div className=\"ml-auto\">\n {isLoading && (\n <div className=\"flex justify-center items-center\">\n <div\n className=\"inline-block h-4 w-4 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]\"\n role=\"status\"\n >\n <span className=\"!absolute !-m-px !h-px !w-px !overflow-hidden !whitespace-nowrap !border-0 !p-0 ![clip:rect(0,0,0,0)]\">\n Loading...\n </span>\n </div>\n </div>\n )}\n </div>\n </div>\n <textarea\n data-testid=\"suggestion-result\"\n ref={suggestionTextAreaRef}\n value={editSuggestion}\n disabled={suggestionIsLoading}\n onChange={(e) => setEditSuggestion(e.target.value)}\n className=\"w-full text-base p-2 border border-gray-300 rounded-md resize-none bg-green-50\"\n style={{ overflow: \"auto\", maxHeight: \"10em\" }}\n />\n </>\n );\n\n const SubmitComponent = (\n <div className=\"flex w-full gap-4 justify-start\">\n <Button\n data-testid=\"insert-button\"\n className=\" bg-green-700 text-white\"\n onClick={() => {\n performInsertion(editSuggestion);\n }}\n >\n Insert <i className=\"material-icons\">check</i>\n </Button>\n </div>\n );\n\n // show source search if the last word in the adjustment prompt BEGINS with an @\n const sourceSearchCandidate = adjustmentPrompt.split(\" \").pop();\n // if the candidate is @someCandidate, then 'someCandidate', otherwise undefined\n const sourceSearchWord = sourceSearchCandidate?.startsWith(\"@\")\n ? sourceSearchCandidate.slice(1)\n : undefined;\n\n return (\n <div className=\"w-full flex flex-col items-start relative gap-2\">\n {AdjustmentPromptComponent}\n {filePointers.length > 0 && (\n <IncludedFilesPreview includedFiles={filePointers} setIncludedFiles={setFilePointers} />\n )}\n {sourceSearchWord !== undefined && (\n <SourceSearchBox\n searchTerm={sourceSearchWord}\n suggestedFiles={suggestedFiles}\n onSelectedFile={(filePointer) => {\n setAdjustmentPrompt(adjustmentPrompt.replace(new RegExp(`@${sourceSearchWord}$`), \"\"));\n setFilePointers((prev) => [...prev, filePointer]);\n\n // focus back on the adjustment prompt, and move the cursor to the end\n adjustmentTextAreaRef.current?.focus();\n }}\n />\n )}\n {generatingSuggestion ? SuggestionComponent : null}\n {generatingSuggestion ? SubmitComponent : null}\n </div>\n );\n};\n","import * as React from \"react\";\nimport { Slot } from \"@radix-ui/react-slot\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\n\nimport { cn } from \"../../lib/utils\";\n\nconst buttonVariants = cva(\n \"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n destructive: \"bg-destructive text-destructive-foreground hover:bg-destructive/90\",\n outline: \"border border-input bg-background hover:bg-accent hover:text-accent-foreground\",\n secondary: \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n ghost: \"hover:bg-accent hover:text-accent-foreground\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default: \"h-10 px-4 py-2\",\n sm: \"h-9 rounded-md px-3\",\n lg: \"h-11 rounded-md px-8\",\n icon: \"h-10 w-10\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n },\n);\n\nexport interface ButtonProps\n extends React.ButtonHTMLAttributes<HTMLButtonElement>,\n VariantProps<typeof buttonVariants> {\n asChild?: boolean;\n}\n\nconst Button = React.forwardRef<HTMLButtonElement, ButtonProps>(\n ({ className, variant, size, asChild = false, ...props }, ref) => {\n const Comp = asChild ? Slot : \"button\";\n return (\n <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />\n );\n },\n);\nButton.displayName = \"Button\";\n\nexport { Button, buttonVariants };\n","import * as React from \"react\";\nimport * as LabelPrimitive from \"@radix-ui/react-label\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\n\nimport { cn } from \"../../lib/utils\";\n\nconst labelVariants = cva(\n \"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70\",\n);\n\nconst Label = React.forwardRef<\n React.ElementRef<typeof LabelPrimitive.Root>,\n React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>\n>(({ className, ...props }, ref) => (\n <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />\n));\nLabel.displayName = LabelPrimitive.Root.displayName;\n\nexport { Label };\n","/**\n * Flatten a promise of a stream, into a stream.\n *\n * Useful because a stream already includes the notion of async value delivery,\n * so it often makes sense to simply await the values rather than the generator of the values.\n *\n * @param {Promise<ReadableStream<A>>} promise - The promise to flatten.\n * @returns {ReadableStream<A>} - The flattened stream.\n */\n\nexport function streamPromiseFlatten<A>(promise: Promise<ReadableStream<A>>): ReadableStream<A> {\n return new ReadableStream<A>({\n async start(controller) {\n try {\n const stream = await promise;\n const reader = stream.getReader();\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n controller.close();\n return;\n }\n\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n },\n });\n}\n","import { DocumentPointer } from \"@copilotkit/react-core\";\nimport { Label } from \"../../ui/label\";\nimport React from \"react\";\nimport Chip from \"@mui/material/Chip/Chip.js\";\nimport Avatar from \"@mui/material/Avatar/Avatar.js\";\n\nexport interface IncludedFilesPreviewProps {\n includedFiles: DocumentPointer[];\n setIncludedFiles: React.Dispatch<React.SetStateAction<DocumentPointer[]>>;\n}\n\nexport const IncludedFilesPreview = ({\n includedFiles,\n setIncludedFiles,\n}: IncludedFilesPreviewProps) => {\n return (\n <div className=\"flex flex-col gap-2 mt-2\">\n <Label className=\"\">Included context:</Label>\n <div className=\"flex flex-wrap gap-2\">\n {includedFiles.map((filePointer, index) => {\n return (\n <FileChipPreview\n key={`file-${filePointer.sourceApplication}.${filePointer.name}`}\n filePointer={filePointer}\n onDelete={() => {\n setIncludedFiles((prev) => prev.filter((fp) => fp !== filePointer));\n }}\n />\n );\n })}\n </div>\n </div>\n );\n};\n\nexport interface FileChipPreviewProps {\n filePointer: DocumentPointer;\n onDelete: () => void;\n}\n\nexport const FileChipPreview = ({ filePointer, onDelete }: FileChipPreviewProps) => {\n return (\n <Chip\n label={filePointer.name}\n onDelete={onDelete}\n avatar={\n <Avatar\n src={filePointer.iconImageUri}\n alt={filePointer.sourceApplication}\n sx={{ backgroundColor: \"transparent\" }}\n ></Avatar>\n }\n />\n );\n};\n","import { HoveringInsertionPromptBoxCore } from \"./hovering-insertion-prompt-box-core\";\nimport {\n EditingEditorState,\n InsertionEditorApiConfig,\n} from \"../../../types/base/autosuggestions-bare-function\";\n\nexport interface Props {\n editorState: EditingEditorState;\n apiConfig: InsertionEditorApiConfig;\n performInsertion: (insertedText: string) => void;\n contextCategories: string[];\n}\n\nexport const HoveringInsertionPromptBox = (props: Props) => {\n return (\n <div\n className=\"flex flex-col justify-center items-center space-y-4 rounded-md border shadow-lg p-4 border-gray- bg-white\"\n style={{ width: \"35rem\" }}\n >\n <HoveringInsertionPromptBoxCore\n state={{\n editorState: props.editorState,\n }}\n insertionOrEditingFunction={props.apiConfig.insertionOrEditingFunction}\n performInsertion={props.performInsertion}\n contextCategories={props.contextCategories}\n />\n </div>\n );\n};\n","import { RenderElementProps } from \"slate-react\";\nimport React from \"react\";\n\nexport type RenderElementFunction = (props: RenderElementProps) => React.JSX.Element;\n\nexport function makeRenderElementFunction(\n suggestionsStyle: React.CSSProperties,\n): RenderElementFunction {\n return (props: RenderElementProps) => {\n switch (props.element.type) {\n case \"paragraph\":\n return <DefaultElement {...props} />;\n case \"suggestion\":\n return <SuggestionElement {...props} suggestionsStyle={suggestionsStyle} />;\n }\n };\n}\n\nconst DefaultElement = (props: RenderElementProps) => {\n return <div {...props.attributes}>{props.children}</div>;\n};\nconst SuggestionElement = (\n props: RenderElementProps & {\n suggestionsStyle: React.CSSProperties;\n },\n) => {\n return (\n <span\n {...props.attributes}\n style={{\n ...props.suggestionsStyle,\n }}\n data-testid=\"suggestion\"\n contentEditable={false}\n >\n {props.children /* https://github.com/ianstormtaylor/slate/issues/3930 */}\n {props.element.type === \"suggestion\" && props.element.content}\n </span>\n );\n};\n","import { RenderPlaceholderProps } from \"slate-react\";\nimport React from \"react\";\n\nexport type RenderPlaceholderFunction = (props: RenderPlaceholderProps) => React.JSX.Element;\n\nexport function makeRenderPlaceholderFunction(\n placeholderStyle?: React.CSSProperties,\n): RenderPlaceholderFunction {\n return (props: RenderPlaceholderProps) => {\n const { style, ...restAttributes } = props.attributes;\n\n return (\n <div\n {...restAttributes}\n style={{\n ...style,\n ...placeholderStyle,\n }}\n >\n {props.children}\n </div>\n );\n };\n}\n","import { useEffect } from \"react\";\n\nexport function useAddBrandingCss(\n suggestionStyleAugmented: React.CSSProperties,\n disableBranding: boolean | undefined,\n) {\n const cssSelector = \".copilot-textarea.with-branding\";\n useEffect(() => {\n if (disableBranding) {\n return;\n }\n\n // ---\n // 1: Add the CSS to the DOM\n const styleEl = document.createElement(\"style\");\n styleEl.id = \"dynamic-styles\";\n\n // Build the CSS string dynamically\n let dynamicStyles = Object.entries(suggestionStyleAugmented)\n .map(([key, value]) => {\n const kebabCaseKey = key.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, \"$1-$2\").toLowerCase();\n return `${kebabCaseKey}: ${value};`;\n })\n .join(\" \");\n\n // Append overrides for italics and font-size\n dynamicStyles += `font-style: normal; font-size: x-small;`;\n dynamicStyles += `content: \"CopilotKit\";`;\n dynamicStyles += `bottom: 6px;`;\n dynamicStyles += `right: 6px;`;\n dynamicStyles += `pointer-events: none;`;\n dynamicStyles += `font-weight: 200;`;\n dynamicStyles += `padding: 0;`;\n dynamicStyles += `margin: 0;`;\n dynamicStyles += `border: 0;`;\n dynamicStyles += `line-height: 1;`;\n dynamicStyles += `position: absolute;`;\n\n // Append it to the ::after class\n styleEl.innerHTML = `\n ${cssSelector}::after {\n ${dynamicStyles}\n }\n `;\n\n document.head.appendChild(styleEl);\n\n // ---\n // 2: Add the scroll listener (to keep the branding in the bottom right as the textarea scrolls)\n const textarea = document.querySelector(cssSelector);\n const handleScroll = () => {\n const styleEl = document.getElementById(\"dynamic-styles\");\n if (styleEl && textarea) {\n const offsetFromBottom = -textarea.scrollTop + 6;\n const offsetFromRight = -textarea.scrollLeft + 6;\n styleEl.innerHTML = `\n ${cssSelector}::after {\n ${dynamicStyles}\n bottom: ${offsetFromBottom}px;\n right: ${offsetFromRight}px;\n }\n `;\n }\n };\n\n textarea?.addEventListener(\"scroll\", handleScroll);\n\n // Cleanup\n return () => {\n document.getElementById(\"dynamic-styles\")?.remove();\n textarea?.removeEventListener(\"scroll\", handleScroll);\n };\n }, [disableBranding, suggestionStyleAugmented]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { BaseSelection } from \"slate\";\nimport { useSlateSelector } from \"slate-react\";\nimport { Range } from \"slate\";\nimport { editorToText } from \"../../lib/editor-to-text\";\n\ninterface TrackerTextEditedSinceLastCursorMovementProps {\n setCursorMovedSinceLastTextChange: (value: boolean) => void;\n}\nexport function TrackerTextEditedSinceLastCursorMovement(\n props: TrackerTextEditedSinceLastCursorMovementProps,\n) {\n const cursorState: RelevantEditorState = useSlateSelector((state) => ({\n selection: state.selection,\n text: editorToText(state),\n }));\n\n const previousState = usePrevious(cursorState);\n\n useEffect(() => {\n if (!previousState) {\n return;\n }\n\n if (cursorChangedWithoutTextChanged(previousState, cursorState)) {\n props.setCursorMovedSinceLastTextChange(true);\n }\n }, [props.setCursorMovedSinceLastTextChange, cursorState]);\n\n return <></>;\n}\n\ntype RelevantEditorState = {\n selection: BaseSelection;\n text: string;\n};\n\nconst cursorChangedWithoutTextChanged = (\n prev: RelevantEditorState,\n next: RelevantEditorState,\n): boolean => {\n // Check if the selection has changed\n const isSelectionChanged = !isSelectionEqual(prev.selection, next.selection);\n\n // Check if the text content remains the same\n const isTextSame = prev.text === next.text;\n\n return isSelectionChanged && isTextSame;\n};\n\nconst isSelectionEqual = (a: BaseSelection, b: BaseSelection) => {\n if (!a && !b) return true;\n if (!a || !b) return false;\n return Range.equals(a, b);\n};\n\n/**\n * Easily keep track of the *previous* value of a variable.\n *\n * Example:\n * ```\n * const [count, setCount] = useState(0);\n * const prevCount = usePrevious(count);\n *\n * useEffect(() => {\n * if (count > prevCount) {\n * console.log('Now I know that count is bigger than before');\n * }\n * }, [count, prevCount]);\n * ```\n */\nfunction usePrevious<T>(value: T): T | undefined {\n const ref = useRef<T>(undefined!);\n\n useEffect(() => {\n ref.current = value;\n });\n\n return ref.current;\n}\n","import { BaseEditor, Descendant, Element } from \"slate\";\nimport { HistoryEditor } from \"slate-history\";\nimport { ReactEditor } from \"slate-react\";\nimport { SuggestionAwareText } from \"../types/base/custom-editor\";\n\nfunction nodeChildrenToTextComponents(\n editor: BaseEditor & ReactEditor & HistoryEditor,\n nodes: Descendant[],\n): SuggestionAwareText[] {\n // find inlineable elements\n const indeciesOfInlineElements = new Set(\n nodes\n .map((node, index) => {\n if (Element.isElement(node) && editor.isInline(node)) {\n return index;\n }\n return -1;\n })\n .filter((index) => index !== -1),\n );\n\n // ignorable elements = inline elements,\n // or neighbors of inline elements that are {text: \"\"}\n const nonIgnorableItems = nodes.filter((node, index) => {\n const isInline = indeciesOfInlineElements.has(index);\n if (isInline) {\n return false;\n }\n\n const isNeighbourOfInline =\n indeciesOfInlineElements.has(index - 1) || indeciesOfInlineElements.has(index + 1);\n if (isNeighbourOfInline) {\n return (node as any).text !== \"\";\n }\n\n return true;\n });\n\n return nonIgnorableItems\n .map((node) => {\n if (Element.isElement(node)) {\n switch (node.type) {\n case \"paragraph\":\n return nodeChildrenToTextComponents(editor, node.children);\n case \"suggestion\":\n return [];\n }\n } else {\n return [node];\n }\n })\n .reduce((acc, val) => acc.concat(val), []);\n}\n\nexport const editorToText = (editor: BaseEditor & ReactEditor & HistoryEditor) => {\n const flattened = nodeChildrenToTextComponents(editor, editor.children);\n\n const text = flattened.map((textComponent) => textComponent.text).join(\"\\n\");\n\n return text;\n};\n","/**\n * <br/>\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/CopilotTextarea.gif\" width=\"500\" />\n *\n * `<CopilotTextarea>` is a React component that acts as a drop-in replacement for the standard `<textarea>`,\n * offering enhanced autocomplete features powered by AI. It is context-aware, integrating seamlessly with the\n * [`useCopilotReadable`](/reference/hooks/useCopilotReadable) hook to provide intelligent suggestions based on the application context.\n *\n * In addition, it provides a hovering editor window (available by default via `Cmd + K` on Mac and `Ctrl + K` on Windows) that allows the user to\n * suggest changes to the text, for example providing a summary or rephrasing the text.\n *\n * ## Example\n *\n * ```tsx\n * import { CopilotTextarea } from '@copilotkit/react-textarea';\n * import \"@copilotkit/react-textarea/styles.css\";\n *\n * <CopilotTextarea\n * autosuggestionsConfig={{\n * textareaPurpose:\n * \"the body of an email message\",\n * chatApiConfigs: {},\n * }}\n * />\n * ```\n *\n * ## Usage\n *\n * ### Install Dependencies\n *\n * This component is part of the [@copilotkit/react-textarea](https://npmjs.com/package/@copilotkit/react-textarea) package.\n *\n * ```shell npm2yarn \\\"@copilotkit/react-textarea\"\\\n * npm install @copilotkit/react-core @copilotkit/react-textarea\n * ```\n *\n * ### Usage\n *\n * Use the CopilotTextarea component in your React application similarly to a standard `<textarea />`,\n * with additional configurations for AI-powered features.\n *\n * For example:\n *\n * ```tsx\n * import { useState } from \"react\";\n * import { CopilotTextarea } from \"@copilotkit/react-textarea\";\n * import \"@copilotkit/react-textarea/styles.css\";\n *\n * export function ExampleComponent() {\n * const [text, setText] = useState(\"\");\n *\n * return (\n * <CopilotTextarea\n * className=\"custom-textarea-class\"\n * value={text}\n * onValueChange={(value: string) => setText(value)}\n * placeholder=\"Enter your text here...\"\n * autosuggestionsConfig={{\n * textareaPurpose: \"Provide context or purpose of the textarea.\",\n * chatApiConfigs: {\n * suggestionsApiConfig: {\n * maxTokens: 20,\n * stop: [\".\", \"?\", \"!\"],\n * },\n * },\n * }}\n * />\n * );\n * }\n * ```\n *\n * ### Look & Feel\n *\n * By default, CopilotKit components do not have any styles. You can import CopilotKit's stylesheet at the root of your project:\n * ```tsx title=\"YourRootComponent.tsx\"\n * ...\n * import \"@copilotkit/react-textarea/styles.css\"; // [!code highlight]\n *\n * export function YourRootComponent() {\n * return (\n * <CopilotKit>\n * ...\n * </CopilotKit>\n * );\n * }\n * ```\n * For more information about how to customize the styles, check out the [Customize Look & Feel](/guides/custom-look-and-feel/customize-built-in-ui-components) guide.\n * */\nimport React from \"react\";\nimport { useMakeStandardAutosuggestionFunction } from \"../../hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function\";\nimport { HTMLCopilotTextAreaElement } from \"../../types\";\nimport { BaseCopilotTextareaProps } from \"../../types/base/base-copilot-textarea-props\";\nimport {\n AutosuggestionsConfig,\n defaultAutosuggestionsConfig,\n} from \"../../types/autosuggestions-config\";\nimport { BaseCopilotTextarea } from \"../base-copilot-textarea/base-copilot-textarea\";\nimport { useMakeStandardInsertionOrEditingFunction } from \"../../hooks/make-autosuggestions-function/use-make-standard-insertion-function\";\nimport merge from \"lodash.merge\";\nimport { AutosuggestionsConfigUserSpecified } from \"../../types/autosuggestions-config/autosuggestions-config-user-specified\";\n\n// Like the base copilot textarea props,\n// but with baseAutosuggestionsConfig replaced with autosuggestionsConfig.\nexport interface CopilotTextareaProps\n extends Omit<BaseCopilotTextareaProps, \"baseAutosuggestionsConfig\"> {\n /**\n * Configuration settings for the autosuggestions feature.\n * For full reference, [check the interface on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/packages/react-textarea/src/types/base/base-copilot-textarea-props.tsx#L8).\n *\n * <PropertyReference name=\"textareaPurpose\" type=\"string\" required={true} >\n * The purpose of the text area in plain text.\n *\n * Example: *\"The body of the email response\"*\n * </PropertyReference>\n *\n * <PropertyReference name=\"chatApiConfigs\" type=\"ChatApiConfigs\" >\n * The chat API configurations.\n *\n * <strong>NOTE:</strong> You must provide specify at least one of `suggestionsApiConfig` or `insertionApiConfig`.\n *\n * <PropertyReference name=\"suggestionsApiConfig\" type=\"SuggestionsApiConfig\">\n * For full reference, please [click here](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/packages/react-textarea/src/types/autosuggestions-config/suggestions-api-config.tsx#L4).\n * </PropertyReference>\n * <PropertyReference name=\"insertionApiConfig\" type=\"InsertionApiConfig\">\n * For full reference, please [click here](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/packages/react-textarea/src/types/autosuggestions-config/insertions-api-config.tsx#L4).\n * </PropertyReference>\n * </PropertyReference>\n *\n * <PropertyReference name=\"disabled\" type=\"boolean\" >\n * Whether the textarea is disabled.\n * </PropertyReference>\n *\n * <PropertyReference name=\"disableBranding\" type=\"boolean\" >\n * Whether to disable the CopilotKit branding.\n * </PropertyReference>\n *\n * <PropertyReference name=\"placeholderStyle\" type=\"React.CSSProperties\" >\n * Specifies the CSS styles to apply to the placeholder text.\n * </PropertyReference>\n *\n * <PropertyReference name=\"suggestionsStyle\" type=\"React.CSSProperties\" >\n * Specifies the CSS styles to apply to the suggestions list.\n * </PropertyReference>\n *\n * <PropertyReference name=\"hoverMenuClassname\" type=\"string\" >\n * A class name to apply to the editor popover window.\n * </PropertyReference>\n *\n * <PropertyReference name=\"value\" type=\"string\" >\n * The initial value of the textarea. Can be controlled via `onValueChange`.\n * </PropertyReference>\n *\n * <PropertyReference name=\"onValueChange\" type=\"(value: string) => void\" >\n * Callback invoked when the value of the textarea changes.\n * </PropertyReference>\n *\n * <PropertyReference name=\"onChange\" type=\"(event: React.ChangeEvent<HTMLTextAreaElement>) => void\" >\n * Callback invoked when a `change` event is triggered on the textarea element.\n * </PropertyReference>\n *\n * <PropertyReference name=\"shortcut\" type=\"string\" >\n * The shortcut to use to open the editor popover window. Default is `\"Cmd-k\"`.\n * </PropertyReference>\n */\n autosuggestionsConfig: AutosuggestionsConfigUserSpecified;\n}\n\n/**\n * A copilot textarea that uses the standard autosuggestions function.\n */\nexport const CopilotTextarea = React.forwardRef(\n (props: CopilotTextareaProps, ref: React.Ref<HTMLCopilotTextAreaElement>) => {\n // separate the AutosuggestionsConfigUserSpecified from the rest of the props\n const { autosuggestionsConfig: autosuggestionsConfigUserSpecified, ...forwardedProps } = props;\n\n const autosuggestionsConfig: AutosuggestionsConfig = merge(\n defaultAutosuggestionsConfig,\n autosuggestionsConfigUserSpecified,\n );\n\n const autosuggestionsFunction = useMakeStandardAutosuggestionFunction(\n autosuggestionsConfig.textareaPurpose,\n autosuggestionsConfig.contextCategories,\n autosuggestionsConfig.chatApiConfigs.suggestionsApiConfig,\n );\n\n const insertionOrEditingFunction = useMakeStandardInsertionOrEditingFunction(\n autosuggestionsConfig.textareaPurpose,\n autosuggestionsConfig.contextCategories,\n autosuggestionsConfig.chatApiConfigs.insertionApiConfig,\n autosuggestionsConfig.chatApiConfigs.editingApiConfig,\n );\n\n return (\n <>\n <BaseCopilotTextarea\n ref={ref}\n {...forwardedProps}\n baseAutosuggestionsConfig={{\n ...autosuggestionsConfig,\n apiConfig: {\n insertionOrEditingFunction: insertionOrEditingFunction,\n autosuggestionsFunction: autosuggestionsFunction,\n },\n }}\n />\n </>\n );\n },\n);\n","import { COPILOT_CLOUD_PUBLIC_API_KEY_HEADER } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"@copilotkit/react-core\";\nimport { useCallback } from \"react\";\nimport { AutosuggestionsBareFunction } from \"../../types\";\nimport { retry } from \"../../lib/retry\";\nimport { InsertionEditorState } from \"../../types/base/autosuggestions-bare-function\";\nimport { SuggestionsApiConfig } from \"../../types/autosuggestions-config/suggestions-api-config\";\nimport {\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\n\n/**\n * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n * The function takes in the text before and after the cursor, and an abort signal.\n * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.\n * The function returns the suggestion from the API response.\n *\n * @param textareaPurpose - The purpose of the textarea. This is included in the system message.\n * @param apiEndpoint - The API endpoint to send the autosuggestion request to.\n * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.\n * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.\n * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) \"global\" context category.\n * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n */\nexport function useMakeStandardAutosuggestionFunction(\n textareaPurpose: string,\n contextCategories: string[],\n apiConfig: SuggestionsApiConfig,\n): AutosuggestionsBareFunction {\n const runtimeClient = { generateCopilotResponse: (...args: any[]) => {} };\n const { getContextString, copilotApiConfig } = useCopilotContext();\n const { chatApiEndpoint: url, publicApiKey, credentials, properties } = copilotApiConfig;\n const headers = {\n ...copilotApiConfig.headers,\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n const { maxTokens, stop, temperature = 0 } = apiConfig;\n\n return useCallback(\n async (editorState: InsertionEditorState, abortSignal: AbortSignal) => {\n const res = await retry(async () => {\n // @ts-expect-error -- Passing null is forbidden, but we're filtering it later\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: apiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString([], contextCategories),\n ),\n }),\n ...apiConfig.fewShotMessages,\n editorState.textAfterCursor != \"\"\n ? new TextMessage({\n role: Role.User,\n content: editorState.textAfterCursor,\n })\n : null,\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n ].filter(Boolean);\n\n // const response = await runtimeClient\n // .generateCopilotResponse({\n // data: {\n // frontend: {\n // actions: [],\n // url: window.location.href,\n // },\n // messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n // metadata: {\n // requestType: CopilotRequestType.TextareaCompletion,\n // },\n // forwardedParameters: {\n // maxTokens,\n // stop,\n // temperature,\n // },\n // },\n // properties,\n // signal: abortSignal,\n // })\n // .toPromise();\n const response: any = {};\n\n let result = \"\";\n for (const message of convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages ?? [],\n )) {\n if (abortSignal.aborted) {\n break;\n }\n if (message.isTextMessage()) {\n result += message.content;\n }\n }\n\n return result;\n });\n\n return res;\n },\n [apiConfig, getContextString, contextCategories, textareaPurpose],\n );\n}\n","export function retry<T>(\n fn: () => Promise<T>,\n retriesLeft: number = 2,\n interval: number = 200,\n backoff: number = 1.5,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n fn()\n .then(resolve)\n .catch((error) => {\n if (retriesLeft === 1) {\n reject(error);\n return;\n }\n\n setTimeout(() => {\n retry(fn, retriesLeft - 1, interval * backoff, backoff)\n .then(resolve)\n .catch(reject);\n }, interval);\n });\n });\n}\n","import { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { MakeSystemPrompt } from \"./subtypes/make-system-prompt\";\n\nexport interface SuggestionsApiConfig {\n makeSystemPrompt: MakeSystemPrompt;\n fewShotMessages: Message[];\n maxTokens?: number;\n stop?: string[];\n temperature?: number;\n}\n\nexport const defaultSuggestionsMakeSystemPrompt: MakeSystemPrompt = (\n textareaPurpose,\n contextString,\n) => {\n return `You are a versatile writing assistant.\n \nThe user is writing some text.\nThe purpose is: \\\"${textareaPurpose}\\\"\n\nYour job is to guess what the user will write next AS BEST YOU CAN.\nOnly guess a SHORT distance ahead. Usually 1 sentence, or at most 1 paragraph.\n\nAdjust yourself to the user's style and implied intent.\n\nThe user will provide both the text before and after the cursor. You should use this to infer what the user is likely to write next.\n<TextAfterCursor>\n<TextBeforeCursor>\n<YourSuggestion>\n\nIf we need to add a whitespace character to the suggested text, make sure to explicitly add it in.\nRefrain from adding <YourSuggestion> tags when responding\n\nThe following external context is also provided. Use it to help you make better suggestions!!!\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n`;\n};\n\nexport const defaultSuggestionsFewShotMessages: Message[] = [\n new TextMessage({\n role: Role.User,\n content:\n \"<TextAfterCursor>While I was there I also picked up some apples, oranges, and bananas.</TextAfterCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content: \"This morning I woke up and went straight to the grocery store.\",\n }),\n new TextMessage({\n role: Role.Assistant,\n content:\n \" When I arrived I went straight to the produce section and picked out a big watermelon. \",\n }),\n new TextMessage({\n role: Role.User,\n content:\n \"<TextAfterCursor>and (iii) to the appointment of the Equityholders' Representative pursuant to Section 10.7 of the Merger Agreement and to the provisions thereof.</TextAfterCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content:\n '<TextBeforeCursor>The Optionholder, in the Optionholder\\'s capacity as a holder of vested Options, hereby irrevocably and unconditionally agrees: (i) that the Optionholder shall be deemed an \"Equityholder\" under the Merger Agreement and shall be entitled to the rights and benefits, and subject to the obligations, of an \"Equityholder\" thereunder;</TextBeforeCursor>',\n }),\n new TextMessage({\n role: Role.Assistant,\n content:\n ' (ii) that, for purposes of this Agreement and the Merger Agreement, the applicable percentage set forth opposite the name of the Optionholder in the Distribution Waterfall shall be such the Optionholder\\'s \"Pro Rata Share\"; ',\n }),\n];\n\nexport const defaultSuggestionsApiConfig: SuggestionsApiConfig = {\n makeSystemPrompt: defaultSuggestionsMakeSystemPrompt,\n fewShotMessages: defaultSuggestionsFewShotMessages,\n};\n","import { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { MakeSystemPrompt } from \"./subtypes/make-system-prompt\";\n\nexport interface InsertionsApiConfig {\n makeSystemPrompt: MakeSystemPrompt;\n fewShotMessages: Message[];\n forwardedParams: { [key: string]: any } | undefined;\n}\n\nexport const defaultInsertionsMakeSystemPrompt: MakeSystemPrompt = (\n textareaPurpose,\n contextString,\n) => {\n return `You are a versatile writing assistant helping the user insert new text into their existing work.\n \nThe user is writing some text.\nThe purpose is: \\\"${textareaPurpose}\\\"\n\nThe following external context is also provided. Use it to inform your suggestions when relevant!!!\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThe user will provide you with a prompt for an INSERTION into the text they are writing. \nYour job is to come up with an INSERTION into the text that the user would like to use, AS BEST YOU CAN.\nOnly insert a SHORT segment. Usually 1 sentence, or at most 1 paragraph.\n\nAdjust yourself to the user's style and implied intent.\n\n\nThe user will provide the text before and after the cursor, as well as the INSERTION prompt. You should use this to infer the best relevant insertion.\nThe conversation will be structured as follows:\n<TextAfterCursor>\n<TextBeforeCursor>\n<InsertionPrompt>\n\n<YourInsertionSuggestion>\n`;\n};\n\nexport const defaultInsertionsFewShotMessages: Message[] = [\n new TextMessage({\n role: Role.User,\n content:\n \"<TextAfterCursor>While I was there I also picked up some apples, oranges, and bananas.</TextAfterCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content:\n \"<TextBeforeCursor>This morning I woke up and went straight to the grocery store.</TextBeforeCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content: \"<InsertionPrompt>I bought a big watermelon</InsertionPrompt>\",\n }),\n new TextMessage({\n role: Role.Assistant,\n content:\n \"When I arrived I went straight to the produce section and picked out a big watermelon.\",\n }),\n new TextMessage({\n role: Role.User,\n content:\n \"<TextAfterCursor>and (iii) to the appointment of the Equityholders' Representative pursuant to Section 10.7 of the Merger Agreement and to the provisions thereof.</TextAfterCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content:\n '<TextBeforeCursor>The Optionholder, in the Optionholder\\'s capacity as a holder of vested Options, hereby irrevocably and unconditionally agrees: (i) that the Optionholder shall be deemed an \"Equityholder\" under the Merger Agreement and shall be entitled to the rights and benefits, and subject to the obligations, of an \"Equityholder\" thereunder;</TextBeforeCursor>',\n }),\n new TextMessage({\n role: Role.User,\n content:\n \"<InsertionPrompt>add section about the optionholder's pro rata share</InsertionPrompt>\",\n }),\n new TextMessage({\n role: Role.Assistant,\n content:\n ' (ii) that, for purposes of this Agreement and the Merger Agreement, the applicable percentage set forth opposite the name of the Optionholder in the Distribution Waterfall shall be such the Optionholder\\'s \"Pro Rata Share\"; ',\n }),\n];\n\nexport const defaultInsertionsApiConfig: InsertionsApiConfig = {\n makeSystemPrompt: defaultInsertionsMakeSystemPrompt,\n fewShotMessages: defaultInsertionsFewShotMessages,\n forwardedParams: undefined,\n};\n","import { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { MakeSystemPrompt } from \"./subtypes/make-system-prompt\";\n\nexport interface EditingApiConfig {\n makeSystemPrompt: MakeSystemPrompt;\n fewShotMessages: Message[];\n forwardedParams: { [key: string]: any } | undefined;\n}\n\nexport const defaultEditingMakeSystemPrompt: MakeSystemPrompt = (\n textareaPurpose,\n contextString,\n) => {\n return `You are a versatile writing assistant helping the user edit a portion of their text.\n \nThe user is writing some text.\nThe purpose is: \\\"${textareaPurpose}\\\"\n\nThe following external context is also provided. Use it when relevant.\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThe user has provided you with a PROMPT for EDITING a PORTION of the text. \nYour job is to come up with a new EDITED version OF THE SEGMENT IN QUESTION - AS BEST YOU CAN.\nOnly rewrite the portion of the text that the user has marked as \"TextToEdit\"!!!\n\nAdjust yourself to the user's style and implied intent.\n\nThe conversation will be structured as follows:\n<TextBeforeCursor>\n<TextToEdit>\n<TextAfterCursor>\n<EditingPrompt>\n\n<YourEditSuggestion>\n`;\n};\n\nexport const defaultEditingFewShotMessages: Message[] = [\n new TextMessage({\n role: Role.User,\n content:\n \"<TextBeforeCursor>This morning I woke up and went straight to the grocery store. </TextBeforeCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content:\n \"<TextToEdit>While I was there I picked up some apples, oranges, and bananas. </TextToEdit>\",\n }),\n new TextMessage({\n role: Role.User,\n content:\n \"<TextAfterCursor>The grocery store was having a sale on fruit, so I decided to stock up.</TextAfterCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content: \"<EditingPrompt>I also bought a big watermelon</EditingPrompt>\",\n }),\n new TextMessage({\n role: Role.Assistant,\n content:\n \"While I was there I picked up some apples, oranges, and bananas, and a big watermelon.\",\n }),\n\n new TextMessage({\n role: Role.User,\n content:\n \"<TextBeforeCursor>Yesterday, I spent the afternoon working on my new project.</TextBeforeCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content: \"<TextToEdit>It's quite challenging and requires a lot of focus.</TextToEdit>\",\n }),\n new TextMessage({\n role: Role.User,\n content:\n \"<TextAfterCursor>I'm really excited about the potential outcomes of this project.</TextAfterCursor>\",\n }),\n new TextMessage({\n role: Role.User,\n content:\n \"<EditingPrompt>emphasize the complexity and my enthusiasm for the project</EditingPrompt>\",\n }),\n new TextMessage({\n role: Role.Assistant,\n content:\n \"It's a highly complex task that demands intense concentration, but I'm incredibly enthusiastic about the promising prospects of this project.\",\n }),\n];\n\nexport const defaultEditingApiConfig: EditingApiConfig = {\n makeSystemPrompt: defaultEditingMakeSystemPrompt,\n fewShotMessages: defaultEditingFewShotMessages,\n forwardedParams: undefined,\n};\n","import { BaseAutosuggestionsConfig, defaultBaseAutosuggestionsConfig } from \"../base\";\nimport { SuggestionsApiConfig, defaultSuggestionsApiConfig } from \"./suggestions-api-config\";\nimport { InsertionsApiConfig, defaultInsertionsApiConfig } from \"./insertions-api-config\";\nimport { EditingApiConfig, defaultEditingApiConfig } from \"./editing-api-config\";\nimport { defaultCopilotContextCategories } from \"@copilotkit/react-core\";\n\n// Like the base autosuggestions config, with 2 additional fields:\n// 1. contextCategories: string[] | undefined;\n// 2. instead of apiConfigs, we have chatApiConfigs: a higher-level abstraction that uses a ChatGPT-like API endpoint.\nexport interface AutosuggestionsConfig extends Omit<BaseAutosuggestionsConfig, \"apiConfig\"> {\n contextCategories: string[];\n chatApiConfigs: {\n suggestionsApiConfig: SuggestionsApiConfig;\n insertionApiConfig: InsertionsApiConfig;\n editingApiConfig: EditingApiConfig;\n };\n}\n\nexport const defaultAutosuggestionsConfig: Omit<\n AutosuggestionsConfig,\n \"textareaPurpose\" | \"apiEndpoint\"\n> = {\n ...defaultBaseAutosuggestionsConfig,\n contextCategories: defaultCopilotContextCategories,\n chatApiConfigs: {\n suggestionsApiConfig: defaultSuggestionsApiConfig,\n insertionApiConfig: defaultInsertionsApiConfig,\n editingApiConfig: defaultEditingApiConfig,\n },\n};\n","import { COPILOT_CLOUD_PUBLIC_API_KEY_HEADER } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"@copilotkit/react-core\";\nimport { useCallback } from \"react\";\nimport {\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { retry } from \"../../lib/retry\";\nimport {\n EditingEditorState,\n Generator_InsertionOrEditingSuggestion,\n} from \"../../types/base/autosuggestions-bare-function\";\nimport { InsertionsApiConfig } from \"../../types/autosuggestions-config/insertions-api-config\";\nimport { EditingApiConfig } from \"../../types/autosuggestions-config/editing-api-config\";\nimport { DocumentPointer } from \"@copilotkit/react-core\";\n\n/**\n * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n * The function takes in the text before and after the cursor, and an abort signal.\n * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.\n * The function returns the suggestion from the API response.\n *\n * @param textareaPurpose - The purpose of the textarea. This is included in the system message.\n * @param apiEndpoint - The API endpoint to send the autosuggestion request to.\n * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.\n * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.\n * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) \"global\" context category.\n * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.\n */\nexport function useMakeStandardInsertionOrEditingFunction(\n textareaPurpose: string,\n contextCategories: string[],\n insertionApiConfig: InsertionsApiConfig,\n editingApiConfig: EditingApiConfig,\n): Generator_InsertionOrEditingSuggestion {\n const runtimeClient: any = { generateCopilotResponse: (...args: any[]) => {} };\n const { getContextString, copilotApiConfig } = useCopilotContext();\n const headers = {\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n };\n\n async function runtimeClientResponseToStringStream(\n responsePromise: ReturnType<typeof runtimeClient.generateCopilotResponse>,\n ) {\n const messagesStream = runtimeClient.asStream(responsePromise);\n\n return new ReadableStream({\n async start(controller) {\n const reader = messagesStream.getReader();\n let sentContent = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n let newContent = \"\";\n\n for (const message of messages) {\n if (message.isTextMessage()) {\n newContent += message.content;\n }\n }\n if (newContent) {\n const contentToSend = newContent.slice(sentContent.length);\n controller.enqueue(contentToSend);\n sentContent += contentToSend;\n }\n }\n controller.close();\n },\n });\n }\n\n const insertionFunction = useCallback(\n async (\n editorState: EditingEditorState,\n insertionPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n const res = await retry(async () => {\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: insertionApiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString(documents, contextCategories),\n ),\n }),\n ...insertionApiConfig.fewShotMessages,\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<InsertionPrompt>${insertionPrompt}</InsertionPrompt>`,\n }),\n ];\n\n return runtimeClientResponseToStringStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [],\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.TextareaCompletion,\n },\n },\n properties: copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n });\n\n return res;\n },\n [insertionApiConfig, getContextString, contextCategories, textareaPurpose],\n );\n\n const editingFunction = useCallback(\n async (\n editorState: EditingEditorState,\n editingPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n const res = await retry(async () => {\n const messages: Message[] = [\n new TextMessage({\n role: Role.System,\n content: editingApiConfig.makeSystemPrompt(\n textareaPurpose,\n getContextString(documents, contextCategories),\n ),\n }),\n ...editingApiConfig.fewShotMessages,\n new TextMessage({\n role: Role.User,\n content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextToEdit>${editorState.selectedText}</TextToEdit>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`,\n }),\n new TextMessage({\n role: Role.User,\n content: `<EditingPrompt>${editingPrompt}</EditingPrompt>`,\n }),\n ];\n\n return runtimeClientResponseToStringStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [],\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.TextareaCompletion,\n },\n },\n properties: copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n });\n\n return res;\n },\n [editingApiConfig, getContextString, contextCategories, textareaPurpose],\n );\n\n const insertionOrEditingFunction = useCallback(\n async (\n editorState: EditingEditorState,\n insertionPrompt: string,\n documents: DocumentPointer[],\n abortSignal: AbortSignal,\n ) => {\n if (editorState.selectedText === \"\") {\n return await insertionFunction(editorState, insertionPrompt, documents, abortSignal);\n } else {\n return await editingFunction(editorState, insertionPrompt, documents, abortSignal);\n }\n },\n [insertionFunction, editingFunction],\n );\n\n return insertionOrEditingFunction;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAAiE;AACjE,IAAAC,iBAAmC;AACnC,IAAAC,sBAAgC;AAChC,IAAAC,yBAAwB;;;ACHxB,mBAA0D;;;ACEnD,IAAM,YAAN,MAAiC;AAAA,EAItC,YAAoB,MAAc;AAAd;AAEpB,oBAAW,CAAO,SAA2B,SAAY;AAEvD,WAAK,OAAO;AAEZ,WAAK,YAAY,WAAW,MAAY;AACtC,YAAI;AACF,eAAK,wBAAwB,IAAI,gBAAgB;AAGjD,gBAAM,KAAK,GAAG,MAAM,KAAK,sBAAsB,MAAM;AAErD,eAAK,wBAAwB;AAAA,QAC/B,SAAS,OAAP;AAAA,QAAe;AAAA,MACnB,IAAG,KAAK,IAAI;AAAA,IACd;AAEA,kBAAS,MAAM;AACb,UAAI,KAAK,uBAAuB;AAC9B,aAAK,sBAAsB,MAAM;AACjC,aAAK,wBAAwB;AAAA,MA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AW;AAAA,MACrF,OAAO;AACL,eAAO,MAAM,gBAAgBA,cAAa,iBAAiB,WAAW,WAAW;AAAA,MACnF;AAAA,IACF;AAAA,IACA,CAAC,mBAAmB,eAAe;AAAA,EACrC;AAEA,SAAO;AACT;;;APpHA,oBAAkB;AAgGZ,IAAAC,uBAAA;AAxBC,IAAM,kBAAkB,eAAAC,QAAM;AAAA,EACnC,CAAC,OAA6B,QAA+C;AAE3E,UAAyF,YAAjF,yBAAuB,mCA7KnC,IA6K6F,IAAnB,2BAAmB,IAAnB,CAA9D;AAER,UAAM,4BAA+C,cAAAC;AAAA,MACnD;AAAA,MACA;AAAA,IACF;AAEA,UAAM,0BAA0B;AAAA,MAC9B,sBAAsB;AAAA,MACtB,sBAAsB;AAAA,MACtB,sBAAsB,eAAe;AAAA,IACvC;AAEA,UAAM,6BAA6B;AAAA,MACjC,sBAAsB;AAAA,MACtB,sBAAsB;AAAA,MACtB,sBAAsB,eAAe;AAAA,MACrC,sBAAsB,eAAe;AAAA,IACvC;AAEA,WACE,+EACE;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,SACI,iBAFL;AAAA,QAGC,2BAA2B,iCACtB,wBADsB;AAAA,UAEzB,WAAW;AAAA,YACT;AAAA,YACA;AAAA,UACF;AAAA,QACF;AAAA;AAAA,IACF,GACF;AAAA,EAEJ;AACF;","names":["import_react","import_slate","import_slate_react","import_tailwind_merge","import_react","import_slate","shouldSave","merge","editor","import_react","import_slate_react","import_slate","import_slate","React","customMethods","editorHtmlElement","editor","import_slate","import_slate","import_react","import_slate","import_slate_react","import_react","import_react","import_jsx_runtime","React","ReactDOM","import_react","import_react","React","import_jsx_runtime","CommandPrimitive","CommandPrimitive","import_jsx_runtime","import_react_core","React","import_jsx_runtime","Button","React","import_class_variance_authority","import_jsx_runtime","import_react","import_jsx_runtime","Chip","Avatar","import_jsx_runtime","Button","import_jsx_runtime","import_jsx_runtime","selection","import_jsx_runtime","import_jsx_runtime","import_react","styleEl","import_react","import_slate_react","import_slate","import_slate","import_jsx_runtime","import_jsx_runtime","React","_a","value","import_react","import_shared","import_react_core","import_react","editorState","import_runtime_client_gql","import_runtime_client_gql","import_runtime_client_gql","import_react_core","import_shared","import_react_core","import_react","import_runtime_client_gql","editorState","import_jsx_runtime","React","merge"]}
|