@gramlot/gramlot 0.3.36 → 0.3.37

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.
Files changed (106) hide show
  1. package/dist/components/charts/__init__.py +1 -1
  2. package/dist/components/charts/assets/collection.js +9 -9
  3. package/dist/components/charts/assets/index.js +1 -1
  4. package/dist/components/charts/grammar.json +0 -30
  5. package/dist/components/drawing/__init__.py +1 -1
  6. package/dist/components/drawing/assets/collection.js +3 -3
  7. package/dist/components/drawing/assets/index.js +1 -1
  8. package/dist/components/grid/__init__.py +1 -1
  9. package/dist/components/grid/assets/collection.js +6 -6
  10. package/dist/components/grid/assets/index.js +1 -1
  11. package/dist/components/grid/grammar.json +0 -2
  12. package/dist/components/inputs/__init__.py +1 -1
  13. package/dist/components/inputs/assets/collection.js +8 -8
  14. package/dist/components/inputs/assets/index.js +1 -1
  15. package/dist/components/inputs/grammar.json +2 -1
  16. package/dist/components/layout/__init__.py +1 -1
  17. package/dist/components/layout/assets/collection.js +9 -9
  18. package/dist/components/layout/assets/index.js +1 -1
  19. package/dist/components/layout/grammar.json +2 -2
  20. package/dist/components/selection_trial/__init__.py +1 -1
  21. package/dist/components/selection_trial/assets/collection.js +3 -3
  22. package/dist/components/selection_trial/assets/index.js +1 -1
  23. package/dist/components/tree/__init__.py +1 -1
  24. package/dist/components/tree/assets/collection.js +6 -6
  25. package/dist/components/tree/assets/index.js +1 -1
  26. package/dist/components/tree/grammar.json +0 -1
  27. package/dist/components/uploads/__init__.py +1 -1
  28. package/dist/components/uploads/assets/collection.js +3 -3
  29. package/dist/components/uploads/assets/index.js +1 -1
  30. package/dist/components/uploads/grammar.json +0 -3
  31. package/dist/gramlot.js +1205 -627
  32. package/dist/gramlot.min.js +45 -45
  33. package/dist/standard-collections.js +1 -1
  34. package/package.json +2 -3
  35. package/src/binding/data-binder.js +11 -3
  36. package/src/binding/grid-struct.js +7 -4
  37. package/src/binding/runtime.js +203 -46
  38. package/src/builder/binding.json +23 -1
  39. package/src/builder/gramlot-builder.d.ts +1 -4
  40. package/src/builder/source.js +185 -29
  41. package/src/chat.js +26 -20
  42. package/src/components/attachment-manager.js +38 -34
  43. package/src/components/chart-data-view.js +4 -7
  44. package/src/components/chart-fields.js +18 -6
  45. package/src/components/chart-renderer.js +10 -3
  46. package/src/components/chart-timeline.js +7 -5
  47. package/src/components/charts.js +74 -67
  48. package/src/components/check-box-text-editor.js +3 -3
  49. package/src/components/check-box-text.js +7 -22
  50. package/src/components/check-box-tree.js +20 -16
  51. package/src/components/choice-editor.js +1 -1
  52. package/src/components/drawing.js +47 -34
  53. package/src/components/grid-cell-editor.js +72 -29
  54. package/src/components/grid-column-filters.js +47 -40
  55. package/src/components/grid-formulas.js +22 -17
  56. package/src/components/grid-header-interaction.js +9 -11
  57. package/src/components/grid-row-interaction.js +25 -24
  58. package/src/components/grid-row-layout.js +28 -29
  59. package/src/components/grid-search-box.js +3 -3
  60. package/src/components/grid-search.js +3 -8
  61. package/src/components/grid-selection.js +33 -29
  62. package/src/components/grid-structure.js +48 -10
  63. package/src/components/grid-tools.js +14 -14
  64. package/src/components/grid.js +83 -79
  65. package/src/components/image-crop-dialog.js +2 -2
  66. package/src/components/image-crop.js +16 -9
  67. package/src/components/image-uploader.js +21 -28
  68. package/src/components/inputs.js +19 -1
  69. package/src/components/registry.js +3 -5
  70. package/src/components/tray-pane.js +85 -61
  71. package/src/components/tree.js +332 -239
  72. package/src/components/upload-engine.js +10 -2
  73. package/src/components/uploader.js +31 -27
  74. package/src/editing-session.d.ts +4 -1
  75. package/src/editing-session.js +120 -83
  76. package/src/experiments/window-selection.js +4 -6
  77. package/src/filesystem.js +2 -2
  78. package/src/gramlot.js +1 -0
  79. package/src/handlers/device-handler.js +219 -213
  80. package/src/handlers/rpc-handler.d.ts +17 -0
  81. package/src/handlers/rpc-handler.js +22 -0
  82. package/src/ide-documents.js +29 -11
  83. package/src/ide-runtime.js +33 -31
  84. package/src/index-page-runtime.d.ts +2 -2
  85. package/src/index-page-runtime.js +67 -48
  86. package/src/message-port-connection.js +100 -0
  87. package/src/message-port-store.js +158 -0
  88. package/src/page-store-connection.js +6 -1
  89. package/src/renderer/gramlot-renderer.js +21 -2
  90. package/src/source-picker.d.ts +2 -2
  91. package/src/source-picker.js +15 -6
  92. package/src/stores/bag-collection-store.js +25 -7
  93. package/src/stores/bag-collection-view.js +23 -22
  94. package/src/view/controls.js +1 -1
  95. package/src/view/html.js +40 -20
  96. package/src/visual-editor-canvas.js +1 -1
  97. package/src/visual-editor.js +18 -19
  98. package/tools/gramlot-tools-inspector.js +400 -374
  99. package/tools/inspector-agent.js +223 -49
  100. package/dist/components/vizabi/__init__.py +0 -13
  101. package/dist/components/vizabi/assets/collection.js +0 -4
  102. package/dist/components/vizabi/assets/index.js +0 -3
  103. package/dist/components/vizabi/commands.json +0 -7
  104. package/dist/components/vizabi/grammar.json +0 -128
  105. package/src/components/vizabi-session.js +0 -66
  106. package/src/components/vizabi.js +0 -66
