diff --git a/README.md b/README.md index 7f8f542..4c96ea6 100644 --- a/README.md +++ b/README.md @@ -53,3 +53,13 @@ You can set an initial folder with an absolute path instead of choosing one in S ``` The folder chosen in Settings takes precedence over this option. + +## Development + +```sh +bun run check +bun run test:styles +bun run test:storage /path/to/opencode +``` + +`check` includes native Node filesystem-watcher tests and rebuilds the GUI bundle. `test:styles` runs that bundle's setup, wallpaper switching, stylesheet cleanup, and gallery-toggle checks in headless Chrome; set `CHROME_BIN` if Chrome is installed elsewhere. `test:storage` checks migration against an OpenCode checkout's actual persistence decoder. Pass the checkout path or set `OPENCODE_CHECKOUT`. diff --git a/bun.lock b/bun.lock index 0799a01..674ff44 100644 --- a/bun.lock +++ b/bun.lock @@ -10,6 +10,7 @@ "@types/bun": "1.4.3", "@typescript/native": "npm:typescript@7.1.0-beta", "effect": "4.1.0", + "playwright-core": "1.65.1", "solid-js": "1.9.17", "vite": "7.3.7", "vite-plugin-solid": "2.11.10", @@ -672,6 +673,8 @@ "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + "playwright-core": ["playwright-core@1.65.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw=="], + "postcss": ["postcss@8.5.33", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ=="], "postcss-selector-parser": ["postcss-selector-parser@7.2.1", "", { "dependencies": { "util-deprecate": "^1.0.2" } }, "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ=="], diff --git a/dist/gui-experimental.cjs b/dist/gui-experimental.cjs index 0334cf6..f974c7d 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 a=require("solid-js/web"),O=require("@opencode/plugin/gui"),w=require("solid-js"),m=require("effect"),se=require("solid-js/store"),N=require("node:fs/promises"),j=require("node:path"),ve=require("node:os"),D=8*1024*1024,ye=m.Schema.Struct({id:m.Schema.String,title:m.Schema.String,version:m.Schema.String}),Se=m.Schema.Struct({id:m.Schema.String,version:m.Schema.String}),ne=O.Ipc.define({id:"wallpaper.catalog.v5",state:m.Schema.Struct({folder:m.Schema.String,folderLabel:m.Schema.optional(m.Schema.String),ready:m.Schema.Boolean,images:m.Schema.Array(ye),error:m.Schema.String}),methods:{refresh:{output:m.Schema.Boolean},setFolder:{input:m.Schema.NonEmptyString,output:m.Schema.Boolean},read:{input:Se,output:m.Schema.String}}}),ke=/^[A-Za-z0-9+/]+={0,2}$/,xe=new Set(["image/png","image/jpeg","image/webp"]),ce=m.Schema.String.check(m.Schema.isPattern(/^(?:data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2})?$/),m.Schema.isMaxLength(23+4*Math.ceil(D/3)),m.Schema.makeFilter(e=>{const t=Q(e);return!e||t.length%4===0&&pe(t)<=D}));function $e(e){if(!xe.has(e.type))throw new Error("image.typeError");if(e.size===0||e.size>D)throw new Error("image.sizeError")}function de(e){const t=/^data:(image\/(?:png|jpeg|webp|svg\+xml))(;base64)?,([\s\S]+)$/.exec(e);if(!t)throw new Error("image.decodeError");const[,o,c,r]=t;if(c&&(r.length%4!==0||pe(r)>D||!ke.test(r)))throw new Error("image.decodeError");if(!c&&o!=="image/svg+xml")throw new Error("image.decodeError");try{const n=new Blob([c?Uint8Array.from(atob(r),l=>l.charCodeAt(0)):decodeURIComponent(r)],{type:o});if(n.size===0||n.size>D)throw new Error("image.decodeError");return n}catch(n){throw new Error("image.decodeError",{cause:n})}}async function Y(e,t){t.throwIfAborted();const o=new Image,c=()=>{o.src=""};t.addEventListener("abort",c,{once:!0});try{return o.src=e,await o.decode(),t.throwIfAborted(),o}catch(r){throw t.throwIfAborted(),new Error("image.decodeError",{cause:r})}finally{t.removeEventListener("abort",c)}}async function Ce(e,t){t.throwIfAborted();const o=URL.createObjectURL(de(e));try{const c=await Y(o,t),r=document.createElement("canvas"),n=Math.min(1,320/c.naturalWidth,200/c.naturalHeight);r.width=Math.max(1,Math.round(c.naturalWidth*n)),r.height=Math.max(1,Math.round(c.naturalHeight*n));const l=r.getContext("2d");if(!l)throw new Error("image.decodeError");l.drawImage(c,0,0,r.width,r.height);const p=await new Promise((d,b)=>{r.toBlob(C=>C?d(C):b(new Error("image.decodeError")),"image/png")});return t.throwIfAborted(),{blob:p,width:r.width,height:r.height}}finally{URL.revokeObjectURL(o)}}async function Ee(e,t){t.throwIfAborted(),$e(e);const o=URL.createObjectURL(e);try{await Y(o,t)}finally{URL.revokeObjectURL(o)}return t.throwIfAborted(),new Promise((c,r)=>{const n=new FileReader,l=()=>n.abort(),p=()=>t.removeEventListener("abort",l);n.onload=()=>{p(),typeof n.result!="string"?r(new Error("image.readError")):c(n.result)},n.onerror=()=>{p(),r(new Error("image.readError"))},n.onabort=()=>{p(),r(t.reason)},t.addEventListener("abort",l,{once:!0});try{n.readAsDataURL(e)}catch(d){p(),r(new Error("image.readError",{cause:d}))}})}function Z(e,t){return e.startsWith("image.")?t(e):`${t("image.readError")} ${e}`}function Q(e){return e.slice(e.indexOf(",")+1)}function pe(e){return e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}const B={tint:{min:0,max:100,initial:80},brightness:{min:25,max:150,initial:100}},ue=["tint","brightness"],P={min:5,max:86400,duration:60,transition:"fade"},Ae=800,Le=m.Schema.Struct({id:m.Schema.String.check(m.Schema.isPattern(/^upload:.+$/)),name:m.Schema.String.check(m.Schema.isMinLength(1)),image:ce.check(m.Schema.isMinLength(1))}),Re=m.Schema.Struct({enabled:m.Schema.Boolean,preset:m.Schema.String,image:ce,imageName:m.Schema.optional(m.Schema.String),images:m.Schema.optional(m.Schema.Array(Le)),tint:m.Schema.optional(m.Schema.Int.check(m.Schema.isBetween({minimum:B.tint.min,maximum:B.tint.max}))),brightness:m.Schema.optional(m.Schema.Int.check(m.Schema.isBetween({minimum:B.brightness.min,maximum:B.brightness.max}))),fit:m.Schema.Literals(["cover","contain"]),slideshow:m.Schema.optional(m.Schema.Boolean),duration:m.Schema.optional(m.Schema.Int.check(m.Schema.isBetween({minimum:P.min,maximum:P.max}))),transition:m.Schema.optional(m.Schema.Literals(["none","fade"])),strength:m.Schema.Int.check(m.Schema.isBetween({minimum:5,maximum:45})),hidden:m.Schema.optional(m.Schema.Array(m.Schema.String))}),ee={enabled:!1,preset:"",image:"",strength:100-B.tint.initial,fit:"cover"};function ge(e){return{tint:e.tint??100-e.strength,brightness:e.brightness??B.brightness.initial}}function K(e,t){return e?.id===t?.id&&e?.version===t?.version&&e?.image===t?.image}function X(e,t){return t.find(o=>o.id===e.preset)}function he(e){const t=e.images??[];return e.image?[{id:"custom",name:e.imageName??"",image:e.image},...t]:t}function Ie(e=[],t=ee,o=[]){const c=new Map(o.map(r=>[r.id,r]));return[...e,...he(t).map(r=>{const n=me(r.name),l=c.get(r.id);return l?.image===r.image&&l.title===n?l:{id:r.id,title:n,version:"custom",image:r.image}})]}function te(e){return e.id==="custom"||e.id.startsWith("upload:")}function Me(e,t,o){if(!te(t)||(t.id==="custom"?(e.image="",delete e.imageName):e.images=e.images?.filter(r=>r.id!==t.id),e.preset!==t.id))return;const c=o[o.findIndex(r=>r.id===t.id)+1]??o.find(r=>r.id!==t.id);e.preset=c?.id??ee.preset,c||(e.enabled=!1)}function ae(e,t){e.enabled=t!=="off",t!=="off"&&(e.preset=t)}function We(e,t,o){ae(e,t?X(e,o)?.id??o[0]?.id??"off":"off")}function V(e,t){return te(e)?e.title||t("image.custom"):e.title}function ie(e,t,o){const c=G(e.name),r=Q(e.image??"");for(const n of he(t)){if(n.name&&G(n.name)===c)throw new Error("image.duplicateName");if(r&&r===Q(n.image))throw new Error("image.duplicateImage")}for(const n of o){const l=ze(n.id);if(l&&G(l)===c)throw new Error("image.duplicateName")}}function ze(e){if(!e.startsWith("file:"))return"";const t=e.slice(5);try{return decodeURIComponent(t)}catch{return t}}function G(e){return me(e).normalize("NFC").toLowerCase()}function me(e){const t=(e.split(/[\\/]/).at(-1)??e).trim();return t.replace(/\.(?:png|jpe?g|webp|svg)$/i,"")||t}function _e(e,t,o,c,r,n){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 o(),!e.signal.aborted&&n({title:e.t("picker.title"),placeholder:e.t("picker.search"),current:c(),options:t().map(l=>({title:V(l,e.t),value:l.id}))},l=>{if(!e.signal.aborted){if(l==="settings"){e.layout.settings("wallpaper");return}r(l)}}))}}}function fe(e){return w.createMemo(()=>{const t=e();return t?{...t}:void 0},void 0,{equals:K})}function Ue(e,t,o=()=>0){const[c,r]=se.createStore({url:"",width:0,height:0,loading:!1,error:"",previous:void 0,transition:0});let n,l,p;const d=()=>{clearTimeout(p),p=void 0,l&&URL.revokeObjectURL(l.url),l=void 0,r({previous:void 0,transition:0})};w.onCleanup(()=>{d(),n&&URL.revokeObjectURL(n.url)});const b=fe(e);return w.createEffect(()=>{const C=b(),L=new AbortController;let h="";if(w.onCleanup(()=>{L.abort(),h&&URL.revokeObjectURL(h),h=""}),r({loading:!!C,error:""}),!C){d(),n&&URL.revokeObjectURL(n.url),n=void 0,r({url:"",width:0,height:0});return}(async()=>{try{const u=C.image??await t(C,L.signal);L.signal.throwIfAborted(),h=URL.createObjectURL(de(u));const g=await Y(h,L.signal);L.signal.throwIfAborted(),d();const E=w.untrack(o);n&&E>0?l=n:n&&URL.revokeObjectURL(n.url),n={url:h,width:g.naturalWidth,height:g.naturalHeight},h="",r({...n,previous:l,transition:l?E:0,loading:!1,error:""}),l&&(p=setTimeout(d,E))}catch(u){h&&URL.revokeObjectURL(h),h="",L.signal.aborted||r({loading:!1,error:u instanceof Error?u.message:String(u)})}})()}),c}function je(e,t){const[o,c]=se.createStore({url:"",width:0,height:0,loading:!1,error:""}),r=fe(e);return w.createRenderEffect(()=>{const n=r(),l=new AbortController;let p;if(w.onCleanup(()=>{l.abort(),p?.release()}),c({url:"",width:0,height:0,loading:!!n,error:""}),!!n)try{if(p=t.acquire(n),p.value){c({...p.value,loading:!1});return}p.ready.then(d=>{l.signal.aborted||c({...d,loading:!1})},d=>{l.signal.aborted||c({loading:!1,error:d instanceof Error?d.message:String(d)})})}catch(d){c({loading:!1,error:d instanceof Error?d.message:String(d)})}}),o}function Pe(e){const t=new Map;return(o,c,r)=>{const n=t.get(o)??new Set,l=r.filter(p=>!p||n.has(p)?!1:(n.add(p),!0));t.set(o,n),l.length&&e.show({variant:"error",icon:"outline-photo",title:c,description:l.join(` +"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const n=require("solid-js/web"),O=require("@opencode/plugin/gui"),h=require("solid-js"),p=require("effect"),de=require("solid-js/store"),ie=require("node:fs"),N=require("node:fs/promises"),_=require("node:path"),Se=require("node:os"),G=8*1024*1024,ke=p.Schema.Struct({id:p.Schema.String,title:p.Schema.String,version:p.Schema.String}),xe=p.Schema.Struct({id:p.Schema.String,version:p.Schema.String}),le=O.Ipc.define({id:"wallpaper.catalog.v5",state:p.Schema.Struct({folder:p.Schema.String,folderLabel:p.Schema.optional(p.Schema.String),ready:p.Schema.Boolean,images:p.Schema.Array(ke),error:p.Schema.String}),methods:{refresh:{output:p.Schema.Boolean},setFolder:{input:p.Schema.NonEmptyString,output:p.Schema.Boolean},read:{input:xe,output:p.Schema.String}}}),$e=/^[A-Za-z0-9+/]+={0,2}$/,Ee=new Set(["image/png","image/jpeg","image/webp"]),pe=p.Schema.String.check(p.Schema.isPattern(/^(?:data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2})?$/),p.Schema.isMaxLength(23+4*Math.ceil(G/3)),p.Schema.makeFilter(e=>{const t=X(e);return!e||t.length%4===0&&ge(t)<=G}));function Ce(e){if(!Ee.has(e.type))throw new Error("image.typeError");if(e.size===0||e.size>G)throw new Error("image.sizeError")}function ue(e){const t=/^data:(image\/(?:png|jpeg|webp|svg\+xml))(;base64)?,([\s\S]+)$/.exec(e);if(!t)throw new Error("image.decodeError");const[,a,i,r]=t;if(i&&(r.length%4!==0||ge(r)>G||!$e.test(r)))throw new Error("image.decodeError");if(!i&&a!=="image/svg+xml")throw new Error("image.decodeError");try{const l=new Blob([i?Uint8Array.from(atob(r),d=>d.charCodeAt(0)):decodeURIComponent(r)],{type:a});if(l.size===0||l.size>G)throw new Error("image.decodeError");return l}catch(l){throw new Error("image.decodeError",{cause:l})}}async function ee(e,t){t.throwIfAborted();const a=new Image,i=()=>{a.src=""};t.addEventListener("abort",i,{once:!0});try{return a.src=e,await a.decode(),t.throwIfAborted(),a}catch(r){throw t.throwIfAborted(),new Error("image.decodeError",{cause:r})}finally{t.removeEventListener("abort",i)}}async function Ae(e,t){t.throwIfAborted();const a=URL.createObjectURL(ue(e));try{const i=await ee(a,t),r=document.createElement("canvas"),l=Math.min(1,320/i.naturalWidth,200/i.naturalHeight);r.width=Math.max(1,Math.round(i.naturalWidth*l)),r.height=Math.max(1,Math.round(i.naturalHeight*l));const d=r.getContext("2d");if(!d)throw new Error("image.decodeError");d.drawImage(i,0,0,r.width,r.height);const g=await new Promise((c,b)=>{r.toBlob(f=>f?c(f):b(new Error("image.decodeError")),"image/png")});return t.throwIfAborted(),{blob:g,width:r.width,height:r.height}}finally{URL.revokeObjectURL(a)}}async function Le(e,t){t.throwIfAborted(),Ce(e);const a=URL.createObjectURL(e);try{await ee(a,t)}finally{URL.revokeObjectURL(a)}return t.throwIfAborted(),new Promise((i,r)=>{const l=new FileReader,d=()=>l.abort(),g=()=>t.removeEventListener("abort",d);l.onload=()=>{g(),typeof l.result!="string"?r(new Error("image.readError")):i(l.result)},l.onerror=()=>{g(),r(new Error("image.readError"))},l.onabort=()=>{g(),r(t.reason)},t.addEventListener("abort",d,{once:!0});try{l.readAsDataURL(e)}catch(c){g(),r(new Error("image.readError",{cause:c}))}})}function Q(e,t){return e.startsWith("image.")?t(e):`${t("image.readError")} ${e}`}function X(e){return e.slice(e.indexOf(",")+1)}function ge(e){return e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}const P={tint:{min:0,max:100,initial:80},brightness:{min:25,max:150,initial:100}},me=["tint","brightness"],j={min:5,max:86400,duration:60,transition:"fade"},he=800,Re=p.Schema.Struct({id:p.Schema.String.check(p.Schema.isPattern(/^(?:custom|upload:.+)$/)),name:p.Schema.String.check(p.Schema.isMinLength(1)),image:pe.check(p.Schema.isMinLength(1))}),U={enabled:p.Schema.Boolean,preset:p.Schema.String,images:p.Schema.Array(Re).check(p.Schema.makeFilter(e=>new Set(e.map(t=>t.id)).size===e.length)),tint:p.Schema.Int.check(p.Schema.isBetween({minimum:P.tint.min,maximum:P.tint.max})),brightness:p.Schema.Int.check(p.Schema.isBetween({minimum:P.brightness.min,maximum:P.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"])},z=p.Schema.Struct({...U,images:p.Schema.optional(U.images),tint:p.Schema.optional(U.tint),brightness:p.Schema.optional(U.brightness),slideshow:p.Schema.optional(U.slideshow),duration:p.Schema.optional(U.duration),transition:p.Schema.optional(U.transition),image:p.Schema.optional(pe),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))}),Me=z.pipe(p.Schema.decodeTo(p.Schema.Struct(U),{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?P.tint.initial:100-e.strength),brightness:e.brightness??P.brightness.initial,slideshow:e.slideshow??!1,duration:e.duration??j.duration,transition:e.transition??j.transition})),encode:p.SchemaGetter.transform(e=>e)})),D={enabled:!1,preset:"",images:[],tint:P.tint.initial,brightness:P.brightness.initial,fit:"cover",slideshow:!1,duration:j.duration,transition:j.transition};function T(e,t){return p.Schema.withDecodingDefaultType(p.Effect.succeed(t))(e).pipe(p.Schema.catchDecoding(()=>p.Effect.succeed(p.Option.some(t))))}const Ie=p.Schema.Struct({enabled:T(U.enabled,D.enabled),preset:T(U.preset,D.preset),fit:T(U.fit,D.fit),images:T(z.fields.images,void 0),tint:T(z.fields.tint,void 0),brightness:T(z.fields.brightness,void 0),slideshow:T(z.fields.slideshow,void 0),duration:T(z.fields.duration,void 0),transition:T(z.fields.transition,void 0),image:T(z.fields.image,void 0),imageName:T(z.fields.imageName,void 0),strength:T(z.fields.strength,void 0)}).pipe(p.Schema.decodeTo(Me));function fe(e){return{tint:e.tint,brightness:e.brightness}}function V(e,t){return e?.id===t?.id&&e?.version===t?.version&&e?.image===t?.image}function Y(e,t){return t.find(a=>a.id===e.preset)}function be(e){return e.images}function We(e=[],t=D,a=[]){const i=new Map(a.map(r=>[r.id,r]));return[...e,...be(t).map(r=>{const l=we(r.name),d=i.get(r.id);return d?.image===r.image&&d.title===l?d:{id:r.id,title:l,version:"custom",image:r.image}})]}function te(e){return e.id==="custom"||e.id.startsWith("upload:")}function _e(e,t,a){if(!te(t)||(e.images=e.images.filter(r=>r.id!==t.id),e.preset!==t.id))return;const i=a[a.findIndex(r=>r.id===t.id)+1]??a.find(r=>r.id!==t.id);e.preset=i?.id??D.preset,i||(e.enabled=!1)}function re(e,t){e.enabled=t!=="off",t!=="off"&&(e.preset=t)}function Te(e,t,a){re(e,t?Y(e,a)?.id??a[0]?.id??"off":"off")}function H(e,t){return te(e)?e.title||t("image.custom"):e.title}function se(e,t,a){const i=K(e.name),r=X(e.image??"");for(const l of be(t)){if(l.name&&K(l.name)===i)throw new Error("image.duplicateName");if(r&&r===X(l.image))throw new Error("image.duplicateImage")}for(const l of a){const d=Ue(l.id);if(d&&K(d)===i)throw new Error("image.duplicateName")}}function Ue(e){if(!e.startsWith("file:"))return"";const t=e.slice(5);return decodeURIComponent(t)}function K(e){return we(e).normalize("NFC").toLowerCase()}function we(e){const t=(e.split(/[\\/]/).at(-1)??e).trim();return t.replace(/\.(?:png|jpe?g|webp|svg)$/i,"")||t}function ze(e,t,a,i,r,l){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 a(),!e.signal.aborted&&l({title:e.t("picker.title"),placeholder:e.t("picker.search"),current:i(),options:t().map(d=>({title:H(d,e.t),value:d.id}))},d=>{if(!e.signal.aborted){if(d==="settings"){e.layout.settings("wallpaper");return}r(d)}}))}}}function ve(e){return h.createMemo(()=>{const t=e();return t?{...t}:void 0},void 0,{equals:V})}function Pe(e,t,a){const[i,r]=h.createSignal(e()),[l,d]=h.createSignal();let g;const c=()=>{clearTimeout(g),g=void 0},b=f=>{c();const C=t()&&!a()?he:0;h.batch(()=>{d(C?{show:f,duration:C}:void 0),!C&&!f&&r(!1)}),C&&(g=setTimeout(()=>{g=void 0,h.batch(()=>{d(void 0),f||r(!1)})},C))};return h.createEffect(h.on(()=>[e(),a()],([f,C])=>{if(c(),!f)return b(!1);r(!0),C&&d(void 0)})),h.createEffect(h.on(()=>e()&&t(),(f,C)=>{f&&!C&&b(!0)})),h.onCleanup(c),{enabled:i,fade:l}}function je(e,t,a=()=>0){const[i,r]=de.createStore({url:"",width:0,height:0,loading:!1,error:"",choice:void 0,previous:void 0,transition:0});let l;const d=()=>{clearTimeout(l),l=void 0,i.previous&&URL.revokeObjectURL(i.previous.url),r({previous:void 0,transition:0})};h.onCleanup(()=>{d(),i.url&&URL.revokeObjectURL(i.url)});const g=ve(e);return h.createEffect(h.on(g,c=>{const b=new AbortController;let f="";if(h.onCleanup(()=>{b.abort(),f&&URL.revokeObjectURL(f),f=""}),r({loading:!!c,error:""}),!c){d(),i.url&&URL.revokeObjectURL(i.url),r({url:"",width:0,height:0,choice:void 0});return}if(i.url&&V(c,i.choice)){r({loading:!1});return}(async()=>{try{const C=c.image??await t(c,b.signal);b.signal.throwIfAborted(),f=URL.createObjectURL(ue(C));const y=await ee(f,b.signal);b.signal.throwIfAborted(),d();const $=h.untrack(a),L=i.url&&$>0?{url:i.url,width:i.width,height:i.height}:void 0;i.url&&!L&&URL.revokeObjectURL(i.url);const I={url:f,width:y.naturalWidth,height:y.naturalHeight};f="",r({...I,choice:c,previous:L,transition:L?$:0,loading:!1,error:""}),L&&(l=setTimeout(d,$))}catch(C){f&&URL.revokeObjectURL(f),f="",b.signal.aborted||r({loading:!1,error:C instanceof Error?C.message:String(C)})}})()})),i}function Fe(e,t){const[a,i]=de.createStore({url:"",width:0,height:0,loading:!1,error:""}),r=ve(e);return h.createRenderEffect(()=>{const l=r(),d=new AbortController;let g;if(h.onCleanup(()=>{d.abort(),g?.release()}),i({url:"",width:0,height:0,loading:!!l,error:""}),!!l)try{if(g=t.acquire(l),g.value){i({...g.value,loading:!1});return}g.ready.then(c=>{d.signal.aborted||i({...c,loading:!1})},c=>{d.signal.aborted||i({loading:!1,error:c instanceof Error?c.message:String(c)})})}catch(c){i({loading:!1,error:c instanceof Error?c.message:String(c)})}}),a}function Be(e){const t=new Map;return Object.assign((i,r,l)=>{const d=t.get(i)??new Set,g=new Set(l.filter(Boolean)),c=[...g].filter(b=>!d.has(b));g.size?t.set(i,g):t.delete(i),c.length&&e.show({variant:"error",icon:"outline-photo",title:r,description:c.join(` -`)})}}function Te(e,{maxEntries:t=48,maxBytes:o=8*1024*1024,concurrency:c=2,signal:r}={}){const n=new Map,l=new Set,p=new Map,d=new Set;let b=0,C=0,L=!1;function h(i){const s=p.get(i);s!==void 0&&(p.delete(i),b-=s)}function u(i){h(i),i.value&&URL.revokeObjectURL(i.value.url),i.value=void 0,l.delete(i)}function g(i){i.retired||(h(i),d.delete(i),n.get(i.choice.id)===i&&n.delete(i.choice.id),i.retired=!0,i.controller.abort(),i.reject(i.controller.signal.reason),i.users?l.add(i):u(i))}function E(i){if(!(i.users||i.retired))for(h(i),p.set(i,i.bytes),b+=i.bytes;p.size>t||b>o;){const s=p.keys().next().value;if(!s)break;g(s)}}function S(){for(;!L&&C(i.controller.signal.throwIfAborted(),e(i.choice,i.controller.signal))).then(s=>{i.controller.signal.throwIfAborted(),i.value={url:URL.createObjectURL(s.blob),width:s.width,height:s.height},i.bytes=s.blob.size,i.resolve(i.value),E(i)}).catch(s=>{i.reject(s),g(i)}).finally(()=>{C--,S()})}}function f(i){if(L)throw new DOMException("Thumbnail cache is disposed.","AbortError");let s=n.get(i.id);if(s&&!K(s.choice,i)&&(g(s),s=void 0),!s){let _,z;const k=new Promise((x,v)=>{_=x,z=v});s={choice:{...i},controller:new AbortController,ready:k,resolve:_,reject:z,users:0,bytes:0,retired:!1},d.add(s)}const y=s;h(y),y.users++,n.set(i.id,y),S();let W=!1;return{value:y.value,ready:y.ready,release(){W||(W=!0,y.users--,y.retired&&!y.users?u(y):E(y))}}}function $(){if(!L){L=!0,r?.removeEventListener("abort",$);for(const i of new Set([...n.values(),...l]))g(i),u(i);n.clear(),l.clear(),p.clear(),b=0,d.clear()}}return r?.addEventListener("abort",$,{once:!0}),r?.aborted&&$(),{acquire:f,peek(i){const s=n.get(i.id);return s&&K(s.choice,i)?s.value:void 0},retain(i){const s=new Map(i.map(y=>[y.id,y]));for(const y of n.values())K(y.choice,s.get(y.choice.id))||g(y)},dispose:$}}const T='[data-slot="home-panel"], [data-slot="session-chat-panel"] > .bg-v2-background-bg-base, [data-component="new-session"]',we=` +`)})},{retain(i){const r=new Set(i);for(const l of t.keys())r.has(l)||t.delete(l)}})}function Oe(e,{maxEntries:t=48,maxBytes:a=8*1024*1024,concurrency:i=2,signal:r}={}){const l=new Map,d=new Set,g=new Map,c=p.Semaphore.makeUnsafe(i);let b=0,f=!1;function C(s){const w=g.get(s);w!==void 0&&(g.delete(s),b-=w)}function y(s){C(s),s.value&&URL.revokeObjectURL(s.value.url),s.value=void 0,d.delete(s)}function $(s){s.retired||(C(s),l.get(s.choice.id)===s&&l.delete(s.choice.id),s.retired=!0,s.controller.abort(),s.reject(s.controller.signal.reason),s.users?d.add(s):y(s))}function L(s){if(!(s.users||s.retired))for(C(s),g.set(s,s.bytes),b+=s.bytes;g.size>t||b>a;){const w=g.keys().next().value;if(!w)break;$(w)}}function I(s){p.Effect.runPromise(c.withPermit(p.Effect.tryPromise({try:w=>e(s.choice,w),catch:w=>w})),{signal:s.controller.signal}).then(w=>{s.controller.signal.throwIfAborted(),s.value={url:URL.createObjectURL(w.blob),width:w.width,height:w.height},s.bytes=w.blob.size,s.resolve(s.value),L(s)}).catch(w=>{s.reject(w),$(s)})}function x(s){if(f)throw new DOMException("Thumbnail cache is disposed.","AbortError");let w=l.get(s.id);if(w&&!V(w.choice,s)&&($(w),w=void 0),!w){const{promise:o,resolve:m,reject:u}=Promise.withResolvers();w={choice:{...s},controller:new AbortController,ready:o,resolve:m,reject:u,users:0,bytes:0,retired:!1},I(w)}const A=w;C(A),A.users++,l.set(s.id,A);let v=!1;return{value:A.value,ready:A.ready,release(){v||(v=!0,A.users--,A.retired&&!A.users?y(A):L(A))}}}function E(){if(!f){f=!0,r?.removeEventListener("abort",E);for(const s of new Set([...l.values(),...d]))$(s),y(s);l.clear(),d.clear(),g.clear(),b=0}}return r?.addEventListener("abort",E,{once:!0}),r?.aborted&&E(),{acquire:x,peek(s){const w=l.get(s.id);return w&&V(w.choice,s)?w.value:void 0},retain(s){const w=new Map(s.map(A=>[A.id,A]));for(const A of l.values())V(A.choice,w.get(A.choice.id))||$(A)},dispose:E}}function qe(e,t){const a=document.createElement("style"),i=document.createElement("style"),r=document.createElement("style");return a.dataset.wallpaperStyle="settings",i.dataset.wallpaperStyle="canvas",r.dataset.wallpaperStyle="image",a.textContent=e,i.textContent=t,i.disabled=!0,document.head.append(a,i,r),{update(l){r.textContent=l,i.disabled=!l},dispose(){a.remove(),i.remove(),r.remove()}}}const F='[data-slot="home-panel"], [data-slot="session-chat-panel"] > .bg-v2-background-bg-base, [data-component="new-session"]',ae=` [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 Oe(e){const t=`:is(${e})`;return` +`;function Ne(e){const t=`:is(${e})`;return` ${t}::before, ${t}::after { content: ""; @@ -34,17 +34,17 @@ z-index: -99; background: var(--wallpaper-tint, transparent); } - `}const Be=` - :is(${T}) { + `}const De=` + :is(${F}) { 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(${T}) [data-wallpaper-backed] { + :is(${F}) [data-wallpaper-backed] { isolation: isolate; - background: transparent; + background: var(--v2-background-bg-base); } [data-slot="session-chat-panel"] [data-session-title] > .bg-v2-background-bg-base, @@ -52,8 +52,6 @@ position: relative; } - /* Old page-colored fades would leave bands over the image. The aligned header - copies conceal scrolling content without blurring or repainting a solid strip. */ [data-slot="session-chat-panel"] .session-header-fade { background: none; } @@ -95,9 +93,6 @@ color: var(--v2-text-text-base); } - /* Counter-shadow paths fill the lower interiors of the letters. Keep those - transparent instead of turning them into gray rectangles. Only the inner - paint group changes; outer groups still control the lodger's animations. */ [data-component="new-session"] [data-component="new-session-wordmark"] { --icon-base: var(--v2-text-text-base); --icon-strong-base: var(--v2-text-text-base); @@ -109,8 +104,6 @@ filter: drop-shadow(0 1px 2px var(--v2-background-bg-base)); } - /* The game's back pins and paddle use z-index -10 and -5. Keep the wallpaper - below them, and outline only the moving shapes rather than shading the arena. */ [data-component="new-session"] :is([data-slot="new-session-pins"], [data-slot="new-session-pins-popped"]) { filter: drop-shadow(0 1px 2px var(--v2-background-bg-base)); } @@ -122,10 +115,10 @@ [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); } -`,Fe=Be+Oe(`${T}, :is(${T}) [data-wallpaper-backed]`);function qe(e,t){const o=e.enabled&&!!t,{tint:c,brightness:r}=ge(e);return{"--wallpaper-image":o?`url(${JSON.stringify(t)})`:"none","--wallpaper-fit":e.fit,"--wallpaper-tint":o?`color-mix(in srgb, var(--v2-background-bg-base) ${c}%, transparent)`:"transparent","--wallpaper-filter":o?`brightness(${r}%) contrast(85%) saturate(90%)`:"none"}}function Ne(e,t){if(!e.enabled||!t)return"";const o=Object.entries(qe(e,t)).map(([c,r])=>`${c}: ${r};`).join(` - `);return`${T} { - ${o} -}`}function be(e,t,o,c){const r=Math[c==="cover"?"max":"min"](e.width/o.width,e.height/o.height),n=o.width*r,l=o.height*r,p=(e.width-n)/2-(t.left-e.left),d=(e.height-l)/2-(t.top-e.top),b=C=>`${Math.round(C*1e3)/1e3}px`;return{"--wallpaper-background-size":`${b(n)} ${b(l)}`,"--wallpaper-background-position":`${b(p)} ${b(d)}`}}function De(e){if(!(e.image.width>0&&e.image.height>0))return()=>{};const t=new Map,o=new Set;let c=0,r=!1,n=!0,l=[];const p=(h,u)=>{u.attribute===null?h.removeAttribute("data-wallpaper-backed"):h.setAttribute("data-wallpaper-backed",u.attribute);for(const[g,E]of u.properties)E.value?h.style.setProperty(g,E.value,E.priority):h.style.removeProperty(g)},d=()=>{!r&&!c&&(c=requestAnimationFrame(C))},b=new ResizeObserver(d);function C(){if(c=0,r)return;n&&(l=[...document.querySelectorAll(we)],n=!1);const h=new Set,u=new Set,g=new Map,E=[];for(const S of l){const f=S.closest(T);if(!f)continue;const $=S.getBoundingClientRect(),i=g.get(f)??f.getBoundingClientRect();g.set(f,i),!(!$.width||!$.height||!i.width||!i.height)&&(h.add(S),u.add(f),u.add(S),E.push({element:S,geometry:be(i,$,e.image,e.fit)}))}for(const[S,f]of t)h.has(S)||(p(S,f),t.delete(S));for(const{element:S,geometry:f}of E){t.has(S)||t.set(S,{attribute:S.getAttribute("data-wallpaper-backed"),properties:new Map(Object.keys(f).map($=>[$,{value:S.style.getPropertyValue($),priority:S.style.getPropertyPriority($)}]))});for(const[$,i]of Object.entries(f))S.style.getPropertyValue($)!==i&&S.style.setProperty($,i);S.hasAttribute("data-wallpaper-backed")||S.setAttribute("data-wallpaper-backed","")}for(const S of o)u.has(S)||(b.unobserve(S),o.delete(S));for(const S of u)o.has(S)||(b.observe(S),o.add(S))}const L=new MutationObserver(()=>{n=!0,d()});return L.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["aria-expanded","data-locked","class"]}),document.addEventListener("scroll",d,{capture:!0,passive:!0}),window.addEventListener("resize",d,{passive:!0}),d(),()=>{if(!r){r=!0,cancelAnimationFrame(c),L.disconnect(),b.disconnect(),document.removeEventListener("scroll",d,!0),window.removeEventListener("resize",d);for(const[h,u]of t)p(h,u);t.clear(),o.clear(),l=[]}}}var Ve=a.template(""),Ke=a.template(""),Ge=a.template("");function He(e){const[t,o]=w.createSignal(!!e.cache.peek(e.choice));let c;w.onMount(()=>{const n=new IntersectionObserver(l=>{o(l.some(p=>p.isIntersecting))},{rootMargin:"200px"});n.observe(c),w.onCleanup(()=>n.disconnect())});const r=je(()=>t()?e.choice:void 0,e.cache);return(()=>{var n=Ve(),l=c;return typeof l=="function"?a.use(l,n):c=n,a.insert(n,a.createComponent(w.Show,{get when(){return r.url},get fallback(){return a.createComponent(w.Show,{get when(){return r.error},get children(){var p=Ke();return a.insert(p,()=>e.t("image.unavailable")),a.effect(d=>{var b=Z(r.error,e.t),C=Z(r.error,e.t);return b!==d.e&&a.setAttribute(p,"title",d.e=b),C!==d.t&&a.setAttribute(p,"aria-label",d.t=C),d},{e:void 0,t:void 0}),p}})},children:p=>(()=>{var d=Ge();return a.effect(()=>a.setAttribute(d,"src",p())),d})()})),a.effect(()=>a.setAttribute(n,"aria-busy",r.loading)),n})()}var Je=a.template(" + + + +
+ +
+ + `) + const configured = process.env.CHROME_BIN ?? (process.platform === "darwin" ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" : "chromium") + const chrome = path.isAbsolute(configured) ? configured : Bun.which(configured) + assert(chrome, "Set CHROME_BIN to an installed Chrome or Chromium executable.") + const browser = await chromium.launchPersistentContext(path.join(directory, "profile"), { + executablePath: chrome, + headless: true, + chromiumSandbox: true, + }) + try { + const page = await browser.newPage() + await page.goto(pathToFileURL(html).href) + await page.waitForFunction(() => document.body.hasAttribute("data-result"), undefined, { timeout: 10000 }) + 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 } + assert(report.pass, report.message ?? "Rendered stylesheet check failed") + } finally { + await browser.close() + } + console.log("Browser checks passed: built GUI setup, image reads, wallpaper switching, on/off, gallery layout, disclosure accessibility, and cleanup.") +} finally { + await rm(directory, { recursive: true, force: true }) +} diff --git a/src/catalog.test.ts b/src/catalog.test.ts index 02e6e5e..1ba23c2 100644 --- a/src/catalog.test.ts +++ b/src/catalog.test.ts @@ -1,4 +1,5 @@ -import { afterEach, expect, jest, test } from "bun:test" +import { afterEach, expect, jest, spyOn, test } from "bun:test" +import * as fs from "node:fs" import { mkdir, mkdtemp, realpath, rm, symlink, truncate } from "node:fs/promises" import os from "node:os" import path from "node:path" @@ -25,6 +26,7 @@ test("discovers nested additions without reading or publishing full image conten await catalog.refresh() expect(catalog.state().ready).toBe(true) expect(catalog.state().images).toEqual([]) + expect(catalog.state().error).toContain("ENOENT") await mkdir(path.join(folder, "nested"), { recursive: true }) await mkdir(path.join(directory, "wallpapers")) await Bun.write(path.join(folder, "nested", "ocean.SVG"), svg) @@ -107,8 +109,7 @@ test("keeps files with the same stem and different extensions distinct", async ( expect(images.map((image) => image.id).sort()).toEqual(["png", "svg"].map((extension) => `file:${encodeURIComponent(path.join(directory, `example.${extension}`))}`)) }) -test("refreshes from the timer without a manual refresh", async () => { - jest.useFakeTimers() +test("refreshes from filesystem events without polling or a manual refresh", async () => { const directory = await fixture() const updated = Promise.withResolvers() const catalog = createCatalog(directory, () => { @@ -117,18 +118,108 @@ test("refreshes from the timer without a manual refresh", async () => { catalogs.push(catalog) await catalog.refresh() await Bun.write(path.join(directory, "new.svg"), svg) - jest.advanceTimersByTime(2000) await updated.promise expect(catalog.state().images.map((image) => image.title)).toEqual(["new"]) }) -test("removes its timer on disposal and refuses further scans", async () => { - jest.useFakeTimers() - const timers = jest.getTimerCount() +test("watches nested files through a folder 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 catalog.refresh() + 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().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"]) +}) + +test("a refresh requested during an active scan includes subsequent filesystem changes", async () => { + const directory = await fixture() + const catalog = tracked(directory) + const first = catalog.refresh() + await Bun.write(path.join(directory, "new.svg"), svg) + await Promise.all([first, catalog.refresh()]) + expect(catalog.state().images.map((image) => image.title)).toEqual(["new"]) +}) + +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) + 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) + result.value.emit("error", new Error("Watcher unavailable")) + await closed.promise + expect(catalog.state().error).toContain("Watcher unavailable") + expect(watch.mock.calls).toHaveLength(calls) + expect(await catalog.refresh()).toBe(true) + expect(catalog.state().error).toBe("") + const replacement = watch.mock.results.at(-1) + 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 + 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(jest.getTimerCount()).toBe(timers) - jest.advanceTimersByTime(2000) expect(await catalog.refresh()).toBe(false) }) @@ -172,13 +263,16 @@ test("rejects reads after cancellation or disposal", async () => { await expect(catalog.read(image)).rejects.toThrow() }) -test("no folder means an empty catalog without filesystem polling or errors", async () => { - jest.useFakeTimers() - const timers = jest.getTimerCount() - const catalog = tracked(wallpaperFolder(undefined)) - expect(await catalog.refresh()).toBe(true) - expect(catalog.state()).toEqual({ folder: "", ready: true, images: [], error: "" }) - expect(jest.getTimerCount()).toBe(timers) +test("no folder means an empty catalog without watchers or errors", async () => { + const watch = spyOn(fs, "watch") + try { + const catalog = tracked(wallpaperFolder(undefined)) + expect(await catalog.refresh()).toBe(true) + expect(catalog.state()).toEqual({ folder: "", ready: true, images: [], error: "" }) + expect(watch).not.toHaveBeenCalled() + } finally { + watch.mockRestore() + } }) function tracked(folder: string) { diff --git a/src/catalog.ts b/src/catalog.ts index 2ef7828..c75706d 100644 --- a/src/catalog.ts +++ b/src/catalog.ts @@ -1,4 +1,5 @@ -import { readdir, readFile, realpath, stat } from "node:fs/promises" +import { watch, type FSWatcher } from "node:fs" +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" @@ -11,6 +12,7 @@ const formats: Readonly> = { ".webp": "image/webp", ".svg": "image/svg+xml", } +const missing = Schema.is(Schema.Struct({ code: Schema.Literal("ENOENT") })) export function wallpaperFolder(options: unknown) { const configured = Schema.decodeUnknownSync(Schema.optional(Schema.Union([ @@ -38,12 +40,99 @@ export function createCatalog(folder: string, changed: () => void) { let value: typeof Catalog.spec.state.Type = { folder, ready: !folder, images: [], error: "" } let cache = new Map() let pending: Promise | undefined + let dirty = false + let watcher: FSWatcher | undefined + let resolvedFolder: string | undefined + const parents = new Map() + let watchError = "" + + function invalidate() { + dirty = true + void refresh() + } + + async function observe() { + if (!folder) return + let root: string | undefined + let failure: unknown + try { + root = await realpath(folder) + resolvedFolder = root + } catch (error) { + failure = error + } + const targets = new Set([folder, ...(resolvedFolder ? [resolvedFolder] : [])]) + for (const [target, monitor] of parents) { + if (targets.has(target)) continue + monitor.watcher.close() + parents.delete(target) + } + for (const target of targets) { + let parent = path.dirname(target) + while (true) { + try { + await stat(parent) + break + } catch (error) { + if (!missing(error) || parent === path.dirname(parent)) throw error + parent = path.dirname(parent) + } + } + if (lifetime.signal.aborted) return + const previous = parents.get(target) + if (previous?.directory === parent) 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))) { + watcher?.close() + watcher = undefined + invalidate() + } + }) + parents.set(target, { directory, watcher: monitor }) + monitor.on("error", (error) => { + monitor.close() + if (parents.get(target)?.watcher === monitor) parents.delete(target) + reportWatchError(error) + }) + } + if (failure) throw failure + if (lifetime.signal.aborted) return + if (!watcher && root) { + const monitor = watch(root, { recursive: true, signal: lifetime.signal }, invalidate) + watcher = monitor + monitor.on("error", (error) => { + monitor.close() + if (watcher === monitor) watcher = undefined + reportWatchError(error) + }) + } + watchError = "" + } + + function reportWatchError(error: unknown) { + watchError = `${folder}: ${String(error)}` + if (!lifetime.signal.aborted) { + value = { ...value, error: [...new Set([value.error, watchError].filter(Boolean))].join("\n") } + changed() + } + } function refresh() { if (lifetime.signal.aborted) return Promise.resolve(false) + dirty = true if (pending) return pending - pending = scan().then( - () => !lifetime.signal.aborted, + pending = (async () => { + do { + dirty = false + try { await observe() } catch (error) { watchError = `${folder}: ${String(error)}` } + await scan() + } while (dirty && !lifetime.signal.aborted) + })().then( + () => !lifetime.signal.aborted && !value.error, (error) => { if (!lifetime.signal.aborted) { value = { ...value, ready: true, error: String(error) } @@ -57,18 +146,19 @@ export function createCatalog(folder: string, changed: () => void) { async function scan() { if (!folder) return - const errors: string[] = [] + const errors: string[] = watchError ? [watchError] : [] let root = folder const files = new Set() try { root = await realpath(folder) for (const entry of await readdir(root, { recursive: true, withFileTypes: true })) { if (!entry.isFile() || !formats[path.extname(entry.name).toLowerCase()]) continue - const file = await realpath(path.join(entry.parentPath, entry.name)) - files.add(file) + const filename = path.join(entry.parentPath, entry.name) + try { files.add(await realpath(filename)) } + catch (error) { errors.push(`${filename}: ${String(error)}`) } } } catch (error) { - if (!missing(error)) errors.push(`${folder}: ${String(error)}`) + errors.push(`${folder}: ${String(error)}`) } const next = new Map() for (const file of files) { @@ -90,7 +180,7 @@ export function createCatalog(folder: string, changed: () => void) { if (lifetime.signal.aborted) return cache = next const images = [...cache.values()].map((entry) => entry.image).sort((a, b) => a.id.localeCompare(b.id)) - const error = errors.sort().join("\n") + const error = [...new Set(errors)].sort().join("\n") if (value.ready && error === value.error && images.length === value.images.length && images.every((image, i) => image === value.images[i])) return value = { folder, ready: true, images, error } changed() @@ -101,39 +191,48 @@ export function createCatalog(folder: string, changed: () => void) { async try(signal) { const entry = cache.get(request.id) if (!entry || entry.image.version !== request.version) throw new Error("The selected wallpaper is missing or has changed.") - const info = await stat(entry.file) - requireSize(info.size) - if (stamp(info) !== request.version) throw new Error("The selected wallpaper has changed. Refresh the gallery.") - const data = await readFile(entry.file, { signal }) - requireSize(data.length) - if (stamp(await stat(entry.file)) !== request.version) throw new Error("The selected wallpaper changed while being read.") - return `data:${formats[path.extname(entry.file).toLowerCase()]};base64,${data.toString("base64")}` + const file = await open(entry.file, "r") + try { + const info = await file.stat() + requireSize(info.size) + if (stamp(info) !== request.version) throw new Error("The selected wallpaper has changed. Refresh the gallery.") + const buffer = Buffer.alloc(info.size + 1) + let size = 0 + while (size < buffer.length) { + signal.throwIfAborted() + const { bytesRead } = await file.read(buffer, size, buffer.length - size, null) + if (!bytesRead) break + size += bytesRead + } + requireSize(size) + if (stamp(await file.stat()) !== request.version) throw new Error("The selected wallpaper changed while being read.") + return `data:${formats[path.extname(entry.file).toLowerCase()]};base64,${buffer.subarray(0, size).toString("base64")}` + } finally { + await file.close() + } }, catch: (error) => error, })), { signal: AbortSignal.any([signal, lifetime.signal]) }) } - const timer = folder ? setInterval(() => void refresh(), 2000) : undefined return { state: () => value, refresh, read, dispose() { lifetime.abort() - clearInterval(timer) + watcher?.close() + for (const monitor of parents.values()) monitor.watcher.close() + parents.clear() cache.clear() }, } } -function missing(error: unknown) { - return error instanceof Error && "code" in error && error.code === "ENOENT" -} - function requireSize(size: number) { if (size === 0 || size > maxImageBytes) throw new Error("image.sizeError") } -function stamp(info: { size: number; mtimeMs: number; ctimeMs: number }) { - return `${info.size}:${info.mtimeMs}:${info.ctimeMs}` +function stamp(info: { size: number; mtimeMs: number; ctimeMs: number; dev: number; ino: number }) { + return `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}` } diff --git a/src/contract.ts b/src/contract.ts index 8f3ac27..b90494b 100644 --- a/src/contract.ts +++ b/src/contract.ts @@ -8,7 +8,6 @@ export const Wallpaper = Schema.Struct({ id: Schema.String, title: Schema.String export const ImageRequest = Schema.Struct({ id: Schema.String, version: Schema.String }) export const Catalog = Ipc.define({ - // Desktop caches clients by ID across reloads. A changed protocol needs a new ID. id: "wallpaper.catalog.v5", state: Schema.Struct({ folder: Schema.String, diff --git a/src/errors.test.ts b/src/errors.test.ts index c61b28b..1c6fd5c 100644 --- a/src/errors.test.ts +++ b/src/errors.test.ts @@ -2,13 +2,10 @@ import { expect, test } from "bun:test" import type { ToastOptions } from "@opencode/plugin/gui" import { createWallpaperErrorReporter } from "./errors" -test("dismissed background errors do not return on polling, retries or Settings reopenings", () => { +test("unchanged background errors do not repeat, but recovered errors can notify again", () => { const shown: ToastOptions[] = [] const report = createWallpaperErrorReporter({ show(options) { shown.push(options); return { dismiss() {} } } }) report("folder", "Wallpaper folder", ["example.jpg: too large", "other.png: empty"]) - // No toast lifecycle callback is needed. Once reported, the scan remains seen - // even after its toast closes or its error temporarily clears during a retry. - report("folder", "Wallpaper folder", []) report("folder", "Wallpaper folder", ["other.png: empty", "example.jpg: too large"]) expect(shown).toEqual([{ variant: "error", icon: "outline-photo", title: "Wallpaper folder", @@ -17,6 +14,18 @@ test("dismissed background errors do not return on polling, retries or Settings report("folder", "Wallpaper folder", ["example.jpg: too large", "new.webp: unreadable"]) expect(shown[1]?.description).toBe("new.webp: unreadable") expect(shown).toHaveLength(2) + 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() {} } } }) + 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", () => { diff --git a/src/errors.ts b/src/errors.ts index 6ee382e..ac0a766 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,17 +1,13 @@ import type { Toasts } from "@opencode/plugin/gui" export function createWallpaperErrorReporter(toast: Pick) { - // Keep this reporter in the window setup, not Settings. Dismissing a toast or - // reopening Settings must not replay errors from an unchanged background scan. const reported = new Map>() - return (source: string, title: string, errors: readonly string[]) => { + const report = (source: string, title: string, errors: readonly string[]) => { const seen = reported.get(source) ?? new Set() - const fresh = errors.filter((error) => { - if (!error || seen.has(error)) return false - seen.add(error) - return true - }) - reported.set(source, seen) + const current = new Set(errors.filter(Boolean)) + const fresh = [...current].filter((error) => !seen.has(error)) + if (current.size) reported.set(source, current) + else reported.delete(source) if (!fresh.length) return toast.show({ variant: "error", @@ -20,4 +16,10 @@ export function createWallpaperErrorReporter(toast: Pick) { description: fresh.join("\n\n"), }) } + return Object.assign(report, { + retain(sources: readonly string[]) { + const active = new Set(sources) + for (const source of reported.keys()) if (!active.has(source)) reported.delete(source) + }, + }) } diff --git a/src/gallery-toggle.tsx b/src/gallery-toggle.tsx new file mode 100644 index 0000000..634df0f --- /dev/null +++ b/src/gallery-toggle.tsx @@ -0,0 +1,14 @@ +export function WallpaperGalleryToggle(props: { + expanded: boolean + controls: string + label: string + onToggle: () => void +}) { + return +} diff --git a/src/gui.tsx b/src/gui.tsx index e5d67f8..dcae154 100644 --- a/src/gui.tsx +++ b/src/gui.tsx @@ -1,86 +1,61 @@ -import { Command, Plugin, SettingsPage, Store } from "@opencode/plugin/gui" +import { Command, Plugin, SettingsPage, Store, createKeyed } from "@opencode/plugin/gui" import { batch, createEffect, createMemo, createSignal, onCleanup } from "solid-js" import { Schema } from "effect" import { wallpaperCommand } from "./command" import { Catalog } from "./contract" import { changeWallpaper, setWallpaperEnabled, wallpaperCatalog, wallpaperTitle, type WallpaperChoice } from "./model" -import { appearanceKeys, Preferences, initial, slideshowControls, wallpaperFadeDuration } from "./preferences" -import { createWallpaperImage, type WallpaperReader } from "./render" +import { appearanceKeys, StoredPreferences, initial, wallpaperFadeDuration } from "./preferences" +import { createWallpaperImage, createWallpaperVisibility, type WallpaperReader } from "./render" import { imageError, thumbnailBlob } from "./image" import { createWallpaperErrorReporter } from "./errors" import { createThumbnailCache } from "./thumbnail-cache" import { alignWallpaperHeaders } from "./backdrop" -import { wallpaperCanvasStyle, wallpaperVariableStyle } from "./style" +import { createWallpaperStyles, wallpaperCanvasStyle, wallpaperVariableStyle } from "./style" import { WallpaperSettings } from "./settings" import { WallpaperPicker } from "./picker" import { createWallpaperSlideshow } from "./slideshow" -import { fadeWallpaper, wallpaperTransitionStyle } from "./transition" +import { createWallpaperVisibilityAnimation, fadeWallpaper, wallpaperTransitionStyle } from "./transition" import en from "./i18n/en" import css from "./settings.css?inline" export default Plugin.define({ - stores: { preferences: Store.global(Preferences, initial) }, + stores: { preferences: Store.global(StoredPreferences, initial) }, i18n: { en }, async main(ctx) { const { createCatalog, wallpaperFolder, wallpaperFolderLabel } = await import("./catalog") - let catalog: ReturnType | undefined - let initializing: Promise | undefined - let fallback: typeof Catalog.spec.state.Type = { folder: "", ready: false, images: [], error: "" } - const folder = () => ctx.storage.store("folder", { schema: Schema.String, initial: "" }) - ctx.onCleanup(() => catalog?.dispose()) + ctx.signal.throwIfAborted() + const folder = ctx.storage.store("folder", { schema: Schema.String, initial: "" }) + let catalog = createCatalog(wallpaperFolder(folder.value || (ctx.options.folder ?? ctx.options.folders)), changed) + ctx.onCleanup(() => catalog.dispose()) let lastError = "" const state = () => { - const value = catalog?.state() ?? fallback + const value = catalog.state() return { ...value, folderLabel: wallpaperFolderLabel(value.folder) } } - const changed = () => { + function changed() { const error = state().error if (error && error !== lastError) ctx.log.write("error", "wallpaper folder scan failed", { error }) lastError = error provider.changed() } - function refresh(): Promise { - if (ctx.signal.aborted) return Promise.resolve(false) - if (catalog) return catalog.refresh() - if (initializing) return initializing - initializing = (async () => { - try { - const configured = ctx.options.folder ?? ctx.options.folders - if (ctx.signal.aborted) return false - catalog = createCatalog(wallpaperFolder(folder().value || configured), changed) - changed() - return await catalog.refresh() - } catch (error) { - if (!ctx.signal.aborted) { - fallback = { ...fallback, ready: true, error: String(error) } - changed() - } - return false - } - })().finally(() => { initializing = undefined }) - return initializing - } const provider = ctx.provide(Catalog, { state, - refresh, + refresh: () => catalog.refresh(), async setFolder(value, caller) { - if (initializing) await initializing caller.signal.throwIfAborted() ctx.signal.throwIfAborted() const selected = wallpaperFolder(value) - folder().set(selected) - catalog?.dispose() + folder.set(selected) + catalog.dispose() catalog = createCatalog(selected, changed) changed() return catalog.refresh() }, async read(request, caller) { - if (!catalog) await refresh() - if (!catalog) throw new Error(state().error || "Wallpaper folders are unavailable.") - return catalog.read(request, caller.signal) + return catalog.read(request, AbortSignal.any([caller.signal, ctx.signal])) }, }) - await refresh() + await catalog.refresh() }, setup(ctx) { const catalog = ctx.desktop ? ctx.main(Catalog) : undefined @@ -91,7 +66,7 @@ export default Plugin.define({ ) const settings = ctx.stores.preferences const slideshow = createWallpaperSlideshow(() => settings.value, images, () => - !image.loading && !image.previous && (!!image.url || !!image.error), + !image.loading && !image.previous && !visibility.fade() && (!!image.url || !!image.error), ) const selected = slideshow.selected const select = (choice: string) => batch(() => { @@ -111,17 +86,21 @@ export default Plugin.define({ if (!catalog) throw new Error("image.readError") return catalog.read({ id: choice.id, version: choice.version }, { signal: AbortSignal.any([signal, ctx.signal]) }) } - const image = createWallpaperImage(selected, read, () => - settings.value.slideshow && (settings.value.transition ?? slideshowControls.transition) === "fade" && !reducedMotion() + const visibility = createWallpaperVisibility(() => settings.value.enabled, () => !!image.url, reducedMotion) + const painted = createMemo(() => settings.value.enabled ? selected() : visibility.enabled() ? image.choice : undefined) + const image = createWallpaperImage(painted, read, () => + settings.value.slideshow && settings.value.transition === "fade" && !reducedMotion() ? wallpaperFadeDuration : 0, ) const reportImage = (choice: WallpaperChoice, error: string) => report( `image:${choice.id}:${choice.version}`, ctx.t("title"), - [`${wallpaperTitle(choice, ctx.t)}: ${imageError(error, ctx.t)}`], + error ? [`${wallpaperTitle(choice, ctx.t)}: ${imageError(error, ctx.t)}`] : [], ) const thumbnails = createThumbnailCache(async (choice, signal) => { try { - return await thumbnailBlob(choice.image ?? await read(choice, signal), signal) + const thumbnail = await thumbnailBlob(choice.image ?? await read(choice, signal), signal) + reportImage(choice, "") + return thumbnail } catch (error) { if (!signal.aborted && !ctx.signal.aborted) reportImage(choice, error instanceof Error ? error.message : String(error)) throw error @@ -132,40 +111,38 @@ export default Plugin.define({ createEffect(() => { if (ctx.signal.aborted) return const state = catalog?.state() - if (state?.error) report(`folder:${state.folder}`, ctx.t("folders.title"), - state.error.split("\n").map((error) => error.replace(/image\.[A-Za-z]+$/, (key) => ctx.t(key)))) + if (state) report(`folder:${state.folder}`, ctx.t("folders.title"), + state.error ? state.error.split("\n").map((error) => error.replace(/image\.[A-Za-z]+$/, (key) => ctx.t(key))) : []) const choice = selected() - if (choice && image.error) reportImage(choice, image.error) + if (choice && !image.loading) reportImage(choice, image.error) const preferences = ctx.stores.preferences.value - if (preferences.enabled && preferences.preset.startsWith("file:") && state?.ready && !state.error && !choice) { - report(`missing:${preferences.preset}`, ctx.t("title"), [ctx.t("folders.missing")]) - } - }) - 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" - settingsStyle.textContent = css - canvasStyle.textContent = wallpaperCanvasStyle + wallpaperTransitionStyle - canvasStyle.disabled = true - document.head.append(settingsStyle, canvasStyle, imageStyle) - onCleanup(() => { settingsStyle.remove(); canvasStyle.remove(); imageStyle.remove() }) - createEffect(() => { - const variables = wallpaperVariableStyle(settings.value, image.url) - imageStyle.textContent = variables - canvasStyle.disabled = !variables - }) - createEffect(() => { - if (!image.url || !image.width || !image.height) return - onCleanup(alignWallpaperHeaders({ image: { width: image.width, height: image.height }, fit: ctx.stores.preferences.value.fit })) + const missing = preferences.enabled && preferences.preset.startsWith("file:") && state?.ready && !state.error && !choice + report(`missing:${preferences.preset}`, ctx.t("title"), missing ? [ctx.t("folders.missing")] : []) + report.retain([ + ...images().map((image) => `image:${image.id}:${image.version}`), + `folder:${state?.folder ?? ""}`, `missing:${preferences.preset}`, "refresh", + ]) }) + const styles = createWallpaperStyles(css, wallpaperCanvasStyle + wallpaperTransitionStyle) + onCleanup(styles.dispose) + const variables = createMemo(() => wallpaperVariableStyle({ ...settings.value, enabled: visibility.enabled() }, image.url)) + createEffect(() => styles.update(variables())) + createKeyed(() => image.url ? { url: image.url, width: image.width, height: image.height, fit: settings.value.fit } : undefined, + (frame) => onCleanup(alignWallpaperHeaders({ image: frame, fit: frame.fit })), + { equals: (left, right) => left?.url === right?.url && left?.fit === right?.fit }, + ) createEffect(() => { const previous = image.previous if (!previous || reducedMotion() || !settings.value.enabled || !settings.value.slideshow || settings.value.transition === "none") return onCleanup(fadeWallpaper(previous, settings.value.fit, image.transition)) }) + const visibilityAnimation = createWallpaperVisibilityAnimation() + onCleanup(visibilityAnimation.clear) + createEffect(() => { + const fade = visibility.fade() + if (fade) visibilityAnimation.fade(fade.show, fade.duration) + else visibilityAnimation.clear() + }) ctx.add(SettingsPage, { id: "wallpaper", icon: "outline-photo", @@ -205,7 +182,9 @@ export default Plugin.define({ wallpaperCommand(ctx, images, async () => { if (!catalog) return true try { - return await catalog.refresh({ signal: ctx.signal }) + const refreshed = await catalog.refresh({ signal: ctx.signal }) + if (refreshed) report("refresh", ctx.t("folders.title"), []) + return refreshed } catch (error) { if (!ctx.signal.aborted) report("refresh", ctx.t("folders.title"), [String(error)]) return false diff --git a/src/i18n/en.ts b/src/i18n/en.ts index cba3725..a951b4d 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -8,8 +8,8 @@ export default { "picker.title": "Choose wallpaper", "picker.description": "Choose a background without leaving the conversation.", "picker.search": "Search wallpapers", - "picker.off": "Wallpaper off", - "picker.on": "Wallpaper on", + "picker.disable": "Turn wallpaper off", + "picker.enable": "Turn wallpaper on", "picker.settings": "Wallpaper settings", "folders.title": "Wallpaper folder", "folders.description": "PNG, JPEG, WebP and SVG files up to 8 MiB, including subfolders.", diff --git a/src/image.test.ts b/src/image.test.ts index 8be0449..9d258ce 100644 --- a/src/image.test.ts +++ b/src/image.test.ts @@ -22,19 +22,19 @@ describe("local wallpaper images", () => { "data:image/png;base64,====", "data:image/png;base64,", ]) { - expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, image })).toThrow() + expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, images: [{ id: "upload:test", name: "test.png", image }] })).toThrow() expect(() => wallpaperBlob(image)).toThrow("image.decodeError") } }) test("enforces both encoded and decoded preference size limits", () => { const image = `data:image/jpeg;base64,${Buffer.alloc(8 * 1024 * 1024).toString("base64")}` - expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, preset: "custom", image })).not.toThrow() + expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, preset: "upload:test", images: [{ id: "upload:test", name: "test.jpg", image }] })).not.toThrow() expect(() => - Schema.decodeUnknownSync(Preferences)({ ...initial, preset: "custom", image: image.slice(0, -4) + "AAAAAAAA" }), + Schema.encodeUnknownSync(Preferences)({ ...initial, images: [{ id: "upload:test", name: "test.jpg", image: image.slice(0, -4) + "AAAAAAAA" }] }), ).toThrow() const oversizedPng = `data:image/png;base64,${Buffer.alloc(8 * 1024 * 1024 + 1).toString("base64")}` - expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, image: oversizedPng })).toThrow() + expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, images: [{ id: "upload:test", name: "test.png", image: oversizedPng }] })).toThrow() }) test("renders a large folder image through a short blob URL without changing its bytes", async () => { @@ -56,7 +56,7 @@ describe("local wallpaper images", () => { test("decodes local SVG data without accepting it as an uploaded preference", async () => { const svg = '' for (const image of [`data:image/svg+xml,${encodeURIComponent(svg)}`, `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`]) { - expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, image })).toThrow() + expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, images: [{ id: "upload:test", name: "test.svg", image }] })).toThrow() expect(await wallpaperBlob(image).text()).toBe(svg) } expect(() => wallpaperBlob("data:image/svg+xml,%")).toThrow("image.decodeError") diff --git a/src/model.test.ts b/src/model.test.ts index ef9312a..807db7b 100644 --- a/src/model.test.ts +++ b/src/model.test.ts @@ -6,9 +6,10 @@ import { canRemoveWallpaper, changeWallpaper, checkWallpaperDuplicate, removeWal import { Preferences, initial } from "./preferences" const customImage = "data:image/png;base64,aGVsbG8=" +const customUpload = { id: "custom", name: "Wallpaper", image: customImage } test("resolves only the selected upload or folder image", () => { - const settings = Schema.decodeUnknownSync(Preferences)({ ...initial, enabled: true, preset: "custom", image: customImage }) + 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) @@ -20,29 +21,21 @@ 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], { image: customImage }) + const choices = wallpaperCatalog([file], { images: [customUpload] }) for (const selected of [file.id, "custom"]) { - const settings = Schema.decodeUnknownSync(Preferences)({ ...initial, preset: selected, image: customImage, strength: 37, fit: "contain" }) + const settings = { ...initial, preset: selected, images: [customUpload], tint: 63, fit: "contain" as const } const before = structuredClone(settings) removeWallpaper(settings, file, choices) expect(settings).toEqual(before) } }) - test("restores previously hidden folder images in the gallery and picker", async () => { - const settings = Schema.decodeUnknownSync(Preferences)({ ...initial, image: customImage, hidden: [file.id, "custom"] }) - const images = () => wallpaperCatalog([file], settings) - const world = picker(undefined, { preferences: settings, images }) - await world.command.run() - expect(world.requests[0]?.options.map((option) => option.value)).toEqual([file.id, "custom"]) - }) - test("removes an unselected uploaded image without changing the active folder wallpaper", async () => { - const settings = { ...initial, enabled: true, preset: file.id, image: customImage, strength: 37, fit: "contain" as const } + const settings = { ...initial, enabled: true, preset: file.id, images: [customUpload], tint: 63, fit: "contain" as const } const choices = wallpaperCatalog([file], settings) removeWallpaper(settings, choices.at(-1)!, choices) const saved = Schema.decodeUnknownSync(Preferences)(JSON.parse(JSON.stringify(settings))) - expect(saved).toEqual({ ...initial, enabled: true, preset: file.id, strength: 37, fit: "contain" }) + 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) @@ -50,45 +43,44 @@ describe("removing wallpapers", () => { }) test("removing the active uploaded image selects the first remaining wallpaper and allows another upload", () => { - const settings = { ...initial, enabled: true, preset: "custom", image: customImage, imageName: "saved.png", strength: 37, fit: "contain" as const } + const settings = { ...initial, enabled: true, preset: "custom", images: [{ ...customUpload, name: "saved.png" }], tint: 63, fit: "contain" as const } const choices = wallpaperCatalog([file], settings) removeWallpaper(settings, choices.at(-1)!, choices) const saved = Schema.decodeUnknownSync(Preferences)(JSON.parse(JSON.stringify(settings))) - expect(saved).toEqual({ ...initial, enabled: true, preset: file.id, strength: 37, fit: "contain" }) + 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", image: customImage } + 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 }) + 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", image: customImage } + 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 }) + expect(settings).toEqual({ ...initial, enabled: false, preset: file.id, images: [] }) }) }) describe("custom uploads", () => { - test("keeps the legacy upload alongside multiple saved images and removes them independently", () => { - const settings = Schema.decodeUnknownSync(Preferences)({ ...initial, preset: "upload:first", image: customImage, imageName: "legacy.png", images: [ + test("removes saved uploads independently", () => { + const settings = { ...initial, preset: "upload:first", images: [ + customUpload, { id: "upload:first", name: "first.png", image: "data:image/png;base64,YWxwaGE=" }, { id: "upload:second", name: "second.webp", image: "data:image/webp;base64,YmV0YQ==" }, - ] }) + ] } const choices = wallpaperCatalog([], settings) - expect(choices.filter(canRemoveWallpaper).map((image) => wallpaperTitle(image, (key) => key))).toEqual(["legacy", "first", "second"]) + expect(choices.filter(canRemoveWallpaper).map((image) => wallpaperTitle(image, (key) => key))).toEqual(["Wallpaper", "first", "second"]) removeWallpaper(settings, choices.find((image) => image.id === "upload:first")!, choices) expect(settings.preset).toBe("upload:second") - expect(settings.image).toBe(customImage) - expect(settings.images?.map((image) => image.id)).toEqual(["upload:second"]) + expect(settings.images.map((image) => image.id)).toEqual(["custom", "upload:second"]) const remaining = wallpaperCatalog([], settings) removeWallpaper(settings, remaining.find((image) => image.id === "upload:second")!, remaining) - expect(settings.image).toBe(customImage) - expect(settings.images).toEqual([]) + expect(settings.images).toEqual([customUpload]) }) test("checks duplicates across every upload and treats extensions as display-name differences only", () => { @@ -101,7 +93,7 @@ describe("custom uploads", () => { }) test("shows the saved filename in the gallery and picker across refreshes", async () => { - const settings = { ...initial, image: customImage, imageName: "My wallpaper.png" } + const settings = { ...initial, images: [{ ...customUpload, name: "My wallpaper.png" }] } const choices = wallpaperCatalog([], settings) expect(wallpaperTitle(choices.at(-1)!, (key) => key)).toBe("My wallpaper") expect(wallpaperCatalog([], settings, choices).at(-1)).toBe(choices.at(-1)) @@ -115,7 +107,7 @@ describe("custom uploads", () => { [" SAVED.PNG ", "saved.png"], ["Café.png", "Cafe\u0301.PNG"], ])("rejects filename %s matching saved filename %s", (name, imageName) => { - expect(() => checkWallpaperDuplicate({ name }, { image: customImage, imageName }, [])).toThrow("image.duplicateName") + expect(() => checkWallpaperDuplicate({ name }, { images: [{ ...customUpload, name: imageName }] }, [])).toThrow("image.duplicateName") }) test("rejects matching folder filenames across nested and Windows paths", () => { @@ -125,8 +117,8 @@ describe("custom uploads", () => { } }) - test("rejects repeated custom-image bytes with a new name or MIME label, including legacy saves", () => { - const settings = { ...initial, image: customImage } + 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")]) { expect(() => checkWallpaperDuplicate({ name: "renamed.png", image: source }, settings, [])).toThrow("image.duplicateImage") } @@ -146,8 +138,8 @@ describe("wallpaper slash picker", () => { test.each([ ["file:example.png", false, "file:example.png", true], ["custom", false, "custom", true], - ] as const)("choosing %s preserves the saved image, fit and strength", async (choice, enabled, preset, shown) => { - const world = picker(choice, { preferences: { enabled, preset: "file:example.png", image: customImage }, images: () => wallpaperCatalog([{ id: "file:example.png", title: "example", version: "1" }], { image: customImage }) }) + ] 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 }) @@ -177,7 +169,7 @@ describe("wallpaper slash picker", () => { }) test("keeps saved uploads and settings accessible when the folder refresh fails", async () => { - const world = picker("settings", { preferences: { image: customImage }, refresh: async () => false }) + const world = picker("settings", { preferences: { images: [customUpload] }, refresh: async () => false }) await world.command.run() expect(world.requests[0]?.options.map((option) => option.value)).toEqual(["custom"]) expect(world.value).toEqual({ ...world.before, enabled: false }) @@ -206,7 +198,7 @@ describe("wallpaper slash picker", () => { test("wallpaper on/off preserves the saved choice, falls back to available images, and stays off with an empty gallery", () => { const images = [{ id: "file:first.png", title: "first", version: "1" }, { id: "custom", title: "custom", version: "1", image: customImage }] - const settings = { ...initial, enabled: true, preset: "custom", image: customImage, strength: 37, fit: "contain" as const } + const settings = { ...initial, enabled: true, preset: "custom", images: [customUpload], tint: 63, fit: "contain" as const } const saved = structuredClone(settings) setWallpaperEnabled(settings, false, images) expect(settings).toEqual({ ...saved, enabled: false }) @@ -227,7 +219,7 @@ function picker(choice: string | undefined, config: { onSelect?: () => void images?: () => readonly WallpaperChoice[] } = {}) { - const value: Mutable = { ...initial, strength: 37, fit: "contain", ...config.preferences, hidden: config.preferences?.hidden?.slice(), images: config.preferences?.images?.map((image) => ({ ...image })) } + const value: Mutable = { ...initial, tint: 63, fit: "contain", ...config.preferences, images: (config.preferences?.images ?? []).map((image) => ({ ...image })) } const before = structuredClone(value) const requests: SelectOptions[] = [] const pages: (string | undefined)[] = [] diff --git a/src/model.ts b/src/model.ts index 8a48290..e550d8d 100644 --- a/src/model.ts +++ b/src/model.ts @@ -3,7 +3,7 @@ import { imageBytes } from "./image" import { initial, type UploadedWallpaper, type WallpaperPreferences } from "./preferences" export type WallpaperChoice = typeof Wallpaper.Type & { readonly image?: string } -type SavedImages = Pick +type SavedImages = Pick export function sameWallpaper(left: WallpaperChoice | undefined, right: WallpaperChoice | undefined) { return left?.id === right?.id && left?.version === right?.version && left?.image === right?.image @@ -14,8 +14,7 @@ export function selectedWallpaper(settings: Pick } export function uploadedWallpapers(settings: SavedImages): readonly UploadedWallpaper[] { - const images = settings.images ?? [] - return settings.image ? [{ id: "custom", name: settings.imageName ?? "", image: settings.image }, ...images] : images + return settings.images } export function wallpaperCatalog(images: readonly (typeof Wallpaper.Type)[] = [], settings: SavedImages = initial, previous: readonly WallpaperChoice[] = []): WallpaperChoice[] { @@ -35,12 +34,9 @@ export function canRemoveWallpaper(choice: Pick) { return choice.id === "custom" || choice.id.startsWith("upload:") } -export function removeWallpaper(draft: { enabled: boolean; preset: string; image: string; imageName?: string; images?: readonly UploadedWallpaper[] }, choice: WallpaperChoice, images: readonly WallpaperChoice[]) { +export function removeWallpaper(draft: { enabled: boolean; preset: string; images: readonly UploadedWallpaper[] }, choice: WallpaperChoice, images: readonly WallpaperChoice[]) { if (!canRemoveWallpaper(choice)) return - if (choice.id === "custom") { - draft.image = "" - delete draft.imageName - } else draft.images = draft.images?.filter((image) => image.id !== choice.id) + draft.images = draft.images.filter((image) => image.id !== choice.id) if (draft.preset !== choice.id) return const next = images[images.findIndex((image) => image.id === choice.id) + 1] ?? images.find((image) => image.id !== choice.id) draft.preset = next?.id ?? initial.preset @@ -77,7 +73,7 @@ export function checkWallpaperDuplicate(upload: { name: string; image?: string } function wallpaperFilename(id: string) { if (!id.startsWith("file:")) return "" const path = id.slice(5) - try { return decodeURIComponent(path) } catch { return path } + return decodeURIComponent(path) } function filenameKey(name: string) { diff --git a/src/picker.tsx b/src/picker.tsx index 1c97935..21ccb6e 100644 --- a/src/picker.tsx +++ b/src/picker.tsx @@ -44,16 +44,10 @@ export function WallpaperPicker(props: { return - + >{ctx.t(props.enabled() ? "picker.disable" : "picker.enable")} props.onSelect("settings")}>{ctx.t("picker.settings")} }> diff --git a/src/preferences.test.ts b/src/preferences.test.ts index 40b9b86..ef98d2b 100644 --- a/src/preferences.test.ts +++ b/src/preferences.test.ts @@ -1,14 +1,46 @@ import { describe, expect, test } from "bun:test" import { Schema } from "effect" -import { Preferences, initial, slideshowControls, wallpaperAppearance } from "./preferences" +import { Preferences, StoredPreferences, initial, slideshowControls, wallpaperAppearance } from "./preferences" import { wallpaperBackground } from "./style" test("starts with wallpaper off and no selection while retaining unknown selections from old saves", () => { - expect(Schema.decodeUnknownSync(Preferences)(initial)).toMatchObject({ enabled: false, preset: "", image: "" }) + expect(Schema.decodeUnknownSync(Preferences)(initial)).toMatchObject({ enabled: false, preset: "", images: [] }) const saved = { ...initial, enabled: true, preset: "legacy-selection" } expect(Schema.decodeUnknownSync(Preferences)(saved)).toEqual(saved) }) +test("migrates the single legacy upload once and encodes only the canonical image list", () => { + 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() +}) + +test("recovers unrelated persisted fields without dropping legacy or current uploads", () => { + const image = "data:image/png;base64,YWJj" + const uploaded = { id: "upload:one", name: "one.png", image } + 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") + 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) { @@ -17,22 +49,27 @@ describe("wallpaper slideshow preferences", () => { } }) - test("rejects invalid display times and unknown transitions", () => { + test("rejects invalid display times and unknown transitions on writes", () => { for (const duration of [0, 4, 86401, 5.5, NaN, Infinity, "60"]) { - expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, duration })).toThrow() + expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, duration })).toThrow() } - expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, transition: "spin" })).toThrow() + expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, transition: "spin" })).toThrow() }) }) describe("wallpaper tint and brightness", () => { - test("preserves old strength settings as tint and defaults brightness without rewriting preferences", () => { + test("migrates old strength to canonical tint and writes no legacy fields", () => { for (const strength of [5, 20, 45]) { - const settings = Schema.decodeUnknownSync(Preferences)({ ...initial, enabled: true, strength }) + 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).toBeUndefined() - expect(settings.brightness).toBeUndefined() + 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) } }) @@ -55,7 +92,7 @@ describe("wallpaper tint and brightness", () => { test.each([ ["tint", -1], ["tint", 101], ["tint", 25.5], ["brightness", 24], ["brightness", 151], ["brightness", 100.5], - ])("rejects invalid %s value %s", (property, value) => { - expect(() => Schema.decodeUnknownSync(Preferences)({ ...initial, [property]: value })).toThrow() + ])("rejects invalid %s value %s on writes", (property, value) => { + expect(() => Schema.encodeUnknownSync(Preferences)({ ...initial, [property]: value })).toThrow() }) }) diff --git a/src/preferences.ts b/src/preferences.ts index bb336e5..af3b92f 100644 --- a/src/preferences.ts +++ b/src/preferences.ts @@ -1,4 +1,4 @@ -import { Schema } from "effect" +import { Effect, Option, Schema, SchemaGetter } from "effect" import { StoredImage } from "./image" export const appearanceControls = { @@ -13,45 +13,95 @@ export const wallpaperFadeDuration = 800 export type WallpaperTransition = "none" | "fade" const UploadedImage = Schema.Struct({ - id: Schema.String.check(Schema.isPattern(/^upload:.+$/)), + id: Schema.String.check(Schema.isPattern(/^(?:custom|upload:.+)$/)), name: Schema.String.check(Schema.isMinLength(1)), image: StoredImage.check(Schema.isMinLength(1)), }) export type UploadedWallpaper = typeof UploadedImage.Type -export const Preferences = Schema.Struct({ +const fields = { enabled: Schema.Boolean, - // Keep selections from old saves readable, even when no matching image exists. preset: Schema.String, - image: StoredImage, - imageName: Schema.optional(Schema.String), - images: Schema.optional(Schema.Array(UploadedImage)), - tint: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: appearanceControls.tint.min, maximum: appearanceControls.tint.max }))), - brightness: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: appearanceControls.brightness.min, maximum: appearanceControls.brightness.max }))), + images: Schema.Array(UploadedImage).check(Schema.makeFilter((images) => + new Set(images.map((image) => image.id)).size === images.length, + )), + tint: Schema.Int.check(Schema.isBetween({ minimum: appearanceControls.tint.min, maximum: appearanceControls.tint.max })), + brightness: Schema.Int.check(Schema.isBetween({ minimum: appearanceControls.brightness.min, maximum: appearanceControls.brightness.max })), fit: Schema.Literals(["cover", "contain"]), - slideshow: Schema.optional(Schema.Boolean), - duration: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: slideshowControls.min, maximum: slideshowControls.max }))), - transition: Schema.optional(Schema.Literals(["none", "fade"])), - // Keep old saves readable. Strength supplies the tint only until the user sets - // it explicitly; hidden no longer controls which wallpapers are available. - strength: Schema.Int.check(Schema.isBetween({ minimum: 5, maximum: 45 })), + slideshow: Schema.Boolean, + duration: Schema.Int.check(Schema.isBetween({ minimum: slideshowControls.min, maximum: slideshowControls.max })), + transition: Schema.Literals(["none", "fade"]), +} + +const SavedPreferences = Schema.Struct({ + ...fields, + images: Schema.optional(fields.images), + tint: Schema.optional(fields.tint), + brightness: Schema.optional(fields.brightness), + slideshow: Schema.optional(fields.slideshow), + duration: Schema.optional(fields.duration), + transition: Schema.optional(fields.transition), + image: Schema.optional(StoredImage), + imageName: Schema.optional(Schema.String), + strength: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 5, maximum: 45 }))), hidden: Schema.optional(Schema.Array(Schema.String)), }) +export const Preferences = SavedPreferences.pipe(Schema.decodeTo(Schema.Struct(fields), { + decode: SchemaGetter.transform((saved) => ({ + enabled: saved.enabled, + preset: saved.preset, + fit: saved.fit, + images: saved.image && !saved.images?.some((image) => image.id === "custom") + ? [{ id: "custom", name: saved.imageName || "Wallpaper", image: saved.image }, ...(saved.images ?? [])] + : saved.images ?? [], + tint: saved.tint ?? (saved.strength === undefined ? appearanceControls.tint.initial : 100 - saved.strength), + brightness: saved.brightness ?? appearanceControls.brightness.initial, + slideshow: saved.slideshow ?? false, + duration: saved.duration ?? slideshowControls.duration, + transition: saved.transition ?? slideshowControls.transition, + })), + encode: SchemaGetter.transform((settings) => settings), +})) + export type WallpaperPreferences = typeof Preferences.Type export const initial: WallpaperPreferences = { enabled: false, preset: "", - image: "", - strength: 100 - appearanceControls.tint.initial, + images: [], + tint: appearanceControls.tint.initial, + brightness: appearanceControls.brightness.initial, fit: "cover", + slideshow: false, + duration: slideshowControls.duration, + transition: slideshowControls.transition, +} + +function recover(schema: S, value: S["Type"]) { + const defaulted = Schema.withDecodingDefaultType(Effect.succeed(value))(schema) + return defaulted.pipe(Schema.catchDecoding(() => Effect.succeed(Option.some(value)))) } -export function wallpaperAppearance(settings: Pick) { +export const StoredPreferences = Schema.Struct({ + enabled: recover(fields.enabled, initial.enabled), + preset: recover(fields.preset, initial.preset), + fit: recover(fields.fit, initial.fit), + images: recover(SavedPreferences.fields.images, undefined), + tint: recover(SavedPreferences.fields.tint, undefined), + brightness: recover(SavedPreferences.fields.brightness, undefined), + slideshow: recover(SavedPreferences.fields.slideshow, undefined), + duration: recover(SavedPreferences.fields.duration, undefined), + transition: recover(SavedPreferences.fields.transition, undefined), + image: recover(SavedPreferences.fields.image, undefined), + 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 ?? 100 - settings.strength, - brightness: settings.brightness ?? appearanceControls.brightness.initial, + tint: settings.tint, + brightness: settings.brightness, } } diff --git a/src/render.test.ts b/src/render.test.ts index e7b7252..b1d9361 100644 --- a/src/render.test.ts +++ b/src/render.test.ts @@ -1,7 +1,7 @@ import { afterEach, expect, jest, spyOn, test } from "bun:test" -import { createRoot, createSignal } from "solid-js" +import { batch, createMemo, createRoot, createSignal } from "solid-js" import type { WallpaperChoice } from "./model" -import { createWallpaperImage } from "./render" +import { createWallpaperImage, createWallpaperVisibility } from "./render" const data = "data:image/png;base64,YWJj" const originalImage = Object.getOwnPropertyDescriptor(globalThis, "Image") @@ -10,7 +10,7 @@ let decodes: { resolve: () => void; reject: () => void }[] let urls: string[] let revoked: string[] -function fixture(duration = 0) { +function fixture(duration = 0, animateVisibility = false) { decodes = [] urls = [] revoked = [] @@ -26,14 +26,26 @@ function fixture(duration = 0) { 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) => { dispose = cleanup const [selected, setSelected] = createSignal() - select = (choice) => { setSelected(choice) } - image = createWallpaperImage(selected, async () => data, () => duration) + 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 source = visibility ? createMemo(() => enabled() ? selected() : visibility?.enabled() ? image.choice : undefined) : selected + select = (choice) => { + if (!visibility) { setSelected(choice); return } + batch(() => { if (choice) setSelected(choice); updateEnabled(!!choice) }) + } + image = createWallpaperImage(source, async () => data, () => duration) }) const choose = (id: string) => select({ id, title: id, version: "1", image: data }) - return { image, choose, select } + return { image, choose, select, setEnabled, setReducedMotion, visibility } } afterEach(() => { @@ -89,7 +101,7 @@ test("retains outgoing URLs until fades finish and releases every frame on clean expect(jest.getTimerCount()).toBe(0) }) -test("preserves the last readable image on failure and clears it when wallpaper is disabled", async () => { +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() @@ -119,3 +131,43 @@ test("aborts rapid selections without letting stale decodes replace the current expect(f.image.error).toBe("") expect(revoked).toContain("blob:test-0") }) + +test("holds the decoded wallpaper through off fades, reverses quick toggles, and cancels pending image changes", async () => { + jest.useFakeTimers() + const f = fixture(0, true) + f.choose("a") + expect(f.visibility?.fade()).toBeUndefined() + decodes[0].resolve() + await flush() + expect(f.visibility?.fade()?.show).toBe(true) + jest.advanceTimersByTime(800) + f.select(undefined) + expect(f.visibility?.fade()?.show).toBe(false) + expect(f.image.url).toBe("blob:test-0") + jest.advanceTimersByTime(400) + f.setEnabled(true) + expect(f.visibility?.fade()?.show).toBe(true) + expect(decodes).toHaveLength(1) + jest.advanceTimersByTime(800) + expect(revoked).toEqual([]) + f.choose("b") + f.select(undefined) + expect(decodes).toHaveLength(2) + decodes[1].resolve() + await flush() + expect(f.image.choice?.id).toBe("a") + jest.advanceTimersByTime(799) + expect(f.image.url).toBe("blob:test-0") + jest.advanceTimersByTime(1) + 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() + f.setReducedMotion(true) + expect(f.visibility?.fade()).toBeUndefined() + f.select(undefined) + expect(f.image.url).toBe("") + expect(jest.getTimerCount()).toBe(0) +}) diff --git a/src/render.ts b/src/render.ts index a0dfe6d..c831881 100644 --- a/src/render.ts +++ b/src/render.ts @@ -1,8 +1,9 @@ -import { createEffect, createMemo, createRenderEffect, onCleanup, untrack, type Accessor } from "solid-js" +import { batch, createEffect, createMemo, createRenderEffect, createSignal, on, onCleanup, untrack, type Accessor } from "solid-js" import { createStore } from "solid-js/store" import { decodeWallpaper, wallpaperBlob } from "./image" import { sameWallpaper, type WallpaperChoice } from "./model" import type { ThumbnailCache, ThumbnailLease } from "./thumbnail-cache" +import { wallpaperFadeDuration } from "./preferences" export type WallpaperReader = (image: WallpaperChoice, signal: AbortSignal) => Promise @@ -15,25 +16,51 @@ function imageSource(selected: Accessor) { export type WallpaperFrame = { url: string; width: number; height: number } +export function createWallpaperVisibility(enabled: Accessor, loaded: Accessor, reducedMotion: Accessor) { + const [paint, setPaint] = createSignal(enabled()) + const [fade, setFade] = createSignal<{ show: boolean; duration: number }>() + let timer: ReturnType | undefined + const cancel = () => { clearTimeout(timer); timer = undefined } + const start = (show: boolean) => { + cancel() + const duration = loaded() && !reducedMotion() ? wallpaperFadeDuration : 0 + batch(() => { + setFade(duration ? { show, duration } : undefined) + if (!duration && !show) setPaint(false) + }) + if (duration) timer = setTimeout(() => { + timer = undefined + batch(() => { setFade(undefined); if (!show) setPaint(false) }) + }, duration) + } + createEffect(on(() => [enabled(), reducedMotion()], ([show, reduced]) => { + cancel() + if (!show) return start(false) + setPaint(true) + if (reduced) setFade(undefined) + })) + createEffect(on(() => enabled() && loaded(), (show, previous) => { + if (show && !previous) start(true) + })) + onCleanup(cancel) + return { enabled: paint, fade } +} + export function createWallpaperImage(selected: Accessor, read: WallpaperReader, transition: Accessor = () => 0) { - const [state, setState] = createStore({ url: "", width: 0, height: 0, loading: false, error: "", previous: undefined as WallpaperFrame | undefined, transition: 0 }) - let current: WallpaperFrame | undefined - let previous: WallpaperFrame | undefined + const [state, setState] = createStore({ url: "", width: 0, height: 0, loading: false, error: "", choice: undefined as WallpaperChoice | undefined, previous: undefined as WallpaperFrame | undefined, transition: 0 }) let expiry: ReturnType | undefined const releasePrevious = () => { clearTimeout(expiry) expiry = undefined - if (previous) URL.revokeObjectURL(previous.url) - previous = undefined + if (state.previous) URL.revokeObjectURL(state.previous.url) setState({ previous: undefined, transition: 0 }) } onCleanup(() => { releasePrevious() - if (current) URL.revokeObjectURL(current.url) + if (state.url) URL.revokeObjectURL(state.url) }) const source = imageSource(selected) - createEffect(() => { - const choice = source() + createEffect(on(source, (choice) => { const controller = new AbortController() let url = "" onCleanup(() => { @@ -44,9 +71,12 @@ export function createWallpaperImage(selected: Accessor { @@ -58,12 +88,11 @@ export function createWallpaperImage(selected: Accessor 0) previous = current - else if (current) URL.revokeObjectURL(current.url) - current = { url, width: image.naturalWidth, height: image.naturalHeight } - // The frame now owns this URL. Source cleanup only releases pending reads. + const previous = state.url && duration > 0 ? { url: state.url, width: state.width, height: state.height } : undefined + if (state.url && !previous) URL.revokeObjectURL(state.url) + const current = { url, width: image.naturalWidth, height: image.naturalHeight } url = "" - setState({ ...current, previous, transition: previous ? duration : 0, loading: false, error: "" }) + setState({ ...current, choice, previous, transition: previous ? duration : 0, loading: false, error: "" }) if (previous) expiry = setTimeout(releasePrevious, duration) } catch (error) { if (url) URL.revokeObjectURL(url) @@ -71,7 +100,7 @@ export function createWallpaperImage(selected: Accessor [data-icon] use[href$="-outline-photo"]) { - grid-template-columns: minmax(0, 1fr) 20px; - row-gap: 4px; - - > [data-icon] { - display: none; - } - - > [data-content] { - display: contents; - } - - [data-title] { - grid-column: 1; - grid-row: 1; - } - - > [data-close-button] { - grid-column: 2; - grid-row: 1; - } - - [data-description] { - grid-column: 1 / -1; - grid-row: 2; - white-space: pre-line; - max-height: min(280px, calc(100dvh - 180px)); - overflow-y: auto; - overscroll-behavior: contain; - } -} - .opencode-wallpaper-gallery-section { display: grid; gap: 12px; @@ -54,6 +20,25 @@ width: 100%; } +.opencode-wallpaper-gallery-toggle-button { + padding: 6px 12px; + 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; + cursor: pointer; +} + +.opencode-wallpaper-gallery-toggle-button:hover { + 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)); @@ -228,7 +213,6 @@ } .opencode-wallpaper-slideshow { - --wallpaper-branch-offset: calc(var(--wallpaper-branch-center, 0px) - 1px); border-bottom: 0.5px solid var(--v2-border-border-base); } @@ -236,54 +220,12 @@ border-bottom: 0; } -.opencode-wallpaper-slideshow-description { - display: block; - position: relative; -} - -.opencode-wallpaper-slideshow-description[data-expanded]::after { - content: ""; - position: absolute; - inset-inline-start: var(--wallpaper-branch-offset, 0px); - top: 100%; - /* The native description's bottom margin is -3.5px. Fill the remaining row padding. */ - height: calc(var(--settings-list-row-padding, 20px) - 3.5px); - border-inline-start: 0.5px solid var(--v2-border-border-base); - pointer-events: none; -} - .opencode-wallpaper-slideshow-options { --settings-list-row-padding: 12px; - padding-inline-start: 30px; + margin-inline-start: 12px; + padding-inline-start: 18px; padding-bottom: 16px; - - > [data-component="settings-row"] { - position: relative; - - &::before, - &::after { - content: ""; - position: absolute; - inset-inline-start: calc(-30px + var(--wallpaper-branch-offset, 0px)); - pointer-events: none; - } - - &::before { - inset-block: 0; - border-inline-start: 0.5px solid var(--v2-border-border-base); - } - - &::after { - top: 50%; - width: calc(26px - var(--wallpaper-branch-offset, 0px)); - border-block-start: 0.5px solid var(--v2-border-border-base); - } - - &:last-child::before { - inset-block-end: auto; - height: 50%; - } - } + border-inline-start: 0.5px solid var(--v2-border-border-base); } .opencode-wallpaper-duration input { diff --git a/src/settings.tsx b/src/settings.tsx index 50023b3..2e7f709 100644 --- a/src/settings.tsx +++ b/src/settings.tsx @@ -6,6 +6,7 @@ import { uploadImage } from "./image" import { appearanceControls, appearanceKeys, slideshowControls, wallpaperAppearance, type WallpaperTransition } from "./preferences" import type { ThumbnailCache } from "./thumbnail-cache" import { WallpaperThumbnail } from "./thumbnail" +import { WallpaperGalleryToggle } from "./gallery-toggle" export function WallpaperSettings(props: { images: Accessor @@ -22,10 +23,8 @@ export function WallpaperSettings(props: { const [folderRequest, setFolderRequest] = createSignal() const [expanded, setExpanded] = createSignal(false) const [columns, setColumns] = createSignal(1) - const [branchOffset, setBranchOffset] = createSignal(0) const galleryId = createUniqueId() let gallery!: HTMLDivElement - let slideshowDescription!: HTMLSpanElement let fileInput!: HTMLInputElement const appearance = createMemo(() => wallpaperAppearance(settings.value)) const limit = () => columns() * 2 - 1 @@ -34,26 +33,15 @@ export function WallpaperSettings(props: { const measure = () => { const tracks = getComputedStyle(gallery).gridTemplateColumns setColumns(tracks === "none" ? 1 : tracks.trim().split(/\s+/).length) - const text = slideshowDescription.firstChild - if (text instanceof Text && text.length) { - const range = document.createRange() - range.setStart(text, 0) - range.setEnd(text, 1) - const letter = range.getBoundingClientRect() - const description = slideshowDescription.getBoundingClientRect() - const center = letter.left + letter.width / 2 - setBranchOffset(getComputedStyle(slideshowDescription).direction === "rtl" ? description.right - center : center - description.left) - } } const observer = new ResizeObserver(measure) observer.observe(gallery) - observer.observe(slideshowDescription) measure() onCleanup(() => observer.disconnect()) }) const cancelUpload = () => { request()?.abort(); setRequest(undefined) } onCleanup(() => { cancelUpload(); folderRequest()?.abort() }) - createRenderEffect(on(() => [settings.value.enabled, settings.value.preset, settings.value.image], cancelUpload, { defer: true })) + createRenderEffect(on(() => [settings.value.enabled, settings.value.preset], cancelUpload, { defer: true })) function select(choice: string) { cancelUpload() @@ -71,8 +59,8 @@ export function WallpaperSettings(props: { if (signal.aborted) return checkWallpaperDuplicate({ name: file.name, image: source }, settings.value, props.images()) settings.update((draft) => { - const id = `upload:${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}` - draft.images = [...(draft.images ?? []), { id, name: file.name, image: source }] + const id = `upload:${crypto.randomUUID()}` + draft.images.push({ id, name: file.name, image: source }) changeWallpaper(draft, id) }) } catch (error) { @@ -191,17 +179,12 @@ export function WallpaperSettings(props: { limit()}> @@ -220,12 +203,12 @@ export function WallpaperSettings(props: { }} /> -
+
+ {ctx.t("slideshow.description")} } @@ -247,7 +230,7 @@ export function WallpaperSettings(props: { > label={ctx.t("transition.title")} - value={settings.value.transition ?? slideshowControls.transition} + value={settings.value.transition} options={[ { value: "none", label: ctx.t("transition.none") }, { value: "fade", label: ctx.t("transition.fade") }, @@ -266,14 +249,14 @@ export function WallpaperSettings(props: { min={slideshowControls.min} max={slideshowControls.max} step="1" - value={settings.value.duration ?? slideshowControls.duration} + value={settings.value.duration} aria-label={ctx.t("duration.title")} onChange={(event) => { const input = event.currentTarget const value = input.valueAsNumber if (Number.isInteger(value) && value >= slideshowControls.min && value <= slideshowControls.max) { settings.update((draft) => { draft.duration = value }) - } else input.value = String(settings.value.duration ?? slideshowControls.duration) + } else input.value = String(settings.value.duration) }} /> diff --git a/src/slideshow.ts b/src/slideshow.ts index bc43daf..c302b16 100644 --- a/src/slideshow.ts +++ b/src/slideshow.ts @@ -1,6 +1,6 @@ import { batch, createEffect, createMemo, createSignal, on, onCleanup, type Accessor } from "solid-js" import { selectedWallpaper, type WallpaperChoice } from "./model" -import { slideshowControls, type WallpaperPreferences } from "./preferences" +import type { WallpaperPreferences } from "./preferences" export function nextWallpaper(current: string, images: readonly WallpaperChoice[]) { if (!images.length) return undefined @@ -26,7 +26,7 @@ export function createWallpaperSlideshow(settings: Accessor setAutomatic(nextWallpaper(current.id, images())?.id), (preferences.duration ?? slideshowControls.duration) * 1000) + const timer = setTimeout(() => setAutomatic(nextWallpaper(current.id, images())?.id), preferences.duration * 1000) onCleanup(() => clearTimeout(timer)) }) return { selected, reset } diff --git a/src/style.ts b/src/style.ts index 796eaef..657b8bb 100644 --- a/src/style.ts +++ b/src/style.ts @@ -1,5 +1,29 @@ import { wallpaperAppearance, 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" + settingsStyle.textContent = settings + canvasStyle.textContent = canvas + canvasStyle.disabled = true + document.head.append(settingsStyle, canvasStyle, imageStyle) + return { + update(variables: string) { + imageStyle.textContent = variables + canvasStyle.disabled = !variables + }, + dispose() { + settingsStyle.remove() + canvasStyle.remove() + imageStyle.remove() + }, + } +} + export const wallpaperPanels = '[data-slot="home-panel"], [data-slot="session-chat-panel"] > .bg-v2-background-bg-base, [data-component="new-session"]' export const wallpaperHeaders = ` @@ -57,7 +81,7 @@ export const wallpaperSurfaces = ` :is(${wallpaperPanels}) [data-wallpaper-backed] { isolation: isolate; - background: transparent; + background: var(--v2-background-bg-base); } [data-slot="session-chat-panel"] [data-session-title] > .bg-v2-background-bg-base, @@ -65,8 +89,6 @@ export const wallpaperSurfaces = ` position: relative; } - /* Old page-colored fades would leave bands over the image. The aligned header - copies conceal scrolling content without blurring or repainting a solid strip. */ [data-slot="session-chat-panel"] .session-header-fade { background: none; } @@ -108,9 +130,6 @@ export const wallpaperSurfaces = ` color: var(--v2-text-text-base); } - /* Counter-shadow paths fill the lower interiors of the letters. Keep those - transparent instead of turning them into gray rectangles. Only the inner - paint group changes; outer groups still control the lodger's animations. */ [data-component="new-session"] [data-component="new-session-wordmark"] { --icon-base: var(--v2-text-text-base); --icon-strong-base: var(--v2-text-text-base); @@ -122,8 +141,6 @@ export const wallpaperSurfaces = ` filter: drop-shadow(0 1px 2px var(--v2-background-bg-base)); } - /* The game's back pins and paddle use z-index -10 and -5. Keep the wallpaper - below them, and outline only the moving shapes rather than shading the arena. */ [data-component="new-session"] :is([data-slot="new-session-pins"], [data-slot="new-session-pins-popped"]) { filter: drop-shadow(0 1px 2px var(--v2-background-bg-base)); } @@ -137,8 +154,6 @@ export const wallpaperSurfaces = ` } ` -// Static rules are registered separately from the image variables so dragging a -// slider does not reparse the complete stylesheet on every input event. export const wallpaperCanvasStyle = wallpaperSurfaces + wallpaperLayers(`${wallpaperPanels}, :is(${wallpaperPanels}) [data-wallpaper-backed]`) export function wallpaperBackground(settings: WallpaperPreferences, image: string) { diff --git a/src/thumbnail-cache.test.ts b/src/thumbnail-cache.test.ts index 553aca7..39ec298 100644 --- a/src/thumbnail-cache.test.ts +++ b/src/thumbnail-cache.test.ts @@ -106,7 +106,7 @@ test("limits concurrent thumbnail generation", async () => { } finally { cache.dispose() } }) -test("retries failures and cancels late work on plugin shutdown", async () => { +test("allows a new request after failure and cancels late work on plugin shutdown", async () => { let loads = 0 const cache = createThumbnailCache(async () => { if (++loads === 1) throw new Error("image.decodeError") @@ -116,9 +116,9 @@ test("retries failures and cancels late work on plugin shutdown", async () => { const failed = cache.acquire(file) await expect(failed.ready).rejects.toThrow("image.decodeError") failed.release() - const retry = cache.acquire(file) - await retry.ready - retry.release() + const requested = cache.acquire(file) + await requested.ready + requested.release() expect(loads).toBe(2) } finally { cache.dispose() } diff --git a/src/thumbnail-cache.ts b/src/thumbnail-cache.ts index 2ac1e73..a9d52aa 100644 --- a/src/thumbnail-cache.ts +++ b/src/thumbnail-cache.ts @@ -1,3 +1,4 @@ +import { Effect, Semaphore } from "effect" import type { ThumbnailBlob } from "./image" import { sameWallpaper, type WallpaperChoice } from "./model" @@ -26,9 +27,8 @@ export function createThumbnailCache( const entries = new Map() const retired = new Set() const idle = new Map() - const queue = new Set() + const permits = Semaphore.makeUnsafe(concurrency) let idleBytes = 0 - let running = 0 let disposed = false function activate(entry: Entry) { @@ -48,7 +48,6 @@ export function createThumbnailCache( function discard(entry: Entry) { if (entry.retired) return activate(entry) - queue.delete(entry) if (entries.get(entry.choice.id) === entry) entries.delete(entry.choice.id) entry.retired = true entry.controller.abort() @@ -57,8 +56,6 @@ export function createThumbnailCache( else revoke(entry) } - // Track idle entries directly instead of scanning and allocating arrays on each - // tile release. Active tiles are pinned; only unused thumbnails can be evicted. function park(entry: Entry) { if (entry.users || entry.retired) return activate(entry) @@ -71,28 +68,20 @@ export function createThumbnailCache( } } - function drain() { - while (!disposed && running < concurrency && queue.size) { - const entry = queue.values().next().value! - queue.delete(entry) - running++ - void Promise.resolve().then(() => { - entry.controller.signal.throwIfAborted() - return load(entry.choice, entry.controller.signal) - }).then((thumbnail) => { - entry.controller.signal.throwIfAborted() - entry.value = { url: URL.createObjectURL(thumbnail.blob), width: thumbnail.width, height: thumbnail.height } - entry.bytes = thumbnail.blob.size - entry.resolve(entry.value) - park(entry) - }).catch((error: unknown) => { - entry.reject(error) - discard(entry) - }).finally(() => { - running-- - drain() - }) - } + function loadEntry(entry: Entry) { + void Effect.runPromise(permits.withPermit(Effect.tryPromise({ + try: (signal) => load(entry.choice, signal), + catch: (error) => error, + })), { signal: entry.controller.signal }).then((thumbnail) => { + entry.controller.signal.throwIfAborted() + entry.value = { url: URL.createObjectURL(thumbnail.blob), width: thumbnail.width, height: thumbnail.height } + entry.bytes = thumbnail.blob.size + entry.resolve(entry.value) + park(entry) + }).catch((error: unknown) => { + entry.reject(error) + discard(entry) + }) } function acquire(choice: WallpaperChoice): ThumbnailLease { @@ -103,17 +92,14 @@ export function createThumbnailCache( entry = undefined } if (!entry) { - let resolve!: Entry["resolve"] - let reject!: Entry["reject"] - const ready = new Promise((accept, fail) => { resolve = accept; reject = fail }) + const { promise: ready, resolve, reject } = Promise.withResolvers() entry = { choice: { ...choice }, controller: new AbortController(), ready, resolve, reject, users: 0, bytes: 0, retired: false } - queue.add(entry) + loadEntry(entry) } const current = entry activate(current) current.users++ entries.set(choice.id, current) - drain() let released = false return { value: current.value, @@ -140,7 +126,6 @@ export function createThumbnailCache( retired.clear() idle.clear() idleBytes = 0 - queue.clear() } signal?.addEventListener("abort", dispose, { once: true }) if (signal?.aborted) dispose() diff --git a/src/transition.ts b/src/transition.ts index 3efff28..91e55d5 100644 --- a/src/transition.ts +++ b/src/transition.ts @@ -16,6 +16,26 @@ export const wallpaperTransitionStyle = ` } ` +export function createWallpaperVisibilityAnimation() { + let animations: Animation[] = [] + const clear = () => { animations.forEach((animation) => animation.cancel()); animations = [] } + return { + fade(show: boolean, duration: number) { + const reversing = animations.length > 0 + const layers = [...document.querySelectorAll(`${wallpaperPanels}, ${wallpaperHeaders}`)].flatMap((element) => + ["::before", "::after"].map((pseudoElement) => ({ element, pseudoElement, + opacity: reversing ? Number(getComputedStyle(element, pseudoElement).opacity) : show ? 0 : 1 })), + ) + clear() + animations = layers.map(({ element, pseudoElement, opacity }) => element.animate( + [{ opacity }, { opacity: show ? 1 : 0 }], + { duration, easing: "ease-in-out", fill: "forwards", pseudoElement }, + )) + }, + clear, + } +} + // Keep tint and the interface still. Only the incoming image pseudo-element fades. export function fadeWallpaper(previous: WallpaperFrame, fit: "cover" | "contain", duration: number) { if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return () => {}