diff --git a/CHANGELOG.md b/CHANGELOG.md index 940fd62..aa1256f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.3.1 + +- Resume videos and restart HTML wallpapers after focus or visibility interruptions without changing the selected wallpaper. HTML simulation state resets on recovery; sandbox restrictions stay unchanged. +- Fix a catalog refresh-completion race and simplify thumbnail ownership, header alignment, gallery controls and styles. +- Consolidate overlapping tests and verify folder deletion/recreation under Desktop's Node runtime, including direct folders, aliases and atomic replacements. + ## 0.3.0 - Add muted, looping MP4 and WebM wallpapers, animated GIF and APNG uploads, and self-contained HTML wallpapers. diff --git a/README.md b/README.md index aaf6684..0d282b9 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,15 @@ # OpenCode Backdrop -

Use your own wallpapers in OpenCode Desktop. Supports OpenCode 2.2.x from 2.2.6, 2.3.x from 2.3.2, and 2.4.x from 2.4.3 through the GUI plugin API.

-image +

Use your own wallpapers in OpenCode Desktop.

+ +Wallpaper preview + +https://github.com/user-attachments/assets/72617017-5f4d-4153-94dd-635d6eaea54d ## Install ```sh -opencode plugin add 'github:viralcodex/opencode-backdrop#v0.3.0' +opencode plugin add 'github:viralcodex/opencode-backdrop#v0.3.1' ``` This installs the plugin globally. Alternatively, add it to your global `opencode.json` or `opencode.jsonc`, keeping any existing plugins. Do not add it to `cli.json`. @@ -14,39 +17,25 @@ This installs the plugin globally. Alternatively, add it to your global `opencod ```jsonc { "$schema": "https://opencode.ai/config.json", - "plugins": ["github:viralcodex/opencode-backdrop#v0.3.0"], + "plugins": ["github:viralcodex/opencode-backdrop#v0.3.1"], } ``` ## Use +Images and HTML (WebGL self-contained animated wallpapers) must be non-empty and no larger than 8 MiB and videos can be up to 256 MiB. 1. Open **Settings > Wallpapers**. 2. Choose **Change folder** to use a local folder, or **+** to upload an image. 3. Select a wallpaper and adjust tint, brightness and fit. -Wallpaper starts off with an empty gallery. Wallpapers and preferences stay local and are not sent to models. Images and HTML must be non-empty and no larger than 8 MiB; videos can be up to 256 MiB. - -- Folders support PNG, JPEG, WebP, SVG, GIF, APNG, MP4, WebM, and self-contained HTML, including subfolders. Changes appear automatically. -- Uploads support PNG, JPEG, WebP, GIF and APNG. Add video and HTML through the wallpaper folder. -- Videos play muted and loop continuously. MP4 with H.264 is recommended; other codecs depend on Desktop support. Animated images keep their original animation. -- HTML wallpapers run in a sandbox without access to the OpenCode interface or local storage. CSP blocks external scripts, styles, assets, and fetch requests. Embed everything in the HTML and use files from sources you trust. This is not a network firewall; a script can still navigate its own frame to another URL. -- Filter the gallery by **All wallpapers**, **Static**, or **Live**. Live tiles have a small play icon beside their name. Hover or keyboard-focus a live tile to preview it without changing your selected wallpaper. -- Videos and animated images show static thumbnail frames until previewed. For an HTML poster, put `Name.poster.png`, `.jpg`, `.jpeg`, or `.webp` beside `Name.html`. Poster files stay out of the gallery. Without a poster, HTML tiles show a live-wallpaper label until previewed. -- The gallery shows at most two rows, including the **+** tile. Use **Show more** to see all wallpapers, or **Show less** to collapse it. -- More tint improves text contrast. **Fill background** crops the image; **Show whole image** keeps it fully visible. -- Use `/wallpaper` in chat to switch images or turn wallpaper off. Escape cancels the picker. -- Turn **Show wallpaper** off to restore the app's backgrounds without losing your choices. -- Turn **Wallpaper slideshow** on to cycle through all wallpapers in gallery order, regardless of the gallery filter. Choose **None** or **Fade** and set **Display time** in seconds, from 5 to 86400. The default is 60 seconds. Slideshow needs at least two wallpapers. Fades apply between images and respect reduced-motion settings; video and HTML switch instantly. Live playback itself does not pause under reduced motion. - -To remove an upload, hover or focus its tile and click **X**. Remove folder wallpapers by moving or deleting their source files. - -## Koi Pond example - -[Koi Pond](https://github.com/Himanshu-Sangshetti/koipond) is a live WebGL wallpaper, not a video. Download `koipond-linux.tar.gz` from its [wallpaper release](https://github.com/Himanshu-Sangshetti/koipond/releases/tag/wallpaper-v0.2.0), extract `web/index.html`, and save it in your wallpaper folder as `Koi Pond.html`. No installer is needed. Select it in **Settings > Wallpapers**. - -Save the repo's [poster image](https://raw.githubusercontent.com/Himanshu-Sangshetti/koipond/main/.github/assets/hero.webp) beside it as `Koi Pond.poster.webp` to show the pond before hovering. - -Other HTML animations work the same way when bundled into one file. The wallpaper cannot intercept clicks or read the OpenCode interface. HTML fills the panel; the fit setting applies to images and videos. +## Features +1. Use `/wallpaper` in chat to switch images or turn wallpaper off. +2. Folders support PNG, JPEG, WebP, SVG, GIF, APNG, MP4, WebM, and self-contained HTML, including subfolders. +3. Uploads support PNG, JPEG, WebP, GIF and APNG. Add video and HTML through the wallpaper folder. +4. Videos play muted and loop continuously. MP4 with H.264 is recommended; other codecs depend on Desktop support. +5. HTML wallpapers run in a sandbox without access to the OpenCode interface or local storage. (CSP blocks external scripts, styles, assets, and fetch requests. Add only from trusted sources.) +6. Turn **Wallpaper slideshow** on to cycle through all wallpapers in gallery order, regardless of the gallery filter. +7. Choose **Fade** and set **Display time** in seconds, from 5 to 86400. The default is 60 seconds. ## Optional folder configuration @@ -57,7 +46,7 @@ You can set an initial folder with an absolute path instead of choosing one in S "$schema": "https://opencode.ai/config.json", "plugins": [ { - "package": "github:viralcodex/opencode-backdrop#v0.3.0", + "package": "github:viralcodex/opencode-backdrop#v0.3.1", "options": { "folder": "/absolute/path/to/wallpapers" }, }, ], @@ -68,15 +57,9 @@ The folder chosen in Settings takes precedence over this option. ## Development -Use Bun 1.4.4, as pinned in `package.json`, so the generated bundle matches CI. +Use Bun 1.4.4, as pinned in `package.json`. ```sh bun run check bun run test:storage /path/to/opencode ``` - -`check` rebuilds the GUI bundle and runs unit, native Node filesystem-watcher, headless Chrome, and package checks. Set `CHROME_BIN` to a Chrome or Chromium executable if it is installed elsewhere. The PR workflow runs these checks and rejects a stale committed bundle. `test:storage` checks migration against an OpenCode checkout's actual persistence decoder. Pass the checkout path or set `OPENCODE_CHECKOUT`. - -## Release - -See [CHANGELOG.md](CHANGELOG.md) for the 0.3.0 release notes. Before tagging `v0.3.0`, run `bun install --frozen-lockfile --ignore-scripts` and `bun run check`, then commit the rebuilt `dist/gui-experimental.cjs` with the source changes. Run the host-storage check against a supported OpenCode checkout and smoke-test the installed package in Desktop. Keep the local `showcase/` captures and artwork out of this PR. diff --git a/dist/gui-experimental.cjs b/dist/gui-experimental.cjs index c511d1e..6754a4e 100644 --- a/dist/gui-experimental.cjs +++ b/dist/gui-experimental.cjs @@ -1,12 +1,12 @@ -"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("solid-js/web"),Z=require("@opencode/plugin/gui"),u=require("solid-js"),p=require("effect"),he=require("solid-js/store"),Se=require("node:fs"),X=require("node:fs/promises"),U=require("node:path"),Be=require("node:os"),Fe=require("node:crypto"),Ne=require("node:http"),qe=require("node:stream/promises"),te=8*1024*1024,He=256*1024*1024,De=p.Schema.Struct({id:p.Schema.String,title:p.Schema.String,version:p.Schema.String,kind:p.Schema.optional(p.Schema.Literals(["video","html"])),animated:p.Schema.optional(p.Schema.Boolean),poster:p.Schema.optional(p.Schema.Struct({id:p.Schema.String,version:p.Schema.String}))}),ue=p.Schema.Struct({id:p.Schema.String,version:p.Schema.String}),ke=Z.Ipc.define({id:"wallpaper.catalog.v7",state:p.Schema.Struct({folder:p.Schema.String,folderLabel:p.Schema.optional(p.Schema.String),ready:p.Schema.Boolean,images:p.Schema.Array(De),error:p.Schema.String}),methods:{refresh:{output:p.Schema.Boolean},setFolder:{input:p.Schema.NonEmptyString,output:p.Schema.Boolean},read:{input:ue,output:p.Schema.String},source:{input:ue,output:p.Schema.String}}}),Ve=/^[A-Za-z0-9+/]+={0,2}$/,Ge=new Set(["image/png","image/jpeg","image/webp","image/gif","image/apng"]),Ae=p.Schema.String.check(p.Schema.isPattern(/^(?:data:image\/(?:png|jpeg|webp|gif|apng);base64,[A-Za-z0-9+/]+={0,2})?$/),p.Schema.isMaxLength(23+4*Math.ceil(te/3)),p.Schema.makeFilter(e=>{const t=ce(e);return!e||t.length%4===0&&Re(t)<=te}));function Ke(e){if(!Ge.has(e.type))throw new Error("image.typeError");if(e.size===0||e.size>te)throw new Error("image.sizeError")}function Le(e,t){if(t==="image/gif"||t==="image/apng")return!0;if(t==="image/webp")return e.length>20&&new TextDecoder().decode(e.subarray(12,16))==="VP8X"&&!!(e[20]&2);if(t==="image/svg+xml")return/<(?:animate\w*|set)\b|\banimation(?:-[\w-]+)?\s*[:=]/i.test(new TextDecoder().decode(e).replace(//g,""));if(t!=="image/png")return!1;const r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=8;a+12<=e.length;a+=r.getUint32(a)+12){const n=r.getUint32(a+4);if(n===1633899596)return a+16<=e.length&&r.getUint32(a+8)>1;if(n===1229209940)return!1}return!1}function be(e){const t=/^data:(image\/(?:png|jpeg|webp|gif|apng|svg\+xml))(;base64)?,([\s\S]+)$/.exec(e);if(!t)throw new Error("image.decodeError");const[,r,a,n]=t;if(a&&(n.length%4!==0||Re(n)>te||!Ve.test(n)))throw new Error("image.decodeError");if(!a&&r!=="image/svg+xml")throw new Error("image.decodeError");try{const i=new Blob([a?Uint8Array.from(atob(n),l=>l.charCodeAt(0)):decodeURIComponent(n)],{type:r});if(i.size===0||i.size>te)throw new Error("image.decodeError");return i}catch(i){throw new Error("image.decodeError",{cause:i})}}async function we(e,t){t.throwIfAborted();const r=new Image,a=()=>{r.src=""};t.addEventListener("abort",a,{once:!0});try{return r.src=e,await r.decode(),t.throwIfAborted(),r}catch(n){throw t.throwIfAborted(),new Error("image.decodeError",{cause:n})}finally{t.removeEventListener("abort",a)}}async function Je(e,t){t.throwIfAborted();const r=URL.createObjectURL(be(e));try{const a=await we(r,t);return await Me(a,a.naturalWidth,a.naturalHeight,t)}finally{URL.revokeObjectURL(r)}}async function Me(e,t,r,a){a.throwIfAborted();const n=document.createElement("canvas"),i=Math.min(1,320/t,200/r);n.width=Math.max(1,Math.round(t*i)),n.height=Math.max(1,Math.round(r*i));const l=n.getContext("2d");if(!l)throw new Error("image.decodeError");l.drawImage(e,0,0,n.width,n.height);const s=await new Promise((c,g)=>{n.toBlob(h=>h?c(h):g(new Error("image.decodeError")),"image/png")});return a.throwIfAborted(),{blob:s,width:n.width,height:n.height}}async function Xe(e,t){t.throwIfAborted(),Ke(e);const r=URL.createObjectURL(e);try{await we(r,t)}finally{URL.revokeObjectURL(r)}return t.throwIfAborted(),new Promise((a,n)=>{const i=new FileReader,l=()=>i.abort(),s=()=>t.removeEventListener("abort",l);i.onload=()=>{s(),typeof i.result!="string"?n(new Error("image.readError")):a(i.result)},i.onerror=()=>{s(),n(new Error("image.readError"))},i.onabort=()=>{s(),n(t.reason)},t.addEventListener("abort",l,{once:!0});try{i.readAsDataURL(e)}catch(c){s(),n(new Error("image.readError",{cause:c}))}})}function ge(e,t){return e.startsWith("image.")?t(e):`${t("image.readError")} ${e}`}function ce(e){return e.slice(e.indexOf(",")+1)}function Re(e){return e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}const K={tint:{min:0,max:100,initial:80},brightness:{min:25,max:150,initial:100}},Ie=["tint","brightness"],J={min:5,max:86400,duration:60,transition:"fade"},Te=800,Ze=p.Schema.Struct({id:p.Schema.String.check(p.Schema.isPattern(/^(?:custom|upload:.+)$/)),name:p.Schema.String.check(p.Schema.isMinLength(1)),image:Ae.check(p.Schema.isMinLength(1))}),H={enabled:p.Schema.Boolean,preset:p.Schema.String,images:p.Schema.Array(Ze).check(p.Schema.makeFilter(e=>new Set(e.map(t=>t.id)).size===e.length)),tint:p.Schema.Int.check(p.Schema.isBetween({minimum:K.tint.min,maximum:K.tint.max})),brightness:p.Schema.Int.check(p.Schema.isBetween({minimum:K.brightness.min,maximum:K.brightness.max})),fit:p.Schema.Literals(["cover","contain"]),slideshow:p.Schema.Boolean,duration:p.Schema.Int.check(p.Schema.isBetween({minimum:J.min,maximum:J.max})),transition:p.Schema.Literals(["none","fade"])},G=p.Schema.Struct({...H,images:p.Schema.optional(H.images),tint:p.Schema.optional(H.tint),brightness:p.Schema.optional(H.brightness),slideshow:p.Schema.optional(H.slideshow),duration:p.Schema.optional(H.duration),transition:p.Schema.optional(H.transition),image:p.Schema.optional(Ae),imageName:p.Schema.optional(p.Schema.String),strength:p.Schema.optional(p.Schema.Int.check(p.Schema.isBetween({minimum:5,maximum:45}))),hidden:p.Schema.optional(p.Schema.Array(p.Schema.String))}),Qe=G.pipe(p.Schema.decodeTo(p.Schema.Struct(H),{decode:p.SchemaGetter.transform(e=>({enabled:e.enabled,preset:e.preset,fit:e.fit,images:e.image&&!e.images?.some(t=>t.id==="custom")?[{id:"custom",name:e.imageName||"Wallpaper",image:e.image},...e.images??[]]:e.images??[],tint:e.tint??(e.strength===void 0?K.tint.initial:100-e.strength),brightness:e.brightness??K.brightness.initial,slideshow:e.slideshow??!1,duration:e.duration??J.duration,transition:e.transition??J.transition})),encode:p.SchemaGetter.transform(e=>e)})),ee={enabled:!1,preset:"",images:[],tint:K.tint.initial,brightness:K.brightness.initial,fit:"cover",slideshow:!1,duration:J.duration,transition:J.transition};function q(e,t){return p.Schema.withDecodingDefaultType(p.Effect.succeed(t))(e).pipe(p.Schema.catchDecoding(()=>p.Effect.succeed(p.Option.some(t))))}const Ye=p.Schema.Struct({enabled:q(H.enabled,ee.enabled),preset:q(H.preset,ee.preset),fit:q(H.fit,ee.fit),images:q(G.fields.images,void 0),tint:q(G.fields.tint,void 0),brightness:q(G.fields.brightness,void 0),slideshow:q(G.fields.slideshow,void 0),duration:q(G.fields.duration,void 0),transition:q(G.fields.transition,void 0),image:q(G.fields.image,void 0),imageName:q(G.fields.imageName,void 0),strength:q(G.fields.strength,void 0)}).pipe(p.Schema.decodeTo(Qe));function We(e){return{tint:e.tint,brightness:e.brightness}}function oe(e,t){return e?.id===t?.id&&e?.version===t?.version&&e?.image===t?.image&&e?.kind===t?.kind&&e?.animated===t?.animated&&e?.poster?.id===t?.poster?.id&&e?.poster?.version===t?.poster?.version}function Q(e){return!!e.kind||!!e.animated}function et(e,t){return t==="all"?e:e.filter(r=>Q(r)===(t==="live"))}function me(e,t){return t.find(r=>r.id===e.preset)}function ze(e){return e.images}function tt(e=[],t=ee,r=[]){const a=new Map(r.map(n=>[n.id,n]));return[...e,...ze(t).map(n=>{const i=Pe(n.name),l=a.get(n.id);if(l?.image===n.image&&l.title===i)return l;const s=n.image.slice(5,n.image.indexOf(";")),c=Uint8Array.from(atob(ce(n.image).slice(0,87380)),g=>g.charCodeAt(0));return{id:n.id,title:i,version:"custom",image:n.image,...Le(c,s)?{animated:!0}:{}}})]}function ve(e){return e.id==="custom"||e.id.startsWith("upload:")}function rt(e,t,r){if(!ve(t)||(e.images=e.images.filter(n=>n.id!==t.id),e.preset!==t.id))return;const a=r[r.findIndex(n=>n.id===t.id)+1]??r.find(n=>n.id!==t.id);e.preset=a?.id??ee.preset,a||(e.enabled=!1)}function ye(e,t){e.enabled=t!=="off",t!=="off"&&(e.preset=t)}function at(e,t,r){ye(e,t?me(e,r)?.id??r[0]?.id??"off":"off")}function Y(e,t){return ve(e)?e.title||t("image.custom"):e.title}function xe(e,t,r){const a=pe(e.name),n=ce(e.image??"");for(const i of ze(t)){if(i.name&&pe(i.name)===a)throw new Error("image.duplicateName");if(n&&n===ce(i.image))throw new Error("image.duplicateImage")}for(const i of r){const l=nt(i.id);if(l&&pe(l)===a)throw new Error("image.duplicateName")}}function nt(e){if(!e.startsWith("file:"))return"";const t=e.slice(5);return decodeURIComponent(t)}function pe(e){return Pe(e).normalize("NFC").toLowerCase()}function Pe(e){const t=(e.split(/[\\/]/).at(-1)??e).trim();return t.replace(/\.(?:png|jpe?g|webp|svg|gif|apng|mp4|webm|html?)$/i,"")||t}function ot(e,t,r,a,n,i){return{id:"choose",title:e.t("picker.title"),description:e.t("picker.description"),keywords:"wallpaper background image",slash:{name:"wallpaper"},async run(){e.signal.aborted||(await r(),!e.signal.aborted&&i({title:e.t("picker.title"),placeholder:e.t("picker.search"),current:a(),options:t().map(l=>({title:Y(l,e.t),value:l.id}))},l=>{if(!e.signal.aborted){if(l==="settings"){e.layout.settings("wallpaper");return}n(l)}}))}}}function _e(e){return u.createMemo(()=>{const t=e();return t?{...t}:void 0},void 0,{equals:oe})}function it(e,t,r){const[a,n]=u.createSignal(e()),[i,l]=u.createSignal();let s;const c=()=>{clearTimeout(s),s=void 0},g=h=>{c();const A=t()&&!r()?Te:0;u.batch(()=>{l(A?{show:h,duration:A}:void 0),!A&&!h&&n(!1)}),A&&(s=setTimeout(()=>{s=void 0,u.batch(()=>{l(void 0),h||n(!1)})},A))};return u.createEffect(u.on(()=>[e(),r()],([h,A])=>{if(c(),!h)return g(!1);n(!0),A&&l(void 0)})),u.createEffect(u.on(()=>e()&&t(),(h,A)=>{h&&!A&&g(!0)})),u.onCleanup(c),{enabled:a,fade:i}}function lt(e,t,r=()=>0){const[a,n]=he.createStore({url:"",width:0,height:0,loading:!1,error:"",choice:void 0,previous:void 0,transition:0});let i;const l=()=>{clearTimeout(i),i=void 0,a.previous&&URL.revokeObjectURL(a.previous.url),n({previous:void 0,transition:0})};u.onCleanup(()=>{l(),a.url&&URL.revokeObjectURL(a.url)});const s=_e(e);return u.createEffect(u.on(s,c=>{const g=new AbortController;let h="";if(u.onCleanup(()=>{g.abort(),h&&URL.revokeObjectURL(h),h=""}),n({loading:!!c,error:""}),!c){l(),a.url&&URL.revokeObjectURL(a.url),n({url:"",width:0,height:0,choice:void 0});return}if(a.url&&oe(c,a.choice)){n({loading:!1});return}(async()=>{try{const A=c.image??await t(c,g.signal);g.signal.throwIfAborted(),h=URL.createObjectURL(be(A));const b=await we(h,g.signal);g.signal.throwIfAborted(),l();const w=u.untrack(r),k=a.url&&w>0?{url:a.url,width:a.width,height:a.height}:void 0;a.url&&!k&&URL.revokeObjectURL(a.url);const z={url:h,width:b.naturalWidth,height:b.naturalHeight};h="",n({...z,choice:c,previous:k,transition:k?w:0,loading:!1,error:""}),k&&(i=setTimeout(l,w))}catch(A){h&&URL.revokeObjectURL(h),h="",g.signal.aborted||n({loading:!1,error:A instanceof Error?A.message:String(A)})}})()})),a}function st(e,t){const[r,a]=he.createStore({url:"",width:0,height:0,loading:!1,error:""}),n=_e(e);return u.createRenderEffect(()=>{const i=n(),l=new AbortController;let s;if(u.onCleanup(()=>{l.abort(),s?.release()}),a({url:"",width:0,height:0,loading:!!i,error:""}),!!i)try{if(s=t.acquire(i),s.value){a({...s.value,loading:!1});return}s.ready.then(c=>{l.signal.aborted||a({...c,loading:!1})},c=>{l.signal.aborted||a({loading:!1,error:c instanceof Error?c.message:String(c)})})}catch(c){a({loading:!1,error:c instanceof Error?c.message:String(c)})}}),r}function ct(e){const t=new Map;return Object.assign((a,n,i)=>{const l=t.get(a)??new Set,s=new Set(i.filter(Boolean)),c=[...s].filter(g=>!l.has(g));s.size?t.set(a,s):t.delete(a),c.length&&e.show({variant:"error",icon:"outline-photo",title:n,description:c.join(` +"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("solid-js/web"),X=require("@opencode/plugin/gui"),u=require("solid-js"),p=require("effect"),fe=require("solid-js/store"),ye=require("node:fs"),J=require("node:fs/promises"),j=require("node:path"),_e=require("node:os"),je=require("node:crypto"),Oe=require("node:http"),Be=require("node:stream/promises"),ee=8*1024*1024,Fe=256*1024*1024,se=p.Schema.Struct({id:p.Schema.String,version:p.Schema.String}),Ne=p.Schema.Struct({id:p.Schema.String,title:p.Schema.String,version:p.Schema.String,kind:p.Schema.optional(p.Schema.Literals(["video","html"])),animated:p.Schema.optional(p.Schema.Boolean),poster:p.Schema.optional(se)}),Se=X.Ipc.define({id:"wallpaper.catalog.v7",state:p.Schema.Struct({folder:p.Schema.String,folderLabel:p.Schema.optional(p.Schema.String),ready:p.Schema.Boolean,images:p.Schema.Array(Ne),error:p.Schema.String}),methods:{refresh:{output:p.Schema.Boolean},setFolder:{input:p.Schema.NonEmptyString,output:p.Schema.Boolean},read:{input:se,output:p.Schema.String},source:{input:se,output:p.Schema.String}}}),qe=/^[A-Za-z0-9+/]+={0,2}$/,He=new Set(["image/png","image/jpeg","image/webp","image/gif","image/apng"]),Ee=p.Schema.String.check(p.Schema.isPattern(/^(?:data:image\/(?:png|jpeg|webp|gif|apng);base64,[A-Za-z0-9+/]+={0,2})?$/),p.Schema.isMaxLength(23+4*Math.ceil(ee/3)),p.Schema.makeFilter(e=>{const t=ce(e);return!e||t.length%4===0&&Me(t)<=ee}));function Ve(e){if(!He.has(e.type))throw new Error("image.typeError");if(e.size===0||e.size>ee)throw new Error("image.sizeError")}function Ae(e,t){if(t==="image/gif"||t==="image/apng")return!0;if(t==="image/webp")return e.length>20&&new TextDecoder().decode(e.subarray(12,16))==="VP8X"&&!!(e[20]&2);if(t==="image/svg+xml")return/<(?:animate\w*|set)\b|\banimation(?:-[\w-]+)?\s*[:=]/i.test(new TextDecoder().decode(e).replace(//g,""));if(t!=="image/png")return!1;const r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let n=8;n+12<=e.length;n+=r.getUint32(n)+12){const a=r.getUint32(n+4);if(a===1633899596)return n+16<=e.length&&r.getUint32(n+8)>1;if(a===1229209940)return!1}return!1}function he(e){const t=/^data:(image\/(?:png|jpeg|webp|gif|apng|svg\+xml))(;base64)?,([\s\S]+)$/.exec(e);if(!t)throw new Error("image.decodeError");const[,r,n,a]=t;if(n&&(a.length%4!==0||Me(a)>ee||!qe.test(a)))throw new Error("image.decodeError");if(!n&&r!=="image/svg+xml")throw new Error("image.decodeError");try{const i=new Blob([n?Uint8Array.from(atob(a),l=>l.charCodeAt(0)):decodeURIComponent(a)],{type:r});if(i.size===0||i.size>ee)throw new Error("image.decodeError");return i}catch(i){throw new Error("image.decodeError",{cause:i})}}async function we(e,t){t.throwIfAborted();const r=new Image,n=()=>{r.src=""};t.addEventListener("abort",n,{once:!0});try{return r.src=e,await r.decode(),t.throwIfAborted(),r}catch(a){throw t.throwIfAborted(),new Error("image.decodeError",{cause:a})}finally{t.removeEventListener("abort",n)}}async function De(e,t){t.throwIfAborted();const r=URL.createObjectURL(he(e));try{const n=await we(r,t);return await Le(n,n.naturalWidth,n.naturalHeight,t)}finally{URL.revokeObjectURL(r)}}async function Le(e,t,r,n){n.throwIfAborted();const a=Math.min(1,320/t,200/r);t=Math.max(1,Math.round(t*a)),r=Math.max(1,Math.round(r*a));const i=new OffscreenCanvas(t,r),l=i.getContext("2d");if(!l)throw new Error("image.decodeError");l.drawImage(e,0,0,i.width,i.height);const s=await i.convertToBlob({type:"image/png"}).catch(c=>{throw new Error("image.decodeError",{cause:c})});return n.throwIfAborted(),{blob:s,width:t,height:r}}async function Ge(e,t){t.throwIfAborted(),Ve(e);const r=URL.createObjectURL(e);try{await we(r,t)}finally{URL.revokeObjectURL(r)}t.throwIfAborted();const n=new FileReader,a=()=>n.abort();return t.addEventListener("abort",a,{once:!0}),new Promise((i,l)=>{n.onload=()=>{typeof n.result!="string"?l(new Error("image.readError")):i(n.result)},n.onerror=()=>l(new Error("image.readError")),n.onabort=()=>l(t.reason);try{n.readAsDataURL(e)}catch(s){l(new Error("image.readError",{cause:s}))}}).finally(()=>t.removeEventListener("abort",a))}function ue(e,t){return e.startsWith("image.")?t(e):`${t("image.readError")} ${e}`}function ce(e){return e.slice(e.indexOf(",")+1)}function Me(e){return e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}const G={tint:{min:0,max:100,initial:80},brightness:{min:25,max:150,initial:100}},Re=["tint","brightness"],K={min:5,max:86400,duration:60,transition:"fade"},Ie=800,Ke=p.Schema.Struct({id:p.Schema.String.check(p.Schema.isPattern(/^(?:custom|upload:.+)$/)),name:p.Schema.String.check(p.Schema.isMinLength(1)),image:Ee.check(p.Schema.isMinLength(1))}),q={enabled:p.Schema.Boolean,preset:p.Schema.String,images:p.Schema.Array(Ke).check(p.Schema.makeFilter(e=>new Set(e.map(t=>t.id)).size===e.length)),tint:p.Schema.Int.check(p.Schema.isBetween({minimum:G.tint.min,maximum:G.tint.max})),brightness:p.Schema.Int.check(p.Schema.isBetween({minimum:G.brightness.min,maximum:G.brightness.max})),fit:p.Schema.Literals(["cover","contain"]),slideshow:p.Schema.Boolean,duration:p.Schema.Int.check(p.Schema.isBetween({minimum:K.min,maximum:K.max})),transition:p.Schema.Literals(["none","fade"])},D=p.Schema.Struct({...q,images:p.Schema.optional(q.images),tint:p.Schema.optional(q.tint),brightness:p.Schema.optional(q.brightness),slideshow:p.Schema.optional(q.slideshow),duration:p.Schema.optional(q.duration),transition:p.Schema.optional(q.transition),image:p.Schema.optional(Ee),imageName:p.Schema.optional(p.Schema.String),strength:p.Schema.optional(p.Schema.Int.check(p.Schema.isBetween({minimum:5,maximum:45}))),hidden:p.Schema.optional(p.Schema.Array(p.Schema.String))}),Je=D.pipe(p.Schema.decodeTo(p.Schema.Struct(q),{decode:p.SchemaGetter.transform(e=>({enabled:e.enabled,preset:e.preset,fit:e.fit,images:e.image&&!e.images?.some(t=>t.id==="custom")?[{id:"custom",name:e.imageName||"Wallpaper",image:e.image},...e.images??[]]:e.images??[],tint:e.tint??(e.strength===void 0?G.tint.initial:100-e.strength),brightness:e.brightness??G.brightness.initial,slideshow:e.slideshow??!1,duration:e.duration??K.duration,transition:e.transition??K.transition})),encode:p.SchemaGetter.transform(e=>e)})),Y={enabled:!1,preset:"",images:[],tint:G.tint.initial,brightness:G.brightness.initial,fit:"cover",slideshow:!1,duration:K.duration,transition:K.transition};function N(e,t){return p.Schema.withDecodingDefaultType(p.Effect.succeed(t))(e).pipe(p.Schema.catchDecoding(()=>p.Effect.succeed(p.Option.some(t))))}const Xe=p.Schema.Struct({enabled:N(q.enabled,Y.enabled),preset:N(q.preset,Y.preset),fit:N(q.fit,Y.fit),images:N(D.fields.images,void 0),tint:N(D.fields.tint,void 0),brightness:N(D.fields.brightness,void 0),slideshow:N(D.fields.slideshow,void 0),duration:N(D.fields.duration,void 0),transition:N(D.fields.transition,void 0),image:N(D.fields.image,void 0),imageName:N(D.fields.imageName,void 0),strength:N(D.fields.strength,void 0)}).pipe(p.Schema.decodeTo(Je));function ne(e,t){return e?.id===t?.id&&e?.version===t?.version&&e?.image===t?.image&&e?.kind===t?.kind&&e?.animated===t?.animated&&e?.poster?.id===t?.poster?.id&&e?.poster?.version===t?.poster?.version}function Z(e){return!!e.kind||!!e.animated}function Ze(e,t){return t==="all"?e:e.filter(r=>Z(r)===(t==="live"))}function ge(e,t){return t.find(r=>r.id===e.preset)}function Qe(e=[],t=Y,r=[]){const n=new Map(r.map(a=>[a.id,a]));return[...e,...t.images.map(a=>{const i=Te(a.name),l=n.get(a.id);if(l?.image===a.image&&l.title===i)return l;const s=a.image.slice(5,a.image.indexOf(";")),c=Uint8Array.from(atob(ce(a.image).slice(0,87380)),g=>g.charCodeAt(0));return{id:a.id,title:i,version:"custom",image:a.image,...Ae(c,s)?{animated:!0}:{}}})]}function be(e){return e.id==="custom"||e.id.startsWith("upload:")}function Ye(e,t,r){if(!be(t)||(e.images=e.images.filter(a=>a.id!==t.id),e.preset!==t.id))return;const n=r[r.findIndex(a=>a.id===t.id)+1]??r.find(a=>a.id!==t.id);e.preset=n?.id??Y.preset,n||(e.enabled=!1)}function ve(e,t){e.enabled=t!=="off",t!=="off"&&(e.preset=t)}function et(e,t,r){ve(e,t?ge(e,r)?.id??r[0]?.id??"off":"off")}function Q(e,t){return be(e)?e.title||t("image.custom"):e.title}function ke(e,t,r){const n=pe(e.name),a=ce(e.image??"");for(const i of t.images){if(i.name&&pe(i.name)===n)throw new Error("image.duplicateName");if(a&&a===ce(i.image))throw new Error("image.duplicateImage")}for(const i of r){const l=tt(i.id);if(l&&pe(l)===n)throw new Error("image.duplicateName")}}function tt(e){return e.startsWith("file:")?decodeURIComponent(e.slice(5)):""}function pe(e){return Te(e).normalize("NFC").toLowerCase()}function Te(e){const t=(e.split(/[\\/]/).at(-1)??e).trim();return t.replace(/\.(?:png|jpe?g|webp|svg|gif|apng|mp4|webm|html?)$/i,"")||t}function rt(e,t,r,n,a,i){return{id:"choose",title:e.t("picker.title"),description:e.t("picker.description"),keywords:"wallpaper background image",slash:{name:"wallpaper"},async run(){e.signal.aborted||(await r(),!e.signal.aborted&&i({title:e.t("picker.title"),placeholder:e.t("picker.search"),current:n(),options:t().map(l=>({title:Q(l,e.t),value:l.id}))},l=>{if(!e.signal.aborted){if(l==="settings"){e.layout.settings("wallpaper");return}a(l)}}))}}}function We(e){return u.createMemo(()=>{const t=e();return t?{...t}:void 0},void 0,{equals:ne})}function at(e,t,r){const[n,a]=u.createSignal(e()),[i,l]=u.createSignal();let s;const c=()=>{clearTimeout(s),s=void 0},g=b=>{c();const A=t()&&!r()?Ie:0;u.batch(()=>{l(A?{show:b,duration:A}:void 0),!A&&!b&&a(!1)}),A&&(s=setTimeout(()=>{s=void 0,u.batch(()=>{l(void 0),b||a(!1)})},A))};return u.createEffect(u.on(()=>[e(),r()],([b,A])=>{if(c(),!b)return g(!1);a(!0),A&&l(void 0)})),u.createEffect(u.on(()=>e()&&t(),(b,A)=>{b&&!A&&g(!0)})),u.onCleanup(c),{enabled:n,fade:i}}function nt(e,t,r=()=>0){const[n,a]=fe.createStore({url:"",width:0,height:0,loading:!1,error:"",choice:void 0,previous:void 0,transition:0});let i;const l=()=>{clearTimeout(i),i=void 0,n.previous&&URL.revokeObjectURL(n.previous.url),a({previous:void 0,transition:0})};u.onCleanup(()=>{l(),n.url&&URL.revokeObjectURL(n.url)});const s=We(e);return u.createEffect(u.on(s,c=>{const g=new AbortController;let b="";if(u.onCleanup(()=>{g.abort(),b&&URL.revokeObjectURL(b),b=""}),a({loading:!!c,error:""}),!c){l(),n.url&&URL.revokeObjectURL(n.url),a({url:"",width:0,height:0,choice:void 0});return}if(n.url&&ne(c,n.choice)){a({loading:!1});return}(async()=>{try{const A=c.image??await t(c,g.signal);g.signal.throwIfAborted(),b=URL.createObjectURL(he(A));const m=await we(b,g.signal);g.signal.throwIfAborted(),l();const w=u.untrack(r),k=n.url&&w>0?{url:n.url,width:n.width,height:n.height}:void 0;n.url&&!k&&URL.revokeObjectURL(n.url);const C={url:b,width:m.naturalWidth,height:m.naturalHeight};b="",a({...C,choice:c,previous:k,transition:k?w:0,loading:!1,error:""}),k&&(i=setTimeout(l,w))}catch(A){b&&URL.revokeObjectURL(b),b="",g.signal.aborted||a({loading:!1,error:A instanceof Error?A.message:String(A)})}})()})),n}function ot(e,t){const[r,n]=fe.createStore({url:"",width:0,height:0,loading:!1,error:""}),a=We(e);return u.createRenderEffect(()=>{const i=a();let l=!0,s;if(u.onCleanup(()=>{l=!1,s?.release()}),n({url:"",width:0,height:0,loading:!!i,error:""}),!i)return;const c=g=>{l&&n({loading:!1,error:g instanceof Error?g.message:String(g)})};try{if(s=t.acquire(i),s.value){n({...s.value,loading:!1});return}s.ready.then(g=>{l&&n({...g,loading:!1})},c)}catch(g){c(g)}}),r}function it(e){const t=new Map;return Object.assign((n,a,i)=>{const l=t.get(n)??new Set,s=new Set(i.filter(Boolean)),c=[...s].filter(g=>!l.has(g));s.size?t.set(n,s):t.delete(n),c.length&&e.show({variant:"error",icon:"outline-photo",title:a,description:c.join(` -`)})},{retain(a){const n=new Set(a);for(const i of t.keys())n.has(i)||t.delete(i)}})}function dt(e,{maxEntries:t=48,maxBytes:r=8*1024*1024,concurrency:a=2,signal:n}={}){const i=new Map,l=new Set,s=new Map,c=p.Semaphore.makeUnsafe(a);let g=0,h=!1;function A(d){const m=s.get(d);m!==void 0&&(s.delete(d),g-=m)}function b(d){A(d),d.value&&URL.revokeObjectURL(d.value.url),d.value=void 0,l.delete(d)}function w(d){d.retired||(A(d),i.get(d.choice.id)===d&&i.delete(d.choice.id),d.retired=!0,d.controller.abort(),d.reject(d.controller.signal.reason),d.users?l.add(d):b(d))}function k(d){if(!(d.users||d.retired))for(A(d),s.set(d,d.bytes),g+=d.bytes;s.size>t||g>r;){const m=s.keys().next().value;if(!m)break;w(m)}}function z(d){p.Effect.runPromise(c.withPermit(p.Effect.tryPromise({try:m=>e(d.choice,m),catch:m=>m})),{signal:d.controller.signal}).then(m=>{d.controller.signal.throwIfAborted(),d.value={url:URL.createObjectURL(m.blob),width:m.width,height:m.height},d.bytes=m.blob.size,d.resolve(d.value),k(d)}).catch(m=>{d.reject(m),w(d)})}function I(d){if(h)throw new DOMException("Thumbnail cache is disposed.","AbortError");let m=i.get(d.id);if(m&&!oe(m.choice,d)&&(w(m),m=void 0),!m){const{promise:T,resolve:f,reject:$}=Promise.withResolvers();m={choice:{...d},controller:new AbortController,ready:T,resolve:f,reject:$,users:0,bytes:0,retired:!1},z(m)}const E=m;A(E),E.users++,i.set(d.id,E);let C=!1;return{value:E.value,ready:E.ready,release(){C||(C=!0,E.users--,E.retired&&!E.users?b(E):k(E))}}}function y(){if(!h){h=!0,n?.removeEventListener("abort",y);for(const d of new Set([...i.values(),...l]))w(d),b(d);i.clear(),l.clear(),s.clear(),g=0}}return n?.addEventListener("abort",y,{once:!0}),n?.aborted&&y(),{acquire:I,peek(d){const m=i.get(d.id);return m&&oe(m.choice,d)?m.value:void 0},retain(d){const m=new Map(d.map(E=>[E.id,E]));for(const E of i.values())oe(E.choice,m.get(E.choice.id))||w(E)},dispose:y}}function pt(e,t){const r=document.createElement("style"),a=document.createElement("style"),n=document.createElement("style");return r.dataset.wallpaperStyle="settings",a.dataset.wallpaperStyle="canvas",n.dataset.wallpaperStyle="image",r.textContent=e,a.textContent=t,a.disabled=!0,document.head.append(r,a,n),{update(i){n.textContent=i,a.disabled=!i},dispose(){r.remove(),a.remove(),n.remove()}}}const D='[data-slot="home-panel"], [data-slot="session-chat-panel"] > .bg-v2-background-bg-base, [data-component="new-session"]',de=` +`)})},{retain(n){const a=new Set(n);for(const i of t.keys())a.has(i)||t.delete(i)}})}function lt(e,{maxEntries:t=48,maxBytes:r=8*1024*1024,concurrency:n=2,signal:a}={}){const i=new Map,l=new Set,s=new Set,c=p.Semaphore.makeUnsafe(n);let g=0,b=!1;function A(d){s.delete(d)&&(g-=d.bytes)}function m(d){A(d),d.value&&URL.revokeObjectURL(d.value.url),d.value=void 0,l.delete(d)}function w(d){d.controller.signal.aborted||(i.get(d.choice.id)===d&&i.delete(d.choice.id),d.controller.abort(),d.result.reject(d.controller.signal.reason),d.users?l.add(d):m(d))}function k(d){if(!(d.users||d.controller.signal.aborted))for(s.add(d),g+=d.bytes;s.size>t||g>r;){const v=s.keys().next().value;if(!v)break;w(v)}}function C(d){p.Effect.runPromise(c.withPermit(p.Effect.tryPromise({try:v=>e(d.choice,v),catch:v=>v})),{signal:d.controller.signal}).then(v=>{d.controller.signal.throwIfAborted(),d.value={url:URL.createObjectURL(v.blob),width:v.width,height:v.height},A(d),d.bytes=v.blob.size,d.result.resolve(d.value),k(d)}).catch(v=>{d.result.reject(v),w(d)})}function O(d){if(b)throw new DOMException("Thumbnail cache is disposed.","AbortError");let v=i.get(d.id);v&&!ne(v.choice,d)&&(w(v),v=void 0),v||(v={choice:{...d},controller:new AbortController,result:Promise.withResolvers(),users:0,bytes:0},C(v));const y=v;A(y),y.users++,i.set(d.id,y);let I=!1;return{value:y.value,ready:y.result.promise,release(){I||(I=!0,y.users--,y.controller.signal.aborted&&!y.users?m(y):k(y))}}}function f(){if(!b){b=!0,a?.removeEventListener("abort",f);for(const d of[...i.values(),...l])w(d),m(d)}}return a?.addEventListener("abort",f,{once:!0}),a?.aborted&&f(),{acquire:O,peek(d){const v=i.get(d.id);return v&&ne(v.choice,d)?v.value:void 0},retain(d){const v=new Map(d.map(y=>[y.id,y]));for(const y of i.values())ne(y.choice,v.get(y.choice.id))||w(y)},dispose:f}}function st(e,t){const[r,n,a]=["settings","canvas","image"].map(i=>{const l=document.createElement("style");return l.dataset.wallpaperStyle=i,l});return r.textContent=e,n.textContent=t,n.disabled=!0,document.head.append(r,n,a),{update(i){a.textContent=i,n.disabled=!i},dispose(){for(const i of[r,n,a])i.remove()}}}const H='[data-slot="home-panel"], [data-slot="session-chat-panel"] > .bg-v2-background-bg-base, [data-component="new-session"]',de=` [data-slot="home-panel"] .sticky.bg-v2-background-bg-base, [data-slot="session-chat-panel"] [data-session-title] > .bg-v2-background-bg-base, [data-slot="session-chat-panel"] [data-slot="session-location-bar"], [data-slot="session-chat-panel"] [data-component="collapsed-tool-group"] > [data-component="collapsible"] > [data-slot="collapsible-trigger"][aria-expanded="true"], [data-slot="session-chat-panel"] :is([data-component="edit-tool"], [data-component="write-tool"], [data-component="apply-patch-tool"]) > [data-component="collapsible"] > [data-slot="collapsible-trigger"]:is([aria-expanded="true"], [data-locked]) -`;function ut(e){const t=`:is(${e})`;return` +`;function ct(e){const t=`:is(${e})`;return` ${t}::before, ${t}::after { content: ""; @@ -34,15 +34,15 @@ z-index: -99; background: var(--wallpaper-tint, transparent); } - `}const gt=` - :is(${D}) { + `}const dt=` + :is(${H}) { position: relative; isolation: isolate; --wallpaper-secondary: color-mix(in srgb, var(--v2-text-text-base) 88%, var(--v2-background-bg-base)); --wallpaper-text-shadow: 0 1px 2px var(--v2-background-bg-base), 0 0 4px var(--v2-background-bg-base); } - :is(${D}) [data-wallpaper-backed] { + :is(${H}) [data-wallpaper-backed] { isolation: isolate; background: var(--v2-background-bg-base); } @@ -70,7 +70,10 @@ :is([data-slot="home-panel"], [data-component="new-session"]) :is(.text-v2-text-text-muted, .text-v2-text-text-faint), [data-component="new-session"] [data-slot="new-session-location-path"], - [data-slot="session-chat-panel"] [data-slot="session-timeline-scroll"] :is(.text-v2-text-text-muted, .text-v2-text-text-faint, [data-slot="basic-tool-tool-subtitle"]:not(.webfetch-link), [data-slot="basic-tool-tool-arg"], [data-slot="context-tool-group-usage"], [data-slot="context-tool-group-matches"], [data-slot="execute-tool-call-args"], [data-slot="text-part-meta"], [data-component="reasoning-part"] [data-component="markdown"]) { + [data-slot="session-chat-panel"] [data-slot="session-timeline-scroll"] :is(.text-v2-text-text-muted, .text-v2-text-text-faint, [data-slot="basic-tool-tool-subtitle"]:not(.webfetch-link), [data-slot="basic-tool-tool-arg"], [data-slot="context-tool-group-usage"], [data-slot="context-tool-group-matches"], [data-slot="execute-tool-call-args"], [data-slot="text-part-meta"], [data-component="reasoning-part"] [data-component="markdown"]), + :is([data-slot="home-panel"], [data-component="new-session"]) :is(.text-v2-icon-icon-muted, .text-v2-icon-icon-faint), + [data-slot="home-panel"] button.text-v2-text-text-faint > [data-slot="icon-svg"], + [data-slot="home-panel"] [data-component="home-session-search"] input::placeholder { color: var(--wallpaper-secondary); } @@ -80,15 +83,6 @@ text-shadow: var(--wallpaper-text-shadow); } - :is([data-slot="home-panel"], [data-component="new-session"]) :is(.text-v2-icon-icon-muted, .text-v2-icon-icon-faint), - [data-slot="home-panel"] button.text-v2-text-text-faint > [data-slot="icon-svg"] { - color: var(--wallpaper-secondary); - } - - [data-slot="home-panel"] [data-component="home-session-search"] input::placeholder { - color: var(--wallpaper-secondary); - } - [data-slot="home-panel"] button:is(:hover, :focus-visible, [data-selected]) { color: var(--v2-text-text-base); } @@ -115,7 +109,7 @@ [data-component="new-session"] [data-slot="brick-breaker-hud"] :is(.bg-v2-border-border-base, .bg-v2-icon-icon-faint) { background-color: var(--wallpaper-secondary); } -`,mt=gt+ut(`${D}, :is(${D}) [data-wallpaper-backed]`)+` +`,pt=dt+ct(`${H}, :is(${H}) [data-wallpaper-backed]`)+` .opencode-wallpaper-media { position: absolute; inset: 0; @@ -133,10 +127,10 @@ [data-wallpaper-media] :is(${de}) { background: var(--v2-background-bg-base); } -`;function ft(e,t,r=!1){const a=e.enabled&&!!t,{tint:n,brightness:i}=We(e);return{"--wallpaper-image":a&&!r?`url(${JSON.stringify(t)})`:"none","--wallpaper-fit":e.fit,"--wallpaper-tint":a?`color-mix(in srgb, var(--v2-background-bg-base) ${n}%, transparent)`:"transparent","--wallpaper-filter":a?`brightness(${i}%) contrast(85%) saturate(90%)`:"none"}}function ht(e,t,r=!1){if(!e.enabled||!t)return"";const a=Object.entries(ft(e,t,r)).map(([n,i])=>`${n}: ${i};`).join(` - `);return`${D} { - ${a} -}`}function Ue(e,t,r,a){const n=Math[a==="cover"?"max":"min"](e.width/r.width,e.height/r.height),i=r.width*n,l=r.height*n,s=(e.width-i)/2-(t.left-e.left),c=(e.height-l)/2-(t.top-e.top),g=h=>`${Math.round(h*1e3)/1e3}px`;return{"--wallpaper-background-size":`${g(i)} ${g(l)}`,"--wallpaper-background-position":`${g(s)} ${g(c)}`}}function bt(e){if(!(e.image.width>0&&e.image.height>0))return()=>{};const t=new Map,r=new Set;let a=0,n=!1,i=!0,l=[];const s=(b,w)=>{w.attribute===null?b.removeAttribute("data-wallpaper-backed"):b.setAttribute("data-wallpaper-backed",w.attribute);for(const[k,z]of w.properties)z.value?b.style.setProperty(k,z.value,z.priority):b.style.removeProperty(k)},c=()=>{!n&&!a&&(a=requestAnimationFrame(h))},g=new ResizeObserver(c);function h(){if(a=0,n)return;i&&(l=[...document.querySelectorAll(de)],i=!1);const b=new Set,w=new Set,k=new Map,z=[];for(const I of l){const y=I.closest(D);if(!y)continue;const d=I.getBoundingClientRect(),m=k.get(y)??y.getBoundingClientRect();k.set(y,m),!(!d.width||!d.height||!m.width||!m.height)&&(b.add(I),w.add(y),w.add(I),z.push({element:I,geometry:Ue(m,d,e.image,e.fit)}))}for(const[I,y]of t)b.has(I)||(s(I,y),t.delete(I));for(const{element:I,geometry:y}of z){t.has(I)||t.set(I,{attribute:I.getAttribute("data-wallpaper-backed"),properties:new Map(Object.keys(y).map(d=>[d,{value:I.style.getPropertyValue(d),priority:I.style.getPropertyPriority(d)}]))});for(const[d,m]of Object.entries(y))I.style.getPropertyValue(d)!==m&&I.style.setProperty(d,m);I.hasAttribute("data-wallpaper-backed")||I.setAttribute("data-wallpaper-backed","")}for(const I of r)w.has(I)||(g.unobserve(I),r.delete(I));for(const I of w)r.has(I)||(g.observe(I),r.add(I))}const A=new MutationObserver(()=>{i=!0,c()});return A.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["aria-expanded","data-locked","class"]}),document.addEventListener("scroll",c,{capture:!0,passive:!0}),window.addEventListener("resize",c,{passive:!0}),c(),()=>{if(!n){n=!0,cancelAnimationFrame(a),A.disconnect(),g.disconnect(),document.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c);for(const[b,w]of t)s(b,w);t.clear(),r.clear(),l=[]}}}function wt(e,t){const[r,a]=he.createStore({url:"",loading:!1,error:""}),n=u.createMemo(e,void 0,{equals:(i,l)=>i?.id===l?.id&&i?.version===l?.version&&i?.kind===l?.kind});return u.createEffect(u.on(n,i=>{const l=new AbortController;let s;u.onCleanup(()=>{l.abort(),s?.()}),a({url:"",loading:!!i,error:""}),i?.kind&&t(i,l.signal).then(c=>{l.signal.throwIfAborted(),s=vt(c,i.kind,g=>{l.signal.aborted||a({loading:!1,error:g,url:g?"":c})}),a({url:c})}).catch(c=>{l.signal.aborted||a({loading:!1,error:c instanceof Error?c.message:String(c)})})})),r}function vt(e,t,r){const a=je(e,t,r);a.className="opencode-wallpaper-media";let n=0;const i=()=>{n=0;const g=[...document.querySelectorAll(D)].findLast(h=>h.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})&&h.getBoundingClientRect().height>0);a.parentElement!==g&&(a.parentElement?.removeAttribute("data-wallpaper-media"),g?(g.setAttribute("data-wallpaper-media",""),g.append(a),a instanceof HTMLVideoElement&&a.play().catch(()=>{})):(a instanceof HTMLVideoElement&&a.pause(),a.remove()))},l=()=>{n||(n=requestAnimationFrame(i))},s=new MutationObserver(l);s.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","hidden","data-active"]});const c=new ResizeObserver(l);return c.observe(document.body),window.addEventListener("resize",l),i(),()=>{s.disconnect(),c.disconnect(),window.removeEventListener("resize",l),cancelAnimationFrame(n),a.parentElement?.removeAttribute("data-wallpaper-media"),a.remove(),a.removeAttribute("src"),a instanceof HTMLVideoElement&&a.load()}}function je(e,t,r){const a=document.createElement(t==="video"?"video":"iframe");return a.setAttribute("aria-hidden","true"),a.tabIndex=-1,a.inert=!0,a.onerror=()=>r("image.decodeError"),a instanceof HTMLVideoElement?(a.autoplay=!0,a.muted=!0,a.loop=!0,a.playsInline=!0,a.onloadeddata=()=>r("")):(a.setAttribute("sandbox","allow-scripts"),a.referrerPolicy="no-referrer",a.onload=()=>r("")),a.src=e,a}async function yt(e,t){t.throwIfAborted();const r=document.createElement("video");r.muted=!0,r.preload="auto",r.crossOrigin="anonymous";const a=new AbortController,n=AbortSignal.timeout(15e3),i=AbortSignal.any([t,n]);try{return await new Promise((l,s)=>{r.onloadeddata=()=>l(),r.onerror=()=>s(new Error("image.decodeError")),i.addEventListener("abort",()=>s(t.aborted?t.reason:new Error("image.decodeError")),{once:!0,signal:a.signal}),i.throwIfAborted(),r.src=e}),await Me(r,r.videoWidth,r.videoHeight,t)}finally{a.abort(),r.onloadeddata=null,r.onerror=null,r.removeAttribute("src"),r.load()}}function St(e){const[t,r]=u.createSignal();return u.createEffect(u.on(()=>e.choice,a=>{const n=new AbortController;let i,l="";r(void 0),u.onCleanup(()=>{n.abort(),i?.removeAttribute("src"),i instanceof HTMLVideoElement&&i.load(),l&&URL.revokeObjectURL(l)}),Promise.resolve(a.image??e.read(a,n.signal)).then(s=>{n.signal.throwIfAborted();const c=(g="")=>{!g&&i&&(i.style.opacity="1")};a.kind?i=je(s,a.kind,c):(i=new Image,i.alt="",i.onload=()=>c(),l=URL.createObjectURL(be(s)),i.src=l),i.className="opencode-wallpaper-preview-media",i.style.opacity="0",r(i)}).catch(()=>{})})),o.createComponent(u.Show,{get when(){return t()},children:a=>a()})}var kt=o.template(""),$e=o.template(""),xt=o.template("");function $t(e){const[t,r]=u.createSignal(!!e.cache.peek(e.choice));let a;u.onMount(()=>{const i=new IntersectionObserver(l=>{r(l.some(s=>s.isIntersecting))},{rootMargin:"200px"});i.observe(a),u.onCleanup(()=>i.disconnect())});const n=st(()=>t()&&(e.choice.kind!=="html"||e.choice.poster)?e.choice:void 0,e.cache);return(()=>{var i=kt(),l=a;return typeof l=="function"?o.use(l,i):a=i,o.insert(i,o.createComponent(u.Show,{get when(){return n.url},get fallback(){return o.createComponent(u.Show,{get when(){return e.choice.kind==="html"},get fallback(){return o.createComponent(u.Show,{get when(){return n.error},get children(){var s=$e();return o.insert(s,()=>e.t("image.unavailable")),o.effect(c=>{var g=ge(n.error,e.t),h=ge(n.error,e.t);return g!==c.e&&o.setAttribute(s,"title",c.e=g),h!==c.t&&o.setAttribute(s,"aria-label",c.t=h),c},{e:void 0,t:void 0}),s}})},get children(){var s=$e();return o.insert(s,()=>e.t("image.live")),s}})},children:s=>(()=>{var c=xt();return o.effect(()=>o.setAttribute(c,"src",s())),c})()}),null),o.insert(i,o.createComponent(u.Show,{get when(){return o.memo(()=>!!e.preview)()&&e.read},children:s=>o.createComponent(St,{get choice(){return e.choice},get read(){return s()}})}),null),o.effect(()=>o.setAttribute(i,"aria-busy",n.loading)),i})()}var Et=o.template(", + Dialog: props =>
{props.children}{props.footer}
, + SettingsLayout: props => props.children, + SettingsSection: props => props.children, + SettingsRow: props =>
{props.title}{props.description}
{props.children}
, + Switch: props => props.onChange(event.currentTarget.checked)} />, + Select: props => , + }, + dialogs: { open: factory => { + dialogView = mount(() => factory({ close: () => dialogView.dispose() })) + } }, } const rules = () => document.head.querySelector('[data-wallpaper-style="image"]')?.textContent ?? '' + const change = (field, value, condition, stage) => { + update(field, value) + return waitFor(condition, stage) + } try { runWithOwner(scope.owner, () => module.exports.default.setup(ctx)) - await waitForStyles(() => rules().includes('--wallpaper-image: url('), 'initial loading') + await waitFor(() => rules().includes('--wallpaper-image: url('), 'initial loading') assert(reads === 1, 'Built GUI setup must read its selected wallpaper') - assert(getComputedStyle(choice).display === 'block', 'Built GUI setup must attach picker CSS') assert(getComputedStyle(panel, '::before').backgroundImage.startsWith('url("blob:'), 'Built GUI setup must paint its decoded image') + assert(document.head.querySelectorAll('[data-wallpaper-style]').length === 3, 'Styles must attach to document.head') + assert(getComputedStyle(panel, '::before').content === '""', 'Wallpaper canvas rules must be active') const first = rules() - update('preset', 'file:second') - await waitForStyles(() => rules().includes('--wallpaper-image: url(') && rules() !== first, 'image replacement') + await change('preset', 'file:second', () => rules().includes('--wallpaper-image: url(') && rules() !== first, 'image replacement') assert(reads === 2, 'Built GUI setup must read a replacement wallpaper') - update('enabled', false) - await waitForStyles(() => rules() === '', 'disabling') + await change('enabled', false, () => rules() === '', 'disabling') assert(getComputedStyle(panel, '::before').content === 'none', 'Built GUI setup must withdraw the wallpaper when disabled') - update('enabled', true) - await waitForStyles(() => rules().includes('--wallpaper-image: url('), 're-enabling') - update('preset', 'file:video') - await waitFor(() => panel.querySelector('video')?.readyState >= 2, 'video playback') + await change('enabled', true, () => rules().includes('--wallpaper-image: url('), 're-enabling') + await change('preset', 'file:video', () => find('video', panel)?.readyState >= 2, 'video playback') const video = panel.querySelector('video') assert(video.muted && video.loop && video.autoplay && video.playsInline, 'Live videos must be muted, looping, inline and autoplaying') assert(video.inert && video.tabIndex === -1 && video.getAttribute('aria-hidden') === 'true', 'Background media must not receive input or enter the accessibility tree') @@ -179,6 +134,10 @@ async function check() { assert(getComputedStyle(video).zIndex === '-100' && getComputedStyle(panel, '::after').zIndex === '-99', 'Theme tint must stay above live media') assert(rules().includes('--wallpaper-image: none'), 'Video playback must replace the static image layer') await waitFor(() => video.currentTime > 0, 'muted autoplay') + window.dispatchEvent(new FocusEvent('blur')) + video.pause() + window.dispatchEvent(new FocusEvent('focus')) + await waitFor(() => !video.paused, 'video focus recovery') const session = document.createElement('div') session.dataset.component = 'new-session' session.style.cssText = 'width:400px;height:200px' @@ -191,42 +150,183 @@ async function check() { panel.hidden = false await waitFor(() => video.parentElement === panel, 'route restoration') session.remove() - update('preset', 'file:html') - await waitFor(() => isolated.length > 0, 'HTML sandbox execution') + await change('preset', 'file:html', () => isolated.length > 0, 'HTML sandbox execution') const iframe = panel.querySelector('iframe') assert(iframe && iframe.getAttribute('sandbox') === 'allow-scripts', 'HTML wallpapers must allow scripts without same-origin, popups or top navigation') assert(iframe.inert && iframe.tabIndex === -1 && iframe.referrerPolicy === 'no-referrer', 'HTML backgrounds must remain non-interactive and omit referrers') assert(isolated[0].parentBlocked && isolated[0].storageBlocked && isolated[0].fetchBlocked, 'HTML must not read the host, use local storage or fetch external assets') assert(!video.isConnected && !video.hasAttribute('src'), 'Replacing live media must stop and release the previous video') - const previewHost = document.createElement('span') - previewHost.className = 'opencode-wallpaper-thumbnail' - document.body.append(previewHost) + await waitFor(() => frames.length > 0, 'HTML animation') + const srcChanges = new MutationObserver(() => {}) + srcChanges.observe(iframe, { attributes: true, attributeFilter: ['src'] }) + for (const mode of ['focus', 'visibility', 'both']) { + iframe.contentWindow.postMessage('stop-wallpaper', '*') + await waitFor(() => frames.at(-1)?.stopped, 'interrupted HTML animation') + const loads = isolated.length, ticks = frames.length + if (mode !== 'visibility') window.dispatchEvent(new FocusEvent('blur')) + if (mode !== 'focus') { + Object.defineProperty(document, 'hidden', { configurable: true, value: true }) + document.dispatchEvent(new Event('visibilitychange')) + if (mode === 'both') { + srcChanges.takeRecords() + window.dispatchEvent(new FocusEvent('focus')) + assert(!srcChanges.takeRecords().length, 'Hidden HTML must not restart before the app returns') + } + Object.defineProperty(document, 'hidden', { configurable: true, value: false }) + document.dispatchEvent(new Event('visibilitychange')) + delete document.hidden + } else window.dispatchEvent(new FocusEvent('focus')) + await waitFor(() => isolated.length === loads + 1 && frames.length > ticks && !frames.at(-1).stopped, 'HTML interruption recovery') + assert(panel.querySelector('iframe') === iframe && preferences.preset === 'file:html', 'Recovering HTML must keep its frame, sandbox and wallpaper selection') + window.dispatchEvent(new FocusEvent('focus')) + await delay(50) + assert(isolated.length === loads + 1, 'Repeated focus without an interruption must not reload HTML') + } + srcChanges.disconnect() const [previewing, setPreviewing] = createSignal(false) - const disposePreview = render(() => , previewHost) + const previewView = mount(() => , 'opencode-wallpaper-thumbnail') + const previewHost = previewView.host assert(!previewHost.querySelector('iframe'), 'Live previews must not load until hovered or focused') + const previewLoads = isolated.length setPreviewing(true) - await waitFor(() => isolated.length > 1, 'live preview') + await waitFor(() => isolated.length > previewLoads, 'live preview') assert(preferences.preset === 'file:html' && panel.querySelector('iframe') === iframe, 'Previewing must not change the active wallpaper') const preview = previewHost.querySelector('iframe') setPreviewing(false) assert(!preview.isConnected && !preview.hasAttribute('src'), 'Leaving a tile must dispose its live preview') - disposePreview() - previewHost.remove() - update('enabled', false) - await waitFor(() => !panel.querySelector('.opencode-wallpaper-media') && rules() === '', 'live disabling') + previewView.dispose() + await change('enabled', false, () => !find('.opencode-wallpaper-media', panel) && rules() === '', 'live disabling') assert(!iframe.hasAttribute('src') && !panel.hasAttribute('data-wallpaper-media'), 'Turning wallpaper off must release HTML and remove its marker') - update('enabled', true) - await waitFor(() => isolated.length > 2, 'live re-enabling') - update('preset', 'file:first') - await waitForStyles(() => rules().includes('--wallpaper-image: url('), 'live to static switching') + const enabledLoads = isolated.length + await change('enabled', true, () => isolated.length > enabledLoads, 'live re-enabling') + await change('preset', 'file:first', () => rules().includes('--wallpaper-image: url('), 'live to static switching') assert(!panel.querySelector('.opencode-wallpaper-media'), 'Switching to a still image must dispose live playback') + const command = commands.find(command => command.id === 'choose') + assert(command.slash.name === 'wallpaper', 'The wallpaper picker must be available as a slash command') + await command.run() + assert(refreshed === 1, 'Opening the picker must refresh the wallpaper catalog') + const dialog = () => find('[role="dialog"]') + const search = dialog().querySelector('[role="combobox"]') + assert(getComputedStyle(find('.opencode-wallpaper-picker-choice', dialog())).display === 'block', 'Built GUI setup must attach picker CSS') + const active = () => document.getElementById(search.getAttribute('aria-activedescendant')) + assert(document.activeElement === search && active().getAttribute('aria-label') === 'first', 'Picker must focus search and expose the current option') + assert(document.getElementById(search.getAttribute('aria-controls')).getAttribute('role') === 'listbox', 'Picker combobox must control its listbox') + press(search, 'ArrowUp') + assert(active().getAttribute('aria-label') === 'Video', 'Arrow navigation must wrap from first to last') + press(search, 'ArrowDown', { ctrlKey: true }); press(search, 'ArrowDown', { isComposing: true }) + assert(active().getAttribute('aria-label') === 'Video', 'Modified and composing keys must not navigate') + press(search, 'ArrowDown') + assert(active().getAttribute('aria-label') === 'first', 'Arrow navigation must wrap from last to first') + setValue(search, ' PD ', 'input') + assert(active().getAttribute('aria-label') === 'Pond' && active().getAttribute('aria-description') === 'image.live', 'Picker search must match case-insensitive subsequences and label live choices') + setValue(search, 'not present', 'input'); press(search, 'Enter') + assert(dialog().querySelector('[role="status"]') && !search.hasAttribute('aria-activedescendant') && preferences.preset === 'file:first', 'Empty search must announce no results without selecting') + setValue(search, '', 'input') + const last = dialog().querySelector('[role="option"]:last-child') + last.dispatchEvent(new PointerEvent('pointermove', { bubbles: true })) + assert(active() === last, 'Pointer movement must update the active picker option') + last.focus(); press(last, 'ArrowUp') + assert(document.activeElement === active() && active().getAttribute('aria-label') === 'Pond', 'Arrow navigation from the list must move focus with its active option') + search.focus() + setValue(search, 'sec', 'input'); press(search, 'Enter') + assert(!dialog() && preferences.enabled && preferences.preset === 'file:second', 'Enter must select its matching wallpaper and close the picker') + await command.run() + const footer = find('.opencode-wallpaper-picker-footer', dialog()) + const [toggleWallpaper, openSettings] = footer.querySelectorAll('button') + toggleWallpaper.click() + assert(dialog() && !preferences.enabled && preferences.preset === 'file:second', 'Turning wallpaper off must keep the picker open and remember the selection') + toggleWallpaper.click() + assert(preferences.enabled, 'Picker toggle must re-enable wallpaper') + openSettings.click() + assert(!dialog() && openedSettings === 'wallpaper', 'Settings action must close the picker and open wallpaper settings') + settingsView = mount(settingsPage.render) + const settingsHost = settingsView.host + settingsHost.style.width = '320px' + await waitFor(() => find('.opencode-wallpaper-gallery-toggle-button', settingsHost), 'collapsed settings gallery') + const gallery = find('.opencode-wallpaper-gallery', settingsHost) + const toggle = find('.opencode-wallpaper-gallery-toggle-button', settingsHost) + assert(toggle.getAttribute('aria-expanded') === 'false' && toggle.textContent === 'gallery.showMore', 'Gallery toggle must expose its collapsed state') + assert(document.getElementById(toggle.getAttribute('aria-controls')) === gallery, 'Gallery toggle must identify its controlled gallery') + assert(getComputedStyle(toggle.parentElement).display === 'flex', 'Gallery toggle CSS must apply') + assert(gallery.children.length === 2 && find('.opencode-wallpaper-add', gallery), 'Collapsed one-column gallery must show one wallpaper and the add tile') + toggle.click() + assert(toggle.getAttribute('aria-expanded') === 'true' && toggle.textContent === 'gallery.showLess', 'Expanded state and action label must update after clicking') + assert(gallery.children.length === 5, 'Expanded gallery must show all four wallpapers and the add tile') + toggle.click() + assert(gallery.children.length === 2 && toggle.getAttribute('aria-expanded') === 'false' && toggle.textContent === 'gallery.showMore', 'Show less must restore the collapsed gallery and label') + toggle.click() + const control = name => find(':is(input, select)[aria-label="' + name + '.title"]', settingsHost) + const selectedTile = find('[aria-pressed="true"]', settingsHost) + for (const [name, value] of [['tint', 0], ['brightness', 150]]) { + const range = control(name) + const output = find('output', range.parentElement) + setValue(range, value, 'input') + assert(preferences[name] === value && output.textContent === value + '%', 'Native range input must update preferences and its percentage output: ' + name) + update(name, initial[name]) + assert(range.value === String(initial[name]) && output.textContent === initial[name] + '%', 'External preference changes must update range controls: ' + name) + } + assert(!control('duration') && !control('transition'), 'Slideshow options must be hidden while disabled') + const slideshow = control('slideshow') + slideshow.click() + for (const [name, values] of [['fit', ['cover', 'contain']], ['transition', ['none', 'fade']]]) { + const select = control(name) + assert(JSON.stringify([...select.options].map(option => option.value)) === JSON.stringify(values), 'Settings selects must retain their enum choices: ' + name) + setValue(select, values.find(value => value !== select.value)) + assert(preferences[name] === select.value, 'Settings select changes must persist: ' + name) + } + const duration = control('duration') + for (const [value, expected] of [[5, 5], [86400, 86400], [4, 86400], [86401, 86400], [5.5, 86400], ['', 86400]]) { + setValue(duration, value) + assert(preferences.duration === expected && duration.value === String(expected), 'Duration must accept integer limits and restore invalid edits: ' + value) + } + slideshow.click() + assert(!control('duration') && !control('transition'), 'Stopping slideshow must remove its dependent controls') + let pendingReader, aborted = 0 + window.FileReader = class extends Reader { + readAsDataURL() { pendingReader = this } + abort() { aborted++; this.onabort?.(new ProgressEvent('abort')) } + } + const fileInput = settingsHost.querySelector('input[type="file"]') + const files = new DataTransfer() + files.items.add(new File([data], 'new.png', { type: 'image/png' })) + fileInput.files = files.files + fileInput.dispatchEvent(new Event('change', { bubbles: true })) + await waitFor(() => pendingReader, 'pending upload') + assert(fileInput.disabled && settingsHost.querySelector('.opencode-wallpaper-add').getAttribute('aria-busy') === 'true', 'Pending uploads must expose busy and disabled controls') + selectedTile.click() + await Promise.resolve() + assert(aborted === 1 && !fileInput.disabled && preferences.images.length === 0 && preferences.preset === 'file:second', 'Selecting a tile must abort a pending upload without saving it or changing the selection') + await command.run() + const choice = find('.opencode-wallpaper-picker-choice', dialog()) + const row = find('[data-action="wallpaper-preset"]', settingsHost) + const section = find('.opencode-wallpaper-gallery-section', settingsHost) + const caption = find('.opencode-wallpaper-live-icon', gallery).parentElement + selectedTile.focus() + assert(selectedTile.matches(':focus-visible') && getComputedStyle(selectedTile).outlineWidth === '2px' && getComputedStyle(selectedTile).outlineOffset === '2px', 'Focused selected gallery tiles must retain the 2px keyboard outline') + assert(getComputedStyle(caption).display === 'flex', 'Gallery captions must keep live icons beside their titles') + const titleBounds = caption.firstElementChild.getBoundingClientRect() + const iconBounds = find('svg', caption).getBoundingClientRect() + assert(iconBounds.left >= titleBounds.right && iconBounds.top < titleBounds.bottom, 'Live icons must stay on the title row') + assert(getComputedStyle(choice).display === 'block', 'Picker choices must not run together inline') + assert(getComputedStyle(row).flexDirection === 'column', 'Gallery row must stack the heading and controls') + assert(getComputedStyle(section).display === 'grid', 'Gallery section CSS must apply') + assert(section.getBoundingClientRect().width >= row.getBoundingClientRect().width - 1, 'Gallery must use the full settings row width') + scope.dispose() + window.dispatchEvent(new FocusEvent('blur')) + window.dispatchEvent(new FocusEvent('focus')) + await delay(50) + assert(!find('.opencode-wallpaper-media'), 'Built GUI setup must release every media element on cleanup') + assert(document.head.querySelectorAll('[data-wallpaper-style]').length === 0, 'Built GUI setup must remove all owned styles on cleanup') + assert(getComputedStyle(choice).display !== 'block', 'Disposal must restore native picker styling') } finally { + delete document.hidden + window.FileReader = Reader + settingsView?.dispose() + dialogView?.dispose() scope.dispose() window.removeEventListener('message', onMessage) URL.revokeObjectURL(videoURL) } - assert(!document.querySelector('.opencode-wallpaper-media'), 'Built GUI setup must release every media element on cleanup') - assert(document.head.querySelectorAll('[data-wallpaper-style]').length === 0, 'Built GUI setup must remove all owned styles on cleanup') const pending = Promise.withResolvers() const cancelledRead = Promise.withResolvers() let selectMedia, disposeMedia @@ -242,16 +342,16 @@ async function check() { const currentMedia = panel.querySelector('iframe') selectMedia({ id: 'current', title: 'Current', version: '1', kind: 'html', poster: { id: 'poster', version: '2' } }) pending.resolve(videoURL) - await new Promise(resolve => setTimeout(resolve, 50)) + await delay(50) assert(panel.querySelector('iframe') === currentMedia && !panel.querySelector('video'), 'Stale reads and poster changes must not replace current playback') selectMedia({ id: 'cancelled', title: 'Cancelled', version: '1', kind: 'video' }) disposeMedia() cancelledRead.resolve(videoURL) - await new Promise(resolve => setTimeout(resolve, 50)) + await delay(50) assert(!document.querySelector('.opencode-wallpaper-media'), 'Disposing while a read is pending must prevent late media mounts') - report({ pass: true, galleryWidth: section.getBoundingClientRect().width, imageDecoded: image.naturalWidth > 0 }) + report({ pass: true }) } -check().catch(error => report({ pass: false, message: error.message })) +check().catch(error => report({ pass: false, message: [error.stack ?? error.message, error.cause?.stack ?? error.cause?.message].filter(Boolean).join('\\n') })) ` const result = await build({ @@ -271,6 +371,18 @@ const catalog = createCatalog(directory, () => {}) const media = await createWallpaperMediaServer(catalog.openMedia) try { await Bun.write(path.join(directory, "sandbox.html"), ` `) const configured = process.env.CHROME_BIN ?? (process.platform === "darwin" ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" : "chromium") @@ -315,14 +418,13 @@ try { const page = await browser.newPage() await page.goto(pathToFileURL(html).href) await page.waitForFunction(() => document.body.hasAttribute("data-result"), undefined, { timeout: 20000 }) - const encoded = await page.locator("body").getAttribute("data-result") - assert(encoded, "Chrome did not report the stylesheet test result") - const report = JSON.parse(Buffer.from(encoded, "base64").toString()) as { pass: boolean; message?: string } + const report = await page.evaluate(() => JSON.parse(document.body.dataset.result ?? "null")) as { pass: boolean; message?: string } + assert(report, "Chrome did not report the stylesheet test result") assert(report.pass, report.message ?? "Rendered stylesheet check failed") } finally { await browser.close() } - console.log("Browser checks passed: built GUI setup, static/live switching, muted video playback, thumbnails, HTML isolation, previews, route changes, on/off, gallery accessibility, and cleanup.") + console.log("Browser checks passed: built GUI setup, static/live switching, video, thumbnails, HTML isolation, previews, routes, picker, settings focus/ranges/slideshow/upload cancellation, and cleanup.") } finally { media.dispose() catalog.dispose() diff --git a/src/backdrop.test.ts b/src/backdrop.test.ts index 68fc16b..098078a 100644 --- a/src/backdrop.test.ts +++ b/src/backdrop.test.ts @@ -1,25 +1,17 @@ import { expect, test } from "bun:test" import { alignWallpaperHeaders, wallpaperHeaderGeometry } from "./backdrop" -test("aligns header copies to the entire panel without stretching the image", () => { +test.each([ + ["cover", "1200px 600px", "-200px -50px"], + ["contain", "1000px 500px", "-100px 0px"], +] as const)("aligns header copies to the panel's centered %s image", (fit, size, position) => { expect(wallpaperHeaderGeometry( { left: 20, top: 40, width: 1000, height: 600 }, { left: 120, top: 90, width: 744, height: 36 }, - { width: 2000, height: 1000 }, "cover", + { width: 2000, height: 1000 }, fit, )).toEqual({ - "--wallpaper-background-size": "1200px 600px", - "--wallpaper-background-position": "-200px -50px", - }) -}) - -test("uses the same centered letterboxes as the panel in contain mode", () => { - expect(wallpaperHeaderGeometry( - { left: 20, top: 40, width: 1000, height: 600 }, - { left: 120, top: 90, width: 744, height: 36 }, - { width: 2000, height: 1000 }, "contain", - )).toEqual({ - "--wallpaper-background-size": "1000px 500px", - "--wallpaper-background-position": "-100px 0px", + "--wallpaper-background-size": size, + "--wallpaper-background-position": position, }) }) diff --git a/src/backdrop.ts b/src/backdrop.ts index 948ada5..c962ad3 100644 --- a/src/backdrop.ts +++ b/src/backdrop.ts @@ -21,7 +21,7 @@ export function alignWallpaperHeaders(options: { image: { width: number; height: if (!(options.image.width > 0 && options.image.height > 0)) return () => {} type Saved = { attribute: string | null; properties: Map } const saved = new Map() - const observed = new Set() + let observed = new Set() let frame = 0 let disposed = false let discover = true @@ -45,10 +45,9 @@ export function alignWallpaperHeaders(options: { image: { width: number; height: headers = [...document.querySelectorAll(wallpaperHeaders)] discover = false } - const live = new Set() const elements = new Set() const bounds = new Map() - const measurements: { element: HTMLElement; geometry: ReturnType }[] = [] + const measurements = new Map>() // Batch all measurements before writes so scrolling does not force a layout // separately for every expanded tool header. for (const element of headers) { @@ -58,17 +57,16 @@ export function alignWallpaperHeaders(options: { image: { width: number; height: const parent = bounds.get(panel) ?? panel.getBoundingClientRect() bounds.set(panel, parent) if (!header.width || !header.height || !parent.width || !parent.height) continue - live.add(element) elements.add(panel) elements.add(element) - measurements.push({ element, geometry: wallpaperHeaderGeometry(parent, header, options.image, options.fit) }) + measurements.set(element, wallpaperHeaderGeometry(parent, header, options.image, options.fit)) } for (const [element, state] of saved) { - if (live.has(element)) continue + if (measurements.has(element)) continue restore(element, state) saved.delete(element) } - for (const { element, geometry } of measurements) { + for (const [element, geometry] of measurements) { if (!saved.has(element)) { saved.set(element, { attribute: element.getAttribute("data-wallpaper-backed"), @@ -85,13 +83,12 @@ export function alignWallpaperHeaders(options: { image: { width: number; height: for (const element of observed) { if (elements.has(element)) continue resize.unobserve(element) - observed.delete(element) } for (const element of elements) { if (observed.has(element)) continue resize.observe(element) - observed.add(element) } + observed = elements } const mutation = new MutationObserver(() => { discover = true diff --git a/src/catalog.test.ts b/src/catalog.test.ts index c9a0277..8f143e0 100644 --- a/src/catalog.test.ts +++ b/src/catalog.test.ts @@ -1,4 +1,4 @@ -import { afterEach, expect, jest, spyOn, test } from "bun:test" +import { afterEach, expect, spyOn, test } from "bun:test" import * as fs from "node:fs" import * as promises from "node:fs/promises" import { mkdir, mkdtemp, realpath, rm, symlink, truncate } from "node:fs/promises" @@ -15,7 +15,6 @@ const pixel = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQ afterEach(async () => { catalogs.splice(0).forEach((catalog) => catalog.dispose()) - jest.useRealTimers() await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))) }) @@ -24,7 +23,7 @@ test("discovers nested additions without reading or publishing full image conten const folder = path.join(directory, "images") const catalog = tracked(folder) expect(catalog.state().ready).toBe(false) - await catalog.refresh() + expect(await catalog.refresh()).toBe(false) expect(catalog.state().ready).toBe(true) expect(catalog.state().images).toEqual([]) expect(catalog.state().error).toContain("ENOENT") @@ -41,12 +40,14 @@ test("discovers nested additions without reading or publishing full image conten const images = catalog.state().images await catalog.refresh() expect(catalog.state().images).toBe(images) + await Bun.write(path.join(folder, "new.svg"), svg) + await catalog.until(() => catalog.state().images.length === 3) + expect(catalog.state().images.some((image) => image.title === "new")).toBe(true) }) test("loads selected bytes on demand and retains selection through edits, removal and restoration", async () => { - const directory = await fixture() + const directory = await fixture({ "ocean.svg": svg }) const file = path.join(directory, "ocean.svg") - await Bun.write(file, svg) const catalog = tracked(directory) await catalog.refresh() const settings = { ...initial, preset: `file:${encodeURIComponent(file)}` } @@ -68,11 +69,8 @@ test("loads selected bytes on demand and retains selection through edits, remova }) test("keeps the catalog small for an 8 MiB image and excludes empty or oversized files", async () => { - const directory = await fixture() - await Bun.write(path.join(directory, "pixel.png"), pixel) + const directory = await fixture({ "pixel.png": pixel, "empty.svg": "", "large.svg": svg }) await truncate(path.join(directory, "pixel.png"), 8 * 1024 * 1024) - await Bun.write(path.join(directory, "empty.svg"), "") - await Bun.write(path.join(directory, "large.svg"), svg) await truncate(path.join(directory, "large.svg"), 8 * 1024 * 1024 + 1) const catalog = tracked(directory) await catalog.refresh() @@ -86,87 +84,22 @@ test("keeps the catalog small for an 8 MiB image and excludes empty or oversized expect(catalog.state().error).toBe("") }) -test("uses canonical file identities when the selected folder is an alias", async () => { - const directory = await fixture() - const nested = path.join(directory, "nested") - const alias = path.join(directory, "alias") - await mkdir(nested) - await symlink(nested, alias) - await Bun.write(path.join(nested, "wall.svg"), svg) - const catalog = tracked(alias) - await catalog.refresh() - expect(catalog.state().images).toHaveLength(1) - expect(catalog.state().images[0]?.title).toBe("wall") - expect(catalog.state().images[0]?.id).toBe(`file:${encodeURIComponent(path.join(nested, "wall.svg"))}`) -}) - -test("keeps files with the same stem and different extensions distinct", async () => { - const directory = await fixture() - await Bun.write(path.join(directory, "example.svg"), svg) - await Bun.write(path.join(directory, "example.png"), pixel) - const catalog = tracked(directory) - await catalog.refresh() - const images = wallpaperCatalog(catalog.state().images) - expect(images.map((image) => image.id).sort()).toEqual(["png", "svg"].map((extension) => `file:${encodeURIComponent(path.join(directory, `example.${extension}`))}`)) -}) - -test("refreshes from filesystem events without polling or a manual refresh", async () => { - const directory = await fixture() - const updated = Promise.withResolvers() - const catalog = createCatalog(directory, () => { - if (catalog.state().images.length) updated.resolve() - }) - catalogs.push(catalog) - await catalog.refresh() - await Bun.write(path.join(directory, "new.svg"), svg) - await updated.promise - expect(catalog.state().images.map((image) => image.title)).toEqual(["new"]) -}) - -test("watches nested files through a folder alias", async () => { +test("keeps canonical identities and same-stem files distinct while watching nested files through an alias", async () => { const directory = await fixture() const folder = path.join(directory, "images") const alias = path.join(directory, "alias") await mkdir(path.join(folder, "nested"), { recursive: true }) await symlink(folder, alias) - const updated = Promise.withResolvers() - const catalog = createCatalog(alias, () => { - if (catalog.state().images.length) updated.resolve() - }) - catalogs.push(catalog) + await Bun.write(path.join(folder, "example.svg"), svg) + await Bun.write(path.join(folder, "example.png"), pixel) + const catalog = tracked(alias) await catalog.refresh() + const images = wallpaperCatalog(catalog.state().images) + expect(images.map((image) => image.id).sort()).toEqual(["png", "svg"].map((extension) => `file:${encodeURIComponent(path.join(folder, `example.${extension}`))}`)) + expect(images.map((image) => image.title)).toEqual(["example", "example"]) await Bun.write(path.join(folder, "nested", "new.svg"), svg) - await updated.promise - expect(catalog.state().images[0]?.title).toBe(path.join("nested", "new")) -}) - -test("reattaches watching after the folder is deleted and recreated", async () => { - const directory = await fixture() - const folder = path.join(directory, "images") - await mkdir(folder) - let updated = Promise.withResolvers() - const catalog = createCatalog(folder, () => { updated.resolve() }) - catalogs.push(catalog) - await catalog.refresh() - updated = Promise.withResolvers() - await rm(folder, { recursive: true }) - await updated.promise - expect(catalog.state().error).toContain("ENOENT") - updated = Promise.withResolvers() - await mkdir(folder) - await Bun.write(path.join(folder, "restored.svg"), svg) - while (catalog.state().error || !catalog.state().images.length) { - await updated.promise - updated = Promise.withResolvers() - } - expect(catalog.state().error).toBe("") - updated = Promise.withResolvers() - await Bun.write(path.join(folder, "another.svg"), svg) - while (catalog.state().images.length < 2) { - await updated.promise - updated = Promise.withResolvers() - } - expect(catalog.state().images.map((image) => image.title)).toEqual(["another", "restored"]) + await catalog.until(() => catalog.state().images.length === 3) + expect(catalog.state().images.find((image) => image.title === path.join("nested", "new"))?.id).toBe(`file:${encodeURIComponent(path.join(folder, "nested", "new.svg"))}`) }) test("a refresh requested during an active scan includes subsequent filesystem changes", async () => { @@ -178,9 +111,22 @@ test("a refresh requested during an active scan includes subsequent filesystem c expect(catalog.state().images.map((image) => image.title)).toEqual(["new"]) }) +test("a refresh requested as a scan finishes includes subsequent filesystem changes", async () => { + const directory = await fixture({ "first.svg": svg }) + const updated = Promise.withResolvers() + const catalog = tracked(directory, () => { + if (catalog.state().images.length !== 1) return + queueMicrotask(() => queueMicrotask(() => { + fs.writeFileSync(path.join(directory, "second.svg"), svg) + void catalog.refresh().then(updated.resolve, updated.reject) + })) + }) + await Promise.all([catalog.refresh(), updated.promise]) + expect(catalog.state().images.map((image) => image.title)).toEqual(["first", "second"]) +}) + test("reattaches watching when a missing folder reappears between observation and scanning", async () => { - const directory = await fixture() - await Bun.write(path.join(directory, "restored.svg"), svg) + const directory = await fixture({ "restored.svg": svg }) const realpath = spyOn(promises, "realpath").mockRejectedValueOnce( Object.assign(new Error("Folder was missing during observation"), { code: "ENOENT" }), ) @@ -194,31 +140,18 @@ test("reattaches watching when a missing folder reappears between observation an } }) -test("missing folders report failures rather than successful empty scans", async () => { - const directory = await fixture() - const catalog = tracked(path.join(directory, "missing")) - expect(await catalog.refresh()).toBe(false) - expect(catalog.state().ready).toBe(true) - expect(catalog.state().error).toContain("ENOENT") -}) - test("reports watcher errors without an automatic retry and recovers on explicit refresh", async () => { const directory = await fixture() const watch = spyOn(fs, "watch") try { - const updated = Promise.withResolvers() - const catalog = createCatalog(directory, () => { - if (catalog.state().images.length) updated.resolve() - }) - catalogs.push(catalog) + const catalog = tracked(directory) await catalog.refresh() const calls = watch.mock.calls.length const result = watch.mock.results.at(-1) if (!result || result.type !== "return") throw new Error("No filesystem watcher was created") - const closed = Promise.withResolvers() - result.value.once("close", closed.resolve) + const close = spyOn(result.value, "close") result.value.emit("error", new Error("Watcher unavailable")) - await closed.promise + expect(close).toHaveBeenCalled() expect(catalog.state().error).toContain("Watcher unavailable") expect(watch.mock.calls).toHaveLength(calls) expect(await catalog.refresh()).toBe(true) @@ -227,26 +160,20 @@ test("reports watcher errors without an automatic retry and recovers on explicit if (!replacement || replacement.type !== "return") throw new Error("No replacement watcher was created") expect(replacement.value).not.toBe(result.value) await Bun.write(path.join(directory, "new.svg"), svg) - await updated.promise + // Native events are checked elsewhere; isolate error recovery from OS event timing. + replacement.value.emit("change", "rename", "new.svg") + await catalog.until(() => catalog.state().images.length > 0) expect(catalog.state().images[0]?.title).toBe("new") } finally { watch.mockRestore() } }) -test("refuses further scans after disposal", async () => { - const catalog = tracked("/unused-wallpaper-folder") - catalog.dispose() - expect(await catalog.refresh()).toBe(false) -}) - test("reports folder failures without repeatedly publishing an unchanged error", async () => { - const directory = await fixture() + const directory = await fixture({ "file.svg": svg }) const file = path.join(directory, "file.svg") - await Bun.write(file, svg) let updates = 0 - const catalog = createCatalog(file, () => { updates++ }) - catalogs.push(catalog) + const catalog = tracked(file, () => { updates++ }) await catalog.refresh() expect(catalog.state().error).toContain(file) await catalog.refresh() @@ -268,16 +195,15 @@ test("uses one absolute folder, including the first legacy configured path", asy expect(wallpaperFolderLabel("")).toBe("") }) -test("rejects reads after cancellation or disposal", async () => { - const directory = await fixture() - await Bun.write(path.join(directory, "image.svg"), svg) +test("rejects reads after cancellation and refuses reads or scans after disposal", async () => { + const directory = await fixture({ "image.svg": svg }) const catalog = tracked(directory) await catalog.refresh() const image = catalog.state().images[0]! - const cancelled = AbortSignal.abort() - await expect(catalog.read(image, cancelled)).rejects.toThrow() + await expect(catalog.read(image, AbortSignal.abort())).rejects.toThrow() catalog.dispose() await expect(catalog.read(image)).rejects.toThrow() + expect(await catalog.refresh()).toBe(false) }) test("no folder means an empty catalog without watchers or errors", async () => { @@ -292,14 +218,21 @@ test("no folder means an empty catalog without watchers or errors", async () => } }) -function tracked(folder: string) { - const catalog = createCatalog(folder, () => {}) +function tracked(folder: string, changed = () => {}) { + let updated = Promise.withResolvers() + const catalog = createCatalog(folder, () => { changed(); updated.resolve(); updated = Promise.withResolvers() }) catalogs.push(catalog) - return catalog + return { + ...catalog, + async until(predicate: () => boolean) { + while (!predicate()) await updated.promise + }, + } } -async function fixture() { +async function fixture(files: Record = {}) { const directory = await realpath(await mkdtemp(path.join(os.tmpdir(), "opencode-wallpaper-test-"))) directories.push(directory) + await Promise.all(Object.entries(files).map(([name, contents]) => Bun.write(path.join(directory, name), contents))) return directory } diff --git a/src/catalog.ts b/src/catalog.ts index fbd14e8..3f8130d 100644 --- a/src/catalog.ts +++ b/src/catalog.ts @@ -3,7 +3,7 @@ import { open, readdir, realpath, stat } from "node:fs/promises" import path from "node:path" import { homedir } from "node:os" import { Effect, Schema, Semaphore } from "effect" -import { Catalog, ImageRequest, maxImageBytes, maxVideoBytes } from "./contract" +import { Catalog, ImageRequest, maxImageBytes, maxVideoBytes, type Wallpaper } from "./contract" import { animatedImage } from "./image" const formats: Readonly> = { @@ -41,7 +41,7 @@ export function wallpaperFolderLabel(folder: string, home = homedir()) { return relative ? `~${path.sep}${relative}` : "~" } -type Cached = { file: string; image: (typeof Catalog.spec.state.Type.images)[number] } +type Cached = { file: string; image: typeof Wallpaper.Type } export function createCatalog(folder: string, changed: () => void) { const lifetime = new AbortController() @@ -55,11 +55,6 @@ export function createCatalog(folder: string, changed: () => void) { const parents = new Map() let watchError = "" - function invalidate() { - dirty = true - void refresh() - } - async function observe() { if (!folder) return let root: string | undefined @@ -77,28 +72,27 @@ export function createCatalog(folder: string, changed: () => void) { parents.delete(target) } for (const target of targets) { - let parent = path.dirname(target) + let directory = path.dirname(target) while (true) { try { - await stat(parent) + await stat(directory) break } catch (error) { - if (!missing(error) || parent === path.dirname(parent)) throw error - parent = path.dirname(parent) + if (!missing(error) || directory === path.dirname(directory)) throw error + directory = path.dirname(directory) } } if (lifetime.signal.aborted) return const previous = parents.get(target) - if (previous?.directory === parent) continue + if (previous?.directory === directory) continue previous?.watcher.close() - const directory = parent const monitor = watch(directory, { signal: lifetime.signal }, (_event, filename) => { const file = filename === null ? target : path.resolve(directory, filename) const relative = path.relative(file, target) - if (!relative || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))) { + if (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) { watcher?.close() watcher = undefined - invalidate() + void refresh() } }) parents.set(target, { directory, watcher: monitor }) @@ -111,7 +105,7 @@ export function createCatalog(folder: string, changed: () => void) { if (failure) throw failure if (lifetime.signal.aborted) return if (!watcher && root) { - const monitor = watch(root, { recursive: true, signal: lifetime.signal }, invalidate) + const monitor = watch(root, { recursive: true, signal: lifetime.signal }, refresh) watcher = monitor monitor.on("error", (error) => { monitor.close() @@ -135,25 +129,25 @@ export function createCatalog(folder: string, changed: () => void) { dirty = true if (pending) return pending pending = (async () => { - do { - dirty = false - let missingWatch = false - try { await observe() } catch (error) { - missingWatch = missing(error) - watchError = `${folder}: ${String(error)}` - } - await scan(missingWatch) - } while (dirty && !lifetime.signal.aborted) - })().then( - () => !lifetime.signal.aborted && !value.error, - (error) => { + try { + do { + dirty = false + let missingWatch = false + try { await observe() } catch (error) { + missingWatch = missing(error) + watchError = `${folder}: ${String(error)}` + } + await scan(missingWatch) + } while (dirty && !lifetime.signal.aborted) + return !lifetime.signal.aborted && !value.error + } catch (error) { if (!lifetime.signal.aborted) { value = { ...value, ready: true, error: String(error) } changed() } return false - }, - ).finally(() => { pending = undefined }) + } finally { pending = undefined } + })() return pending } @@ -198,8 +192,9 @@ export function createCatalog(folder: string, changed: () => void) { if (lifetime.signal.aborted) return const posters = new Map() for (const entry of next.values()) { - if (!posterFile.test(entry.file)) continue - const stem = entry.file.slice(0, -path.extname(entry.file).length).replace(/\.poster$/i, ".poster") + const match = posterFile.exec(entry.file) + if (!match) continue + const stem = entry.file.slice(0, match.index) const previous = posters.get(stem) if (previous && posterExtensions.indexOf(path.extname(previous.file).toLowerCase()) <= posterExtensions.indexOf(path.extname(entry.file).toLowerCase())) continue posters.set(stem, entry) @@ -207,7 +202,7 @@ export function createCatalog(folder: string, changed: () => void) { for (const entry of next.values()) { if (!entry.image.kind) continue const stem = entry.file.slice(0, -path.extname(entry.file).length) - const poster = posters.get(`${stem}.poster`)?.image + const poster = posters.get(stem)?.image if (entry.image.poster?.id === poster?.id && entry.image.poster?.version === poster?.version) continue entry.image = { ...entry.image, poster: poster ? { id: poster.id, version: poster.version } : undefined } } @@ -269,8 +264,6 @@ export function createCatalog(folder: string, changed: () => void) { }, dispose() { lifetime.abort() - watcher?.close() - for (const monitor of parents.values()) monitor.watcher.close() parents.clear() cache.clear() }, diff --git a/src/contract.ts b/src/contract.ts index 73c50e9..5d48c4c 100644 --- a/src/contract.ts +++ b/src/contract.ts @@ -4,15 +4,15 @@ import { Schema } from "effect" export const maxImageBytes = 8 * 1024 * 1024 export const maxVideoBytes = 256 * 1024 * 1024 +export const ImageRequest = Schema.Struct({ id: Schema.String, version: Schema.String }) + export const Wallpaper = Schema.Struct({ id: Schema.String, title: Schema.String, version: Schema.String, kind: Schema.optional(Schema.Literals(["video", "html"])), animated: Schema.optional(Schema.Boolean), - poster: Schema.optional(Schema.Struct({ id: Schema.String, version: Schema.String })), + poster: Schema.optional(ImageRequest), }) -export const ImageRequest = Schema.Struct({ id: Schema.String, version: Schema.String }) - export const Catalog = Ipc.define({ id: "wallpaper.catalog.v7", state: Schema.Struct({ diff --git a/src/errors.test.ts b/src/errors.test.ts index 1c6fd5c..412bc54 100644 --- a/src/errors.test.ts +++ b/src/errors.test.ts @@ -2,7 +2,7 @@ import { expect, test } from "bun:test" import type { ToastOptions } from "@opencode/plugin/gui" import { createWallpaperErrorReporter } from "./errors" -test("unchanged background errors do not repeat, but recovered errors can notify again", () => { +test("deduplicates errors until recovery, source removal, or an image version change", () => { const shown: ToastOptions[] = [] const report = createWallpaperErrorReporter({ show(options) { shown.push(options); return { dismiss() {} } } }) report("folder", "Wallpaper folder", ["example.jpg: too large", "other.png: empty"]) @@ -17,20 +17,12 @@ test("unchanged background errors do not repeat, but recovered errors can notify report("folder", "Wallpaper folder", []) report("folder", "Wallpaper folder", ["example.jpg: too large"]) expect(shown[2]?.description).toBe("example.jpg: too large") -}) - -test("drops deduplication state for removed sources", () => { - const shown: ToastOptions[] = [] - const report = createWallpaperErrorReporter({ show(options) { shown.push(options); return { dismiss() {} } } }) + shown.length = 0 report("old", "Wallpapers", ["Unreadable image"]) report.retain(["current"]) report("old", "Wallpapers", ["Unreadable image"]) expect(shown).toHaveLength(2) -}) - -test("image failures are shared across the active image and thumbnails, but new versions can notify", () => { - const shown: ToastOptions[] = [] - const report = createWallpaperErrorReporter({ show(options) { shown.push(options); return { dismiss() {} } } }) + shown.length = 0 report("image:example:1", "Wallpapers", ["Unreadable image", "Unreadable image", ""]) report("image:example:1", "Wallpapers", ["Unreadable image"]) expect(shown).toHaveLength(1) diff --git a/src/gallery-toggle.tsx b/src/gallery-toggle.tsx deleted file mode 100644 index 634df0f..0000000 --- a/src/gallery-toggle.tsx +++ /dev/null @@ -1,14 +0,0 @@ -export function WallpaperGalleryToggle(props: { - expanded: boolean - controls: string - label: string - onToggle: () => void -}) { - return -} diff --git a/src/image.ts b/src/image.ts index dae68af..c95e582 100644 --- a/src/image.ts +++ b/src/image.ts @@ -80,18 +80,16 @@ export async function thumbnailBlob(data: string, signal: AbortSignal): Promise< export async function thumbnail(image: CanvasImageSource, width: number, height: number, signal: AbortSignal): Promise { signal.throwIfAborted() - const canvas = document.createElement("canvas") const scale = Math.min(1, 320 / width, 200 / height) - canvas.width = Math.max(1, Math.round(width * scale)) - canvas.height = Math.max(1, Math.round(height * scale)) + width = Math.max(1, Math.round(width * scale)) + height = Math.max(1, Math.round(height * scale)) + const canvas = new OffscreenCanvas(width, height) const context = canvas.getContext("2d") if (!context) throw new Error("image.decodeError") context.drawImage(image, 0, 0, canvas.width, canvas.height) - const blob = await new Promise((resolve, reject) => { - canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error("image.decodeError")), "image/png") - }) + const blob = await canvas.convertToBlob({ type: "image/png" }).catch((cause) => { throw new Error("image.decodeError", { cause }) }) signal.throwIfAborted() - return { blob, width: canvas.width, height: canvas.height } + return { blob, width, height } } export async function uploadImage(file: File, signal: AbortSignal) { @@ -104,25 +102,22 @@ export async function uploadImage(file: File, signal: AbortSignal) { URL.revokeObjectURL(url) } signal.throwIfAborted() + const reader = new FileReader() + const cancel = () => reader.abort() + signal.addEventListener("abort", cancel, { once: true }) return new Promise((resolve, reject) => { - const reader = new FileReader() - const cancel = () => reader.abort() - const finish = () => signal.removeEventListener("abort", cancel) reader.onload = () => { - finish() if (typeof reader.result !== "string") reject(new Error("image.readError")) else resolve(reader.result) } - reader.onerror = () => { finish(); reject(new Error("image.readError")) } - reader.onabort = () => { finish(); reject(signal.reason) } - signal.addEventListener("abort", cancel, { once: true }) + reader.onerror = () => reject(new Error("image.readError")) + reader.onabort = () => reject(signal.reason) try { reader.readAsDataURL(file) } catch (cause) { - finish() reject(new Error("image.readError", { cause })) } - }) + }).finally(() => signal.removeEventListener("abort", cancel)) } export function imageError(error: string, t: (key: string) => string) { diff --git a/src/media-server.test.ts b/src/media-server.test.ts index 4bb11a0..71d6484 100644 --- a/src/media-server.test.ts +++ b/src/media-server.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test" +import { afterEach, expect, test } from "bun:test" import { mkdtemp, realpath, rm, truncate } from "node:fs/promises" import { tmpdir } from "node:os" import path from "node:path" @@ -7,129 +7,127 @@ import { createWallpaperMediaServer } from "./media-server" import { StoredImage, wallpaperBlob } from "./image" import { Schema } from "effect" -test("serves only current catalog media, supports video ranges, and isolates HTML", async () => { - const directory = await mkdtemp(path.join(tmpdir(), "opencode-wallpaper-media-")) - const catalog = createCatalog(directory, () => {}) - const server = await createWallpaperMediaServer(catalog.openMedia) - try { - await Bun.write(path.join(directory, "pond.html"), "") - await Bun.write(path.join(directory, "pond.POSTER.PNG"), "poster") - await Bun.write(path.join(directory, "pond.poster.webp"), "fallback poster") - await Bun.write(path.join(directory, "loop.mp4"), "0123456789") - await Bun.write(path.join(directory, "large.webm"), "0") - await truncate(path.join(directory, "large.webm"), 9 * 1024 * 1024) - await Bun.write(path.join(directory, "fish.gif"), "GIF89a") - await catalog.refresh() - const video = catalog.state().images.find((image) => image.title === "loop")! - const html = catalog.state().images.find((image) => image.title === "pond")! - expect(video.kind).toBe("video") - expect(html.kind).toBe("html") - expect(html.poster?.id).toBe(`file:${encodeURIComponent(await realpath(path.join(directory, "pond.POSTER.PNG")))}`) - expect(catalog.state().images.some((image) => /poster/i.test(image.title))).toBe(false) - expect(await catalog.read(html.poster!)).toBe("data:image/png;base64,cG9zdGVy") - const previous = catalog.state().images - await catalog.refresh() - expect(catalog.state().images).toBe(previous) - expect(catalog.state().images.find((image) => image.title === "large")?.kind).toBe("video") - expect(catalog.state().images.find((image) => image.title === "fish")?.kind).toBeUndefined() - const url = await server.source(video) - const range = await fetch(url, { headers: { Range: "bytes=2-5" } }) - expect(range.status).toBe(206) - expect(range.headers.get("content-range")).toBe("bytes 2-5/10") - expect(await range.text()).toBe("2345") - expect(await (await fetch(url, { headers: { Range: "bytes=-3" } })).text()).toBe("789") - expect((await fetch(url, { headers: { Range: "bytes=50-" } })).status).toBe(416) - expect((await fetch(url, { method: "HEAD" })).headers.get("content-length")).toBe("10") - expect((await fetch(url.replace(new URL(url).pathname, "/wrong"))).status).toBe(404) - const page = await fetch(await server.source(html)) - expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8") - expect(page.headers.get("content-security-policy")).toContain("sandbox allow-scripts") - expect(page.headers.get("content-security-policy")).toContain("default-src 'none'") - expect(page.headers.get("permissions-policy")).toContain("camera=()") - expect(page.headers.get("permissions-policy")).toContain("autoplay=()") - expect(page.headers.get("referrer-policy")).toBe("no-referrer") - await page.text() - await Bun.write(path.join(directory, "pond.POSTER.PNG"), "new poster") - await catalog.refresh() - expect(catalog.state().images.find((image) => image.id === html.id)?.poster?.version).not.toBe(html.poster?.version) - await expect(catalog.read(html.poster!)).rejects.toThrow("changed") - await rm(path.join(directory, "pond.POSTER.PNG")) - await catalog.refresh() - const fallback = catalog.state().images.find((image) => image.id === html.id)! - expect(fallback.poster?.id).toEndWith("pond.poster.webp") - await rm(path.join(directory, "pond.poster.webp")) - await catalog.refresh() - expect(catalog.state().images.find((image) => image.id === html.id)?.poster).toBeUndefined() - await expect(catalog.read(video)).rejects.toThrow("media URL") - await Bun.write(path.join(directory, "loop.mp4"), "changed") - expect((await fetch(url)).status).toBe(404) - await expect(server.source({ id: "file:outside", version: "1" })).rejects.toThrow("missing") - server.dispose() - await expect(server.source(html)).rejects.toThrow("unavailable") - } finally { - server.dispose() - catalog.dispose() - await rm(directory, { recursive: true, force: true }) - } +const directories: string[] = [] +const catalogs: ReturnType[] = [] +const servers: Awaited>[] = [] + +afterEach(async () => { + servers.splice(0).forEach((server) => server.dispose()) + catalogs.splice(0).forEach((catalog) => catalog.dispose()) + await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))) }) -test("rejects malformed ranges and requests without the media token", async () => { - const directory = await mkdtemp(path.join(tmpdir(), "opencode-wallpaper-ranges-")) - const catalog = createCatalog(directory, () => {}) - const server = await createWallpaperMediaServer(catalog.openMedia) - try { - await Bun.write(path.join(directory, "loop.webm"), "0123456789") - await catalog.refresh() - const url = await server.source(catalog.state().images[0]) - for (const range of ["bytes=", "bytes=-", "bytes=-0", "bytes=5-2", "bytes=0-2,5-7", "bytes=9007199254740992-"]) { - const response = await fetch(url, { headers: { Range: range } }) - expect(response.status).toBe(416) - expect(response.headers.get("content-range")).toBe("bytes */10") - await response.text() - } - for (const range of ["bytes=0-99", "bytes=-99", "bytes=0-"]) { - const response = await fetch(url, { headers: { Range: range } }) - expect(response.status).toBe(206) - expect(response.headers.get("content-range")).toBe("bytes 0-9/10") - expect(await response.text()).toBe("0123456789") - } - expect((await fetch(new URL(url).origin)).status).toBe(404) - expect((await fetch(url, { method: "POST" })).status).toBe(404) - const malformed = new URL(url) - malformed.searchParams.delete("version") - expect((await fetch(malformed)).status).toBe(404) - } finally { - server.dispose() - catalog.dispose() - await rm(directory, { recursive: true, force: true }) +test("serves only current catalog media and isolates HTML", async () => { + const { directory, catalog, server } = await fixture() + await Bun.write(path.join(directory, "pond.html"), "") + await Bun.write(path.join(directory, "pond.POSTER.PNG"), "poster") + await Bun.write(path.join(directory, "pond.poster.webp"), "fallback poster") + await Bun.write(path.join(directory, "loop.mp4"), "0123456789") + await Bun.write(path.join(directory, "large.webm"), "0") + await truncate(path.join(directory, "large.webm"), 9 * 1024 * 1024) + await Bun.write(path.join(directory, "fish.gif"), "GIF89a") + await catalog.refresh() + const video = catalog.state().images.find((image) => image.title === "loop")! + const html = catalog.state().images.find((image) => image.title === "pond")! + expect(video.kind).toBe("video") + expect(html.kind).toBe("html") + expect(html.poster?.id).toBe(`file:${encodeURIComponent(await realpath(path.join(directory, "pond.POSTER.PNG")))}`) + expect(catalog.state().images.some((image) => /poster/i.test(image.title))).toBe(false) + expect(await catalog.read(html.poster!)).toBe("data:image/png;base64,cG9zdGVy") + const previous = catalog.state().images + await catalog.refresh() + expect(catalog.state().images).toBe(previous) + expect(catalog.state().images.find((image) => image.title === "large")?.kind).toBe("video") + expect(catalog.state().images.find((image) => image.title === "fish")?.kind).toBeUndefined() + const url = await server.source(video) + const page = await fetch(await server.source(html)) + expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8") + expect(page.headers.get("content-security-policy")).toContain("sandbox allow-scripts") + expect(page.headers.get("content-security-policy")).toContain("default-src 'none'") + expect(page.headers.get("permissions-policy")).toContain("camera=()") + expect(page.headers.get("permissions-policy")).toContain("autoplay=()") + expect(page.headers.get("referrer-policy")).toBe("no-referrer") + await page.text() + await Bun.write(path.join(directory, "pond.POSTER.PNG"), "new poster") + await catalog.refresh() + expect(catalog.state().images.find((image) => image.id === html.id)?.poster?.version).not.toBe(html.poster?.version) + await expect(catalog.read(html.poster!)).rejects.toThrow("changed") + await rm(path.join(directory, "pond.POSTER.PNG")) + await catalog.refresh() + const fallback = catalog.state().images.find((image) => image.id === html.id)! + expect(fallback.poster?.id).toEndWith("pond.poster.webp") + await rm(path.join(directory, "pond.poster.webp")) + await catalog.refresh() + expect(catalog.state().images.find((image) => image.id === html.id)?.poster).toBeUndefined() + await expect(catalog.read(video)).rejects.toThrow("media URL") + await Bun.write(path.join(directory, "loop.mp4"), "changed") + expect((await fetch(url)).status).toBe(404) + await expect(server.source({ id: "file:outside", version: "1" })).rejects.toThrow("missing") + server.dispose() + await expect(server.source(html)).rejects.toThrow("unavailable") +}) + +test.each(["mp4", "webm"])("serves %s ranges and rejects malformed or unauthorized requests", async (extension) => { + const { directory, catalog, server } = await fixture() + await Bun.write(path.join(directory, `loop.${extension}`), "0123456789") + await catalog.refresh() + const url = await server.source(catalog.state().images[0]) + const response = await fetch(url) + expect(response.status).toBe(200) + expect(response.headers.get("content-type")).toBe(`video/${extension}`) + expect(response.headers.get("cache-control")).toBe("no-store") + expect(response.headers.get("x-content-type-options")).toBe("nosniff") + expect(response.headers.get("access-control-allow-origin")).toBe("*") + expect(await response.text()).toBe("0123456789") + for (const range of ["bytes=", "bytes=-", "bytes=-0", "bytes=5-2", "bytes=50-", "bytes=0-2,5-7", "bytes=9007199254740992-"]) { + const response = await fetch(url, { headers: { Range: range } }) + expect(response.status).toBe(416) + expect(response.headers.get("content-range")).toBe("bytes */10") + await response.text() + } + for (const [range, contentRange, body] of [ + ["bytes=2-5", "bytes 2-5/10", "2345"], + ["bytes=-3", "bytes 7-9/10", "789"], + ["bytes=0-99", "bytes 0-9/10", "0123456789"], + ["bytes=-99", "bytes 0-9/10", "0123456789"], + ["bytes=0-", "bytes 0-9/10", "0123456789"], + ] as const) { + const response = await fetch(url, { headers: { Range: range } }) + expect(response.status).toBe(206) + expect(response.headers.get("content-range")).toBe(contentRange) + expect(await response.text()).toBe(body) } + const head = await fetch(url, { method: "HEAD" }) + expect(head.headers.get("content-length")).toBe("10") + expect(await head.text()).toBe("") + for (const invalid of [new URL(url).origin, url.replace(new URL(url).pathname, "/wrong")]) { + expect((await fetch(invalid)).status).toBe(404) + } + expect((await fetch(url, { method: "POST" })).status).toBe(404) + const malformed = new URL(url) + malformed.searchParams.delete("version") + expect((await fetch(malformed)).status).toBe(404) }) test("enforces separate image, HTML, and video limits", async () => { - const directory = await mkdtemp(path.join(tmpdir(), "opencode-wallpaper-limits-")) - const catalog = createCatalog(directory, () => {}) - try { - for (const [name, size] of [ - ["max.mp4", 256 * 1024 * 1024], - ["large.webm", 256 * 1024 * 1024 + 1], - ["large.html", 8 * 1024 * 1024 + 1], - ["empty.mp4", 0], - ] as const) { - await Bun.write(path.join(directory, name), "0") - await truncate(path.join(directory, name), size) - } - await catalog.refresh() - expect(catalog.state().images.map((image) => image.title)).toEqual(["max"]) - expect(catalog.state().error).toBe("empty.mp4: image.videoSizeError\nlarge.html: image.sizeError\nlarge.webm: image.videoSizeError") - const media = await catalog.openMedia(catalog.state().images[0]) - expect(media.size).toBe(256 * 1024 * 1024) - await media.file.close() - catalog.dispose() - await expect(catalog.openMedia({ id: "file:missing", version: "1" })).rejects.toThrow("missing") - } finally { - catalog.dispose() - await rm(directory, { recursive: true, force: true }) + const { directory, catalog } = await fixture() + for (const [name, size] of [ + ["max.mp4", 256 * 1024 * 1024], + ["large.webm", 256 * 1024 * 1024 + 1], + ["large.html", 8 * 1024 * 1024 + 1], + ["empty.mp4", 0], + ] as const) { + await Bun.write(path.join(directory, name), "0") + await truncate(path.join(directory, name), size) } + await catalog.refresh() + expect(catalog.state().images.map((image) => image.title)).toEqual(["max"]) + expect(catalog.state().error).toBe("empty.mp4: image.videoSizeError\nlarge.html: image.sizeError\nlarge.webm: image.videoSizeError") + const media = await catalog.openMedia(catalog.state().images[0]) + expect(media.size).toBe(256 * 1024 * 1024) + await media.file.close() + catalog.dispose() + await expect(catalog.openMedia({ id: "file:missing", version: "1" })).rejects.toThrow("missing") }) test("accepts animated image uploads without converting their bytes", () => { @@ -139,3 +137,13 @@ test("accepts animated image uploads without converting their bytes", () => { expect(wallpaperBlob(data).type).toBe(`image/${type}`) } }) + +async function fixture() { + const directory = await mkdtemp(path.join(tmpdir(), "opencode-wallpaper-media-")) + directories.push(directory) + const catalog = createCatalog(directory, () => {}) + catalogs.push(catalog) + const server = await createWallpaperMediaServer(catalog.openMedia) + servers.push(server) + return { directory, catalog, server } +} diff --git a/src/media-server.ts b/src/media-server.ts index 0a5db5b..646aa8b 100644 --- a/src/media-server.ts +++ b/src/media-server.ts @@ -9,8 +9,8 @@ const htmlPolicy = "default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe- export async function createWallpaperMediaServer(open: ReturnType["openMedia"]) { const token = randomBytes(24).toString("hex") - const server = createServer((request, response) => { - void (async () => { + const server = createServer(async (request, response) => { + try { const url = new URL(request.url ?? "", "http://127.0.0.1") if (url.pathname !== `/${token}` || !["GET", "HEAD"].includes(request.method ?? "")) { response.writeHead(404).end() @@ -46,10 +46,10 @@ export async function createWallpaperMediaServer(open: ReturnType { + } catch { if (!response.headersSent) response.writeHead(404).end() else response.destroy() - }) + } }) await new Promise((resolve, reject) => { server.once("error", reject) diff --git a/src/media.ts b/src/media.ts index 84343cb..dccf0dc 100644 --- a/src/media.ts +++ b/src/media.ts @@ -20,7 +20,7 @@ export function createWallpaperMedia(selected: Accessor { if (!controller.signal.aborted) setState({ loading: false, error, url: error ? "" : url }) - }) + }, controller.signal) setState({ url }) }).catch((error) => { if (!controller.signal.aborted) setState({ loading: false, error: error instanceof Error ? error.message : String(error) }) @@ -29,7 +29,7 @@ export function createWallpaperMedia(selected: Accessor void) { +function mountWallpaperMedia(url: string, kind: "video" | "html", loaded: (error: string) => void, signal: AbortSignal) { const element = wallpaperMediaElement(url, kind, loaded) element.className = "opencode-wallpaper-media" let frame = 0 @@ -50,16 +50,29 @@ function mountWallpaperMedia(url: string, kind: "video" | "html", loaded: (error } } const schedule = () => { if (!frame) frame = requestAnimationFrame(attach) } + let interrupted = document.hidden + const interrupt = () => { interrupted = true } + const resume = () => { + if (document.hidden) return + if (interrupted && element.isConnected) { + if (element instanceof HTMLVideoElement) void element.play().catch(() => {}) + else element.src = url + } + interrupted = false + schedule() + } + window.addEventListener("blur", interrupt, { signal }) + window.addEventListener("focus", resume, { signal }) + document.addEventListener("visibilitychange", () => document.hidden ? interrupt() : resume(), { signal }) const observer = new MutationObserver(schedule) observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["class", "style", "hidden", "data-active"] }) const resized = new ResizeObserver(schedule) resized.observe(document.body) - window.addEventListener("resize", schedule) + window.addEventListener("resize", schedule, { signal }) attach() return () => { observer.disconnect() resized.disconnect() - window.removeEventListener("resize", schedule) cancelAnimationFrame(frame) element.parentElement?.removeAttribute("data-wallpaper-media") element.remove() @@ -101,7 +114,7 @@ export async function videoThumbnailBlob(url: string, signal: AbortSignal) { try { await new Promise((resolve, reject) => { video.onloadeddata = () => resolve() - video.onerror = () => reject(new Error("image.decodeError")) + video.onerror = () => reject(new Error("image.decodeError", { cause: video.error })) lifetime.addEventListener("abort", () => reject(signal.aborted ? signal.reason : new Error("image.decodeError")), { once: true, signal: listeners.signal }) lifetime.throwIfAborted() video.src = url diff --git a/src/model.test.ts b/src/model.test.ts index b05f6f5..e4abbcb 100644 --- a/src/model.test.ts +++ b/src/model.test.ts @@ -8,6 +8,7 @@ import { Preferences, initial } from "./preferences" const customImage = "data:image/png;base64,aGVsbG8=" const customUpload = { id: "custom", name: "Wallpaper", image: customImage } +const file = { id: "file:example.png", title: "example", version: "1" } test("filters static images separately from videos, HTML and animated image uploads", () => { const images = wallpaperCatalog([ @@ -32,15 +33,6 @@ test("filters static images separately from videos, HTML and animated image uplo expect(animatedImage(new TextEncoder().encode(''), "image/svg+xml")).toBe(true) }) -test("resolves only the selected upload or folder image", () => { - const settings = { ...initial, enabled: true, preset: "custom", images: [customUpload] } - const file = { id: "file:example.png", title: "example", version: "1" } - const images = wallpaperCatalog([file], settings) - expect(selectedWallpaper(settings, images)?.image).toBe(customImage) - const selected = { ...settings, preset: file.id } - expect(selectedWallpaper(selected, images)).toBe(file) -}) - test("invalidates cached choices when live metadata or poster versions change", () => { const choice: WallpaperChoice = { id: "file:pond", title: "Pond", version: "1", kind: "html", poster: { id: "file:poster", version: "1" } } expect(sameWallpaper(choice, { ...choice })).toBe(true) @@ -51,8 +43,6 @@ test("invalidates cached choices when live metadata or poster versions change", }) describe("removing wallpapers", () => { - const file = { id: "file:example.png", title: "example", version: "1" } - test("refuses to remove a folder image whether selected or not", () => { const choices = wallpaperCatalog([file], { images: [customUpload] }) for (const selected of [file.id, "custom"]) { @@ -71,31 +61,22 @@ describe("removing wallpapers", () => { expect(saved).toEqual({ ...initial, enabled: true, preset: file.id, tint: 63, fit: "contain" }) const world = picker(undefined, { preferences: saved, images: () => wallpaperCatalog([{ ...file, version: "2" }], saved, choices) }) await world.command.run() - expect(world.requests[0]?.options.some((option) => option.value === "custom")).toBe(false) - expect(world.requests[0]?.options.some((option) => option.value === file.id)).toBe(true) + expect(world.requests[0]?.options.map((option) => option.value)).toEqual([file.id]) }) - test("removing the active uploaded image selects the first remaining wallpaper and allows another upload", () => { - const settings = { ...initial, enabled: true, preset: "custom", images: [{ ...customUpload, name: "saved.png" }], tint: 63, fit: "contain" as const } - const choices = wallpaperCatalog([file], settings) + test.each([ + [true, [file], file.id, true], + [false, [file], file.id, false], + [true, [], "", false], + ] as const)("removing the active upload with enabled=%s and files=%j preserves appearance and chooses %s", (enabled, files, preset, shown) => { + const settings = { ...initial, enabled, preset: "custom", images: [{ ...customUpload, name: "saved.png" }], tint: 63, fit: "contain" as const } + const choices = wallpaperCatalog(files, settings) removeWallpaper(settings, choices.at(-1)!, choices) + const expected = { ...initial, images: [], enabled: shown, preset, tint: 63, fit: "contain" as const } + expect(settings).toEqual(expected) const saved = Schema.decodeUnknownSync(Preferences)(JSON.parse(JSON.stringify(settings))) - expect(saved).toEqual({ ...initial, enabled: true, preset: file.id, tint: 63, fit: "contain" }) - expect(() => checkWallpaperDuplicate({ name: "saved.png", image: customImage }, saved, wallpaperCatalog([file]))).not.toThrow() - }) - - test("turns off the background if the uploaded image is the only provided choice", () => { - const settings = { ...initial, enabled: true, preset: "custom", images: [customUpload] } - const choices = wallpaperCatalog([], settings).filter(canRemoveWallpaper) - removeWallpaper(settings, choices[0], choices) - expect(settings).toEqual({ ...initial, enabled: false, images: [] }) - }) - - test("removing the saved selection while wallpaper is off keeps it off", () => { - const settings = { ...initial, enabled: false, preset: "custom", images: [customUpload] } - const choices = wallpaperCatalog([file], settings) - removeWallpaper(settings, choices.at(-1)!, choices) - expect(settings).toEqual({ ...initial, enabled: false, preset: file.id, images: [] }) + expect(saved).toEqual(expected) + expect(() => checkWallpaperDuplicate({ name: "saved.png", image: customImage }, saved, wallpaperCatalog(files))).not.toThrow() }) }) @@ -116,18 +97,11 @@ describe("custom uploads", () => { expect(settings.images).toEqual([customUpload]) }) - test("checks duplicates across every upload and treats extensions as display-name differences only", () => { - const settings = { ...initial, images: [ - { id: "upload:first", name: "first.png", image: customImage }, - { id: "upload:second", name: "second.webp", image: "data:image/webp;base64,YmV0YQ==" }, - ] } - expect(() => checkWallpaperDuplicate({ name: "FIRST.jpg" }, settings, wallpaperCatalog([], settings))).toThrow("image.duplicateName") - expect(() => checkWallpaperDuplicate({ name: "renamed.png", image: "data:image/png;base64,YmV0YQ==" }, settings, [])).toThrow("image.duplicateImage") - }) - - test("shows the saved filename in the gallery and picker across refreshes", async () => { - const settings = { ...initial, images: [{ ...customUpload, name: "My wallpaper.png" }] } - const choices = wallpaperCatalog([], settings) + test("resolves the selected upload or file and preserves saved filenames across gallery and picker refreshes", async () => { + const settings = { ...initial, preset: "custom", images: [{ ...customUpload, name: "My wallpaper.png" }] } + const choices = wallpaperCatalog([file], settings) + expect(selectedWallpaper(settings, choices)?.image).toBe(customImage) + expect(selectedWallpaper({ ...settings, preset: file.id }, choices)).toBe(file) expect(wallpaperTitle(choices.at(-1)!, (key) => key)).toBe("My wallpaper") expect(wallpaperCatalog([], settings, choices).at(-1)).toBe(choices.at(-1)) const world = picker(undefined, { preferences: settings }) @@ -135,24 +109,19 @@ describe("custom uploads", () => { expect(world.requests[0]?.options.find((option) => option.value === "custom")?.title).toBe("My wallpaper") }) - test.each([ - ["saved.png", "saved.png"], - [" SAVED.PNG ", "saved.png"], - ["Café.png", "Cafe\u0301.PNG"], - ])("rejects filename %s matching saved filename %s", (name, imageName) => { - expect(() => checkWallpaperDuplicate({ name }, { images: [{ ...customUpload, name: imageName }] }, [])).toThrow("image.duplicateName") - }) - - test("rejects matching folder filenames across nested and Windows paths", () => { - const images = ["/images/nested/example.PNG", "C:\\images\\nested\\example.PNG"].map((file) => ({ id: `file:${encodeURIComponent(file)}`, title: "nested/example", version: "1" })) - for (const image of images) { - expect(() => checkWallpaperDuplicate({ name: "example.png" }, initial, [image])).toThrow("image.duplicateName") + test("checks all upload and folder names after normalization and rejects repeated bytes regardless of MIME label", () => { + const settings = { images: [ + { ...customUpload, name: "first.png" }, + { id: "upload:second", name: "saved.png", image: "data:image/webp;base64,YmV0YQ==" }, + { id: "upload:cafe", name: "Cafe\u0301.PNG", image: customImage }, + ] } + for (const name of ["FIRST.jpg", "saved.png", " SAVED.PNG ", "Café.png"]) { + expect(() => checkWallpaperDuplicate({ name }, settings, [])).toThrow("image.duplicateName") } - }) - - test("rejects repeated uploaded-image bytes with a new name or MIME label", () => { - const settings = { ...initial, images: [customUpload] } - for (const source of [customImage, customImage.replace("image/png", "image/jpeg")]) { + for (const file of ["/images/nested/example.PNG", "C:\\images\\nested\\example.PNG"]) { + expect(() => checkWallpaperDuplicate({ name: "example.png" }, initial, [{ id: `file:${encodeURIComponent(file)}`, title: "nested/example", version: "1" }])).toThrow("image.duplicateName") + } + for (const source of [customImage, customImage.replace("image/png", "image/jpeg"), "data:image/png;base64,YmV0YQ=="]) { expect(() => checkWallpaperDuplicate({ name: "renamed.png", image: source }, settings, [])).toThrow("image.duplicateImage") } expect(() => checkWallpaperDuplicate({ name: "different.png", image: "data:image/png;base64,b3RoZXI=" }, settings, [])).not.toThrow() @@ -160,30 +129,18 @@ describe("custom uploads", () => { }) describe("wallpaper slash picker", () => { - test("offers current choices without an empty custom image and leaves preferences unchanged on cancel", async () => { - const world = picker(undefined) + test.each([undefined, "settings", file.id, "custom"])("picker choice %s preserves saved appearance and opens settings only when requested", async (choice) => { + const selecting = choice === file.id || choice === "custom" + const uploads = selecting ? [customUpload] : [] + const world = picker(choice, { + preferences: { enabled: false, preset: selecting ? file.id : "", images: uploads }, + images: () => wallpaperCatalog(selecting ? [file] : [], { images: uploads }), + }) await world.command.run() expect(world.requests[0]?.current).toBe("off") - 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], - ] as const)("choosing %s preserves the saved images, fit and tint", async (choice, enabled, preset, shown) => { - const world = picker(choice, { preferences: { enabled, preset: "file:example.png", images: [customUpload] }, images: () => wallpaperCatalog([{ id: "file:example.png", title: "example", version: "1" }], { images: [customUpload] }) }) - await world.command.run() - expect(world.requests[0]?.current).toBe(enabled ? "file:example.png" : "off") - expect(world.value).toEqual({ ...world.before, enabled: shown, preset }) - expect(world.pages).toEqual([]) - }) - - test("opens full settings only when requested, without changing the wallpaper", async () => { - const world = picker("settings") - await world.command.run() - expect(world.pages).toEqual(["wallpaper"]) - expect(world.value).toEqual(world.before) + expect(world.requests[0]?.options.map((option) => option.value)).toEqual(selecting ? [file.id, "custom"] : []) + expect(world.value).toEqual(selecting ? { ...world.before, enabled: true, preset: choice } : world.before) + expect(world.pages).toEqual(choice === "settings" ? ["wallpaper"] : []) }) test("refreshes the live catalog before opening and selects a newly discovered file", async () => { @@ -192,7 +149,7 @@ describe("wallpaper slash picker", () => { preferences: { enabled: false }, images: () => wallpaperCatalog(images), refresh: async () => { - images.push({ id: "file:example.png", title: "example", version: "new" }) + images.push({ ...file, version: "new" }) return true }, }) diff --git a/src/model.ts b/src/model.ts index 22d5bd6..5288c63 100644 --- a/src/model.ts +++ b/src/model.ts @@ -24,15 +24,11 @@ export function selectedWallpaper(settings: Pick return images.find((image) => image.id === settings.preset) } -export function uploadedWallpapers(settings: SavedImages): readonly UploadedWallpaper[] { - return settings.images -} - export function wallpaperCatalog(images: readonly (typeof Wallpaper.Type)[] = [], settings: SavedImages = initial, previous: readonly WallpaperChoice[] = []): WallpaperChoice[] { const saved = new Map(previous.map((image) => [image.id, image])) return [ ...images, - ...uploadedWallpapers(settings).map((upload) => { + ...settings.images.map((upload) => { const title = wallpaperName(upload.name) const cached = saved.get(upload.id) if (cached?.image === upload.image && cached.title === title) return cached @@ -73,7 +69,7 @@ export function wallpaperTitle(image: WallpaperChoice, t: (key: string) => strin export function checkWallpaperDuplicate(upload: { name: string; image?: string }, settings: SavedImages, images: readonly WallpaperChoice[]) { const key = filenameKey(upload.name) const bytes = imageBytes(upload.image ?? "") - for (const saved of uploadedWallpapers(settings)) { + for (const saved of settings.images) { if (saved.name && filenameKey(saved.name) === key) throw new Error("image.duplicateName") if (bytes && bytes === imageBytes(saved.image)) throw new Error("image.duplicateImage") } @@ -85,8 +81,7 @@ export function checkWallpaperDuplicate(upload: { name: string; image?: string } function wallpaperFilename(id: string) { if (!id.startsWith("file:")) return "" - const path = id.slice(5) - return decodeURIComponent(path) + return decodeURIComponent(id.slice(5)) } function filenameKey(name: string) { diff --git a/src/preferences.test.ts b/src/preferences.test.ts index 123021b..5e1424c 100644 --- a/src/preferences.test.ts +++ b/src/preferences.test.ts @@ -1,6 +1,6 @@ -import { describe, expect, test } from "bun:test" +import { expect, test } from "bun:test" import { Schema } from "effect" -import { Preferences, StoredPreferences, initial, slideshowControls, wallpaperAppearance } from "./preferences" +import { Preferences, StoredPreferences, initial, slideshowControls } from "./preferences" import { wallpaperBackground } from "./style" test("starts with wallpaper off and no selection while retaining unknown selections from old saves", () => { @@ -9,24 +9,22 @@ test("starts with wallpaper off and no selection while retaining unknown selecti expect(Schema.decodeUnknownSync(Preferences)(saved)).toEqual(saved) }) -test("migrates the single legacy upload once and encodes only the canonical image list", () => { +test("migrates legacy uploads and strength once, writing only canonical fields", () => { const image = "data:image/png;base64,YWJj" - const saved = { enabled: true, preset: "custom", image, imageName: "old.png", strength: 20, fit: "contain" } - const settings = Schema.decodeUnknownSync(Preferences)(saved) - expect(settings.images).toEqual([{ id: "custom", name: "old.png", image }]) - const encoded = Schema.encodeSync(Preferences)(settings) - expect(encoded).not.toHaveProperty("image") - expect(encoded).not.toHaveProperty("imageName") - expect(Schema.decodeUnknownSync(Preferences)(encoded)).toEqual(settings) - expect(Schema.decodeUnknownSync(StoredPreferences)({ ...saved, hidden: ["custom"] }).images).toEqual(settings.images) -}) - -test("rejects duplicate upload identities", () => { - const upload = { id: "upload:one", name: "one.png", image: "data:image/png;base64,YWJj" } - expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, images: [upload, upload] })).toThrow() + for (const [strength, legacy] of [[5, ""], [20, ""], [45, ""], [20, image]] as const) { + const saved = { enabled: true, preset: "custom", image: legacy, imageName: "old.png", strength, fit: "contain", hidden: ["custom"] } + const settings = Schema.decodeUnknownSync(Preferences)(saved) + const expected = { ...initial, enabled: true, preset: "custom", images: legacy ? [{ id: "custom", name: "old.png", image }] : [], tint: 100 - strength, fit: "contain" as const } + expect(settings).toEqual(expected) + expect(wallpaperBackground(settings, "blob:wallpaper")["--wallpaper-filter"]).toContain("brightness(100%)") + const encoded = Schema.encodeSync(Preferences)(settings) + expect(encoded).toEqual(expected) + expect(Schema.decodeUnknownSync(Preferences)(encoded)).toEqual(settings) + expect(Schema.decodeUnknownSync(StoredPreferences)(saved).images).toEqual(settings.images) + } }) -test("round-trips animated uploads alongside existing images without changing bytes or selection", () => { +test("round-trips animated uploads without changing bytes or selection and rejects duplicate identities", () => { const saved = { ...initial, enabled: true, preset: "upload:gif", tint: 42, images: [ { id: "upload:png", name: "old.png", image: "data:image/png;base64,YWJj" }, { id: "upload:gif", name: "fish.gif", image: "data:image/gif;base64,R0lGODlh" }, @@ -35,6 +33,7 @@ test("round-trips animated uploads alongside existing images without changing by const restored = Schema.decodeUnknownSync(StoredPreferences)(saved) expect(restored).toEqual(saved) expect(Schema.decodeUnknownSync(StoredPreferences)(Schema.encodeSync(StoredPreferences)(restored))).toEqual(saved) + expect(() => Schema.decodeUnknownSync(Preferences)({ ...saved, images: [saved.images[0], saved.images[0]] })).toThrow() }) test("recovers unrelated persisted fields without dropping legacy or current uploads", () => { @@ -43,67 +42,41 @@ test("recovers unrelated persisted fields without dropping legacy or current upl for (const changed of [{ tint: 101 }, { brightness: "bad" }, { fit: undefined }, { duration: 0 }, { strength: "bad" }]) { const saved = { enabled: true, preset: "custom", image, imageName: "old.png", images: [uploaded], strength: 20, fit: "contain", ...changed } const settings = Schema.decodeUnknownSync(StoredPreferences)(saved) - expect(settings.images).toEqual([{ id: "custom", name: "old.png", image }, uploaded]) - expect(settings.enabled).toBe(true) - expect(settings.preset).toBe("custom") + expect(settings).toMatchObject({ images: [{ id: "custom", name: "old.png", image }, uploaded], enabled: true, preset: "custom" }) const encoded = Schema.encodeSync(StoredPreferences)(settings) expect(encoded).not.toHaveProperty("image") expect(Schema.decodeUnknownSync(StoredPreferences)(encoded).images).toEqual(settings.images) } }) -describe("wallpaper slideshow preferences", () => { - test("persists slideshow options at both display-time limits", () => { - for (const [transition, duration] of [["none", slideshowControls.min], ["fade", slideshowControls.max]] as const) { - const saved = { ...initial, slideshow: true, duration, transition } - expect(Schema.decodeUnknownSync(Preferences)(JSON.parse(JSON.stringify(saved)))).toEqual(saved) - } - }) - - test("rejects invalid display times and unknown transitions on writes", () => { - for (const duration of [0, 4, 86401, 5.5, NaN, Infinity, "60"]) { - expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, duration })).toThrow() - } - expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, transition: "spin" })).toThrow() - }) +test("persists slideshow options at both display-time limits", () => { + for (const [transition, duration] of [["none", slideshowControls.min], ["fade", slideshowControls.max]] as const) { + const saved = { ...initial, slideshow: true, duration, transition } + expect(Schema.decodeUnknownSync(Preferences)(JSON.parse(JSON.stringify(saved)))).toEqual(saved) + } }) -describe("wallpaper tint and brightness", () => { - test("migrates old strength to canonical tint and writes no legacy fields", () => { - for (const strength of [5, 20, 45]) { - const settings = Schema.decodeUnknownSync(Preferences)({ enabled: true, preset: "", image: "", strength, fit: "cover", hidden: ["file:old"] }) - expect(wallpaperAppearance(settings).tint).toBe(100 - strength) - expect(wallpaperBackground(settings, "blob:wallpaper")["--wallpaper-filter"]).toContain("brightness(100%)") - expect(settings.tint).toBe(100 - strength) - expect(settings.brightness).toBe(100) - const encoded = Schema.encodeSync(Preferences)(settings) - expect(encoded).not.toHaveProperty("strength") - expect(encoded).not.toHaveProperty("hidden") - expect(encoded).not.toHaveProperty("image") - expect(Schema.decodeUnknownSync(Preferences)(encoded)).toEqual(settings) - } - }) - - test("persists independent tint and brightness, including zero tint", () => { - const settings = Schema.decodeUnknownSync(Preferences)({ ...initial, enabled: true, tint: 0, brightness: 150 }) - const saved = Schema.decodeUnknownSync(Preferences)(JSON.parse(JSON.stringify(settings))) - expect(wallpaperAppearance(saved).tint).toBe(0) - expect(wallpaperBackground(saved, "blob:wallpaper")).toEqual({ - "--wallpaper-image": 'url("blob:wallpaper")', - "--wallpaper-fit": "cover", - "--wallpaper-tint": "color-mix(in srgb, var(--v2-background-bg-base) 0%, transparent)", - "--wallpaper-filter": "brightness(150%) contrast(85%) saturate(90%)", - }) - expect(wallpaperBackground({ ...saved, enabled: false }, "blob:wallpaper")["--wallpaper-image"]).toBe("none") - expect(wallpaperBackground({ ...saved, enabled: false }, "blob:wallpaper")["--wallpaper-filter"]).toBe("none") - expect(wallpaperBackground(saved, "")["--wallpaper-tint"]).toBe("transparent") - expect(wallpaperBackground(saved, "")["--wallpaper-filter"]).toBe("none") +test("persists independent tint and brightness, including zero tint", () => { + const settings = { ...initial, enabled: true, tint: 0, brightness: 150 } + const saved = Schema.decodeUnknownSync(Preferences)(JSON.parse(JSON.stringify(settings))) + expect(saved).toEqual(settings) + expect(wallpaperBackground(saved, "blob:wallpaper")).toEqual({ + "--wallpaper-image": 'url("blob:wallpaper")', + "--wallpaper-fit": "cover", + "--wallpaper-tint": "color-mix(in srgb, var(--v2-background-bg-base) 0%, transparent)", + "--wallpaper-filter": "brightness(150%) contrast(85%) saturate(90%)", }) + expect(wallpaperBackground({ ...saved, enabled: false }, "blob:wallpaper")["--wallpaper-image"]).toBe("none") + expect(wallpaperBackground({ ...saved, enabled: false }, "blob:wallpaper")["--wallpaper-filter"]).toBe("none") + expect(wallpaperBackground(saved, "")["--wallpaper-tint"]).toBe("transparent") + expect(wallpaperBackground(saved, "")["--wallpaper-filter"]).toBe("none") +}) - test.each([ - ["tint", -1], ["tint", 101], ["tint", 25.5], - ["brightness", 24], ["brightness", 151], ["brightness", 100.5], - ])("rejects invalid %s value %s on writes", (property, value) => { - expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, [property]: value })).toThrow() - }) +test.each([ + ["duration", [0, 4, 86401, 5.5, NaN, Infinity, "60"]], + ["transition", ["spin"]], + ["tint", [-1, 101, 25.5]], + ["brightness", [24, 151, 100.5]], +])("rejects invalid %s values on writes", (property, values) => { + for (const value of values) expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, [property]: value })).toThrow() }) diff --git a/src/preferences.ts b/src/preferences.ts index af3b92f..00d00ed 100644 --- a/src/preferences.ts +++ b/src/preferences.ts @@ -98,10 +98,3 @@ export const StoredPreferences = Schema.Struct({ imageName: recover(SavedPreferences.fields.imageName, undefined), strength: recover(SavedPreferences.fields.strength, undefined), }).pipe(Schema.decodeTo(Preferences)) - -export function wallpaperAppearance(settings: Pick) { - return { - tint: settings.tint, - brightness: settings.brightness, - } -} diff --git a/src/preview.tsx b/src/preview.tsx index 8b4d789..7a023b2 100644 --- a/src/preview.tsx +++ b/src/preview.tsx @@ -1,4 +1,4 @@ -import { createEffect, createSignal, on, onCleanup, Show } from "solid-js" +import { createEffect, createSignal, on, onCleanup } from "solid-js" import { wallpaperBlob } from "./image" import { wallpaperMediaElement } from "./media" import type { WallpaperChoice } from "./model" @@ -33,5 +33,5 @@ export function WallpaperPreview(props: { choice: WallpaperChoice; read: Wallpap setElement(preview) }).catch(() => {}) })) - return {(element) => element()} + return <>{element()} } diff --git a/src/render.test.ts b/src/render.test.ts index b1d9361..a5cf333 100644 --- a/src/render.test.ts +++ b/src/render.test.ts @@ -1,4 +1,4 @@ -import { afterEach, expect, jest, spyOn, test } from "bun:test" +import { afterEach, expect, jest, mock, spyOn, test } from "bun:test" import { batch, createMemo, createRoot, createSignal } from "solid-js" import type { WallpaperChoice } from "./model" import { createWallpaperImage, createWallpaperVisibility } from "./render" @@ -24,36 +24,31 @@ function fixture(duration = 0, animateVisibility = false) { } }) spyOn(URL, "createObjectURL").mockImplementation(() => { const url = `blob:test-${urls.length}`; urls.push(url); return url }) spyOn(URL, "revokeObjectURL").mockImplementation((url) => { revoked.push(url) }) - let select!: (choice: WallpaperChoice | undefined) => void - let image!: ReturnType - let visibility: ReturnType | undefined - let setEnabled!: (enabled: boolean) => void - let setReducedMotion!: (reduced: boolean) => void - createRoot((cleanup) => { + const state = createRoot((cleanup) => { dispose = cleanup + let image!: ReturnType const [selected, setSelected] = createSignal() const [enabled, updateEnabled] = createSignal(false) const [motion, updateMotion] = createSignal(false) - setEnabled = (value) => { updateEnabled(value) } - setReducedMotion = (value) => { updateMotion(value) } - visibility = animateVisibility ? createWallpaperVisibility(enabled, () => !!image.url, motion) : undefined + const visibility = animateVisibility ? createWallpaperVisibility(enabled, () => !!image.url, motion) : undefined const source = visibility ? createMemo(() => enabled() ? selected() : visibility?.enabled() ? image.choice : undefined) : selected - select = (choice) => { + const select = (choice: WallpaperChoice | undefined) => { if (!visibility) { setSelected(choice); return } batch(() => { if (choice) setSelected(choice); updateEnabled(!!choice) }) } image = createWallpaperImage(source, async () => data, () => duration) + return { image, select, setEnabled: updateEnabled, setReducedMotion: updateMotion, visibility } }) - const choose = (id: string) => select({ id, title: id, version: "1", image: data }) - return { image, choose, select, setEnabled, setReducedMotion, visibility } + const choose = (id: string) => state.select({ id, title: id, version: "1", image: data }) + const load = async (id: string) => { choose(id); decodes.at(-1)!.resolve(); await flush() } + return { ...state, choose, load } } afterEach(() => { dispose?.() dispose = undefined jest.useRealTimers() - spyOn(URL, "createObjectURL").mockRestore() - spyOn(URL, "revokeObjectURL").mockRestore() + mock.restore() if (originalImage) Object.defineProperty(globalThis, "Image", originalImage) else Reflect.deleteProperty(globalThis, "Image") }) @@ -62,39 +57,29 @@ const flush = async () => { await Promise.resolve(); await Promise.resolve(); aw test("keeps the current frame during reads and decoding, then releases it for an instant switch", async () => { const f = fixture() - f.choose("a") - decodes[0].resolve() - await flush() - expect(f.image.url).toBe("blob:test-0") + await f.load("a") f.choose("b") expect(f.image.loading).toBe(true) expect(f.image.url).toBe("blob:test-0") expect(revoked).toEqual([]) decodes[1].resolve() await flush() - expect(f.image.url).toBe("blob:test-1") - expect(f.image.previous).toBeUndefined() + expect(f.image).toMatchObject({ url: "blob:test-1", previous: undefined }) expect(revoked).toEqual(["blob:test-0"]) }) test("retains outgoing URLs until fades finish and releases every frame on cleanup", async () => { jest.useFakeTimers() const f = fixture(800) - f.choose("a") - decodes[0].resolve() - await flush() - f.choose("b") - decodes[1].resolve() - await flush() + await f.load("a") + await f.load("b") expect(f.image.previous?.url).toBe("blob:test-0") expect(f.image.transition).toBe(800) expect(revoked).toEqual([]) jest.advanceTimersByTime(800) expect(f.image.previous).toBeUndefined() expect(revoked).toEqual(["blob:test-0"]) - f.choose("c") - decodes[2].resolve() - await flush() + await f.load("c") dispose?.() dispose = undefined expect(revoked.sort()).toEqual(["blob:test-0", "blob:test-1", "blob:test-2"]) @@ -103,18 +88,13 @@ test("retains outgoing URLs until fades finish and releases every frame on clean test("preserves the last readable image on failure and clears it when its source is removed", async () => { const f = fixture() - f.choose("a") - decodes[0].resolve() - await flush() + await f.load("a") f.choose("b") decodes[1].reject() await flush() - expect(f.image.url).toBe("blob:test-0") - expect(f.image.error).toBe("image.decodeError") - expect(f.image.loading).toBe(false) + expect(f.image).toMatchObject({ url: "blob:test-0", error: "image.decodeError", loading: false }) f.select(undefined) - expect(f.image.url).toBe("") - expect(f.image.width).toBe(0) + expect(f.image).toMatchObject({ url: "", width: 0 }) expect(revoked.sort()).toEqual(["blob:test-0", "blob:test-1"]) }) @@ -126,9 +106,7 @@ test("aborts rapid selections without letting stale decodes replace the current await flush() decodes[0].resolve() await flush() - expect(f.image.url).toBe("blob:test-1") - expect(f.image.previous).toBeUndefined() - expect(f.image.error).toBe("") + expect(f.image).toMatchObject({ url: "blob:test-1", previous: undefined, error: "" }) expect(revoked).toContain("blob:test-0") }) @@ -162,9 +140,7 @@ test("holds the decoded wallpaper through off fades, reverses quick toggles, and expect(f.image.url).toBe("") expect(revoked.sort()).toEqual(["blob:test-0", "blob:test-1"]) expect(jest.getTimerCount()).toBe(0) - f.choose("a") - decodes[2].resolve() - await flush() + await f.load("a") f.setReducedMotion(true) expect(f.visibility?.fade()).toBeUndefined() f.select(undefined) diff --git a/src/render.ts b/src/render.ts index c831881..a9f47fd 100644 --- a/src/render.ts +++ b/src/render.ts @@ -109,11 +109,14 @@ export function createWallpaperThumbnail(selected: Accessor { const choice = source() - const controller = new AbortController() + let active = true let lease: ThumbnailLease | undefined - onCleanup(() => { controller.abort(); lease?.release() }) + onCleanup(() => { active = false; lease?.release() }) setState({ url: "", width: 0, height: 0, loading: !!choice, error: "" }) if (!choice) return + const fail = (error: unknown) => { + if (active) setState({ loading: false, error: error instanceof Error ? error.message : String(error) }) + } try { lease = cache.acquire(choice) if (lease.value) { @@ -121,13 +124,9 @@ export function createWallpaperThumbnail(selected: Accessor { - if (!controller.signal.aborted) setState({ ...thumbnail, loading: false }) - }, (error: unknown) => { - if (!controller.signal.aborted) setState({ loading: false, error: error instanceof Error ? error.message : String(error) }) - }) - } catch (error) { - setState({ loading: false, error: error instanceof Error ? error.message : String(error) }) - } + if (active) setState({ ...thumbnail, loading: false }) + }, fail) + } catch (error) { fail(error) } }) return state } diff --git a/src/settings.css b/src/settings.css index 0316b45..c1778ea 100644 --- a/src/settings.css +++ b/src/settings.css @@ -20,13 +20,20 @@ width: 100%; } -.opencode-wallpaper-gallery-toggle-button { - padding: 6px 12px; +.opencode-wallpaper-gallery-toggle-button, +.opencode-wallpaper-gallery button, +.opencode-wallpaper-duration input, +.opencode-wallpaper-picker-search, +.opencode-wallpaper-picker-choice { border: 1px solid var(--v2-border-border-base); border-radius: 6px; background: var(--v2-background-bg-layer-01); color: var(--v2-text-text-base); font: inherit; +} + +.opencode-wallpaper-gallery-toggle-button { + padding: 6px 12px; cursor: pointer; } @@ -34,11 +41,6 @@ background: var(--v2-background-bg-layer-02); } -.opencode-wallpaper-gallery-toggle-button:focus-visible { - outline: 2px solid var(--v2-border-border-focus); - outline-offset: 2px; -} - .opencode-wallpaper-gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 160px), 1fr)); @@ -58,29 +60,24 @@ min-width: 0; } -.opencode-wallpaper-gallery-heading { +.opencode-wallpaper-gallery-heading, +.opencode-wallpaper-gallery-controls, +.opencode-wallpaper-range, +.opencode-wallpaper-picker-footer { display: flex; align-items: center; - justify-content: space-between; flex-wrap: wrap; gap: 8px; } -.opencode-wallpaper-gallery-controls { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 8px; +.opencode-wallpaper-gallery-heading, +.opencode-wallpaper-picker-footer { + justify-content: space-between; } .opencode-wallpaper-gallery button { padding: 4px; - border-radius: 6px; - border: 1px solid var(--v2-border-border-base); - color: var(--v2-text-text-base); - background: var(--v2-background-bg-layer-01); text-align: start; - font: inherit; cursor: pointer; } @@ -225,7 +222,9 @@ display: none; } -.opencode-wallpaper-gallery button:focus-visible { +.opencode-wallpaper-gallery-toggle-button:focus-visible, +.opencode-wallpaper-gallery button:focus-visible, +.opencode-wallpaper-duration input:focus-visible { outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px; } @@ -235,13 +234,6 @@ cursor: not-allowed; } -.opencode-wallpaper-range { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 8px; -} - .opencode-wallpaper-range output { width: 5ch; flex-shrink: 0; @@ -274,22 +266,11 @@ .opencode-wallpaper-duration input { width: 8ch; text-align: center; - font-variant-numeric: tabular-nums; } .opencode-wallpaper-duration input, .opencode-wallpaper-picker-search { padding: 6px 8px; - border: 1px solid var(--v2-border-border-base); - border-radius: 6px; - background: var(--v2-background-bg-layer-01); - color: var(--v2-text-text-base); - font: inherit; -} - -.opencode-wallpaper-duration input:focus-visible { - outline: 2px solid var(--v2-border-border-focus); - outline-offset: 2px; } .opencode-wallpaper-duration input:disabled { @@ -327,10 +308,7 @@ width: 100%; padding: 8px; border: 0; - border-radius: 6px; background: transparent; - color: var(--v2-text-text-base); - font: inherit; text-align: start; cursor: pointer; } @@ -351,10 +329,5 @@ } .opencode-wallpaper-picker-footer { - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; - flex-wrap: wrap; width: 100%; } diff --git a/src/settings.tsx b/src/settings.tsx index a05e02e..ae2f80a 100644 --- a/src/settings.tsx +++ b/src/settings.tsx @@ -3,10 +3,9 @@ import { usePlugin } from "@opencode/plugin/gui" import type definition from "./gui" import { canRemoveWallpaper, changeWallpaper, checkWallpaperDuplicate, filterWallpapers, isLiveWallpaper, removeWallpaper, wallpaperTitle, type WallpaperChoice, type WallpaperFilter } from "./model" import { uploadImage } from "./image" -import { appearanceControls, appearanceKeys, slideshowControls, wallpaperAppearance, type WallpaperTransition } from "./preferences" +import { appearanceControls, appearanceKeys, slideshowControls, type WallpaperTransition } from "./preferences" import type { ThumbnailCache } from "./thumbnail-cache" import { WallpaperThumbnail } from "./thumbnail" -import { WallpaperGalleryToggle } from "./gallery-toggle" import { WallpaperLiveIcon } from "./live-icon" import type { WallpaperReader } from "./render" @@ -33,7 +32,6 @@ export function WallpaperSettings(props: { const galleryId = createUniqueId() let gallery!: HTMLDivElement let fileInput!: HTMLInputElement - const appearance = createMemo(() => wallpaperAppearance(settings.value)) const limit = () => columns() * 2 - 1 const filtered = createMemo(() => filterWallpapers(props.images(), filter())) const visibleImages = createMemo(() => expanded() ? filtered() : filtered().slice(0, limit())) @@ -142,10 +140,7 @@ export function WallpaperSettings(props: { label={ctx.t("fit.title")} value={settings.value.fit} - options={[ - { value: "cover", label: ctx.t("fit.cover") }, - { value: "contain", label: ctx.t("fit.contain") }, - ]} + options={(["cover", "contain"] as const).map((value) => ({ value, label: ctx.t(`fit.${value}`) }))} onChange={(value) => settings.update((draft) => { draft.fit = value })} /> @@ -207,12 +202,13 @@ export function WallpaperSettings(props: { limit()}> @@ -235,11 +231,7 @@ export function WallpaperSettings(props: { - {ctx.t("slideshow.description")} -
- } + description={ctx.t("slideshow.description")} > label={ctx.t("transition.title")} value={settings.value.transition} - options={[ - { value: "none", label: ctx.t("transition.none") }, - { value: "fade", label: ctx.t("transition.fade") }, - ]} + options={(["none", "fade"] as const).map((value) => ({ value, label: ctx.t(`transition.${value}`) }))} onChange={(value) => settings.update((draft) => { draft.transition = value })} /> @@ -304,11 +293,11 @@ export function WallpaperSettings(props: { min={appearanceControls[key].min} max={appearanceControls[key].max} step="1" - value={appearance()[key]} + value={settings.value[key]} aria-label={ctx.t(`${key}.title`)} onInput={(event) => settings.update((draft) => { draft[key] = event.currentTarget.valueAsNumber })} /> - {appearance()[key]}% + {settings.value[key]}% } diff --git a/src/style.ts b/src/style.ts index 6f9fb45..e890489 100644 --- a/src/style.ts +++ b/src/style.ts @@ -1,12 +1,11 @@ -import { wallpaperAppearance, type WallpaperPreferences } from "./preferences" +import type { WallpaperPreferences } from "./preferences" export function createWallpaperStyles(settings: string, canvas: string) { - const settingsStyle = document.createElement("style") - const canvasStyle = document.createElement("style") - const imageStyle = document.createElement("style") - settingsStyle.dataset.wallpaperStyle = "settings" - canvasStyle.dataset.wallpaperStyle = "canvas" - imageStyle.dataset.wallpaperStyle = "image" + const [settingsStyle, canvasStyle, imageStyle] = ["settings", "canvas", "image"].map((kind) => { + const style = document.createElement("style") + style.dataset.wallpaperStyle = kind + return style + }) settingsStyle.textContent = settings canvasStyle.textContent = canvas canvasStyle.disabled = true @@ -17,9 +16,7 @@ export function createWallpaperStyles(settings: string, canvas: string) { canvasStyle.disabled = !variables }, dispose() { - settingsStyle.remove() - canvasStyle.remove() - imageStyle.remove() + for (const style of [settingsStyle, canvasStyle, imageStyle]) style.remove() }, } } @@ -107,7 +104,10 @@ export const wallpaperSurfaces = ` :is([data-slot="home-panel"], [data-component="new-session"]) :is(.text-v2-text-text-muted, .text-v2-text-text-faint), [data-component="new-session"] [data-slot="new-session-location-path"], - [data-slot="session-chat-panel"] [data-slot="session-timeline-scroll"] :is(.text-v2-text-text-muted, .text-v2-text-text-faint, [data-slot="basic-tool-tool-subtitle"]:not(.webfetch-link), [data-slot="basic-tool-tool-arg"], [data-slot="context-tool-group-usage"], [data-slot="context-tool-group-matches"], [data-slot="execute-tool-call-args"], [data-slot="text-part-meta"], [data-component="reasoning-part"] [data-component="markdown"]) { + [data-slot="session-chat-panel"] [data-slot="session-timeline-scroll"] :is(.text-v2-text-text-muted, .text-v2-text-text-faint, [data-slot="basic-tool-tool-subtitle"]:not(.webfetch-link), [data-slot="basic-tool-tool-arg"], [data-slot="context-tool-group-usage"], [data-slot="context-tool-group-matches"], [data-slot="execute-tool-call-args"], [data-slot="text-part-meta"], [data-component="reasoning-part"] [data-component="markdown"]), + :is([data-slot="home-panel"], [data-component="new-session"]) :is(.text-v2-icon-icon-muted, .text-v2-icon-icon-faint), + [data-slot="home-panel"] button.text-v2-text-text-faint > [data-slot="icon-svg"], + [data-slot="home-panel"] [data-component="home-session-search"] input::placeholder { color: var(--wallpaper-secondary); } @@ -117,15 +117,6 @@ export const wallpaperSurfaces = ` text-shadow: var(--wallpaper-text-shadow); } - :is([data-slot="home-panel"], [data-component="new-session"]) :is(.text-v2-icon-icon-muted, .text-v2-icon-icon-faint), - [data-slot="home-panel"] button.text-v2-text-text-faint > [data-slot="icon-svg"] { - color: var(--wallpaper-secondary); - } - - [data-slot="home-panel"] [data-component="home-session-search"] input::placeholder { - color: var(--wallpaper-secondary); - } - [data-slot="home-panel"] button:is(:hover, :focus-visible, [data-selected]) { color: var(--v2-text-text-base); } @@ -176,7 +167,7 @@ export const wallpaperCanvasStyle = wallpaperSurfaces + wallpaperLayers(`${wallp export function wallpaperBackground(settings: WallpaperPreferences, image: string, media = false) { const visible = settings.enabled && !!image - const { tint, brightness } = wallpaperAppearance(settings) + const { tint, brightness } = settings return { "--wallpaper-image": visible && !media ? `url(${JSON.stringify(image)})` : "none", "--wallpaper-fit": settings.fit, diff --git a/src/thumbnail-cache.test.ts b/src/thumbnail-cache.test.ts index 39ec298..ce1d35a 100644 --- a/src/thumbnail-cache.test.ts +++ b/src/thumbnail-cache.test.ts @@ -1,46 +1,54 @@ -import { expect, spyOn, test } from "bun:test" +import { afterEach, expect, mock, spyOn, test } from "bun:test" +import { createRoot, createSignal } from "solid-js" import { createThumbnailCache } from "./thumbnail-cache" import type { ThumbnailBlob } from "./image" +import type { WallpaperChoice } from "./model" +import { createWallpaperThumbnail } from "./render" const file = { id: "file:example.png", title: "example", version: "1" } const thumbnail = (): ThumbnailBlob => ({ blob: new Blob(["tile"], { type: "image/png" }), width: 32, height: 20 }) -function deferred() { - let resolve!: (value: T) => void - const promise = new Promise((accept) => { resolve = accept }) - return { promise, resolve } +const cleanups: (() => void)[] = [] +function fixture(...args: Parameters) { + const cache = createThumbnailCache(...args) + cleanups.push(cache.dispose) + return cache } -const tick = () => new Promise((resolve) => setImmediate(resolve)) - -test("reopening a tile reuses its URL synchronously without another read or decode", async () => { - let loads = 0 - const cache = createThumbnailCache(async () => { loads++; return thumbnail() }) - try { - const first = cache.acquire(file) - const loaded = await first.ready - first.release() - const reopened = cache.acquire({ ...file, title: "renamed label" }) - expect(reopened.value).toBe(loaded) - expect(await reopened.ready).toBe(loaded) - expect(loads).toBe(1) - reopened.release() - } finally { cache.dispose() } +function tile(cache: ReturnType) { + return createRoot((dispose) => { + cleanups.push(dispose) + const [selected, select] = createSignal() + const image = createWallpaperThumbnail(selected, cache) + select(file) + return { image, select } + }) +} +afterEach(() => { + for (const dispose of cleanups.splice(0).reverse()) dispose() + mock.restore() }) +const tick = () => new Promise((resolve) => setImmediate(resolve)) -test("shares an in-flight thumbnail and lets it finish after one consumer closes", async () => { +test("shares in-flight thumbnails, ignores closed tiles, and reopens synchronously without another load", async () => { let loads = 0 - const pending = deferred() - const cache = createThumbnailCache(async () => { loads++; return pending.promise }) - try { - const first = cache.acquire(file) - const second = cache.acquire(file) - expect(first.ready).toBe(second.ready) - first.release() - pending.resolve(thumbnail()) - await second.ready - expect(loads).toBe(1) - second.release() - expect(cache.peek(file)?.url).toBeTruthy() - } finally { cache.dispose() } + const pending = Promise.withResolvers() + const cache = fixture(async () => { loads++; return pending.promise }) + const first = cache.acquire(file) + const second = cache.acquire(file) + expect(first.ready).toBe(second.ready) + const rendered = tile(cache) + rendered.select(undefined) + first.release() + pending.resolve(thumbnail()) + const loaded = await second.ready + expect(rendered.image.url).toBe("") + second.release() + expect(cache.peek(file)).toBe(loaded) + const reopened = cache.acquire({ ...file, title: "renamed label" }) + expect(reopened.value).toBe(loaded) + expect(await reopened.ready).toBe(loaded) + expect(tile(cache).image.url).toBe(loaded.url) + expect(loads).toBe(1) + reopened.release() }) test("invalidates changed file versions and changed uploaded content", async () => { @@ -49,93 +57,101 @@ test("invalidates changed file versions and changed uploaded content", async () [{ ...file, id: "upload:one", image: "first" }, { ...file, id: "upload:one", image: "second" }], ]) { let loads = 0 - const cache = createThumbnailCache(async () => { loads++; return thumbnail() }) - try { - const first = cache.acquire(before) - await first.ready - first.release() - const original = { ...before } - Object.assign(before, after) - cache.retain([before]) - expect(cache.peek(original)).toBeUndefined() - const changed = cache.acquire(before) - await changed.ready - expect(loads).toBe(2) - changed.release() - } finally { cache.dispose() } + const cache = fixture(async () => { loads++; return thumbnail() }) + const first = cache.acquire(before) + await first.ready + first.release() + const original = { ...before } + Object.assign(before, after) + cache.retain([before]) + expect(cache.peek(original)).toBeUndefined() + const changed = cache.acquire(before) + await changed.ready + expect(loads).toBe(2) + changed.release() } }) test("bounds idle entries and bytes without evicting displayed thumbnails", async () => { const revoke = spyOn(URL, "revokeObjectURL") - try { - for (const limits of [{ maxEntries: 1 }, { maxBytes: 4 }]) { - const cache = createThumbnailCache(async () => thumbnail(), limits) - try { - const first = cache.acquire(file) - const firstImage = await first.ready - const secondFile = { ...file, id: "file:other.png" } - const second = cache.acquire(secondFile) - await second.ready - expect(cache.peek(file)).toBe(firstImage) - first.release() - second.release() - expect(cache.peek(file)).toBeUndefined() - expect(cache.peek(secondFile)).toBeTruthy() - expect(revoke).toHaveBeenCalledWith(firstImage.url) - } finally { cache.dispose() } - } - } finally { revoke.mockRestore() } + for (const limits of [{ maxEntries: 1 }, { maxBytes: 4 }]) { + const cache = fixture(async () => thumbnail(), limits) + const first = cache.acquire(file) + const firstImage = await first.ready + const secondFile = { ...file, id: "file:other.png" } + const second = cache.acquire(secondFile) + await second.ready + expect(cache.peek(file)).toBe(firstImage) + first.release() + second.release() + expect(cache.peek(file)).toBeUndefined() + expect(cache.peek(secondFile)).toBeTruthy() + expect(revoke).toHaveBeenCalledWith(firstImage.url) + } +}) + +test("holds retired URLs until leases release, makes release idempotent, and refuses disposed acquisitions", async () => { + const revoke = spyOn(URL, "revokeObjectURL") + const cache = fixture(async () => thumbnail()) + const first = cache.acquire(file) + const loaded = await first.ready + const changed = cache.acquire({ ...file, version: "2" }) + await changed.ready + expect(cache.peek(file)).toBeUndefined() + expect(revoke).not.toHaveBeenCalledWith(loaded.url) + first.release() + first.release() + expect(revoke.mock.calls.filter(([url]) => url === loaded.url)).toHaveLength(1) + cache.dispose() + expect(() => cache.acquire(file)).toThrow("Thumbnail cache is disposed.") + changed.release() }) test("limits concurrent thumbnail generation", async () => { - const gates = Array.from({ length: 3 }, () => deferred()) + const gates = Array.from({ length: 3 }, () => Promise.withResolvers()) let loads = 0 - const cache = createThumbnailCache(async () => gates[loads++]!.promise, { concurrency: 1 }) - try { - const leases = gates.map((_, index) => cache.acquire({ ...file, id: `file:${index}.png` })) + const cache = fixture(async () => gates[loads++]!.promise, { concurrency: 1 }) + const leases = gates.map((_, index) => cache.acquire({ ...file, id: `file:${index}.png` })) + await tick() + expect(loads).toBe(1) + for (let index = 0; index < gates.length; index++) { + gates[index]!.resolve(thumbnail()) + await leases[index]!.ready + leases[index]!.release() await tick() - expect(loads).toBe(1) - for (let index = 0; index < gates.length; index++) { - gates[index]!.resolve(thumbnail()) - await leases[index]!.ready - leases[index]!.release() - await tick() - expect(loads).toBe(Math.min(index + 2, gates.length)) - } - } finally { cache.dispose() } + expect(loads).toBe(Math.min(index + 2, gates.length)) + } }) test("allows a new request after failure and cancels late work on plugin shutdown", async () => { let loads = 0 - const cache = createThumbnailCache(async () => { + const cache = fixture(async () => { if (++loads === 1) throw new Error("image.decodeError") return thumbnail() }) - try { - const failed = cache.acquire(file) - await expect(failed.ready).rejects.toThrow("image.decodeError") - failed.release() - const requested = cache.acquire(file) - await requested.ready - requested.release() - expect(loads).toBe(2) - } finally { cache.dispose() } + const failed = cache.acquire(file) + const rendered = tile(cache) + rendered.select(undefined) + await expect(failed.ready).rejects.toThrow("image.decodeError") + expect(rendered.image.error).toBe("") + failed.release() + const requested = cache.acquire(file) + await requested.ready + requested.release() + expect(loads).toBe(2) - const pending = deferred() + const pending = Promise.withResolvers() const signal = new AbortController() const create = spyOn(URL, "createObjectURL") - const stopped = createThumbnailCache(async () => pending.promise, { signal: signal.signal }) - try { - const lease = stopped.acquire(file) - const failure = lease.ready.catch((error: unknown) => error) - await tick() - signal.abort() - expect(await failure).toMatchObject({ name: "AbortError" }) - pending.resolve(thumbnail()) - await tick() - expect(create).not.toHaveBeenCalled() - expect(stopped.peek(file)).toBeUndefined() - lease.release() - } finally { stopped.dispose(); create.mockRestore() } + const stopped = fixture(async () => pending.promise, { signal: signal.signal }) + const lease = stopped.acquire(file) + const failure = lease.ready.catch((error: unknown) => error) + await tick() + signal.abort() + expect(await failure).toMatchObject({ name: "AbortError" }) + pending.resolve(thumbnail()) + await tick() + expect(create).not.toHaveBeenCalled() + expect(stopped.peek(file)).toBeUndefined() + lease.release() }) diff --git a/src/thumbnail-cache.ts b/src/thumbnail-cache.ts index a9d52aa..ecd4780 100644 --- a/src/thumbnail-cache.ts +++ b/src/thumbnail-cache.ts @@ -9,13 +9,10 @@ export type ThumbnailCache = ReturnType type Entry = { choice: WallpaperChoice controller: AbortController - ready: Promise - resolve: (thumbnail: Thumbnail) => void - reject: (error: unknown) => void + result: PromiseWithResolvers value?: Thumbnail bytes: number users: number - retired: boolean } export function createThumbnailCache( @@ -26,16 +23,14 @@ export function createThumbnailCache( ) { const entries = new Map() const retired = new Set() - const idle = new Map() + const idle = new Set() const permits = Semaphore.makeUnsafe(concurrency) let idleBytes = 0 let disposed = false function activate(entry: Entry) { - const bytes = idle.get(entry) - if (bytes === undefined) return - idle.delete(entry) - idleBytes -= bytes + if (!idle.delete(entry)) return + idleBytes -= entry.bytes } function revoke(entry: Entry) { @@ -46,20 +41,17 @@ export function createThumbnailCache( } function discard(entry: Entry) { - if (entry.retired) return - activate(entry) + if (entry.controller.signal.aborted) return if (entries.get(entry.choice.id) === entry) entries.delete(entry.choice.id) - entry.retired = true entry.controller.abort() - entry.reject(entry.controller.signal.reason) + entry.result.reject(entry.controller.signal.reason) if (entry.users) retired.add(entry) else revoke(entry) } function park(entry: Entry) { - if (entry.users || entry.retired) return - activate(entry) - idle.set(entry, entry.bytes) + if (entry.users || entry.controller.signal.aborted) return + idle.add(entry) idleBytes += entry.bytes while (idle.size > maxEntries || idleBytes > maxBytes) { const oldest = idle.keys().next().value @@ -75,11 +67,12 @@ export function createThumbnailCache( })), { signal: entry.controller.signal }).then((thumbnail) => { entry.controller.signal.throwIfAborted() entry.value = { url: URL.createObjectURL(thumbnail.blob), width: thumbnail.width, height: thumbnail.height } + activate(entry) entry.bytes = thumbnail.blob.size - entry.resolve(entry.value) + entry.result.resolve(entry.value) park(entry) }).catch((error: unknown) => { - entry.reject(error) + entry.result.reject(error) discard(entry) }) } @@ -92,8 +85,7 @@ export function createThumbnailCache( entry = undefined } if (!entry) { - const { promise: ready, resolve, reject } = Promise.withResolvers() - entry = { choice: { ...choice }, controller: new AbortController(), ready, resolve, reject, users: 0, bytes: 0, retired: false } + entry = { choice: { ...choice }, controller: new AbortController(), result: Promise.withResolvers(), users: 0, bytes: 0 } loadEntry(entry) } const current = entry @@ -103,12 +95,12 @@ export function createThumbnailCache( let released = false return { value: current.value, - ready: current.ready, + ready: current.result.promise, release() { if (released) return released = true current.users-- - if (current.retired && !current.users) revoke(current) + if (current.controller.signal.aborted && !current.users) revoke(current) else park(current) }, } @@ -118,14 +110,10 @@ export function createThumbnailCache( if (disposed) return disposed = true signal?.removeEventListener("abort", dispose) - for (const entry of new Set([...entries.values(), ...retired])) { + for (const entry of [...entries.values(), ...retired]) { discard(entry) revoke(entry) } - entries.clear() - retired.clear() - idle.clear() - idleBytes = 0 } signal?.addEventListener("abort", dispose, { once: true }) if (signal?.aborted) dispose() diff --git a/src/thumbnail.tsx b/src/thumbnail.tsx index afd9b75..1902b1e 100644 --- a/src/thumbnail.tsx +++ b/src/thumbnail.tsx @@ -1,9 +1,8 @@ import { createSignal, onCleanup, onMount, Show } from "solid-js" import { imageError } from "./image" import type { WallpaperChoice } from "./model" -import { createWallpaperThumbnail } from "./render" +import { createWallpaperThumbnail, type WallpaperReader } from "./render" import type { ThumbnailCache } from "./thumbnail-cache" -import type { WallpaperReader } from "./render" import { WallpaperPreview } from "./preview" export function WallpaperThumbnail(props: { choice: WallpaperChoice; cache: ThumbnailCache; t: (key: string) => string; preview?: boolean; read?: WallpaperReader }) {