@womp/mcp-ui 0.1.4 → 0.1.5
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/README.md +8 -2
- package/dist/cart/index.html +284 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +22 -4
- package/dist/order/index.html +187 -0
- package/dist/print/index.html +2 -2
- package/package.json +5 -3
- package/src/cart/index.html +210 -0
- package/src/cart/main.ts +157 -0
- package/src/order/index.html +113 -0
- package/src/order/main.ts +110 -0
- package/src/print/index.html +1 -1
- package/src/print/main.ts +30 -19
package/dist/print/index.html
CHANGED
|
@@ -225,7 +225,7 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
225
225
|
- omitted: host decides border`)}),F({method:B(`ui/request-display-mode`),params:F({mode:Uh.describe(`The display mode being requested.`)})}),og=F({mode:Uh.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),sg=L([B(`model`),B(`app`)]).describe(`Tool visibility scope - who can access the tool.`),F({resourceUri:A().optional(),visibility:P(sg).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
226
226
|
- "model": Tool visible to and callable by the agent
|
|
227
227
|
- "app": Tool callable by the app from this server only`),csp:Hl().optional(),permissions:Hl().optional()}),F({mimeTypes:P(A()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),F({method:B(`ui/download-file`),params:F({contents:P(L([kp,Ap])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),F({method:B(`ui/message`),params:F({role:B(`user`).describe(`Message role, currently only "user" is supported.`),content:P(jp).describe(`Message content blocks (text, image, etc.).`)})}),F({method:B(`ui/notifications/sandbox-resource-ready`),params:F({html:A().describe(`HTML content to load into the inner iframe.`),sandbox:A().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:Yh.optional().describe(`CSP configuration from resource metadata.`),permissions:Xh.optional().describe(`Sandbox permissions from resource metadata.`)})}),cg=F({method:B(`ui/notifications/tool-result`),params:Bp.describe(`Standard MCP tool execution result.`)}),lg=F({toolInfo:F({id:rf.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Lp.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:Hh.optional().describe(`Current color theme preference.`),styles:tg.optional().describe(`Style configuration for theming the app.`),displayMode:Uh.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:P(Uh).optional().describe(`Display modes the host supports.`),containerDimensions:L([F({height:j().describe(`Fixed container height in pixels.`)}),F({maxHeight:L([j(),zl()]).optional().describe(`Maximum container height in pixels.`)})]).and(L([F({width:j().describe(`Fixed container width in pixels.`)}),F({maxWidth:L([j(),zl()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
228
|
-
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:A().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:A().optional().describe(`User's timezone in IANA format.`),userAgent:A().optional().describe(`Host application identifier.`),platform:L([B(`web`),B(`desktop`),B(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:F({touch:M().optional().describe(`Whether the device supports touch input.`),hover:M().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:F({top:j().describe(`Top safe area inset in pixels.`),right:j().describe(`Right safe area inset in pixels.`),bottom:j().describe(`Bottom safe area inset in pixels.`),left:j().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),ug=F({method:B(`ui/notifications/host-context-changed`),params:lg.describe(`Partial context update containing only changed fields.`)}),F({method:B(`ui/update-model-context`),params:F({content:P(jp).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:R(A(),N().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),F({method:B(`ui/initialize`),params:F({appInfo:bf.describe(`App identification (name and version).`),appCapabilities:ag.describe(`Features and capabilities this app provides.`),protocolVersion:A().describe(`Protocol version this app supports.`)})}),dg=F({protocolVersion:A().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:bf.describe(`Host application identification and version.`),hostCapabilities:ig.describe(`Features and capabilities provided by the host.`),hostContext:lg.describe(`Rich context about the host environment.`)}).passthrough(),fg={target:`draft-2020-12`},pg=class e extends zh{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Zh,toolinputpartial:Qh,toolresult:cg,toolcancelled:$h,hostcontextchanged:ug};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||o({jitless:!0}),this.setRequestHandler(jf,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=Dh(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Ih(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Ih(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Fh(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Fh(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(ng,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Hp,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Rp,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){if(e===`sampling/createMessage`&&!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Bp,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},dp,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},ap,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?am:im;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},Jh,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},mf,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},Kh,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},qh,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},og,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new Vh(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Bh}},dg,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}}}));function hg(e,t){let n,r=0,i,a=()=>{n!==void 0&&(clearTimeout(n),n=void 0)},o=new pg({name:e,version:`0.0.1`},{}),s=async e=>{let t=await o.request({method:`tools/call`,params:{name:`get_generation`,arguments:{operationId:e}}},Bp);if(!t.isError)return t.structuredContent},c=(e,o)=>{n=window.setTimeout(async()=>{if(Date.now()-r>bg){t.onTimeout?.();return}try{let n=await s(e);if(n?.status===`complete`){a(),i=n,t.onResult(n);return}}catch{}c(e,Math.min(o*1.5,yg))},o)},l=e=>{e&&(a(),i=e,t.onResult(e),e.status===`running`&&e.operationId!==void 0&&(r=Date.now(),c(e.operationId,vg)))};return o.ontoolinput=e=>{t.onInput?.(e?.arguments||{}),t.onResult({status:`running`})},o.ontoolresult=e=>l(e?.structuredContent),o.onhostcontextchanged=e=>{if(e?.theme&&Lh(e.theme),e?.styles?.variables&&Rh(e.styles.variables),e?.displayMode&&(document.documentElement.dataset.displayMode=e.displayMode),e?.safeAreaInsets){let{top:t=0,right:n=0,bottom:r=0,left:i=0}=e.safeAreaInsets;document.body.style.padding=`${t}px ${n}px ${r}px ${i}px`}},o.onteardown=async()=>(a(),{}),o.connect(new Vh(window.parent,window.parent)).catch(()=>{}),{app:o,current:()=>i}}function gg(e,t){return e.openLink({url:t})}async function _g(e,t,n){return e.request({method:`tools/call`,params:{name:t,arguments:n}},Bp)}var $,vg,yg,bg,xg=t((()=>{mg(),Fm(),$=e=>document.getElementById(e),vg=2e3,yg=1e4,bg=36e4}));n((()=>{xg();var e=e=>`$${e.toFixed(2)}`,t=$(`material`),n=$(`longest`),r=$(`quantity`),i=$(`order`),a,o,s=0,c;function l(e,t=!1){let n=$(`status`);n.textContent=e,n.classList.toggle(`error`,t)}function u(t){$(`card`).classList.remove(`quoting`);let n=t.dimensionsCm;n&&($(`size`).textContent=`${n.width.toFixed(1)} x ${n.height.toFixed(1)} x ${n.depth.toFixed(1)} cm`);let r=t.solid;if(!r)return;let a=$(`price`);a.textContent=``;let o=document.createElement(`span`);if(o.className=`amount`,o.textContent=e(r.unitPrice),a.append(o),r.discount>0){let t=document.createElement(`span`);t.className=`was`,t.textContent=e(r.salePrice),a.append(t)}let s=document.createElement(`span`);s.className=`per`,s.textContent=t.quantity&&t.quantity>1?`per unit x ${t.quantity}`:`per unit`,a.append(s);let c=$(`rows`);if(c.textContent=``,t.hollow){let n=document.createElement(`div`);n.textContent=`hollow (Pro): ${e(t.hollow.unitPrice)} per unit${t.callerIsPro?``:` — requires a subscription`}`,c.append(n)}let u=document.createElement(`div`);u.textContent=`~${r.productionDays} production day${r.productionDays===1?``:`s`}`,c.append(u),$(`note`).hidden=!1,i.hidden=!1,i.disabled=!1,l(``)}function d(e){if(e.material){if(![...t.options].some(t=>t.value===e.material)){let n=document.createElement(`option`);n.value=e.material,n.textContent=e.material,t.append(n)}t.value=e.material}typeof e.longestSideCm==`number`&&(n.value=String(Math.round(e.longestSideCm*10)/10)),typeof e.quantity==`number`&&(r.value=String(e.quantity))}function f(e,n){t.textContent=``;for(let n of e){let e=document.createElement(`option`);e.value=n.id,e.textContent=n.id,t.append(e)}n&&(t.value=n)}function p(){return{...a?.generationId?{generationId:a.generationId}:{},...a?.glbUrl?{glbUrl:a.glbUrl}:{},material:t.value,quantity:Math.min(100,Math.max(1,Math.round(Number(r.value)||1))),longestSideCm:Math.min(60,Math.max(2,Number(n.value)||10))}}async function ee(){if(!a||o)return;let e=++s;$(`card`).classList.add(`quoting`),i.disabled=!0,l(`Updating price…`);try{let t=await _g(ne.app,`estimate_print`,p());if(e!==s)return;if(t.isError){let e=t.content?.find(e=>e.type===`text`)?.text||`Could not update the quote.`;$(`card`).classList.remove(`quoting`),i.disabled=!1,l(String(e),!0);return}u(t.structuredContent||{})}catch{if(e!==s)return;$(`card`).classList.remove(`quoting`),i.disabled=!1,l(`Could not update the quote — check the connection and try again.`,!0)}}function te(){c!==void 0&&clearTimeout(c),c=window.setTimeout(()=>void ee(),600)}t.addEventListener(`change`,te),n.addEventListener(`change`,te),r.addEventListener(`change`,te);var ne=hg(`Womp print`,{onTimeout:()=>l(`Still measuring — ask me to check on it.`),onInput:e=>{d({material:typeof e.material==`string`?e.material:void 0,longestSideCm:typeof e.longestSideCm==`number`?e.longestSideCm:void 0,quantity:typeof e.quantity==`number`?e.quantity:void 0})},onResult:e=>{let t=e;if(t.status===`running`){$(`card`).classList.add(`quoting`),l(`Measuring mesh…`);return}t.source&&(a=t.source),t.printUrl?(o=t.printUrl,$(`controls`).hidden=!0,$(`order-label`).textContent=`Complete order on womp.com`):t.materials?.length&&(f(t.materials,t.material),$(`controls`).hidden=!1),d(t),u(t)}});i.addEventListener(`click`,async()=>{if(o){gg(ne.app,o);return}if(a){i.disabled=!0,$(`order-label`).textContent=`Setting up project…`,l(``);try{let e=await _g(ne.app,`prepare_print`,p()),t=e.structuredContent||{};if(e.isError||!t.printUrl){let t=e.content?.find(e=>e.type===`text`)?.text||`Could not set up the print.`;l(String(t),!0);return}o=t.printUrl,$(`controls`).hidden=!0,u(t),$(`order-label`).textContent=`Complete order on womp.com`,gg(ne.app,t.printUrl)}catch{l(`Could not set up the print — try again.`,!0)}finally{i.disabled=!1,o||($(`order-label`).textContent=`Continue on womp.com`)}}})}))();</script>
|
|
228
|
+
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:A().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:A().optional().describe(`User's timezone in IANA format.`),userAgent:A().optional().describe(`Host application identifier.`),platform:L([B(`web`),B(`desktop`),B(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:F({touch:M().optional().describe(`Whether the device supports touch input.`),hover:M().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:F({top:j().describe(`Top safe area inset in pixels.`),right:j().describe(`Right safe area inset in pixels.`),bottom:j().describe(`Bottom safe area inset in pixels.`),left:j().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),ug=F({method:B(`ui/notifications/host-context-changed`),params:lg.describe(`Partial context update containing only changed fields.`)}),F({method:B(`ui/update-model-context`),params:F({content:P(jp).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:R(A(),N().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),F({method:B(`ui/initialize`),params:F({appInfo:bf.describe(`App identification (name and version).`),appCapabilities:ag.describe(`Features and capabilities this app provides.`),protocolVersion:A().describe(`Protocol version this app supports.`)})}),dg=F({protocolVersion:A().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:bf.describe(`Host application identification and version.`),hostCapabilities:ig.describe(`Features and capabilities provided by the host.`),hostContext:lg.describe(`Rich context about the host environment.`)}).passthrough(),fg={target:`draft-2020-12`},pg=class e extends zh{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Zh,toolinputpartial:Qh,toolresult:cg,toolcancelled:$h,hostcontextchanged:ug};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||o({jitless:!0}),this.setRequestHandler(jf,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=Dh(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Ih(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Ih(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Fh(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Fh(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(ng,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Hp,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Rp,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){if(e===`sampling/createMessage`&&!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Bp,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},dp,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},ap,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?am:im;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},Jh,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},mf,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},Kh,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},qh,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},og,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new Vh(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Bh}},dg,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}}}));function hg(e,t){let n,r=0,i,a=()=>{n!==void 0&&(clearTimeout(n),n=void 0)},o=new pg({name:e,version:`0.0.1`},{}),s=async e=>{let t=await o.request({method:`tools/call`,params:{name:`get_generation`,arguments:{operationId:e}}},Bp);if(!t.isError)return t.structuredContent},c=(e,o)=>{n=window.setTimeout(async()=>{if(Date.now()-r>bg){t.onTimeout?.();return}try{let n=await s(e);if(n?.status===`complete`){a(),i=n,t.onResult(n);return}}catch{}c(e,Math.min(o*1.5,yg))},o)},l=e=>{e&&(a(),i=e,t.onResult(e),e.status===`running`&&e.operationId!==void 0&&(r=Date.now(),c(e.operationId,vg)))};return o.ontoolinput=e=>{t.onInput?.(e?.arguments||{}),t.onResult({status:`running`})},o.ontoolresult=e=>l(e?.structuredContent),o.onhostcontextchanged=e=>{if(e?.theme&&Lh(e.theme),e?.styles?.variables&&Rh(e.styles.variables),e?.displayMode&&(document.documentElement.dataset.displayMode=e.displayMode),e?.safeAreaInsets){let{top:t=0,right:n=0,bottom:r=0,left:i=0}=e.safeAreaInsets;document.body.style.padding=`${t}px ${n}px ${r}px ${i}px`}},o.onteardown=async()=>(a(),{}),o.connect(new Vh(window.parent,window.parent)).catch(()=>{}),{app:o,current:()=>i}}function gg(e,t){return e.openLink({url:t})}async function _g(e,t,n){return e.request({method:`tools/call`,params:{name:t,arguments:n}},Bp)}var $,vg,yg,bg,xg=t((()=>{mg(),Fm(),$=e=>document.getElementById(e),vg=2e3,yg=1e4,bg=36e4}));n((()=>{xg();var e=e=>`$${e.toFixed(2)}`,t=$(`material`),n=$(`longest`),r=$(`quantity`),i=$(`order`),a,o,s=``,c=0,l;function u(e,t=!1){let n=$(`status`);n.textContent=e,n.classList.toggle(`error`,t)}function d(t){$(`card`).classList.remove(`quoting`);let n=t.dimensionsCm;n&&($(`size`).textContent=`${n.width.toFixed(1)} x ${n.height.toFixed(1)} x ${n.depth.toFixed(1)} cm`);let r=t.solid;if(!r)return;let a=$(`price`);a.textContent=``;let o=document.createElement(`span`);if(o.className=`amount`,o.textContent=e(r.unitPrice),a.append(o),r.discount>0){let t=document.createElement(`span`);t.className=`was`,t.textContent=e(r.salePrice),a.append(t)}let s=document.createElement(`span`);s.className=`per`,s.textContent=t.quantity&&t.quantity>1?`per unit x ${t.quantity}`:`per unit`,a.append(s);let c=$(`rows`);if(c.textContent=``,t.hollow){let n=document.createElement(`div`);n.textContent=`hollow (Pro): ${e(t.hollow.unitPrice)} per unit${t.callerIsPro?``:` — requires a subscription`}`,c.append(n)}let l=document.createElement(`div`);l.textContent=`~${r.productionDays} production day${r.productionDays===1?``:`s`}`,c.append(l),$(`note`).hidden=!1,i.hidden=!1,i.disabled=!1,u(``)}function f(e){if(e.material){if(![...t.options].some(t=>t.value===e.material)){let n=document.createElement(`option`);n.value=e.material,n.textContent=e.material,t.append(n)}t.value=e.material}typeof e.longestSideCm==`number`&&(n.value=String(Math.round(e.longestSideCm*10)/10)),typeof e.quantity==`number`&&(r.value=String(e.quantity))}function p(e,n){t.textContent=``;for(let n of e){let e=document.createElement(`option`);e.value=n.id,e.textContent=n.id,t.append(e)}n&&(t.value=n)}function ee(){return{...a?.generationId?{generationId:a.generationId}:{},...a?.glbUrl?{glbUrl:a.glbUrl}:{},material:t.value,quantity:Math.min(100,Math.max(1,Math.round(Number(r.value)||1))),longestSideCm:Math.min(60,Math.max(2,Number(n.value)||10))}}async function te(){if(!a||o)return;let e=++c;$(`card`).classList.add(`quoting`),i.disabled=!0,u(`Updating price…`);try{let t=await _g(re.app,`estimate_print`,ee());if(e!==c)return;if(t.isError){let e=t.content?.find(e=>e.type===`text`)?.text||`Could not update the quote.`;$(`card`).classList.remove(`quoting`),i.disabled=!1,u(String(e),!0);return}d(t.structuredContent||{})}catch{if(e!==c)return;$(`card`).classList.remove(`quoting`),i.disabled=!1,u(`Could not update the quote — check the connection and try again.`,!0)}}function ne(){l!==void 0&&clearTimeout(l),s=``,$(`order-label`).textContent=`Add to cart`,l=window.setTimeout(()=>void te(),600)}t.addEventListener(`change`,ne),n.addEventListener(`change`,ne),r.addEventListener(`change`,ne);var re=hg(`Womp print`,{onTimeout:()=>u(`Still measuring — ask me to check on it.`),onInput:e=>{f({material:typeof e.material==`string`?e.material:void 0,longestSideCm:typeof e.longestSideCm==`number`?e.longestSideCm:void 0,quantity:typeof e.quantity==`number`?e.quantity:void 0})},onResult:e=>{let t=e;if(t.status===`running`){$(`card`).classList.add(`quoting`),u(`Measuring mesh…`);return}t.source&&(a=t.source),t.printUrl?(o=t.printUrl,$(`controls`).hidden=!0,$(`order-label`).textContent=`Complete order on womp.com`):t.materials?.length&&(p(t.materials,t.material),$(`controls`).hidden=!1),f(t),d(t)}});i.addEventListener(`click`,async()=>{if(o){gg(re.app,o);return}if(s){gg(re.app,s);return}if(a){i.disabled=!0,$(`order-label`).textContent=`Adding to cart…`,u(``);try{let e=await _g(re.app,`add_to_cart`,ee()),t=e.structuredContent||{};if(e.isError||!t.payUrl){let t=e.content?.find(e=>e.type===`text`)?.text||`Could not add to the cart.`;u(String(t),!0),$(`order-label`).textContent=`Add to cart`;return}s=t.payUrl,$(`order-label`).textContent=`Checkout on womp.com`,u(`Added — cart has ${t.items?.length??1} item(s), subtotal $${(t.subtotal??0).toFixed(2)}. Shipping and promo codes apply at checkout.`)}catch{u(`Could not add to the cart — try again.`,!0),$(`order-label`).textContent=`Add to cart`}finally{i.disabled=!1}}})}))();</script>
|
|
229
229
|
</head>
|
|
230
230
|
<body>
|
|
231
231
|
<div class="card" id="card">
|
|
@@ -256,7 +256,7 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
256
256
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
257
257
|
<path d="M7 17 17 7M9 7h8v8" />
|
|
258
258
|
</svg>
|
|
259
|
-
<span id="order-label">
|
|
259
|
+
<span id="order-label">Add to cart</span>
|
|
260
260
|
</button>
|
|
261
261
|
<div class="note" id="note" hidden>
|
|
262
262
|
Shipping is added at checkout; the final price is confirmed before printing.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@womp/mcp-ui",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "MCP Apps widgets for Womp's MCP server — interactive cards rendered inline in Claude and other MCP hosts.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "commonjs",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
},
|
|
16
16
|
"scripts": {
|
|
17
17
|
"build": "yarn build:ui && yarn build:bake",
|
|
18
|
-
"build:ui": "yarn build:ui:image && yarn build:ui:mesh && yarn build:ui:print",
|
|
18
|
+
"build:ui": "yarn build:ui:image && yarn build:ui:mesh && yarn build:ui:print && yarn build:ui:cart && yarn build:ui:order",
|
|
19
19
|
"build:bake": "node scripts/bake-html.mjs",
|
|
20
20
|
"dev": "vite",
|
|
21
21
|
"dev:host": "vite",
|
|
@@ -25,7 +25,9 @@
|
|
|
25
25
|
"prepublishOnly": "yarn clean && yarn build",
|
|
26
26
|
"build:ui:image": "CARD=image vite build",
|
|
27
27
|
"build:ui:mesh": "CARD=mesh vite build",
|
|
28
|
-
"build:ui:print": "CARD=print vite build"
|
|
28
|
+
"build:ui:print": "CARD=print vite build",
|
|
29
|
+
"build:ui:cart": "CARD=cart vite build",
|
|
30
|
+
"build:ui:order": "CARD=order vite build"
|
|
29
31
|
},
|
|
30
32
|
"devDependencies": {
|
|
31
33
|
"@modelcontextprotocol/ext-apps": "^1.7.5",
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<title>Womp cart</title>
|
|
6
|
+
<style>
|
|
7
|
+
/* Same var()-with-fallback discipline as every card: host style
|
|
8
|
+
variables arrive over the bridge after the handshake. The row layout
|
|
9
|
+
mirrors swan-frontend's CartPanel item rows (thumbnail · title +
|
|
10
|
+
material/size/qty · line total) as closely as a card can. */
|
|
11
|
+
:root {
|
|
12
|
+
color-scheme: light dark;
|
|
13
|
+
}
|
|
14
|
+
body {
|
|
15
|
+
margin: 0;
|
|
16
|
+
font-family: var(--font-sans, system-ui, -apple-system, "Segoe UI", sans-serif);
|
|
17
|
+
color: var(--color-text-primary, #e8e8e8);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
.card {
|
|
21
|
+
max-width: 400px;
|
|
22
|
+
border-radius: var(--border-radius-lg, 14px);
|
|
23
|
+
overflow: hidden;
|
|
24
|
+
background: var(--color-background-secondary, #1b1b1d);
|
|
25
|
+
border: 1px solid var(--color-border-primary, rgba(255, 255, 255, 0.08));
|
|
26
|
+
padding: 14px;
|
|
27
|
+
box-sizing: border-box;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
.head {
|
|
31
|
+
display: flex;
|
|
32
|
+
align-items: baseline;
|
|
33
|
+
justify-content: space-between;
|
|
34
|
+
gap: 8px;
|
|
35
|
+
margin-bottom: 10px;
|
|
36
|
+
}
|
|
37
|
+
.title {
|
|
38
|
+
font-size: var(--font-text-sm-size, 13px);
|
|
39
|
+
font-weight: 600;
|
|
40
|
+
}
|
|
41
|
+
.count {
|
|
42
|
+
font-size: var(--font-text-xs-size, 11px);
|
|
43
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.6));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
.items {
|
|
47
|
+
display: grid;
|
|
48
|
+
gap: 10px;
|
|
49
|
+
}
|
|
50
|
+
.item {
|
|
51
|
+
display: grid;
|
|
52
|
+
grid-template-columns: 56px 1fr auto;
|
|
53
|
+
gap: 10px;
|
|
54
|
+
align-items: center;
|
|
55
|
+
}
|
|
56
|
+
.thumb {
|
|
57
|
+
width: 56px;
|
|
58
|
+
height: 56px;
|
|
59
|
+
border-radius: var(--border-radius-md, 10px);
|
|
60
|
+
background: var(--color-background-tertiary, #2a2a2e);
|
|
61
|
+
object-fit: cover;
|
|
62
|
+
display: block;
|
|
63
|
+
}
|
|
64
|
+
.thumb.pulsing {
|
|
65
|
+
background: linear-gradient(90deg, #2a2a2e, #37373d, #2a2a2e);
|
|
66
|
+
background-size: 200% 100%;
|
|
67
|
+
animation: sweep 1.4s ease-in-out infinite;
|
|
68
|
+
}
|
|
69
|
+
@keyframes sweep {
|
|
70
|
+
0% { background-position: 200% 0; }
|
|
71
|
+
100% { background-position: -200% 0; }
|
|
72
|
+
}
|
|
73
|
+
@media (prefers-reduced-motion: reduce) {
|
|
74
|
+
.thumb.pulsing { animation: none; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
.item-main {
|
|
78
|
+
min-width: 0;
|
|
79
|
+
display: grid;
|
|
80
|
+
gap: 2px;
|
|
81
|
+
}
|
|
82
|
+
.item-title {
|
|
83
|
+
font-size: var(--font-text-sm-size, 13px);
|
|
84
|
+
font-weight: 500;
|
|
85
|
+
white-space: nowrap;
|
|
86
|
+
overflow: hidden;
|
|
87
|
+
text-overflow: ellipsis;
|
|
88
|
+
}
|
|
89
|
+
.item-sub {
|
|
90
|
+
font-size: var(--font-text-xs-size, 11px);
|
|
91
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.6));
|
|
92
|
+
white-space: nowrap;
|
|
93
|
+
overflow: hidden;
|
|
94
|
+
text-overflow: ellipsis;
|
|
95
|
+
}
|
|
96
|
+
.badge {
|
|
97
|
+
display: inline-block;
|
|
98
|
+
font-size: 10px;
|
|
99
|
+
padding: 1px 6px;
|
|
100
|
+
border-radius: var(--border-radius-full, 999px);
|
|
101
|
+
background: var(--color-background-tertiary, #2a2a2e);
|
|
102
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.7));
|
|
103
|
+
vertical-align: 1px;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
.item-price {
|
|
107
|
+
text-align: right;
|
|
108
|
+
display: grid;
|
|
109
|
+
gap: 2px;
|
|
110
|
+
}
|
|
111
|
+
.line-total {
|
|
112
|
+
font-size: var(--font-text-sm-size, 13px);
|
|
113
|
+
font-weight: 600;
|
|
114
|
+
font-variant-numeric: tabular-nums;
|
|
115
|
+
}
|
|
116
|
+
.per-unit {
|
|
117
|
+
font-size: 10px;
|
|
118
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.55));
|
|
119
|
+
font-variant-numeric: tabular-nums;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
.empty {
|
|
123
|
+
padding: 18px 0;
|
|
124
|
+
font-size: var(--font-text-sm-size, 13px);
|
|
125
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.6));
|
|
126
|
+
text-align: center;
|
|
127
|
+
}
|
|
128
|
+
.empty[hidden] { display: none; }
|
|
129
|
+
|
|
130
|
+
.divider {
|
|
131
|
+
height: 1px;
|
|
132
|
+
background: var(--color-border-primary, rgba(255, 255, 255, 0.08));
|
|
133
|
+
margin: 12px 0 10px;
|
|
134
|
+
}
|
|
135
|
+
.divider[hidden] { display: none; }
|
|
136
|
+
|
|
137
|
+
.totals {
|
|
138
|
+
display: flex;
|
|
139
|
+
justify-content: space-between;
|
|
140
|
+
align-items: baseline;
|
|
141
|
+
font-size: var(--font-text-sm-size, 13px);
|
|
142
|
+
}
|
|
143
|
+
.totals[hidden] { display: none; }
|
|
144
|
+
.subtotal {
|
|
145
|
+
font-weight: 700;
|
|
146
|
+
font-variant-numeric: tabular-nums;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
.cta {
|
|
150
|
+
margin-top: 12px;
|
|
151
|
+
display: flex;
|
|
152
|
+
width: 100%;
|
|
153
|
+
align-items: center;
|
|
154
|
+
justify-content: center;
|
|
155
|
+
gap: 6px;
|
|
156
|
+
border: 0;
|
|
157
|
+
cursor: pointer;
|
|
158
|
+
font: inherit;
|
|
159
|
+
font-size: var(--font-text-sm-size, 13px);
|
|
160
|
+
font-weight: 600;
|
|
161
|
+
padding: 9px 12px;
|
|
162
|
+
border-radius: var(--border-radius-full, 999px);
|
|
163
|
+
color: #fff;
|
|
164
|
+
background: var(--color-background-accent, #5867dd);
|
|
165
|
+
}
|
|
166
|
+
.cta:hover { filter: brightness(1.1); }
|
|
167
|
+
.cta:focus-visible { outline: 2px solid var(--color-ring-primary, #7aa2ff); outline-offset: 1px; }
|
|
168
|
+
.cta[hidden] { display: none; }
|
|
169
|
+
.cta svg { width: 14px; height: 14px; display: block; }
|
|
170
|
+
|
|
171
|
+
.note {
|
|
172
|
+
margin-top: 8px;
|
|
173
|
+
font-size: 10px;
|
|
174
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.5));
|
|
175
|
+
}
|
|
176
|
+
.note[hidden] { display: none; }
|
|
177
|
+
|
|
178
|
+
.status {
|
|
179
|
+
margin-top: 8px;
|
|
180
|
+
font-size: var(--font-text-xs-size, 11px);
|
|
181
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.6));
|
|
182
|
+
}
|
|
183
|
+
.status:empty { display: none; }
|
|
184
|
+
</style>
|
|
185
|
+
</head>
|
|
186
|
+
<body>
|
|
187
|
+
<div class="card" id="card">
|
|
188
|
+
<div class="head">
|
|
189
|
+
<div class="title">Cart</div>
|
|
190
|
+
<div class="count" id="count"></div>
|
|
191
|
+
</div>
|
|
192
|
+
<div class="items" id="items"></div>
|
|
193
|
+
<div class="empty" id="empty" hidden>The cart is empty.</div>
|
|
194
|
+
<div class="divider" id="divider" hidden></div>
|
|
195
|
+
<div class="totals" id="totals" hidden>
|
|
196
|
+
<span>Subtotal</span>
|
|
197
|
+
<span class="subtotal" id="subtotal"></span>
|
|
198
|
+
</div>
|
|
199
|
+
<button class="cta" id="checkout" hidden>
|
|
200
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
201
|
+
<path d="M7 17 17 7M9 7h8v8" />
|
|
202
|
+
</svg>
|
|
203
|
+
Checkout on womp.com
|
|
204
|
+
</button>
|
|
205
|
+
<div class="note" id="note" hidden>Shipping and promo codes are applied at checkout.</div>
|
|
206
|
+
<div class="status" id="status">Connecting…</div>
|
|
207
|
+
</div>
|
|
208
|
+
<script type="module" src="./main.ts"></script>
|
|
209
|
+
</body>
|
|
210
|
+
</html>
|
package/src/cart/main.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { $, callTool, createCard, openLink, type GenerationResult } from "../shared/bridge";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The cart card — renders add_to_cart / view_cart / remove_from_cart results
|
|
5
|
+
* as swan-frontend-style cart rows (thumbnail · title + material/size/qty ·
|
|
6
|
+
* line total) with the checkout link out to the real cart UI.
|
|
7
|
+
*
|
|
8
|
+
* Thumbnails lag item creation by a few seconds (the preview render is a GPU
|
|
9
|
+
* job kicked off at cart-add), so rows start as skeletons and the card polls
|
|
10
|
+
* the app-callable `view_cart` until every thumbnail exists — the same
|
|
11
|
+
* self-filling trick as the mesh card, bounded so a dead render can't poll
|
|
12
|
+
* forever. Like every card, it never touches money: checkout is a
|
|
13
|
+
* `ui/open-link` to `/pay/<ids>`.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
interface CartItem {
|
|
17
|
+
orderItemId: number;
|
|
18
|
+
title: string;
|
|
19
|
+
material: string;
|
|
20
|
+
quantity: number;
|
|
21
|
+
unitPrice: number;
|
|
22
|
+
dimensionsCm?: { width: number; height: number; depth: number };
|
|
23
|
+
thumbnailUrl?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface CartPayload {
|
|
27
|
+
items?: CartItem[];
|
|
28
|
+
subtotal?: number;
|
|
29
|
+
payUrl?: string;
|
|
30
|
+
removed?: number[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const usd = (n: number) => `$${n.toFixed(2)}`;
|
|
34
|
+
|
|
35
|
+
let payUrl = "";
|
|
36
|
+
let pollTimer: number | undefined;
|
|
37
|
+
let pollUntil = 0;
|
|
38
|
+
/** Bound the thumbnail-refresh polling: renders usually land well inside this. */
|
|
39
|
+
const THUMB_POLL_MS = 4_000;
|
|
40
|
+
const THUMB_POLL_CEILING_MS = 90_000;
|
|
41
|
+
|
|
42
|
+
const setStatus = (text: string) => {
|
|
43
|
+
$("status").textContent = text;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
function itemRow(item: CartItem): HTMLElement {
|
|
47
|
+
const row = document.createElement("div");
|
|
48
|
+
row.className = "item";
|
|
49
|
+
|
|
50
|
+
if (item.thumbnailUrl) {
|
|
51
|
+
const img = document.createElement("img");
|
|
52
|
+
img.className = "thumb";
|
|
53
|
+
img.alt = item.title;
|
|
54
|
+
img.src = item.thumbnailUrl;
|
|
55
|
+
row.append(img);
|
|
56
|
+
} else {
|
|
57
|
+
const skeleton = document.createElement("div");
|
|
58
|
+
skeleton.className = "thumb pulsing";
|
|
59
|
+
row.append(skeleton);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const main = document.createElement("div");
|
|
63
|
+
main.className = "item-main";
|
|
64
|
+
const title = document.createElement("div");
|
|
65
|
+
title.className = "item-title";
|
|
66
|
+
title.textContent = item.title;
|
|
67
|
+
const sub = document.createElement("div");
|
|
68
|
+
sub.className = "item-sub";
|
|
69
|
+
const badge = document.createElement("span");
|
|
70
|
+
badge.className = "badge";
|
|
71
|
+
badge.textContent = item.material;
|
|
72
|
+
sub.append(badge);
|
|
73
|
+
const bits: string[] = [];
|
|
74
|
+
if (item.dimensionsCm) {
|
|
75
|
+
const d = item.dimensionsCm;
|
|
76
|
+
bits.push(`${d.width.toFixed(1)} x ${d.height.toFixed(1)} x ${d.depth.toFixed(1)} cm`);
|
|
77
|
+
}
|
|
78
|
+
bits.push(`qty ${item.quantity}`);
|
|
79
|
+
sub.append(` ${bits.join(" · ")}`);
|
|
80
|
+
main.append(title, sub);
|
|
81
|
+
row.append(main);
|
|
82
|
+
|
|
83
|
+
const price = document.createElement("div");
|
|
84
|
+
price.className = "item-price";
|
|
85
|
+
const line = document.createElement("div");
|
|
86
|
+
line.className = "line-total";
|
|
87
|
+
line.textContent = usd(item.unitPrice * item.quantity);
|
|
88
|
+
price.append(line);
|
|
89
|
+
if (item.quantity > 1) {
|
|
90
|
+
const per = document.createElement("div");
|
|
91
|
+
per.className = "per-unit";
|
|
92
|
+
per.textContent = `${usd(item.unitPrice)} each`;
|
|
93
|
+
price.append(per);
|
|
94
|
+
}
|
|
95
|
+
row.append(price);
|
|
96
|
+
return row;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function render(data: CartPayload) {
|
|
100
|
+
const items = data.items || [];
|
|
101
|
+
if (data.payUrl) payUrl = data.payUrl;
|
|
102
|
+
|
|
103
|
+
$("count").textContent = items.length ? `${items.length} item${items.length === 1 ? "" : "s"}` : "";
|
|
104
|
+
const list = $("items");
|
|
105
|
+
list.textContent = "";
|
|
106
|
+
items.forEach((item) => list.append(itemRow(item)));
|
|
107
|
+
|
|
108
|
+
$("empty").hidden = items.length > 0;
|
|
109
|
+
$("divider").hidden = !items.length;
|
|
110
|
+
$("totals").hidden = !items.length;
|
|
111
|
+
$("checkout").hidden = !items.length || !payUrl;
|
|
112
|
+
$("note").hidden = !items.length;
|
|
113
|
+
if (typeof data.subtotal === "number") $("subtotal").textContent = usd(data.subtotal);
|
|
114
|
+
setStatus("");
|
|
115
|
+
|
|
116
|
+
scheduleThumbnailRefresh(items);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Poll view_cart until every row has its render, bounded. */
|
|
120
|
+
function scheduleThumbnailRefresh(items: CartItem[]) {
|
|
121
|
+
if (pollTimer !== undefined) {
|
|
122
|
+
clearTimeout(pollTimer);
|
|
123
|
+
pollTimer = undefined;
|
|
124
|
+
}
|
|
125
|
+
if (!items.length || items.every((i) => i.thumbnailUrl)) return;
|
|
126
|
+
if (!pollUntil) pollUntil = Date.now() + THUMB_POLL_CEILING_MS;
|
|
127
|
+
if (Date.now() > pollUntil) return;
|
|
128
|
+
|
|
129
|
+
pollTimer = window.setTimeout(async () => {
|
|
130
|
+
try {
|
|
131
|
+
const res = await callTool(card.app, "view_cart", {});
|
|
132
|
+
if (!res.isError && res.structuredContent) {
|
|
133
|
+
render(res.structuredContent as CartPayload);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
} catch {
|
|
137
|
+
// A failed refresh only delays thumbnails; the ceiling stops it.
|
|
138
|
+
}
|
|
139
|
+
scheduleThumbnailRefresh(items);
|
|
140
|
+
}, THUMB_POLL_MS);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const card = createCard("Womp cart", {
|
|
144
|
+
onResult: (raw: GenerationResult) => {
|
|
145
|
+
const data = raw as CartPayload & GenerationResult;
|
|
146
|
+
if (data.status === "running") {
|
|
147
|
+
setStatus("Updating cart…");
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
pollUntil = 0;
|
|
151
|
+
render(data);
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
$("checkout").addEventListener("click", () => {
|
|
156
|
+
if (payUrl) void openLink(card.app, payUrl);
|
|
157
|
+
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<title>Womp orders</title>
|
|
6
|
+
<style>
|
|
7
|
+
:root {
|
|
8
|
+
color-scheme: light dark;
|
|
9
|
+
}
|
|
10
|
+
body {
|
|
11
|
+
margin: 0;
|
|
12
|
+
font-family: var(--font-sans, system-ui, -apple-system, "Segoe UI", sans-serif);
|
|
13
|
+
color: var(--color-text-primary, #e8e8e8);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
.card {
|
|
17
|
+
max-width: 400px;
|
|
18
|
+
border-radius: var(--border-radius-lg, 14px);
|
|
19
|
+
overflow: hidden;
|
|
20
|
+
background: var(--color-background-secondary, #1b1b1d);
|
|
21
|
+
border: 1px solid var(--color-border-primary, rgba(255, 255, 255, 0.08));
|
|
22
|
+
padding: 14px;
|
|
23
|
+
box-sizing: border-box;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
.orders { display: grid; gap: 12px; }
|
|
27
|
+
|
|
28
|
+
.order { display: grid; gap: 6px; }
|
|
29
|
+
.order + .order {
|
|
30
|
+
border-top: 1px solid var(--color-border-primary, rgba(255, 255, 255, 0.08));
|
|
31
|
+
padding-top: 12px;
|
|
32
|
+
}
|
|
33
|
+
.order-head {
|
|
34
|
+
display: flex;
|
|
35
|
+
align-items: center;
|
|
36
|
+
justify-content: space-between;
|
|
37
|
+
gap: 8px;
|
|
38
|
+
}
|
|
39
|
+
.order-id {
|
|
40
|
+
font-size: var(--font-text-sm-size, 13px);
|
|
41
|
+
font-weight: 600;
|
|
42
|
+
}
|
|
43
|
+
/* Status chips mirror the orders page's wording; color encodes the band:
|
|
44
|
+
waiting (amber), moving (blue), done (green), stopped (red/gray). */
|
|
45
|
+
.chip {
|
|
46
|
+
font-size: 10px;
|
|
47
|
+
font-weight: 600;
|
|
48
|
+
letter-spacing: 0.04em;
|
|
49
|
+
padding: 2px 8px;
|
|
50
|
+
border-radius: var(--border-radius-full, 999px);
|
|
51
|
+
background: var(--color-background-tertiary, #2a2a2e);
|
|
52
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.7));
|
|
53
|
+
white-space: nowrap;
|
|
54
|
+
}
|
|
55
|
+
.chip.wait { background: rgba(217, 174, 85, 0.16); color: #d9ae55; }
|
|
56
|
+
.chip.move { background: rgba(122, 162, 255, 0.16); color: #7aa2ff; }
|
|
57
|
+
.chip.done { background: rgba(127, 199, 150, 0.16); color: #7fc796; }
|
|
58
|
+
.chip.stop { background: rgba(224, 141, 141, 0.16); color: #e08d8d; }
|
|
59
|
+
|
|
60
|
+
.lines {
|
|
61
|
+
font-size: var(--font-text-xs-size, 11px);
|
|
62
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.6));
|
|
63
|
+
display: grid;
|
|
64
|
+
gap: 2px;
|
|
65
|
+
}
|
|
66
|
+
.total-row {
|
|
67
|
+
display: flex;
|
|
68
|
+
justify-content: space-between;
|
|
69
|
+
font-size: var(--font-text-xs-size, 12px);
|
|
70
|
+
}
|
|
71
|
+
.total-row b { font-variant-numeric: tabular-nums; }
|
|
72
|
+
|
|
73
|
+
.action {
|
|
74
|
+
margin-top: 4px;
|
|
75
|
+
border-left: 3px solid #d9ae55;
|
|
76
|
+
background: rgba(217, 174, 85, 0.1);
|
|
77
|
+
border-radius: 6px;
|
|
78
|
+
padding: 8px 10px;
|
|
79
|
+
font-size: var(--font-text-xs-size, 11px);
|
|
80
|
+
color: var(--color-text-primary, #e8e8e8);
|
|
81
|
+
}
|
|
82
|
+
.action[hidden] { display: none; }
|
|
83
|
+
|
|
84
|
+
.tracking {
|
|
85
|
+
font-size: var(--font-text-xs-size, 11px);
|
|
86
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.7));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
.empty {
|
|
90
|
+
padding: 14px 0;
|
|
91
|
+
font-size: var(--font-text-sm-size, 13px);
|
|
92
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.6));
|
|
93
|
+
text-align: center;
|
|
94
|
+
}
|
|
95
|
+
.empty[hidden] { display: none; }
|
|
96
|
+
|
|
97
|
+
.status {
|
|
98
|
+
margin-top: 8px;
|
|
99
|
+
font-size: var(--font-text-xs-size, 11px);
|
|
100
|
+
color: var(--color-text-secondary, rgba(232, 232, 232, 0.6));
|
|
101
|
+
}
|
|
102
|
+
.status:empty { display: none; }
|
|
103
|
+
</style>
|
|
104
|
+
</head>
|
|
105
|
+
<body>
|
|
106
|
+
<div class="card" id="card">
|
|
107
|
+
<div class="orders" id="orders"></div>
|
|
108
|
+
<div class="empty" id="empty" hidden>No print orders yet.</div>
|
|
109
|
+
<div class="status" id="status">Connecting…</div>
|
|
110
|
+
</div>
|
|
111
|
+
<script type="module" src="./main.ts"></script>
|
|
112
|
+
</body>
|
|
113
|
+
</html>
|