Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhanced Placeholder Configuration in LibreChat Prompt Library #3618

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 91 additions & 23 deletions client/src/components/Prompts/Groups/VariableForm.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,56 @@
import { useMemo } from 'react';
import React, { useMemo, useState } from 'react';
import { useForm, useFieldArray, Controller, useWatch } from 'react-hook-form';
import type { TPromptGroup } from 'librechat-data-provider';
import { extractVariableInfo, wrapVariable, replaceSpecialVars } from '~/utils';
import { useAuthContext, useLocalize, useSubmitMessage } from '~/hooks';
import { Textarea } from '~/components/ui';
import { TextareaAutosize, Input, InputWithDropdown } from '~/components/ui';

type FieldType = 'text' | 'multiline' | 'select';

type FieldConfig = {
variable: string;
type: FieldType;
options?: string[];
};

type FormValues = {
fields: { variable: string; value: string }[];
fields: { variable: string; value: string; config: FieldConfig }[];
};

/**
* Variable Format Guide:
*
* Variables in prompts should be enclosed in double curly braces: {{variable}}
*
* Simple text input:
* {{variable_name}}
*
* Multiline text input:
* {{variable_name:multiline}}
*
* Dropdown select with predefined options:
* {{variable_name:option1|option2|option3}}
*
* All dropdown selects allow custom input in addition to predefined options.
*
* Examples:
* {{name}} - Simple text input for a name
* {{email:multiline}} - Multiline input for an email
* {{tone:formal|casual|business casual}} - Dropdown for tone selection with custom input option
*
* Note: The order of variables in the prompt will be preserved in the input form.
*/

const parseFieldConfig = (variable: string): FieldConfig => {
const content = variable;
if (content.includes(':')) {
const [name, options] = content.split(':');
if (options && options.includes('|')) {
return { variable: name, type: 'select', options: options.split('|') };
}
return { variable: name, type: options as FieldType };
}
return { variable: content, type: 'text' };
};

