@gjsify/example-gtk-adwaita-storybook 0.46.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gjs.js CHANGED
@@ -78,7 +78,7 @@ if(globalThis.__gjsifyBundleUrl??=import.meta.url,Symbol.dispose||(Symbol.dispos
78
78
  </method>${e.length>0?`\n${e.join(`
79
79
  `)}`:``}
80
80
  </interface>
81
- </node>`}function isWin32(){return e.DIR_SEPARATOR===92}function defaultListenAddress(){return isWin32()?`nonce-tcp:host=127.0.0.1`:`unix:tmpdir=${e.get_tmp_dir()}`}var DevtoolsPeerServerError=class extends Error{constructor(e,t,n,r){super(e),this.address=t,this.reason=n,this.name=`DevtoolsPeerServerError`,this.cause=r}};function isAddressInUse(t){return t instanceof e.Error&&t.matches(r.io_error_quark(),r.IOErrorEnum.ADDRESS_IN_USE)}function unixSocketPath(e){if(!e.startsWith(`unix:`))return null;for(let t of e.slice(5).split(`,`)){let e=t.indexOf(`=`);if(!(e<0||t.slice(0,e)!==`path`))try{return decodeURIComponent(t.slice(e+1))}catch{return null}}return null}function inspectExistingSocket(e){try{if((r.File.new_for_path(e).query_info(`unix::mode`,r.FileQueryInfoFlags.NONE,null).get_attribute_uint32(`unix::mode`)&61440)!=49152)return`not-a-socket`}catch{return`not-a-socket`}let t=new r.SocketClient;t.set_timeout(2);let n;try{n=t.connect(r.UnixSocketAddress.new(e),null)}catch{return`dead`}return n.close(null),`live`}function clearReclaimableSocket(t){let n=unixSocketPath(t);if(!n||!e.file_test(n,e.FileTest.EXISTS))return;let i=inspectExistingSocket(n);if(i===`live`)throw new DevtoolsPeerServerError(`cannot listen on ${t}: another process is already listening there. Stop it, or point ${X} (or options.address) at a different socket — GJSIFY_DEVTOOLS_INSTANCE=<label> lets two devtools-enabled apps run side by side.`,t,`address-in-use`);if(i===`not-a-socket`)throw new DevtoolsPeerServerError(`cannot listen on ${t}: ${n} already exists and is not a socket, so it will NOT be removed. Point ${X} (or options.address) at a free path.`,t,`occupied-by-other-file`);try{r.File.new_for_path(n).delete(null)}catch(e){throw new DevtoolsPeerServerError(`cannot listen on ${t}: ${n} is a socket nothing listens on, but removing it failed (${e}). Delete it by hand, or point ${X} at a free path.`,t,`address-in-use`,e)}_.log(`[gjsify-devtools] reclaimed the stale socket ${n}: nothing was listening on it (an abnormal exit — Ctrl-C, SIGKILL, a crash — leaves the inode behind).`)}function flagsForAddress(e){return e.startsWith(`tcp:`)||e.startsWith(`nonce-tcp:`)?r.DBusServerFlags.NONE:r.DBusServerFlags.AUTHENTICATION_REQUIRE_SAME_USER}function startDevtoolsPeerServer(e,t,n){let i=n&&n!==``?n:defaultListenAddress();clearReclaimableSocket(i);let o;try{o=r.DBusServer.new_sync(i,flagsForAddress(i),r.dbus_generate_guid(),null,null)}catch(e){let t=isAddressInUse(e);throw new DevtoolsPeerServerError(t?`cannot listen on ${i}: the address is already in use (${e}). Stop whatever holds it, or point ${X} (or options.address) at a different address.`:`cannot listen on ${i}: ${e}. Check the address form — \`unix:path=/tmp/app.sock\`, \`unix:tmpdir=/tmp\` or \`nonce-tcp:host=127.0.0.1\`.`,i,t?`address-in-use`:`listen-failed`,e)}let s=new Set;o.connect(`new-connection`,(n,r)=>(s.add(r),r.connect(`closed`,()=>{e.unexport(r),s.delete(r)}),e.export(r,t),!0)),o.start();let c=!1;return{address:o.get_client_address(),objectPath:t,get connectionCount(){return s.size},stop(){if(!c){c=!0,o.stop();for(let t of s)e.unexport(t),!t.is_closed()&&t.close(null,(e,t)=>{try{e.close_finish(t)}catch{}});s.clear()}}}}function writeDevtoolsAddressFile(t,n){try{if(e.mkdir_with_parents(e.path_get_dirname(t),448),!e.file_set_contents(t,`${n}\n`))return null}catch(e){return _.error(`[gjsify-devtools] could not publish the peer address to ${t}: ${e}`),null}try{r.File.new_for_path(t).set_attribute_uint32(`unix::mode`,384,r.FileQueryInfoFlags.NONE,null)}catch(e){_.error(`[gjsify-devtools] could not restrict ${t} to the current user: ${e}`)}return t}function removeDevtoolsAddressFile(e){try{r.File.new_for_path(e).delete(null)}catch{}}function captureWidgetPng(e){let t=e.get_native()?.get_renderer();if(!t)return null;let r=e.get_width(),o=e.get_height();if(r<=0||o<=0)return null;let s=n.WidgetPaintable.new(e),c=n.Snapshot.new();s.snapshot(c,r,o);let l=c.to_node();if(!l)return null;let u=new i.Rect;u.init(0,0,r,o);let d=t.render_texture(l,u).save_to_png_bytes().get_data();return d?new Uint8Array(d):null}function dumpGSettings(e){let t=r.SettingsSchemaSource.get_default()?.lookup(e,!0);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`GSettings schema '${e}' is not installed`));let n=new r.Settings({settings_schema:t}),i={};for(let e of t.list_keys())i[e]=n.get_value(e).recursiveUnpack();return i}function parseWidgetPath(e){let t=e.split(`/`).filter(e=>e.length>0);if(t.length===0)return null;let n=t[0].match(/^toplevel:(\d+)$/);if(!n)return null;let r=[];for(let e of t.slice(1)){let t=e.match(/^child:(\d+)$/);if(!t)return null;r.push(Number(t[1]))}return{toplevel:Number(n[1]),children:r}}function buildWidgetPath(e,t){return[`toplevel:${e}`,...t.map(e=>`child:${e}`)].join(`/`)}function widgetType(e){return gtypeName(e)??`GtkWidget`}function gtypeName(e){let t=e;return typeof t?.$typeName==`string`&&t.$typeName.length>0?t.$typeName:t?.constructor?.$gtype?.name??null}function activateWidget(e){let t=e;if(typeof t.activate==`function`&&t.activate()===!0)return!0;let n=typeof t.get_parent==`function`?t.get_parent():null;if(n&&widgetType(n)===`GtkListBox`){let t=n,r=!1;return typeof t.select_row==`function`&&(t.select_row(e),r=!0),typeof t.emit==`function`&&(t.emit(`row-activated`,e),r=!0),r}return!1}function sendKeyToWidget(e,t,n){let r=e.observe_controllers(),i=!1;for(let e=0;e<r.get_n_items();e++){let o=r.get_item(e);gtypeName(o)===`GtkEventControllerKey`&&(o.emit(`key-pressed`,t,0,n),i=!0)}return i}function nthChild(e,t){let n=e.get_first_child(),r=0;for(;n&&r<t;)n=n.get_next_sibling(),r++;return r===t?n:null}function listToplevels(){let e=n.Window.get_toplevels(),t=e.get_n_items(),r=[];for(let n=0;n<t;n++){let t=e.get_item(n);t&&r.push({path:`toplevel:${n}`,type:widgetType(t),title:t.get_title?.()??null,mapped:t.get_mapped(),focused:t.is_active??!1})}return r}function resolveWidgetPath(e){let t=parseWidgetPath(e);if(!t)return null;let r=n.Window.get_toplevels().get_item(t.toplevel);if(!r)return null;for(let e of t.children)if(r=nthChild(r,e),!r)return null;return r}function parseWidgetSelector(e){let t=e.indexOf(`:`),n=(t<0?e:e.slice(0,t)).trim(),r=(t<0?``:e.slice(t+1)).trim();return!n&&!r?null:{type:n,cssClass:r}}function findWidgetPath(e,t,n){if(!e.get_visible()||!e.get_mapped())return null;let r=!t.type||widgetType(e)===t.type,i=!t.cssClass||e.get_css_classes().includes(t.cssClass);if(r&&i)return n;let o=e.get_first_child(),s=0;for(;o;){let e=findWidgetPath(o,t,`${n}/child:${s}`);if(e)return e;o=o.get_next_sibling(),s++}return null}function dumpTree(e,t,n){let r={path:n,type:widgetType(e),name:e.get_name()||null,cssClasses:e.get_css_classes(),mapped:e.get_mapped(),visible:e.get_visible(),children:[]};if(t<=0)return r;let i=e.get_first_child(),o=0;for(;i;)r.children.push(dumpTree(i,t-1,`${n}/child:${o}`)),i=i.get_next_sibling(),o++;return r}function jsonSafe(e){let t=typeof e;return e==null||t===`string`||t===`number`||t===`boolean`?e??null:`[${t}]`}function getWidgetProperty(e,t){let n=e,r=t.replace(/-/g,`_`),i=t.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase());for(let e of[t,r,i])if(e in n)return jsonSafe(n[e])}function childIndex(e,t){let n=e.get_first_child(),r=0;for(;n;){if(n===t)return r;n=n.get_next_sibling(),r++}return-1}function pathOfWidget(e){let t=[],r=e,i=r.get_parent();for(;i;){let e=childIndex(i,r);if(e<0)return null;t.unshift(e),r=i,i=r.get_parent()}let o=n.Window.get_toplevels(),s=o.get_n_items();for(let e=0;e<s;e++)if(o.get_item(e)===r)return buildWidgetPath(e,t);return null}function isActiveWindowScope(e){return!e||e===`window`||e===`active`}function frameDelay(t){return new Promise(n=>{e.timeout_add(e.PRIORITY_DEFAULT,t,()=>(n(),e.SOURCE_REMOVE))})}async function captureWidgetWhenRenderable(e,t=12,n=50){for(let r=0;r<t;r++){let t=captureWidgetPng(e);if(t)return t;await frameDelay(n)}return captureWidgetPng(e)}var DevtoolsService=class{constructor(e,t){this._app=e,this._options=t,this._exported=new Map,this._peer=null,this._addressFile=null,this._kinds=new Map,this._extensions=t.extend??[];for(let[e,t]of Object.entries(bt))this._kinds.set(e,t);for(let e of this._extensions){for(let[t,n]of Object.entries(e.methodKinds))this._kinds.set(t,n);for(let[t,n]of Object.entries(e.handlers)){let e=n;this[t]=(...n)=>(this._guard(t),e(...n))}}}export(e,t){if(this._exported.has(e))return;let n=buildDevtoolsIfaceXml(this._extensions.flatMap(e=>e.methodsXml??[])),i=r.DBusExportedObject.wrapJSObject(n,this);i.export(e,t),this._exported.set(e,i)}unexport(e){if(e){this._exported.get(e)?.unexport(),this._exported.delete(e);return}for(let e of this._exported.values())e.unexport();this._exported.clear(),this._peer?.stop(),this._peer=null,this._addressFile&&=(removeDevtoolsAddressFile(this._addressFile),null)}attachPeerServer(e,t){this._peer=e,this._addressFile=t??null}get peerAddress(){return this._peer?.address??null}get addressFile(){return this._addressFile}GetStatus(){let e=this._app.get_active_window(),t={appId:this._app.get_application_id()??`unknown`,instance:this._options.instance??`default`,activeWindow:e?{id:e.get_name()||`window`,title:e.get_title()??``,mapped:e.get_mapped()}:null,toplevelCount:n.Window.get_toplevels().get_n_items(),focusedWidget:null,paused:this._isPaused()};for(let e of this._extensions){let n=e.contributeStatus?.();n&&Object.assign(t,n)}return JSON.stringify(t)}async ScreenshotAsync(t,n){try{let r=typeof t?.[0]==`string`?t[0]:``,i=await this._captureScopePng(r);n.return_value(new e.Variant(`(ay)`,[i]))}catch(e){n.return_dbus_error(`org.gjsify.Devtools.Error.Screenshot`,e instanceof Error?e.message:String(e))}}async _captureScopePng(e){let t=this._resolveRootWidget(e);if(!t){if(isActiveWindowScope(e))return new Uint8Array;throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`))}let r=captureWidgetPng(t.widget);if(!r){let e=t.widget.get_root();e instanceof n.Window&&e.present(),r=await captureWidgetWhenRenderable(t.widget)}return r??new Uint8Array}ListActions(){let e={app:describeActions(this._actionGroup(`app`)),win:describeActions(this._actionGroup(`win`))};return JSON.stringify(e)}ActivateAction(e,t,n){this._guard(`ActivateAction`);let r=this._scope(e);activateAction(this._requireGroup(r,t),t,this._parseValue(n))}ChangeActionState(e,t,n){this._guard(`ChangeActionState`);let r=this._scope(e);changeActionState(this._requireGroup(r,t),t,this._parseValue(n))}PresentWindow(){this._app.get_active_window()?.present()}ResizeWindow(e,t){this._guard(`ResizeWindow`);let n=this._app.get_active_window();if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no active window to resize`));let r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(t));return n.is_maximized()&&n.unmaximize(),n.is_fullscreen()&&n.unfullscreen(),n.set_default_size(r,i),[r,i]}ListToplevels(){return JSON.stringify(listToplevels())}DumpTree(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e||`active window`}'`));return JSON.stringify(dumpTree(n.widget,t>0?t:8,n.path))}GetProperty(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));let r=getWidgetProperty(n.widget,t);if(r===void 0)throw Error(formatDbusErrorMessage(`not-found`,`widget has no property '${t}'`));return JSON.stringify(r)}GetFocused(){let e=this._app.get_active_window(),t=e?e.get_focus():null;return JSON.stringify(t?{path:pathOfWidget(t),name:t.get_name()||null,type:widgetType(t)}:null)}ActivateWidget(e){this._guard(`ActivateWidget`);let t=this._resolveRootWidget(e);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));return activateWidget(t.widget)}FindWidget(e){let t=parseWidgetSelector(e);if(!t)throw Error(formatDbusErrorMessage(`invalid-params`,`empty selector '${e}'`));let n=this._resolveRootWidget(``);return n?findWidgetPath(n.widget,t,n.path)??``:``}SendKey(e,t){this._guard(`SendKey`);let[r,i,o]=n.accelerator_parse(e);if(!r)throw Error(formatDbusErrorMessage(`invalid-params`,`cannot parse accelerator '${e}'`));let s;if(s=t?this._resolveRootWidget(t)?.widget??null:this._app.get_active_window()?.get_focus()??null,!s)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${t||`focus`}'`));return sendKeyToWidget(s,i,o??0)}DumpGSettings(e){return JSON.stringify(dumpGSettings(e))}DumpCss(){return JSON.stringify(dumpCss())}SwapCss(e,t){return this._guard(`SwapCss`),swapCss(e,t)}_resolveRootWidget(e){if(isActiveWindowScope(e)){let e=this._app.get_active_window();return e?{widget:e,path:pathOfWidget(e)??`toplevel:0`}:null}let t=resolveWidgetPath(e);return t?{widget:t,path:e}:null}_isPaused(){return this._options.paused?.()??!1}_guard(e){let t=this._kinds.get(e);if(!t)throw Error(formatDbusErrorMessage(`internal`,`unclassified devtools method '${e}'`));if(t===`mutating`&&this._isPaused())throw Error(formatDbusErrorMessage(`paused`,`${e} rejected — external control is paused. Read-only methods keep working.`))}_scope(e){return e===`app`?`app`:`win`}_actionGroup(e){if(e===`app`)return this._app;if(this._options.winActionGroup)return this._options.winActionGroup;let t=this._app.get_active_window();return t instanceof n.ApplicationWindow?t:null}_requireGroup(e,t){let n=this._actionGroup(e);if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no '${e}' action group`));if(!n.has_action(t))throw Error(formatDbusErrorMessage(`not-found`,`unknown action ${e}.${t}`));return n}_parseValue(e){if(!e||e===`null`)return null;try{return JSON.parse(e)}catch{throw Error(formatDbusErrorMessage(`invalid-params`,`value_json is not valid JSON: ${e}`))}}};const xt=`DBUS_SESSION_BUS_ADDRESS`,St=new Set;function envEnabled(){return isDevtoolsEnabledValue(e.getenv(`GJSIFY_DEVTOOLS`))}function envValue(t){let n=e.getenv(t);return n&&n!==``?n:null}function sessionBusUsable(){if(!envValue(xt))return!1;try{return r.bus_get_sync(r.BusType.SESSION,null),!0}catch{return!1}}function chooseDevtoolsTransport(e){return e.requestedAddress?{kind:`peer`,address:e.requestedAddress,reason:`requested`}:e.hasAppConnection?{kind:`session-bus`}:e.sessionBusUsable?{kind:`unregistered`}:{kind:`peer`,address:null,reason:`no-session-bus`}}function describeMissingConnection(e,t){return e?t?`[gjsify-devtools] the session bus answers but this application is not registered on it yet — call installDevtools() from the GtkApplication "startup" handler (the bus connection and object path exist only after registration).`:`[gjsify-devtools] ${xt} is set (${e}) but no bus answers there — using the bus-less peer transport instead. On macOS this is the usual state: Homebrew's dbus listens on launchd, so the advertised address only works while that socket is live.`:`[gjsify-devtools] this machine has no session bus (${xt} is unset) — using the bus-less peer transport instead. Point the bridge at the address below, or set ${X} on both the app and \`gjsify debug\` to pin it yourself.`}function installDevtools(e,t={}){if(!(t.enabled??envEnabled()))return null;let n=t.instance??envValue(`GJSIFY_DEVTOOLS_INSTANCE`)??void 0,r=new DevtoolsService(e,{...t,instance:n});try{return exportDevtools(e,r,t,n)}catch(e){return r.unexport(),_.error(`[gjsify-devtools] devtools stayed OFF, the app is unaffected — ${describeInstallFailure(e)}`),null}}function describeInstallFailure(e){return e instanceof DevtoolsPeerServerError||e instanceof Error?e.message:String(e)}function exportDevtools(t,n,r,i){let o=t.get_is_registered(),s=o?t.get_dbus_connection():null,c=o?t.get_dbus_object_path():null,l=envValue(xt),u=!!(s&&c),d=u||sessionBusUsable(),f=chooseDevtoolsTransport({requestedAddress:r.address??envValue(X),hasAppConnection:u,sessionBusUsable:d}),p=t.get_application_id()??`unknown`,m=`${c??appIdToObjectPath(p)}/devtools`;if((f.kind===`unregistered`||f.kind===`peer`&&f.reason===`no-session-bus`)&&_.error(describeMissingConnection(l,d)),f.kind===`session-bus`&&s)n.export(s,m),_.log(`[gjsify-devtools] exported ${yt} at ${m} (dest ${p})`);else if(f.kind===`peer`){let r=startDevtoolsPeerServer(n,m,f.address??void 0),o=writeDevtoolsAddressFile(devtoolsAddressFilePath(e.get_user_runtime_dir(),p,i),r.address);n.attachPeerServer(r,o),_.log(`[gjsify-devtools] exported ${yt} at ${m} (peer address ${r.address}${o?`, published to ${o}`:``})`),o&&t.connect(`shutdown`,()=>removeDevtoolsAddressFile(o))}return St.add(n),n}const Ct=[`AdwNavigationSplitView`,`GtkListBox`,`AdwOverlaySplitView`];function probeEnabled(){let t=e.getenv(`GJSIFY_STORYBOOK_PROBE`);if(t==null)return!1;let n=t.toLowerCase();return n!==``&&n!==`0`&&n!==`false`}function collectTypes(e,t){t.add(e.type);for(let n of e.children)collectTypes(n,t)}function installStorybookProbe(t,n,r={}){let i=r.requireChrome??Ct,o=r.out??e.getenv(`GJSIFY_STORYBOOK_PROBE_OUT`)??void 0,s=r.timeoutMs??8e3,c=r.storyWidget??e.getenv(`GJSIFY_STORYBOOK_PROBE_STORY_WIDGET`)??void 0,l=n.controller.listStories(),u=[...new Set(l.map(e=>e.category))],d=r.story??e.getenv(`GJSIFY_STORYBOOK_PROBE_STORY`)??l[0]?.title,f=d?n.openStoryByTitle(d):!1,p=n.activeStory,m=new Set;collectTypes(dumpTree(n,60,`toplevel:0`),m);let h=i.filter(e=>!m.has(e)),g=new Set;p&&collectTypes(dumpTree(p,60,`story`),g);let v=g.size,ee=c?g.has(c):null,finish=n=>{let r=JSON.stringify(n);if(n.ok)_.log(`STORYBOOK PROBE: PASS ${r}`);else{_.error(`STORYBOOK PROBE: FAIL ${r}`);try{typeof process<`u`&&(process.exitCode=1)}catch{}}if(o)try{e.file_set_contents(o,JSON.stringify(n,null,2))}catch{}t.quit()},te=0;e.timeout_add(e.PRIORITY_DEFAULT,100,()=>{te+=100;let t=captureWidgetPng(n),r=n.get_width()>0&&n.get_height()>0;if(!t&&!(te>=s))return e.SOURCE_CONTINUE;let o=p?captureWidgetPng(p):null,m=l.length>=1&&u.length>=1&&h.length===0&&f&&p!=null&&v>1,_;return l.length<1?_=`no stories registered`:u.length<1?_=`no categories`:h.length>0?_=`chrome missing: ${h.join(`, `)}`:!f||p==null?_=`could not open story: ${d??`(none)`}`:v<=1&&(_=`opened story rendered an empty subtree`),m&&c&&!g.has(c)&&(m=!1,_=`story widget ${c} not found in the opened story subtree`),m&&r&&(!t||t.length===0)&&(m=!1,_=`window realized (${n.get_width()}x${n.get_height()}) but the GSK capture was empty`),finish({ok:m,reason:_,stories:l.length,categories:u,opened:f,activeStory:p?p.meta.title:null,requiredChrome:i,missingChrome:h,storySubtreeWidgets:v,storyWidgetPresent:ee,windowRealized:r,windowPngBytes:t?t.length:0,storyPngBytes:o?o.length:0}),e.SOURCE_REMOVE})}const wt={UNKNOWN:0,CUSTOM:1,GPL_2_0:2,GPL_3_0:3,LGPL_2_1:4,LGPL_3_0:5,BSD:6,MIT_X11:7,ARTISTIC:8,GPL_2_0_ONLY:9,GPL_3_0_ONLY:10,LGPL_2_1_ONLY:11,LGPL_3_0_ONLY:12,AGPL_3_0:13,AGPL_3_0_ONLY:14,BSD_3:15,APACHE_2_0:16,MPL_2_0:17,"0BSD":18};wt.GPL_2_0_ONLY,wt.GPL_3_0_ONLY,wt.UNKNOWN;const Tt=[`blue`,`teal`,`green`,`yellow`,`orange`,`red`,`pink`,`purple`,`slate`],Et={blue:`#3584e4`,teal:`#2190a4`,green:`#3a944a`,yellow:`#c88800`,orange:`#ed5b00`,red:`#e62d42`,pink:`#d56199`,purple:`#9141ac`,slate:`#6f8396`};function parseHex(e){let t=/^#([0-9a-f]{6})$/i.exec(e.trim());if(!t)return null;let n=Number.parseInt(t[1],16);return[(n>>16&255)/255,(n>>8&255)/255,(n&255)/255]}function toHex(e,t,n){let channel=e=>Math.round(Math.min(1,Math.max(0,e))*255).toString(16).padStart(2,`0`);return`#${channel(e)}${channel(t)}${channel(n)}`}const toLinear=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,fromLinear=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055;function linearToOklab(e,t,n){let r=Math.cbrt(.4122214708*e+.5363325363*t+.0514459929*n),i=Math.cbrt(.2119034982*e+.6806995451*t+.1073969566*n),o=Math.cbrt(.0883024619*e+.2817188376*t+.6299787005*n);return[.2104542553*r+.793617785*i-.0040720468*o,1.9779984951*r-2.428592205*i+.4505937099*o,.0259040371*r+.7827717662*i-.808675766*o]}function oklabToLinear(e,t,n){let r=(e+.3963377774*t+.2158037573*n)**3,i=(e-.1055613458*t-.0638541728*n)**3,o=(e-.0894841775*t-1.291485548*n)**3;return[4.0767416621*r-3.3077115913*i+.2309699292*o,-1.2684380046*r+2.6097574011*i-.3413193965*o,-.0041960863*r-.7034186147*i+1.707614701*o]}function adwaitaStandaloneColor(e,t){let n=parseHex(e);if(!n)return e;let[r,i,o]=linearToOklab(toLinear(n[0]),toLinear(n[1]),toLinear(n[2])),[s,c,l]=oklabToLinear(t?Math.max(r,.85):Math.min(r,.5),i,o);return toHex(fromLinear(s),fromLinear(c),fromLinear(l))}function adwaitaAccentBgColor(e){return Et[e]}function adwaitaAccentColor(e,t){return adwaitaStandaloneColor(Et[e],t)}Math.PI*.35,Math.PI*.015,Math.PI*.9;const Dt=Math.PI*.9,Ot=Math.PI*.7,kt=Math.PI*1.1,At=Math.PI*1.35,jt=Dt+kt+At-Ot;53*Math.PI*2/jt,kt-Ot/2;const Mt={system:`Follow system`,light:`Light`,dark:`Dark`},Nt={blue:`Blue`,teal:`Teal`,green:`Green`,yellow:`Yellow`,orange:`Orange`,red:`Red`,pink:`Pink`,purple:`Purple`,slate:`Slate`};var StorybookAppearance=class{constructor(){this._provider=null,this._applying=!1,this._styleManager=o.StyleManager.get_default(),this.settings=new StorybookSettings(()=>this._styleManager.get_dark()),this.settings.subscribe(e=>this._apply(e)),this._styleManager.connect(`notify::dark`,()=>this.settings.systemChanged()),this._apply(this.settings.state)}_apply(e){if(!this._applying){this._applying=!0;try{this._styleManager.set_color_scheme(e.colorScheme===`light`?o.ColorScheme.FORCE_LIGHT:e.colorScheme===`dark`?o.ColorScheme.FORCE_DARK:o.ColorScheme.DEFAULT),this._applyAccent(this.settings.resolvedAccent)}finally{this._applying=!1}}}_applyAccent(e){let r=t.Display.get_default();if(!r)return;if(!this._provider){if(!e)return;this._provider=new n.CssProvider,n.StyleContext.add_provider_for_display(r,this._provider,n.STYLE_PROVIDER_PRIORITY_APPLICATION)}if(!e){this._provider.load_from_string(``);return}let i=adwaitaAccentBgColor(e),o=adwaitaAccentColor(e,this.settings.resolvedDark);this._provider.load_from_string(`:root { --accent-bg-color: ${i}; --accent-color: ${o}; }`)}};function buildSwatch(e,t,r){let i=new n.CheckButton({tooltip_text:t,halign:n.Align.CENTER,valign:n.Align.CENTER,focus_on_click:!1});for(let t of e)i.add_css_class(t);return i.update_property([n.AccessibleProperty.LABEL],[t]),r&&i.set_group(r),i}function buildSwatchCard(e=!1){let t=new o.WrapBox({align:.5,child_spacing:8,line_spacing:8,margin_top:12,margin_bottom:12,margin_start:12,margin_end:12}),n=new o.Bin({child:t,hexpand:!0});return n.add_css_class(`card`),e&&n.add_css_class(`storybook-card-attached`),{card:n,row:t}}function buildAppearanceDialog(e){let t=e.settings,r=new o.PreferencesPage,i=new o.PreferencesGroup({title:`Style`}),{card:s,row:c}=buildSwatchCard(),l=null,u=new Map;for(let e of gt){let n=buildSwatch([`storybook-swatch`,`storybook-scheme-swatch`,`storybook-scheme-${e}`],Mt[e],l);l??=n,n.set_active(t.colorScheme===e),n.connect(`toggled`,()=>{n.get_active()&&(t.colorScheme=e)}),u.set(e,n),c.append(n)}i.add(s),r.add(i);let d=new o.PreferencesGroup({title:`Accent colour`});d.add_css_class(`storybook-attached-group`);let f=new o.SwitchRow({title:`Use a custom accent colour`,subtitle:`Off follows the desktop, which owns the accent`,active:t.accentMode===`custom`});d.add(f);let{card:p,row:m}=buildSwatchCard(!0),h=null,g=new Map;for(let e of Tt){let r=buildSwatch([`storybook-swatch`],Nt[e],h);h??=r,r.set_active(t.accent===e);let i=new n.CssProvider;i.load_from_string(`checkbutton { background-color: ${adwaitaAccentBgColor(e)}; }`),r.get_style_context().add_provider(i,n.STYLE_PROVIDER_PRIORITY_APPLICATION),r.connect(`toggled`,()=>{r.get_active()&&(t.accent=e)}),g.set(e,r),m.append(r)}m.set_sensitive(t.accentMode===`custom`),f.connect(`notify::active`,()=>{t.accentMode=f.get_active()?`custom`:`system`}),d.add(p),r.add(d),t.subscribe(e=>{let t=u.get(e.colorScheme);t&&!t.get_active()&&t.set_active(!0);let n=g.get(e.accent);n&&!n.get_active()&&n.set_active(!0);let r=e.accentMode===`custom`;f.get_active()!==r&&f.set_active(r),m.set_sensitive(r)});let _=new o.PreferencesDialog({title:`Appearance`});return _.add(r),_}function adwControlWidgetFactory(){return{text(e,t){let n=new o.EntryRow({title:e});t&&n.set_tooltip_text(t);let r=null;return n.connect(`changed`,()=>r?.(n.get_text())),{node:n,get:()=>n.get_text(),set:e=>n.set_text(e),onChange:e=>{r=e}}},boolean(e,t){let n=new o.SwitchRow({title:e,subtitle:t??``}),r=null;return n.connect(`notify::active`,()=>r?.(n.get_active())),{node:n,get:()=>n.get_active(),set:e=>n.set_active(e),onChange:e=>{r=e}}},number(e){let t=o.SpinRow.new_with_range(e.min??0,e.max??100,e.step??1);t.set_title(e.label||e.name),e.description&&t.set_subtitle(e.description);let n=null;return t.connect(`changed`,()=>n?.(t.get_value())),{node:t,get:()=>t.get_value(),set:e=>t.set_value(e),onChange:e=>{n=e}}},range(e){return buildRangeWidget(e)},select(e){return buildSelectWidget(e)},color(e,t){return buildColorWidget(e,t)}}}function buildRangeWidget(e){let t=e.min??0,r=e.max??100,i=e.step??1,o=typeof e.min==`number`?e.min:0,s=Number.isInteger(i)&&Number.isInteger(o),c=new n.Adjustment({lower:t,upper:r,step_increment:i,value:o});c.step_increment=i;let l=new n.ListBoxRow({selectable:!1,activatable:!1});l.add_css_class(`story-range-row`);let u=new n.Box({orientation:n.Orientation.VERTICAL,spacing:6,margin_top:12,margin_bottom:12,margin_start:12,margin_end:12}),d=new n.Box({orientation:n.Orientation.HORIZONTAL,spacing:12}),f=new n.Label({label:e.label||e.name,halign:n.Align.START,hexpand:!0,ellipsize:3});f.add_css_class(`heading`);let formatValue=e=>s?String(Math.round(e)):e.toFixed(2),p=new n.Label({label:formatValue(o),halign:n.Align.END});if(p.add_css_class(`numeric`),p.add_css_class(`dim-label`),d.append(f),d.append(p),u.append(d),e.description){let t=new n.Label({label:e.description,halign:n.Align.START,xalign:0,wrap:!0,max_width_chars:32});t.add_css_class(`caption`),t.add_css_class(`dim-label`),u.append(t)}let m=new n.Scale({orientation:n.Orientation.HORIZONTAL,adjustment:c,draw_value:!1,hexpand:!0}),h=null,g=!1;return m.connect(`value-changed`,()=>{if(g)return;let e=m.get_value();if(s){let t=Math.round(e);if(t!==e){m.set_value(t);return}e=t}p.set_label(formatValue(e)),h?.(e)}),u.append(m),l.set_child(u),{node:l,get:()=>m.get_value(),set:e=>{g=!0,m.set_value(e),g=!1,p.set_label(formatValue(e))},onChange:e=>{h=e}}}function buildSelectWidget(e){let t=e.options??[],r=n.StringList.new(t.map(e=>e.label)),i=new o.ComboRow({title:e.label||e.name,subtitle:e.description??``,model:r}),s=null;return i.connect(`notify::selected`,()=>s?.(i.get_selected())),{node:i,get:()=>i.get_selected(),set:e=>i.set_selected(e),onChange:e=>{s=e}}}function buildColorWidget(e,r){let i=new o.ActionRow({title:e,subtitle:r??``}),s=new n.ColorDialogButton({dialog:new n.ColorDialog({title:e}),valign:n.Align.CENTER});i.add_suffix(s),i.set_activatable_widget(s);let channel=e=>Math.round(Math.max(0,Math.min(1,e))*255).toString(16).padStart(2,`0`),rgbaToHex=e=>`#${channel(e.red)}${channel(e.green)}${channel(e.blue)}`,c=null,l=!1;return s.connect(`notify::rgba`,()=>{l||c?.(rgbaToHex(s.get_rgba()))}),{node:i,get:()=>rgbaToHex(s.get_rgba()),set:e=>{let n=new t.RGBA;n.parse(e)&&(l=!0,s.set_rgba(n),l=!1)},onChange:e=>{c=e}}}var Pt=class StorybookWindow extends o.ApplicationWindow{static{s.registerClass({GTypeName:`StorybookWindow`},StorybookWindow)}constructor(e){super(e),this._appearance=new StorybookAppearance,this._controlRows=[],this._rowByTitle=new Map,this._onSelect=null,this._suppressSelect=!1,this.set_default_size(1200,800),this.set_size_request(360,320),this.set_title(`Storybook`),this._buildUI(),this._controller=new StorybookController(this,e=>this._buildControls(e)),this._sidebar_list.connect(`row-selected`,this._onRowSelected.bind(this)),this._show_controls_button.connect(`toggled`,this._onToggleControls.bind(this)),this._controls_split_view.set_show_sidebar(!0)}_onRowSelected(e,t){if(this._suppressSelect||!t)return;let n=t;n.storyWidget&&this._onSelect?.(n.storyWidget)}get controller(){return this._controller}_buildControls(e){let t=e.meta.controls;if(!Array.isArray(t))return[];let n=adwControlWidgetFactory(),r=[];for(let i of t){if(!i?.name||!i?.type){_.warn(`Invalid control configuration:`,i);continue}let t=bindControl(e,i,n);t&&r.push(t)}return r}_buildUI(){this._sidebar_list=new n.ListBox({selection_mode:n.SelectionMode.SINGLE}),this._sidebar_list.add_css_class(`navigation-sidebar`);let e=new n.ScrolledWindow({hexpand:!0,vexpand:!0,child:this._sidebar_list}),t=new o.HeaderBar({title_widget:new o.WindowTitle({title:`Stories`}),show_end_title_buttons:!1}),r=new o.ToolbarView({content:e,top_bar_style:o.ToolbarStyle.FLAT});r.add_top_bar(t);let i=new o.NavigationPage({title:`Stories`,tag:`stories`,child:r});this._content_area=new o.Bin({hexpand:!0,vexpand:!0});let s=new n.ScrolledWindow({hexpand:!0,vexpand:!0,child:this._content_area});s.add_css_class(`sb-preview-area`),this._control_panel=new o.PreferencesGroup({title:`Controls`});let c=new o.PreferencesPage;c.add(this._control_panel);let l=new n.ScrolledWindow({vexpand:!0,child:c});this._controls_split_view=new o.OverlaySplitView({show_sidebar:!0,sidebar_position:n.PackType.END,min_sidebar_width:280,max_sidebar_width:360,content:s,sidebar:l,css_classes:[`storybook-controls`]}),this._preview_title=new o.WindowTitle({title:`Preview`}),this._show_controls_button=new n.ToggleButton({icon_name:`sidebar-show-right-symbolic`,tooltip_text:`Toggle Controls`,active:!0});let u=new o.HeaderBar({title_widget:this._preview_title});u.pack_end(this._show_controls_button);let d=new n.Button({icon_name:`applications-graphics-symbolic`,tooltip_text:`Appearance`});d.connect(`clicked`,()=>buildAppearanceDialog(this._appearance).present(this)),u.pack_end(d);let f=new o.ToolbarView({content:this._controls_split_view,top_bar_style:o.ToolbarStyle.FLAT});f.add_top_bar(u);let p=new o.NavigationPage({title:`Preview`,tag:`preview`,child:f});this._main_split_view=new o.NavigationSplitView({min_sidebar_width:220,max_sidebar_width:320,sidebar:i,content:p}),this.set_content(this._main_split_view);let m=o.BreakpointCondition.parse(`max-width: 720sp`);if(m){let e=new o.Breakpoint({condition:m});e.connect(`apply`,()=>{this._main_split_view.collapsed=!0,this._controls_split_view.collapsed=!0}),e.connect(`unapply`,()=>{this._main_split_view.collapsed=!1,this._controls_split_view.collapsed=!1}),this.add_breakpoint(e)}}_onToggleControls(e){this._controls_split_view.set_show_sidebar(e.get_active())}populateSidebar(e){this._controller.mount(e,!0)}renderSidebar(e,t){this._onSelect=t,this._suppressSelect=!0,this._clearSidebar(),this._rowByTitle.clear();for(let t of e){this._addCategoryToSidebar(t.category);for(let{instance:e,name:n}of t.stories)this._addStoryToSidebar(e,n)}this._suppressSelect=!1}markSelected(e){let t=this._rowByTitle.get(e);t&&this._sidebar_list.get_selected_row()!==t&&(this._suppressSelect=!0,this._sidebar_list.select_row(t),this._suppressSelect=!1)}setPreviewTitle(e){this._preview_title.set_title(e)}showPreview(e){this._content_area.set_child(e),this._main_split_view.get_collapsed()&&this._main_split_view.set_show_content(!0)}renderControls(e){this._clearControlPanel();for(let t of e){let e=t.view;e instanceof o.PreferencesRow&&e.set_use_markup(!1),this._control_panel.add(e),this._controlRows.push(e)}this._show_controls_button.set_active(!0)}_clearSidebar(){let e=this._sidebar_list.get_first_child();for(;e;){let t=e.get_next_sibling();e.unparent(),e=t}}_addCategoryToSidebar(e){let t=new n.ListBoxRow({selectable:!1}),r=new n.Label({label:e,halign:n.Align.START,margin_top:10,margin_bottom:4,margin_start:12,margin_end:12});r.add_css_class(`heading`),r.add_css_class(`dim-label`),t.set_child(r),this._sidebar_list.append(t)}_addStoryToSidebar(e,t){let r=new n.ListBoxRow,i=new n.Label({label:t||`Unnamed Story`,halign:n.Align.START,margin_start:20,margin_top:6,margin_bottom:6});r.set_child(i),this._sidebar_list.append(r),r.storyWidget=e,this._rowByTitle.set(e.meta.title,r)}_clearControlPanel(){for(let e of this._controlRows)this._control_panel.remove(e);this._controlRows=[]}get activeStory(){return this._controller.activeStory}openStoryByTitle(e){return this._controller.openStoryByTitle(e)}setActiveArg(e,t){return this._controller.setActiveArg(e,t)}};s.type_ensure(Pt.$gtype);var Ft=class StorybookApplication extends o.Application{static{s.registerClass({GTypeName:`StorybookApplication`},StorybookApplication)}constructor(e){super({application_id:e.applicationId,flags:r.ApplicationFlags.DEFAULT_FLAGS}),this._window=null,this._options=e,this.connect(`startup`,()=>this._initStyles()),this.connect(`activate`,()=>this._onActivate())}_initStyles(){let e=new n.CssProvider;e.load_from_string(`
81
+ </node>`}function isWin32(){return e.DIR_SEPARATOR===92}function defaultListenAddress(){return isWin32()?`nonce-tcp:host=127.0.0.1`:`unix:tmpdir=${e.get_tmp_dir()}`}var DevtoolsPeerServerError=class extends Error{constructor(e,t,n,r){super(e),this.address=t,this.reason=n,this.name=`DevtoolsPeerServerError`,this.cause=r}};function isAddressInUse(t){return t instanceof e.Error&&t.matches(r.io_error_quark(),r.IOErrorEnum.ADDRESS_IN_USE)}function unixSocketPath(e){if(!e.startsWith(`unix:`))return null;for(let t of e.slice(5).split(`,`)){let e=t.indexOf(`=`);if(!(e<0||t.slice(0,e)!==`path`))try{return decodeURIComponent(t.slice(e+1))}catch{return null}}return null}function inspectExistingSocket(e){try{if((r.File.new_for_path(e).query_info(`unix::mode`,r.FileQueryInfoFlags.NONE,null).get_attribute_uint32(`unix::mode`)&61440)!=49152)return`not-a-socket`}catch{return`not-a-socket`}let t=new r.SocketClient;t.set_timeout(2);let n;try{n=t.connect(r.UnixSocketAddress.new(e),null)}catch{return`dead`}return n.close(null),`live`}function clearReclaimableSocket(t){let n=unixSocketPath(t);if(!n||!e.file_test(n,e.FileTest.EXISTS))return;let i=inspectExistingSocket(n);if(i===`live`)throw new DevtoolsPeerServerError(`cannot listen on ${t}: another process is already listening there. Stop it, or point ${X} (or options.address) at a different socket — GJSIFY_DEVTOOLS_INSTANCE=<label> lets two devtools-enabled apps run side by side.`,t,`address-in-use`);if(i===`not-a-socket`)throw new DevtoolsPeerServerError(`cannot listen on ${t}: ${n} already exists and is not a socket, so it will NOT be removed. Point ${X} (or options.address) at a free path.`,t,`occupied-by-other-file`);try{r.File.new_for_path(n).delete(null)}catch(e){throw new DevtoolsPeerServerError(`cannot listen on ${t}: ${n} is a socket nothing listens on, but removing it failed (${e}). Delete it by hand, or point ${X} at a free path.`,t,`address-in-use`,e)}_.log(`[gjsify-devtools] reclaimed the stale socket ${n}: nothing was listening on it (an abnormal exit — Ctrl-C, SIGKILL, a crash — leaves the inode behind).`)}function flagsForAddress(e){return e.startsWith(`tcp:`)||e.startsWith(`nonce-tcp:`)?r.DBusServerFlags.NONE:r.DBusServerFlags.AUTHENTICATION_REQUIRE_SAME_USER}function startDevtoolsPeerServer(e,t,n){let i=n&&n!==``?n:defaultListenAddress();clearReclaimableSocket(i);let o;try{o=r.DBusServer.new_sync(i,flagsForAddress(i),r.dbus_generate_guid(),null,null)}catch(e){let t=isAddressInUse(e);throw new DevtoolsPeerServerError(t?`cannot listen on ${i}: the address is already in use (${e}). Stop whatever holds it, or point ${X} (or options.address) at a different address.`:`cannot listen on ${i}: ${e}. Check the address form — \`unix:path=/tmp/app.sock\`, \`unix:tmpdir=/tmp\` or \`nonce-tcp:host=127.0.0.1\`.`,i,t?`address-in-use`:`listen-failed`,e)}let s=new Set;o.connect(`new-connection`,(n,r)=>(s.add(r),r.connect(`closed`,()=>{e.unexport(r),s.delete(r)}),e.export(r,t),!0)),o.start();let c=!1;return{address:o.get_client_address(),objectPath:t,get connectionCount(){return s.size},stop(){if(!c){c=!0,o.stop();for(let t of s)e.unexport(t),!t.is_closed()&&t.close(null,(e,t)=>{try{e.close_finish(t)}catch{}});s.clear()}}}}function writeDevtoolsAddressFile(t,n){try{if(e.mkdir_with_parents(e.path_get_dirname(t),448),!e.file_set_contents(t,`${n}\n`))return null}catch(e){return _.error(`[gjsify-devtools] could not publish the peer address to ${t}: ${e}`),null}try{r.File.new_for_path(t).set_attribute_uint32(`unix::mode`,384,r.FileQueryInfoFlags.NONE,null)}catch(e){_.error(`[gjsify-devtools] could not restrict ${t} to the current user: ${e}`)}return t}function removeDevtoolsAddressFile(e){try{r.File.new_for_path(e).delete(null)}catch{}}function captureWidgetPng(e){let t=e.get_native()?.get_renderer();if(!t)return null;let r=e.get_width(),o=e.get_height();if(r<=0||o<=0)return null;let s=n.WidgetPaintable.new(e),c=n.Snapshot.new();s.snapshot(c,r,o);let l=c.to_node();if(!l)return null;let u=new i.Rect;u.init(0,0,r,o);let d=t.render_texture(l,u).save_to_png_bytes().get_data();return d?new Uint8Array(d):null}function dumpGSettings(e){let t=r.SettingsSchemaSource.get_default()?.lookup(e,!0);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`GSettings schema '${e}' is not installed`));let n=new r.Settings({settings_schema:t}),i={};for(let e of t.list_keys())i[e]=n.get_value(e).recursiveUnpack();return i}function parseWidgetPath(e){let t=e.split(`/`).filter(e=>e.length>0);if(t.length===0)return null;let n=t[0].match(/^toplevel:(\d+)$/);if(!n)return null;let r=[];for(let e of t.slice(1)){let t=e.match(/^child:(\d+)$/);if(!t)return null;r.push(Number(t[1]))}return{toplevel:Number(n[1]),children:r}}function buildWidgetPath(e,t){return[`toplevel:${e}`,...t.map(e=>`child:${e}`)].join(`/`)}function widgetType(e){return gtypeName(e)??`GtkWidget`}function gtypeName(e){let t=e;return typeof t?.$typeName==`string`&&t.$typeName.length>0?t.$typeName:t?.constructor?.$gtype?.name??null}function activateWidget(e){let t=e;if(typeof t.activate==`function`&&t.activate()===!0)return!0;let n=typeof t.get_parent==`function`?t.get_parent():null;if(n&&widgetType(n)===`GtkListBox`){let t=n,r=!1;return typeof t.select_row==`function`&&(t.select_row(e),r=!0),typeof t.emit==`function`&&(t.emit(`row-activated`,e),r=!0),r}return!1}function sendKeyToWidget(e,t,n){let r=e.observe_controllers(),i=!1;for(let e=0;e<r.get_n_items();e++){let o=r.get_item(e);gtypeName(o)===`GtkEventControllerKey`&&(o.emit(`key-pressed`,t,0,n),i=!0)}return i}function nthChild(e,t){let n=e.get_first_child(),r=0;for(;n&&r<t;)n=n.get_next_sibling(),r++;return r===t?n:null}function listToplevels(){let e=n.Window.get_toplevels(),t=e.get_n_items(),r=[];for(let n=0;n<t;n++){let t=e.get_item(n);t&&r.push({path:`toplevel:${n}`,type:widgetType(t),title:t.get_title?.()??null,mapped:t.get_mapped(),focused:t.is_active??!1})}return r}function resolveWidgetPath(e){let t=parseWidgetPath(e);if(!t)return null;let r=n.Window.get_toplevels().get_item(t.toplevel);if(!r)return null;for(let e of t.children)if(r=nthChild(r,e),!r)return null;return r}function parseWidgetSelector(e){let t=e.indexOf(`:`),n=(t<0?e:e.slice(0,t)).trim(),r=(t<0?``:e.slice(t+1)).trim();return!n&&!r?null:{type:n,cssClass:r}}function findWidgetPath(e,t,n){if(!e.get_visible()||!e.get_mapped())return null;let r=!t.type||widgetType(e)===t.type,i=!t.cssClass||e.get_css_classes().includes(t.cssClass);if(r&&i)return n;let o=e.get_first_child(),s=0;for(;o;){let e=findWidgetPath(o,t,`${n}/child:${s}`);if(e)return e;o=o.get_next_sibling(),s++}return null}function dumpTree(e,t,n){let r={path:n,type:widgetType(e),name:e.get_name()||null,cssClasses:e.get_css_classes(),mapped:e.get_mapped(),visible:e.get_visible(),children:[]};if(t<=0)return e.get_first_child()&&(r.truncated=!0),r;let i=e.get_first_child(),o=0;for(;i;)r.children.push(dumpTree(i,t-1,`${n}/child:${o}`)),i=i.get_next_sibling(),o++;return r}function jsonSafe(e){let t=typeof e;return e==null||t===`string`||t===`number`||t===`boolean`?e??null:`[${t}]`}function getWidgetProperty(e,t){let n=e,r=t.replace(/-/g,`_`),i=t.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase());for(let e of[t,r,i])if(e in n)return jsonSafe(n[e])}function childIndex(e,t){let n=e.get_first_child(),r=0;for(;n;){if(n===t)return r;n=n.get_next_sibling(),r++}return-1}function pathOfWidget(e){let t=[],r=e,i=r.get_parent();for(;i;){let e=childIndex(i,r);if(e<0)return null;t.unshift(e),r=i,i=r.get_parent()}let o=n.Window.get_toplevels(),s=o.get_n_items();for(let e=0;e<s;e++)if(o.get_item(e)===r)return buildWidgetPath(e,t);return null}function isActiveWindowScope(e){return!e||e===`window`||e===`active`}function frameDelay(t){return new Promise(n=>{e.timeout_add(e.PRIORITY_DEFAULT,t,()=>(n(),e.SOURCE_REMOVE))})}async function captureWidgetWhenRenderable(e,t=12,n=50){for(let r=0;r<t;r++){let t=captureWidgetPng(e);if(t)return t;await frameDelay(n)}return captureWidgetPng(e)}var DevtoolsService=class{constructor(e,t){this._app=e,this._options=t,this._exported=new Map,this._peer=null,this._addressFile=null,this._kinds=new Map,this._extensions=t.extend??[];for(let[e,t]of Object.entries(bt))this._kinds.set(e,t);for(let e of this._extensions){for(let[t,n]of Object.entries(e.methodKinds))this._kinds.set(t,n);for(let[t,n]of Object.entries(e.handlers)){let e=n;this[t]=(...n)=>(this._guard(t),e(...n))}}}export(e,t){if(this._exported.has(e))return;let n=buildDevtoolsIfaceXml(this._extensions.flatMap(e=>e.methodsXml??[])),i=r.DBusExportedObject.wrapJSObject(n,this);i.export(e,t),this._exported.set(e,i)}unexport(e){if(e){this._exported.get(e)?.unexport(),this._exported.delete(e);return}for(let e of this._exported.values())e.unexport();this._exported.clear(),this._peer?.stop(),this._peer=null,this._addressFile&&=(removeDevtoolsAddressFile(this._addressFile),null)}attachPeerServer(e,t){this._peer=e,this._addressFile=t??null}get peerAddress(){return this._peer?.address??null}get addressFile(){return this._addressFile}GetStatus(){let e=this._app.get_active_window(),t={appId:this._app.get_application_id()??`unknown`,instance:this._options.instance??`default`,activeWindow:e?{id:e.get_name()||`window`,title:e.get_title()??``,mapped:e.get_mapped()}:null,toplevelCount:n.Window.get_toplevels().get_n_items(),focusedWidget:null,paused:this._isPaused()};for(let e of this._extensions){let n=e.contributeStatus?.();n&&Object.assign(t,n)}return JSON.stringify(t)}async ScreenshotAsync(t,n){try{let r=typeof t?.[0]==`string`?t[0]:``,i=await this._captureScopePng(r);n.return_value(new e.Variant(`(ay)`,[i]))}catch(e){n.return_dbus_error(`org.gjsify.Devtools.Error.Screenshot`,e instanceof Error?e.message:String(e))}}async _captureScopePng(e){let t=this._resolveRootWidget(e);if(!t){if(isActiveWindowScope(e))return new Uint8Array;throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`))}let r=captureWidgetPng(t.widget);if(!r){let e=t.widget.get_root();e instanceof n.Window&&e.present(),r=await captureWidgetWhenRenderable(t.widget)}return r??new Uint8Array}ListActions(){let e={app:describeActions(this._actionGroup(`app`)),win:describeActions(this._actionGroup(`win`))};return JSON.stringify(e)}ActivateAction(e,t,n){this._guard(`ActivateAction`);let r=this._scope(e);activateAction(this._requireGroup(r,t),t,this._parseValue(n))}ChangeActionState(e,t,n){this._guard(`ChangeActionState`);let r=this._scope(e);changeActionState(this._requireGroup(r,t),t,this._parseValue(n))}PresentWindow(){this._app.get_active_window()?.present()}ResizeWindow(e,t){this._guard(`ResizeWindow`);let n=this._app.get_active_window();if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no active window to resize`));let r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(t));return n.is_maximized()&&n.unmaximize(),n.is_fullscreen()&&n.unfullscreen(),n.set_default_size(r,i),[r,i]}ListToplevels(){return JSON.stringify(listToplevels())}DumpTree(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e||`active window`}'`));return JSON.stringify(dumpTree(n.widget,t>0?t:40,n.path))}GetProperty(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));let r=getWidgetProperty(n.widget,t);if(r===void 0)throw Error(formatDbusErrorMessage(`not-found`,`widget has no property '${t}'`));return JSON.stringify(r)}GetFocused(){let e=this._app.get_active_window(),t=e?e.get_focus():null;return JSON.stringify(t?{path:pathOfWidget(t),name:t.get_name()||null,type:widgetType(t)}:null)}ActivateWidget(e){this._guard(`ActivateWidget`);let t=this._resolveRootWidget(e);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));return activateWidget(t.widget)}FindWidget(e){let t=parseWidgetSelector(e);if(!t)throw Error(formatDbusErrorMessage(`invalid-params`,`empty selector '${e}'`));let n=this._resolveRootWidget(``);return n?findWidgetPath(n.widget,t,n.path)??``:``}SendKey(e,t){this._guard(`SendKey`);let[r,i,o]=n.accelerator_parse(e);if(!r)throw Error(formatDbusErrorMessage(`invalid-params`,`cannot parse accelerator '${e}'`));let s;if(s=t?this._resolveRootWidget(t)?.widget??null:this._app.get_active_window()?.get_focus()??null,!s)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${t||`focus`}'`));return sendKeyToWidget(s,i,o??0)}DumpGSettings(e){return JSON.stringify(dumpGSettings(e))}DumpCss(){return JSON.stringify(dumpCss())}SwapCss(e,t){return this._guard(`SwapCss`),swapCss(e,t)}_resolveRootWidget(e){if(isActiveWindowScope(e)){let e=this._app.get_active_window();return e?{widget:e,path:pathOfWidget(e)??`toplevel:0`}:null}let t=resolveWidgetPath(e);return t?{widget:t,path:e}:null}_isPaused(){return this._options.paused?.()??!1}_guard(e){let t=this._kinds.get(e);if(!t)throw Error(formatDbusErrorMessage(`internal`,`unclassified devtools method '${e}'`));if(t===`mutating`&&this._isPaused())throw Error(formatDbusErrorMessage(`paused`,`${e} rejected — external control is paused. Read-only methods keep working.`))}_scope(e){return e===`app`?`app`:`win`}_actionGroup(e){if(e===`app`)return this._app;if(this._options.winActionGroup)return this._options.winActionGroup;let t=this._app.get_active_window();return t instanceof n.ApplicationWindow?t:null}_requireGroup(e,t){let n=this._actionGroup(e);if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no '${e}' action group`));if(!n.has_action(t))throw Error(formatDbusErrorMessage(`not-found`,`unknown action ${e}.${t}`));return n}_parseValue(e){if(!e||e===`null`)return null;try{return JSON.parse(e)}catch{throw Error(formatDbusErrorMessage(`invalid-params`,`value_json is not valid JSON: ${e}`))}}};const xt=`DBUS_SESSION_BUS_ADDRESS`,St=new Set;function envEnabled(){return isDevtoolsEnabledValue(e.getenv(`GJSIFY_DEVTOOLS`))}function envValue(t){let n=e.getenv(t);return n&&n!==``?n:null}function sessionBusUsable(){if(!envValue(xt))return!1;try{return r.bus_get_sync(r.BusType.SESSION,null),!0}catch{return!1}}function chooseDevtoolsTransport(e){return e.requestedAddress?{kind:`peer`,address:e.requestedAddress,reason:`requested`}:e.hasAppConnection?{kind:`session-bus`}:e.sessionBusUsable?{kind:`unregistered`}:{kind:`peer`,address:null,reason:`no-session-bus`}}function describeMissingConnection(e,t){return e?t?`[gjsify-devtools] the session bus answers but this application is not registered on it yet — call installDevtools() from the GtkApplication "startup" handler (the bus connection and object path exist only after registration).`:`[gjsify-devtools] ${xt} is set (${e}) but no bus answers there — using the bus-less peer transport instead. On macOS this is the usual state: Homebrew's dbus listens on launchd, so the advertised address only works while that socket is live.`:`[gjsify-devtools] this machine has no session bus (${xt} is unset) — using the bus-less peer transport instead. Point the bridge at the address below, or set ${X} on both the app and \`gjsify debug\` to pin it yourself.`}function installDevtools(e,t={}){if(!(t.enabled??envEnabled()))return null;let n=t.instance??envValue(`GJSIFY_DEVTOOLS_INSTANCE`)??void 0,r=new DevtoolsService(e,{...t,instance:n});try{return exportDevtools(e,r,t,n)}catch(e){return r.unexport(),_.error(`[gjsify-devtools] devtools stayed OFF, the app is unaffected — ${describeInstallFailure(e)}`),null}}function describeInstallFailure(e){return e instanceof DevtoolsPeerServerError||e instanceof Error?e.message:String(e)}function exportDevtools(t,n,r,i){let o=t.get_is_registered(),s=o?t.get_dbus_connection():null,c=o?t.get_dbus_object_path():null,l=envValue(xt),u=!!(s&&c),d=u||sessionBusUsable(),f=chooseDevtoolsTransport({requestedAddress:r.address??envValue(X),hasAppConnection:u,sessionBusUsable:d}),p=t.get_application_id()??`unknown`,m=`${c??appIdToObjectPath(p)}/devtools`;if((f.kind===`unregistered`||f.kind===`peer`&&f.reason===`no-session-bus`)&&_.error(describeMissingConnection(l,d)),f.kind===`session-bus`&&s)n.export(s,m),_.log(`[gjsify-devtools] exported ${yt} at ${m} (dest ${p})`);else if(f.kind===`peer`){let r=startDevtoolsPeerServer(n,m,f.address??void 0),o=writeDevtoolsAddressFile(devtoolsAddressFilePath(e.get_user_runtime_dir(),p,i),r.address);n.attachPeerServer(r,o),_.log(`[gjsify-devtools] exported ${yt} at ${m} (peer address ${r.address}${o?`, published to ${o}`:``})`),o&&t.connect(`shutdown`,()=>removeDevtoolsAddressFile(o))}return St.add(n),n}const Ct=[`AdwNavigationSplitView`,`GtkListBox`,`AdwOverlaySplitView`];function probeEnabled(){let t=e.getenv(`GJSIFY_STORYBOOK_PROBE`);if(t==null)return!1;let n=t.toLowerCase();return n!==``&&n!==`0`&&n!==`false`}function collectTypes(e,t){t.add(e.type);for(let n of e.children)collectTypes(n,t)}function installStorybookProbe(t,n,r={}){let i=r.requireChrome??Ct,o=r.out??e.getenv(`GJSIFY_STORYBOOK_PROBE_OUT`)??void 0,s=r.timeoutMs??8e3,c=r.storyWidget??e.getenv(`GJSIFY_STORYBOOK_PROBE_STORY_WIDGET`)??void 0,l=n.controller.listStories(),u=[...new Set(l.map(e=>e.category))],d=r.story??e.getenv(`GJSIFY_STORYBOOK_PROBE_STORY`)??l[0]?.title,f=d?n.openStoryByTitle(d):!1,p=n.activeStory,m=new Set;collectTypes(dumpTree(n,60,`toplevel:0`),m);let h=i.filter(e=>!m.has(e)),g=new Set;p&&collectTypes(dumpTree(p,60,`story`),g);let v=g.size,ee=c?g.has(c):null,finish=n=>{let r=JSON.stringify(n);if(n.ok)_.log(`STORYBOOK PROBE: PASS ${r}`);else{_.error(`STORYBOOK PROBE: FAIL ${r}`);try{typeof process<`u`&&(process.exitCode=1)}catch{}}if(o)try{e.file_set_contents(o,JSON.stringify(n,null,2))}catch{}t.quit()},te=0;e.timeout_add(e.PRIORITY_DEFAULT,100,()=>{te+=100;let t=captureWidgetPng(n),r=n.get_width()>0&&n.get_height()>0;if(!t&&!(te>=s))return e.SOURCE_CONTINUE;let o=p?captureWidgetPng(p):null,m=l.length>=1&&u.length>=1&&h.length===0&&f&&p!=null&&v>1,_;return l.length<1?_=`no stories registered`:u.length<1?_=`no categories`:h.length>0?_=`chrome missing: ${h.join(`, `)}`:!f||p==null?_=`could not open story: ${d??`(none)`}`:v<=1&&(_=`opened story rendered an empty subtree`),m&&c&&!g.has(c)&&(m=!1,_=`story widget ${c} not found in the opened story subtree`),m&&r&&(!t||t.length===0)&&(m=!1,_=`window realized (${n.get_width()}x${n.get_height()}) but the GSK capture was empty`),finish({ok:m,reason:_,stories:l.length,categories:u,opened:f,activeStory:p?p.meta.title:null,requiredChrome:i,missingChrome:h,storySubtreeWidgets:v,storyWidgetPresent:ee,windowRealized:r,windowPngBytes:t?t.length:0,storyPngBytes:o?o.length:0}),e.SOURCE_REMOVE})}const wt={UNKNOWN:0,CUSTOM:1,GPL_2_0:2,GPL_3_0:3,LGPL_2_1:4,LGPL_3_0:5,BSD:6,MIT_X11:7,ARTISTIC:8,GPL_2_0_ONLY:9,GPL_3_0_ONLY:10,LGPL_2_1_ONLY:11,LGPL_3_0_ONLY:12,AGPL_3_0:13,AGPL_3_0_ONLY:14,BSD_3:15,APACHE_2_0:16,MPL_2_0:17,"0BSD":18};wt.GPL_2_0_ONLY,wt.GPL_3_0_ONLY,wt.UNKNOWN;const Tt=[`blue`,`teal`,`green`,`yellow`,`orange`,`red`,`pink`,`purple`,`slate`],Et={blue:`#3584e4`,teal:`#2190a4`,green:`#3a944a`,yellow:`#c88800`,orange:`#ed5b00`,red:`#e62d42`,pink:`#d56199`,purple:`#9141ac`,slate:`#6f8396`};function parseHex(e){let t=/^#([0-9a-f]{6})$/i.exec(e.trim());if(!t)return null;let n=Number.parseInt(t[1],16);return[(n>>16&255)/255,(n>>8&255)/255,(n&255)/255]}function toHex(e,t,n){let channel=e=>Math.round(Math.min(1,Math.max(0,e))*255).toString(16).padStart(2,`0`);return`#${channel(e)}${channel(t)}${channel(n)}`}const toLinear=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,fromLinear=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055;function linearToOklab(e,t,n){let r=Math.cbrt(.4122214708*e+.5363325363*t+.0514459929*n),i=Math.cbrt(.2119034982*e+.6806995451*t+.1073969566*n),o=Math.cbrt(.0883024619*e+.2817188376*t+.6299787005*n);return[.2104542553*r+.793617785*i-.0040720468*o,1.9779984951*r-2.428592205*i+.4505937099*o,.0259040371*r+.7827717662*i-.808675766*o]}function oklabToLinear(e,t,n){let r=(e+.3963377774*t+.2158037573*n)**3,i=(e-.1055613458*t-.0638541728*n)**3,o=(e-.0894841775*t-1.291485548*n)**3;return[4.0767416621*r-3.3077115913*i+.2309699292*o,-1.2684380046*r+2.6097574011*i-.3413193965*o,-.0041960863*r-.7034186147*i+1.707614701*o]}function adwaitaStandaloneColor(e,t){let n=parseHex(e);if(!n)return e;let[r,i,o]=linearToOklab(toLinear(n[0]),toLinear(n[1]),toLinear(n[2])),[s,c,l]=oklabToLinear(t?Math.max(r,.85):Math.min(r,.5),i,o);return toHex(fromLinear(s),fromLinear(c),fromLinear(l))}function adwaitaAccentBgColor(e){return Et[e]}function adwaitaAccentColor(e,t){return adwaitaStandaloneColor(Et[e],t)}Math.PI*.35,Math.PI*.015,Math.PI*.9;const Dt=Math.PI*.9,Ot=Math.PI*.7,kt=Math.PI*1.1,At=Math.PI*1.35,jt=Dt+kt+At-Ot;53*Math.PI*2/jt,kt-Ot/2;const Mt={system:`Follow system`,light:`Light`,dark:`Dark`},Nt={blue:`Blue`,teal:`Teal`,green:`Green`,yellow:`Yellow`,orange:`Orange`,red:`Red`,pink:`Pink`,purple:`Purple`,slate:`Slate`};var StorybookAppearance=class{constructor(){this._provider=null,this._applying=!1,this._styleManager=o.StyleManager.get_default(),this.settings=new StorybookSettings(()=>this._styleManager.get_dark()),this.settings.subscribe(e=>this._apply(e)),this._styleManager.connect(`notify::dark`,()=>this.settings.systemChanged()),this._apply(this.settings.state)}_apply(e){if(!this._applying){this._applying=!0;try{this._styleManager.set_color_scheme(e.colorScheme===`light`?o.ColorScheme.FORCE_LIGHT:e.colorScheme===`dark`?o.ColorScheme.FORCE_DARK:o.ColorScheme.DEFAULT),this._applyAccent(this.settings.resolvedAccent)}finally{this._applying=!1}}}_applyAccent(e){let r=t.Display.get_default();if(!r)return;if(!this._provider){if(!e)return;this._provider=new n.CssProvider,n.StyleContext.add_provider_for_display(r,this._provider,n.STYLE_PROVIDER_PRIORITY_APPLICATION)}if(!e){this._provider.load_from_string(``);return}let i=adwaitaAccentBgColor(e),o=adwaitaAccentColor(e,this.settings.resolvedDark);this._provider.load_from_string(`:root { --accent-bg-color: ${i}; --accent-color: ${o}; }`)}};function buildSwatch(e,t,r){let i=new n.CheckButton({tooltip_text:t,halign:n.Align.CENTER,valign:n.Align.CENTER,focus_on_click:!1});for(let t of e)i.add_css_class(t);return i.update_property([n.AccessibleProperty.LABEL],[t]),r&&i.set_group(r),i}function buildSwatchCard(e=!1){let t=new o.WrapBox({align:.5,child_spacing:8,line_spacing:8,margin_top:12,margin_bottom:12,margin_start:12,margin_end:12}),n=new o.Bin({child:t,hexpand:!0});return n.add_css_class(`card`),e&&n.add_css_class(`storybook-card-attached`),{card:n,row:t}}function buildAppearanceDialog(e){let t=e.settings,r=new o.PreferencesPage,i=new o.PreferencesGroup({title:`Style`}),{card:s,row:c}=buildSwatchCard(),l=null,u=new Map;for(let e of gt){let n=buildSwatch([`storybook-swatch`,`storybook-scheme-swatch`,`storybook-scheme-${e}`],Mt[e],l);l??=n,n.set_active(t.colorScheme===e),n.connect(`toggled`,()=>{n.get_active()&&(t.colorScheme=e)}),u.set(e,n),c.append(n)}i.add(s),r.add(i);let d=new o.PreferencesGroup({title:`Accent colour`});d.add_css_class(`storybook-attached-group`);let f=new o.SwitchRow({title:`Use a custom accent colour`,subtitle:`Off follows the desktop, which owns the accent`,active:t.accentMode===`custom`});d.add(f);let{card:p,row:m}=buildSwatchCard(!0),h=null,g=new Map;for(let e of Tt){let r=buildSwatch([`storybook-swatch`],Nt[e],h);h??=r,r.set_active(t.accent===e);let i=new n.CssProvider;i.load_from_string(`checkbutton { background-color: ${adwaitaAccentBgColor(e)}; }`),r.get_style_context().add_provider(i,n.STYLE_PROVIDER_PRIORITY_APPLICATION),r.connect(`toggled`,()=>{r.get_active()&&(t.accent=e)}),g.set(e,r),m.append(r)}m.set_sensitive(t.accentMode===`custom`),f.connect(`notify::active`,()=>{t.accentMode=f.get_active()?`custom`:`system`}),d.add(p),r.add(d),t.subscribe(e=>{let t=u.get(e.colorScheme);t&&!t.get_active()&&t.set_active(!0);let n=g.get(e.accent);n&&!n.get_active()&&n.set_active(!0);let r=e.accentMode===`custom`;f.get_active()!==r&&f.set_active(r),m.set_sensitive(r)});let _=new o.PreferencesDialog({title:`Appearance`});return _.add(r),_}function adwControlWidgetFactory(){return{text(e,t){let n=new o.EntryRow({title:e});t&&n.set_tooltip_text(t);let r=null;return n.connect(`changed`,()=>r?.(n.get_text())),{node:n,get:()=>n.get_text(),set:e=>n.set_text(e),onChange:e=>{r=e}}},boolean(e,t){let n=new o.SwitchRow({title:e,subtitle:t??``}),r=null;return n.connect(`notify::active`,()=>r?.(n.get_active())),{node:n,get:()=>n.get_active(),set:e=>n.set_active(e),onChange:e=>{r=e}}},number(e){let t=o.SpinRow.new_with_range(e.min??0,e.max??100,e.step??1);t.set_title(e.label||e.name),e.description&&t.set_subtitle(e.description);let n=null;return t.connect(`changed`,()=>n?.(t.get_value())),{node:t,get:()=>t.get_value(),set:e=>t.set_value(e),onChange:e=>{n=e}}},range(e){return buildRangeWidget(e)},select(e){return buildSelectWidget(e)},color(e,t){return buildColorWidget(e,t)}}}function buildRangeWidget(e){let t=e.min??0,r=e.max??100,i=e.step??1,o=typeof e.min==`number`?e.min:0,s=Number.isInteger(i)&&Number.isInteger(o),c=new n.Adjustment({lower:t,upper:r,step_increment:i,value:o});c.step_increment=i;let l=new n.ListBoxRow({selectable:!1,activatable:!1});l.add_css_class(`story-range-row`);let u=new n.Box({orientation:n.Orientation.VERTICAL,spacing:6,margin_top:12,margin_bottom:12,margin_start:12,margin_end:12}),d=new n.Box({orientation:n.Orientation.HORIZONTAL,spacing:12}),f=new n.Label({label:e.label||e.name,halign:n.Align.START,hexpand:!0,ellipsize:3});f.add_css_class(`heading`);let formatValue=e=>s?String(Math.round(e)):e.toFixed(2),p=new n.Label({label:formatValue(o),halign:n.Align.END});if(p.add_css_class(`numeric`),p.add_css_class(`dim-label`),d.append(f),d.append(p),u.append(d),e.description){let t=new n.Label({label:e.description,halign:n.Align.START,xalign:0,wrap:!0,max_width_chars:32});t.add_css_class(`caption`),t.add_css_class(`dim-label`),u.append(t)}let m=new n.Scale({orientation:n.Orientation.HORIZONTAL,adjustment:c,draw_value:!1,hexpand:!0}),h=null,g=!1;return m.connect(`value-changed`,()=>{if(g)return;let e=m.get_value();if(s){let t=Math.round(e);if(t!==e){m.set_value(t);return}e=t}p.set_label(formatValue(e)),h?.(e)}),u.append(m),l.set_child(u),{node:l,get:()=>m.get_value(),set:e=>{g=!0,m.set_value(e),g=!1,p.set_label(formatValue(e))},onChange:e=>{h=e}}}function buildSelectWidget(e){let t=e.options??[],r=n.StringList.new(t.map(e=>e.label)),i=new o.ComboRow({title:e.label||e.name,subtitle:e.description??``,model:r}),s=null;return i.connect(`notify::selected`,()=>s?.(i.get_selected())),{node:i,get:()=>i.get_selected(),set:e=>i.set_selected(e),onChange:e=>{s=e}}}function buildColorWidget(e,r){let i=new o.ActionRow({title:e,subtitle:r??``}),s=new n.ColorDialogButton({dialog:new n.ColorDialog({title:e}),valign:n.Align.CENTER});i.add_suffix(s),i.set_activatable_widget(s);let channel=e=>Math.round(Math.max(0,Math.min(1,e))*255).toString(16).padStart(2,`0`),rgbaToHex=e=>`#${channel(e.red)}${channel(e.green)}${channel(e.blue)}`,c=null,l=!1;return s.connect(`notify::rgba`,()=>{l||c?.(rgbaToHex(s.get_rgba()))}),{node:i,get:()=>rgbaToHex(s.get_rgba()),set:e=>{let n=new t.RGBA;n.parse(e)&&(l=!0,s.set_rgba(n),l=!1)},onChange:e=>{c=e}}}var Pt=class StorybookWindow extends o.ApplicationWindow{static{s.registerClass({GTypeName:`StorybookWindow`},StorybookWindow)}constructor(e){super(e),this._appearance=new StorybookAppearance,this._controlRows=[],this._rowByTitle=new Map,this._onSelect=null,this._suppressSelect=!1,this.set_default_size(1200,800),this.set_size_request(360,320),this.set_title(`Storybook`),this._buildUI(),this._controller=new StorybookController(this,e=>this._buildControls(e)),this._sidebar_list.connect(`row-selected`,this._onRowSelected.bind(this)),this._show_controls_button.connect(`toggled`,this._onToggleControls.bind(this)),this._controls_split_view.set_show_sidebar(!0)}_onRowSelected(e,t){if(this._suppressSelect||!t)return;let n=t;n.storyWidget&&this._onSelect?.(n.storyWidget)}get controller(){return this._controller}_buildControls(e){let t=e.meta.controls;if(!Array.isArray(t))return[];let n=adwControlWidgetFactory(),r=[];for(let i of t){if(!i?.name||!i?.type){_.warn(`Invalid control configuration:`,i);continue}let t=bindControl(e,i,n);t&&r.push(t)}return r}_buildUI(){this._sidebar_list=new n.ListBox({selection_mode:n.SelectionMode.SINGLE}),this._sidebar_list.add_css_class(`navigation-sidebar`);let e=new n.ScrolledWindow({hexpand:!0,vexpand:!0,child:this._sidebar_list}),t=new o.HeaderBar({title_widget:new o.WindowTitle({title:`Stories`}),show_end_title_buttons:!1}),r=new o.ToolbarView({content:e,top_bar_style:o.ToolbarStyle.FLAT});r.add_top_bar(t);let i=new o.NavigationPage({title:`Stories`,tag:`stories`,child:r});this._content_area=new o.Bin({hexpand:!0,vexpand:!0});let s=new n.ScrolledWindow({hexpand:!0,vexpand:!0,child:this._content_area});s.add_css_class(`sb-preview-area`),this._control_panel=new o.PreferencesGroup({title:`Controls`});let c=new o.PreferencesPage;c.add(this._control_panel);let l=new n.ScrolledWindow({vexpand:!0,child:c});this._controls_split_view=new o.OverlaySplitView({show_sidebar:!0,sidebar_position:n.PackType.END,min_sidebar_width:280,max_sidebar_width:360,content:s,sidebar:l,css_classes:[`storybook-controls`]}),this._preview_title=new o.WindowTitle({title:`Preview`}),this._show_controls_button=new n.ToggleButton({icon_name:`sidebar-show-right-symbolic`,tooltip_text:`Toggle Controls`,active:!0});let u=new o.HeaderBar({title_widget:this._preview_title});u.pack_end(this._show_controls_button);let d=new n.Button({icon_name:`applications-graphics-symbolic`,tooltip_text:`Appearance`});d.connect(`clicked`,()=>buildAppearanceDialog(this._appearance).present(this)),u.pack_end(d);let f=new o.ToolbarView({content:this._controls_split_view,top_bar_style:o.ToolbarStyle.FLAT});f.add_top_bar(u);let p=new o.NavigationPage({title:`Preview`,tag:`preview`,child:f});this._main_split_view=new o.NavigationSplitView({min_sidebar_width:220,max_sidebar_width:320,sidebar:i,content:p}),this.set_content(this._main_split_view);let m=o.BreakpointCondition.parse(`max-width: 720sp`);if(m){let e=new o.Breakpoint({condition:m});e.connect(`apply`,()=>{this._main_split_view.collapsed=!0,this._controls_split_view.collapsed=!0}),e.connect(`unapply`,()=>{this._main_split_view.collapsed=!1,this._controls_split_view.collapsed=!1}),this.add_breakpoint(e)}}_onToggleControls(e){this._controls_split_view.set_show_sidebar(e.get_active())}populateSidebar(e){this._controller.mount(e,!0)}renderSidebar(e,t){this._onSelect=t,this._suppressSelect=!0,this._clearSidebar(),this._rowByTitle.clear();for(let t of e){this._addCategoryToSidebar(t.category);for(let{instance:e,name:n}of t.stories)this._addStoryToSidebar(e,n)}this._suppressSelect=!1}markSelected(e){let t=this._rowByTitle.get(e);t&&this._sidebar_list.get_selected_row()!==t&&(this._suppressSelect=!0,this._sidebar_list.select_row(t),this._suppressSelect=!1)}setPreviewTitle(e){this._preview_title.set_title(e)}showPreview(e){this._content_area.set_child(e),this._main_split_view.get_collapsed()&&this._main_split_view.set_show_content(!0)}renderControls(e){this._clearControlPanel();for(let t of e){let e=t.view;e instanceof o.PreferencesRow&&e.set_use_markup(!1),this._control_panel.add(e),this._controlRows.push(e)}this._show_controls_button.set_active(!0)}_clearSidebar(){let e=this._sidebar_list.get_first_child();for(;e;){let t=e.get_next_sibling();e.unparent(),e=t}}_addCategoryToSidebar(e){let t=new n.ListBoxRow({selectable:!1}),r=new n.Label({label:e,halign:n.Align.START,margin_top:10,margin_bottom:4,margin_start:12,margin_end:12});r.add_css_class(`heading`),r.add_css_class(`dim-label`),t.set_child(r),this._sidebar_list.append(t)}_addStoryToSidebar(e,t){let r=new n.ListBoxRow,i=new n.Label({label:t||`Unnamed Story`,halign:n.Align.START,margin_start:20,margin_top:6,margin_bottom:6});r.set_child(i),this._sidebar_list.append(r),r.storyWidget=e,this._rowByTitle.set(e.meta.title,r)}_clearControlPanel(){for(let e of this._controlRows)this._control_panel.remove(e);this._controlRows=[]}get activeStory(){return this._controller.activeStory}openStoryByTitle(e){return this._controller.openStoryByTitle(e)}setActiveArg(e,t){return this._controller.setActiveArg(e,t)}};s.type_ensure(Pt.$gtype);var Ft=class StorybookApplication extends o.Application{static{s.registerClass({GTypeName:`StorybookApplication`},StorybookApplication)}constructor(e){super({application_id:e.applicationId,flags:r.ApplicationFlags.DEFAULT_FLAGS}),this._window=null,this._options=e,this.connect(`startup`,()=>this._initStyles()),this.connect(`activate`,()=>this._onActivate())}_initStyles(){let e=new n.CssProvider;e.load_from_string(`
82
82
  /* Appearance dialog — round swatches with a selection ring, the shape GNOME's own
83
83
  appearance switcher uses. Adapted from Learn6502's theme-mode-selector.css and
84
84
  accent-color-selector.css (JumpLink/easy6502, MIT).
package/dist/gjs.node.mjs CHANGED
@@ -70,7 +70,7 @@ import{createRequire as e}from"node:module";import"@gjsify/node-gi/globals";impo
70
70
  </method>${e.length>0?`\n${e.join(`
71
71
  `)}`:``}
72
72
  </interface>
73
- </node>`}const ee=e(import.meta.url);let b;function load$3(){return b===void 0&&(b=ee(`@gjsify/node-gi/gi`).requireGi(`Gio`,`2.0`)),b}__name(load$3,`load`);var x=new Proxy(Object.create(null),{get(e,t){return load$3()[t]},has(e,t){return t in load$3()}});function isWin32(){return l.DIR_SEPARATOR===92}function defaultListenAddress(){return isWin32()?`nonce-tcp:host=127.0.0.1`:`unix:tmpdir=${l.get_tmp_dir()}`}var DevtoolsPeerServerError=class extends Error{constructor(e,t,n,r){super(e),this.address=t,this.reason=n,this.name=`DevtoolsPeerServerError`,this.cause=r}};function isAddressInUse(e){return e instanceof l.Error&&e.matches(x.io_error_quark(),x.IOErrorEnum.ADDRESS_IN_USE)}function unixSocketPath(e){if(!e.startsWith(`unix:`))return null;for(let t of e.slice(5).split(`,`)){let e=t.indexOf(`=`);if(!(e<0||t.slice(0,e)!==`path`))try{return decodeURIComponent(t.slice(e+1))}catch{return null}}return null}function inspectExistingSocket(e){try{if((x.File.new_for_path(e).query_info(`unix::mode`,x.FileQueryInfoFlags.NONE,null).get_attribute_uint32(`unix::mode`)&61440)!=49152)return`not-a-socket`}catch{return`not-a-socket`}let t=new x.SocketClient;t.set_timeout(2);let n;try{n=t.connect(x.UnixSocketAddress.new(e),null)}catch{return`dead`}return n.close(null),`live`}function clearReclaimableSocket(e){let t=unixSocketPath(e);if(!t||!l.file_test(t,l.FileTest.EXISTS))return;let n=inspectExistingSocket(t);if(n===`live`)throw new DevtoolsPeerServerError(`cannot listen on ${e}: another process is already listening there. Stop it, or point ${y} (or options.address) at a different socket — GJSIFY_DEVTOOLS_INSTANCE=<label> lets two devtools-enabled apps run side by side.`,e,`address-in-use`);if(n===`not-a-socket`)throw new DevtoolsPeerServerError(`cannot listen on ${e}: ${t} already exists and is not a socket, so it will NOT be removed. Point ${y} (or options.address) at a free path.`,e,`occupied-by-other-file`);try{x.File.new_for_path(t).delete(null)}catch(n){throw new DevtoolsPeerServerError(`cannot listen on ${e}: ${t} is a socket nothing listens on, but removing it failed (${n}). Delete it by hand, or point ${y} at a free path.`,e,`address-in-use`,n)}console.log(`[gjsify-devtools] reclaimed the stale socket ${t}: nothing was listening on it (an abnormal exit — Ctrl-C, SIGKILL, a crash — leaves the inode behind).`)}function flagsForAddress(e){return e.startsWith(`tcp:`)||e.startsWith(`nonce-tcp:`)?x.DBusServerFlags.NONE:x.DBusServerFlags.AUTHENTICATION_REQUIRE_SAME_USER}function startDevtoolsPeerServer(e,t,n){let r=n&&n!==``?n:defaultListenAddress();clearReclaimableSocket(r);let i;try{i=x.DBusServer.new_sync(r,flagsForAddress(r),x.dbus_generate_guid(),null,null)}catch(e){let t=isAddressInUse(e);throw new DevtoolsPeerServerError(t?`cannot listen on ${r}: the address is already in use (${e}). Stop whatever holds it, or point ${y} (or options.address) at a different address.`:`cannot listen on ${r}: ${e}. Check the address form — \`unix:path=/tmp/app.sock\`, \`unix:tmpdir=/tmp\` or \`nonce-tcp:host=127.0.0.1\`.`,r,t?`address-in-use`:`listen-failed`,e)}let a=new Set;i.connect(`new-connection`,(n,r)=>(a.add(r),r.connect(`closed`,()=>{e.unexport(r),a.delete(r)}),e.export(r,t),!0)),i.start();let o=!1;return{address:i.get_client_address(),objectPath:t,get connectionCount(){return a.size},stop(){if(!o){o=!0,i.stop();for(let t of a)e.unexport(t),!t.is_closed()&&t.close(null,(e,t)=>{try{e.close_finish(t)}catch{}});a.clear()}}}}function writeDevtoolsAddressFile(e,t){try{if(l.mkdir_with_parents(l.path_get_dirname(e),448),!l.file_set_contents(e,`${t}\n`))return null}catch(t){return console.error(`[gjsify-devtools] could not publish the peer address to ${e}: ${t}`),null}try{x.File.new_for_path(e).set_attribute_uint32(`unix::mode`,384,x.FileQueryInfoFlags.NONE,null)}catch(t){console.error(`[gjsify-devtools] could not restrict ${e} to the current user: ${t}`)}return e}function removeDevtoolsAddressFile(e){try{x.File.new_for_path(e).delete(null)}catch{}}const te=e(import.meta.url);let S;function load$2(){return S===void 0&&(S=te(`@gjsify/node-gi/gi`).requireGi(`Graphene`,`1.0`)),S}__name(load$2,`load`);var ne=new Proxy(Object.create(null),{get(e,t){return load$2()[t]},has(e,t){return t in load$2()}});function captureWidgetPng(e){let t=e.get_native()?.get_renderer();if(!t)return null;let n=e.get_width(),r=e.get_height();if(n<=0||r<=0)return null;let i=h.WidgetPaintable.new(e),a=h.Snapshot.new();i.snapshot(a,n,r);let o=a.to_node();if(!o)return null;let s=new ne.Rect;s.init(0,0,n,r);let c=t.render_texture(o,s).save_to_png_bytes().get_data();return c?new Uint8Array(c):null}function dumpGSettings(e){let t=x.SettingsSchemaSource.get_default()?.lookup(e,!0);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`GSettings schema '${e}' is not installed`));let n=new x.Settings({settings_schema:t}),r={};for(let e of t.list_keys())r[e]=n.get_value(e).recursiveUnpack();return r}function parseWidgetPath(e){let t=e.split(`/`).filter(e=>e.length>0);if(t.length===0)return null;let n=t[0].match(/^toplevel:(\d+)$/);if(!n)return null;let r=[];for(let e of t.slice(1)){let t=e.match(/^child:(\d+)$/);if(!t)return null;r.push(Number(t[1]))}return{toplevel:Number(n[1]),children:r}}function buildWidgetPath(e,t){return[`toplevel:${e}`,...t.map(e=>`child:${e}`)].join(`/`)}function widgetType(e){return gtypeName(e)??`GtkWidget`}function gtypeName(e){let t=e;return typeof t?.$typeName==`string`&&t.$typeName.length>0?t.$typeName:t?.constructor?.$gtype?.name??null}function activateWidget(e){let t=e;if(typeof t.activate==`function`&&t.activate()===!0)return!0;let n=typeof t.get_parent==`function`?t.get_parent():null;if(n&&widgetType(n)===`GtkListBox`){let t=n,r=!1;return typeof t.select_row==`function`&&(t.select_row(e),r=!0),typeof t.emit==`function`&&(t.emit(`row-activated`,e),r=!0),r}return!1}function sendKeyToWidget(e,t,n){let r=e.observe_controllers(),i=!1;for(let e=0;e<r.get_n_items();e++){let a=r.get_item(e);gtypeName(a)===`GtkEventControllerKey`&&(a.emit(`key-pressed`,t,0,n),i=!0)}return i}function nthChild(e,t){let n=e.get_first_child(),r=0;for(;n&&r<t;)n=n.get_next_sibling(),r++;return r===t?n:null}function listToplevels(){let e=h.Window.get_toplevels(),t=e.get_n_items(),n=[];for(let r=0;r<t;r++){let t=e.get_item(r);t&&n.push({path:`toplevel:${r}`,type:widgetType(t),title:t.get_title?.()??null,mapped:t.get_mapped(),focused:t.is_active??!1})}return n}function resolveWidgetPath(e){let t=parseWidgetPath(e);if(!t)return null;let n=h.Window.get_toplevels().get_item(t.toplevel);if(!n)return null;for(let e of t.children)if(n=nthChild(n,e),!n)return null;return n}function parseWidgetSelector(e){let t=e.indexOf(`:`),n=(t<0?e:e.slice(0,t)).trim(),r=(t<0?``:e.slice(t+1)).trim();return!n&&!r?null:{type:n,cssClass:r}}function findWidgetPath(e,t,n){if(!e.get_visible()||!e.get_mapped())return null;let r=!t.type||widgetType(e)===t.type,i=!t.cssClass||e.get_css_classes().includes(t.cssClass);if(r&&i)return n;let a=e.get_first_child(),o=0;for(;a;){let e=findWidgetPath(a,t,`${n}/child:${o}`);if(e)return e;a=a.get_next_sibling(),o++}return null}function dumpTree(e,t,n){let r={path:n,type:widgetType(e),name:e.get_name()||null,cssClasses:e.get_css_classes(),mapped:e.get_mapped(),visible:e.get_visible(),children:[]};if(t<=0)return r;let i=e.get_first_child(),a=0;for(;i;)r.children.push(dumpTree(i,t-1,`${n}/child:${a}`)),i=i.get_next_sibling(),a++;return r}function jsonSafe(e){let t=typeof e;return e==null||t===`string`||t===`number`||t===`boolean`?e??null:`[${t}]`}function getWidgetProperty(e,t){let n=e,r=t.replace(/-/g,`_`),i=t.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase());for(let e of[t,r,i])if(e in n)return jsonSafe(n[e])}function childIndex(e,t){let n=e.get_first_child(),r=0;for(;n;){if(n===t)return r;n=n.get_next_sibling(),r++}return-1}function pathOfWidget(e){let t=[],n=e,r=n.get_parent();for(;r;){let e=childIndex(r,n);if(e<0)return null;t.unshift(e),n=r,r=n.get_parent()}let i=h.Window.get_toplevels(),a=i.get_n_items();for(let e=0;e<a;e++)if(i.get_item(e)===n)return buildWidgetPath(e,t);return null}function isActiveWindowScope(e){return!e||e===`window`||e===`active`}function frameDelay(e){return new Promise(t=>{l.timeout_add(l.PRIORITY_DEFAULT,e,()=>(t(),l.SOURCE_REMOVE))})}async function captureWidgetWhenRenderable(e,t=12,n=50){for(let r=0;r<t;r++){let t=captureWidgetPng(e);if(t)return t;await frameDelay(n)}return captureWidgetPng(e)}var DevtoolsService=class{constructor(e,t){this._app=e,this._options=t,this._exported=new Map,this._peer=null,this._addressFile=null,this._kinds=new Map,this._extensions=t.extend??[];for(let[e,t]of Object.entries(v))this._kinds.set(e,t);for(let e of this._extensions){for(let[t,n]of Object.entries(e.methodKinds))this._kinds.set(t,n);for(let[t,n]of Object.entries(e.handlers)){let e=n;this[t]=(...n)=>(this._guard(t),e(...n))}}}export(e,t){if(this._exported.has(e))return;let n=buildDevtoolsIfaceXml(this._extensions.flatMap(e=>e.methodsXml??[])),r=x.DBusExportedObject.wrapJSObject(n,this);r.export(e,t),this._exported.set(e,r)}unexport(e){if(e){this._exported.get(e)?.unexport(),this._exported.delete(e);return}for(let e of this._exported.values())e.unexport();this._exported.clear(),this._peer?.stop(),this._peer=null,this._addressFile&&=(removeDevtoolsAddressFile(this._addressFile),null)}attachPeerServer(e,t){this._peer=e,this._addressFile=t??null}get peerAddress(){return this._peer?.address??null}get addressFile(){return this._addressFile}GetStatus(){let e=this._app.get_active_window(),t={appId:this._app.get_application_id()??`unknown`,instance:this._options.instance??`default`,activeWindow:e?{id:e.get_name()||`window`,title:e.get_title()??``,mapped:e.get_mapped()}:null,toplevelCount:h.Window.get_toplevels().get_n_items(),focusedWidget:null,paused:this._isPaused()};for(let e of this._extensions){let n=e.contributeStatus?.();n&&Object.assign(t,n)}return JSON.stringify(t)}async ScreenshotAsync(e,t){try{let n=typeof e?.[0]==`string`?e[0]:``,r=await this._captureScopePng(n);t.return_value(new l.Variant(`(ay)`,[r]))}catch(e){t.return_dbus_error(`org.gjsify.Devtools.Error.Screenshot`,e instanceof Error?e.message:String(e))}}async _captureScopePng(e){let t=this._resolveRootWidget(e);if(!t){if(isActiveWindowScope(e))return new Uint8Array;throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`))}let n=captureWidgetPng(t.widget);if(!n){let e=t.widget.get_root();e instanceof h.Window&&e.present(),n=await captureWidgetWhenRenderable(t.widget)}return n??new Uint8Array}ListActions(){let e={app:describeActions(this._actionGroup(`app`)),win:describeActions(this._actionGroup(`win`))};return JSON.stringify(e)}ActivateAction(e,t,n){this._guard(`ActivateAction`);let r=this._scope(e);activateAction(this._requireGroup(r,t),t,this._parseValue(n))}ChangeActionState(e,t,n){this._guard(`ChangeActionState`);let r=this._scope(e);changeActionState(this._requireGroup(r,t),t,this._parseValue(n))}PresentWindow(){this._app.get_active_window()?.present()}ResizeWindow(e,t){this._guard(`ResizeWindow`);let n=this._app.get_active_window();if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no active window to resize`));let r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(t));return n.is_maximized()&&n.unmaximize(),n.is_fullscreen()&&n.unfullscreen(),n.set_default_size(r,i),[r,i]}ListToplevels(){return JSON.stringify(listToplevels())}DumpTree(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e||`active window`}'`));return JSON.stringify(dumpTree(n.widget,t>0?t:8,n.path))}GetProperty(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));let r=getWidgetProperty(n.widget,t);if(r===void 0)throw Error(formatDbusErrorMessage(`not-found`,`widget has no property '${t}'`));return JSON.stringify(r)}GetFocused(){let e=this._app.get_active_window(),t=e?e.get_focus():null;return JSON.stringify(t?{path:pathOfWidget(t),name:t.get_name()||null,type:widgetType(t)}:null)}ActivateWidget(e){this._guard(`ActivateWidget`);let t=this._resolveRootWidget(e);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));return activateWidget(t.widget)}FindWidget(e){let t=parseWidgetSelector(e);if(!t)throw Error(formatDbusErrorMessage(`invalid-params`,`empty selector '${e}'`));let n=this._resolveRootWidget(``);return n?findWidgetPath(n.widget,t,n.path)??``:``}SendKey(e,t){this._guard(`SendKey`);let[n,r,i]=h.accelerator_parse(e);if(!n)throw Error(formatDbusErrorMessage(`invalid-params`,`cannot parse accelerator '${e}'`));let a;if(a=t?this._resolveRootWidget(t)?.widget??null:this._app.get_active_window()?.get_focus()??null,!a)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${t||`focus`}'`));return sendKeyToWidget(a,r,i??0)}DumpGSettings(e){return JSON.stringify(dumpGSettings(e))}DumpCss(){return JSON.stringify(dumpCss())}SwapCss(e,t){return this._guard(`SwapCss`),swapCss(e,t)}_resolveRootWidget(e){if(isActiveWindowScope(e)){let e=this._app.get_active_window();return e?{widget:e,path:pathOfWidget(e)??`toplevel:0`}:null}let t=resolveWidgetPath(e);return t?{widget:t,path:e}:null}_isPaused(){return this._options.paused?.()??!1}_guard(e){let t=this._kinds.get(e);if(!t)throw Error(formatDbusErrorMessage(`internal`,`unclassified devtools method '${e}'`));if(t===`mutating`&&this._isPaused())throw Error(formatDbusErrorMessage(`paused`,`${e} rejected — external control is paused. Read-only methods keep working.`))}_scope(e){return e===`app`?`app`:`win`}_actionGroup(e){if(e===`app`)return this._app;if(this._options.winActionGroup)return this._options.winActionGroup;let t=this._app.get_active_window();return t instanceof h.ApplicationWindow?t:null}_requireGroup(e,t){let n=this._actionGroup(e);if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no '${e}' action group`));if(!n.has_action(t))throw Error(formatDbusErrorMessage(`not-found`,`unknown action ${e}.${t}`));return n}_parseValue(e){if(!e||e===`null`)return null;try{return JSON.parse(e)}catch{throw Error(formatDbusErrorMessage(`invalid-params`,`value_json is not valid JSON: ${e}`))}}};const C=`DBUS_SESSION_BUS_ADDRESS`,re=new Set;function envEnabled(){return isDevtoolsEnabledValue(l.getenv(`GJSIFY_DEVTOOLS`))}function envValue(e){let t=l.getenv(e);return t&&t!==``?t:null}function sessionBusUsable(){if(!envValue(C))return!1;try{return x.bus_get_sync(x.BusType.SESSION,null),!0}catch{return!1}}function chooseDevtoolsTransport(e){return e.requestedAddress?{kind:`peer`,address:e.requestedAddress,reason:`requested`}:e.hasAppConnection?{kind:`session-bus`}:e.sessionBusUsable?{kind:`unregistered`}:{kind:`peer`,address:null,reason:`no-session-bus`}}function describeMissingConnection(e,t){return e?t?`[gjsify-devtools] the session bus answers but this application is not registered on it yet — call installDevtools() from the GtkApplication "startup" handler (the bus connection and object path exist only after registration).`:`[gjsify-devtools] ${C} is set (${e}) but no bus answers there — using the bus-less peer transport instead. On macOS this is the usual state: Homebrew's dbus listens on launchd, so the advertised address only works while that socket is live.`:`[gjsify-devtools] this machine has no session bus (${C} is unset) — using the bus-less peer transport instead. Point the bridge at the address below, or set ${y} on both the app and \`gjsify debug\` to pin it yourself.`}function installDevtools(e,t={}){if(!(t.enabled??envEnabled()))return null;let n=t.instance??envValue(`GJSIFY_DEVTOOLS_INSTANCE`)??void 0,r=new DevtoolsService(e,{...t,instance:n});try{return exportDevtools(e,r,t,n)}catch(e){return r.unexport(),console.error(`[gjsify-devtools] devtools stayed OFF, the app is unaffected — ${describeInstallFailure(e)}`),null}}function describeInstallFailure(e){return e instanceof DevtoolsPeerServerError||e instanceof Error?e.message:String(e)}function exportDevtools(e,t,n,r){let i=e.get_is_registered(),a=i?e.get_dbus_connection():null,o=i?e.get_dbus_object_path():null,s=envValue(C),c=!!(a&&o),u=c||sessionBusUsable(),d=chooseDevtoolsTransport({requestedAddress:n.address??envValue(y),hasAppConnection:c,sessionBusUsable:u}),f=e.get_application_id()??`unknown`,p=`${o??appIdToObjectPath(f)}/devtools`;if((d.kind===`unregistered`||d.kind===`peer`&&d.reason===`no-session-bus`)&&console.error(describeMissingConnection(s,u)),d.kind===`session-bus`&&a)t.export(a,p),console.log(`[gjsify-devtools] exported ${_} at ${p} (dest ${f})`);else if(d.kind===`peer`){let n=startDevtoolsPeerServer(t,p,d.address??void 0),i=writeDevtoolsAddressFile(devtoolsAddressFilePath(l.get_user_runtime_dir(),f,r),n.address);t.attachPeerServer(n,i),console.log(`[gjsify-devtools] exported ${_} at ${p} (peer address ${n.address}${i?`, published to ${i}`:``})`),i&&e.connect(`shutdown`,()=>removeDevtoolsAddressFile(i))}return re.add(t),t}const ie=[`AdwNavigationSplitView`,`GtkListBox`,`AdwOverlaySplitView`];function probeEnabled(){let e=l.getenv(`GJSIFY_STORYBOOK_PROBE`);if(e==null)return!1;let t=e.toLowerCase();return t!==``&&t!==`0`&&t!==`false`}function collectTypes(e,t){t.add(e.type);for(let n of e.children)collectTypes(n,t)}function installStorybookProbe(e,t,n={}){let r=n.requireChrome??ie,i=n.out??l.getenv(`GJSIFY_STORYBOOK_PROBE_OUT`)??void 0,a=n.timeoutMs??8e3,o=n.storyWidget??l.getenv(`GJSIFY_STORYBOOK_PROBE_STORY_WIDGET`)??void 0,s=t.controller.listStories(),c=[...new Set(s.map(e=>e.category))],u=n.story??l.getenv(`GJSIFY_STORYBOOK_PROBE_STORY`)??s[0]?.title,d=u?t.openStoryByTitle(u):!1,f=t.activeStory,p=new Set;collectTypes(dumpTree(t,60,`toplevel:0`),p);let m=r.filter(e=>!p.has(e)),h=new Set;f&&collectTypes(dumpTree(f,60,`story`),h);let g=h.size,_=o?h.has(o):null,finish=t=>{let n=JSON.stringify(t);if(t.ok)console.log(`STORYBOOK PROBE: PASS ${n}`);else{console.error(`STORYBOOK PROBE: FAIL ${n}`);try{typeof process<`u`&&(process.exitCode=1)}catch{}}if(i)try{l.file_set_contents(i,JSON.stringify(t,null,2))}catch{}e.quit()},v=0;l.timeout_add(l.PRIORITY_DEFAULT,100,()=>{v+=100;let e=captureWidgetPng(t),n=t.get_width()>0&&t.get_height()>0;if(!e&&!(v>=a))return l.SOURCE_CONTINUE;let i=f?captureWidgetPng(f):null,p=s.length>=1&&c.length>=1&&m.length===0&&d&&f!=null&&g>1,y;return s.length<1?y=`no stories registered`:c.length<1?y=`no categories`:m.length>0?y=`chrome missing: ${m.join(`, `)}`:!d||f==null?y=`could not open story: ${u??`(none)`}`:g<=1&&(y=`opened story rendered an empty subtree`),p&&o&&!h.has(o)&&(p=!1,y=`story widget ${o} not found in the opened story subtree`),p&&n&&(!e||e.length===0)&&(p=!1,y=`window realized (${t.get_width()}x${t.get_height()}) but the GSK capture was empty`),finish({ok:p,reason:y,stories:s.length,categories:c,opened:d,activeStory:f?f.meta.title:null,requiredChrome:r,missingChrome:m,storySubtreeWidgets:g,storyWidgetPresent:_,windowRealized:n,windowPngBytes:e?e.length:0,storyPngBytes:i?i.length:0}),l.SOURCE_REMOVE})}const ae=e(import.meta.url);let oe;function load$1(){return oe===void 0&&(oe=ae(`@gjsify/node-gi/gi`).requireGi(`Adw`,`1`)),oe}__name(load$1,`load`);var w=new Proxy(Object.create(null),{get(e,t){return load$1()[t]},has(e,t){return t in load$1()}});const T={UNKNOWN:0,CUSTOM:1,GPL_2_0:2,GPL_3_0:3,LGPL_2_1:4,LGPL_3_0:5,BSD:6,MIT_X11:7,ARTISTIC:8,GPL_2_0_ONLY:9,GPL_3_0_ONLY:10,LGPL_2_1_ONLY:11,LGPL_3_0_ONLY:12,AGPL_3_0:13,AGPL_3_0_ONLY:14,BSD_3:15,APACHE_2_0:16,MPL_2_0:17,"0BSD":18};T.GPL_2_0_ONLY,T.GPL_3_0_ONLY,T.UNKNOWN;const se=[`blue`,`teal`,`green`,`yellow`,`orange`,`red`,`pink`,`purple`,`slate`],ce={blue:`#3584e4`,teal:`#2190a4`,green:`#3a944a`,yellow:`#c88800`,orange:`#ed5b00`,red:`#e62d42`,pink:`#d56199`,purple:`#9141ac`,slate:`#6f8396`};function parseHex(e){let t=/^#([0-9a-f]{6})$/i.exec(e.trim());if(!t)return null;let n=Number.parseInt(t[1],16);return[(n>>16&255)/255,(n>>8&255)/255,(n&255)/255]}function toHex(e,t,n){let channel=e=>Math.round(Math.min(1,Math.max(0,e))*255).toString(16).padStart(2,`0`);return`#${channel(e)}${channel(t)}${channel(n)}`}const toLinear=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,fromLinear=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055;function linearToOklab(e,t,n){let r=Math.cbrt(.4122214708*e+.5363325363*t+.0514459929*n),i=Math.cbrt(.2119034982*e+.6806995451*t+.1073969566*n),a=Math.cbrt(.0883024619*e+.2817188376*t+.6299787005*n);return[.2104542553*r+.793617785*i-.0040720468*a,1.9779984951*r-2.428592205*i+.4505937099*a,.0259040371*r+.7827717662*i-.808675766*a]}function oklabToLinear(e,t,n){let r=(e+.3963377774*t+.2158037573*n)**3,i=(e-.1055613458*t-.0638541728*n)**3,a=(e-.0894841775*t-1.291485548*n)**3;return[4.0767416621*r-3.3077115913*i+.2309699292*a,-1.2684380046*r+2.6097574011*i-.3413193965*a,-.0041960863*r-.7034186147*i+1.707614701*a]}function adwaitaStandaloneColor(e,t){let n=parseHex(e);if(!n)return e;let[r,i,a]=linearToOklab(toLinear(n[0]),toLinear(n[1]),toLinear(n[2])),[o,s,c]=oklabToLinear(t?Math.max(r,.85):Math.min(r,.5),i,a);return toHex(fromLinear(o),fromLinear(s),fromLinear(c))}function adwaitaAccentBgColor(e){return ce[e]}function adwaitaAccentColor(e,t){return adwaitaStandaloneColor(ce[e],t)}Math.PI*.35,Math.PI*.015,Math.PI*.9;const le=Math.PI*.9,ue=Math.PI*.7,de=Math.PI*1.1,fe=Math.PI*1.35,pe=le+de+fe-ue;53*Math.PI*2/pe,de-ue/2;const me={system:`Follow system`,light:`Light`,dark:`Dark`},he={blue:`Blue`,teal:`Teal`,green:`Green`,yellow:`Yellow`,orange:`Orange`,red:`Red`,pink:`Pink`,purple:`Purple`,slate:`Slate`};var StorybookAppearance=class{constructor(){this._provider=null,this._applying=!1,this._styleManager=w.StyleManager.get_default(),this.settings=new StorybookSettings(()=>this._styleManager.get_dark()),this.settings.subscribe(e=>this._apply(e)),this._styleManager.connect(`notify::dark`,()=>this.settings.systemChanged()),this._apply(this.settings.state)}_apply(e){if(!this._applying){this._applying=!0;try{this._styleManager.set_color_scheme(e.colorScheme===`light`?w.ColorScheme.FORCE_LIGHT:e.colorScheme===`dark`?w.ColorScheme.FORCE_DARK:w.ColorScheme.DEFAULT),this._applyAccent(this.settings.resolvedAccent)}finally{this._applying=!1}}}_applyAccent(e){let t=f.Display.get_default();if(!t)return;if(!this._provider){if(!e)return;this._provider=new h.CssProvider,h.StyleContext.add_provider_for_display(t,this._provider,h.STYLE_PROVIDER_PRIORITY_APPLICATION)}if(!e){this._provider.load_from_string(``);return}let n=adwaitaAccentBgColor(e),r=adwaitaAccentColor(e,this.settings.resolvedDark);this._provider.load_from_string(`:root { --accent-bg-color: ${n}; --accent-color: ${r}; }`)}};function buildSwatch(e,t,n){let r=new h.CheckButton({tooltip_text:t,halign:h.Align.CENTER,valign:h.Align.CENTER,focus_on_click:!1});for(let t of e)r.add_css_class(t);return r.update_property([h.AccessibleProperty.LABEL],[t]),n&&r.set_group(n),r}function buildSwatchCard(e=!1){let t=new w.WrapBox({align:.5,child_spacing:8,line_spacing:8,margin_top:12,margin_bottom:12,margin_start:12,margin_end:12}),n=new w.Bin({child:t,hexpand:!0});return n.add_css_class(`card`),e&&n.add_css_class(`storybook-card-attached`),{card:n,row:t}}function buildAppearanceDialog(e){let t=e.settings,n=new w.PreferencesPage,r=new w.PreferencesGroup({title:`Style`}),{card:i,row:o}=buildSwatchCard(),s=null,c=new Map;for(let e of a){let n=buildSwatch([`storybook-swatch`,`storybook-scheme-swatch`,`storybook-scheme-${e}`],me[e],s);s??=n,n.set_active(t.colorScheme===e),n.connect(`toggled`,()=>{n.get_active()&&(t.colorScheme=e)}),c.set(e,n),o.append(n)}r.add(i),n.add(r);let l=new w.PreferencesGroup({title:`Accent colour`});l.add_css_class(`storybook-attached-group`);let u=new w.SwitchRow({title:`Use a custom accent colour`,subtitle:`Off follows the desktop, which owns the accent`,active:t.accentMode===`custom`});l.add(u);let{card:d,row:f}=buildSwatchCard(!0),p=null,m=new Map;for(let e of se){let n=buildSwatch([`storybook-swatch`],he[e],p);p??=n,n.set_active(t.accent===e);let r=new h.CssProvider;r.load_from_string(`checkbutton { background-color: ${adwaitaAccentBgColor(e)}; }`),n.get_style_context().add_provider(r,h.STYLE_PROVIDER_PRIORITY_APPLICATION),n.connect(`toggled`,()=>{n.get_active()&&(t.accent=e)}),m.set(e,n),f.append(n)}f.set_sensitive(t.accentMode===`custom`),u.connect(`notify::active`,()=>{t.accentMode=u.get_active()?`custom`:`system`}),l.add(d),n.add(l),t.subscribe(e=>{let t=c.get(e.colorScheme);t&&!t.get_active()&&t.set_active(!0);let n=m.get(e.accent);n&&!n.get_active()&&n.set_active(!0);let r=e.accentMode===`custom`;u.get_active()!==r&&u.set_active(r),f.set_sensitive(r)});let g=new w.PreferencesDialog({title:`Appearance`});return g.add(n),g}const ge=e(import.meta.url);let E;function load(){return E===void 0&&(E=ge("@gjsify/node-gi/gi").requireGi(`GObject`,`2.0`)),E}var D=new Proxy(Object.create(null),{get(e,t){return load()[t]},has(e,t){return t in load()}});function adwControlWidgetFactory(){return{text(e,t){let n=new w.EntryRow({title:e});t&&n.set_tooltip_text(t);let r=null;return n.connect(`changed`,()=>r?.(n.get_text())),{node:n,get:()=>n.get_text(),set:e=>n.set_text(e),onChange:e=>{r=e}}},boolean(e,t){let n=new w.SwitchRow({title:e,subtitle:t??``}),r=null;return n.connect(`notify::active`,()=>r?.(n.get_active())),{node:n,get:()=>n.get_active(),set:e=>n.set_active(e),onChange:e=>{r=e}}},number(e){let t=w.SpinRow.new_with_range(e.min??0,e.max??100,e.step??1);t.set_title(e.label||e.name),e.description&&t.set_subtitle(e.description);let n=null;return t.connect(`changed`,()=>n?.(t.get_value())),{node:t,get:()=>t.get_value(),set:e=>t.set_value(e),onChange:e=>{n=e}}},range(e){return buildRangeWidget(e)},select(e){return buildSelectWidget(e)},color(e,t){return buildColorWidget(e,t)}}}function buildRangeWidget(e){let t=e.min??0,n=e.max??100,r=e.step??1,i=typeof e.min==`number`?e.min:0,a=Number.isInteger(r)&&Number.isInteger(i),o=new h.Adjustment({lower:t,upper:n,step_increment:r,value:i});o.step_increment=r;let s=new h.ListBoxRow({selectable:!1,activatable:!1});s.add_css_class(`story-range-row`);let c=new h.Box({orientation:h.Orientation.VERTICAL,spacing:6,margin_top:12,margin_bottom:12,margin_start:12,margin_end:12}),l=new h.Box({orientation:h.Orientation.HORIZONTAL,spacing:12}),u=new h.Label({label:e.label||e.name,halign:h.Align.START,hexpand:!0,ellipsize:3});u.add_css_class(`heading`);let formatValue=e=>a?String(Math.round(e)):e.toFixed(2),d=new h.Label({label:formatValue(i),halign:h.Align.END});if(d.add_css_class(`numeric`),d.add_css_class(`dim-label`),l.append(u),l.append(d),c.append(l),e.description){let t=new h.Label({label:e.description,halign:h.Align.START,xalign:0,wrap:!0,max_width_chars:32});t.add_css_class(`caption`),t.add_css_class(`dim-label`),c.append(t)}let f=new h.Scale({orientation:h.Orientation.HORIZONTAL,adjustment:o,draw_value:!1,hexpand:!0}),p=null,m=!1;return f.connect(`value-changed`,()=>{if(m)return;let e=f.get_value();if(a){let t=Math.round(e);if(t!==e){f.set_value(t);return}e=t}d.set_label(formatValue(e)),p?.(e)}),c.append(f),s.set_child(c),{node:s,get:()=>f.get_value(),set:e=>{m=!0,f.set_value(e),m=!1,d.set_label(formatValue(e))},onChange:e=>{p=e}}}function buildSelectWidget(e){let t=e.options??[],n=h.StringList.new(t.map(e=>e.label)),r=new w.ComboRow({title:e.label||e.name,subtitle:e.description??``,model:n}),i=null;return r.connect(`notify::selected`,()=>i?.(r.get_selected())),{node:r,get:()=>r.get_selected(),set:e=>r.set_selected(e),onChange:e=>{i=e}}}function buildColorWidget(e,t){let n=new w.ActionRow({title:e,subtitle:t??``}),r=new h.ColorDialogButton({dialog:new h.ColorDialog({title:e}),valign:h.Align.CENTER});n.add_suffix(r),n.set_activatable_widget(r);let channel=e=>Math.round(Math.max(0,Math.min(1,e))*255).toString(16).padStart(2,`0`),rgbaToHex=e=>`#${channel(e.red)}${channel(e.green)}${channel(e.blue)}`,i=null,a=!1;return r.connect(`notify::rgba`,()=>{a||i?.(rgbaToHex(r.get_rgba()))}),{node:n,get:()=>rgbaToHex(r.get_rgba()),set:e=>{let t=new f.RGBA;t.parse(e)&&(a=!0,r.set_rgba(t),a=!1)},onChange:e=>{i=e}}}var _e=class StorybookWindow extends w.ApplicationWindow{static{D.registerClass({GTypeName:`StorybookWindow`},StorybookWindow)}constructor(e){super(e),this._appearance=new StorybookAppearance,this._controlRows=[],this._rowByTitle=new Map,this._onSelect=null,this._suppressSelect=!1,this.set_default_size(1200,800),this.set_size_request(360,320),this.set_title(`Storybook`),this._buildUI(),this._controller=new StorybookController(this,e=>this._buildControls(e)),this._sidebar_list.connect(`row-selected`,this._onRowSelected.bind(this)),this._show_controls_button.connect(`toggled`,this._onToggleControls.bind(this)),this._controls_split_view.set_show_sidebar(!0)}_onRowSelected(e,t){if(this._suppressSelect||!t)return;let n=t;n.storyWidget&&this._onSelect?.(n.storyWidget)}get controller(){return this._controller}_buildControls(e){let t=e.meta.controls;if(!Array.isArray(t))return[];let n=adwControlWidgetFactory(),r=[];for(let i of t){if(!i?.name||!i?.type){console.warn(`Invalid control configuration:`,i);continue}let t=bindControl(e,i,n);t&&r.push(t)}return r}_buildUI(){this._sidebar_list=new h.ListBox({selection_mode:h.SelectionMode.SINGLE}),this._sidebar_list.add_css_class(`navigation-sidebar`);let e=new h.ScrolledWindow({hexpand:!0,vexpand:!0,child:this._sidebar_list}),t=new w.HeaderBar({title_widget:new w.WindowTitle({title:`Stories`}),show_end_title_buttons:!1}),n=new w.ToolbarView({content:e,top_bar_style:w.ToolbarStyle.FLAT});n.add_top_bar(t);let r=new w.NavigationPage({title:`Stories`,tag:`stories`,child:n});this._content_area=new w.Bin({hexpand:!0,vexpand:!0});let i=new h.ScrolledWindow({hexpand:!0,vexpand:!0,child:this._content_area});i.add_css_class(`sb-preview-area`),this._control_panel=new w.PreferencesGroup({title:`Controls`});let a=new w.PreferencesPage;a.add(this._control_panel);let o=new h.ScrolledWindow({vexpand:!0,child:a});this._controls_split_view=new w.OverlaySplitView({show_sidebar:!0,sidebar_position:h.PackType.END,min_sidebar_width:280,max_sidebar_width:360,content:i,sidebar:o,css_classes:[`storybook-controls`]}),this._preview_title=new w.WindowTitle({title:`Preview`}),this._show_controls_button=new h.ToggleButton({icon_name:`sidebar-show-right-symbolic`,tooltip_text:`Toggle Controls`,active:!0});let s=new w.HeaderBar({title_widget:this._preview_title});s.pack_end(this._show_controls_button);let c=new h.Button({icon_name:`applications-graphics-symbolic`,tooltip_text:`Appearance`});c.connect(`clicked`,()=>buildAppearanceDialog(this._appearance).present(this)),s.pack_end(c);let l=new w.ToolbarView({content:this._controls_split_view,top_bar_style:w.ToolbarStyle.FLAT});l.add_top_bar(s);let u=new w.NavigationPage({title:`Preview`,tag:`preview`,child:l});this._main_split_view=new w.NavigationSplitView({min_sidebar_width:220,max_sidebar_width:320,sidebar:r,content:u}),this.set_content(this._main_split_view);let d=w.BreakpointCondition.parse(`max-width: 720sp`);if(d){let e=new w.Breakpoint({condition:d});e.connect(`apply`,()=>{this._main_split_view.collapsed=!0,this._controls_split_view.collapsed=!0}),e.connect(`unapply`,()=>{this._main_split_view.collapsed=!1,this._controls_split_view.collapsed=!1}),this.add_breakpoint(e)}}_onToggleControls(e){this._controls_split_view.set_show_sidebar(e.get_active())}populateSidebar(e){this._controller.mount(e,!0)}renderSidebar(e,t){this._onSelect=t,this._suppressSelect=!0,this._clearSidebar(),this._rowByTitle.clear();for(let t of e){this._addCategoryToSidebar(t.category);for(let{instance:e,name:n}of t.stories)this._addStoryToSidebar(e,n)}this._suppressSelect=!1}markSelected(e){let t=this._rowByTitle.get(e);t&&this._sidebar_list.get_selected_row()!==t&&(this._suppressSelect=!0,this._sidebar_list.select_row(t),this._suppressSelect=!1)}setPreviewTitle(e){this._preview_title.set_title(e)}showPreview(e){this._content_area.set_child(e),this._main_split_view.get_collapsed()&&this._main_split_view.set_show_content(!0)}renderControls(e){this._clearControlPanel();for(let t of e){let e=t.view;e instanceof w.PreferencesRow&&e.set_use_markup(!1),this._control_panel.add(e),this._controlRows.push(e)}this._show_controls_button.set_active(!0)}_clearSidebar(){let e=this._sidebar_list.get_first_child();for(;e;){let t=e.get_next_sibling();e.unparent(),e=t}}_addCategoryToSidebar(e){let t=new h.ListBoxRow({selectable:!1}),n=new h.Label({label:e,halign:h.Align.START,margin_top:10,margin_bottom:4,margin_start:12,margin_end:12});n.add_css_class(`heading`),n.add_css_class(`dim-label`),t.set_child(n),this._sidebar_list.append(t)}_addStoryToSidebar(e,t){let n=new h.ListBoxRow,r=new h.Label({label:t||`Unnamed Story`,halign:h.Align.START,margin_start:20,margin_top:6,margin_bottom:6});n.set_child(r),this._sidebar_list.append(n),n.storyWidget=e,this._rowByTitle.set(e.meta.title,n)}_clearControlPanel(){for(let e of this._controlRows)this._control_panel.remove(e);this._controlRows=[]}get activeStory(){return this._controller.activeStory}openStoryByTitle(e){return this._controller.openStoryByTitle(e)}setActiveArg(e,t){return this._controller.setActiveArg(e,t)}};D.type_ensure(_e.$gtype);var ve=class StorybookApplication extends w.Application{static{D.registerClass({GTypeName:`StorybookApplication`},StorybookApplication)}constructor(e){super({application_id:e.applicationId,flags:x.ApplicationFlags.DEFAULT_FLAGS}),this._window=null,this._options=e,this.connect(`startup`,()=>this._initStyles()),this.connect(`activate`,()=>this._onActivate())}_initStyles(){let e=new h.CssProvider;e.load_from_string(`
73
+ </node>`}const ee=e(import.meta.url);let b;function load$3(){return b===void 0&&(b=ee(`@gjsify/node-gi/gi`).requireGi(`Gio`,`2.0`)),b}__name(load$3,`load`);var x=new Proxy(Object.create(null),{get(e,t){return load$3()[t]},has(e,t){return t in load$3()}});function isWin32(){return l.DIR_SEPARATOR===92}function defaultListenAddress(){return isWin32()?`nonce-tcp:host=127.0.0.1`:`unix:tmpdir=${l.get_tmp_dir()}`}var DevtoolsPeerServerError=class extends Error{constructor(e,t,n,r){super(e),this.address=t,this.reason=n,this.name=`DevtoolsPeerServerError`,this.cause=r}};function isAddressInUse(e){return e instanceof l.Error&&e.matches(x.io_error_quark(),x.IOErrorEnum.ADDRESS_IN_USE)}function unixSocketPath(e){if(!e.startsWith(`unix:`))return null;for(let t of e.slice(5).split(`,`)){let e=t.indexOf(`=`);if(!(e<0||t.slice(0,e)!==`path`))try{return decodeURIComponent(t.slice(e+1))}catch{return null}}return null}function inspectExistingSocket(e){try{if((x.File.new_for_path(e).query_info(`unix::mode`,x.FileQueryInfoFlags.NONE,null).get_attribute_uint32(`unix::mode`)&61440)!=49152)return`not-a-socket`}catch{return`not-a-socket`}let t=new x.SocketClient;t.set_timeout(2);let n;try{n=t.connect(x.UnixSocketAddress.new(e),null)}catch{return`dead`}return n.close(null),`live`}function clearReclaimableSocket(e){let t=unixSocketPath(e);if(!t||!l.file_test(t,l.FileTest.EXISTS))return;let n=inspectExistingSocket(t);if(n===`live`)throw new DevtoolsPeerServerError(`cannot listen on ${e}: another process is already listening there. Stop it, or point ${y} (or options.address) at a different socket — GJSIFY_DEVTOOLS_INSTANCE=<label> lets two devtools-enabled apps run side by side.`,e,`address-in-use`);if(n===`not-a-socket`)throw new DevtoolsPeerServerError(`cannot listen on ${e}: ${t} already exists and is not a socket, so it will NOT be removed. Point ${y} (or options.address) at a free path.`,e,`occupied-by-other-file`);try{x.File.new_for_path(t).delete(null)}catch(n){throw new DevtoolsPeerServerError(`cannot listen on ${e}: ${t} is a socket nothing listens on, but removing it failed (${n}). Delete it by hand, or point ${y} at a free path.`,e,`address-in-use`,n)}console.log(`[gjsify-devtools] reclaimed the stale socket ${t}: nothing was listening on it (an abnormal exit — Ctrl-C, SIGKILL, a crash — leaves the inode behind).`)}function flagsForAddress(e){return e.startsWith(`tcp:`)||e.startsWith(`nonce-tcp:`)?x.DBusServerFlags.NONE:x.DBusServerFlags.AUTHENTICATION_REQUIRE_SAME_USER}function startDevtoolsPeerServer(e,t,n){let r=n&&n!==``?n:defaultListenAddress();clearReclaimableSocket(r);let i;try{i=x.DBusServer.new_sync(r,flagsForAddress(r),x.dbus_generate_guid(),null,null)}catch(e){let t=isAddressInUse(e);throw new DevtoolsPeerServerError(t?`cannot listen on ${r}: the address is already in use (${e}). Stop whatever holds it, or point ${y} (or options.address) at a different address.`:`cannot listen on ${r}: ${e}. Check the address form — \`unix:path=/tmp/app.sock\`, \`unix:tmpdir=/tmp\` or \`nonce-tcp:host=127.0.0.1\`.`,r,t?`address-in-use`:`listen-failed`,e)}let a=new Set;i.connect(`new-connection`,(n,r)=>(a.add(r),r.connect(`closed`,()=>{e.unexport(r),a.delete(r)}),e.export(r,t),!0)),i.start();let o=!1;return{address:i.get_client_address(),objectPath:t,get connectionCount(){return a.size},stop(){if(!o){o=!0,i.stop();for(let t of a)e.unexport(t),!t.is_closed()&&t.close(null,(e,t)=>{try{e.close_finish(t)}catch{}});a.clear()}}}}function writeDevtoolsAddressFile(e,t){try{if(l.mkdir_with_parents(l.path_get_dirname(e),448),!l.file_set_contents(e,`${t}\n`))return null}catch(t){return console.error(`[gjsify-devtools] could not publish the peer address to ${e}: ${t}`),null}try{x.File.new_for_path(e).set_attribute_uint32(`unix::mode`,384,x.FileQueryInfoFlags.NONE,null)}catch(t){console.error(`[gjsify-devtools] could not restrict ${e} to the current user: ${t}`)}return e}function removeDevtoolsAddressFile(e){try{x.File.new_for_path(e).delete(null)}catch{}}const te=e(import.meta.url);let S;function load$2(){return S===void 0&&(S=te(`@gjsify/node-gi/gi`).requireGi(`Graphene`,`1.0`)),S}__name(load$2,`load`);var ne=new Proxy(Object.create(null),{get(e,t){return load$2()[t]},has(e,t){return t in load$2()}});function captureWidgetPng(e){let t=e.get_native()?.get_renderer();if(!t)return null;let n=e.get_width(),r=e.get_height();if(n<=0||r<=0)return null;let i=h.WidgetPaintable.new(e),a=h.Snapshot.new();i.snapshot(a,n,r);let o=a.to_node();if(!o)return null;let s=new ne.Rect;s.init(0,0,n,r);let c=t.render_texture(o,s).save_to_png_bytes().get_data();return c?new Uint8Array(c):null}function dumpGSettings(e){let t=x.SettingsSchemaSource.get_default()?.lookup(e,!0);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`GSettings schema '${e}' is not installed`));let n=new x.Settings({settings_schema:t}),r={};for(let e of t.list_keys())r[e]=n.get_value(e).recursiveUnpack();return r}function parseWidgetPath(e){let t=e.split(`/`).filter(e=>e.length>0);if(t.length===0)return null;let n=t[0].match(/^toplevel:(\d+)$/);if(!n)return null;let r=[];for(let e of t.slice(1)){let t=e.match(/^child:(\d+)$/);if(!t)return null;r.push(Number(t[1]))}return{toplevel:Number(n[1]),children:r}}function buildWidgetPath(e,t){return[`toplevel:${e}`,...t.map(e=>`child:${e}`)].join(`/`)}function widgetType(e){return gtypeName(e)??`GtkWidget`}function gtypeName(e){let t=e;return typeof t?.$typeName==`string`&&t.$typeName.length>0?t.$typeName:t?.constructor?.$gtype?.name??null}function activateWidget(e){let t=e;if(typeof t.activate==`function`&&t.activate()===!0)return!0;let n=typeof t.get_parent==`function`?t.get_parent():null;if(n&&widgetType(n)===`GtkListBox`){let t=n,r=!1;return typeof t.select_row==`function`&&(t.select_row(e),r=!0),typeof t.emit==`function`&&(t.emit(`row-activated`,e),r=!0),r}return!1}function sendKeyToWidget(e,t,n){let r=e.observe_controllers(),i=!1;for(let e=0;e<r.get_n_items();e++){let a=r.get_item(e);gtypeName(a)===`GtkEventControllerKey`&&(a.emit(`key-pressed`,t,0,n),i=!0)}return i}function nthChild(e,t){let n=e.get_first_child(),r=0;for(;n&&r<t;)n=n.get_next_sibling(),r++;return r===t?n:null}function listToplevels(){let e=h.Window.get_toplevels(),t=e.get_n_items(),n=[];for(let r=0;r<t;r++){let t=e.get_item(r);t&&n.push({path:`toplevel:${r}`,type:widgetType(t),title:t.get_title?.()??null,mapped:t.get_mapped(),focused:t.is_active??!1})}return n}function resolveWidgetPath(e){let t=parseWidgetPath(e);if(!t)return null;let n=h.Window.get_toplevels().get_item(t.toplevel);if(!n)return null;for(let e of t.children)if(n=nthChild(n,e),!n)return null;return n}function parseWidgetSelector(e){let t=e.indexOf(`:`),n=(t<0?e:e.slice(0,t)).trim(),r=(t<0?``:e.slice(t+1)).trim();return!n&&!r?null:{type:n,cssClass:r}}function findWidgetPath(e,t,n){if(!e.get_visible()||!e.get_mapped())return null;let r=!t.type||widgetType(e)===t.type,i=!t.cssClass||e.get_css_classes().includes(t.cssClass);if(r&&i)return n;let a=e.get_first_child(),o=0;for(;a;){let e=findWidgetPath(a,t,`${n}/child:${o}`);if(e)return e;a=a.get_next_sibling(),o++}return null}function dumpTree(e,t,n){let r={path:n,type:widgetType(e),name:e.get_name()||null,cssClasses:e.get_css_classes(),mapped:e.get_mapped(),visible:e.get_visible(),children:[]};if(t<=0)return e.get_first_child()&&(r.truncated=!0),r;let i=e.get_first_child(),a=0;for(;i;)r.children.push(dumpTree(i,t-1,`${n}/child:${a}`)),i=i.get_next_sibling(),a++;return r}function jsonSafe(e){let t=typeof e;return e==null||t===`string`||t===`number`||t===`boolean`?e??null:`[${t}]`}function getWidgetProperty(e,t){let n=e,r=t.replace(/-/g,`_`),i=t.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase());for(let e of[t,r,i])if(e in n)return jsonSafe(n[e])}function childIndex(e,t){let n=e.get_first_child(),r=0;for(;n;){if(n===t)return r;n=n.get_next_sibling(),r++}return-1}function pathOfWidget(e){let t=[],n=e,r=n.get_parent();for(;r;){let e=childIndex(r,n);if(e<0)return null;t.unshift(e),n=r,r=n.get_parent()}let i=h.Window.get_toplevels(),a=i.get_n_items();for(let e=0;e<a;e++)if(i.get_item(e)===n)return buildWidgetPath(e,t);return null}function isActiveWindowScope(e){return!e||e===`window`||e===`active`}function frameDelay(e){return new Promise(t=>{l.timeout_add(l.PRIORITY_DEFAULT,e,()=>(t(),l.SOURCE_REMOVE))})}async function captureWidgetWhenRenderable(e,t=12,n=50){for(let r=0;r<t;r++){let t=captureWidgetPng(e);if(t)return t;await frameDelay(n)}return captureWidgetPng(e)}var DevtoolsService=class{constructor(e,t){this._app=e,this._options=t,this._exported=new Map,this._peer=null,this._addressFile=null,this._kinds=new Map,this._extensions=t.extend??[];for(let[e,t]of Object.entries(v))this._kinds.set(e,t);for(let e of this._extensions){for(let[t,n]of Object.entries(e.methodKinds))this._kinds.set(t,n);for(let[t,n]of Object.entries(e.handlers)){let e=n;this[t]=(...n)=>(this._guard(t),e(...n))}}}export(e,t){if(this._exported.has(e))return;let n=buildDevtoolsIfaceXml(this._extensions.flatMap(e=>e.methodsXml??[])),r=x.DBusExportedObject.wrapJSObject(n,this);r.export(e,t),this._exported.set(e,r)}unexport(e){if(e){this._exported.get(e)?.unexport(),this._exported.delete(e);return}for(let e of this._exported.values())e.unexport();this._exported.clear(),this._peer?.stop(),this._peer=null,this._addressFile&&=(removeDevtoolsAddressFile(this._addressFile),null)}attachPeerServer(e,t){this._peer=e,this._addressFile=t??null}get peerAddress(){return this._peer?.address??null}get addressFile(){return this._addressFile}GetStatus(){let e=this._app.get_active_window(),t={appId:this._app.get_application_id()??`unknown`,instance:this._options.instance??`default`,activeWindow:e?{id:e.get_name()||`window`,title:e.get_title()??``,mapped:e.get_mapped()}:null,toplevelCount:h.Window.get_toplevels().get_n_items(),focusedWidget:null,paused:this._isPaused()};for(let e of this._extensions){let n=e.contributeStatus?.();n&&Object.assign(t,n)}return JSON.stringify(t)}async ScreenshotAsync(e,t){try{let n=typeof e?.[0]==`string`?e[0]:``,r=await this._captureScopePng(n);t.return_value(new l.Variant(`(ay)`,[r]))}catch(e){t.return_dbus_error(`org.gjsify.Devtools.Error.Screenshot`,e instanceof Error?e.message:String(e))}}async _captureScopePng(e){let t=this._resolveRootWidget(e);if(!t){if(isActiveWindowScope(e))return new Uint8Array;throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`))}let n=captureWidgetPng(t.widget);if(!n){let e=t.widget.get_root();e instanceof h.Window&&e.present(),n=await captureWidgetWhenRenderable(t.widget)}return n??new Uint8Array}ListActions(){let e={app:describeActions(this._actionGroup(`app`)),win:describeActions(this._actionGroup(`win`))};return JSON.stringify(e)}ActivateAction(e,t,n){this._guard(`ActivateAction`);let r=this._scope(e);activateAction(this._requireGroup(r,t),t,this._parseValue(n))}ChangeActionState(e,t,n){this._guard(`ChangeActionState`);let r=this._scope(e);changeActionState(this._requireGroup(r,t),t,this._parseValue(n))}PresentWindow(){this._app.get_active_window()?.present()}ResizeWindow(e,t){this._guard(`ResizeWindow`);let n=this._app.get_active_window();if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no active window to resize`));let r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(t));return n.is_maximized()&&n.unmaximize(),n.is_fullscreen()&&n.unfullscreen(),n.set_default_size(r,i),[r,i]}ListToplevels(){return JSON.stringify(listToplevels())}DumpTree(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e||`active window`}'`));return JSON.stringify(dumpTree(n.widget,t>0?t:40,n.path))}GetProperty(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));let r=getWidgetProperty(n.widget,t);if(r===void 0)throw Error(formatDbusErrorMessage(`not-found`,`widget has no property '${t}'`));return JSON.stringify(r)}GetFocused(){let e=this._app.get_active_window(),t=e?e.get_focus():null;return JSON.stringify(t?{path:pathOfWidget(t),name:t.get_name()||null,type:widgetType(t)}:null)}ActivateWidget(e){this._guard(`ActivateWidget`);let t=this._resolveRootWidget(e);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));return activateWidget(t.widget)}FindWidget(e){let t=parseWidgetSelector(e);if(!t)throw Error(formatDbusErrorMessage(`invalid-params`,`empty selector '${e}'`));let n=this._resolveRootWidget(``);return n?findWidgetPath(n.widget,t,n.path)??``:``}SendKey(e,t){this._guard(`SendKey`);let[n,r,i]=h.accelerator_parse(e);if(!n)throw Error(formatDbusErrorMessage(`invalid-params`,`cannot parse accelerator '${e}'`));let a;if(a=t?this._resolveRootWidget(t)?.widget??null:this._app.get_active_window()?.get_focus()??null,!a)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${t||`focus`}'`));return sendKeyToWidget(a,r,i??0)}DumpGSettings(e){return JSON.stringify(dumpGSettings(e))}DumpCss(){return JSON.stringify(dumpCss())}SwapCss(e,t){return this._guard(`SwapCss`),swapCss(e,t)}_resolveRootWidget(e){if(isActiveWindowScope(e)){let e=this._app.get_active_window();return e?{widget:e,path:pathOfWidget(e)??`toplevel:0`}:null}let t=resolveWidgetPath(e);return t?{widget:t,path:e}:null}_isPaused(){return this._options.paused?.()??!1}_guard(e){let t=this._kinds.get(e);if(!t)throw Error(formatDbusErrorMessage(`internal`,`unclassified devtools method '${e}'`));if(t===`mutating`&&this._isPaused())throw Error(formatDbusErrorMessage(`paused`,`${e} rejected — external control is paused. Read-only methods keep working.`))}_scope(e){return e===`app`?`app`:`win`}_actionGroup(e){if(e===`app`)return this._app;if(this._options.winActionGroup)return this._options.winActionGroup;let t=this._app.get_active_window();return t instanceof h.ApplicationWindow?t:null}_requireGroup(e,t){let n=this._actionGroup(e);if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no '${e}' action group`));if(!n.has_action(t))throw Error(formatDbusErrorMessage(`not-found`,`unknown action ${e}.${t}`));return n}_parseValue(e){if(!e||e===`null`)return null;try{return JSON.parse(e)}catch{throw Error(formatDbusErrorMessage(`invalid-params`,`value_json is not valid JSON: ${e}`))}}};const C=`DBUS_SESSION_BUS_ADDRESS`,re=new Set;function envEnabled(){return isDevtoolsEnabledValue(l.getenv(`GJSIFY_DEVTOOLS`))}function envValue(e){let t=l.getenv(e);return t&&t!==``?t:null}function sessionBusUsable(){if(!envValue(C))return!1;try{return x.bus_get_sync(x.BusType.SESSION,null),!0}catch{return!1}}function chooseDevtoolsTransport(e){return e.requestedAddress?{kind:`peer`,address:e.requestedAddress,reason:`requested`}:e.hasAppConnection?{kind:`session-bus`}:e.sessionBusUsable?{kind:`unregistered`}:{kind:`peer`,address:null,reason:`no-session-bus`}}function describeMissingConnection(e,t){return e?t?`[gjsify-devtools] the session bus answers but this application is not registered on it yet — call installDevtools() from the GtkApplication "startup" handler (the bus connection and object path exist only after registration).`:`[gjsify-devtools] ${C} is set (${e}) but no bus answers there — using the bus-less peer transport instead. On macOS this is the usual state: Homebrew's dbus listens on launchd, so the advertised address only works while that socket is live.`:`[gjsify-devtools] this machine has no session bus (${C} is unset) — using the bus-less peer transport instead. Point the bridge at the address below, or set ${y} on both the app and \`gjsify debug\` to pin it yourself.`}function installDevtools(e,t={}){if(!(t.enabled??envEnabled()))return null;let n=t.instance??envValue(`GJSIFY_DEVTOOLS_INSTANCE`)??void 0,r=new DevtoolsService(e,{...t,instance:n});try{return exportDevtools(e,r,t,n)}catch(e){return r.unexport(),console.error(`[gjsify-devtools] devtools stayed OFF, the app is unaffected — ${describeInstallFailure(e)}`),null}}function describeInstallFailure(e){return e instanceof DevtoolsPeerServerError||e instanceof Error?e.message:String(e)}function exportDevtools(e,t,n,r){let i=e.get_is_registered(),a=i?e.get_dbus_connection():null,o=i?e.get_dbus_object_path():null,s=envValue(C),c=!!(a&&o),u=c||sessionBusUsable(),d=chooseDevtoolsTransport({requestedAddress:n.address??envValue(y),hasAppConnection:c,sessionBusUsable:u}),f=e.get_application_id()??`unknown`,p=`${o??appIdToObjectPath(f)}/devtools`;if((d.kind===`unregistered`||d.kind===`peer`&&d.reason===`no-session-bus`)&&console.error(describeMissingConnection(s,u)),d.kind===`session-bus`&&a)t.export(a,p),console.log(`[gjsify-devtools] exported ${_} at ${p} (dest ${f})`);else if(d.kind===`peer`){let n=startDevtoolsPeerServer(t,p,d.address??void 0),i=writeDevtoolsAddressFile(devtoolsAddressFilePath(l.get_user_runtime_dir(),f,r),n.address);t.attachPeerServer(n,i),console.log(`[gjsify-devtools] exported ${_} at ${p} (peer address ${n.address}${i?`, published to ${i}`:``})`),i&&e.connect(`shutdown`,()=>removeDevtoolsAddressFile(i))}return re.add(t),t}const ie=[`AdwNavigationSplitView`,`GtkListBox`,`AdwOverlaySplitView`];function probeEnabled(){let e=l.getenv(`GJSIFY_STORYBOOK_PROBE`);if(e==null)return!1;let t=e.toLowerCase();return t!==``&&t!==`0`&&t!==`false`}function collectTypes(e,t){t.add(e.type);for(let n of e.children)collectTypes(n,t)}function installStorybookProbe(e,t,n={}){let r=n.requireChrome??ie,i=n.out??l.getenv(`GJSIFY_STORYBOOK_PROBE_OUT`)??void 0,a=n.timeoutMs??8e3,o=n.storyWidget??l.getenv(`GJSIFY_STORYBOOK_PROBE_STORY_WIDGET`)??void 0,s=t.controller.listStories(),c=[...new Set(s.map(e=>e.category))],u=n.story??l.getenv(`GJSIFY_STORYBOOK_PROBE_STORY`)??s[0]?.title,d=u?t.openStoryByTitle(u):!1,f=t.activeStory,p=new Set;collectTypes(dumpTree(t,60,`toplevel:0`),p);let m=r.filter(e=>!p.has(e)),h=new Set;f&&collectTypes(dumpTree(f,60,`story`),h);let g=h.size,_=o?h.has(o):null,finish=t=>{let n=JSON.stringify(t);if(t.ok)console.log(`STORYBOOK PROBE: PASS ${n}`);else{console.error(`STORYBOOK PROBE: FAIL ${n}`);try{typeof process<`u`&&(process.exitCode=1)}catch{}}if(i)try{l.file_set_contents(i,JSON.stringify(t,null,2))}catch{}e.quit()},v=0;l.timeout_add(l.PRIORITY_DEFAULT,100,()=>{v+=100;let e=captureWidgetPng(t),n=t.get_width()>0&&t.get_height()>0;if(!e&&!(v>=a))return l.SOURCE_CONTINUE;let i=f?captureWidgetPng(f):null,p=s.length>=1&&c.length>=1&&m.length===0&&d&&f!=null&&g>1,y;return s.length<1?y=`no stories registered`:c.length<1?y=`no categories`:m.length>0?y=`chrome missing: ${m.join(`, `)}`:!d||f==null?y=`could not open story: ${u??`(none)`}`:g<=1&&(y=`opened story rendered an empty subtree`),p&&o&&!h.has(o)&&(p=!1,y=`story widget ${o} not found in the opened story subtree`),p&&n&&(!e||e.length===0)&&(p=!1,y=`window realized (${t.get_width()}x${t.get_height()}) but the GSK capture was empty`),finish({ok:p,reason:y,stories:s.length,categories:c,opened:d,activeStory:f?f.meta.title:null,requiredChrome:r,missingChrome:m,storySubtreeWidgets:g,storyWidgetPresent:_,windowRealized:n,windowPngBytes:e?e.length:0,storyPngBytes:i?i.length:0}),l.SOURCE_REMOVE})}const ae=e(import.meta.url);let oe;function load$1(){return oe===void 0&&(oe=ae(`@gjsify/node-gi/gi`).requireGi(`Adw`,`1`)),oe}__name(load$1,`load`);var w=new Proxy(Object.create(null),{get(e,t){return load$1()[t]},has(e,t){return t in load$1()}});const T={UNKNOWN:0,CUSTOM:1,GPL_2_0:2,GPL_3_0:3,LGPL_2_1:4,LGPL_3_0:5,BSD:6,MIT_X11:7,ARTISTIC:8,GPL_2_0_ONLY:9,GPL_3_0_ONLY:10,LGPL_2_1_ONLY:11,LGPL_3_0_ONLY:12,AGPL_3_0:13,AGPL_3_0_ONLY:14,BSD_3:15,APACHE_2_0:16,MPL_2_0:17,"0BSD":18};T.GPL_2_0_ONLY,T.GPL_3_0_ONLY,T.UNKNOWN;const se=[`blue`,`teal`,`green`,`yellow`,`orange`,`red`,`pink`,`purple`,`slate`],ce={blue:`#3584e4`,teal:`#2190a4`,green:`#3a944a`,yellow:`#c88800`,orange:`#ed5b00`,red:`#e62d42`,pink:`#d56199`,purple:`#9141ac`,slate:`#6f8396`};function parseHex(e){let t=/^#([0-9a-f]{6})$/i.exec(e.trim());if(!t)return null;let n=Number.parseInt(t[1],16);return[(n>>16&255)/255,(n>>8&255)/255,(n&255)/255]}function toHex(e,t,n){let channel=e=>Math.round(Math.min(1,Math.max(0,e))*255).toString(16).padStart(2,`0`);return`#${channel(e)}${channel(t)}${channel(n)}`}const toLinear=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,fromLinear=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055;function linearToOklab(e,t,n){let r=Math.cbrt(.4122214708*e+.5363325363*t+.0514459929*n),i=Math.cbrt(.2119034982*e+.6806995451*t+.1073969566*n),a=Math.cbrt(.0883024619*e+.2817188376*t+.6299787005*n);return[.2104542553*r+.793617785*i-.0040720468*a,1.9779984951*r-2.428592205*i+.4505937099*a,.0259040371*r+.7827717662*i-.808675766*a]}function oklabToLinear(e,t,n){let r=(e+.3963377774*t+.2158037573*n)**3,i=(e-.1055613458*t-.0638541728*n)**3,a=(e-.0894841775*t-1.291485548*n)**3;return[4.0767416621*r-3.3077115913*i+.2309699292*a,-1.2684380046*r+2.6097574011*i-.3413193965*a,-.0041960863*r-.7034186147*i+1.707614701*a]}function adwaitaStandaloneColor(e,t){let n=parseHex(e);if(!n)return e;let[r,i,a]=linearToOklab(toLinear(n[0]),toLinear(n[1]),toLinear(n[2])),[o,s,c]=oklabToLinear(t?Math.max(r,.85):Math.min(r,.5),i,a);return toHex(fromLinear(o),fromLinear(s),fromLinear(c))}function adwaitaAccentBgColor(e){return ce[e]}function adwaitaAccentColor(e,t){return adwaitaStandaloneColor(ce[e],t)}Math.PI*.35,Math.PI*.015,Math.PI*.9;const le=Math.PI*.9,ue=Math.PI*.7,de=Math.PI*1.1,fe=Math.PI*1.35,pe=le+de+fe-ue;53*Math.PI*2/pe,de-ue/2;const me={system:`Follow system`,light:`Light`,dark:`Dark`},he={blue:`Blue`,teal:`Teal`,green:`Green`,yellow:`Yellow`,orange:`Orange`,red:`Red`,pink:`Pink`,purple:`Purple`,slate:`Slate`};var StorybookAppearance=class{constructor(){this._provider=null,this._applying=!1,this._styleManager=w.StyleManager.get_default(),this.settings=new StorybookSettings(()=>this._styleManager.get_dark()),this.settings.subscribe(e=>this._apply(e)),this._styleManager.connect(`notify::dark`,()=>this.settings.systemChanged()),this._apply(this.settings.state)}_apply(e){if(!this._applying){this._applying=!0;try{this._styleManager.set_color_scheme(e.colorScheme===`light`?w.ColorScheme.FORCE_LIGHT:e.colorScheme===`dark`?w.ColorScheme.FORCE_DARK:w.ColorScheme.DEFAULT),this._applyAccent(this.settings.resolvedAccent)}finally{this._applying=!1}}}_applyAccent(e){let t=f.Display.get_default();if(!t)return;if(!this._provider){if(!e)return;this._provider=new h.CssProvider,h.StyleContext.add_provider_for_display(t,this._provider,h.STYLE_PROVIDER_PRIORITY_APPLICATION)}if(!e){this._provider.load_from_string(``);return}let n=adwaitaAccentBgColor(e),r=adwaitaAccentColor(e,this.settings.resolvedDark);this._provider.load_from_string(`:root { --accent-bg-color: ${n}; --accent-color: ${r}; }`)}};function buildSwatch(e,t,n){let r=new h.CheckButton({tooltip_text:t,halign:h.Align.CENTER,valign:h.Align.CENTER,focus_on_click:!1});for(let t of e)r.add_css_class(t);return r.update_property([h.AccessibleProperty.LABEL],[t]),n&&r.set_group(n),r}function buildSwatchCard(e=!1){let t=new w.WrapBox({align:.5,child_spacing:8,line_spacing:8,margin_top:12,margin_bottom:12,margin_start:12,margin_end:12}),n=new w.Bin({child:t,hexpand:!0});return n.add_css_class(`card`),e&&n.add_css_class(`storybook-card-attached`),{card:n,row:t}}function buildAppearanceDialog(e){let t=e.settings,n=new w.PreferencesPage,r=new w.PreferencesGroup({title:`Style`}),{card:i,row:o}=buildSwatchCard(),s=null,c=new Map;for(let e of a){let n=buildSwatch([`storybook-swatch`,`storybook-scheme-swatch`,`storybook-scheme-${e}`],me[e],s);s??=n,n.set_active(t.colorScheme===e),n.connect(`toggled`,()=>{n.get_active()&&(t.colorScheme=e)}),c.set(e,n),o.append(n)}r.add(i),n.add(r);let l=new w.PreferencesGroup({title:`Accent colour`});l.add_css_class(`storybook-attached-group`);let u=new w.SwitchRow({title:`Use a custom accent colour`,subtitle:`Off follows the desktop, which owns the accent`,active:t.accentMode===`custom`});l.add(u);let{card:d,row:f}=buildSwatchCard(!0),p=null,m=new Map;for(let e of se){let n=buildSwatch([`storybook-swatch`],he[e],p);p??=n,n.set_active(t.accent===e);let r=new h.CssProvider;r.load_from_string(`checkbutton { background-color: ${adwaitaAccentBgColor(e)}; }`),n.get_style_context().add_provider(r,h.STYLE_PROVIDER_PRIORITY_APPLICATION),n.connect(`toggled`,()=>{n.get_active()&&(t.accent=e)}),m.set(e,n),f.append(n)}f.set_sensitive(t.accentMode===`custom`),u.connect(`notify::active`,()=>{t.accentMode=u.get_active()?`custom`:`system`}),l.add(d),n.add(l),t.subscribe(e=>{let t=c.get(e.colorScheme);t&&!t.get_active()&&t.set_active(!0);let n=m.get(e.accent);n&&!n.get_active()&&n.set_active(!0);let r=e.accentMode===`custom`;u.get_active()!==r&&u.set_active(r),f.set_sensitive(r)});let g=new w.PreferencesDialog({title:`Appearance`});return g.add(n),g}const ge=e(import.meta.url);let E;function load(){return E===void 0&&(E=ge("@gjsify/node-gi/gi").requireGi(`GObject`,`2.0`)),E}var D=new Proxy(Object.create(null),{get(e,t){return load()[t]},has(e,t){return t in load()}});function adwControlWidgetFactory(){return{text(e,t){let n=new w.EntryRow({title:e});t&&n.set_tooltip_text(t);let r=null;return n.connect(`changed`,()=>r?.(n.get_text())),{node:n,get:()=>n.get_text(),set:e=>n.set_text(e),onChange:e=>{r=e}}},boolean(e,t){let n=new w.SwitchRow({title:e,subtitle:t??``}),r=null;return n.connect(`notify::active`,()=>r?.(n.get_active())),{node:n,get:()=>n.get_active(),set:e=>n.set_active(e),onChange:e=>{r=e}}},number(e){let t=w.SpinRow.new_with_range(e.min??0,e.max??100,e.step??1);t.set_title(e.label||e.name),e.description&&t.set_subtitle(e.description);let n=null;return t.connect(`changed`,()=>n?.(t.get_value())),{node:t,get:()=>t.get_value(),set:e=>t.set_value(e),onChange:e=>{n=e}}},range(e){return buildRangeWidget(e)},select(e){return buildSelectWidget(e)},color(e,t){return buildColorWidget(e,t)}}}function buildRangeWidget(e){let t=e.min??0,n=e.max??100,r=e.step??1,i=typeof e.min==`number`?e.min:0,a=Number.isInteger(r)&&Number.isInteger(i),o=new h.Adjustment({lower:t,upper:n,step_increment:r,value:i});o.step_increment=r;let s=new h.ListBoxRow({selectable:!1,activatable:!1});s.add_css_class(`story-range-row`);let c=new h.Box({orientation:h.Orientation.VERTICAL,spacing:6,margin_top:12,margin_bottom:12,margin_start:12,margin_end:12}),l=new h.Box({orientation:h.Orientation.HORIZONTAL,spacing:12}),u=new h.Label({label:e.label||e.name,halign:h.Align.START,hexpand:!0,ellipsize:3});u.add_css_class(`heading`);let formatValue=e=>a?String(Math.round(e)):e.toFixed(2),d=new h.Label({label:formatValue(i),halign:h.Align.END});if(d.add_css_class(`numeric`),d.add_css_class(`dim-label`),l.append(u),l.append(d),c.append(l),e.description){let t=new h.Label({label:e.description,halign:h.Align.START,xalign:0,wrap:!0,max_width_chars:32});t.add_css_class(`caption`),t.add_css_class(`dim-label`),c.append(t)}let f=new h.Scale({orientation:h.Orientation.HORIZONTAL,adjustment:o,draw_value:!1,hexpand:!0}),p=null,m=!1;return f.connect(`value-changed`,()=>{if(m)return;let e=f.get_value();if(a){let t=Math.round(e);if(t!==e){f.set_value(t);return}e=t}d.set_label(formatValue(e)),p?.(e)}),c.append(f),s.set_child(c),{node:s,get:()=>f.get_value(),set:e=>{m=!0,f.set_value(e),m=!1,d.set_label(formatValue(e))},onChange:e=>{p=e}}}function buildSelectWidget(e){let t=e.options??[],n=h.StringList.new(t.map(e=>e.label)),r=new w.ComboRow({title:e.label||e.name,subtitle:e.description??``,model:n}),i=null;return r.connect(`notify::selected`,()=>i?.(r.get_selected())),{node:r,get:()=>r.get_selected(),set:e=>r.set_selected(e),onChange:e=>{i=e}}}function buildColorWidget(e,t){let n=new w.ActionRow({title:e,subtitle:t??``}),r=new h.ColorDialogButton({dialog:new h.ColorDialog({title:e}),valign:h.Align.CENTER});n.add_suffix(r),n.set_activatable_widget(r);let channel=e=>Math.round(Math.max(0,Math.min(1,e))*255).toString(16).padStart(2,`0`),rgbaToHex=e=>`#${channel(e.red)}${channel(e.green)}${channel(e.blue)}`,i=null,a=!1;return r.connect(`notify::rgba`,()=>{a||i?.(rgbaToHex(r.get_rgba()))}),{node:n,get:()=>rgbaToHex(r.get_rgba()),set:e=>{let t=new f.RGBA;t.parse(e)&&(a=!0,r.set_rgba(t),a=!1)},onChange:e=>{i=e}}}var _e=class StorybookWindow extends w.ApplicationWindow{static{D.registerClass({GTypeName:`StorybookWindow`},StorybookWindow)}constructor(e){super(e),this._appearance=new StorybookAppearance,this._controlRows=[],this._rowByTitle=new Map,this._onSelect=null,this._suppressSelect=!1,this.set_default_size(1200,800),this.set_size_request(360,320),this.set_title(`Storybook`),this._buildUI(),this._controller=new StorybookController(this,e=>this._buildControls(e)),this._sidebar_list.connect(`row-selected`,this._onRowSelected.bind(this)),this._show_controls_button.connect(`toggled`,this._onToggleControls.bind(this)),this._controls_split_view.set_show_sidebar(!0)}_onRowSelected(e,t){if(this._suppressSelect||!t)return;let n=t;n.storyWidget&&this._onSelect?.(n.storyWidget)}get controller(){return this._controller}_buildControls(e){let t=e.meta.controls;if(!Array.isArray(t))return[];let n=adwControlWidgetFactory(),r=[];for(let i of t){if(!i?.name||!i?.type){console.warn(`Invalid control configuration:`,i);continue}let t=bindControl(e,i,n);t&&r.push(t)}return r}_buildUI(){this._sidebar_list=new h.ListBox({selection_mode:h.SelectionMode.SINGLE}),this._sidebar_list.add_css_class(`navigation-sidebar`);let e=new h.ScrolledWindow({hexpand:!0,vexpand:!0,child:this._sidebar_list}),t=new w.HeaderBar({title_widget:new w.WindowTitle({title:`Stories`}),show_end_title_buttons:!1}),n=new w.ToolbarView({content:e,top_bar_style:w.ToolbarStyle.FLAT});n.add_top_bar(t);let r=new w.NavigationPage({title:`Stories`,tag:`stories`,child:n});this._content_area=new w.Bin({hexpand:!0,vexpand:!0});let i=new h.ScrolledWindow({hexpand:!0,vexpand:!0,child:this._content_area});i.add_css_class(`sb-preview-area`),this._control_panel=new w.PreferencesGroup({title:`Controls`});let a=new w.PreferencesPage;a.add(this._control_panel);let o=new h.ScrolledWindow({vexpand:!0,child:a});this._controls_split_view=new w.OverlaySplitView({show_sidebar:!0,sidebar_position:h.PackType.END,min_sidebar_width:280,max_sidebar_width:360,content:i,sidebar:o,css_classes:[`storybook-controls`]}),this._preview_title=new w.WindowTitle({title:`Preview`}),this._show_controls_button=new h.ToggleButton({icon_name:`sidebar-show-right-symbolic`,tooltip_text:`Toggle Controls`,active:!0});let s=new w.HeaderBar({title_widget:this._preview_title});s.pack_end(this._show_controls_button);let c=new h.Button({icon_name:`applications-graphics-symbolic`,tooltip_text:`Appearance`});c.connect(`clicked`,()=>buildAppearanceDialog(this._appearance).present(this)),s.pack_end(c);let l=new w.ToolbarView({content:this._controls_split_view,top_bar_style:w.ToolbarStyle.FLAT});l.add_top_bar(s);let u=new w.NavigationPage({title:`Preview`,tag:`preview`,child:l});this._main_split_view=new w.NavigationSplitView({min_sidebar_width:220,max_sidebar_width:320,sidebar:r,content:u}),this.set_content(this._main_split_view);let d=w.BreakpointCondition.parse(`max-width: 720sp`);if(d){let e=new w.Breakpoint({condition:d});e.connect(`apply`,()=>{this._main_split_view.collapsed=!0,this._controls_split_view.collapsed=!0}),e.connect(`unapply`,()=>{this._main_split_view.collapsed=!1,this._controls_split_view.collapsed=!1}),this.add_breakpoint(e)}}_onToggleControls(e){this._controls_split_view.set_show_sidebar(e.get_active())}populateSidebar(e){this._controller.mount(e,!0)}renderSidebar(e,t){this._onSelect=t,this._suppressSelect=!0,this._clearSidebar(),this._rowByTitle.clear();for(let t of e){this._addCategoryToSidebar(t.category);for(let{instance:e,name:n}of t.stories)this._addStoryToSidebar(e,n)}this._suppressSelect=!1}markSelected(e){let t=this._rowByTitle.get(e);t&&this._sidebar_list.get_selected_row()!==t&&(this._suppressSelect=!0,this._sidebar_list.select_row(t),this._suppressSelect=!1)}setPreviewTitle(e){this._preview_title.set_title(e)}showPreview(e){this._content_area.set_child(e),this._main_split_view.get_collapsed()&&this._main_split_view.set_show_content(!0)}renderControls(e){this._clearControlPanel();for(let t of e){let e=t.view;e instanceof w.PreferencesRow&&e.set_use_markup(!1),this._control_panel.add(e),this._controlRows.push(e)}this._show_controls_button.set_active(!0)}_clearSidebar(){let e=this._sidebar_list.get_first_child();for(;e;){let t=e.get_next_sibling();e.unparent(),e=t}}_addCategoryToSidebar(e){let t=new h.ListBoxRow({selectable:!1}),n=new h.Label({label:e,halign:h.Align.START,margin_top:10,margin_bottom:4,margin_start:12,margin_end:12});n.add_css_class(`heading`),n.add_css_class(`dim-label`),t.set_child(n),this._sidebar_list.append(t)}_addStoryToSidebar(e,t){let n=new h.ListBoxRow,r=new h.Label({label:t||`Unnamed Story`,halign:h.Align.START,margin_start:20,margin_top:6,margin_bottom:6});n.set_child(r),this._sidebar_list.append(n),n.storyWidget=e,this._rowByTitle.set(e.meta.title,n)}_clearControlPanel(){for(let e of this._controlRows)this._control_panel.remove(e);this._controlRows=[]}get activeStory(){return this._controller.activeStory}openStoryByTitle(e){return this._controller.openStoryByTitle(e)}setActiveArg(e,t){return this._controller.setActiveArg(e,t)}};D.type_ensure(_e.$gtype);var ve=class StorybookApplication extends w.Application{static{D.registerClass({GTypeName:`StorybookApplication`},StorybookApplication)}constructor(e){super({application_id:e.applicationId,flags:x.ApplicationFlags.DEFAULT_FLAGS}),this._window=null,this._options=e,this.connect(`startup`,()=>this._initStyles()),this.connect(`activate`,()=>this._onActivate())}_initStyles(){let e=new h.CssProvider;e.load_from_string(`
74
74
  /* Appearance dialog — round swatches with a selection ring, the shape GNOME's own
75
75
  appearance switcher uses. Adapted from Learn6502's theme-mode-selector.css and
76
76
  accent-color-selector.css (JumpLink/easy6502, MIT).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjsify/example-gtk-adwaita-storybook",
3
- "version": "0.46.0",
3
+ "version": "0.48.0",
4
4
  "description": "Interactive component browser for Libadwaita widgets — a native Adwaita storybook built on @gjsify/storybook, debuggable over DBus/MCP via @gjsify/devtools",
5
5
  "type": "module",
6
6
  "main": "dist/gjs.js",
@@ -54,11 +54,11 @@
54
54
  "@girs/glib-2.0": "4.6.0",
55
55
  "@girs/gobject-2.0": "4.6.0",
56
56
  "@girs/gtk-4.0": "4.6.0",
57
- "@gjsify/adwaita-web": "^0.46.0",
58
- "@gjsify/cli": "^0.46.0",
57
+ "@gjsify/adwaita-web": "^0.48.0",
58
+ "@gjsify/cli": "^0.48.0",
59
59
  "@gjsify/node-gi": "file:../../../packages/node-gi/node-gi",
60
- "@gjsify/storybook": "^0.46.0",
61
- "@gjsify/adwaita-storybook": "^0.46.0",
60
+ "@gjsify/storybook": "^0.48.0",
61
+ "@gjsify/adwaita-storybook": "^0.48.0",
62
62
  "@types/node": "^25.9.2",
63
63
  "typescript": "^6.0.3"
64
64
  },
@@ -16,7 +16,7 @@ export class MenuButtonWebStory extends StoryElement {
16
16
 
17
17
  initialize(): void {
18
18
  this._widget = document.createElement('gtk-menu-button');
19
- this._widget.setAttribute('menu', JSON.stringify(MENU_BUTTON_ITEMS.map((label) => ({ label }))));
19
+ this._widget.setAttribute('menu-model', JSON.stringify(MENU_BUTTON_ITEMS.map((label) => ({ label }))));
20
20
  this._apply();
21
21
  this.addContent(this._widget);
22
22
  }
@@ -23,7 +23,7 @@ function iconBaseName(symbolic: string): string {
23
23
  /** Build an <adw-split-button> from the current story args. */
24
24
  function splitButton(args: StoryArgs, opts: { flat?: boolean } = {}): HTMLElement {
25
25
  const el = document.createElement('adw-split-button');
26
- el.setAttribute('menu', MENU);
26
+ el.setAttribute('menu-model', MENU);
27
27
  el.setAttribute('label', args.label as string);
28
28
  const iconName = args.iconName as string;
29
29
  if (iconName) el.setAttribute('icon-name', iconBaseName(iconName));
@@ -16,7 +16,7 @@ export class DropDownWebStory extends StoryElement {
16
16
 
17
17
  initialize(): void {
18
18
  this._dropDown = document.createElement('gtk-drop-down');
19
- this._dropDown.setAttribute('options', JSON.stringify(DROP_DOWN_OPTIONS));
19
+ this._dropDown.setAttribute('model', JSON.stringify(DROP_DOWN_OPTIONS));
20
20
  this._apply();
21
21
  this.addContent(this._dropDown);
22
22
  }
@@ -39,7 +39,7 @@ export class PreferencesDialogWebStory extends StoryElement {
39
39
  // Accent colour — a combo row over the same five options.
40
40
  const accent = document.createElement('adw-combo-row');
41
41
  accent.setAttribute('title', 'Accent colour');
42
- accent.setAttribute('items', JSON.stringify(['Blue', 'Teal', 'Green', 'Orange', 'Purple']));
42
+ accent.setAttribute('model', JSON.stringify(['Blue', 'Teal', 'Green', 'Orange', 'Purple']));
43
43
  accent.setAttribute('selected', '0');
44
44
  group.append(accent);
45
45
 
@@ -58,8 +58,8 @@ export class OverviewWidgetsWebStory extends StoryElement {
58
58
  }),
59
59
  el('adw-combo-row', {
60
60
  title: OVERVIEW_TEXT.accentColor,
61
- // `items` is JSON, not a comma list — the element parses it.
62
- items: JSON.stringify([...OVERVIEW_ACCENT_OPTIONS]),
61
+ // `model` is JSON, not a comma list — the element parses it.
62
+ model: JSON.stringify([...OVERVIEW_ACCENT_OPTIONS]),
63
63
  selected: '0',
64
64
  }),
65
65
  );
@@ -16,7 +16,7 @@ export class ComboRowWebStory extends StoryElement {
16
16
 
17
17
  initialize(): void {
18
18
  this._row = document.createElement('adw-combo-row');
19
- this._row.setAttribute('items', JSON.stringify([...COMBO_ROW_OPTIONS]));
19
+ this._row.setAttribute('model', JSON.stringify([...COMBO_ROW_OPTIONS]));
20
20
  this._syncRow();
21
21
 
22
22
  const group = document.createElement('adw-preferences-group');
@@ -41,7 +41,7 @@ export class PreferencesGroupWebStory extends StoryElement {
41
41
 
42
42
  const regionRow = document.createElement('adw-combo-row');
43
43
  regionRow.setAttribute('title', 'Region');
44
- regionRow.setAttribute('items', JSON.stringify(REGION_OPTIONS));
44
+ regionRow.setAttribute('model', JSON.stringify(REGION_OPTIONS));
45
45
  regionRow.setAttribute('selected', '0');
46
46
  this._group.append(regionRow);
47
47
 
@@ -16,8 +16,6 @@ export class SpinRowWebStory extends StoryElement {
16
16
 
17
17
  initialize(): void {
18
18
  this._row = document.createElement('adw-spin-row');
19
- this._row.setAttribute('min', '0');
20
- this._row.setAttribute('max', '100');
21
19
  this._syncRow();
22
20
 
23
21
  const group = document.createElement('adw-preferences-group');
@@ -37,9 +35,16 @@ export class SpinRowWebStory extends StoryElement {
37
35
  private _syncRow(): void {
38
36
  if (!this._row) return;
39
37
  this._row.setAttribute('title', this.args.title as string);
40
- // Mirror Adw.SpinRow.digits via the step's decimal precision.
38
+ // The WHOLE adjustment every time, so the reflected attribute stays true to the
39
+ // state rather than naming the one field that last moved. It is the same value the
40
+ // GTK story hands `new Gtk.Adjustment` (ADR 0047), written the same way on all
41
+ // three renderers — except `digits`, which this element does not have and mirrors
42
+ // through the step's decimal precision instead.
41
43
  const digits = this.args.digits as number;
42
- this._row.setAttribute('step', String(10 ** -digits));
44
+ this._row.setAttribute(
45
+ 'adjustment',
46
+ JSON.stringify({ lower: 0, upper: 100, pageIncrement: 10, stepIncrement: 10 ** -digits }),
47
+ );
43
48
  this._row.setAttribute('value', String(this.args.value as number));
44
49
  }
45
50
  }