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
24 changes: 12 additions & 12 deletions dist/gui-experimental.cjs

Large diffs are not rendered by default.

28 changes: 11 additions & 17 deletions src/command.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import type { Command, Context } from "@opencode/plugin/gui"
import type { Command, Context, SelectOptions } from "@opencode/plugin/gui"
import { wallpaperTitle, type WallpaperChoice } from "./model"

export function wallpaperCommand(
ctx: Pick<Context, "t" | "signal"> & {
dialogs: Pick<Context["dialogs"], "select">
layout: Pick<Context["layout"], "settings">
},
images: () => readonly WallpaperChoice[],
refresh: () => Promise<boolean>,
current: () => string,
select: (choice: string) => void,
open: (options: SelectOptions<string>, choose: (choice: string) => void) => void,
): Command {
return {
id: "choose",
Expand All @@ -21,25 +21,19 @@ export function wallpaperCommand(
if (ctx.signal.aborted) return
await refresh()
if (ctx.signal.aborted) return
const choice = await ctx.dialogs.select<string>({
open({
title: ctx.t("picker.title"),
placeholder: ctx.t("picker.search"),
current: current(),
options: [
...images().map((preset) => ({
title: wallpaperTitle(preset, ctx.t),
value: preset.id,
})),
{ title: ctx.t("picker.off"), value: "off" },
{ title: ctx.t("picker.settings"), value: "settings" },
],
options: images().map((preset) => ({ title: wallpaperTitle(preset, ctx.t), value: preset.id })),
}, (choice) => {
if (ctx.signal.aborted) return
if (choice === "settings") {
ctx.layout.settings("wallpaper")
return
}
select(choice)
})
if (!choice || ctx.signal.aborted) return
if (choice === "settings") {
ctx.layout.settings("wallpaper")
return
}
select(choice)
},
}
}
18 changes: 16 additions & 2 deletions src/gui.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { batch, createEffect, createMemo, createSignal, onCleanup } from "solid-
import { Schema } from "effect"
import { wallpaperCommand } from "./command"
import { Catalog } from "./contract"
import { changeWallpaper, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model"
import { changeWallpaper, setWallpaperEnabled, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model"
import { appearanceKeys, Preferences, initial, slideshowControls, wallpaperFadeDuration } from "./preferences"
import { createWallpaperImage, type WallpaperReader } from "./render"
import { imageError, thumbnailBlob } from "./image"
Expand All @@ -12,6 +12,7 @@ import { createThumbnailCache } from "./thumbnail-cache"
import { alignWallpaperHeaders } from "./backdrop"
import { wallpaperCanvasStyle, wallpaperVariableStyle } from "./style"
import { WallpaperSettings } from "./settings"
import { WallpaperPicker } from "./picker"
import { createWallpaperSlideshow } from "./slideshow"
import { fadeWallpaper, wallpaperTransitionStyle } from "./transition"
import en from "./i18n/en"
Expand Down Expand Up @@ -97,6 +98,10 @@ export default Plugin.define({
slideshow.reset()
settings.update((draft) => { changeWallpaper(draft, choice) })
})
const setEnabled = (enabled: boolean) => batch(() => {
slideshow.reset()
settings.update((draft) => { setWallpaperEnabled(draft, enabled, images()) })
})
const motion = window.matchMedia("(prefers-reduced-motion: reduce)")
const [reducedMotion, setReducedMotion] = createSignal(motion.matches)
const motionChanged = () => setReducedMotion(motion.matches)
Expand Down Expand Up @@ -179,6 +184,7 @@ export default Plugin.define({
images={images}
selected={selected}
select={select}
setEnabled={setEnabled}
thumbnails={thumbnails}
folder={() => catalog?.state()?.folderLabel ?? catalog?.state()?.folder ?? ""}
changeFolder={async (folder, signal) => {
Expand All @@ -204,7 +210,15 @@ export default Plugin.define({
if (!ctx.signal.aborted) report("refresh", ctx.t("folders.title"), [String(error)])
return false
}
}, () => settings.value.enabled ? selected()?.id ?? settings.value.preset : "off", select),
}, () => settings.value.enabled ? selected()?.id ?? settings.value.preset : "off", select,
(options, choose) => {
ctx.dialogs.open((dialog) => <WallpaperPicker
options={options}
enabled={() => settings.value.enabled}
onToggle={setEnabled}
onSelect={(value) => { dialog.close(); choose(value) }}
/>)
}),
)
},
})
1 change: 1 addition & 0 deletions src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export default {
"picker.description": "Choose a background without leaving the conversation.",
"picker.search": "Search wallpapers",
"picker.off": "Wallpaper off",
"picker.on": "Wallpaper on",
"picker.settings": "Wallpaper settings",
"folders.title": "Wallpaper folder",
"folders.description": "PNG, JPEG, WebP and SVG files up to 8 MiB, including subfolders.",
Expand Down
48 changes: 28 additions & 20 deletions src/model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"
import type { Mutable, SelectOptions } from "@opencode/plugin/gui"
import { Schema } from "effect"
import { wallpaperCommand } from "./command"
import { canRemoveWallpaper, changeWallpaper, checkWallpaperDuplicate, removeWallpaper, selectedWallpaper, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model"
import { canRemoveWallpaper, changeWallpaper, checkWallpaperDuplicate, removeWallpaper, selectedWallpaper, setWallpaperEnabled, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model"
import { Preferences, initial } from "./preferences"

const customImage = "data:image/png;base64,aGVsbG8="
Expand Down Expand Up @@ -34,7 +34,7 @@ describe("removing wallpapers", () => {
const images = () => wallpaperCatalog([file], settings)
const world = picker(undefined, { preferences: settings, images })
await world.command.run()
expect(world.requests[0]?.options.map((option) => option.value)).toEqual([file.id, "custom", "off", "settings"])
expect(world.requests[0]?.options.map((option) => option.value)).toEqual([file.id, "custom"])
})

test("removes an unselected uploaded image without changing the active folder wallpaper", async () => {
Expand Down Expand Up @@ -139,17 +139,13 @@ describe("wallpaper slash picker", () => {
const world = picker(undefined)
await world.command.run()
expect(world.requests[0]?.current).toBe("off")
expect(world.requests[0]?.options.map((option) => option.value)).toEqual([
"off",
"settings",
])
expect(world.requests[0]?.options).toEqual([])
expect(world.value).toEqual(world.before)
})

test.each([
["file:example.png", false, "file:example.png", true],
["custom", false, "custom", true],
["off", true, "file:example.png", false],
] as const)("choosing %s preserves the saved image, fit and strength", async (choice, enabled, preset, shown) => {
const world = picker(choice, { preferences: { enabled, preset: "file:example.png", image: customImage }, images: () => wallpaperCatalog([{ id: "file:example.png", title: "example", version: "1" }], { image: customImage }) })
await world.command.run()
Expand Down Expand Up @@ -180,13 +176,12 @@ describe("wallpaper slash picker", () => {
expect(world.value).toEqual({ ...world.before, preset: "file:example.png", enabled: true })
})

test("keeps saved uploads, off and settings accessible when the folder refresh fails", async () => {
const world = picker("off", { preferences: { image: customImage }, refresh: async () => false })
test("keeps saved uploads and settings accessible when the folder refresh fails", async () => {
const world = picker("settings", { preferences: { image: customImage }, refresh: async () => false })
await world.command.run()
expect(world.requests[0]?.options.map((option) => option.value)).toEqual([
"custom", "off", "settings",
])
expect(world.requests[0]?.options.map((option) => option.value)).toEqual(["custom"])
expect(world.value).toEqual({ ...world.before, enabled: false })
expect(world.pages).toEqual(["wallpaper"])
})

test.each(["before refresh", "during refresh", "during dialog"] as const)("cancellation %s prevents selection changes", async (stage) => {
Expand All @@ -209,6 +204,22 @@ describe("wallpaper slash picker", () => {
})
})

test("wallpaper on/off preserves the saved choice, falls back to available images, and stays off with an empty gallery", () => {
const images = [{ id: "file:first.png", title: "first", version: "1" }, { id: "custom", title: "custom", version: "1", image: customImage }]
const settings = { ...initial, enabled: true, preset: "custom", image: customImage, strength: 37, fit: "contain" as const }
const saved = structuredClone(settings)
setWallpaperEnabled(settings, false, images)
expect(settings).toEqual({ ...saved, enabled: false })
setWallpaperEnabled(settings, true, images)
expect(settings).toEqual(saved)
settings.preset = "missing"
setWallpaperEnabled(settings, true, images)
expect(settings.preset).toBe("file:first.png")
setWallpaperEnabled(settings, true, [])
expect(settings.enabled).toBe(false)
expect(settings.preset).toBe("file:first.png")
})

function picker(choice: string | undefined, config: {
preferences?: Partial<typeof initial>
refresh?: () => Promise<boolean>
Expand All @@ -223,15 +234,12 @@ function picker(choice: string | undefined, config: {
const command = wallpaperCommand({
t: (key) => key,
signal: config.signal ?? new AbortController().signal,
dialogs: {
async select<T>(options: SelectOptions<T>) {
requests.push(options)
config.onSelect?.()
return options.options.find((option) => option.value === choice)?.value
},
},
layout: { settings: (page) => { pages.push(page) } },
}, config.images ?? (() => wallpaperCatalog([], value)), config.refresh ?? (async () => true),
() => value.enabled ? value.preset : "off", (selected) => changeWallpaper(value, selected))
() => value.enabled ? value.preset : "off", (selected) => changeWallpaper(value, selected), (options, choose) => {
requests.push(options)
config.onSelect?.()
if (choice && (choice === "off" || choice === "settings" || options.options.some((option) => option.value === choice))) choose(choice)
})
return { command, value, before, requests, pages }
}
4 changes: 4 additions & 0 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ export function changeWallpaper(draft: { enabled: boolean; preset: string }, cho
if (choice !== "off") draft.preset = choice
}

export function setWallpaperEnabled(draft: { enabled: boolean; preset: string }, enabled: boolean, images: readonly WallpaperChoice[]) {
changeWallpaper(draft, enabled ? selectedWallpaper(draft, images)?.id ?? images[0]?.id ?? "off" : "off")
}

export function wallpaperTitle(image: WallpaperChoice, t: (key: string) => string) {
if (canRemoveWallpaper(image)) return image.title || t("image.custom")
return image.title
Expand Down
94 changes: 94 additions & 0 deletions src/picker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { batch, createMemo, createSignal, createUniqueId, For, onMount, Show, type Accessor } from "solid-js"
import { usePlugin, type SelectOptions } from "@opencode/plugin/gui"

export function WallpaperPicker(props: {
options: SelectOptions<string>
enabled: Accessor<boolean>
onToggle: (enabled: boolean) => void
onSelect: (choice: string) => void
}) {
const ctx = usePlugin()
const [query, setQuery] = createSignal("")
const [active, setActive] = createSignal(Math.max(0, props.options.options.findIndex((option) => option.value === props.options.current)))
const id = createUniqueId()
let search!: HTMLInputElement
let list!: HTMLDivElement
const rows = createMemo(() => {
const text = query().trim().toLocaleLowerCase()
if (!text) return props.options.options
return props.options.options.filter((option) => {
let matched = 0
for (const character of option.title.toLocaleLowerCase()) {
if (character === text[matched]) matched++
}
return matched === text.length
})
})
const row = () => document.getElementById(`${id}-${active()}`)
onMount(() => { search.focus(); row()?.scrollIntoView({ block: "nearest" }) })

function navigate(event: KeyboardEvent) {
if (event.isComposing || event.altKey || event.ctrlKey || event.metaKey) return
if (event.key === "Enter" && event.target === search) {
event.preventDefault()
const selected = rows()[active()]
if (selected) props.onSelect(selected.value)
return
}
if (!rows().length || (event.key !== "ArrowDown" && event.key !== "ArrowUp")) return
event.preventDefault()
setActive((index) => (index + (event.key === "ArrowDown" ? 1 : -1) + rows().length) % rows().length)
row()?.scrollIntoView({ block: "nearest" })
if (list.contains(document.activeElement)) row()?.focus()
}

return <ctx.ui.Dialog title={props.options.title} size="large" footer={
<div class="opencode-wallpaper-picker-footer">
<button
type="button"
data-component="button-v2"
data-variant="neutral"
data-size="normal"
aria-label={ctx.t("enabled.title")}
aria-pressed={props.enabled()}
disabled={!props.enabled() && !props.options.options.length}
onClick={() => props.onToggle(!props.enabled())}
>{ctx.t(props.enabled() ? "picker.on" : "picker.off")}</button>
<ctx.ui.Button onClick={() => props.onSelect("settings")}>{ctx.t("picker.settings")}</ctx.ui.Button>
</div>
}>
<div class="opencode-wallpaper-picker" onKeyDown={navigate}>
<input
ref={search}
type="search"
role="combobox"
class="opencode-wallpaper-picker-search"
aria-label={ctx.t("picker.search")}
aria-controls={`${id}-list`}
aria-expanded={true}
aria-autocomplete="list"
aria-activedescendant={rows().length ? `${id}-${active()}` : undefined}
placeholder={props.options.placeholder}
value={query()}
onInput={(event) => {
batch(() => { setQuery(event.currentTarget.value); setActive(0) })
list.scrollTop = 0
}}
/>
<div ref={list} id={`${id}-list`} class="opencode-wallpaper-picker-list" data-scrollable role="listbox" aria-label={props.options.title}>
<For each={rows()}>{(option, index) => <button
id={`${id}-${index()}`}
type="button"
role="option"
class="opencode-wallpaper-picker-choice"
tabIndex={-1}
aria-selected={active() === index()}
onPointerMove={() => setActive(index())}
onFocus={() => setActive(index())}
onClick={() => props.onSelect(option.value)}
><span dir="auto">{option.title}</span></button>}</For>
<Show when={!rows().length}><div role="status" class="opencode-wallpaper-picker-empty">{ctx.t("palette.empty")}</div></Show>
</div>
</div>
</ctx.ui.Dialog>
}
Loading