export default function VariableForm({
Expand All @@ -30,9 +74,13 @@ export default function VariableForm({
);

const { submitPrompt } = useSubmitMessage();
const { control, handleSubmit } = useForm<FormValues>({
const { control, handleSubmit, setValue } = useForm<FormValues>({
defaultValues: {
fields: uniqueVariables.map((variable) => ({ variable: wrapVariable(variable), value: '' })),
fields: uniqueVariables.map((variable) => ({
variable: wrapVariable(variable),
value: '',
config: parseFieldConfig(variable),
})),
},
});

Expand All @@ -46,6 +94,8 @@ export default function VariableForm({
name: 'fields',
});

const [customOptions, setCustomOptions] = useState<{ [key: string]: string }>({});

if (!uniqueVariables.length) {
return null;
}
Expand Down Expand Up @@ -96,35 +146,53 @@ export default function VariableForm({
<div className="mb-6 max-h-screen overflow-auto rounded-md bg-gray-100 p-4 dark:bg-gray-700/50 dark:text-gray-300 md:max-h-80">
<p className="text-md whitespace-pre-wrap">{generateHighlightedText()}</p>
</div>
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4">
<div className="space-y-4">
{fields.map((field, index) => (
<div key={field.id} className="flex flex-col">
<div key={field.id} className="flex flex-col space-y-2">
<Controller
name={`fields.${index}.value`}
control={control}
render={({ field }) => (
<Textarea
{...field}
id={`fields.${index}.value`}
className="input text-grey-darker h-10 rounded border px-3 py-2 focus:bg-white dark:border-gray-500 dark:focus:bg-gray-700"
placeholder={uniqueVariables[index]}
onKeyDown={(e) => {
// Submit the form on enter like you would with an Input component
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit((data) => onSubmit(data))();
}
}}
/>
)}
render={({ field: inputField }) => {
switch (field.config.type) {
case 'multiline':
return (
<TextareaAutosize
{...inputField}
id={`fields.${index}.value`}
className="w-full rounded border px-3 py-2"
placeholder={`Enter ${field.config.variable}`}
maxRows={8}
/>
);
case 'select':
return (
<InputWithDropdown
{...inputField}
id={`fields.${index}.value`}
className="w-full rounded border px-3 py-2"
placeholder={`Enter ${field.config.variable}`}
options={field.config.options || []}
/>
);
default:
return (
<Input
{...inputField}
id={`fields.${index}.value`}
className="w-full rounded border px-3 py-2"
placeholder={`Enter ${field.config.variable}`}
/>
);
}
}}
/>
</div>
))}
</div>
<div className="flex justify-end">
<button
type="submit"
className="btn rounded bg-green-500 font-bold text-white transition-all hover:bg-green-600"
className="btn rounded bg-green-500 px-4 py-2 font-bold text-white transition-all hover:bg-green-600"
>
{localize('com_ui_submit')}
</button>
Expand Down
155 changes: 155 additions & 0 deletions client/src/components/ui/InputWithDropDown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import * as React from 'react';
import { cn } from '../../utils';

export type InputWithDropdownProps = React.InputHTMLAttributes<HTMLInputElement> & {
options: string[];
onSelect?: (value: string) => void;
};

const InputWithDropdown = React.forwardRef<HTMLInputElement, InputWithDropdownProps>(
({ className, options, onSelect, ...props }, ref) => {
const [isOpen, setIsOpen] = React.useState(false);
const [inputValue, setInputValue] = React.useState((props.value as string) || '');
const [highlightedIndex, setHighlightedIndex] = React.useState(-1);
const inputRef = React.useRef<HTMLInputElement>(null);

const handleSelect = (value: string) => {
setInputValue(value);
setIsOpen(false);
setHighlightedIndex(-1);
if (onSelect) {
onSelect(value);
}
if (props.onChange) {
props.onChange({ target: { value } } as React.ChangeEvent<HTMLInputElement>);
}
};

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
if (props.onChange) {
props.onChange(e);
}
};

const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
if (!isOpen) {
setIsOpen(true);
} else {
setHighlightedIndex((prevIndex) =>
prevIndex < options.length - 1 ? prevIndex + 1 : prevIndex,
);
}
break;
case 'ArrowUp':
e.preventDefault();
setHighlightedIndex((prevIndex) => (prevIndex > 0 ? prevIndex - 1 : 0));
break;
case 'Enter':
e.preventDefault();
if (isOpen && highlightedIndex !== -1) {
handleSelect(options[highlightedIndex]);
}
setIsOpen(false);
break;
case 'Escape':
setIsOpen(false);
setHighlightedIndex(-1);
break;
}
};

React.useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (inputRef.current && !inputRef.current.contains(event.target as Node)) {
setIsOpen(false);
setHighlightedIndex(-1);
}
};

document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);

return (
<div className="relative" ref={inputRef}>
<div className="relative">
<input
{...props}
value={inputValue}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
aria-haspopup="listbox"
aria-controls="dropdown-list"
className={cn(
'flex h-10 w-full rounded-md border border-gray-300 bg-transparent px-3 py-2 pr-10 text-sm placeholder:text-gray-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:text-gray-50',
className ?? '',
)}
ref={ref}
/>
<button
type="button"
className="absolute inset-y-0 right-0 flex items-center px-2 text-gray-400 hover:text-gray-600"
onClick={() => setIsOpen(!isOpen)}
aria-label={isOpen ? 'Close dropdown' : 'Open dropdown'}
>
<svg
className="h-5 w-5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</svg>
</button>
</div>
{isOpen && (
<ul
id="dropdown-list"
role="listbox"
className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border border-gray-300 bg-white shadow-lg dark:border-gray-700 dark:bg-gray-800"
>
{options.map((option, index) => (
<li
key={index}
role="option"
aria-selected={index === highlightedIndex}
className={cn(
'cursor-pointer px-3 py-2',
index === highlightedIndex
? 'bg-blue-100 dark:bg-blue-700'
: 'hover:bg-gray-100 dark:hover:bg-gray-700',
)}
onClick={() => handleSelect(option)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleSelect(option);
}
}}
tabIndex={0}
>
{option}
</li>
))}
</ul>
)}
</div>
);
},
);

InputWithDropdown.displayName = 'InputWithDropdown';

export default InputWithDropdown;
5 changes: 3 additions & 2 deletions client/src/components/ui/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ export * from './Tooltip';
export { default as Combobox } from './Combobox';
export { default as Dropdown } from './Dropdown';
export { default as FileUpload } from './FileUpload';
export { default as DropdownPopup } from './DropdownPopup';
export { default as DelayedRender } from './DelayedRender';
export { default as ThemeSelector } from './ThemeSelector';
export { default as SelectDropDown } from './SelectDropDown';
export { default as MultiSelectPop } from './MultiSelectPop';
export { default as InputWithDropdown } from './InputWithDropDown';
export { default as SelectDropDownPop } from './SelectDropDownPop';
export { default as MultiSelectDropDown } from './MultiSelectDropDown';
export { default as DropdownPopup } from './DropdownPopup';
export { default as MultiSelectDropDown } from './MultiSelectDropDown';