Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
62 lines
2.3 KiB
TypeScript
62 lines
2.3 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
import { get, put } from "../../api";
|
|
import { useT } from "../../i18n";
|
|
import { toast } from "../../dialogs";
|
|
import { Icon } from "../Icon";
|
|
|
|
export interface Snippet {
|
|
id?: string;
|
|
name: string;
|
|
text: string;
|
|
}
|
|
|
|
/** Personal prompt snippets: typed as `/name` in the composer. */
|
|
export function Snippets() {
|
|
const t = useT();
|
|
const [items, setItems] = useState<Snippet[]>();
|
|
useEffect(() => {
|
|
get<Snippet[]>("/account/snippets")
|
|
.then(setItems)
|
|
.catch((e) => toast(e.message));
|
|
}, []);
|
|
if (!items) return null;
|
|
const set = (i: number, patch: Partial<Snippet>) => setItems(items.map((s, j) => (j === i ? { ...s, ...patch } : s)));
|
|
const save = () => {
|
|
const clean = items.filter((s) => s.name.trim() || s.text.trim()).map((s) => ({ ...s, name: s.name.trim().replace(/^\/+/, "").replace(/\s+/g, "-") }));
|
|
put<Snippet[]>("/account/snippets", clean)
|
|
.then((r) => (setItems(r), toast(t("settings.saved"), "success")))
|
|
.catch((e) => toast(e.message));
|
|
};
|
|
return (
|
|
<div className="panel">
|
|
<h3>
|
|
<Icon name="sparkle" /> {t("snippets.title")}
|
|
</h3>
|
|
<div className="hint" style={{ marginBottom: 8 }}>
|
|
{t("snippets.hint")}
|
|
</div>
|
|
{items.map((s, i) => (
|
|
<div key={s.id ?? i} className="snippet-row">
|
|
<div className="row">
|
|
<span className="snippet-slash">/</span>
|
|
<input value={s.name} placeholder={t("snippets.name")} maxLength={40} onChange={(e) => set(i, { name: e.target.value })} aria-label={t("snippets.name")} />
|
|
<button title={t("common.delete")} aria-label={t("common.delete")} onClick={() => setItems(items.filter((_, j) => j !== i))}>
|
|
<Icon name="trash" />
|
|
</button>
|
|
</div>
|
|
<textarea rows={2} value={s.text} placeholder={t("snippets.text")} onChange={(e) => set(i, { text: e.target.value })} aria-label={t("snippets.text")} />
|
|
</div>
|
|
))}
|
|
<div className="row" style={{ marginTop: 8 }}>
|
|
<button onClick={() => setItems([...items, { name: "", text: "" }])}>
|
|
<Icon name="plus" /> {t("snippets.add")}
|
|
</button>
|
|
<span className="grow" />
|
|
<button className="primary" onClick={save}>
|
|
{t("common.save")}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|