@@ -1,6 +1,6 @@
1
- var ie=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var le=Object.prototype.hasOwnProperty;var ce=(w,e)=>{for(var r in e)ie(w,r,{get:e[r],enumerable:!0})},re=(w,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ne(e))!le.call(w,s)&&s!==r&&ie(w,s,{get:()=>e[s],enumerable:!(t=oe(e,s))||t.enumerable});return w},G=(w,e,r)=>(re(w,e,"default"),r&&re(r,e,"default"));import{Bag as E,createDOMPurify as me}from"@gramlot/gramlot";var M={};ce(M,{defineCollection:()=>Q});G(M,Ae);import*as Ae from"@gramlot/gramlot/components";import{defineCollection as he}from"@gramlot/gramlot/components";function Q(w){if(w.name!=="tree")throw new Error("Unexpected bundled collection");let e=[],r={};w.css?.forEach((t,s)=>{t.href=e[s].href});for(let[t,s]of Object.entries(w.assets??{}))s.href=r[t].href;return he({...w,css:e,assets:r})}import{sharedModules as de}from"@gramlot/gramlot";var ue=w=>de["./components/parameters.js"][w];var ae=ue("projectParameters");function X(w){return class extends w{constructor(){super();let e=this.attachShadow({mode:"open"}),r=this.ownerDocument.createElement("style");r.textContent=`:host{box-sizing:border-box;display:block;min-width:0;font:inherit;color:var(--gramlot-ink,CanvasText)}
1
+ var rt=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var ot=Object.prototype.hasOwnProperty;var lt=(A,t)=>{for(var s in t)rt(A,s,{get:t[s],enumerable:!0})},st=(A,t,s,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of it(t))!ot.call(A,r)&&r!==s&&rt(A,r,{get:()=>t[r],enumerable:!(e=at(t,r))||e.enumerable});return A},G=(A,t,s)=>(st(A,t,"default"),s&&st(s,t,"default"));import{Bag as j,createDOMPurify as ft}from"@gramlot/gramlot";var O={};lt(O,{defineCollection:()=>K});G(O,kt);import*as kt from"@gramlot/gramlot/components";import{defineCollection as ct}from"@gramlot/gramlot/components";function K(A){if(A.name!=="tree")throw new Error("Unexpected bundled collection");let t=[],s={};A.css?.forEach((e,r)=>{e.href=t[r].href});for(let[e,r]of Object.entries(A.assets??{}))r.href=s[e].href;return ct({...A,css:t,assets:s})}import{sharedModules as ht}from"@gramlot/gramlot";var dt=A=>ht["./components/parameters.js"][A];var nt=dt("projectParameters");function H(A){return class extends A{constructor(){super();let t=this.attachShadow({mode:"open"}),s=this.ownerDocument.createElement("style");s.textContent=`:host{box-sizing:border-box;display:block;min-width:0;font:inherit;color:var(--gramlot-ink,CanvasText)}
2
2
  *,*::before,*::after{box-sizing:border-box}.control-box{min-width:0}slot{display:contents}
3
- ::slotted(*){min-width:0;max-width:100%}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",this.control=this.controlBox,this.control.id="control",this.control.append(this.ownerDocument.createElement("slot")),e.append(r,this.controlBox)}projectAttributes(e){return ae(this,e)}}}X.parameters={};import{sharedModules as pe}from"@gramlot/gramlot";var fe=w=>pe["./renderer/attributes.js"][w],q=fe("SVG_NS");var ge=(0,M.defineComponent)({name:"rowActions",tag:"gramlot-row-actions",base:X,subTags:"button,dropDownButton",sourceContext:!0,parameters:{position:{dtype:"T",default:"end"},actionState:{dtype:"T",nullable:!0,default:null},state:{dtype:"X",nullable:!0,default:null,binding:"read"}},implementation:w=>class extends w{#e=null;#g;connectedCallback(){this.slot="row-actions",this.hidden=!0}setSourceContext(e){this.#g=e}setRowContext(e,r){this.#e={item:e,path:r},this.#a()}getRowContext(){return this.#e}clearRowContext(){this.#e=null,this.hidden=!0}projectAttributes(e,r){let t=super.projectAttributes(e,r);if(!["start","end"].includes(this.parameters.position))throw new TypeError("rowActions position must be start or end");return this.#a(),t}#a(){if(!(!this.#e||!this.parameters.actionState))for(let e of this.children){let r=e.getAttribute("rowAction");if(r===null)continue;let t=this.#g.callLogic(this.parameters.actionState,{...this.#e,action:r,state:this.parameters.state});if(!t||typeof t.hidden!="boolean"||typeof t.icon!="string"||typeof t.title!="string")throw new TypeError("rowActions actionState must return hidden, icon and title");e.setActionPresentation(t)}}}}),be=(0,M.defineComponent)({name:"tree",tag:"gramlot-tree",base:X,subTags:"rowActions[:1]",sourceContext:!0,bagStore:!0,dragSource:!0,parameters:{storepath:{dtype:"T"},draggable:{dtype:"B",default:!1,binding:"read"},labelAttribute:{dtype:"T",nullable:!0,default:null,binding:"read"},internalNames:{dtype:"B",default:!1,binding:"read"},hideValues:{dtype:"B",default:!1,binding:"read"},excludeRoot:{dtype:"T",nullable:!0,default:null,binding:"read"},labelCb:{dtype:"T",nullable:!0,default:null},getLabel:{dtype:"T",nullable:!0,default:null},labelState:{dtype:"X",nullable:!0,default:null,binding:"read"},getLabelClass:{dtype:"T",nullable:!0,default:null},getIconClass:{dtype:"T",nullable:!0,default:null},selectedLabelClass:{dtype:"T",default:"",binding:"read"},searchText:{dtype:"T",default:"",binding:"read"},searchEager:{dtype:"B",default:!0,binding:"read"},searchAttributes:{dtype:"T",default:"",binding:"read"},favorites:{dtype:"X",nullable:!0,default:null,binding:"read"},favoritesLabel:{dtype:"T",default:"Favorites",binding:"read"},autoCollapse:{dtype:"B",default:!1,binding:"read"},resolveLazy:{dtype:"B",default:!0,binding:"read"},selectedPath:{dtype:"T",nullable:!0,default:null,binding:"twoWay"},onChecked:{dtype:["B","T"],nullable:!0,default:null},checkedPaths:{dtype:"T",nullable:!0,default:null,binding:"twoWay"},checkedPaths_joiner:{dtype:"T",default:","},checkChildren:{dtype:"B",default:!0,binding:"read"}},implementation:w=>class extends w{#e;#g;#a;#i=new Set;#c=new Map;#j=new Map;#l=!1;#A=new WeakMap;#M=new Map;#C;#$=0;#b=null;#O=!1;#o;#z=!1;#d=!1;#w=new WeakMap;#x=new WeakSet;#u=new Set;#s=new Map;#p="";#G=null;#t="";#f=null;#I=0;#h=new Set;#E=new WeakSet;#N=new WeakSet;#m=!1;#n=new Map;constructor(){super(),this.#g=me(this.ownerDocument.defaultView),this.control.replaceChildren(),this.control.setAttribute("role","tree"),this.control.setAttribute("aria-label","Tree"),this.control.classList.add("tree"),this.control.setAttribute("part","tree");let e=this.ownerDocument.createElement("style");e.textContent=`
3
+ ::slotted(*){min-width:0;max-width:100%}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",this.control=this.controlBox,this.control.id="control",this.control.append(this.ownerDocument.createElement("slot")),t.append(s,this.controlBox)}projectAttributes(t){return nt(this,t)}}}H.parameters={};import{sharedModules as ut}from"@gramlot/gramlot";var pt=A=>ut["./renderer/attributes.js"][A],F=pt("SVG_NS");var bt=(0,O.defineComponent)({name:"rowActions",tag:"gramlot-row-actions",base:H,subTags:"button,dropDownButton",sourceContext:!0,parameters:{position:{dtype:"T",default:"end"},actionState:{dtype:"T",nullable:!0,default:null},state:{dtype:"X",nullable:!0,default:null,binding:"read"}},implementation:A=>class extends A{#i=null;#t;connectedCallback(){this.slot="row-actions",this.hidden=!0}setSourceContext(t){this.#t=t}setRowContext(t,s){this.#i={path:t,read:s},this.#s()}getRowContext(){if(!this.#i)return null;let{path:t,read:s}=this.#i,e=s();return e?{item:e,path:t}:null}clearRowContext(){this.#i=null,this.hidden=!0}projectAttributes(t,s){let e=super.projectAttributes(t,s);if(!["start","end"].includes(this.parameters.position))throw new TypeError("rowActions position must be start or end");return this.#s(),e}#s(){let t=this.getRowContext();if(!(!t||!this.parameters.actionState))for(let s of this.children){let e=s.getAttribute("rowAction");if(e===null)continue;let r=this.#t.callLogic(this.parameters.actionState,{...t,action:e,state:this.#t.getStaticData(this.#t.attrDatapath("state"))});if(!r||typeof r.hidden!="boolean"||typeof r.icon!="string"||typeof r.title!="string")throw new TypeError("rowActions actionState must return hidden, icon and title");s.setActionPresentation(r)}}}}),mt=(0,O.defineComponent)({name:"tree",tag:"gramlot-tree",base:H,subTags:"rowActions[:1]",sourceContext:!0,dragSource:!0,parameters:{storepath:{dtype:"T"},draggable:{dtype:"B",default:!1,binding:"read"},labelAttribute:{dtype:"T",nullable:!0,default:null,binding:"read"},internalNames:{dtype:"B",default:!1,binding:"read"},hideValues:{dtype:"B",default:!1,binding:"read"},excludeRoot:{dtype:"T",nullable:!0,default:null,binding:"read"},labelCb:{dtype:"T",nullable:!0,default:null},getLabel:{dtype:"T",nullable:!0,default:null},labelState:{dtype:"X",nullable:!0,default:null,binding:"read"},getLabelClass:{dtype:"T",nullable:!0,default:null},getIconClass:{dtype:"T",nullable:!0,default:null},selectedLabelClass:{dtype:"T",default:"",binding:"read"},searchText:{dtype:"T",default:"",binding:"read"},searchEager:{dtype:"B",default:!0,binding:"read"},searchAttributes:{dtype:"T",default:"",binding:"read"},favorites:{dtype:"X",nullable:!0,default:null,binding:"read"},favoritesLabel:{dtype:"T",default:"Favorites",binding:"read"},autoCollapse:{dtype:"B",default:!1,binding:"read"},resolveLazy:{dtype:"B",default:!0,binding:"read"},selectedPath:{dtype:"T",nullable:!0,default:null,binding:"twoWay"},onChecked:{dtype:["B","T"],nullable:!0,default:null},checkedPaths:{dtype:"T",nullable:!0,default:null,binding:"twoWay"},checkedPaths_joiner:{dtype:"T",default:","},checkChildren:{dtype:"B",default:!0,binding:"read"}},implementation:A=>class extends A{#i;#t;#s=new Set;#o=new Map;#B=new Map;#a=!1;#w=new WeakMap;#P=new Map;#R;#q=0;#u=null;#j=!1;#$=!1;#x=!1;#p=new Map;#f=null;#W=null;#F=null;#c=new Set;#n=new Map;#b="";#G=null;#e="";#h=null;#M=0;#l=new Set;#y=new Set;#v=new Set;#d=!1;#k=new Map;constructor(){super(),this.#i=ft(this.ownerDocument.defaultView),this.control.replaceChildren(),this.control.setAttribute("role","tree"),this.control.setAttribute("aria-label","Tree"),this.control.classList.add("tree"),this.control.setAttribute("part","tree");let t=this.ownerDocument.createElement("style");t.textContent=`
4
4
  :host{position:relative}
5
5
  .control-box{overflow:auto;padding:4px;min-height:32px}
6
6
  ul{list-style:none;margin:0;padding:0} ul ul{padding-inline-start:20px}
@@ -22,10 +22,10 @@ var ie=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var ne=Objec
22
22
  background:var(--gramlot-tree-badge-background,#e7eaf0);color:var(--gramlot-tree-badge-color,#394452)}
23
23
  .badge[data-colored]{color:var(--gramlot-tree-colored-badge-color,white)}
24
24
  .icon{width:16px;height:16px;flex:none;background:currentColor;opacity:.7;mask:center/contain no-repeat;
25
- mask-image:url("data:image/svg+xml,%3Csvg xmlns='${q}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M5 3h9l5 5v13H5zM14 3v6h5M8 13h8M8 17h8'/%3E%3C/svg%3E")}
26
- .branch-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${q}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 7V4h7l3 3h8v13H3z'/%3E%3C/svg%3E")}
27
- .opened-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${q}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 19V4h7l3 3h8v3M3 20l3-9h16l-3 9z'/%3E%3C/svg%3E")}
25
+ mask-image:url("data:image/svg+xml,%3Csvg xmlns='${F}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M5 3h9l5 5v13H5zM14 3v6h5M8 13h8M8 17h8'/%3E%3C/svg%3E")}
26
+ .branch-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${F}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 7V4h7l3 3h8v13H3z'/%3E%3C/svg%3E")}
27
+ .opened-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${F}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 19V4h7l3 3h8v3M3 20l3-9h16l-3 9z'/%3E%3C/svg%3E")}
28
28
  .loading>.row{opacity:.65}.error>.row .caption{text-decoration:underline dotted}
29
29
  mark{background:#ffe493;color:#302300;font-weight:600;border-radius:2px;padding:0 1px}
30
30
  .search-status{padding:4px;color:var(--gramlot-text-secondary,#555);font-size:.9em}
31
- [hidden]{display:none}`,this.shadowRoot.append(e);let r=this.ownerDocument.createElement("slot");r.name="row-actions",this.shadowRoot.append(r),this.addEventListener("pointerleave",()=>{let t=this.#T();t&&!t.contains(this.ownerDocument.activeElement)&&t.clearRowContext()})}setSourceContext(e){this.#a=e}get storeBag(){return this.#e}getDragContext(e){for(let r of e.composedPath()){let t=this.#A.get(r);if(!t)continue;let{item:s,path:i,caption:o}=t,d=r.getBoundingClientRect(),l=d.height?(e.clientY-d.top)/d.height:.5,y=l<.25?"before":l>.75?"after":"inside";return{element:r,item:s,path:i,placement:y,dragValues:{"text/plain":o.textContent,nodeattr:{...s.getAttr()},treenode:{fullpath:s.fullpath,relpath:i}}}}return null}setStoreBag(e){if(!(e instanceof E))throw new TypeError("tree storepath must resolve to a Bag");e!==this.#e&&(this.#e=e,this.#y(),this.#t=this.#p.toLowerCase(),this.#i.clear(),this.#s.clear(),this.#C=void 0,this.#$++,this.#o=void 0,this.#w=new WeakMap,this.#x=new WeakSet),this.#r()}projectAttributes(e,r){this.#d=Object.hasOwn(e,"checkedPaths"),this.#z=this.#d||!!e.onChecked;let t=this.parameters?.searchEager,s=this.parameters?.resolveLazy,i=super.projectAttributes(e,r);(t!==this.parameters.searchEager||s!==this.parameters.resolveLazy)&&(this.#y(),this.#t=this.#p.toLowerCase()),this.#G!==this.parameters.excludeRoot&&(this.#G=this.parameters.excludeRoot,this.#y(),this.#t=this.#p.toLowerCase());let o=this.parameters.searchText.trim();return o!==this.#p&&(this.#y(),this.#p=o,o?this.#f=setTimeout(()=>{this.#f=null,this.#t=o.toLowerCase(),this.#r()},200):this.#t=""),this.#r(),i}connectedCallback(){this.#f===null&&(this.#t=this.#p.toLowerCase()),this.#r()}disconnectedCallback(){this.#y()}#y(){clearTimeout(this.#f),this.#f=null,this.#I++,this.#m=!1,this.#N=new WeakSet,this.#h.clear(),this.#E=new WeakSet}#S(e){return this.#t?this.#h.has(e):this.#i.has(e)}async#X(){let e=this.#I,r=this.#e,t=()=>this.isConnected&&e===this.#I&&r===this.#e&&this.parameters.searchEager&&this.parameters.resolveLazy;this.#m=!0;let s=async(i,o=new Set)=>{if(!t())return;if(o.has(i))throw new TypeError("tree requires an acyclic Bag store");let d=new Set(o).add(i);for(let l of i.getNodes())if(!(i===this.#e&&l.label===this.parameters.excludeRoot)){if(!t())return;if(l.attr.loop!==!0&&!(l.resolver!==null&&!this.parameters.resolveLazy)){if(l.resolver!==null&&l.resolver.expired&&!this.#N.has(l)&&(this.#N.add(l),await this.#F(l,!0)),!t())return;l.staticValue instanceof E&&await s(l.staticValue,d)}}};try{await s(r)}finally{t()&&(this.#m=!1,this.#r())}}#Y(e){let r=this.ownerDocument.createTreeWalker(e,4),t=[];for(;r.nextNode();)t.push(r.currentNode);for(let s of t){let i=s.textContent,o=i.toLowerCase(),d=this.ownerDocument.createDocumentFragment(),l=0,y=o.indexOf(this.#t);if(!(y<0)){for(;y>=0;){d.append(i.slice(l,y));let T=this.ownerDocument.createElement("mark");T.textContent=i.slice(y,y+this.#t.length),d.append(T),l=y+this.#t.length,y=o.indexOf(this.#t,l)}d.append(i.slice(l)),s.replaceWith(d)}}}retrySelection(){this.#C=void 0,this.#r()}#r(){this.#O||(this.#O=!0,queueMicrotask(()=>{this.#O=!1,this.isConnected&&this.#e&&this.#J()}))}#J(){let e=this.shadowRoot.activeElement?.closest("[role=treeitem]")?.dataset.path,r=this.shadowRoot.activeElement?.dataset.favoritePath,t=this.shadowRoot.activeElement?.dataset.favoritesGroup==="true",s=[],i=!1;this.#z&&this.parameters.checkChildren&&!(this.#d&&this.parameters.checkedPaths!==this.#o)&&(i=this.#H(this.#e,new Set,s));let o=new Map,d=new Set,l=(c,b,g)=>{if(d.has(c))throw new TypeError("tree requires an acyclic Bag store");d.add(c);for(let u of c.getNodes()){if(c===this.#e&&u.label===this.parameters.excludeRoot)continue;let a=b?`${b}.${u.label}`:u.label,p=u.resolver!==null&&!this.parameters.resolveLazy?null:u.staticValue;o.set(a,{node:u,ancestors:g,children:p instanceof E?p:null}),p instanceof E&&l(p,a,[...g,u])}d.delete(c)};l(this.#e,"",[]),this.parameters.searchEager&&this.parameters.resolveLazy&&this.#t&&this.#f===null&&!this.#m&&[...o.values()].some(({node:c})=>c.attr.loop!==!0&&c.resolver!==null&&c.resolver.expired&&!this.#N.has(c))&&this.#X();let y=this.#T(),T=y?y.getRowContext():null;if(T&&((T.item.getAttr("favoriteEntry")===!0?this.parameters.favorites instanceof E&&this.parameters.favorites.getNodes().includes(T.item):o.get(T.path)?.node===T.item)||y.clearRowContext()),this.#d&&this.parameters.checkedPaths!==this.#o){let c=this.#o===void 0;this.#o=this.parameters.checkedPaths;for(let{node:b}of o.values())b.attr.checked==="disabled:on"||b.attr.checked==="disabled:off"||(!c||this.#o!==null)&&b.setAttr({checked:!1});for(let b of(this.#o||"").split(this.parameters.checkedPaths_joiner).filter(Boolean)){let g=o.get(b);g&&this.#_(g.node,!0,!1)}}else if(this.#d&&s.length){let c=(this.parameters.checkedPaths||"").split(this.parameters.checkedPaths_joiner).filter(Boolean);for(let b of c){let g=o.get(b);if(!g||g.node.attr.checked===!0||g.node.attr.checked==="disabled:on"||g.node.attr.checked==="disabled:off")continue;let u=g.node.parentBag;for(;u&&!s.includes(u);)u=u.parentNode?.parentBag;u&&this.#_(g.node,!0,!1)}(i||c.length)&&this.#W(!0)}else i&&this.#W(!0);let z=new Set([...o.values()].map(c=>c.node));for(let c of this.#i)z.has(c)||this.#i.delete(c);for(let c of this.#s.keys())z.has(c)||this.#s.delete(c);let f=this.parameters.selectedPath,N=null;if(f!==this.#C){this.#C=f,this.#b=f;let c=++this.#$,b=o.get(f)?.ancestors??[];f&&!o.has(f)&&(N={requested:f,version:c,store:this.#e});for(let g=0;g<b.length;g++){let u=b[g];this.#i.has(u)||this.#q(u)}}let k=this.#b;this.#c.clear(),this.#j.clear(),this.#A=new WeakMap,this.#M.clear();let L=new Map,F=(c,b,g)=>{let u=this.ownerDocument.createElement("ul");u.className="group",u.setAttribute("part","group"),u.setAttribute("role","group");for(let a of c.getNodes()){if(c===this.#e&&a.label===this.parameters.excludeRoot)continue;let p=b?`${b}.${a.label}`:a.label,{children:B}=o.get(p),U=B===null&&!this.parameters.hideValues&&(a.resolver===null||!a.resolver.expired),x=B!==null?B.length>0:U||a.resolver!==null&&this.parameters.resolveLazy&&a.attr.child_count!==0,h=this.ownerDocument.createElement("li");h.className=`node ${x?"branch":"leaf"}`,h.setAttribute("part",`node ${x?"branch":"leaf"}`),h.classList.toggle("loading",this.#u.has(a)),h.classList.toggle("error",this.#s.has(a)),h.setAttribute("aria-busy",String(this.#u.has(a))),h.setAttribute("role","treeitem"),h.setAttribute("aria-selected",String(k===p)),h.classList.toggle("selected",k===p),h.dataset.path=p,h.tabIndex=-1;let C=this.ownerDocument.createElement("div");C.className="row",C.addEventListener("pointerenter",()=>this.#P(C,a,p)),h.addEventListener("focus",()=>this.#P(C,a,p)),C.draggable=this.parameters.draggable,C.setAttribute("part",`row ${x?"branch-row":"leaf-row"}${k===p?" selected-row":""}`),this.#s.has(a)&&(C.title=String(this.#s.get(a)));let P=this.ownerDocument.createElement(x?"button":"span");if(P.setAttribute("part",x?"expander":"spacer"),x){P.className="expander",P.type="button",P.tabIndex=-1;let n=this.ownerDocument.createElementNS(q,"svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let m=this.ownerDocument.createElementNS(q,"path");m.setAttribute("d","m9 5 7 7-7 7"),m.setAttribute("fill","none"),m.setAttribute("stroke","currentColor"),m.setAttribute("stroke-width","1.8"),m.setAttribute("stroke-linecap","round"),m.setAttribute("stroke-linejoin","round"),n.append(m),P.append(n),P.addEventListener("click",S=>{S.stopPropagation(),h.focus(),J()})}else P.className="spacer";let R=this.ownerDocument.createElement("span");R.className="caption";let _=this.ownerDocument.createElement("span");_.className="badge",_.setAttribute("part","badge"),this.#A.set(C,{item:a,path:p,caption:R}),R.setAttribute("part","caption");let $=this.ownerDocument.createElement("span");$.className=`icon ${x?"branch-icon":"leaf-icon"}`,$.setAttribute("aria-hidden","true"),$.setAttribute("part",`icon ${x?"branch-icon":"leaf-icon"}`);let A;this.#z&&(A=this.ownerDocument.createElement("input"),A.type="checkbox",A.className="checkbox",A.setAttribute("part","checkbox"),A.tabIndex=-1,A.addEventListener("click",n=>{if(n.stopPropagation(),typeof this.parameters.onChecked=="string"){let m=this.#a.callLogic(this.parameters.onChecked,{item:a,path:p});if(m instanceof Promise)throw new TypeError("tree onChecked must be synchronous");if(m===!1){this.#r();return}}this.#_(a,A.checked,!0)})),C.append(P,A||$,_,R),h.append(C);let O=x?B?F(B,p,h):this.ownerDocument.createElement("ul"):null;if(O&&(O.className="group",O.setAttribute("role","group"),O.setAttribute("part","group")),O&&h.append(O),U){let n=this.ownerDocument.createElement("li");n.className="value-node",n.setAttribute("part","value-node"),n.setAttribute("role","treeitem"),n.setAttribute("aria-selected","false"),n.tabIndex=-1,n.dataset.path=p,n.dataset.valueRow="true";let m=this.ownerDocument.createElement("div");m.className="row value-row",m.setAttribute("part","row value-row");let S=this.ownerDocument.createElement("span");S.className="spacer";let v=this.ownerDocument.createElement("span");v.className="value",v.setAttribute("part","value"),v.textContent=String(a.staticValue),m.append(S,v),n.append(m),O.append(n),m.addEventListener("click",()=>this.#V(p)),n.addEventListener("keydown",D=>{let V=this.#k(),H=V.indexOf(n),j;if(D.key==="ArrowUp")j=V[H-1];else if(D.key==="ArrowDown")j=V[H+1];else if(D.key==="Home")j=V[0];else if(D.key==="End")j=V.at(-1);else if(D.key==="ArrowLeft")j=h;else if(D.key==="Enter"||D.key===" ")this.#V(p);else return;D.preventDefault(),D.stopPropagation(),j&&(this.#v(j),j.focus())})}let Y=()=>{let n=this.#S(a),m=this.#b===p,S=a.attr.badge;if(S!=null&&typeof S!="string"&&typeof S!="number")throw new TypeError("tree badge must be text or a number");let v=a.attr.badge_color;if(v!=null&&typeof v!="string")throw new TypeError("tree badge_color must be text");_.textContent=S==null?"":String(S),_.hidden=S==null||S==="",_.style.backgroundColor=v??"",_.toggleAttribute("data-colored",v!=null&&v!=="");let D={item:a,path:p,opened:n,selected:m,state:this.parameters.labelState},V=this.parameters.labelAttribute,H=this.parameters.internalNames&&a.getAttr("fieldpath")?a.label:this.parameters.getLabel!==null?this.#R("getLabel",D):V!==null?Object.hasOwn(a.attr,V)?a.attr[V]:a.label:this.parameters.labelCb!==null?this.#R("labelCb",D):a.label;this.#ee(R,H,!(this.parameters.internalNames&&a.getAttr("fieldpath"))&&(this.parameters.getLabel!==null||V===null&&this.parameters.labelCb!==null)),this.#t&&this.#Y(R);let j=this.parameters.getLabelClass!==null?this.#R("getLabelClass",D):a.attr[n?"labelClassOpened":"labelClassClosed"]||a.attr.labelClass||"",ee=[...this.#D(j),...m?this.#D(this.parameters.selectedLabelClass):[]];R.className=["caption",...ee].join(" "),R.setAttribute("part",["caption",...ee].join(" "));let te=this.#D(a.attr.node_class??"");h.className=["node",x?"branch":"leaf",...te,...m?["selected"]:[],...x?[n?"opened":"closed"]:[],...this.#u.has(a)?["loading"]:[],...this.#s.has(a)?["error"]:[]].join(" "),h.setAttribute("part",["node",x?"branch":"leaf",...te].join(" "));let se=!A&&this.parameters.getIconClass!==null,K=se?this.#D(this.#R("getIconClass",D)):[x?"branch-icon":"leaf-icon",...x?[n?"opened-icon":"closed-icon"]:[]];if($.className=["icon",...K].join(" "),$.setAttribute("part",["icon",...K].join(" ")),$.hidden=se&&K.length===0,A){let W=a.attr.checked;A.checked=W===!0||W==="disabled:on",A.indeterminate=W===-1,h.setAttribute("aria-checked",W===-1?"mixed":String(A.checked)),A.disabled=W==="disabled:on"||W==="disabled:off",A.setAttribute("aria-label",R.textContent)}x&&P.setAttribute("aria-label",`${n?"Collapse":"Expand"} ${R.textContent}`)};this.#M.set(p,Y);let Z=()=>{let n=this.#S(a);h.setAttribute("aria-expanded",String(n)),h.classList.toggle("opened",n),h.classList.toggle("closed",!n),$.classList.toggle("opened-icon",n),$.setAttribute("part",`icon branch-icon ${n?"opened-icon":"closed-icon"}`),O.hidden=!n,Y()},J=()=>{let n=this.#t?this.#h:this.#i;n.has(a)?(n.delete(a),this.#t&&this.#E.add(a)):(this.#t?(this.#E.delete(a),this.#h.add(a)):this.#q(a),a.resolver!==null&&this.#F(a));for(let m of L.values())m();this.#v(p)};x?(L.set(a,Z),Z()):Y(),C.addEventListener("click",()=>this.#V(p)),h.addEventListener("keydown",n=>{if(n.target!==h)return;let m=this.#k(),S=m.indexOf(h),v;if(n.key==="ArrowDown")v=m[S+1];else if(n.key==="ArrowUp")v=m[S-1];else if(n.key==="Home")v=m[0];else if(n.key==="End")v=m.at(-1);else if(n.key==="ArrowRight"&&x)this.#S(a)?v=O.firstElementChild:J();else if(n.key==="ArrowLeft")x&&this.#S(a)?J():v=g;else if(n.key===" "&&A)A.click();else if(n.key==="Enter"||n.key===" ")this.#V(p);else return;n.preventDefault(),n.stopPropagation(),v&&(this.#v(v),v.focus())}),this.#c.set(p,h),u.append(h)}return u},I=F(this.#e,"",null);if(this.parameters.favorites!==null){if(!(this.parameters.favorites instanceof E))throw new TypeError("tree favorites must be a Bag");this.parameters.favorites.length&&I.prepend(this.#K(this.parameters.favorites,k))}if(this.control.replaceChildren(I),this.control.setAttribute("aria-busy",String(this.#m)),this.#t){let c=new Set,b=[];this.#h.clear();for(let[u,a]of this.#c){let p=a.firstElementChild.querySelector(".caption"),B=o.get(u);if(B.ancestors.some(h=>h.attr.loop===!0))continue;let U=this.parameters.searchAttributes.split(",").map(h=>h.trim()).filter(Boolean).flatMap(h=>{let C=B.node.getAttr(h);return Array.isArray(C)?C.filter(P=>typeof P=="string"):typeof C=="string"?[C]:[]}),x=[p.textContent,...U].some(h=>h.toLowerCase().includes(this.#t));if(x&&b.push(p),x||this.#s.has(B.node)||this.#u.has(B.node)){c.add(B.node);for(let h of B.ancestors)c.add(h),this.#E.has(h)||this.#h.add(h)}}for(let[u,a]of this.#c)a.hidden=!c.has(o.get(u).node);for(let u of L.values())u();let g=this.ownerDocument.createElement("div");g.className="search-status",g.setAttribute("role","status"),g.textContent=this.#m?"Searching\u2026":this.#s.size?"Some branches could not be searched. Expand them to retry.":b.length?"":"No matches",this.control.append(g)}this.#v(e??k),r?this.#j.get(r)?.focus():t?I.querySelector("[data-favorites-group]")?.focus():e&&this.#c.get(e)?.focus(),N&&queueMicrotask(()=>this.#Q(N))}#K(e,r){let t=this.ownerDocument,s=t.createElement("li");s.className="node branch",s.setAttribute("role","treeitem"),s.dataset.favoritesGroup="true",s.tabIndex=-1;let i=t.createElement("div");i.className="row";let o=t.createElement("button");o.type="button",o.className="expander",o.tabIndex=-1;let d=t.createElement("span");d.textContent="\u2661",d.setAttribute("aria-hidden","true");let l=t.createElement("span");l.className="caption",l.textContent=this.parameters.favoritesLabel;let y=t.createElement("ul");y.className="group",y.setAttribute("role","group");let T=()=>{s.setAttribute("aria-expanded",String(this.#l)),o.textContent=this.#l?"\u25BE":"\u25B8",o.setAttribute("aria-label",`${this.#l?"Collapse":"Expand"} ${this.parameters.favoritesLabel}`),y.hidden=!this.#l},z=()=>{this.#l=!this.#l,T()};o.addEventListener("click",f=>{f.stopPropagation(),z(),s.focus()}),i.addEventListener("click",z),s.addEventListener("focus",()=>this.#T()?.clearRowContext()),s.addEventListener("keydown",f=>{if(f.target===s){if(f.key==="ArrowRight")this.#l?y.firstElementChild?.focus():z();else if(f.key==="ArrowLeft")this.#l&&z();else if(f.key==="Enter"||f.key===" ")z();else if(f.key==="ArrowDown"||f.key==="ArrowUp"){let N=this.#k(),k=N.indexOf(s);N[k+(f.key==="ArrowDown"?1:-1)]?.focus()}else return;f.preventDefault(),f.stopPropagation()}}),i.append(o,d,l),s.append(i,y);for(let f of e.getNodes()){let N=f.getAttr("originalPath"),k=t.createElement("li");k.className="node leaf",k.setAttribute("role","treeitem"),k.dataset.favoritePath=N,k.tabIndex=-1,k.setAttribute("aria-selected",String(r===N));let L=t.createElement("div");L.className="row";let F=t.createElement("span");F.className="spacer";let I=t.createElement("span");I.className="icon",I.setAttribute("aria-hidden","true");let c=t.createElement("span");c.className="badge",c.setAttribute("part","badge");let b=f.getAttr("badge");c.textContent=b==null?"":String(b),c.hidden=b==null||b==="";let g=f.getAttr("badge_color");g&&(c.style.backgroundColor=g,c.setAttribute("data-colored",""));let u=t.createElement("span");u.className="caption",u.textContent=f.getAttr(this.parameters.internalNames?"fieldpath":"fullcaption"),L.title=f.getAttr("fieldpath"),L.draggable=this.parameters.draggable,this.#A.set(L,{item:f,path:N,caption:u}),L.addEventListener("pointerenter",()=>this.#P(L,f,N)),k.addEventListener("focus",()=>this.#P(L,f,N)),L.addEventListener("click",()=>this.#U(N)),k.addEventListener("keydown",a=>{if(a.target===k){if(a.key==="Enter"||a.key===" ")this.#U(N);else if(a.key==="ArrowLeft")s.focus();else if(a.key==="ArrowDown"||a.key==="ArrowUp"){let p=this.#k(),B=p.indexOf(k);p[B+(a.key==="ArrowDown"?1:-1)]?.focus()}else return;a.preventDefault(),a.stopPropagation()}}),L.append(F,I,c,u),k.append(L),y.append(k),this.#j.set(N,k)}return T(),s}#U(e){this.parameters.selectedPath===e?this.retrySelection():this.#a.writeParameter("selectedPath",e)}async#Q({requested:e,version:r,store:t}){let s=()=>this.isConnected&&this.#$===r&&this.#e===t&&this.parameters.selectedPath===e&&this.#b===e,i=e.split("."),o=t;for(let d of i.slice(0,-1)){if(!s())return;let l=o.getNode(d);if(!l||l.resolver!==null&&!this.parameters.resolveLazy||l.resolver===null&&!(l.staticValue instanceof E)||!s()||o.getNode(d)!==l||(this.#q(l),this.#r(),l.resolver!==null&&!(l.staticValue instanceof E)&&await this.#F(l),!s()||o.getNode(d)!==l||!(l.staticValue instanceof E)))return;o=l.staticValue}s()&&o.getNode(i.at(-1))&&this.#r()}#_(e,r,t){if(e.attr.checked==="disabled:on"||e.attr.checked==="disabled:off")return;let s=this.#n.get(e)??e.getValue();if(s instanceof Promise&&!this.#n.has(e)){this.#s.delete(e);let i=s.catch(o=>{this.#s.set(e,o),this.#i.delete(e)}).finally(()=>{this.#n.get(e)===i&&this.#n.delete(e),this.#r()});this.#n.set(e,i)}if(this.parameters.checkChildren&&s instanceof E&&(e.resolver!==null&&this.#w.set(e,s),this.#L(s,r)),e.setAttr({checked:this.parameters.checkChildren&&s instanceof E&&s.length?this.#B(s):r}),this.parameters.checkChildren)for(let i=e.parentBag.parentNode;i&&i!==this.#e.parentNode;i=i.parentBag.parentNode)i.setAttr({checked:this.#B(i.staticValue)});t&&this.#W()}#L(e,r,t=!1){for(let s of e.getNodes()){if(t&&this.#x.has(s)||(this.#x.add(s),s.attr.checked==="disabled:on"||s.attr.checked==="disabled:off"))continue;let i=s.staticValue;i instanceof E&&i.length?(s.resolver!==null&&this.#w.set(s,i),this.#L(i,r),s.setAttr({checked:this.#B(i)})):s.setAttr({checked:r})}}#H(e,r=new Set,t=[]){if(r.has(e))throw new TypeError("tree requires an acyclic Bag store");r.add(e);let s=!1;for(let i of e.getNodes()){this.#x.add(i);let o=i.staticValue;if(!(o instanceof E))continue;let d=!1;i.resolver!==null&&this.#w.get(i)!==o?(this.#w.set(i,o),t.push(o),typeof i.attr.checked=="boolean"&&(this.#L(o,i.attr.checked),d=!0)):typeof i.attr.checked=="boolean"&&o.getNodes().some(l=>!this.#x.has(l))&&(this.#L(o,i.attr.checked,!0),t.push(o),d=!0),d=this.#H(o,r,t)||d,d&&o.length&&i.attr.checked!=="disabled:on"&&i.attr.checked!=="disabled:off"&&i.setAttr({checked:this.#B(o)}),s||=d}return r.delete(e),s}#W(e=!1){let r=[],t=(s,i)=>{for(let o of s.getNodes()){let d=i?`${i}.${o.label}`:o.label,l=o.staticValue;l instanceof E&&l.length?(!this.parameters.checkChildren&&o.attr.checked===!0&&r.push(d),t(l,d)):o.attr.checked===!0&&r.push(d)}};if(t(this.#e,""),e&&this.#d)for(let s of(this.parameters.checkedPaths||"").split(this.parameters.checkedPaths_joiner).filter(Boolean))!r.includes(s)&&this.#Z(s)&&r.push(s);this.#o=r.join(this.parameters.checkedPaths_joiner),this.#a.writeParameter("checkedPaths",this.#o),this.#r()}#Z(e){let r=e.split("."),t=this.#e;for(let s=0;s<r.length;s++){let i=t.getNode(r[s]);if(!i||s===r.length-1)return!1;if(i.resolver!==null&&!(i.staticValue instanceof E))return!0;if(!(i.staticValue instanceof E))return!1;t=i.staticValue}return!1}#B(e){let r=e.getNodes().map(t=>t.attr.checked==="disabled:on"?!0:t.attr.checked==="disabled:off"||t.attr.checked==null?!1:t.attr.checked);return r.every(t=>t===!0)?!0:r.every(t=>t===!1)?!1:-1}#D(e){if(typeof e!="string")throw new TypeError("Tree classes must be a string");return e.split(/\s+/).filter(Boolean)}#T(){let e=[...this.children].filter(r=>r.localName==="gramlot-row-actions");if(e.length>1)throw new Error("tree accepts one rowActions bar");return e[0]??null}#P(e,r,t){let s=this.#T();if(!s||s.contains(this.ownerDocument.activeElement))return;let i=this.getBoundingClientRect(),o=e.getBoundingClientRect();s.setRowContext(r,t),s.style.position="absolute",s.style.top=`${o.top-i.top}px`,s.style.left=s.parameters.position==="start"?`${o.left-i.left}px`:"auto",s.style.right=s.parameters.position==="end"?`${i.right-o.right}px`:"auto",s.style.zIndex="1",s.hidden=!1}#R(e,r){let t=this.#a.callLogic(this.parameters[e],r);if(e==="labelCb"||e==="getLabel"){if(!t||typeof t!="object"||Object.keys(t).length!==1||!(Object.hasOwn(t,"text")&&typeof t.text=="string"||Object.hasOwn(t,"html")&&typeof t.html=="string"))throw new TypeError(`tree ${e} must return {text: string} or {html: string} synchronously`)}else if(typeof t!="string")throw new TypeError(`tree ${e} must return a string synchronously`);return t}#ee(e,r,t){t&&Object.hasOwn(r,"html")?e.replaceChildren(this.#g.sanitize(r.html,{USE_PROFILES:{html:!0},FORBID_TAGS:["style","form","input","button","select","textarea"],RETURN_DOM_FRAGMENT:!0})):e.textContent=t?r.text:r}#k(){return[...this.control.querySelectorAll("[role=treeitem]")].filter(e=>!e.closest("[hidden]"))}#q(e){if(this.#t){this.#h.add(e);return}if(this.parameters.autoCollapse)for(let r of e.parentBag.getNodes())r!==e&&this.#i.delete(r);this.#i.add(e)}#F(e,r=!1){if(this.#n.has(e))return this.#n.get(e);this.#u.add(e),this.#s.delete(e),this.#r();let t=(async()=>{try{await Promise.resolve().then(()=>e.getValue())}catch(s){this.#s.set(e,s),r||this.#i.delete(e)}finally{this.#u.delete(e),this.#n.delete(e),this.#r()}})();return this.#n.set(e,t),t}#v(e){let r=this.#k(),t=typeof e=="string"||e==null?r.find(s=>s.dataset.path===e)??r[0]:e;for(let s of this.control.querySelectorAll("[role=treeitem]"))s.tabIndex=s===t?0:-1}#V(e){this.#b=e;for(let[r,t]of this.#c)t.setAttribute("aria-selected",String(r===e)),t.classList.toggle("selected",r===e),this.#M.get(r)(),t.firstElementChild.setAttribute("part",`row ${t.classList.contains("branch")?"branch-row":"leaf-row"}${r===e?" selected-row":""}`);this.#v(e),this.#c.get(e).focus(),this.#a.writeParameter("selectedPath",e)}}}),je=Q({name:"tree",components:[be,ge]});export{ge as RowActions,be as Tree,je as default};
31
+ [hidden]{display:none}`,this.shadowRoot.append(t);let s=this.ownerDocument.createElement("slot");s.name="row-actions",this.shadowRoot.append(s),this.addEventListener("pointerleave",()=>{let e=this.#L();e&&!e.contains(this.ownerDocument.activeElement)&&e.clearRowContext()})}setSourceContext(t){this.#t=t}get storeBag(){return this.#t.treeStore()}getDragContext(t){for(let s of t.composedPath()){let e=this.#w.get(s);if(!e)continue;let{path:r,caption:n,favorite:l}=e,a=this.#K(r,l);if(!a)return null;let c=s.getBoundingClientRect(),o=c.height?(t.clientY-c.top)/c.height:.5,d=o<.25?"before":o>.75?"after":"inside";return{element:s,item:a,path:r,placement:d,dragValues:{"text/plain":n.textContent,nodeattr:{...a.getAttr()},treenode:{fullpath:a.fullpath,relpath:r}}}}return null}projectAttributes(t,s){let e={};this.#p=new Map;for(let[c,o]of Object.entries(t)){if(!c.startsWith("checked_")){e[c]=o;continue}let d=c.slice(8);if(!d||typeof o!="string"||!o||/^[\^=]/.test(o))throw new TypeError(`tree ${c} requires a Data path, optionally followed by :joiner`);let b=o.indexOf(":");this.#p.set(c,{attribute:d,path:b<0?o:o.slice(0,b),joiner:(b<0?"":o.slice(b+1))||","})}this.#x=Object.hasOwn(t,"checkedPaths"),this.#$=this.#x||!!t.onChecked||this.#p.size>0;let r=this.parameters?.searchEager,n=this.parameters?.resolveLazy,l=super.projectAttributes(e,s);(r!==this.parameters.searchEager||n!==this.parameters.resolveLazy)&&(this.#A(),this.#e=this.#b.toLowerCase()),this.#G!==this.parameters.excludeRoot&&(this.#G=this.parameters.excludeRoot,this.#A(),this.#e=this.#b.toLowerCase());let a=this.parameters.searchText.trim();return a!==this.#b&&(this.#A(),this.#b=a,a?this.#h=setTimeout(()=>{this.#h=null,this.#e=a.toLowerCase(),this.#r()},200):this.#e=""),this.#r(),l}connectedCallback(){this.#h===null&&(this.#e=this.#b.toLowerCase()),this.#r()}disconnectedCallback(){this.#A()}#A(){clearTimeout(this.#h),this.#h=null,this.#M++,this.#d=!1,this.#v.clear(),this.#l.clear(),this.#y.clear()}#C(t){return this.#e?this.#l.has(t):this.#s.has(t)}async#Q(){let t=this.#M,s=this.storeBag,e=()=>this.isConnected&&t===this.#M&&this.parameters.searchEager&&this.parameters.resolveLazy;this.#d=!0;let r=async(n,l,a=new Set)=>{if(!e())return;if(a.has(n))throw new TypeError("tree requires an acyclic Bag store");let c=new Set(a).add(n);for(let o of n.getNodes()){if(!l&&o.label===this.parameters.excludeRoot)continue;if(!e())return;if(o.attr.loop===!0||o.resolver!==null&&!this.parameters.resolveLazy)continue;let d=l?`${l}.${o.label}`:o.label;if(o.resolver!==null&&o.resolver.expired&&!this.#v.has(d)&&(this.#v.add(d),await this.#I(o,d,!0)),!e())return;o.staticValue instanceof j&&await r(o.staticValue,d,c)}};try{await r(s,"")}finally{e()&&(this.#d=!1,this.#r())}}#Z(t){let s=this.ownerDocument.createTreeWalker(t,4),e=[];for(;s.nextNode();)e.push(s.currentNode);for(let r of e){let n=r.textContent,l=n.toLowerCase(),a=this.ownerDocument.createDocumentFragment(),c=0,o=l.indexOf(this.#e);if(!(o<0)){for(;o>=0;){a.append(n.slice(c,o));let d=this.ownerDocument.createElement("mark");d.textContent=n.slice(o,o+this.#e.length),a.append(d),c=o+this.#e.length,o=l.indexOf(this.#e,c)}a.append(n.slice(c)),r.replaceWith(a)}}}retrySelection(){this.#R=void 0,this.#r()}#r(){this.#j||(this.#j=!0,queueMicrotask(()=>{if(this.#j=!1,!this.isConnected)return;let t;try{if(t=this.storeBag,t instanceof Promise)return;if(!(t instanceof j))throw new TypeError("tree storepath must resolve to a Bag")}catch(s){this.#t.reportError(s,"Tree");return}this.#tt(t)}))}#tt(t){let s=this.shadowRoot.activeElement?.closest("[role=treeitem]")?.dataset.path,e=this.shadowRoot.activeElement?.dataset.favoritePath,r=this.shadowRoot.activeElement?.dataset.favoritesGroup==="true",n=new Map,l=new Set,a=(x,w,C)=>{if(l.has(x))throw new TypeError("tree requires an acyclic Bag store");l.add(x);for(let m of x.getNodes()){if(!w&&m.label===this.parameters.excludeRoot)continue;let f=w?`${w}.${m.label}`:m.label,i=m.resolver!==null&&!this.parameters.resolveLazy?null:m.staticValue;n.set(f,{node:m,ancestors:C,children:i instanceof j?i:null}),i instanceof j&&a(i,f,[...C,m])}l.delete(x)};a(t,"",[]),this.parameters.searchEager&&this.parameters.resolveLazy&&this.#e&&this.#h===null&&!this.#d&&[...n].some(([x,{node:w}])=>w.attr.loop!==!0&&w.resolver!==null&&w.resolver.expired&&!this.#v.has(x))&&this.#Q();let c=this.#L();c&&c.getRowContext()===null&&c.clearRowContext();let o=this.#$?this.#nt(t):null;for(let x of this.#s)n.has(x)||this.#s.delete(x);for(let x of this.#n.keys())n.has(x)||this.#n.delete(x);let d=this.parameters.selectedPath,b=null;if(d!==this.#R){this.#R=d,this.#u=d;let x=++this.#q,w=n.get(d)?.ancestors??[];d&&!n.has(d)&&(b={requested:d,version:x});for(let C=0;C<w.length;C++){let m=d.split(".").slice(0,C+1).join(".");this.#s.has(m)||this.#z(m)}}let u=this.#u;this.#o.clear(),this.#B.clear(),this.#w=new WeakMap,this.#P.clear();let v=new Map,g=(x,w,C)=>{let m=this.ownerDocument.createElement("ul");m.className="group",m.setAttribute("part","group"),m.setAttribute("role","group");for(let f of x.getNodes()){if(!w&&f.label===this.parameters.excludeRoot)continue;let i=w?`${w}.${f.label}`:f.label,{children:R}=n.get(i),q=R===null&&!this.parameters.hideValues&&(f.resolver===null||!f.resolver.expired),E=R!==null?R.length>0:q||f.resolver!==null&&this.parameters.resolveLazy&&f.attr.child_count!==0,p=this.ownerDocument.createElement("li");p.className=`node ${E?"branch":"leaf"}`,p.setAttribute("part",`node ${E?"branch":"leaf"}`),p.classList.toggle("loading",this.#c.has(i)),p.classList.toggle("error",this.#n.has(i)),p.setAttribute("aria-busy",String(this.#c.has(i))),p.setAttribute("role","treeitem"),p.setAttribute("aria-selected",String(u===i)),p.classList.toggle("selected",u===i),p.dataset.path=i,p.tabIndex=-1;let L=this.ownerDocument.createElement("div");L.className="row",L.addEventListener("pointerenter",()=>this.#N(L,i,!1)),p.addEventListener("focus",()=>this.#N(L,i,!1)),L.draggable=this.parameters.draggable,L.setAttribute("part",`row ${E?"branch-row":"leaf-row"}${u===i?" selected-row":""}`),this.#n.has(i)&&(L.title=String(this.#n.get(i)));let D=this.ownerDocument.createElement(E?"button":"span");if(D.setAttribute("part",E?"expander":"spacer"),E){D.className="expander",D.type="button",D.tabIndex=-1;let h=this.ownerDocument.createElementNS(F,"svg");h.setAttribute("viewBox","0 0 24 24"),h.setAttribute("aria-hidden","true"),h.setAttribute("focusable","false");let y=this.ownerDocument.createElementNS(F,"path");y.setAttribute("d","m9 5 7 7-7 7"),y.setAttribute("fill","none"),y.setAttribute("stroke","currentColor"),y.setAttribute("stroke-width","1.8"),y.setAttribute("stroke-linecap","round"),y.setAttribute("stroke-linejoin","round"),h.append(y),D.append(h),D.addEventListener("click",T=>{T.stopPropagation(),p.focus(),Y()})}else D.className="spacer";let $=this.ownerDocument.createElement("span");$.className="caption";let _=this.ownerDocument.createElement("span");_.className="badge",_.setAttribute("part","badge"),this.#w.set(L,{path:i,caption:$,favorite:!1}),$.setAttribute("part","caption");let z=this.ownerDocument.createElement("span");z.className=`icon ${E?"branch-icon":"leaf-icon"}`,z.setAttribute("aria-hidden","true"),z.setAttribute("part",`icon ${E?"branch-icon":"leaf-icon"}`);let N;this.#$&&(N=this.ownerDocument.createElement("input"),N.type="checkbox",N.className="checkbox",N.setAttribute("part","checkbox"),N.tabIndex=-1,N.addEventListener("click",h=>{if(h.stopPropagation(),typeof this.parameters.onChecked=="string"){let y=this.#t.callLogic(this.parameters.onChecked,{item:f,path:i});if(y instanceof Promise)throw new TypeError("tree onChecked must be synchronous");if(y===!1){this.#r();return}}this.#at(i)})),L.append(D,N||z,_,$),p.append(L);let I=E?R?g(R,i,p):this.ownerDocument.createElement("ul"):null;if(I&&(I.className="group",I.setAttribute("role","group"),I.setAttribute("part","group")),I&&p.append(I),q){let h=this.ownerDocument.createElement("li");h.className="value-node",h.setAttribute("part","value-node"),h.setAttribute("role","treeitem"),h.setAttribute("aria-selected","false"),h.tabIndex=-1,h.dataset.path=i,h.dataset.valueRow="true";let y=this.ownerDocument.createElement("div");y.className="row value-row",y.setAttribute("part","row value-row");let T=this.ownerDocument.createElement("span");T.className="spacer";let S=this.ownerDocument.createElement("span");S.className="value",S.setAttribute("part","value"),S.textContent=String(f.staticValue),y.append(T,S),h.append(y),I.append(h),y.addEventListener("click",()=>this.#T(i)),h.addEventListener("keydown",B=>{let M=this.#m(),U=M.indexOf(h),V;if(B.key==="ArrowUp")V=M[U-1];else if(B.key==="ArrowDown")V=M[U+1];else if(B.key==="Home")V=M[0];else if(B.key==="End")V=M.at(-1);else if(B.key==="ArrowLeft")V=p;else if(B.key==="Enter"||B.key===" ")this.#T(i);else return;B.preventDefault(),B.stopPropagation(),V&&(this.#g(V),V.focus())})}let X=()=>{let h=this.#C(i),y=this.#u===i,T=f.attr.badge;if(T!=null&&typeof T!="string"&&typeof T!="number")throw new TypeError("tree badge must be text or a number");let S=f.attr.badge_color;if(S!=null&&typeof S!="string")throw new TypeError("tree badge_color must be text");_.textContent=T==null?"":String(T),_.hidden=T==null||T==="",_.style.backgroundColor=S??"",_.toggleAttribute("data-colored",S!=null&&S!=="");let B={item:f,path:i,opened:h,selected:y,state:this.#t.getStaticData(this.#t.attrDatapath("labelState"))},M=this.parameters.labelAttribute,U=this.parameters.internalNames&&f.getAttr("fieldpath")?f.label:this.parameters.getLabel!==null?this.#D("getLabel",B):M!==null?Object.hasOwn(f.attr,M)?f.attr[M]:f.label:this.parameters.labelCb!==null?this.#D("labelCb",B):f.label;this.#ot($,U,!(this.parameters.internalNames&&f.getAttr("fieldpath"))&&(this.parameters.getLabel!==null||M===null&&this.parameters.labelCb!==null)),this.#e&&this.#Z($);let V=this.parameters.getLabelClass!==null?this.#D("getLabelClass",B):f.attr[h?"labelClassOpened":"labelClassClosed"]||f.attr.labelClass||"",Z=[...this.#S(V),...y?this.#S(this.parameters.selectedLabelClass):[]];$.className=["caption",...Z].join(" "),$.setAttribute("part",["caption",...Z].join(" "));let tt=this.#S(f.attr.node_class??"");p.className=["node",E?"branch":"leaf",...tt,...y?["selected"]:[],...E?[h?"opened":"closed"]:[],...this.#c.has(i)?["loading"]:[],...this.#n.has(i)?["error"]:[]].join(" "),p.setAttribute("part",["node",E?"branch":"leaf",...tt].join(" "));let et=!N&&this.parameters.getIconClass!==null,J=et?this.#S(this.#D("getIconClass",B)):[E?"branch-icon":"leaf-icon",...E?[h?"opened-icon":"closed-icon"]:[]];if(z.className=["icon",...J].join(" "),z.setAttribute("part",["icon",...J].join(" ")),z.hidden=et&&J.length===0,N){let W=o.get(i);N.checked=W===!0||W==="disabled:on",N.indeterminate=W===-1,p.setAttribute("aria-checked",W===-1?"mixed":String(N.checked)),N.disabled=W==="disabled:on"||W==="disabled:off",N.setAttribute("aria-label",$.textContent)}E&&D.setAttribute("aria-label",`${h?"Collapse":"Expand"} ${$.textContent}`)};this.#P.set(i,X);let Q=()=>{let h=this.#C(i);p.setAttribute("aria-expanded",String(h)),p.classList.toggle("opened",h),p.classList.toggle("closed",!h),z.classList.toggle("opened-icon",h),z.setAttribute("part",`icon branch-icon ${h?"opened-icon":"closed-icon"}`),I.hidden=!h,X()},Y=()=>{let h=this.#e?this.#l:this.#s;h.has(i)?(h.delete(i),this.#e&&this.#y.add(i)):(this.#e?(this.#y.delete(i),this.#l.add(i)):this.#z(i),f.resolver!==null&&this.#I(f,i));for(let y of v.values())y();this.#g(i)};E?(v.set(i,Q),Q()):X(),L.addEventListener("click",()=>this.#T(i)),p.addEventListener("keydown",h=>{if(h.target!==p)return;let y=this.#m(),T=y.indexOf(p),S;if(h.key==="ArrowDown")S=y[T+1];else if(h.key==="ArrowUp")S=y[T-1];else if(h.key==="Home")S=y[0];else if(h.key==="End")S=y.at(-1);else if(h.key==="ArrowRight"&&E)this.#C(i)?S=I.firstElementChild:Y();else if(h.key==="ArrowLeft")E&&this.#C(i)?Y():S=C;else if(h.key===" "&&N)N.click();else if(h.key==="Enter"||h.key===" ")this.#T(i);else return;h.preventDefault(),h.stopPropagation(),S&&(this.#g(S),S.focus())}),this.#o.set(i,p),m.append(p)}return m},k=g(t,"",null),P=this.#lt();if(P?.length&&k.prepend(this.#et(P,u)),this.control.replaceChildren(k),this.control.setAttribute("aria-busy",String(this.#d)),this.#e){let x=new Set,w=[];this.#l.clear();for(let[m,f]of this.#o){let i=f.firstElementChild.querySelector(".caption"),R=n.get(m);if(R.ancestors.some(p=>p.attr.loop===!0))continue;let q=this.parameters.searchAttributes.split(",").map(p=>p.trim()).filter(Boolean).flatMap(p=>{let L=R.node.getAttr(p);return Array.isArray(L)?L.filter(D=>typeof D=="string"):typeof L=="string"?[L]:[]}),E=[i.textContent,...q].some(p=>p.toLowerCase().includes(this.#e));if(E&&w.push(i),E||this.#n.has(m)||this.#c.has(m)){x.add(m);let p=m.split(".");for(let L of R.ancestors.keys()){let D=p.slice(0,L+1).join(".");x.add(D),this.#y.has(D)||this.#l.add(D)}}}for(let[m,f]of this.#o)f.hidden=!x.has(m);for(let m of v.values())m();let C=this.ownerDocument.createElement("div");C.className="search-status",C.setAttribute("role","status"),C.textContent=this.#d?"Searching\u2026":this.#n.size?"Some branches could not be searched. Expand them to retry.":w.length?"":"No matches",this.control.append(C)}this.#g(s??u),e?this.#B.get(e)?.focus():r?k.querySelector("[data-favorites-group]")?.focus():s&&this.#o.get(s)?.focus(),b&&queueMicrotask(()=>this.#st(b))}#et(t,s){let e=this.ownerDocument,r=e.createElement("li");r.className="node branch",r.setAttribute("role","treeitem"),r.dataset.favoritesGroup="true",r.tabIndex=-1;let n=e.createElement("div");n.className="row";let l=e.createElement("button");l.type="button",l.className="expander",l.tabIndex=-1;let a=e.createElement("span");a.textContent="\u2661",a.setAttribute("aria-hidden","true");let c=e.createElement("span");c.className="caption",c.textContent=this.parameters.favoritesLabel;let o=e.createElement("ul");o.className="group",o.setAttribute("role","group");let d=()=>{r.setAttribute("aria-expanded",String(this.#a)),l.textContent=this.#a?"\u25BE":"\u25B8",l.setAttribute("aria-label",`${this.#a?"Collapse":"Expand"} ${this.parameters.favoritesLabel}`),o.hidden=!this.#a},b=()=>{this.#a=!this.#a,d()};l.addEventListener("click",u=>{u.stopPropagation(),b(),r.focus()}),n.addEventListener("click",b),r.addEventListener("focus",()=>this.#L()?.clearRowContext()),r.addEventListener("keydown",u=>{if(u.target===r){if(u.key==="ArrowRight")this.#a?o.firstElementChild?.focus():b();else if(u.key==="ArrowLeft")this.#a&&b();else if(u.key==="Enter"||u.key===" ")b();else if(u.key==="ArrowDown"||u.key==="ArrowUp"){let v=this.#m(),g=v.indexOf(r);v[g+(u.key==="ArrowDown"?1:-1)]?.focus()}else return;u.preventDefault(),u.stopPropagation()}}),n.append(l,a,c),r.append(n,o);for(let u of t.getNodes()){let v=u.getAttr("originalPath"),g=e.createElement("li");g.className="node leaf",g.setAttribute("role","treeitem"),g.dataset.favoritePath=v,g.tabIndex=-1,g.setAttribute("aria-selected",String(s===v));let k=e.createElement("div");k.className="row";let P=e.createElement("span");P.className="spacer";let x=e.createElement("span");x.className="icon",x.setAttribute("aria-hidden","true");let w=e.createElement("span");w.className="badge",w.setAttribute("part","badge");let C=u.getAttr("badge");w.textContent=C==null?"":String(C),w.hidden=C==null||C==="";let m=u.getAttr("badge_color");m&&(w.style.backgroundColor=m,w.setAttribute("data-colored",""));let f=e.createElement("span");f.className="caption",f.textContent=u.getAttr(this.parameters.internalNames?"fieldpath":"fullcaption"),k.title=u.getAttr("fieldpath"),k.draggable=this.parameters.draggable,this.#w.set(k,{path:v,caption:f,favorite:!0}),k.addEventListener("pointerenter",()=>this.#N(k,v,!0)),g.addEventListener("focus",()=>this.#N(k,v,!0)),k.addEventListener("click",()=>this.#U(v)),g.addEventListener("keydown",i=>{if(i.target===g){if(i.key==="Enter"||i.key===" ")this.#U(v);else if(i.key==="ArrowLeft")r.focus();else if(i.key==="ArrowDown"||i.key==="ArrowUp"){let R=this.#m(),q=R.indexOf(g);R[q+(i.key==="ArrowDown"?1:-1)]?.focus()}else return;i.preventDefault(),i.stopPropagation()}}),k.append(P,x,w,f),g.append(k),o.append(g),this.#B.set(v,g)}return d(),r}#U(t){this.parameters.selectedPath===t?this.retrySelection():this.#t.writeParameter("selectedPath",t)}async#st({requested:t,version:s}){let e=()=>this.isConnected&&this.#q===s&&this.parameters.selectedPath===t&&this.#u===t,r=t.split(".");for(let n of r.slice(0,-1).keys()){let l=r.slice(0,n+1).join(".");if(!e())return;let a=this.#_(l);if(!a||a.resolver!==null&&!this.parameters.resolveLazy||a.resolver===null&&!(a.staticValue instanceof j))return;this.#z(l),this.#r(),a.resolver!==null&&!(a.staticValue instanceof j)&&await this.#I(a,l)}e()&&this.#_(t)&&this.#r()}#H(){let t=this.#t.sourceNode.getAttr("_valuelabel"),s=t==null?null:{_valuelabel:t},e=[{name:"checkedPaths",attribute:null,joiner:this.parameters.checkedPaths_joiner,value:this.#x?this.parameters.checkedPaths:this.#W,write:r=>{this.#x?this.#t.writeParameter("checkedPaths",r,s):this.#W=r}},{name:"checkedBranches",attribute:null,branches:!0,joiner:",",value:this.#F,write:r=>{this.#F=r}}];for(let[r,{attribute:n,path:l,joiner:a}]of this.#p){let c=this.#t.readRelativeData(l);if(c!=null&&typeof c!="string")throw new TypeError(`tree ${r} must address text`);e.push({name:r,attribute:n,joiner:a,value:c,write:o=>this.#t.setRelativeData(l,o,s)})}return e}#E(t){return(t.value??"").split(t.joiner).filter(Boolean)}#V(t){let s={paths:new Set,attributes:new Map};for(let e of this.#p.values())s.attributes.set(e.attribute,new Set);for(let e of t){let r=e.attribute===null?s.paths:s.attributes.get(e.attribute);for(let n of this.#E(e))r.add(n)}return s}#X(t){let s=t.resolver!==null&&!this.parameters.resolveLazy?null:t.staticValue;return s instanceof j?s:null}#O(t,s,e=null){let r=new Map,n=this.parameters.checkChildren,l=new Set,a=(o,d)=>s.paths.has(d)||[...s.attributes].some(([b,u])=>o.attr[b]!=null&&u.has(String(o.attr[b]))),c=(o,d,b,u)=>{if(l.has(o))throw new TypeError("tree requires an acyclic Bag store");l.add(o);let v=[];for(let g of o.getNodes()){if(!d&&g.label===this.parameters.excludeRoot)continue;let k=d?`${d}.${g.label}`:g.label,P=this.#X(g),x=e!==null&&k===e.path?e.value:u,w;if(g.attr.checked==="disabled:on"||g.attr.checked==="disabled:off")w=g.attr.checked,P&&c(P,k,!1,void 0);else{let C=x!==void 0?x:b||a(g,k),m=P?c(P,k,n&&C,n?x:void 0):[];w=n&&m.length?this.#rt(m):C}r.set(k,w),v.push(w)}return l.delete(o),v};return c(t,"",!1,void 0),r}#rt(t){let s=t.map(e=>e==="disabled:on"?!0:e==="disabled:off"?!1:e);return s.every(e=>e===!0)?!0:s.every(e=>e===!1)?!1:-1}#Y(t,s,e,r=null,n=null){let l=[],a=new Set,c=this.parameters.checkChildren,o=(d,b)=>{for(let u of d.getNodes()){if(!b&&u.label===this.parameters.excludeRoot)continue;let v=b?`${b}.${u.label}`:u.label,g=this.#X(u),k=e.attribute===null?v:u.attr[e.attribute]==null?null:String(u.attr[e.attribute]);k!==null&&a.add(k);let P=e.branches?c&&g?.length>0:!(c&&g?.length);k!==null&&P&&s.get(v)===!0&&!l.includes(k)&&l.push(k),g&&o(g,v)}};if(o(t,""),r!==null&&!e.branches)for(let d of this.#E(r))l.includes(d)||(e.attribute!==null?!a.has(d):this.#it(d)&&!(c&&n!==null&&(d===n||d.startsWith(`${n}.`))))&&l.push(d);return l.join(e.joiner)}#nt(t){let s=this.#H(),e=this.#f===null,r=s.filter(a=>e?this.#E(a).length:(this.#f.get(a.name)??"")!==(a.value??"")),n=this.#O(t,this.#V(r.length||e?r:s));this.#f=new Map(s.map(a=>[a.name,a.value??""]));let l=r.find(a=>a.name==="checkedPaths");if(l&&!e)for(let a of this.#E(l))n.has(a)&&typeof n.get(a)!="string"&&this.#J(a,!0);if(r.length)for(let a of s){if(r.includes(a))continue;let c=this.#Y(t,n,a);c!==(a.value??"")&&(this.#f.set(a.name,c),a.write(c))}return n}#at(t){let s=this.storeBag,e=this.#H(),r=this.#O(s,this.#V(e)),n=r.get(t);if(n==="disabled:on"||n==="disabled:off")return;let l=n!==!1;if(this.parameters.checkChildren){let c=[...r].filter(([b])=>b.startsWith(`${t}.`)),o=c.filter(([,b])=>b==="disabled:on"||b==="disabled:off").map(([b])=>`${b}.`),d=c.filter(([b,u])=>u!=="disabled:on"&&u!=="disabled:off"&&!o.some(v=>b.startsWith(v))&&!c.some(([v])=>v.startsWith(`${b}.`)));d.length&&(l=d.some(([,b])=>b===!0))}let a=this.#O(s,this.#V(e),{path:t,value:!l});this.#J(t,!l);for(let c of e){let o=this.#Y(s,a,c,c,t);this.#f.set(c.name,o),o!==(c.value??"")&&c.write(o)}this.#r()}#J(t,s){this.#t.publish("checked",{path:t,checked:s})}#it(t){let s=t.split("."),e=this.storeBag;for(let r=0;r<s.length;r++){let n=e.getNode(s[r]);if(!n||r===s.length-1)return!1;if(n.resolver!==null&&!(n.staticValue instanceof j))return!0;if(!(n.staticValue instanceof j))return!1;e=n.staticValue}return!1}#S(t){if(typeof t!="string")throw new TypeError("Tree classes must be a string");return t.split(/\s+/).filter(Boolean)}#L(){let t=[...this.children].filter(s=>s.localName==="gramlot-row-actions");if(t.length>1)throw new Error("tree accepts one rowActions bar");return t[0]??null}#N(t,s,e){let r=this.#L();if(!r||r.contains(this.ownerDocument.activeElement))return;let n=this.getBoundingClientRect(),l=t.getBoundingClientRect();r.setRowContext(s,()=>this.#K(s,e)),r.style.position="absolute",r.style.top=`${l.top-n.top}px`,r.style.left=r.parameters.position==="start"?`${l.left-n.left}px`:"auto",r.style.right=r.parameters.position==="end"?`${n.right-l.right}px`:"auto",r.style.zIndex="1",r.hidden=!1}#D(t,s){let e=this.#t.callLogic(this.parameters[t],s);if(t==="labelCb"||t==="getLabel"){if(!e||typeof e!="object"||Object.keys(e).length!==1||!(Object.hasOwn(e,"text")&&typeof e.text=="string"||Object.hasOwn(e,"html")&&typeof e.html=="string"))throw new TypeError(`tree ${t} must return {text: string} or {html: string} synchronously`)}else if(typeof e!="string")throw new TypeError(`tree ${t} must return a string synchronously`);return e}#ot(t,s,e){e&&Object.hasOwn(s,"html")?t.replaceChildren(this.#i.sanitize(s.html,{USE_PROFILES:{html:!0},FORBID_TAGS:["style","form","input","button","select","textarea"],RETURN_DOM_FRAGMENT:!0})):t.textContent=e?s.text:s}#m(){return[...this.control.querySelectorAll("[role=treeitem]")].filter(t=>!t.closest("[hidden]"))}#z(t){if(this.#e){this.#l.add(t);return}if(this.parameters.autoCollapse){let s=t.includes(".")?t.slice(0,t.lastIndexOf(".")):"";for(let e of[...this.#s]){let r=e.includes(".")?e.slice(0,e.lastIndexOf(".")):"";e!==t&&r===s&&this.#s.delete(e)}}this.#s.add(t)}#I(t,s,e=!1){if(this.#k.has(s))return this.#k.get(s);this.#c.add(s),this.#n.delete(s),this.#r();let r=(async()=>{try{await Promise.resolve().then(()=>t.getValue())}catch(n){this.#n.set(s,n),e||this.#s.delete(s)}finally{this.#c.delete(s),this.#k.delete(s),this.#r()}})();return this.#k.set(s,r),r}#_(t){let s=this.storeBag,e=null;for(let r of t.split(".")){if(!(s instanceof j)||(e=s.getNode(r),!e))return null;s=e.staticValue}return e}#K(t,s){if(!s)return this.#_(t);let e=this.#t.getStaticData(this.#t.attrDatapath("favorites"));return e instanceof j?e.getNodes().find(r=>r.getAttr("originalPath")===t)??null:null}#lt(){let t=this.#t.getStaticData(this.#t.attrDatapath("favorites"));if(t!==null&&!(t instanceof j))throw new TypeError("tree favorites must be a Bag");return t}#g(t){let s=this.#m(),e=typeof t=="string"||t==null?s.find(r=>r.dataset.path===t)??s[0]:t;for(let r of this.control.querySelectorAll("[role=treeitem]"))r.tabIndex=r===e?0:-1}#T(t){this.#u=t;for(let[s,e]of this.#o)e.setAttribute("aria-selected",String(s===t)),e.classList.toggle("selected",s===t),this.#P.get(s)(),e.firstElementChild.setAttribute("part",`row ${e.classList.contains("branch")?"branch-row":"leaf-row"}${s===t?" selected-row":""}`);this.#g(t),this.#o.get(t).focus(),this.#t.writeParameter("selectedPath",t)}}}),jt=K({name:"tree",components:[mt,bt]});export{bt as RowActions,mt as Tree,jt as default};
@@ -1,3 +1,3 @@
1
1
  export {default} from "./collection.js";
2
2
  export * from "./collection.js";
3
- export const buildId = "sha256:9f96abe1657005e4f18f1fe9a585f4a0a7b24eb4407c09c57f427919c7ece9bc";
3
+ export const buildId = "sha256:db17118acfb0402560878738fdc21bf59a96c129c8249867c664a2bb37b6a2cb";
@@ -123,7 +123,6 @@
123
123
  "tree": {
124
124
  "_meta": {
125
125
  "gramlot_component": {
126
- "bagStore": true,
127
126
  "command": false,
128
127
  "dataScope": false,
129
128
  "dragSource": true,
@@ -8,6 +8,6 @@ mygramlot = GramlotCollection(
8
8
  module="assets/index.js",
9
9
  css=(),
10
10
  dependencies=(),
11
- build_id="sha256:713c837016d47c74e514f8121ddc5727939530dbbf644c4f26e73f14e25d5001",
11
+ build_id="sha256:5e0b1291248f1696acf7eabcf1bd9c3689ce266f300b872b31940291ce841a9b",
12
12
  files=("assets/collection.js", "assets/index.js", "commands.json", "grammar.json",),
13
13
  )
@@ -1,6 +1,6 @@
1
- var et=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var ft=Object.prototype.hasOwnProperty;var bt=(n,t)=>{for(var e in t)et(n,e,{get:t[e],enumerable:!0})},tt=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of gt(t))!ft.call(n,s)&&s!==e&&et(n,s,{get:()=>t[s],enumerable:!(i=ut(t,s))||i.enumerable});return n},N=(n,t,e)=>(tt(n,t,"default"),e&&tt(e,t,"default"));var w={};bt(w,{defineCollection:()=>Z});N(w,Ut);import*as Ut from"@gramlot/gramlot/components";import{defineCollection as wt}from"@gramlot/gramlot/components";function Z(n){if(n.name!=="uploads")throw new Error("Unexpected bundled collection");let t=[],e={};n.css?.forEach((i,s)=>{i.href=t[s].href});for(let[i,s]of Object.entries(n.assets??{}))s.href=e[i].href;return wt({...n,css:t,assets:e})}import{Bag as It}from"@gramlot/gramlot";import{sharedModules as yt}from"@gramlot/gramlot";var xt=n=>yt["./components/parameters.js"][n];var st=xt("projectParameters");function S(n){return class extends n{constructor(){super();let t=this.attachShadow({mode:"open"}),e=this.ownerDocument.createElement("style");e.textContent=`:host{box-sizing:border-box;display:block;min-width:0;font:inherit;color:var(--gramlot-ink,CanvasText)}
1
+ var et=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var ft=Object.prototype.hasOwnProperty;var wt=(h,t)=>{for(var e in t)et(h,e,{get:t[e],enumerable:!0})},tt=(h,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of gt(t))!ft.call(h,i)&&i!==e&&et(h,i,{get:()=>t[i],enumerable:!(s=ut(t,i))||s.enumerable});return h},M=(h,t,e)=>(tt(h,t,"default"),e&&tt(e,t,"default"));var y={};wt(y,{defineCollection:()=>Z});M(y,$t);import*as $t from"@gramlot/gramlot/components";import{defineCollection as bt}from"@gramlot/gramlot/components";function Z(h){if(h.name!=="uploads")throw new Error("Unexpected bundled collection");let t=[],e={};h.css?.forEach((s,i)=>{s.href=t[i].href});for(let[s,i]of Object.entries(h.assets??{}))i.href=e[s].href;return bt({...h,css:t,assets:e})}import{Bag as It}from"@gramlot/gramlot";import{sharedModules as yt}from"@gramlot/gramlot";var xt=h=>yt["./components/parameters.js"][h];var st=xt("projectParameters");function N(h){return class extends h{constructor(){super();let t=this.attachShadow({mode:"open"}),e=this.ownerDocument.createElement("style");e.textContent=`:host{box-sizing:border-box;display:block;min-width:0;font:inherit;color:var(--gramlot-ink,CanvasText)}
2
2
  *,*::before,*::after{box-sizing:border-box}.control-box{min-width:0}slot{display:contents}
3
- ::slotted(*){min-width:0;max-width:100%}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",this.control=this.controlBox,this.control.id="control",this.control.append(this.ownerDocument.createElement("slot")),t.append(e,this.controlBox)}projectAttributes(t){return st(this,t)}}}S.parameters={};import{Bag as q}from"@gramlot/gramlot";import{sharedModules as vt}from"@gramlot/gramlot";var it=n=>vt["@genrojs/tytx"][n];var rt=it("fromTytx");var at=it("toTytx");import{sharedModules as Et}from"@gramlot/gramlot";var Ct=n=>Et["./random-id.js"][n],A=Ct("randomId");function M(n,t){if(t===null)return{};let e=n.getRelativeData(t);if(!(e instanceof q))throw new TypeError("uploader contextPath must resolve to a Bag");return e.asDict(!1,!1,!0)}var P=class{#s=new Map;#h=new Map;#t=new Map;#i=new Set;#n=!1;constructor({gramlot:t,window:e,store:i,operation:s,onComplete:r,onChange:o,getContext:a}){if(!(i instanceof q))throw new TypeError("uploader storepath must resolve to a Bag");Object.assign(this,{gramlot:t,window:e,store:i,operation:s,onComplete:r,onChange:o,getContext:a})}add(t){if(this.#n)throw new Error("Uploader is closed");let e=`f_${A().replaceAll("-","")}`;return this.#s.set(e,t),this.store.setItem(e,new q({name:t.name,size:t.size,mediaType:t.type||"",metadata:new q,status:"queued",loaded:0,result:null,error:null})),this.onChange(),e}#e(t,e){if(this.#n)return;let i=this.store.getItem(t);if(i){for(let[s,r]of Object.entries(e))i.setItem(s,r);this.#n||this.onChange()}}async start(t){if(this.#n||this.#h.has(t))return;let e=this.#s.get(t),i=this.store.getItem(t);if(!e||!i||i.getItem("status")!=="queued")return;if(!this.gramlot.capabilities.includes("upload")){this.#e(t,{status:"failed",error:"Upload is unavailable in this environment"});return}let s={xhr:null,controller:new AbortController,transferId:null,cancelled:!1};this.#h.set(t,s),this.#e(t,{status:"preparing",error:null});try{let r=await this.gramlot.rpc.call("upload","prepare",{operation:this.operation,metadata:{name:e.name,size:e.size,mediaType:e.type||"",fields:i.getItem("metadata").asDict(!1,!1,!0),context:this.getContext()}});if(s.transferId=r.transferId,this.#t.set(t,r.transferId),s.cancelled||this.#n){let a=await this.gramlot.rpc.call("upload","cancel",{transferId:s.transferId});await this.#c(t,a,!0);return}this.#e(t,{status:"uploading"});let o=await this.#r(e,s,r.authorization,t);await this.#c(t,o,s.cancelled)}catch(r){if(s.transferId)try{let o=await this.gramlot.rpc.call("upload",s.cancelled?"cancel":"status",{transferId:s.transferId});await this.#c(t,o,s.cancelled)}catch(o){this.#e(t,{status:"uncertain",error:o.message})}else this.#e(t,{status:s.cancelled?"cancelled":"failed",error:r.message})}finally{this.#h.delete(t)}}#r(t,e,i,s){return this.gramlot.uploadUrl?new Promise((r,o)=>{let a=e.xhr=new this.window.XMLHttpRequest;a.open("POST",this.gramlot.uploadUrl,!0),a.setRequestHeader("Content-Type","application/octet-stream"),a.setRequestHeader("X-Gramlot-Page-Id",this.gramlot.pageId),a.setRequestHeader("X-Gramlot-Transfer-Id",e.transferId),a.setRequestHeader("X-Gramlot-Upload-Token",i),a.upload.addEventListener("progress",l=>this.#e(s,{loaded:l.loaded})),a.addEventListener("load",()=>{if(a.status!==200){o(new Error(`Upload HTTP ${a.status}`));return}try{r(rt(a.responseText))}catch(l){o(l)}},{once:!0}),a.addEventListener("error",()=>o(new Error("Upload connection failed")),{once:!0}),a.addEventListener("abort",()=>o(new Error("Upload cancelled")),{once:!0}),a.send(t)}):this.gramlot.rpc.transport.upload({pageId:this.gramlot.pageId,transferId:e.transferId,authorization:i,file:t},r=>this.#e(s,{loaded:r}),e.controller.signal)}async#c(t,e,i=!1){if(e.state==="completed"){if(this.#e(t,{status:"completed",result:e.result,error:null}),this.#s.delete(t),this.#t.delete(t),!this.#n&&this.onComplete)try{await this.onComplete(this.store.getNode(t),e.result)}catch(s){this.#e(t,{error:`Completion callback: ${s.message}`})}}else e.state==="unsaved"?(this.#t.delete(t),this.#e(t,{status:i?"cancelled":"failed",error:i?null:"Transfer was not saved"})):this.#e(t,{status:"uncertain",error:"Upload outcome is not yet known"})}localFile(t){return this.#s.get(t)??null}remove(t){let e=this.store.getItem(t);return!e||this.#h.has(t)||!["queued","completed","failed","cancelled"].includes(e.getItem("status"))?!1:(this.#s.delete(t),this.#t.delete(t),this.store.popNode(t),this.#n||this.onChange(),!0)}async reconcile(t){let e=this.#t.get(t);if(!(!e||this.#n||this.#h.has(t)||this.#i.has(t))){this.#i.add(t);try{let i=await this.gramlot.rpc.call("upload","status",{transferId:e});await this.#c(t,i)}catch(i){this.#e(t,{status:"uncertain",error:i.message})}finally{this.#i.delete(t)}}}retry(t){let e=this.store.getItem(t);!e||!this.#s.has(t)||!["failed","cancelled"].includes(e.getItem("status"))||this.#e(t,{status:"queued",loaded:0,error:null})}cancel(t){let e=this.#h.get(t);e&&(e.cancelled=!0,e.controller.abort(),e.xhr?.abort())}dispose(){this.#n=!0;for(let t of this.#h.keys())this.cancel(t);this.#s.clear()}};var ot=(0,w.defineComponent)({name:"uploader",tag:"gramlot-uploader",base:S,sourceContext:!0,bagStore:!0,parameters:{operation:{dtype:"T"},storepath:{dtype:"T"},contextPath:{dtype:"T",nullable:!0,default:null},accept:{dtype:"T",default:"",binding:"read"},multiple:{dtype:"B",default:!1,binding:"read"},autoUpload:{dtype:"B",default:!0,binding:"read"},manualUpload:{dtype:"B",default:!0,binding:"read"},disabled:{dtype:"B",default:!1,binding:"read"},selectedPath:{dtype:"T",nullable:!0,default:null,binding:"twoWay"},onComplete:{dtype:"T",nullable:!0,default:null}},implementation:n=>class extends n{#s;#h;#t;#i=!1;#n=null;#e=null;#r;#c=null;constructor(){super(),this.control.replaceChildren();let t=this.ownerDocument,e=t.createElement("style");e.textContent=":host{display:block} .drop{border:1px dashed currentColor;padding:1em;display:grid;gap:.5em} ul{padding-inline-start:1.2em} button,input{font:inherit}",this.drop=t.createElement("div"),this.drop.className="drop";let i=t.createElement("label");i.textContent="Choose files or drop them here ",this.input=t.createElement("input"),this.input.type="file",i.append(this.input),this.startButton=t.createElement("button"),this.startButton.type="button",this.startButton.textContent="Upload",this.message=t.createElement("div"),this.message.setAttribute("role","status"),this.summary=t.createElement("div"),this.summary.setAttribute("aria-label","Upload summary"),this.summary.setAttribute("aria-live","polite"),this.list=t.createElement("ul"),this.preview=t.createElement("div"),this.preview.setAttribute("aria-label","File preview"),this.drop.append(i,this.startButton,this.message,this.summary,this.list,this.preview),this.control.append(this.drop),this.shadowRoot.append(e),this.input.addEventListener("change",()=>{this.#l(this.input.files),this.input.value=""}),this.startButton.addEventListener("click",()=>{this.parameters.manualUpload&&!this.parameters.autoUpload&&this.#a()}),this.drop.addEventListener("dragover",s=>{!this.parameters?.disabled&&[...s.dataTransfer.types].includes("Files")&&(s.preventDefault(),s.stopPropagation(),s.dataTransfer.dropEffect="copy")}),this.drop.addEventListener("drop",s=>{!this.parameters?.disabled&&[...s.dataTransfer.types].includes("Files")&&(s.preventDefault(),s.stopPropagation(),this.#l(s.dataTransfer.files))})}setSourceContext(t){this.#s=t}setStoreBag(t){if(!(t instanceof It))throw new TypeError("uploader storepath must resolve to a Bag");let e=this.#h&&this.#h!==t;e&&(this.#o(),this.#t?.dispose(),this.#t=null,this.#c=null,this.#r=null),this.#h=t,e&&this.#s&&this.#s.writeParameter("selectedPath",null)}projectAttributes(t,e){let i=!!(this.parameters?.autoUpload&&!this.parameters.disabled),s=super.projectAttributes(t,e);return this.input.accept=this.parameters.accept||"",this.input.multiple=!!this.parameters.multiple,this.input.disabled=!!this.parameters.disabled,this.startButton.disabled=!!this.parameters.disabled,this.startButton.hidden=!!(this.parameters.autoUpload||!this.parameters.manualUpload),this.parameters.selectedPath!==this.#r&&(this.#r=this.parameters.selectedPath,this.#c=this.parameters.selectedPath),this.#d(),this.#t&&(this.#t.operation=this.parameters.operation),this.#p(),!i&&this.parameters.autoUpload&&!this.parameters.disabled&&this.#t&&this.ownerDocument.defaultView.queueMicrotask(()=>{this.isConnected&&this.parameters.autoUpload&&!this.parameters.disabled&&this.#a()}),s}#d(){if(!this.#t&&this.#s&&this.#h&&this.parameters){let{gramlot:t,window:e}=this.#s.upload();this.#t=new P({gramlot:t,window:e,store:this.#h,operation:this.parameters.operation,onChange:()=>this.#p(),getContext:()=>M(this.#s.sourceNode,this.parameters.contextPath),onComplete:(i,s)=>this.parameters.onComplete?this.#s.callLogic(this.parameters.onComplete,{item:i,result:s}):null})}}connectedCallback(){this.#d()}disconnectedCallback(){this.ownerDocument.defaultView.queueMicrotask(()=>{this.isConnected||(this.#o(),this.#t?.dispose(),this.#t=null)})}#l(t){if(!this.#t||this.parameters.disabled)return;let e=[...t];if(!this.parameters.multiple&&e.length>1){this.message.textContent="Select one file";return}let i=(this.parameters.accept||"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean);for(let s of e){let r=s.name.toLowerCase(),o=(s.type||"").toLowerCase();if(i.length&&!i.some(a=>a.startsWith(".")?r.endsWith(a):a.endsWith("/*")?o.startsWith(a.slice(0,-1)):o===a)){this.message.textContent=`${s.name}: file type is not accepted`;continue}this.#t.add(s)}this.parameters.autoUpload&&this.#a()}async#a(){if(!this.#t||this.parameters.disabled||this.#i)return;this.#i=!0;let t=this.#t;try{for(;!this.parameters.disabled&&this.#t===t;){let e=this.#h.getNodes().find(i=>i.value.getItem("status")==="queued");if(!e)break;await t.start(e.label)}}finally{this.#i=!1}}#m(t){this.#c=t,this.#r=t,this.#s.writeParameter("selectedPath",t),this.#p()}#o(){this.#n&&this.ownerDocument.defaultView.URL.revokeObjectURL(this.#n),this.#n=null,this.#e=null,this.preview?.replaceChildren()}async#u(t,e){this.#o(),this.#e=t;let i=(e.type||"").toLowerCase();if(["image/png","image/jpeg","image/gif","image/webp"].includes(i)){this.#n=this.ownerDocument.defaultView.URL.createObjectURL(e);let s=this.ownerDocument.createElement("img");s.src=this.#n,s.alt=e.name,s.style.maxWidth="100%",s.style.maxHeight="200px",this.preview.append(s);return}if((i.startsWith("text/")||e.name.toLowerCase().endsWith(".grmlt"))&&e.size<=1048576){try{let s=await e.text();if(this.#e!==t||!this.isConnected)return;let r=this.ownerDocument.createElement("pre");r.textContent=s,r.style.maxHeight="200px",r.style.overflow="auto",this.preview.append(r)}catch(s){this.#e===t&&(this.preview.textContent=`Preview failed: ${s.message}`)}return}this.preview.textContent="No preview available"}#p(){if(!this.list||!this.#h)return;this.list.replaceChildren();let t=this.#h.getNodes(),e=new Map,i=0,s=0;for(let r of t){let o=r.value,a=o.getItem("status");e.set(a,(e.get(a)??0)+1),i+=o.getItem("loaded"),s+=o.getItem("size")}this.summary.textContent=`${t.length} file${t.length===1?"":"s"} \u2014 ${i}/${s} bytes`+[...e].map(([r,o])=>` \xB7 ${o} ${r}`).join("");for(let r of t){let o=r.value,a=this.ownerDocument.createElement("li"),l=this.ownerDocument.createElement("button");l.type="button",l.textContent=o.getItem("name"),l.disabled=!!this.parameters.disabled,l.setAttribute("aria-pressed",String(r.label===this.#c)),l.setAttribute("aria-label",`Select ${o.getItem("name")}`),l.addEventListener("click",()=>{this.#m(r.label);let c=this.#h.getNodes().findIndex(d=>d.label===r.label);c>=0&&this.list.children[c].firstElementChild.focus()}),a.append(l,this.ownerDocument.createTextNode(` \u2014 ${o.getItem("status")} (${o.getItem("loaded")}/${o.getItem("size")}) `));let m=o.getItem("status");if(["preparing","uploading"].includes(m)){let c=this.ownerDocument.createElement("button");c.textContent="Cancel",c.type="button",c.addEventListener("click",()=>this.#t.cancel(r.label)),a.append(c)}else if(["failed","cancelled"].includes(m)){let c=this.ownerDocument.createElement("button");c.textContent="Retry",c.type="button",c.disabled=!!this.parameters.disabled,c.addEventListener("click",()=>{this.#t.retry(r.label),this.parameters.autoUpload&&this.#a()}),a.append(c)}if(m==="uncertain"){let c=this.ownerDocument.createElement("button");c.textContent="Check status",c.type="button",c.addEventListener("click",()=>{this.#t.reconcile(r.label)}),a.append(c)}if(["queued","completed","failed","cancelled"].includes(m)){let c=this.#t?.localFile(r.label);if(c){let g=this.ownerDocument.createElement("button");g.textContent="Preview",g.type="button",g.addEventListener("click",()=>{this.#u(r.label,c)}),a.append(g)}let d=this.ownerDocument.createElement("button");d.textContent="Remove",d.type="button",d.disabled=!!this.parameters.disabled,d.addEventListener("click",()=>{this.#t.remove(r.label)&&(this.#e===r.label&&this.#o(),this.#c===r.label&&this.#m(null))}),a.append(d)}o.getItem("error")&&a.append(this.ownerDocument.createTextNode(` ${o.getItem("error")}`)),this.list.append(a)}}}});import{Bag as ct}from"@gramlot/gramlot";import{sharedModules as Tt}from"@gramlot/gramlot";var kt=n=>Tt["./components/bases.js"][n];var nt=kt("controlElement");async function Bt({document:n,image:t,sourceWidth:e,sourceHeight:i,width:s,height:r,outputWidth:o,outputHeight:a,x:l,y:m,zoom:c,rotate:d,type:g,quality:x}){if([e,i,s,r,o,a].some(p=>!Number.isSafeInteger(p)||p<=0))throw new TypeError("Crop dimensions must be positive safe integers");if(BigInt(o)*BigInt(r)!==BigInt(a)*BigInt(s))throw new RangeError("Crop output must preserve the viewport aspect ratio");if(![l,m,c,d].every(Number.isFinite)||c<=0)throw new TypeError("Invalid image transform");if(typeof g!="string"||!g.startsWith("image/"))throw new TypeError("Crop output requires an image MIME type");if(x!==void 0&&(!Number.isFinite(x)||x<0||x>1))throw new RangeError("Crop quality must be between zero and one");let E=n.createElement("canvas");if(E.width=o,E.height=a,E.width!==o||E.height!==a)throw new RangeError("Crop output dimensions are unsupported");let I=E.getContext("2d");if(!I)throw new Error("Image crop canvas is unavailable");return I.scale(o/s,a/r),I.translate(s/2+l,r/2+m),I.rotate(d*Math.PI/180),I.scale(c,c),I.drawImage(t,-e/2,-i/2,e,i),await new Promise((p,f)=>{E.toBlob(B=>{if(!B){f(new Error("Image crop encoding failed"));return}if(B.type!==g){f(new Error(`Unsupported image format: ${g}`));return}p(B)},g,x)})}var O=class{#s;#h;#t;#i;#n;#e;#r;#c;#d=0;#l=!1;#a=!1;constructor({state:t,document:e,original:i,image:s,sourceWidth:r,sourceHeight:o,width:a,height:l,x:m=0,y:c=0,zoom:d=1,rotate:g=0}){let x={x:m,y:c,zoom:d,rotate:g};if(this.#m(x),!i||!s)throw new TypeError("An original and decoded image are required");this.#s=e,this.#h=i,this.#t=s,this.#i=r,this.#n=o,this.#e=a,this.#r=l,this.#c=t,t.setItem("initial",x),t.setItem("transform",{...x})}#m({x:t,y:e,zoom:i,rotate:s}){if(![t,e,i,s].every(Number.isFinite)||i<=0)throw new TypeError("Invalid image transform")}#o(){if(this.#l)throw new Error("Image editing session is closed")}get original(){return this.#h}get transform(){return{...this.#c.getItem("transform")}}setTransform(t){if(this.#o(),!t||Object.keys(t).sort().join(",")!=="rotate,x,y,zoom")throw new TypeError("Expected x, y, zoom and rotate");this.#m(t),this.#c.setItem("transform",{...t}),this.#d++}reset(){this.#o(),this.#c.setItem("transform",{...this.#c.getItem("initial")}),this.#d++}cancel(){this.#l=!0,this.#d++}async confirm({outputWidth:t,outputHeight:e,type:i,quality:s}){if(this.#o(),this.#a)throw new Error("Image crop is already being generated");let r=this.#d;this.#a=!0;try{let o=await Bt({document:this.#s,image:this.#t,sourceWidth:this.#i,sourceHeight:this.#n,width:this.#e,height:this.#r,outputWidth:t,outputHeight:e,...this.#c.getItem("transform"),type:i,quality:s});if(this.#l||this.#d!==r)throw new DOMException("Image edit cancelled or changed","AbortError");return this.#l=!0,o}finally{this.#a=!1}}};var V=class{#s;#h;#t;#i;#n;#e;#r;#c;#d;#l=!1;#a;#m;#o=new Map;#u;#p;constructor({state:t,document:e,original:i,image:s,sourceWidth:r,sourceHeight:o,width:a,height:l,x:m=0,y:c=0,zoom:d=1,rotate:g=0,outputWidth:x,outputHeight:T,type:E,quality:I}){this.#s=e,this.#h=s,this.#i={width:a,height:l,sourceWidth:r,sourceHeight:o,outputWidth:x,outputHeight:T,type:E,quality:I},this.#r=d/5,this.#c=d*5,this.#t=new O({state:t,document:e,original:i,image:s,sourceWidth:r,sourceHeight:o,width:a,height:l,x:m,y:c,zoom:d,rotate:g});let p=this.#n=e.createElement("dialog");p.setAttribute("aria-label","Edit image"),p.className="gramlot-image-crop-dialog";let f=e.createElement("style");f.textContent=`
3
+ ::slotted(*){min-width:0;max-width:100%}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",this.control=this.controlBox,this.control.id="control",this.control.append(this.ownerDocument.createElement("slot")),t.append(e,this.controlBox)}projectAttributes(t){return st(this,t)}}}N.parameters={};import{Bag as U}from"@gramlot/gramlot";import{sharedModules as vt}from"@gramlot/gramlot";var it=h=>vt["@genrojs/tytx"][h];var rt=it("fromTytx");var at=it("toTytx");import{sharedModules as Et}from"@gramlot/gramlot";var Ct=h=>Et["./random-id.js"][h],ot=Ct("randomId");function P(h,t){if(t===null)return{};let e=h.getRelativeData(t);if(!(e instanceof U))throw new TypeError("uploader contextPath must resolve to a Bag");return e.asDict(!1,!1,!0)}var A=class{#i=new Map;#e=new Map;#s=new Map;#c=new Set;#t=!1;constructor({gramlot:t,window:e,data:s,path:i,operation:a,onComplete:o,onChange:r,getContext:n}){if(!(s instanceof U))throw new TypeError("uploader requires the Data root Bag");if(typeof i!="string"||!i)throw new TypeError(`uploader requires a Data path: ${i}`);Object.assign(this,{gramlot:t,window:e,data:s,path:i,operation:a,onComplete:o,onChange:r,getContext:n})}get store(){let t=this.data.getItem(this.path,null,!0);if(!(t instanceof U))throw new TypeError("uploader storepath must resolve to a Bag");return t}add(t){if(this.#t)throw new Error("Uploader is closed");let e=`f_${ot().replaceAll("-","")}`;return this.#i.set(e,t),this.store.setItem(e,new U({name:t.name,size:t.size,mediaType:t.type||"",metadata:new U,status:"queued",loaded:0,result:null,error:null})),this.onChange(),e}#r(t,e){if(this.#t)return;let s=this.store.getItem(t);if(s){for(let[i,a]of Object.entries(e))s.setItem(i,a);this.#t||this.onChange()}}async start(t){if(this.#t||this.#e.has(t))return;let e=this.#i.get(t),s=this.store.getItem(t);if(!e||!s||s.getItem("status")!=="queued")return;if(!this.gramlot.capabilities.includes("upload")){this.#r(t,{status:"failed",error:"Upload is unavailable in this environment"});return}let i={xhr:null,controller:new AbortController,transferId:null,cancelled:!1};this.#e.set(t,i),this.#r(t,{status:"preparing",error:null});try{let a=await this.gramlot.rpc.call("upload","prepare",{operation:this.operation,metadata:{name:e.name,size:e.size,mediaType:e.type||"",fields:s.getItem("metadata").asDict(!1,!1,!0),context:this.getContext()}});if(i.transferId=a.transferId,this.#s.set(t,a.transferId),i.cancelled||this.#t){let r=await this.gramlot.rpc.call("upload","cancel",{transferId:i.transferId});await this.#u(t,r,!0);return}this.#r(t,{status:"uploading"});let o=await this.#d(e,i,a.authorization,t);await this.#u(t,o,i.cancelled)}catch(a){if(i.transferId)try{let o=await this.gramlot.rpc.call("upload",i.cancelled?"cancel":"status",{transferId:i.transferId});await this.#u(t,o,i.cancelled)}catch(o){this.#r(t,{status:"uncertain",error:o.message})}else this.#r(t,{status:i.cancelled?"cancelled":"failed",error:a.message})}finally{this.#e.delete(t)}}#d(t,e,s,i){return this.gramlot.uploadUrl?new Promise((a,o)=>{let r=e.xhr=new this.window.XMLHttpRequest;r.open("POST",this.gramlot.uploadUrl,!0),r.setRequestHeader("Content-Type","application/octet-stream"),r.setRequestHeader("X-Gramlot-Page-Id",this.gramlot.pageId),r.setRequestHeader("X-Gramlot-Transfer-Id",e.transferId),r.setRequestHeader("X-Gramlot-Upload-Token",s),r.upload.addEventListener("progress",n=>this.#r(i,{loaded:n.loaded})),r.addEventListener("load",()=>{if(r.status!==200){o(new Error(`Upload HTTP ${r.status}`));return}try{a(rt(r.responseText))}catch(n){o(n)}},{once:!0}),r.addEventListener("error",()=>o(new Error("Upload connection failed")),{once:!0}),r.addEventListener("abort",()=>o(new Error("Upload cancelled")),{once:!0}),r.send(t)}):this.gramlot.rpc.transport.upload({pageId:this.gramlot.pageId,transferId:e.transferId,authorization:s,file:t},a=>this.#r(i,{loaded:a}),e.controller.signal)}async#u(t,e,s=!1){if(e.state==="completed"){if(this.#r(t,{status:"completed",result:e.result,error:null}),this.#i.delete(t),this.#s.delete(t),!this.#t&&this.onComplete)try{await this.onComplete(this.store.getNode(t),e.result)}catch(i){this.#r(t,{error:`Completion callback: ${i.message}`})}}else e.state==="unsaved"?(this.#s.delete(t),this.#r(t,{status:s?"cancelled":"failed",error:s?null:"Transfer was not saved"})):this.#r(t,{status:"uncertain",error:"Upload outcome is not yet known"})}localFile(t){return this.#i.get(t)??null}remove(t){let e=this.store.getItem(t);return!e||this.#e.has(t)||!["queued","completed","failed","cancelled"].includes(e.getItem("status"))?!1:(this.#i.delete(t),this.#s.delete(t),this.store.popNode(t),this.#t||this.onChange(),!0)}async reconcile(t){let e=this.#s.get(t);if(!(!e||this.#t||this.#e.has(t)||this.#c.has(t))){this.#c.add(t);try{let s=await this.gramlot.rpc.call("upload","status",{transferId:e});await this.#u(t,s)}catch(s){this.#r(t,{status:"uncertain",error:s.message})}finally{this.#c.delete(t)}}}retry(t){let e=this.store.getItem(t);!e||!this.#i.has(t)||!["failed","cancelled"].includes(e.getItem("status"))||this.#r(t,{status:"queued",loaded:0,error:null})}cancel(t){let e=this.#e.get(t);e&&(e.cancelled=!0,e.controller.abort(),e.xhr?.abort())}dispose(){this.#t=!0;for(let t of this.#e.keys())this.cancel(t);this.#i.clear()}};var nt=(0,y.defineComponent)({name:"uploader",tag:"gramlot-uploader",base:N,sourceContext:!0,parameters:{operation:{dtype:"T"},storepath:{dtype:"T"},contextPath:{dtype:"T",nullable:!0,default:null},accept:{dtype:"T",default:"",binding:"read"},multiple:{dtype:"B",default:!1,binding:"read"},autoUpload:{dtype:"B",default:!0,binding:"read"},manualUpload:{dtype:"B",default:!0,binding:"read"},disabled:{dtype:"B",default:!1,binding:"read"},selectedPath:{dtype:"T",nullable:!0,default:null,binding:"twoWay"},onComplete:{dtype:"T",nullable:!0,default:null}},implementation:h=>class extends h{#i;#e;#s=!1;#c=null;#t=null;#r;#d=null;constructor(){super(),this.control.replaceChildren();let t=this.ownerDocument,e=t.createElement("style");e.textContent=":host{display:block} .drop{border:1px dashed currentColor;padding:1em;display:grid;gap:.5em} ul{padding-inline-start:1.2em} button,input{font:inherit}",this.drop=t.createElement("div"),this.drop.className="drop";let s=t.createElement("label");s.textContent="Choose files or drop them here ",this.input=t.createElement("input"),this.input.type="file",s.append(this.input),this.startButton=t.createElement("button"),this.startButton.type="button",this.startButton.textContent="Upload",this.message=t.createElement("div"),this.message.setAttribute("role","status"),this.summary=t.createElement("div"),this.summary.setAttribute("aria-label","Upload summary"),this.summary.setAttribute("aria-live","polite"),this.list=t.createElement("ul"),this.preview=t.createElement("div"),this.preview.setAttribute("aria-label","File preview"),this.drop.append(s,this.startButton,this.message,this.summary,this.list,this.preview),this.control.append(this.drop),this.shadowRoot.append(e),this.input.addEventListener("change",()=>{this.#a(this.input.files),this.input.value=""}),this.startButton.addEventListener("click",()=>{this.parameters.manualUpload&&!this.parameters.autoUpload&&this.#l()}),this.drop.addEventListener("dragover",i=>{!this.parameters?.disabled&&[...i.dataTransfer.types].includes("Files")&&(i.preventDefault(),i.stopPropagation(),i.dataTransfer.dropEffect="copy")}),this.drop.addEventListener("drop",i=>{!this.parameters?.disabled&&[...i.dataTransfer.types].includes("Files")&&(i.preventDefault(),i.stopPropagation(),this.#a(i.dataTransfer.files))})}setSourceContext(t){this.#i=t}#u(){let t=this.#i.getStaticData(this.#i.attrDatapath("storepath"));if(!(t instanceof It))throw new TypeError("uploader storepath must resolve to a Bag");return t}projectAttributes(t,e){this.#e&&this.#e.path!==this.#i.attrDatapath("storepath")&&(this.#o(),this.#e.dispose(),this.#e=null,this.#d=null,this.#r=null,this.#i.writeParameter("selectedPath",null));let s=!!(this.parameters?.autoUpload&&!this.parameters.disabled),i=super.projectAttributes(t,e);return this.input.accept=this.parameters.accept||"",this.input.multiple=!!this.parameters.multiple,this.input.disabled=!!this.parameters.disabled,this.startButton.disabled=!!this.parameters.disabled,this.startButton.hidden=!!(this.parameters.autoUpload||!this.parameters.manualUpload),this.parameters.selectedPath!==this.#r&&(this.#r=this.parameters.selectedPath,this.#d=this.parameters.selectedPath),this.#g(),this.#e&&(this.#e.operation=this.parameters.operation),this.#m(),!s&&this.parameters.autoUpload&&!this.parameters.disabled&&this.#e&&this.ownerDocument.defaultView.queueMicrotask(()=>{this.isConnected&&this.parameters.autoUpload&&!this.parameters.disabled&&this.#l()}),i}#g(){if(!this.#e&&this.#i&&this.parameters){let{gramlot:t,window:e}=this.#i.upload();this.#e=new A({gramlot:t,window:e,data:this.#i.sourceNode.data,path:this.#i.attrDatapath("storepath"),operation:this.parameters.operation,onChange:()=>this.#m(),getContext:()=>P(this.#i.sourceNode,this.parameters.contextPath),onComplete:(s,i)=>this.parameters.onComplete?this.#i.callLogic(this.parameters.onComplete,{item:s,result:i}):null})}}connectedCallback(){this.#g()}disconnectedCallback(){this.ownerDocument.defaultView.queueMicrotask(()=>{this.isConnected||(this.#o(),this.#e?.dispose(),this.#e=null)})}#a(t){if(!this.#e||this.parameters.disabled)return;let e=[...t];if(!this.parameters.multiple&&e.length>1){this.message.textContent="Select one file";return}let s=(this.parameters.accept||"").split(",").map(i=>i.trim().toLowerCase()).filter(Boolean);for(let i of e){let a=i.name.toLowerCase(),o=(i.type||"").toLowerCase();if(s.length&&!s.some(r=>r.startsWith(".")?a.endsWith(r):r.endsWith("/*")?o.startsWith(r.slice(0,-1)):o===r)){this.message.textContent=`${i.name}: file type is not accepted`;continue}this.#e.add(i)}this.parameters.autoUpload&&this.#l()}async#l(){if(!this.#e||this.parameters.disabled||this.#s)return;this.#s=!0;let t=this.#e;try{for(;!this.parameters.disabled&&this.#e===t;){let e=t.store.getNodes().find(s=>s.value.getItem("status")==="queued");if(!e)break;await t.start(e.label)}}finally{this.#s=!1}}#n(t){this.#d=t,this.#r=t,this.#i.writeParameter("selectedPath",t),this.#m()}#o(){this.#c&&this.ownerDocument.defaultView.URL.revokeObjectURL(this.#c),this.#c=null,this.#t=null,this.preview?.replaceChildren()}async#h(t,e){this.#o(),this.#t=t;let s=(e.type||"").toLowerCase();if(["image/png","image/jpeg","image/gif","image/webp"].includes(s)){this.#c=this.ownerDocument.defaultView.URL.createObjectURL(e);let i=this.ownerDocument.createElement("img");i.src=this.#c,i.alt=e.name,i.style.maxWidth="100%",i.style.maxHeight="200px",this.preview.append(i);return}if((s.startsWith("text/")||e.name.toLowerCase().endsWith(".grmlt"))&&e.size<=1048576){try{let i=await e.text();if(this.#t!==t||!this.isConnected)return;let a=this.ownerDocument.createElement("pre");a.textContent=i,a.style.maxHeight="200px",a.style.overflow="auto",this.preview.append(a)}catch(i){this.#t===t&&(this.preview.textContent=`Preview failed: ${i.message}`)}return}this.preview.textContent="No preview available"}#m(){if(!this.list||!this.#i)return;let t=this.#u().getNodes();this.list.replaceChildren();let e=new Map,s=0,i=0;for(let a of t){let o=a.value,r=o.getItem("status");e.set(r,(e.get(r)??0)+1),s+=o.getItem("loaded"),i+=o.getItem("size")}this.summary.textContent=`${t.length} file${t.length===1?"":"s"} \u2014 ${s}/${i} bytes`+[...e].map(([a,o])=>` \xB7 ${o} ${a}`).join("");for(let a of t){let o=a.value,r=a.label,n=this.ownerDocument.createElement("li"),d=this.ownerDocument.createElement("button");d.type="button",d.textContent=o.getItem("name"),d.disabled=!!this.parameters.disabled,d.setAttribute("aria-pressed",String(r===this.#d)),d.setAttribute("aria-label",`Select ${o.getItem("name")}`),d.addEventListener("click",()=>{this.#n(r);let l=this.#u().getNodes().findIndex(p=>p.label===r);l>=0&&this.list.children[l].firstElementChild.focus()}),n.append(d,this.ownerDocument.createTextNode(` \u2014 ${o.getItem("status")} (${o.getItem("loaded")}/${o.getItem("size")}) `));let b=o.getItem("status");if(["preparing","uploading"].includes(b)){let l=this.ownerDocument.createElement("button");l.textContent="Cancel",l.type="button",l.addEventListener("click",()=>this.#e.cancel(r)),n.append(l)}else if(["failed","cancelled"].includes(b)){let l=this.ownerDocument.createElement("button");l.textContent="Retry",l.type="button",l.disabled=!!this.parameters.disabled,l.addEventListener("click",()=>{this.#e.retry(r),this.parameters.autoUpload&&this.#l()}),n.append(l)}if(b==="uncertain"){let l=this.ownerDocument.createElement("button");l.textContent="Check status",l.type="button",l.addEventListener("click",()=>{this.#e.reconcile(r)}),n.append(l)}if(["queued","completed","failed","cancelled"].includes(b)){let l=this.#e?.localFile(r);if(l){let f=this.ownerDocument.createElement("button");f.textContent="Preview",f.type="button",f.addEventListener("click",()=>{this.#h(r,l)}),n.append(f)}let p=this.ownerDocument.createElement("button");p.textContent="Remove",p.type="button",p.disabled=!!this.parameters.disabled,p.addEventListener("click",()=>{this.#e.remove(r)&&(this.#t===r&&this.#o(),this.#d===r&&this.#n(null))}),n.append(p)}o.getItem("error")&&n.append(this.ownerDocument.createTextNode(` ${o.getItem("error")}`)),this.list.append(n)}}}});import{sharedModules as Tt}from"@gramlot/gramlot";var kt=h=>Tt["./components/bases.js"][h];var lt=kt("controlElement");async function Dt({document:h,image:t,sourceWidth:e,sourceHeight:s,width:i,height:a,outputWidth:o,outputHeight:r,x:n,y:d,zoom:b,rotate:l,type:p,quality:f}){if([e,s,i,a,o,r].some(m=>!Number.isSafeInteger(m)||m<=0))throw new TypeError("Crop dimensions must be positive safe integers");if(BigInt(o)*BigInt(a)!==BigInt(r)*BigInt(i))throw new RangeError("Crop output must preserve the viewport aspect ratio");if(![n,d,b,l].every(Number.isFinite)||b<=0)throw new TypeError("Invalid image transform");if(typeof p!="string"||!p.startsWith("image/"))throw new TypeError("Crop output requires an image MIME type");if(f!==void 0&&(!Number.isFinite(f)||f<0||f>1))throw new RangeError("Crop quality must be between zero and one");let C=h.createElement("canvas");if(C.width=o,C.height=r,C.width!==o||C.height!==r)throw new RangeError("Crop output dimensions are unsupported");let T=C.getContext("2d");if(!T)throw new Error("Image crop canvas is unavailable");return T.scale(o/i,r/a),T.translate(i/2+n,a/2+d),T.rotate(l*Math.PI/180),T.scale(b,b),T.drawImage(t,-e/2,-s/2,e,s),await new Promise((m,u)=>{C.toBlob(B=>{if(!B){u(new Error("Image crop encoding failed"));return}if(B.type!==p){u(new Error(`Unsupported image format: ${p}`));return}m(B)},p,f)})}var q=class{#i;#e;#s;#c;#t;#r;#d;#u;#g;#a=0;#l=!1;#n=!1;constructor({data:t,path:e,document:s,original:i,image:a,sourceWidth:o,sourceHeight:r,width:n,height:d,x:b=0,y:l=0,zoom:p=1,rotate:f=0}){let v={x:b,y:l,zoom:p,rotate:f};if(this.#m(v),!i||!a)throw new TypeError("An original and decoded image are required");if(this.#i=s,this.#e=i,this.#s=a,this.#c=o,this.#t=r,this.#r=n,this.#d=d,typeof e!="string"||!e)throw new TypeError(`An image editing session requires a Data path: ${e}`);this.#u=t,this.#g=e,this.#h("initial",v),this.#h("transform",{...v})}#o(t){return this.#u.getItem(`${this.#g}.${t}`,null,!0)}#h(t,e){this.#u.setItem(`${this.#g}.${t}`,e)}#m({x:t,y:e,zoom:s,rotate:i}){if(![t,e,s,i].every(Number.isFinite)||s<=0)throw new TypeError("Invalid image transform")}#f(){if(this.#l)throw new Error("Image editing session is closed")}get original(){return this.#e}get transform(){return{...this.#o("transform")}}setTransform(t){if(this.#f(),!t||Object.keys(t).sort().join(",")!=="rotate,x,y,zoom")throw new TypeError("Expected x, y, zoom and rotate");this.#m(t),this.#h("transform",{...t}),this.#a++}reset(){this.#f(),this.#h("transform",{...this.#o("initial")}),this.#a++}cancel(){this.#l=!0,this.#a++}async confirm({outputWidth:t,outputHeight:e,type:s,quality:i}){if(this.#f(),this.#n)throw new Error("Image crop is already being generated");let a=this.#a;this.#n=!0;try{let o=await Dt({document:this.#i,image:this.#s,sourceWidth:this.#c,sourceHeight:this.#t,width:this.#r,height:this.#d,outputWidth:t,outputHeight:e,...this.#o("transform"),type:s,quality:i});if(this.#l||this.#a!==a)throw new DOMException("Image edit cancelled or changed","AbortError");return this.#l=!0,o}finally{this.#n=!1}}};var V=class{#i;#e;#s;#c;#t;#r;#d;#u;#g;#a=!1;#l;#n;#o=new Map;#h;#m;constructor({data:t,path:e,document:s,original:i,image:a,sourceWidth:o,sourceHeight:r,width:n,height:d,x:b=0,y:l=0,zoom:p=1,rotate:f=0,outputWidth:v,outputHeight:C,type:T,quality:m}){this.#i=s,this.#e=a,this.#c={width:n,height:d,sourceWidth:o,sourceHeight:r,outputWidth:v,outputHeight:C,type:T,quality:m},this.#d=p/5,this.#u=p*5,this.#s=new q({data:t,path:e,document:s,original:i,image:a,sourceWidth:o,sourceHeight:r,width:n,height:d,x:b,y:l,zoom:p,rotate:f});let u=this.#t=s.createElement("dialog");u.setAttribute("aria-label","Edit image"),u.className="gramlot-image-crop-dialog";let B=s.createElement("style");B.textContent=`
4
4
  .gramlot-image-crop-dialog{box-sizing:border-box;width:min(100% - 2rem, 510px);max-width:calc(100vw - 2rem);max-height:calc(100vh - 2rem);
5
5
  border:1px solid var(--gramlot-border,#d5dde6);border-radius:18px;padding:0;
6
6
  color:var(--gramlot-ink,#202a35);background:var(--gramlot-surface,#fff);
@@ -37,4 +37,4 @@ var et=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var gt=Objec
37
37
  @media(max-width:380px){.gramlot-image-crop-dialog{width:calc(100vw - 8px);max-width:calc(100vw - 8px)}
38
38
  .gramlot-image-crop-dialog .crop-heading,.gramlot-image-crop-dialog .crop-body{padding-left:8px;padding-right:8px}
39
39
  .gramlot-image-crop-dialog .crop-actions{padding:12px 8px}}
40
- `;let B=e.createElement("header");B.className="crop-heading";let J=e.createElement("h2");J.textContent="Edit image";let W=e.createElement("p");W.className="crop-subtitle",W.textContent="Move and adjust the image within the frame.",B.append(J,W);let b=this.#m=e.createElement("div");b.setAttribute("aria-label","Crop preview"),b.setAttribute("role","group"),b.tabIndex=0,b.setAttribute("aria-description","Use arrow keys to move the image. Use the adjacent controls to zoom or rotate."),Object.assign(b.style,{position:"relative",overflow:"hidden",width:`${a}px`,height:`${l}px`,maxWidth:"none",background:"#ddd",margin:"auto",touchAction:"none",userSelect:"none",cursor:"grab"}),this.#e=e.createElement("img"),this.#e.src=s.src,this.#e.alt="",this.#e.draggable=!1,Object.assign(this.#e.style,{position:"absolute",left:"50%",top:"50%",maxWidth:"none",width:`${r}px`,height:`${o}px`,transformOrigin:"center center"}),b.append(this.#e);let Q=(h,v,C)=>{let y=e.createElement("button");return y.type="button",y.className=`crop-handle crop-${h}-handle`,y.dataset.cropHandle=h,y.setAttribute("aria-label",v),y.title=v,y.textContent=C,y},H=Q("rotate","Rotate image","\u21BB"),K=Q("zoom","Zoom image","\u2198"),F=e.createElement("div");F.className="crop-viewport",F.append(b);let U=e.createElement("div");U.className="crop-position",U.style.width=`${a+42}px`;let _=e.createElement("div");_.className="crop-handles",_.append(H,K),U.append(F,_);let G=e.createElement("p");G.className="crop-help",G.textContent="Drag to move \xB7 pinch to zoom";let z=e.createElement("div");z.className="crop-body",z.append(U);let R=e.createElement("div");R.setAttribute("role","alert");let X=e.createElement("div");X.className="crop-actions";let $=e.createElement("button");$.type="button",$.textContent="Reset";let j=e.createElement("button");j.type="button",j.textContent="Cancel";let L=e.createElement("button");L.type="button",L.textContent="Confirm",L.className="primary";let Y=e.createElement("div");Y.className="crop-action-buttons",Y.append($,j,L),X.append(G,Y),z.append(R),p.append(f,B,z,X),this.#a=new e.defaultView.AbortController;let u={signal:this.#a.signal};b.addEventListener("pointerdown",h=>this.#w(h),u);for(let h of[H,K])h.addEventListener("pointerdown",v=>this.#w(v),u);b.addEventListener("pointermove",h=>this.#E(h),u),b.addEventListener("pointerup",h=>this.#I(h),u);for(let h of["pointercancel","lostpointercapture"])b.addEventListener(h,v=>{this.#o.has(v.pointerId)&&this.#f()},u);b.addEventListener("dragstart",h=>h.preventDefault(),u),b.addEventListener("wheel",h=>this.#C(h),{...u,passive:!1}),b.addEventListener("gesturestart",h=>this.#k(h),{...u,passive:!1}),b.addEventListener("gesturechange",h=>this.#b(h),{...u,passive:!1}),b.addEventListener("gestureend",h=>this.#T(h),{...u,passive:!1}),e.defaultView.addEventListener("blur",()=>this.#f(),u),e.addEventListener("visibilitychange",()=>{e.hidden&&this.#f()},u),b.addEventListener("keydown",h=>{let v={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[h.key];if(!v)return;h.preventDefault(),this.#f();let C=this.#t.transform,y=h.shiftKey?10:1;C.x+=v[0]*y,C.y+=v[1]*y,this.#t.setTransform(C),this.#y()},u);for(let[h,v]of[[H,"rotate"],[K,"zoom"]])h.addEventListener("keydown",C=>{if(!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(C.key))return;C.preventDefault(),this.#f();let y=C.key==="ArrowUp"||C.key==="ArrowRight",D=this.#t.transform;v==="rotate"?D.rotate+=y?5:-5:D.zoom=this.#g(D.zoom*(y?1.05:1/1.05)),this.#t.setTransform(D),this.#y()},u);$.addEventListener("click",()=>{this.#f(),this.#t.reset(),this.#y()},u),j.addEventListener("click",()=>this.cancel(),u),p.addEventListener("cancel",h=>{h.preventDefault(),this.cancel()},u),p.addEventListener("close",()=>{this.#l||this.cancel()},u),L.addEventListener("click",async()=>{this.#f(),L.disabled=!0,R.textContent="";try{let h=this.#t.transform,{outputWidth:v,outputHeight:C,type:y,quality:D}=this.#i,mt=await this.#t.confirm({outputWidth:v,outputHeight:C,type:y,quality:D});this.#B({blob:mt,transform:h})}catch(h){this.#l||(R.textContent=h.message,L.disabled=!1)}},u),this.#y()}#v(){let[t,e]=this.#o.values();return e?{x:(t.x+e.x)/2,y:(t.y+e.y)/2,distance:Math.hypot(e.x-t.x,e.y-t.y),angle:Math.atan2(e.y-t.y,e.x-t.x)}:{x:t.x,y:t.y,distance:0,angle:0}}#x(t="move"){let e=this.#v();if(this.#o.size===2&&e.distance===0){this.#f();return}let i=this.#m.getBoundingClientRect(),s={x:i.left+i.width/2,y:i.top+i.height/2},r=Math.atan2(e.y-s.y,e.x-s.x),o=Math.hypot(e.x-s.x,e.y-s.y);this.#u={base:this.#t.transform,geometry:e,mode:t,center:s,distance:o,lastAngle:e.angle,handleAngle:r,rotation:0}}#w(t){if(t.button!==0||this.#l||this.#p||this.#o.size&&(t.pointerType!=="touch"||[...this.#o.values()].some(s=>s.type!=="touch")))return;if(this.#o.size===2){this.#f();return}let e=t.target.closest("[data-crop-handle]")?.dataset.cropHandle,i=e?`handle-${e}`:t.pointerType==="touch"?"move":t.shiftKey&&!t.altKey&&!t.ctrlKey&&!t.metaKey?"zoom":t.altKey&&!t.shiftKey&&!t.ctrlKey&&!t.metaKey?"rotate":!t.shiftKey&&!t.altKey&&!t.ctrlKey&&!t.metaKey?"move":null;i&&(t.preventDefault(),this.#o.set(t.pointerId,{x:t.clientX,y:t.clientY,type:t.pointerType}),this.#m.setPointerCapture(t.pointerId),this.#m.style.cursor="grabbing",this.#x(i))}#E(t){let e=this.#o.get(t.pointerId);if(!e||!this.#u)return;t.preventDefault(),e.x=t.clientX,e.y=t.clientY;let i=this.#v(),s=this.#u,r=i.x-s.geometry.x,o=i.y-s.geometry.y,a={...s.base};if(this.#o.size===2){if(a.x+=r,a.y+=o,i.distance>0){let l=i.angle-s.lastAngle;s.rotation+=Math.atan2(Math.sin(l),Math.cos(l))*180/Math.PI,s.lastAngle=i.angle}a.rotate+=s.rotation,a.zoom=s.base.zoom*i.distance/s.geometry.distance}else if(s.mode==="handle-zoom"){let l=Math.hypot(i.x-s.center.x,i.y-s.center.y);s.distance>0&&(a.zoom=s.base.zoom*l/s.distance)}else if(s.mode==="handle-rotate"){let l=Math.atan2(i.y-s.center.y,i.x-s.center.x),m=l-s.handleAngle;s.rotation+=Math.atan2(Math.sin(m),Math.cos(m))*180/Math.PI,s.handleAngle=l,a.rotate+=s.rotation}else s.mode==="zoom"?a.zoom=s.base.zoom*Math.exp(o/100):s.mode==="rotate"?a.rotate-=o:(a.x+=r,a.y+=o);a.zoom=this.#g(a.zoom),this.#t.setTransform(a),this.#y()}#I(t){this.#o.has(t.pointerId)&&(this.#E(t),this.#o.delete(t.pointerId),this.#m.hasPointerCapture(t.pointerId)&&this.#m.releasePointerCapture(t.pointerId),this.#o.size?this.#x():this.#f())}#f(){let t=[...this.#o.keys()];this.#o.clear(),this.#u=null,this.#p=null;for(let e of t)this.#m.hasPointerCapture(e)&&this.#m.releasePointerCapture(e);this.#m&&(this.#m.style.cursor="grab")}#g(t){return Math.max(this.#r,Math.min(this.#c,t))}#C(t){if(this.#l||this.#o.size||!t.ctrlKey&&!t.altKey||(t.preventDefault(),this.#p))return;let e=t.deltaMode===1?16:t.deltaMode===2?this.#i.height:1,i=this.#t.transform;t.ctrlKey?i.zoom=this.#g(i.zoom*Math.exp(-t.deltaY*e/100)):i.rotate-=t.deltaY*e/4,this.#t.setTransform(i),this.#y()}#k(t){this.#l||this.#o.size||(t.preventDefault(),this.#p=this.#t.transform)}#b(t){if(!this.#p||this.#l||(t.preventDefault(),!Number.isFinite(t.scale)||t.scale<=0||!Number.isFinite(t.rotation)))return;let e={...this.#p};e.zoom=this.#g(e.zoom*t.scale),e.rotate+=t.rotation,this.#t.setTransform(e),this.#y()}#T(t){this.#p&&(t.preventDefault(),this.#p=null)}#y(){let{x:t,y:e,zoom:i,rotate:s}=this.#t.transform;this.#e.style.transform=`translate(-50%, -50%) translate(${t}px, ${e}px) rotate(${s}deg) scale(${i})`}open(){if(this.#d||this.#l)throw new Error("Image crop dialog has already opened");return new Promise((t,e)=>{this.#d=t,this.#s.body.append(this.#n);try{this.#n.showModal()}catch(i){this.#l=!0,this.#a.abort(),this.#n.remove(),e(i)}})}cancel(){if(!this.#l){if(this.#f(),this.#t.cancel(),!this.#d){this.#l=!0,this.#a.abort();return}this.#B(null)}}#B(t){this.#l||(this.#l=!0,this.#f(),this.#a.abort(),this.#n.open&&this.#n.close(),this.#n.remove(),this.#d(t))}};import{sharedModules as Lt}from"@gramlot/gramlot";var Dt=n=>Lt["./media-frame.js"][n],lt=Dt("captureVideoFrame");function ht({document:n,signal:t}){if(t.aborted)return Promise.reject(new DOMException("Screen capture cancelled","AbortError"));let e=n.defaultView,i;try{i=e.navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1})}catch(s){return Promise.reject(s)}return new Promise((s,r)=>{let o=!1,a=null,l=!1,m=new e.AbortController,c={signal:m.signal},d=n.createElement("video");d.muted=!0,d.autoplay=!0,d.playsInline=!0,Object.assign(d.style,{position:"fixed",width:"1px",height:"1px",opacity:"0",pointerEvents:"none"});let g=p=>{for(let f of p.getTracks())f.stop()},x=()=>{a&&(g(a),a=null),d.srcObject=null,d.remove()},T=(p,f)=>{o||(o=!0,m.abort(),t.removeEventListener("abort",E),x(),p?r(p):s(f))},E=()=>T(new DOMException("Screen capture cancelled","AbortError"));t.addEventListener("abort",E,{once:!0});let I=()=>{if(!(o||l||d.readyState<2||!d.videoWidth||!d.videoHeight)){l=!0;try{let p=lt(n,d);x(),p.toBlob(f=>{!f||f.type!=="image/png"?T(new Error("Screen image encoding failed")):T(null,f)},"image/png")}catch(p){T(p)}}};d.addEventListener("loadeddata",I,c),t.aborted&&E(),i.then(async p=>{if(o){g(p);return}a=p;for(let f of a.getTracks())f.addEventListener("ended",()=>{l||T(new Error("Screen sharing ended"))},c);n.body.append(d),d.srcObject=a;try{await d.play(),I()}catch(f){l||T(f)}},p=>T(p))})}var dt=(0,w.defineComponent)({name:"imageUploader",tag:"gramlot-image-uploader",base:nt,sourceContext:!0,bagStore:!0,parameters:{value:{dtype:"T",nullable:!0,default:null,binding:"twoWay"},storepath:{dtype:"T"},contextPath:{dtype:"T",nullable:!0,default:null},operation:{dtype:"T",nullable:!0,default:null},cropWidth:{dtype:"L",default:256},cropHeight:{dtype:"L",default:256},outputWidth:{dtype:"L",default:512},outputHeight:{dtype:"L",default:512},disabled:{dtype:"B",default:!1,binding:"read"},onComplete:{dtype:"T",nullable:!0,default:null}},implementation:n=>class extends n{#s;#h;#t;#i;#n;#e;#r=0;#c;#d;#l;#a=null;#m=!1;#o=!1;#u;#p=null;constructor(){super();let t=this.ownerDocument;this.control=t.createElement("div"),this.controlBox.append(this.control);let e=t.createElement("style");e.textContent=":host{display:block} .image-uploader{display:grid;gap:.5em;justify-items:start} img{max-width:100%;max-height:240px} .actions{display:flex;gap:.5em;flex-wrap:wrap} button{font:inherit} .image-uploader[data-drag-over]{outline:2px dashed var(--gramlot-action,#3766b5);outline-offset:4px}";let i=t.createElement("div");i.className="image-uploader",this.preview=t.createElement("img"),this.preview.alt="Selected image",this.input=t.createElement("input"),this.input.type="file",this.input.accept="image/png,image/jpeg,image/webp",this.input.hidden=!0;let s=t.createElement("div");s.className="actions";let r=o=>{let a=t.createElement("button");return a.type="button",a.textContent=o,s.append(a),a};this.chooseButton=r("Choose image"),this.cameraButton=r("Take photo"),this.screenButton=r("Capture screen"),this.editButton=r("Edit"),this.clearButton=r("Clear"),this.cancelScreenButton=r("Cancel capture"),this.cancelButton=r("Cancel upload"),this.checkButton=r("Check status"),this.message=t.createElement("div"),this.message.setAttribute("role","status"),i.append(this.preview,this.input,s,this.message),this.control.append(i),this.shadowRoot.append(e),this.chooseButton.addEventListener("click",()=>this.input.click()),i.addEventListener("dragover",o=>{!this.parameters?.disabled&&!this.#e&&this.#a===null&&!this.#p&&[...o.dataTransfer.types].includes("Files")&&(o.preventDefault(),o.stopPropagation(),o.dataTransfer.dropEffect="copy",i.setAttribute("data-drag-over",""))}),i.addEventListener("dragleave",()=>i.removeAttribute("data-drag-over")),i.addEventListener("drop",o=>{if(i.removeAttribute("data-drag-over"),this.parameters?.disabled||this.#e||this.#a!==null||this.#p||![...o.dataTransfer.types].includes("Files"))return;o.preventDefault(),o.stopPropagation();let a=[...o.dataTransfer.files];if(a.length!==1){this.message.textContent="Select one image";return}this.#y(a[0])}),this.cameraButton.addEventListener("click",()=>this.#w()),this.screenButton.addEventListener("click",()=>this.#E()),this.cancelScreenButton.addEventListener("click",()=>this.#p?.abort()),this.input.addEventListener("change",o=>{o.stopPropagation();let a=this.input.files[0];this.input.value="",a&&this.#y(a)}),this.editButton.addEventListener("click",()=>{this.#B()}),this.clearButton.addEventListener("click",()=>{this.#C(),this.#k(null)}),this.cancelButton.addEventListener("click",()=>{this.#e&&this.#t.cancel(this.#e.id)}),this.checkButton.addEventListener("click",()=>{this.#M()})}setSourceContext(t){this.#s=t,t.sourceNode.imageCropState||Object.defineProperty(t.sourceNode,"imageCropState",{value:new ct,configurable:!0})}readControlValue(){return this.parameters?.value??null}writeControlValue(t){this.parameters&&(this.parameters.value=t,this.#b())}setStoreBag(t){if(!(t instanceof ct))throw new TypeError("imageUploader storepath must resolve to a Bag");this.#h&&this.#h!==t&&(this.#C(),this.#t?.dispose(),this.#t=null),this.#h=t}projectAttributes(t,e){let i=super.projectAttributes(t,e),s=this.parameters;for(let r of["cropWidth","cropHeight","outputWidth","outputHeight"])if(!Number.isSafeInteger(s[r])||s[r]<=0)throw new RangeError(`${r} must be a positive integer`);if(s.cropWidth*s.outputHeight!==s.cropHeight*s.outputWidth)throw new RangeError("Crop and output aspect ratios must match");return this.#c!==void 0&&s.value!==this.#c&&s.value!==this.#d&&this.#C(),this.#c=s.value,this.#d=void 0,this.#f(),this.#t&&(this.#t.operation=s.operation),this.#b(),i}connectedCallback(){this.#f(),this.#v()}disconnectedCallback(){this.ownerDocument.defaultView.queueMicrotask(()=>{this.isConnected||(this.#l&&(this.#s.upload().gramlot.data.unsubscribe(this.#l,{any:!0}),this.#l=null),this.#C(),this.#t?.dispose(),this.#t=null)})}#v(){if(this.#l||!this.#s)return;let{gramlot:t}=this.#s.upload();this.#l=`image-uploader-camera-${A()}`,t.data.subscribe(this.#l,{any:e=>this.#x(e)}),this.#x()}#x(t=null){let{gramlot:e}=this.#s.upload(),i=!!(e.dvc.provider&&e.dvc.provider.capabilities.includes("camera")),s=e.data.getNode("_gramlot.device.camera"),r=s?.attr.status;if((i!==this.#o||r!==this.#u)&&(this.#o=i,this.#u=r,this.#b()),this.#a===null||t?.node!==s)return;if(r==="pending"){this.#m=!0;return}if(!this.#m||!["success","cancelled","denied","unavailable","error"].includes(r))return;let o=this.#a;this.#a=null,this.#m=!1,this.#b(),r==="success"?this.#I(s.staticValue.getItem("url"),o):r!=="cancelled"&&(this.message.textContent=s.attr.error?.message||"Camera is unavailable")}#w(){if(!(!this.#o||this.#u==="pending"||this.parameters.disabled||this.#e||this.#a!==null||this.#p)){this.#a=++this.#r,this.#m=!1;try{this.#s.sourceNode.FIRE("_gramlot.device.camera?capture")}catch(t){this.#a=null,this.message.textContent=`Camera failed: ${t.message}`,this.#b()}}}#E(){if(this.parameters.disabled||this.#e||this.#a!==null||this.#p||this.#n)return;let t=this.ownerDocument.defaultView,e=new t.AbortController,i=++this.#r;this.#p=e,this.message.textContent="",this.#b(),ht({document:this.ownerDocument,signal:e.signal}).then(r=>{if(i===this.#r)return this.#p=null,this.#b(),this.#y(new t.File([r],"screen.png",{type:"image/png"}))}).catch(r=>{i===this.#r&&(this.#p=null,this.#b(),r.name!=="AbortError"&&(this.message.textContent=r.name==="NotAllowedError"?"Screen capture was cancelled or not permitted":`Screen capture failed: ${r.message}`))})}async#I(t,e){try{let i=await this.#T(t);if(e!==this.#r){this.#g(i);return}await this.#L(i,e)}catch(i){e===this.#r&&(this.message.textContent=`Image failed: ${i.message}`)}}#f(){if(!this.#t&&this.#s&&this.#h&&this.parameters){let{gramlot:t,window:e}=this.#s.upload();this.#t=new P({gramlot:t,window:e,store:this.#h,operation:this.parameters.operation,onChange:()=>this.#b(),getContext:()=>M(this.#s.sourceNode,this.parameters.contextPath),onComplete:(i,s)=>this.#P(i,s)})}}#g(t){t?.objectUrl&&this.ownerDocument.defaultView.URL.revokeObjectURL(t.objectUrl)}#C(){this.#r++,this.#p?.abort(),this.#p=null,this.#a=null,this.#m=!1,this.#n?.cancel(),this.#n=null,this.#e&&(this.#t?.cancel(this.#e.id),this.#e.candidate!==this.#i&&this.#g(this.#e.candidate),this.#e=null),this.#g(this.#i),this.#i=null}#k(t){this.#d=t,this.#s.writeParameter("value",t)}#b(){if(!this.parameters)return;let t=this.parameters.value;t?(this.preview.src=t,this.preview.hidden=!1):(this.preview.removeAttribute("src"),this.preview.hidden=!0);let e=this.#e&&this.#h.getItem(this.#e.id)?.getItem("status"),i=!!(this.#e||this.#a!==null||this.#p);this.screenButton.hidden=!this.ownerDocument.defaultView.navigator.mediaDevices?.getDisplayMedia,this.screenButton.disabled=!!(this.parameters.disabled||i),this.cancelScreenButton.hidden=!this.#p,this.cameraButton.hidden=!this.#o,this.cameraButton.disabled=!!(this.parameters.disabled||i||this.#u==="pending"),this.chooseButton.disabled=this.editButton.disabled=this.clearButton.disabled=!!(this.parameters.disabled||i),this.editButton.disabled||=!t&&!this.#i,this.clearButton.disabled||=!t,this.cancelButton.hidden=!["preparing","uploading"].includes(e),this.checkButton.hidden=e!=="uncertain",e&&(this.message.textContent=`Upload: ${e}${this.#h.getItem(this.#e.id).getItem("error")?" \u2014 "+this.#h.getItem(this.#e.id).getItem("error"):""}`)}async#T(t,e=null){let i=this.ownerDocument.defaultView,s=new i.Image;e||(s.crossOrigin="anonymous"),s.src=e||t;try{await s.decode()}catch(a){throw e&&i.URL.revokeObjectURL(e),a}if(!s.naturalWidth||!s.naturalHeight)throw e&&i.URL.revokeObjectURL(e),new Error("Image has no dimensions");let{cropWidth:r,cropHeight:o}=this.parameters;return{image:s,original:t,objectUrl:e,transform:{x:0,y:0,zoom:Math.max(r/s.naturalWidth,o/s.naturalHeight),rotate:0}}}async#y(t){if(this.parameters.disabled||this.#e||this.#p)return;if(!["image/png","image/jpeg","image/webp"].includes(t.type)){this.message.textContent="Choose a PNG, JPEG or WebP image";return}let e=++this.#r;try{let i=await this.#T(t,this.ownerDocument.defaultView.URL.createObjectURL(t));if(e!==this.#r){this.#g(i);return}await this.#L(i,e)}catch(i){e===this.#r&&(this.message.textContent=`Image failed: ${i.message}`)}}async#B(){if(this.parameters.disabled||this.#e||this.#p)return;let t=++this.#r;try{let e=this.#i||await this.#T(this.parameters.value);if(t!==this.#r){e!==this.#i&&this.#g(e);return}await this.#L(e,t)}catch(e){t===this.#r&&(this.message.textContent=`Image failed: ${e.message}`)}}async#L(t,e){let i=this.parameters,s=this.#n=new V({state:this.#s.sourceNode.imageCropState,document:this.ownerDocument,original:t.original,image:t.image,sourceWidth:t.image.naturalWidth,sourceHeight:t.image.naturalHeight,width:i.cropWidth,height:i.cropHeight,outputWidth:i.outputWidth,outputHeight:i.outputHeight,type:"image/png",...t.transform}),r;try{r=await s.open()}catch(o){throw t!==this.#i&&this.#g(t),o}if(this.#n===s&&(this.#n=null),!r||e!==this.#r){t!==this.#i&&this.#g(t);return}if(i.operation===null)try{let o=await new Promise((a,l)=>{let m=new this.ownerDocument.defaultView.FileReader;m.onload=()=>a(m.result),m.onerror=()=>l(m.error),m.readAsDataURL(r.blob)});if(e!==this.#r){t!==this.#i&&this.#g(t);return}this.#D(t,r.transform,o),this.message.textContent="Image updated"}catch(o){throw t!==this.#i&&this.#g(t),o}else{let o=typeof t.original=="string"?"image.png":t.original.name.replace(/\.[^.]*$/,"")+".png",a=new this.ownerDocument.defaultView.File([r.blob],o,{type:"image/png"}),l=this.#t.add(a);this.#e={id:l,candidate:t,transform:r.transform,token:e},await this.#t.start(l),this.#A(l)}}#D(t,e,i){this.#i!==t&&this.#g(this.#i),t.transform=e,this.#i=t,this.#k(i)}async#P(t,e){let i=this.#e;if(!(!i||i.id!==t.label||i.token!==this.#r)){if(typeof e!="string"||!e)throw new TypeError("Image upload must return a displayable URL");this.#D(i.candidate,i.transform,e),this.#e=null,this.#b(),this.parameters.onComplete&&await this.#s.callLogic(this.parameters.onComplete,{item:t,result:e})}}#A(t){if(!this.#e||this.#e.id!==t)return;let e=this.#h.getItem(t),i=e.getItem("status");if(["failed","cancelled","completed"].includes(i)){let s=e.getItem("error");this.#e.candidate!==this.#i&&this.#g(this.#e.candidate),this.#e=null,this.#b(),this.message.textContent=s||`Upload: ${i}`}else this.#b()}async#M(){if(!this.#e)return;let t=this.#e.id;await this.#t.reconcile(t),this.#A(t)}}});import{Bag as k}from"@gramlot/gramlot";var pt=(0,w.defineComponent)({name:"attachmentManager",tag:"gramlot-attachment-manager",base:S,sourceContext:!0,bagStore:!0,parameters:{operation:{dtype:"T"},storepath:{dtype:"T"},contextPath:{dtype:"T"},ready:{dtype:"B",default:!1,binding:"read"},listMethod:{dtype:"T"},readMethod:{dtype:"T"},removeMethod:{dtype:"T"},accept:{dtype:"T",default:"",binding:"read"},disabled:{dtype:"B",default:!1,binding:"read"},selectedPath:{dtype:"T",nullable:!0,default:null,binding:"twoWay"}},implementation:n=>class extends n{#s;#h;#t;#i=0;#n=0;#e=0;#r=!1;#c=null;get#d(){return this.#s.sourceNode.attachmentState}get#l(){return this.#d.getItem("contextKey")}set#l(t){this.#d.setItem("contextKey",t)}get#a(){return this.#d.getItem("selected")}set#a(t){this.#d.setItem("selected",t)}get#m(){return this.#d.getItem("items")}set#m(t){this.#d.setItem("items",t)}constructor(){super(),this.control.replaceChildren();let t=this.ownerDocument,e=t.createElement("style");e.textContent=":host{display:block} .attachments{display:grid;gap:.75em} .attachment-list{padding-inline-start:1.2em} .preview img{max-width:100%;max-height:240px} button{font:inherit}";let i=t.createElement("div");i.className="attachments",this.uploader=t.createElement("gramlot-uploader");let s=t.createElement("strong");s.textContent="Attachments",this.list=t.createElement("ul"),this.list.className="attachment-list",this.list.setAttribute("aria-label","Attachments"),this.preview=t.createElement("div"),this.preview.className="preview",this.preview.setAttribute("aria-label","Attachment preview"),this.removeButton=t.createElement("button"),this.removeButton.type="button",this.removeButton.textContent="Remove attachment",this.message=t.createElement("div"),this.message.setAttribute("role","status"),i.append(this.uploader,s,this.list,this.preview,this.removeButton,this.message),this.control.append(i),this.shadowRoot.append(e),this.removeButton.addEventListener("click",()=>{this.#I()})}setSourceContext(t){this.#s=t,t.sourceNode.attachmentState||Object.defineProperty(t.sourceNode,"attachmentState",{value:new k({contextKey:null,selected:null,items:new k,preview:null,message:""}),configurable:!0}),this.#o(this.#d.getItem("message")),this.#u(),this.uploader.setSourceContext({...t,callLogic:()=>this.#x()})}setStoreBag(t){if(!(t instanceof k))throw new TypeError("attachmentManager storepath must resolve to a Bag");this.#h=t,this.uploader.setStoreBag(t)}projectAttributes(t,e){let i=super.projectAttributes(t,e),s=this.parameters;for(let r of["operation","contextPath","listMethod","readMethod","removeMethod"])if(typeof s[r]!="string"||!s[r])throw new TypeError(`attachmentManager requires ${r}`);return this.uploader.projectAttributes({operation:s.operation,storepath:s.storepath,contextPath:s.contextPath,accept:s.accept,multiple:!0,autoUpload:!!s.ready,manualUpload:!1,disabled:s.disabled,selectedPath:s.selectedPath,onComplete:"attachmentComplete"},e),this.#v(),this.#w(),i}connectedCallback(){if(this.#r=!1,this.#s&&!this.#t){let{gramlot:t}=this.#s.upload();this.#t=`attachment-manager-${A()}`,t.data.subscribe(this.#t,{any:()=>this.#v()})}this.#v()}disconnectedCallback(){this.ownerDocument.defaultView.queueMicrotask(()=>{this.isConnected||(this.#r=!0,this.#i++,this.#t&&(this.#s.upload().gramlot.data.unsubscribe(this.#t,{any:!0}),this.#t=null))})}#o(t){this.#d.setItem("message",t),this.message.textContent=t}#u(){this.preview.replaceChildren();let t=this.#d.getItem("preview");if(t)if(t.getItem("kind")==="image"){let e=this.ownerDocument.createElement("img");e.src=t.getItem("src"),e.alt="Attachment preview",this.preview.append(e)}else{let e=this.ownerDocument.createElement("pre");e.textContent=t.getItem("text"),this.preview.append(e)}}#p(){return M(this.#s.sourceNode,this.parameters.contextPath)}#v(){if(!(!this.parameters||!this.#s||!this.isConnected||this.#r)){if(!this.parameters.ready){this.#l!==null&&(this.#l=null,this.#i++,this.#c=null,this.#a=null,this.#m=new k,this.#d.setItem("preview",null),this.#u(),this.#w());return}try{let t=this.#p(),e=at(t);e!==this.#l&&(this.#l=e,this.#i++,this.#c=null,this.#a=null,this.#m=new k,this.#d.setItem("preview",null),this.#u(),this.#w(),this.#x())}catch(t){this.#l!==null&&(this.#l=null,this.#i++,this.#c=null,this.#a=null,this.#m=new k,this.#d.setItem("preview",null),this.#u(),this.#w()),this.#o(t.message)}}}async#x(){if(!this.parameters.ready||this.#r||!this.isConnected)return;let t=this.#i,e=++this.#n;try{let i=await this.#s.upload().gramlot.rpc.call("data",this.parameters.listMethod,{context:this.#p()});if(t!==this.#i||e!==this.#n||this.#r)return;if(!(i instanceof k))throw new TypeError("Attachment list must be a Bag");for(let s of i.getNodes())if(typeof s.getAttr("caption")!="string")throw new TypeError("Attachment caption must be text");this.#m=i,this.#a&&!this.#m.getNode(this.#a)&&(this.#a=null,this.#e++,this.#d.setItem("preview",null),this.#u()),this.#o(""),this.#w()}catch(i){t===this.#i&&e===this.#n&&!this.#r&&this.#o(`Attachments: ${i.message}`)}}#w(){if(!(!this.parameters||!this.#s)){this.list.replaceChildren();for(let t of this.#m.getNodes()){let e=this.ownerDocument.createElement("li"),i=this.ownerDocument.createElement("button");i.type="button",i.textContent=t.getAttr("caption"),i.setAttribute("aria-pressed",String(t.label===this.#a)),i.disabled=!!(this.parameters.disabled||!this.parameters.ready||this.#c),i.addEventListener("click",()=>{this.#E(t.label)}),e.append(i),this.list.append(e)}this.removeButton.disabled=!!(this.parameters.disabled||!this.parameters.ready||!this.#a||this.#c)}}async#E(t){if(!this.parameters.ready||this.parameters.disabled)return;this.#a=t,this.#w(),this.#d.setItem("preview",null),this.#u();let e=this.#i,i=++this.#e;try{let s=await this.#s.upload().gramlot.rpc.call("data",this.parameters.readMethod,{context:this.#p(),selected:t});if(e!==this.#i||i!==this.#e||this.#r)return;if(!(s instanceof k))throw new TypeError("Attachment preview must be a Bag");let r=s.getItem("kind"),o=s.getItem("text"),a=s.getItem("src");if(!(r==="image"&&typeof a=="string"&&a||["text","message"].includes(r)&&typeof o=="string"))throw new TypeError("Invalid attachment preview");this.#d.setItem("preview",s),this.#u(),this.#o("")}catch(s){e===this.#i&&i===this.#e&&!this.#r&&this.#o(`Preview: ${s.message}`)}}async#I(){if(!this.#a||!this.parameters.ready||this.parameters.disabled||this.#c)return;let t=this.#a,e=this.#i,i=this.#c={};this.#e++,this.#w();try{let s=await this.#s.upload().gramlot.rpc.call("data",this.parameters.removeMethod,{context:this.#p(),selected:t});if(e!==this.#i||this.#r)return;if(s!==!0)throw new Error("Attachment was not removed");this.#a=null,this.#d.setItem("preview",null),this.#u(),await this.#x()}catch(s){e===this.#i&&!this.#r&&this.#o(`Remove: ${s.message}`)}finally{this.#c===i&&(this.#c=null,this.#w())}}}});var Pe=Z({name:"uploads",components:[ot,dt,pt]});export{pt as AttachmentManager,dt as ImageUploader,ot as Uploader,Pe as default};
40
+ `;let W=s.createElement("header");W.className="crop-heading";let J=s.createElement("h2");J.textContent="Edit image";let O=s.createElement("p");O.className="crop-subtitle",O.textContent="Move and adjust the image within the frame.",W.append(J,O);let w=this.#n=s.createElement("div");w.setAttribute("aria-label","Crop preview"),w.setAttribute("role","group"),w.tabIndex=0,w.setAttribute("aria-description","Use arrow keys to move the image. Use the adjacent controls to zoom or rotate."),Object.assign(w.style,{position:"relative",overflow:"hidden",width:`${n}px`,height:`${d}px`,maxWidth:"none",background:"#ddd",margin:"auto",touchAction:"none",userSelect:"none",cursor:"grab"}),this.#r=s.createElement("img"),this.#r.src=a.src,this.#r.alt="",this.#r.draggable=!1,Object.assign(this.#r.style,{position:"absolute",left:"50%",top:"50%",maxWidth:"none",width:`${o}px`,height:`${r}px`,transformOrigin:"center center"}),w.append(this.#r);let Q=(c,E,I)=>{let x=s.createElement("button");return x.type="button",x.className=`crop-handle crop-${c}-handle`,x.dataset.cropHandle=c,x.setAttribute("aria-label",E),x.title=E,x.textContent=I,x},H=Q("rotate","Rotate image","\u21BB"),K=Q("zoom","Zoom image","\u2198"),F=s.createElement("div");F.className="crop-viewport",F.append(w);let $=s.createElement("div");$.className="crop-position",$.style.width=`${n+42}px`;let _=s.createElement("div");_.className="crop-handles",_.append(H,K),$.append(F,_);let G=s.createElement("p");G.className="crop-help",G.textContent="Drag to move \xB7 pinch to zoom";let z=s.createElement("div");z.className="crop-body",z.append($);let R=s.createElement("div");R.setAttribute("role","alert");let X=s.createElement("div");X.className="crop-actions";let S=s.createElement("button");S.type="button",S.textContent="Reset";let j=s.createElement("button");j.type="button",j.textContent="Cancel";let D=s.createElement("button");D.type="button",D.textContent="Confirm",D.className="primary";let Y=s.createElement("div");Y.className="crop-action-buttons",Y.append(S,j,D),X.append(G,Y),z.append(R),u.append(B,W,z,X),this.#l=new s.defaultView.AbortController;let g={signal:this.#l.signal};w.addEventListener("pointerdown",c=>this.#E(c),g);for(let c of[H,K])c.addEventListener("pointerdown",E=>this.#E(E),g);w.addEventListener("pointermove",c=>this.#C(c),g),w.addEventListener("pointerup",c=>this.#b(c),g);for(let c of["pointercancel","lostpointercapture"])w.addEventListener(c,E=>{this.#o.has(E.pointerId)&&this.#p()},g);w.addEventListener("dragstart",c=>c.preventDefault(),g),w.addEventListener("wheel",c=>this.#D(c),{...g,passive:!1}),w.addEventListener("gesturestart",c=>this.#w(c),{...g,passive:!1}),w.addEventListener("gesturechange",c=>this.#T(c),{...g,passive:!1}),w.addEventListener("gestureend",c=>this.#k(c),{...g,passive:!1}),s.defaultView.addEventListener("blur",()=>this.#p(),g),s.addEventListener("visibilitychange",()=>{s.hidden&&this.#p()},g),w.addEventListener("keydown",c=>{let E={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[c.key];if(!E)return;c.preventDefault(),this.#p();let I=this.#s.transform,x=c.shiftKey?10:1;I.x+=E[0]*x,I.y+=E[1]*x,this.#s.setTransform(I),this.#v()},g);for(let[c,E]of[[H,"rotate"],[K,"zoom"]])c.addEventListener("keydown",I=>{if(!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(I.key))return;I.preventDefault(),this.#p();let x=I.key==="ArrowUp"||I.key==="ArrowRight",L=this.#s.transform;E==="rotate"?L.rotate+=x?5:-5:L.zoom=this.#y(L.zoom*(x?1.05:1/1.05)),this.#s.setTransform(L),this.#v()},g);S.addEventListener("click",()=>{this.#p(),this.#s.reset(),this.#v()},g),j.addEventListener("click",()=>this.cancel(),g),u.addEventListener("cancel",c=>{c.preventDefault(),this.cancel()},g),u.addEventListener("close",()=>{this.#a||this.cancel()},g),D.addEventListener("click",async()=>{this.#p(),D.disabled=!0,R.textContent="";try{let c=this.#s.transform,{outputWidth:E,outputHeight:I,type:x,quality:L}=this.#c,mt=await this.#s.confirm({outputWidth:E,outputHeight:I,type:x,quality:L});this.#I({blob:mt,transform:c})}catch(c){this.#a||(R.textContent=c.message,D.disabled=!1)}},g),this.#v()}#f(){let[t,e]=this.#o.values();return e?{x:(t.x+e.x)/2,y:(t.y+e.y)/2,distance:Math.hypot(e.x-t.x,e.y-t.y),angle:Math.atan2(e.y-t.y,e.x-t.x)}:{x:t.x,y:t.y,distance:0,angle:0}}#x(t="move"){let e=this.#f();if(this.#o.size===2&&e.distance===0){this.#p();return}let s=this.#n.getBoundingClientRect(),i={x:s.left+s.width/2,y:s.top+s.height/2},a=Math.atan2(e.y-i.y,e.x-i.x),o=Math.hypot(e.x-i.x,e.y-i.y);this.#h={base:this.#s.transform,geometry:e,mode:t,center:i,distance:o,lastAngle:e.angle,handleAngle:a,rotation:0}}#E(t){if(t.button!==0||this.#a||this.#m||this.#o.size&&(t.pointerType!=="touch"||[...this.#o.values()].some(i=>i.type!=="touch")))return;if(this.#o.size===2){this.#p();return}let e=t.target.closest("[data-crop-handle]")?.dataset.cropHandle,s=e?`handle-${e}`:t.pointerType==="touch"?"move":t.shiftKey&&!t.altKey&&!t.ctrlKey&&!t.metaKey?"zoom":t.altKey&&!t.shiftKey&&!t.ctrlKey&&!t.metaKey?"rotate":!t.shiftKey&&!t.altKey&&!t.ctrlKey&&!t.metaKey?"move":null;s&&(t.preventDefault(),this.#o.set(t.pointerId,{x:t.clientX,y:t.clientY,type:t.pointerType}),this.#n.setPointerCapture(t.pointerId),this.#n.style.cursor="grabbing",this.#x(s))}#C(t){let e=this.#o.get(t.pointerId);if(!e||!this.#h)return;t.preventDefault(),e.x=t.clientX,e.y=t.clientY;let s=this.#f(),i=this.#h,a=s.x-i.geometry.x,o=s.y-i.geometry.y,r={...i.base};if(this.#o.size===2){if(r.x+=a,r.y+=o,s.distance>0){let n=s.angle-i.lastAngle;i.rotation+=Math.atan2(Math.sin(n),Math.cos(n))*180/Math.PI,i.lastAngle=s.angle}r.rotate+=i.rotation,r.zoom=i.base.zoom*s.distance/i.geometry.distance}else if(i.mode==="handle-zoom"){let n=Math.hypot(s.x-i.center.x,s.y-i.center.y);i.distance>0&&(r.zoom=i.base.zoom*n/i.distance)}else if(i.mode==="handle-rotate"){let n=Math.atan2(s.y-i.center.y,s.x-i.center.x),d=n-i.handleAngle;i.rotation+=Math.atan2(Math.sin(d),Math.cos(d))*180/Math.PI,i.handleAngle=n,r.rotate+=i.rotation}else i.mode==="zoom"?r.zoom=i.base.zoom*Math.exp(o/100):i.mode==="rotate"?r.rotate-=o:(r.x+=a,r.y+=o);r.zoom=this.#y(r.zoom),this.#s.setTransform(r),this.#v()}#b(t){this.#o.has(t.pointerId)&&(this.#C(t),this.#o.delete(t.pointerId),this.#n.hasPointerCapture(t.pointerId)&&this.#n.releasePointerCapture(t.pointerId),this.#o.size?this.#x():this.#p())}#p(){let t=[...this.#o.keys()];this.#o.clear(),this.#h=null,this.#m=null;for(let e of t)this.#n.hasPointerCapture(e)&&this.#n.releasePointerCapture(e);this.#n&&(this.#n.style.cursor="grab")}#y(t){return Math.max(this.#d,Math.min(this.#u,t))}#D(t){if(this.#a||this.#o.size||!t.ctrlKey&&!t.altKey||(t.preventDefault(),this.#m))return;let e=t.deltaMode===1?16:t.deltaMode===2?this.#c.height:1,s=this.#s.transform;t.ctrlKey?s.zoom=this.#y(s.zoom*Math.exp(-t.deltaY*e/100)):s.rotate-=t.deltaY*e/4,this.#s.setTransform(s),this.#v()}#w(t){this.#a||this.#o.size||(t.preventDefault(),this.#m=this.#s.transform)}#T(t){if(!this.#m||this.#a||(t.preventDefault(),!Number.isFinite(t.scale)||t.scale<=0||!Number.isFinite(t.rotation)))return;let e={...this.#m};e.zoom=this.#y(e.zoom*t.scale),e.rotate+=t.rotation,this.#s.setTransform(e),this.#v()}#k(t){this.#m&&(t.preventDefault(),this.#m=null)}#v(){let{x:t,y:e,zoom:s,rotate:i}=this.#s.transform;this.#r.style.transform=`translate(-50%, -50%) translate(${t}px, ${e}px) rotate(${i}deg) scale(${s})`}open(){if(this.#g||this.#a)throw new Error("Image crop dialog has already opened");return new Promise((t,e)=>{this.#g=t,this.#i.body.append(this.#t);try{this.#t.showModal()}catch(s){this.#a=!0,this.#l.abort(),this.#t.remove(),e(s)}})}cancel(){if(!this.#a){if(this.#p(),this.#s.cancel(),!this.#g){this.#a=!0,this.#l.abort();return}this.#I(null)}}#I(t){this.#a||(this.#a=!0,this.#p(),this.#l.abort(),this.#t.open&&this.#t.close(),this.#t.remove(),this.#g(t))}};import{sharedModules as Bt}from"@gramlot/gramlot";var Lt=h=>Bt["./media-frame.js"][h],ht=Lt("captureVideoFrame");function ct({document:h,signal:t}){if(t.aborted)return Promise.reject(new DOMException("Screen capture cancelled","AbortError"));let e=h.defaultView,s;try{s=e.navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1})}catch(i){return Promise.reject(i)}return new Promise((i,a)=>{let o=!1,r=null,n=!1,d=new e.AbortController,b={signal:d.signal},l=h.createElement("video");l.muted=!0,l.autoplay=!0,l.playsInline=!0,Object.assign(l.style,{position:"fixed",width:"1px",height:"1px",opacity:"0",pointerEvents:"none"});let p=m=>{for(let u of m.getTracks())u.stop()},f=()=>{r&&(p(r),r=null),l.srcObject=null,l.remove()},v=(m,u)=>{o||(o=!0,d.abort(),t.removeEventListener("abort",C),f(),m?a(m):i(u))},C=()=>v(new DOMException("Screen capture cancelled","AbortError"));t.addEventListener("abort",C,{once:!0});let T=()=>{if(!(o||n||l.readyState<2||!l.videoWidth||!l.videoHeight)){n=!0;try{let m=ht(h,l);f(),m.toBlob(u=>{!u||u.type!=="image/png"?v(new Error("Screen image encoding failed")):v(null,u)},"image/png")}catch(m){v(m)}}};l.addEventListener("loadeddata",T,b),t.aborted&&C(),s.then(async m=>{if(o){p(m);return}r=m;for(let u of r.getTracks())u.addEventListener("ended",()=>{n||v(new Error("Screen sharing ended"))},b);h.body.append(l),l.srcObject=r;try{await l.play(),T()}catch(u){n||v(u)}},m=>v(m))})}var dt=(0,y.defineComponent)({name:"imageUploader",tag:"gramlot-image-uploader",base:lt,sourceContext:!0,parameters:{value:{dtype:"T",nullable:!0,default:null,binding:"twoWay"},storepath:{dtype:"T"},contextPath:{dtype:"T",nullable:!0,default:null},operation:{dtype:"T",nullable:!0,default:null},cropWidth:{dtype:"L",default:256},cropHeight:{dtype:"L",default:256},outputWidth:{dtype:"L",default:512},outputHeight:{dtype:"L",default:512},disabled:{dtype:"B",default:!1,binding:"read"},onComplete:{dtype:"T",nullable:!0,default:null}},implementation:h=>class extends h{#i;#e;#s;#c;#t;#r=0;#d;#u;#g=null;#a=null;#l=!1;#n=!1;#o;#h=null;constructor(){super();let t=this.ownerDocument;this.control=t.createElement("div"),this.controlBox.append(this.control);let e=t.createElement("style");e.textContent=":host{display:block} .image-uploader{display:grid;gap:.5em;justify-items:start} img{max-width:100%;max-height:240px} .actions{display:flex;gap:.5em;flex-wrap:wrap} button{font:inherit} .image-uploader[data-drag-over]{outline:2px dashed var(--gramlot-action,#3766b5);outline-offset:4px}";let s=t.createElement("div");s.className="image-uploader",this.preview=t.createElement("img"),this.preview.alt="Selected image",this.input=t.createElement("input"),this.input.type="file",this.input.accept="image/png,image/jpeg,image/webp",this.input.hidden=!0;let i=t.createElement("div");i.className="actions";let a=o=>{let r=t.createElement("button");return r.type="button",r.textContent=o,i.append(r),r};this.chooseButton=a("Choose image"),this.cameraButton=a("Take photo"),this.screenButton=a("Capture screen"),this.editButton=a("Edit"),this.clearButton=a("Clear"),this.cancelScreenButton=a("Cancel capture"),this.cancelButton=a("Cancel upload"),this.checkButton=a("Check status"),this.message=t.createElement("div"),this.message.setAttribute("role","status"),s.append(this.preview,this.input,i,this.message),this.control.append(s),this.shadowRoot.append(e),this.chooseButton.addEventListener("click",()=>this.input.click()),s.addEventListener("dragover",o=>{!this.parameters?.disabled&&!this.#t&&this.#a===null&&!this.#h&&[...o.dataTransfer.types].includes("Files")&&(o.preventDefault(),o.stopPropagation(),o.dataTransfer.dropEffect="copy",s.setAttribute("data-drag-over",""))}),s.addEventListener("dragleave",()=>s.removeAttribute("data-drag-over")),s.addEventListener("drop",o=>{if(s.removeAttribute("data-drag-over"),this.parameters?.disabled||this.#t||this.#a!==null||this.#h||![...o.dataTransfer.types].includes("Files"))return;o.preventDefault(),o.stopPropagation();let r=[...o.dataTransfer.files];if(r.length!==1){this.message.textContent="Select one image";return}this.#k(r[0])}),this.cameraButton.addEventListener("click",()=>this.#x()),this.screenButton.addEventListener("click",()=>this.#E()),this.cancelScreenButton.addEventListener("click",()=>this.#h?.abort()),this.input.addEventListener("change",o=>{o.stopPropagation();let r=this.input.files[0];this.input.value="",r&&this.#k(r)}),this.editButton.addEventListener("click",()=>{this.#v()}),this.clearButton.addEventListener("click",()=>{this.#y(),this.#D(null)}),this.cancelButton.addEventListener("click",()=>{this.#t&&this.#e.cancel(this.#t.id)}),this.checkButton.addEventListener("click",()=>{this.#P()})}setSourceContext(t){this.#i=t}readControlValue(){return this.parameters?.value??null}writeControlValue(t){this.parameters&&(this.parameters.value=t,this.#w())}projectAttributes(t,e){this.#e&&this.#e.path!==this.#i.attrDatapath("storepath")&&(this.#y(),this.#e.dispose(),this.#e=null);let s=super.projectAttributes(t,e),i=this.parameters;for(let a of["cropWidth","cropHeight","outputWidth","outputHeight"])if(!Number.isSafeInteger(i[a])||i[a]<=0)throw new RangeError(`${a} must be a positive integer`);if(i.cropWidth*i.outputHeight!==i.cropHeight*i.outputWidth)throw new RangeError("Crop and output aspect ratios must match");return this.#d!==void 0&&i.value!==this.#d&&i.value!==this.#u&&this.#y(),this.#d=i.value,this.#u=void 0,this.#b(),this.#e&&(this.#e.operation=i.operation),this.#w(),s}connectedCallback(){this.#b(),this.#m()}disconnectedCallback(){this.ownerDocument.defaultView.queueMicrotask(()=>{this.isConnected||(this.#g?.close(),this.#g=null,this.#y(),this.#e?.dispose(),this.#e=null)})}#m(){this.#g||!this.#i||(this.#g=this.#i.sourceNode.rootBuilder.binding.router.register({path:"_gramlot.device.camera",subtree:!0,recipient:{receive:t=>this.#f(t)}}),this.#f())}#f(t=null){let{gramlot:e}=this.#i.upload(),s=!!(e.dvc.provider&&e.dvc.provider.capabilities.includes("camera")),i=e.data.getNode("_gramlot.device.camera"),a=i?.attr.status;if((s!==this.#n||a!==this.#o)&&(this.#n=s,this.#o=a,this.#w()),this.#a===null||t?.node!==i)return;if(a==="pending"){this.#l=!0;return}if(!this.#l||!["success","cancelled","denied","unavailable","error"].includes(a))return;let o=this.#a;this.#a=null,this.#l=!1,this.#w(),a==="success"?this.#C(i.staticValue.getItem("url"),o):a!=="cancelled"&&(this.message.textContent=i.attr.error?.message||"Camera is unavailable")}#x(){if(!(!this.#n||this.#o==="pending"||this.parameters.disabled||this.#t||this.#a!==null||this.#h)){this.#a=++this.#r,this.#l=!1;try{this.#i.sourceNode.FIRE("_gramlot.device.camera?capture")}catch(t){this.#a=null,this.message.textContent=`Camera failed: ${t.message}`,this.#w()}}}#E(){if(this.parameters.disabled||this.#t||this.#a!==null||this.#h||this.#c)return;let t=this.ownerDocument.defaultView,e=new t.AbortController,s=++this.#r;this.#h=e,this.message.textContent="",this.#w(),ct({document:this.ownerDocument,signal:e.signal}).then(a=>{if(s===this.#r)return this.#h=null,this.#w(),this.#k(new t.File([a],"screen.png",{type:"image/png"}))}).catch(a=>{s===this.#r&&(this.#h=null,this.#w(),a.name!=="AbortError"&&(this.message.textContent=a.name==="NotAllowedError"?"Screen capture was cancelled or not permitted":`Screen capture failed: ${a.message}`))})}async#C(t,e){try{let s=await this.#T(t);if(e!==this.#r){this.#p(s);return}await this.#I(s,e)}catch(s){e===this.#r&&(this.message.textContent=`Image failed: ${s.message}`)}}#b(){if(!this.#e&&this.#i&&this.parameters){let{gramlot:t,window:e}=this.#i.upload();this.#e=new A({gramlot:t,window:e,data:this.#i.sourceNode.data,path:this.#i.attrDatapath("storepath"),operation:this.parameters.operation,onChange:()=>this.#w(),getContext:()=>P(this.#i.sourceNode,this.parameters.contextPath),onComplete:(s,i)=>this.#A(s,i)})}}#p(t){t?.objectUrl&&this.ownerDocument.defaultView.URL.revokeObjectURL(t.objectUrl)}#y(){this.#r++,this.#h?.abort(),this.#h=null,this.#a=null,this.#l=!1,this.#c?.cancel(),this.#c=null,this.#t&&(this.#e?.cancel(this.#t.id),this.#t.candidate!==this.#s&&this.#p(this.#t.candidate),this.#t=null),this.#p(this.#s),this.#s=null}#D(t){this.#u=t,this.#i.writeParameter("value",t)}#w(){if(!this.parameters)return;let t=this.parameters.value;t?(this.preview.src=t,this.preview.hidden=!1):(this.preview.removeAttribute("src"),this.preview.hidden=!0);let e=this.#t&&this.#e.store.getItem(this.#t.id)?.getItem("status"),s=!!(this.#t||this.#a!==null||this.#h);this.screenButton.hidden=!this.ownerDocument.defaultView.navigator.mediaDevices?.getDisplayMedia,this.screenButton.disabled=!!(this.parameters.disabled||s),this.cancelScreenButton.hidden=!this.#h,this.cameraButton.hidden=!this.#n,this.cameraButton.disabled=!!(this.parameters.disabled||s||this.#o==="pending"),this.chooseButton.disabled=this.editButton.disabled=this.clearButton.disabled=!!(this.parameters.disabled||s),this.editButton.disabled||=!t&&!this.#s,this.clearButton.disabled||=!t,this.cancelButton.hidden=!["preparing","uploading"].includes(e),this.checkButton.hidden=e!=="uncertain",e&&(this.message.textContent=`Upload: ${e}${this.#e.store.getItem(this.#t.id).getItem("error")?" \u2014 "+this.#e.store.getItem(this.#t.id).getItem("error"):""}`)}async#T(t,e=null){let s=this.ownerDocument.defaultView,i=new s.Image;e||(i.crossOrigin="anonymous"),i.src=e||t;try{await i.decode()}catch(r){throw e&&s.URL.revokeObjectURL(e),r}if(!i.naturalWidth||!i.naturalHeight)throw e&&s.URL.revokeObjectURL(e),new Error("Image has no dimensions");let{cropWidth:a,cropHeight:o}=this.parameters;return{image:i,original:t,objectUrl:e,transform:{x:0,y:0,zoom:Math.max(a/i.naturalWidth,o/i.naturalHeight),rotate:0}}}async#k(t){if(this.parameters.disabled||this.#t||this.#h)return;if(!["image/png","image/jpeg","image/webp"].includes(t.type)){this.message.textContent="Choose a PNG, JPEG or WebP image";return}let e=++this.#r;try{let s=await this.#T(t,this.ownerDocument.defaultView.URL.createObjectURL(t));if(e!==this.#r){this.#p(s);return}await this.#I(s,e)}catch(s){e===this.#r&&(this.message.textContent=`Image failed: ${s.message}`)}}async#v(){if(this.parameters.disabled||this.#t||this.#h)return;let t=++this.#r;try{let e=this.#s||await this.#T(this.parameters.value);if(t!==this.#r){e!==this.#s&&this.#p(e);return}await this.#I(e,t)}catch(e){t===this.#r&&(this.message.textContent=`Image failed: ${e.message}`)}}async#I(t,e){let s=this.parameters,i=this.#c=new V({data:this.#i.sourceNode.data,path:this.#i.sourceNode.workspaceDatapath,document:this.ownerDocument,original:t.original,image:t.image,sourceWidth:t.image.naturalWidth,sourceHeight:t.image.naturalHeight,width:s.cropWidth,height:s.cropHeight,outputWidth:s.outputWidth,outputHeight:s.outputHeight,type:"image/png",...t.transform}),a;try{a=await i.open()}catch(o){throw t!==this.#s&&this.#p(t),o}if(this.#c===i&&(this.#c=null),!a||e!==this.#r){t!==this.#s&&this.#p(t);return}if(s.operation===null)try{let o=await new Promise((r,n)=>{let d=new this.ownerDocument.defaultView.FileReader;d.onload=()=>r(d.result),d.onerror=()=>n(d.error),d.readAsDataURL(a.blob)});if(e!==this.#r){t!==this.#s&&this.#p(t);return}this.#B(t,a.transform,o),this.message.textContent="Image updated"}catch(o){throw t!==this.#s&&this.#p(t),o}else{let o=typeof t.original=="string"?"image.png":t.original.name.replace(/\.[^.]*$/,"")+".png",r=new this.ownerDocument.defaultView.File([a.blob],o,{type:"image/png"}),n=this.#e.add(r);this.#t={id:n,candidate:t,transform:a.transform,token:e},await this.#e.start(n),this.#L(n)}}#B(t,e,s){this.#s!==t&&this.#p(this.#s),t.transform=e,this.#s=t,this.#D(s)}async#A(t,e){let s=this.#t;if(!(!s||s.id!==t.label||s.token!==this.#r)){if(typeof e!="string"||!e)throw new TypeError("Image upload must return a displayable URL");this.#B(s.candidate,s.transform,e),this.#t=null,this.#w(),this.parameters.onComplete&&await this.#i.callLogic(this.parameters.onComplete,{item:t,result:e})}}#L(t){if(!this.#t||this.#t.id!==t)return;let e=this.#e.store.getItem(t),s=e.getItem("status");if(["failed","cancelled","completed"].includes(s)){let i=e.getItem("error");this.#t.candidate!==this.#s&&this.#p(this.#t.candidate),this.#t=null,this.#w(),this.message.textContent=i||`Upload: ${s}`}else this.#w()}async#P(){if(!this.#t)return;let t=this.#t.id;await this.#e.reconcile(t),this.#L(t)}}});import{Bag as k}from"@gramlot/gramlot";var pt=(0,y.defineComponent)({name:"attachmentManager",tag:"gramlot-attachment-manager",base:N,sourceContext:!0,parameters:{operation:{dtype:"T"},storepath:{dtype:"T"},contextPath:{dtype:"T"},ready:{dtype:"B",default:!1,binding:"read"},listMethod:{dtype:"T"},readMethod:{dtype:"T"},removeMethod:{dtype:"T"},accept:{dtype:"T",default:"",binding:"read"},disabled:{dtype:"B",default:!1,binding:"read"},selectedPath:{dtype:"T",nullable:!0,default:null,binding:"twoWay"}},implementation:h=>class extends h{#i;#e=null;#s=0;#c=0;#t=0;#r=!1;#d=null;get#u(){return this.#i.sourceNode.workspaceDatapath}#g(t){return this.#i.getStaticData(`${this.#u}.${t}`)}#a(t,e){this.#i.sourceNode.data.setItem(`${this.#u}.${t}`,e)}get#l(){return this.#g("contextKey")}set#l(t){this.#a("contextKey",t)}get#n(){return this.#g("selected")}set#n(t){this.#a("selected",t)}get#o(){return this.#g("items")}set#o(t){this.#a("items",t)}constructor(){super(),this.control.replaceChildren();let t=this.ownerDocument,e=t.createElement("style");e.textContent=":host{display:block} .attachments{display:grid;gap:.75em} .attachment-list{padding-inline-start:1.2em} .preview img{max-width:100%;max-height:240px} button{font:inherit}";let s=t.createElement("div");s.className="attachments",this.uploader=t.createElement("gramlot-uploader");let i=t.createElement("strong");i.textContent="Attachments",this.list=t.createElement("ul"),this.list.className="attachment-list",this.list.setAttribute("aria-label","Attachments"),this.preview=t.createElement("div"),this.preview.className="preview",this.preview.setAttribute("aria-label","Attachment preview"),this.removeButton=t.createElement("button"),this.removeButton.type="button",this.removeButton.textContent="Remove attachment",this.message=t.createElement("div"),this.message.setAttribute("role","status"),s.append(this.uploader,i,this.list,this.preview,this.removeButton,this.message),this.control.append(s),this.shadowRoot.append(e),this.removeButton.addEventListener("click",()=>{this.#y()})}setSourceContext(t){this.#i=t,this.#o instanceof k||t.sourceNode.data.setItem(this.#u,new k({contextKey:null,selected:null,items:new k,preview:null,message:""})),this.#m(this.#g("message")),this.#f(),this.uploader.setSourceContext({...t,callLogic:()=>this.#C()})}projectAttributes(t,e){let s=super.projectAttributes(t,e),i=this.parameters;for(let a of["operation","contextPath","listMethod","readMethod","removeMethod"])if(typeof i[a]!="string"||!i[a])throw new TypeError(`attachmentManager requires ${a}`);return this.uploader.projectAttributes({operation:i.operation,storepath:i.storepath,contextPath:i.contextPath,accept:i.accept,multiple:!0,autoUpload:!!i.ready,manualUpload:!1,disabled:i.disabled,selectedPath:i.selectedPath,onComplete:"attachmentComplete"},e),this.isConnected&&this.#h(),this.#E(),this.#b(),s}connectedCallback(){this.#r=!1,this.#i&&this.parameters&&this.#h(),this.#E()}#h(){let t=this.#i.attrDatapath("contextPath");this.#e?.path!==t&&(this.#e?.close(),this.#e=this.#i.sourceNode.rootBuilder.binding.router.register({path:t,subtree:!0,recipient:{receive:()=>this.#E()}}))}disconnectedCallback(){this.ownerDocument.defaultView.queueMicrotask(()=>{this.isConnected||(this.#r=!0,this.#s++,this.#e?.close(),this.#e=null)})}#m(t){this.#a("message",t),this.message.textContent=t}#f(){this.preview.replaceChildren();let t=this.#g("preview");if(t)if(t.getItem("kind")==="image"){let e=this.ownerDocument.createElement("img");e.src=t.getItem("src"),e.alt="Attachment preview",this.preview.append(e)}else{let e=this.ownerDocument.createElement("pre");e.textContent=t.getItem("text"),this.preview.append(e)}}#x(){return P(this.#i.sourceNode,this.parameters.contextPath)}#E(){if(!(!this.parameters||!this.#i||!this.isConnected||this.#r)){if(!this.parameters.ready){this.#l!==null&&(this.#l=null,this.#s++,this.#d=null,this.#n=null,this.#o=new k,this.#a("preview",null),this.#f(),this.#b());return}try{let t=this.#x(),e=at(t);e!==this.#l&&(this.#l=e,this.#s++,this.#d=null,this.#n=null,this.#o=new k,this.#a("preview",null),this.#f(),this.#b(),this.#C())}catch(t){this.#l!==null&&(this.#l=null,this.#s++,this.#d=null,this.#n=null,this.#o=new k,this.#a("preview",null),this.#f(),this.#b()),this.#m(t.message)}}}async#C(){if(!this.parameters.ready||this.#r||!this.isConnected)return;let t=this.#s,e=++this.#c;try{let s=await this.#i.upload().gramlot.rpc.call("data",this.parameters.listMethod,{context:this.#x()});if(t!==this.#s||e!==this.#c||this.#r)return;if(!(s instanceof k))throw new TypeError("Attachment list must be a Bag");for(let i of s.getNodes())if(typeof i.getAttr("caption")!="string")throw new TypeError("Attachment caption must be text");this.#o=s,this.#n&&!this.#o.getNode(this.#n)&&(this.#n=null,this.#t++,this.#a("preview",null),this.#f()),this.#m(""),this.#b()}catch(s){t===this.#s&&e===this.#c&&!this.#r&&this.#m(`Attachments: ${s.message}`)}}#b(){if(!(!this.parameters||!this.#i)){this.list.replaceChildren();for(let t of this.#o.getNodes()){let e=this.ownerDocument.createElement("li"),s=this.ownerDocument.createElement("button");s.type="button",s.textContent=t.getAttr("caption"),s.setAttribute("aria-pressed",String(t.label===this.#n)),s.disabled=!!(this.parameters.disabled||!this.parameters.ready||this.#d),s.addEventListener("click",()=>{this.#p(t.label)}),e.append(s),this.list.append(e)}this.removeButton.disabled=!!(this.parameters.disabled||!this.parameters.ready||!this.#n||this.#d)}}async#p(t){if(!this.parameters.ready||this.parameters.disabled)return;this.#n=t,this.#b(),this.#a("preview",null),this.#f();let e=this.#s,s=++this.#t;try{let i=await this.#i.upload().gramlot.rpc.call("data",this.parameters.readMethod,{context:this.#x(),selected:t});if(e!==this.#s||s!==this.#t||this.#r)return;if(!(i instanceof k))throw new TypeError("Attachment preview must be a Bag");let a=i.getItem("kind"),o=i.getItem("text"),r=i.getItem("src");if(!(a==="image"&&typeof r=="string"&&r||["text","message"].includes(a)&&typeof o=="string"))throw new TypeError("Invalid attachment preview");this.#a("preview",i),this.#f(),this.#m("")}catch(i){e===this.#s&&s===this.#t&&!this.#r&&this.#m(`Preview: ${i.message}`)}}async#y(){if(!this.#n||!this.parameters.ready||this.parameters.disabled||this.#d)return;let t=this.#n,e=this.#s,s=this.#d={};this.#t++,this.#b();try{let i=await this.#i.upload().gramlot.rpc.call("data",this.parameters.removeMethod,{context:this.#x(),selected:t});if(e!==this.#s||this.#r)return;if(i!==!0)throw new Error("Attachment was not removed");this.#n=null,this.#a("preview",null),this.#f(),await this.#C()}catch(i){e===this.#s&&!this.#r&&this.#m(`Remove: ${i.message}`)}finally{this.#d===s&&(this.#d=null,this.#b())}}}});var Be=Z({name:"uploads",components:[nt,dt,pt]});export{pt as AttachmentManager,dt as ImageUploader,nt as Uploader,Be as default};
@@ -1,3 +1,3 @@
1
1
  export {default} from "./collection.js";
2
2
  export * from "./collection.js";
3
- export const buildId = "sha256:713c837016d47c74e514f8121ddc5727939530dbbf644c4f26e73f14e25d5001";
3
+ export const buildId = "sha256:5e0b1291248f1696acf7eabcf1bd9c3689ce266f300b872b31940291ce841a9b";
@@ -8,7 +8,6 @@
8
8
  "attachmentManager": {
9
9
  "_meta": {
10
10
  "gramlot_component": {
11
- "bagStore": true,
12
11
  "command": false,
13
12
  "dataScope": false,
14
13
  "parameters": {
@@ -240,7 +239,6 @@
240
239
  "imageUploader": {
241
240
  "_meta": {
242
241
  "gramlot_component": {
243
- "bagStore": true,
244
242
  "command": false,
245
243
  "dataScope": false,
246
244
  "parameters": {
@@ -486,7 +484,6 @@
486
484
  "uploader": {
487
485
  "_meta": {
488
486
  "gramlot_component": {
489
- "bagStore": true,
490
487
  "command": false,
491
488
  "dataScope": false,
492
489
  "parameters": {