Skip to content
Merged
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
159 changes: 155 additions & 4 deletions src/components/SettingDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import {
ArrowPathIcon,
ArrowUpTrayIcon,
BeakerIcon,
BookmarkIcon,
ChatBubbleLeftEllipsisIcon,
ChatBubbleLeftRightIcon,
ChatBubbleOvalLeftEllipsisIcon,
CircleStackIcon,
CloudArrowDownIcon,
CloudArrowUpIcon,
Cog6ToothIcon,
CogIcon,
CpuChipIcon,
Expand All @@ -15,20 +18,22 @@ import {
HandRaisedIcon,
RocketLaunchIcon,
SquaresPlusIcon,
TrashIcon,
TvIcon,
} from '@heroicons/react/24/outline';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import React, { FC, ReactElement, useEffect, useMemo, useState } from 'react';
import { baseUrl, CONFIG_DEFAULT, INFERENCE_PROVIDERS, isDev } from '../config';
import { useAppContext } from '../context/app.context';
import { useInferenceContext } from '../context/inference.context';
import * as lang from '../lang/en.json';
import { OpenInNewTab } from '../utils/common';
import { dateFormatter, OpenInNewTab } from '../utils/common';
import { InferenceApiModel } from '../utils/inferenceApi';
import { classNames, isBoolean, isNumeric, isString } from '../utils/misc';
import StorageUtils from '../utils/storage';
import {
Configuration,
ConfigurationKey,
ConfigurationPreset,
InferenceProvidersKey,
ProviderOption,
} from '../utils/types';
Expand Down Expand Up @@ -60,7 +65,12 @@ interface SettingFieldInput {

interface SettingFieldCustom {
type: SettingInputType.CUSTOM;
key: ConfigurationKey | 'custom' | 'import-export' | 'fetch-models';
key:
| ConfigurationKey
| 'custom'
| 'import-export'
| 'preset-manager'
| 'fetch-models';
component:
| string
| React.FC<{
Expand Down Expand Up @@ -234,6 +244,23 @@ const getSettingTabsConfiguration = (
],
},

/* Presets */
{
title: (
<>
<BookmarkIcon className={ICON_CLASSNAME} />
Presets
</>
),
fields: [
{
type: SettingInputType.CUSTOM,
key: 'preset-manager',
component: UnusedCustomField,
},
],
},

/* Import/Export */
{
title: (
Expand Down Expand Up @@ -599,6 +626,14 @@ export default function SettingDialog({
return (
<ImportExportComponent key={key} onClose={onClose} />
);
case 'preset-manager':
return (
<PresetManager
key={key}
config={localConfig}
onLoadConfig={setLocalConfig}
/>
);
case 'fetch-models':
return (
<button
Expand Down Expand Up @@ -836,7 +871,7 @@ const SettingsModalDropdown: React.FC<{
const SettingsSectionLabel: React.FC<{
children: React.ReactNode;
}> = ({ children }) => (
<div className="pb-2">
<div className="mb-2">
<h4>{children}</h4>
</div>
);
Expand All @@ -845,6 +880,122 @@ const DelimeterComponent: React.FC = () => (
<div className="pb-3" aria-label="delimeter" />
);

const PresetManager: FC<{
config: Configuration;
onLoadConfig: (config: Configuration) => void;
}> = ({ config, onLoadConfig }) => {
const { presets, savePreset, removePreset } = useAppContext();
const { showConfirm, showPrompt } = useModals();

const handleSavePreset = async () => {
const newPresetName = (
(await showPrompt('Enter the new preset name')) || ''
).trim();
if (newPresetName === '') return;

const existingPreset = presets.find((p) => p.name === newPresetName);
if (
!existingPreset ||
(await showConfirm(
`Preset "${newPresetName}" already exists, overwrite it?`
))
) {
await savePreset(newPresetName, config);
}
};

const handleLoadPreset = async (preset: ConfigurationPreset) => {
if (
await showConfirm(
`Load preset "${preset.name}"? Current settings will be replaced.`
)
) {
onLoadConfig(
Object.assign(Object.assign({}, CONFIG_DEFAULT), preset.config)
);
}
};

const handleDeletePreset = async (preset: ConfigurationPreset) => {
if (await showConfirm(`Delete preset "${preset.name}"?`)) {
await removePreset(preset.name);
}
};

return (
<>
{/* Save new preset */}
<SettingsSectionLabel>
{lang.settings.presetManager.newPreset.title}
</SettingsSectionLabel>

<button
className="btn btn-neutral max-w-80 mb-4"
onClick={handleSavePreset}
title="Save new preset"
aria-label="Save new preset"
>
<CloudArrowUpIcon className="w-5 h-5" />
{lang.settings.presetManager.newPreset.saveBtnLabel}
</button>

{/* List of saved presets */}
<SettingsSectionLabel>
{lang.settings.presetManager.savedPresets.title}
</SettingsSectionLabel>

{presets.length === 0 && (
<div className="block opacity-75 max-w-80">
<div
className="text-xs"
dangerouslySetInnerHTML={{
__html: lang.settings.presetManager.savedPresets.noPresetFound,
}}
/>
</div>
)}

{presets.length > 0 && (
<div className="grid grid-rows-1 gap-2 max-h-64 overflow-y-auto">
{presets
.sort((a, b) => b.createdAt - a.createdAt)
.map((preset) => (
<div key={preset.id} className="card bg-base-200 p-3">
<div className="flex items-center justify-between">
<div>
<h4 className="font-medium">{preset.name}</h4>
<p className="text-xs opacity-40">
Created: {dateFormatter.format(preset.createdAt)}
</p>
</div>

<div className="flex gap-2">
<button
className="btn btn-ghost w-8 h-8 p-0 rounded-full"
onClick={() => handleLoadPreset(preset)}
title="Load preset"
aria-label="Load preset"
>
<CloudArrowDownIcon className="w-5 h-5" />
</button>
<button
className="btn btn-ghost w-8 h-8 p-0 rounded-full"
onClick={() => handleDeletePreset(preset)}
title="Delete preset"
aria-label="Delete preset"
>
<TrashIcon className="w-5 h-5" />
</button>
</div>
</div>
</div>
))}
</div>
)}
</>
);
};

const ImportExportComponent: React.FC<{ onClose: () => void }> = ({
onClose,
}) => {
Expand Down
37 changes: 34 additions & 3 deletions src/context/app.context.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { CONFIG_DEFAULT, isDev } from '../config';
import StorageUtils from '../utils/storage';
import { Configuration } from '../utils/types';
import { Configuration, ConfigurationPreset } from '../utils/types';

interface AppContextValue {
config: Configuration;
saveConfig: (config: Configuration) => void;
presets: ConfigurationPreset[];
savePreset: (name: string, config: Configuration) => Promise<void>;
removePreset: (name: string) => Promise<void>;
showSettings: boolean;
setShowSettings: (show: boolean) => void;
}

const AppContext = createContext<AppContextValue>({
config: {} as Configuration,
saveConfig: () => {},
presets: [],
savePreset: () => new Promise(() => {}),
removePreset: () => new Promise(() => {}),
showSettings: false,
setShowSettings: () => {},
});
Expand All @@ -23,11 +30,18 @@ export const AppContextProvider = ({
children: React.ReactElement;
}) => {
const [config, setConfig] = useState<Configuration>(CONFIG_DEFAULT);
const [presets, setPresets] = useState<ConfigurationPreset[]>([]);
const [showSettings, setShowSettings] = useState<boolean>(false);

useEffect(() => {
if (isDev) console.debug('Load config');
setConfig(StorageUtils.getConfig());
const init = async () => {
if (isDev) console.debug('Load config');
setConfig(StorageUtils.getConfig());

if (isDev) console.debug('Load presets');
setPresets(await StorageUtils.getPresets());
};
init();
}, []);

const saveConfig = (config: Configuration) => {
Expand All @@ -36,11 +50,28 @@ export const AppContextProvider = ({
setConfig(config);
};

const savePreset = async (name: string, config: Configuration) => {
if (isDev) console.debug('Save preset', { name, config });
StorageUtils.savePreset(name, config);
setPresets(await StorageUtils.getPresets());
toast.success('Preset is saved successfully');
};

const removePreset = async (name: string) => {
if (isDev) console.debug('Remove preset', name);
StorageUtils.removePreset(name);
setPresets(await StorageUtils.getPresets());
toast.success('Preset is removed successfully');
};

return (
<AppContext.Provider
value={{
config,
saveConfig,
presets,
savePreset,
removePreset,
showSettings,
setShowSettings,
}}
Expand Down
10 changes: 10 additions & 0 deletions src/lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,16 @@
"label": "",
"note": ""
}
},
"presetManager": {
"newPreset": {
"title": "Save current settings as a preset",
"saveBtnLabel": "Save New Preset"
},
"savedPresets": {
"title": "Existing presets",
"noPresetFound": "No presets yet."
}
}
},
"newVersion": {
Expand Down
11 changes: 9 additions & 2 deletions src/utils/common.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,17 @@ export function BtnWithTooltips({
);
}

export const dateFormatter = new Intl.DateTimeFormat(
Intl.DateTimeFormat().resolvedOptions().locale,
{
dateStyle: 'short',
timeStyle: 'short',
}
);

export const timeFormatter = new Intl.DateTimeFormat(
Intl.DateTimeFormat().resolvedOptions().locale,
{
hour: '2-digit',
minute: '2-digit',
timeStyle: 'short',
}
);
Loading