generated from nhcarrigan/template
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6635d6ebfb |
+1
-1
@@ -15,7 +15,7 @@
|
||||
"@tauri-apps/plugin-dialog": "2.3.0",
|
||||
"@tauri-apps/plugin-fs": "2.4.0",
|
||||
"react": "19.1.0",
|
||||
"react-dom": "19.1.0"
|
||||
"react-dom": "19.2.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nhcarrigan/eslint-config": "5.2.0",
|
||||
|
||||
Generated
+10
-10
@@ -21,8 +21,8 @@ importers:
|
||||
specifier: 19.1.0
|
||||
version: 19.1.0
|
||||
react-dom:
|
||||
specifier: 19.1.0
|
||||
version: 19.1.0(react@19.1.0)
|
||||
specifier: 19.2.4
|
||||
version: 19.2.4(react@19.1.0)
|
||||
devDependencies:
|
||||
'@nhcarrigan/eslint-config':
|
||||
specifier: 5.2.0
|
||||
@@ -1948,10 +1948,10 @@ packages:
|
||||
queue-microtask@1.2.3:
|
||||
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
|
||||
|
||||
react-dom@19.1.0:
|
||||
resolution: {integrity: sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==}
|
||||
react-dom@19.2.4:
|
||||
resolution: {integrity: sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==}
|
||||
peerDependencies:
|
||||
react: ^19.1.0
|
||||
react: ^19.2.4
|
||||
|
||||
react-is@16.13.1:
|
||||
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
|
||||
@@ -2037,8 +2037,8 @@ packages:
|
||||
resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
scheduler@0.26.0:
|
||||
resolution: {integrity: sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==}
|
||||
scheduler@0.27.0:
|
||||
resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}
|
||||
|
||||
semver@5.7.2:
|
||||
resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==}
|
||||
@@ -4435,10 +4435,10 @@ snapshots:
|
||||
|
||||
queue-microtask@1.2.3: {}
|
||||
|
||||
react-dom@19.1.0(react@19.1.0):
|
||||
react-dom@19.2.4(react@19.1.0):
|
||||
dependencies:
|
||||
react: 19.1.0
|
||||
scheduler: 0.26.0
|
||||
scheduler: 0.27.0
|
||||
|
||||
react-is@16.13.1: {}
|
||||
|
||||
@@ -4568,7 +4568,7 @@ snapshots:
|
||||
es-errors: 1.3.0
|
||||
is-regex: 1.2.1
|
||||
|
||||
scheduler@0.26.0: {}
|
||||
scheduler@0.27.0: {}
|
||||
|
||||
semver@5.7.2: {}
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 298 KiB After Width: | Height: | Size: 155 KiB |
+21
-56
@@ -46,19 +46,12 @@ fn build_safety_settings() -> Value {
|
||||
])
|
||||
}
|
||||
|
||||
fn build_generation_config(
|
||||
mode: &str,
|
||||
aspect_ratio: Option<&str>,
|
||||
image_size: &str,
|
||||
) -> Value {
|
||||
fn build_generation_config(mode: &str) -> Value {
|
||||
let image_config = match mode {
|
||||
"avatar" => json!({ "aspectRatio": "1:1", "imageSize": image_size }),
|
||||
"art" => {
|
||||
let ratio = aspect_ratio.unwrap_or("16:9");
|
||||
json!({ "aspectRatio": ratio, "imageSize": image_size })
|
||||
}
|
||||
"avatar" => json!({ "aspectRatio": "1:1", "imageSize": "4K" }),
|
||||
"art" => json!({ "aspectRatio": "16:9", "imageSize": "4K" }),
|
||||
// replace mode: omit aspectRatio so the model infers it from the source image
|
||||
_ => json!({ "imageSize": image_size }),
|
||||
_ => json!({ "imageSize": "4K" }),
|
||||
};
|
||||
json!({
|
||||
"imageConfig": image_config,
|
||||
@@ -90,56 +83,37 @@ fn build_user_gemini_parts(
|
||||
user_image_base64: &Option<String>,
|
||||
user_image_mime: &Option<String>,
|
||||
) -> Vec<Value> {
|
||||
if let Some(image_data) = user_image_base64.as_deref() {
|
||||
if mode == "replace" && user_image_base64.is_some() {
|
||||
let mime = user_image_mime.as_deref().unwrap_or("image/png");
|
||||
let data = user_image_base64.as_deref().unwrap_or("");
|
||||
let base_text = user_text.as_deref().unwrap_or("");
|
||||
let final_text = if mode == "replace" {
|
||||
if base_text.is_empty() {
|
||||
REPLACE_MODE_APPEND.to_string()
|
||||
} else {
|
||||
format!("{}\n{}", base_text, REPLACE_MODE_APPEND)
|
||||
}
|
||||
let final_text = if base_text.is_empty() {
|
||||
REPLACE_MODE_APPEND.to_string()
|
||||
} else {
|
||||
base_text.to_string()
|
||||
format!("{}\n{}", base_text, REPLACE_MODE_APPEND)
|
||||
};
|
||||
|
||||
let mut parts = vec![json!({"inlineData": {"mimeType": mime, "data": image_data}})];
|
||||
if !final_text.is_empty() {
|
||||
parts.push(json!({"text": final_text}));
|
||||
}
|
||||
parts
|
||||
vec![
|
||||
json!({"inlineData": {"mimeType": mime, "data": data}}),
|
||||
json!({"text": final_text}),
|
||||
]
|
||||
} else {
|
||||
// No image: text-only message
|
||||
// Art/avatar mode, or replace mode follow-up correction (text only)
|
||||
let text = user_text.as_deref().unwrap_or("");
|
||||
vec![json!({"text": text})]
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GeminiCallParams {
|
||||
pub mode: String,
|
||||
pub aspect_ratio: Option<String>,
|
||||
pub image_size: String,
|
||||
pub user_text: Option<String>,
|
||||
pub user_image_base64: Option<String>,
|
||||
pub user_image_mime: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn call_gemini(
|
||||
api_key: String,
|
||||
mode: String,
|
||||
history: Vec<ThreadMessage>,
|
||||
params: GeminiCallParams,
|
||||
user_text: Option<String>,
|
||||
user_image_base64: Option<String>,
|
||||
user_image_mime: Option<String>,
|
||||
) -> Result<(Vec<MessagePart>, f64), String> {
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let GeminiCallParams {
|
||||
mode,
|
||||
aspect_ratio,
|
||||
image_size,
|
||||
user_text,
|
||||
user_image_base64,
|
||||
user_image_mime,
|
||||
} = params;
|
||||
|
||||
let is_first_message = history.is_empty();
|
||||
|
||||
let mut contents: Vec<Value> = history
|
||||
@@ -182,11 +156,7 @@ pub async fn call_gemini(
|
||||
|
||||
contents.push(json!({"role": "user", "parts": user_parts}));
|
||||
|
||||
let generation_config = build_generation_config(
|
||||
mode.as_str(),
|
||||
aspect_ratio.as_deref(),
|
||||
image_size.as_str(),
|
||||
);
|
||||
let generation_config = build_generation_config(mode.as_str());
|
||||
let safety_settings = build_safety_settings();
|
||||
|
||||
let request_body = json!({
|
||||
@@ -278,13 +248,8 @@ pub async fn call_gemini(
|
||||
let candidates_tokens = usage["candidatesTokenCount"].as_u64().unwrap_or(0);
|
||||
let image_part_count = result_parts.iter().filter(|p| p.part_type == "image").count() as u64;
|
||||
|
||||
// Image output tokens per image vary by resolution, billed at $120/1M tokens
|
||||
let tokens_per_image: u64 = match image_size.as_str() {
|
||||
"1K" => 500,
|
||||
"2K" => 1_000,
|
||||
_ => 2_000, // 4K default
|
||||
};
|
||||
let image_output_tokens = image_part_count * tokens_per_image;
|
||||
// Image output tokens (4K = 2000 tokens each) billed at $120/1M tokens
|
||||
let image_output_tokens = image_part_count * 2_000_u64;
|
||||
// Remaining candidates tokens are text/thinking, billed at $12/1M tokens
|
||||
let text_output_tokens = candidates_tokens.saturating_sub(image_output_tokens);
|
||||
|
||||
|
||||
+3
-17
@@ -1,7 +1,7 @@
|
||||
mod gemini;
|
||||
mod storage;
|
||||
|
||||
use gemini::{call_gemini, read_reference_image_base64, GeminiCallParams};
|
||||
use gemini::{call_gemini, read_reference_image_base64};
|
||||
use serde::Serialize;
|
||||
use storage::{
|
||||
delete_thread_from_disk, load_config_from_disk, load_threads_from_disk, save_config_to_disk,
|
||||
@@ -46,30 +46,16 @@ async fn save_config(config: Config) -> Result<(), String> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn send_message(
|
||||
api_key: String,
|
||||
mode: String,
|
||||
aspect_ratio: Option<String>,
|
||||
image_size: String,
|
||||
history: Vec<ThreadMessage>,
|
||||
user_text: Option<String>,
|
||||
user_image_base64: Option<String>,
|
||||
user_image_mime: Option<String>,
|
||||
) -> Result<SendMessageResult, String> {
|
||||
let (parts, cost_usd) = call_gemini(
|
||||
api_key,
|
||||
history,
|
||||
GeminiCallParams {
|
||||
mode,
|
||||
aspect_ratio,
|
||||
image_size,
|
||||
user_text,
|
||||
user_image_base64,
|
||||
user_image_mime,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let (parts, cost_usd) =
|
||||
call_gemini(api_key, mode, history, user_text, user_image_base64, user_image_mime).await?;
|
||||
Ok(SendMessageResult { parts, cost_usd })
|
||||
}
|
||||
|
||||
|
||||
@@ -25,19 +25,11 @@ pub struct ThreadMessage {
|
||||
pub cost_usd: Option<f64>,
|
||||
}
|
||||
|
||||
fn default_image_size() -> String {
|
||||
"4K".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Thread {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub mode: String,
|
||||
#[serde(rename = "aspectRatio", skip_serializing_if = "Option::is_none")]
|
||||
pub aspect_ratio: Option<String>,
|
||||
#[serde(rename = "imageSize", default = "default_image_size")]
|
||||
pub image_size: String,
|
||||
pub messages: Vec<ThreadMessage>,
|
||||
#[serde(rename = "createdAt")]
|
||||
pub created_at: i64,
|
||||
|
||||
+2
-16
@@ -16,14 +16,7 @@ import { SettingsModal } from "./components/settingsModal.tsx";
|
||||
import { Sidebar } from "./components/sidebar.tsx";
|
||||
import { ThreadView } from "./components/threadView.tsx";
|
||||
import { WelcomeScreen } from "./components/welcomeScreen.tsx";
|
||||
import type {
|
||||
AspectRatio,
|
||||
Config,
|
||||
ImageSize,
|
||||
Mode,
|
||||
PendingInput,
|
||||
Thread,
|
||||
} from "./types/index.ts";
|
||||
import type { Config, Mode, PendingInput, Thread } from "./types/index.ts";
|
||||
|
||||
const generateThreadName = (mode: Mode, text?: string): string => {
|
||||
if (
|
||||
@@ -127,18 +120,11 @@ const app = (): JSX.Element => {
|
||||
});
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
mode: Mode,
|
||||
aspectRatio: AspectRatio | undefined,
|
||||
imageSize: ImageSize,
|
||||
): void => {
|
||||
(mode: Mode): void => {
|
||||
const now = Date.now();
|
||||
const createdThread: Thread = {
|
||||
/* eslint-disable-next-line stylistic/no-extra-parens -- Required for conditional spread with exactOptionalPropertyTypes */
|
||||
...(aspectRatio !== undefined && { aspectRatio }),
|
||||
createdAt: now,
|
||||
id: generateId(),
|
||||
imageSize: imageSize,
|
||||
messages: [],
|
||||
mode: mode,
|
||||
name: `New ${mode} thread`,
|
||||
|
||||
@@ -19,12 +19,7 @@ import {
|
||||
type JSX,
|
||||
type KeyboardEvent,
|
||||
} from "react";
|
||||
import type {
|
||||
AspectRatio,
|
||||
ImageSize,
|
||||
Mode,
|
||||
PendingInput,
|
||||
} from "../types/index.ts";
|
||||
import type { Mode, PendingInput } from "../types/index.ts";
|
||||
|
||||
const dropZoneBaseClass = [
|
||||
"border-2 border-dashed rounded-xl p-8",
|
||||
@@ -118,19 +113,14 @@ const readClipboardImage = async(
|
||||
onFileRead(new File([ blob ], "clipboard.png", { type: imageType }));
|
||||
};
|
||||
|
||||
const modeLabelText = (
|
||||
mode: Mode,
|
||||
aspectRatio: AspectRatio | undefined,
|
||||
imageSize: ImageSize,
|
||||
): string => {
|
||||
const modeLabelText = (mode: Mode): string => {
|
||||
if (mode === "avatar") {
|
||||
return `🟣 Avatar Mode · ${imageSize}`;
|
||||
return "🟣 Avatar Mode (1:1)";
|
||||
}
|
||||
if (mode === "art") {
|
||||
const ratio = aspectRatio ?? "16:9";
|
||||
return `🩷 Art Mode (${ratio}) · ${imageSize}`;
|
||||
return "🩷 Art Mode (16:9)";
|
||||
}
|
||||
return `🔵 Replace Mode · ${imageSize}`;
|
||||
return "🔵 Replace Mode";
|
||||
};
|
||||
|
||||
type OnSendCallback = (
|
||||
@@ -140,9 +130,7 @@ type OnSendCallback = (
|
||||
)=> void;
|
||||
|
||||
interface InputAreaProperties {
|
||||
readonly aspectRatio?: AspectRatio;
|
||||
readonly hasMessages: boolean;
|
||||
readonly imageSize: ImageSize;
|
||||
readonly initialImageBase64?: string;
|
||||
readonly initialImageMime?: string;
|
||||
readonly initialImagePreview?: string;
|
||||
@@ -156,9 +144,7 @@ interface InputAreaProperties {
|
||||
/**
|
||||
* Renders the input area for composing and sending messages.
|
||||
* @param props - The component props.
|
||||
* @param props.aspectRatio - The thread's aspect ratio setting (Art mode only).
|
||||
* @param props.hasMessages - Whether the thread already has messages (affects replace mode UI).
|
||||
* @param props.imageSize - The thread's resolution setting.
|
||||
* @param props.initialImageBase64 - Initial base64 image data to pre-populate.
|
||||
* @param props.initialImageMime - Initial image MIME type to pre-populate.
|
||||
* @param props.initialImagePreview - Initial image preview URL to pre-populate.
|
||||
@@ -170,9 +156,7 @@ interface InputAreaProperties {
|
||||
* @returns The JSX element.
|
||||
*/
|
||||
const inputArea = ({
|
||||
aspectRatio,
|
||||
hasMessages,
|
||||
imageSize,
|
||||
initialImageBase64,
|
||||
initialImageMime,
|
||||
initialImagePreview,
|
||||
@@ -272,8 +256,7 @@ const inputArea = ({
|
||||
if (isInitialReplace && imageBase64 === undefined) {
|
||||
return;
|
||||
}
|
||||
const hasContent = text.trim().length > 0 || imageBase64 !== undefined;
|
||||
if (!isInitialReplace && !hasContent) {
|
||||
if (!isInitialReplace && text.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -349,14 +332,11 @@ const inputArea = ({
|
||||
: dropZoneInactiveClass,
|
||||
].join(" ");
|
||||
|
||||
const hasNoContent = text.trim().length === 0 && imageBase64 === undefined;
|
||||
const isSendDisabled = isLoading || hasNoContent;
|
||||
|
||||
return (
|
||||
<div className="border-t border-purple-900/30 p-4 bg-[#0f0a1a]">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-xs text-gray-500 uppercase tracking-wider">
|
||||
{modeLabelText(mode, aspectRatio, imageSize)}
|
||||
{modeLabelText(mode)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -417,15 +397,6 @@ const inputArea = ({
|
||||
type="file"
|
||||
/>
|
||||
|
||||
<textarea
|
||||
className={textareaClass}
|
||||
disabled={isLoading}
|
||||
onChange={handleTextChange}
|
||||
placeholder="Add notes to include with the image (optional)..."
|
||||
rows={2}
|
||||
value={text}
|
||||
/>
|
||||
|
||||
<button
|
||||
className={replaceButtonClass}
|
||||
disabled={isLoading || imageBase64 === undefined}
|
||||
@@ -443,40 +414,41 @@ const inputArea = ({
|
||||
</div>
|
||||
|
||||
: <div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-2">
|
||||
{imagePreview === undefined
|
||||
? <button
|
||||
className={pasteButtonClass}
|
||||
onClick={handlePasteButtonClick}
|
||||
type="button"
|
||||
>
|
||||
{mode === "replace"
|
||||
? "📋 Paste replacement image (optional)"
|
||||
: "📋 Paste image (optional)"}
|
||||
</button>
|
||||
|
||||
: <div className="relative inline-block">
|
||||
<img
|
||||
alt="Upload preview"
|
||||
className="max-h-32 rounded-lg border border-purple-700/40"
|
||||
src={imagePreview}
|
||||
/>
|
||||
<button
|
||||
className={clearButtonClass}
|
||||
onClick={clearImage}
|
||||
{mode === "replace"
|
||||
? <div className="flex flex-col gap-2">
|
||||
{imagePreview === undefined
|
||||
? <button
|
||||
className={pasteButtonClass}
|
||||
onClick={handlePasteButtonClick}
|
||||
type="button"
|
||||
>
|
||||
{"×"}
|
||||
{"📋 Paste replacement image (optional)"}
|
||||
</button>
|
||||
</div>}
|
||||
<input
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
ref={fileInputReference}
|
||||
type="file"
|
||||
/>
|
||||
</div>
|
||||
|
||||
: <div className="relative inline-block">
|
||||
<img
|
||||
alt="Upload preview"
|
||||
className="max-h-32 rounded-lg border border-purple-700/40"
|
||||
src={imagePreview}
|
||||
/>
|
||||
<button
|
||||
className={clearButtonClass}
|
||||
onClick={clearImage}
|
||||
type="button"
|
||||
>
|
||||
{"×"}
|
||||
</button>
|
||||
</div>}
|
||||
<input
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
ref={fileInputReference}
|
||||
type="file"
|
||||
/>
|
||||
</div>
|
||||
|
||||
: null}
|
||||
|
||||
<div className="flex gap-3 items-end">
|
||||
<textarea
|
||||
@@ -492,7 +464,7 @@ const inputArea = ({
|
||||
/>
|
||||
<button
|
||||
className={sendButtonClass}
|
||||
disabled={isSendDisabled}
|
||||
disabled={isLoading || text.trim().length === 0}
|
||||
onClick={handleSend}
|
||||
type="button"
|
||||
>
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
/**
|
||||
* @file Modal for selecting a new thread generation mode and options.
|
||||
* @file Modal for selecting a new thread generation mode.
|
||||
* @copyright Naomi Carrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Naomi Carrigan
|
||||
*/
|
||||
/* eslint-disable max-lines-per-function -- Component JSX inherently requires many lines */
|
||||
/* eslint-disable max-lines -- Two-step modal requires many option definitions */
|
||||
import {
|
||||
useCallback,
|
||||
useState,
|
||||
type JSX,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
import type { AspectRatio, ImageSize, Mode } from "../types/index.ts";
|
||||
import { useCallback, type JSX, type MouseEvent } from "react";
|
||||
import type { Mode } from "../types/index.ts";
|
||||
|
||||
interface ModeOption {
|
||||
colour: string;
|
||||
@@ -22,25 +16,14 @@ interface ModeOption {
|
||||
mode: Mode;
|
||||
}
|
||||
|
||||
interface AspectRatioOption {
|
||||
label: string;
|
||||
value: AspectRatio;
|
||||
}
|
||||
|
||||
interface ImageSizeOption {
|
||||
description: string;
|
||||
label: string;
|
||||
value: ImageSize;
|
||||
}
|
||||
|
||||
const avatarDescription = [
|
||||
"Generate a square 1:1 portrait.",
|
||||
"Perfect for profile pictures and avatars.",
|
||||
].join(" ");
|
||||
|
||||
const artDescription = [
|
||||
"Generate landscape or portrait artwork.",
|
||||
"Choose your aspect ratio and resolution.",
|
||||
"Generate wide 16:9 landscape artwork.",
|
||||
"Great for wallpapers and banners.",
|
||||
].join(" ");
|
||||
|
||||
const replaceDescription = [
|
||||
@@ -72,21 +55,6 @@ const modeOptionList: Array<ModeOption> = [
|
||||
},
|
||||
];
|
||||
|
||||
const aspectRatioOptions: Array<AspectRatioOption> = [
|
||||
{ label: "1:1 Square", value: "1:1" },
|
||||
{ label: "4:3 Standard", value: "4:3" },
|
||||
{ label: "3:4 Portrait", value: "3:4" },
|
||||
{ label: "16:9 Widescreen", value: "16:9" },
|
||||
{ label: "9:16 Wallpaper", value: "9:16" },
|
||||
{ label: "21:9 Ultrawide", value: "21:9" },
|
||||
];
|
||||
|
||||
const imageSizeOptions: Array<ImageSizeOption> = [
|
||||
{ description: "Faster, cheaper", label: "1K", value: "1K" },
|
||||
{ description: "Balanced", label: "2K", value: "2K" },
|
||||
{ description: "Best quality", label: "4K", value: "4K" },
|
||||
];
|
||||
|
||||
const colourMap: Record<
|
||||
string,
|
||||
{ badge: string; button: string; hover: string }
|
||||
@@ -114,20 +82,6 @@ const isMode = (value: string): value is Mode => {
|
||||
return validModesSet.has(value);
|
||||
};
|
||||
|
||||
const validAspectRatios = new Set<string>([
|
||||
"1:1", "3:4", "4:3", "9:16", "16:9", "21:9",
|
||||
]);
|
||||
|
||||
const isAspectRatio = (value: string): value is AspectRatio => {
|
||||
return validAspectRatios.has(value);
|
||||
};
|
||||
|
||||
const validImageSizes = new Set<string>([ "1K", "2K", "4K" ]);
|
||||
|
||||
const isImageSize = (value: string): value is ImageSize => {
|
||||
return validImageSizes.has(value);
|
||||
};
|
||||
|
||||
const overlayClass = [
|
||||
"fixed inset-0 bg-black/70 backdrop-blur-sm",
|
||||
"flex items-center justify-center z-50",
|
||||
@@ -139,243 +93,32 @@ const panelClass = [
|
||||
"shadow-2xl shadow-purple-900/30",
|
||||
].join(" ");
|
||||
|
||||
const pillBaseClass = [
|
||||
"px-4 py-2 rounded-xl border text-sm font-medium",
|
||||
"transition-all duration-200 cursor-pointer",
|
||||
].join(" ");
|
||||
|
||||
const pillActiveClass = "border-purple-500 bg-purple-600/30 text-white";
|
||||
|
||||
const pillInactiveClass = [
|
||||
"border-purple-900/40 bg-transparent text-gray-400",
|
||||
"hover:border-purple-500/60 hover:text-gray-200",
|
||||
].join(" ");
|
||||
|
||||
const startButtonClass = [
|
||||
"w-full bg-gradient-to-r from-purple-600 to-pink-600",
|
||||
"hover:from-purple-500 hover:to-pink-500",
|
||||
"text-white font-semibold py-3 rounded-xl",
|
||||
"transition-all duration-200 mt-2",
|
||||
].join(" ");
|
||||
|
||||
const sizeButtonActiveClass = "border-purple-500 bg-purple-600/30 text-white";
|
||||
|
||||
const sizeButtonInactiveClass = [
|
||||
"border-purple-900/40 bg-transparent text-gray-400",
|
||||
"hover:border-purple-500/60 hover:text-gray-200",
|
||||
].join(" ");
|
||||
|
||||
const backButtonClass = [
|
||||
"text-gray-400 hover:text-white",
|
||||
"transition-colors text-xl",
|
||||
].join(" ");
|
||||
|
||||
const sectionLabelClass = [
|
||||
"text-sm text-gray-400",
|
||||
"uppercase tracking-wider mb-3",
|
||||
].join(" ");
|
||||
|
||||
interface NewThreadModalProperties {
|
||||
readonly onClose: ()=> void;
|
||||
readonly onSelect: (
|
||||
mode: Mode,
|
||||
aspectRatio: AspectRatio | undefined,
|
||||
imageSize: ImageSize,
|
||||
)=> void;
|
||||
readonly onSelect: (mode: Mode)=> void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the new thread modal for selecting a generation mode and options.
|
||||
* Renders the new thread modal for selecting a generation mode.
|
||||
* @param props - The component props.
|
||||
* @param props.onClose - Callback to close the modal.
|
||||
* @param props.onSelect - Callback when a mode and options are confirmed.
|
||||
* @param props.onSelect - Callback when a mode is selected.
|
||||
* @returns The JSX element.
|
||||
*/
|
||||
const threadModal = ({
|
||||
onClose,
|
||||
onSelect,
|
||||
}: NewThreadModalProperties): JSX.Element => {
|
||||
const [ step, setStep ] = useState<"mode" | "options">("mode");
|
||||
const [ selectedMode, setSelectedMode ] = useState<Mode | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const [ aspectRatio, setAspectRatio ] = useState<AspectRatio>("16:9");
|
||||
const [ imageSize, setImageSize ] = useState<ImageSize>("4K");
|
||||
|
||||
const handleModeSelect = useCallback(
|
||||
(event: MouseEvent<HTMLButtonElement>): void => {
|
||||
const rawMode = event.currentTarget.dataset.mode;
|
||||
if (rawMode !== undefined && isMode(rawMode)) {
|
||||
setSelectedMode(rawMode);
|
||||
setStep("options");
|
||||
onSelect(rawMode);
|
||||
}
|
||||
},
|
||||
[],
|
||||
[ onSelect ],
|
||||
);
|
||||
|
||||
const handleBack = useCallback((): void => {
|
||||
setStep("mode");
|
||||
}, []);
|
||||
|
||||
const handleStart = useCallback((): void => {
|
||||
if (selectedMode === undefined) {
|
||||
return;
|
||||
}
|
||||
const ratio = selectedMode === "art"
|
||||
? aspectRatio
|
||||
: undefined;
|
||||
onSelect(selectedMode, ratio, imageSize);
|
||||
}, [ selectedMode, aspectRatio, imageSize, onSelect ]);
|
||||
|
||||
const handleAspectRatioSelect = useCallback(
|
||||
(event: MouseEvent<HTMLButtonElement>): void => {
|
||||
const rawRatio = event.currentTarget.dataset.ratio;
|
||||
if (rawRatio !== undefined && isAspectRatio(rawRatio)) {
|
||||
setAspectRatio(rawRatio);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleImageSizeSelect = useCallback(
|
||||
(event: MouseEvent<HTMLButtonElement>): void => {
|
||||
const rawSize = event.currentTarget.dataset.size;
|
||||
if (rawSize !== undefined && isImageSize(rawSize)) {
|
||||
setImageSize(rawSize);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const selectedModeOption = modeOptionList.find((o) => {
|
||||
return o.mode === selectedMode;
|
||||
});
|
||||
const selectedColours = selectedModeOption === undefined
|
||||
? colourMap.purple
|
||||
: colourMap[selectedModeOption.colour];
|
||||
|
||||
if (step === "options" && selectedModeOption !== undefined) {
|
||||
return (
|
||||
<div className={overlayClass}>
|
||||
<div className={panelClass}>
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<button
|
||||
className={backButtonClass}
|
||||
onClick={handleBack}
|
||||
type="button"
|
||||
>
|
||||
{"←"}
|
||||
</button>
|
||||
<h2 className="text-2xl font-bold text-white flex-1">
|
||||
{"Configure Thread"}
|
||||
</h2>
|
||||
<button
|
||||
className="text-gray-400 hover:text-white transition-colors"
|
||||
onClick={onClose}
|
||||
type="button"
|
||||
>
|
||||
{"×"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={[
|
||||
"flex items-center gap-3 mb-6 p-4",
|
||||
"rounded-xl bg-[#241836] border border-purple-900/30",
|
||||
].join(" ")}
|
||||
>
|
||||
<span className="text-3xl">{selectedModeOption.icon}</span>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-white font-semibold">
|
||||
{selectedModeOption.label}
|
||||
</span>
|
||||
<span
|
||||
className={`text-xs px-2 py-0.5 rounded-full ${selectedColours?.badge ?? ""}`}
|
||||
>
|
||||
{selectedModeOption.mode}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-gray-400 text-xs mt-0.5">
|
||||
{selectedModeOption.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedMode === "art"
|
||||
? <div className="mb-6">
|
||||
<p className={sectionLabelClass}>
|
||||
{"Aspect Ratio"}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{aspectRatioOptions.map((option) => {
|
||||
const pillClass = [
|
||||
pillBaseClass,
|
||||
aspectRatio === option.value
|
||||
? pillActiveClass
|
||||
: pillInactiveClass,
|
||||
].join(" ");
|
||||
return (
|
||||
<button
|
||||
className={pillClass}
|
||||
data-ratio={option.value}
|
||||
key={option.value}
|
||||
onClick={handleAspectRatioSelect}
|
||||
type="button"
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
: null}
|
||||
|
||||
<div className="mb-6">
|
||||
<p className={sectionLabelClass}>
|
||||
{"Resolution"}
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
{imageSizeOptions.map((option) => {
|
||||
const sizeClass = [
|
||||
"flex-1 flex flex-col items-center py-3 px-2",
|
||||
"rounded-xl border text-sm font-medium",
|
||||
"transition-all duration-200 cursor-pointer",
|
||||
imageSize === option.value
|
||||
? sizeButtonActiveClass
|
||||
: sizeButtonInactiveClass,
|
||||
].join(" ");
|
||||
return (
|
||||
<button
|
||||
className={sizeClass}
|
||||
data-size={option.value}
|
||||
key={option.value}
|
||||
onClick={handleImageSizeSelect}
|
||||
type="button"
|
||||
>
|
||||
<span className="text-base font-bold">{option.label}</span>
|
||||
<span className="text-xs mt-0.5 opacity-70">
|
||||
{option.description}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className={startButtonClass}
|
||||
onClick={handleStart}
|
||||
type="button"
|
||||
>
|
||||
{"Start Thread →"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={overlayClass}>
|
||||
<div className={panelClass}>
|
||||
|
||||
@@ -68,19 +68,19 @@ const modeLabel = (mode: Mode): string => {
|
||||
interface BuildUserPartsOptions {
|
||||
readonly imageBase64?: string;
|
||||
readonly imageMime?: string;
|
||||
readonly mode: Mode;
|
||||
readonly text: string;
|
||||
}
|
||||
|
||||
const buildUserParts = ({
|
||||
imageBase64,
|
||||
imageMime,
|
||||
mode,
|
||||
text,
|
||||
}: BuildUserPartsOptions): Array<MessagePart> => {
|
||||
const userParts: Array<MessagePart> = [];
|
||||
|
||||
if (imageBase64 === undefined) {
|
||||
userParts.push({ text: text, type: "text" });
|
||||
} else {
|
||||
if (mode === "replace" && imageBase64 !== undefined) {
|
||||
userParts.push({
|
||||
imageData: imageBase64,
|
||||
mimeType: imageMime ?? "image/png",
|
||||
@@ -89,6 +89,8 @@ const buildUserParts = ({
|
||||
if (text.length > 0) {
|
||||
userParts.push({ text: text, type: "text" });
|
||||
}
|
||||
} else {
|
||||
userParts.push({ text: text, type: "text" });
|
||||
}
|
||||
|
||||
return userParts;
|
||||
@@ -172,18 +174,13 @@ const threadView = ({
|
||||
onLoadingChange(true);
|
||||
onErrorChange(undefined);
|
||||
|
||||
const {
|
||||
aspectRatio,
|
||||
imageSize: rawImageSize,
|
||||
messages,
|
||||
mode,
|
||||
} = thread;
|
||||
const imageSize = rawImageSize ?? "4K";
|
||||
const { messages, mode } = thread;
|
||||
const userParts = buildUserParts({
|
||||
/* eslint-disable-next-line stylistic/no-extra-parens -- Required for conditional spread with exactOptionalPropertyTypes */
|
||||
...(imageBase64 !== undefined && { imageBase64 }),
|
||||
/* eslint-disable-next-line stylistic/no-extra-parens -- Required for conditional spread with exactOptionalPropertyTypes */
|
||||
...(imageMime !== undefined && { imageMime }),
|
||||
mode,
|
||||
text,
|
||||
});
|
||||
|
||||
@@ -220,9 +217,7 @@ const threadView = ({
|
||||
"send_message",
|
||||
{
|
||||
apiKey,
|
||||
aspectRatio,
|
||||
history,
|
||||
imageSize,
|
||||
mode,
|
||||
userImageBase64,
|
||||
userImageMime,
|
||||
@@ -258,13 +253,7 @@ const threadView = ({
|
||||
|
||||
const handleRetry = useCallback(
|
||||
(modelMessageIndex: number): void => {
|
||||
const {
|
||||
aspectRatio,
|
||||
imageSize: rawImageSize,
|
||||
messages,
|
||||
mode,
|
||||
} = thread;
|
||||
const imageSize = rawImageSize ?? "4K";
|
||||
const { messages, mode } = thread;
|
||||
const userMessageIndex = modelMessageIndex - 1;
|
||||
const userMessage = messages[userMessageIndex];
|
||||
|
||||
@@ -311,9 +300,7 @@ const threadView = ({
|
||||
}
|
||||
const response = await invoke<SendResult>("send_message", {
|
||||
apiKey,
|
||||
aspectRatio,
|
||||
history,
|
||||
imageSize,
|
||||
mode,
|
||||
userImageBase64,
|
||||
userImageMime,
|
||||
@@ -366,13 +353,7 @@ const threadView = ({
|
||||
|
||||
const handleEditCommit = useCallback(
|
||||
(messageIndex: number, editedText: string): void => {
|
||||
const {
|
||||
aspectRatio,
|
||||
imageSize: rawImageSize,
|
||||
messages,
|
||||
mode,
|
||||
} = thread;
|
||||
const imageSize = rawImageSize ?? "4K";
|
||||
const { messages, mode } = thread;
|
||||
const originalMessage = messages[messageIndex];
|
||||
if (originalMessage === undefined) {
|
||||
return;
|
||||
@@ -423,9 +404,7 @@ const threadView = ({
|
||||
}
|
||||
const response = await invoke<SendResult>("send_message", {
|
||||
apiKey,
|
||||
aspectRatio,
|
||||
history,
|
||||
imageSize,
|
||||
mode,
|
||||
userImageBase64,
|
||||
userImageMime,
|
||||
@@ -557,11 +536,7 @@ const threadView = ({
|
||||
{...(pendingInput?.text !== undefined && {
|
||||
initialText: pendingInput.text,
|
||||
})}
|
||||
{...(thread.aspectRatio !== undefined && {
|
||||
aspectRatio: thread.aspectRatio,
|
||||
})}
|
||||
hasMessages={thread.messages.length > 0}
|
||||
imageSize={thread.imageSize ?? "4K"}
|
||||
isLoading={isLoading}
|
||||
mode={thread.mode}
|
||||
onInputChange={onPendingInputChange}
|
||||
|
||||
+7
-20
@@ -5,8 +5,6 @@
|
||||
* @author Naomi Carrigan
|
||||
*/
|
||||
|
||||
type AspectRatio = "1:1" | "3:4" | "4:3" | "9:16" | "16:9" | "21:9";
|
||||
type ImageSize = "1K" | "2K" | "4K";
|
||||
type Mode = "avatar" | "art" | "replace";
|
||||
|
||||
interface Config {
|
||||
@@ -35,23 +33,12 @@ interface ThreadMessage {
|
||||
}
|
||||
|
||||
interface Thread {
|
||||
aspectRatio?: AspectRatio;
|
||||
createdAt: number;
|
||||
id: string;
|
||||
imageSize?: ImageSize;
|
||||
messages: Array<ThreadMessage>;
|
||||
mode: Mode;
|
||||
name: string;
|
||||
updatedAt: number;
|
||||
createdAt: number;
|
||||
id: string;
|
||||
messages: Array<ThreadMessage>;
|
||||
mode: Mode;
|
||||
name: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export type {
|
||||
AspectRatio,
|
||||
Config,
|
||||
ImageSize,
|
||||
MessagePart,
|
||||
Mode,
|
||||
PendingInput,
|
||||
Thread,
|
||||
ThreadMessage,
|
||||
};
|
||||
export type { Config, MessagePart, Mode, PendingInput, Thread, ThreadMessage };
|
||||
|
||||
Reference in New Issue
Block a user