@nice2dev/ui-ai 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +103 -0
- package/dist/NiceAIHintBubble.d.ts +3 -1
- package/dist/NiceAccessibilityAI.d.ts +1 -1
- package/dist/NiceCodeEditorAI.d.ts +1 -1
- package/dist/NiceDataGridAI.d.ts +1 -1
- package/dist/NiceIconSuggestorAI.d.ts +7 -4
- package/dist/NiceReportBuilderAI.d.ts +2 -2
- package/dist/NiceWorkflowDesignerAI.d.ts +1 -1
- package/dist/index.cjs +125 -117
- package/dist/index.mjs +3944 -3986
- package/dist/ui-ai.css +1 -1
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),
|
|
2
|
-
`);n=
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),l=require("react"),T=require("@nice2dev/ui-core"),Ma=require("@nice2dev/ui");class Ve{constructor(a={},i){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1,this.config={maxRequestsPerMinute:a.maxRequestsPerMinute??30,maxTokensPerSession:a.maxTokensPerSession??1e4,warnThresholdPercent:a.warnThresholdPercent??80},this.onWarning=i}canRequest(){return this.pruneOldTimestamps(),!(this.timestamps.length>=this.config.maxRequestsPerMinute||this.tokenCount>=this.config.maxTokensPerSession)}recordRequest(){return this.canRequest()?(this.timestamps.push(Date.now()),!0):!1}recordTokens(a){this.tokenCount+=a,this.checkWarning()}getStatus(){this.pruneOldTimestamps();const a=this.config.maxTokensPerSession>0?this.tokenCount/this.config.maxTokensPerSession*100:0,i=this.config.maxRequestsPerMinute>0?this.timestamps.length/this.config.maxRequestsPerMinute*100:0;return{requestsThisMinute:this.timestamps.length,tokensThisSession:this.tokenCount,isLimited:!this.canRequest(),isWarning:a>=this.config.warnThresholdPercent||i>=this.config.warnThresholdPercent}}reset(){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1}pruneOldTimestamps(){const a=Date.now()-6e4;this.timestamps=this.timestamps.filter(i=>i>a)}checkWarning(){var i;if(this.warningEmitted)return;this.getStatus().isWarning&&(this.warningEmitted=!0,(i=this.onWarning)==null||i.call(this))}}const Xe=l.createContext(null);function $a({config:t,rateLimits:a,enabled:i=!0,onRateLimitWarning:r,children:n}){const s=l.useRef(null);s.current||(s.current=new Ve(a,r));const o=l.useCallback(()=>s.current.getStatus(),[]),c=l.useMemo(()=>({config:t,enabled:i,rateLimiter:s.current,getRateLimitStatus:o}),[t,i,o]);return e.jsx(Xe.Provider,{value:c,children:n})}function ee(){return l.useContext(Xe)}async function*Qe(t,a){var s,o,c,m,p,u,v,w,A;const i=(s=t.body)==null?void 0:s.getReader();if(!i)throw new Error("Response body is not readable");const r=new TextDecoder;let n="";try{for(;!(a!=null&&a.aborted);){const{done:R,value:M}=await i.read();if(R)break;n+=r.decode(M,{stream:!0});const P=n.split(`
|
|
2
|
+
`);n=P.pop()??"";for(const g of P){const d=g.trim();if(!(!d||d===":")){if(d.startsWith("data:")){const j=d.slice(5).trim();if(j==="[DONE]"){yield{token:"",done:!0};return}try{const y=JSON.parse(j),I=((m=(c=(o=y.choices)==null?void 0:o[0])==null?void 0:c.delta)==null?void 0:m.content)??"",b=((u=(p=y.choices)==null?void 0:p[0])==null?void 0:u.finish_reason)==="stop";(I||b)&&(yield{token:I,done:b,usage:y.usage})}catch{j&&(yield{token:j,done:!1})}continue}try{const j=JSON.parse(d),y=j.text??j.content??j.token??"";y&&(yield{token:y,done:!1})}catch{d&&(yield{token:d,done:!1})}}}}if(n.trim()){const R=n.trim();if(R.startsWith("data:")){const M=R.slice(5).trim();if(M&&M!=="[DONE]")try{const g=((A=(w=(v=JSON.parse(M).choices)==null?void 0:v[0])==null?void 0:w.delta)==null?void 0:A.content)??"";g&&(yield{token:g,done:!0})}catch{yield{token:M,done:!0}}}}}finally{i.releaseLock()}}async function Ze(t){var i,r,n,s;const a=await t.json();if((n=(r=(i=a.choices)==null?void 0:i[0])==null?void 0:r.message)!=null&&n.content)return{text:a.choices[0].message.content,usage:a.usage};if((s=a.message)!=null&&s.content)return{text:a.message.content};if(typeof a.text=="string")return{text:a.text};if(typeof a.content=="string")return{text:a.content};if(typeof a.response=="string")return{text:a.response};throw new Error("Unrecognized AI response format")}const se=new Map;function Be(t,a){const i=a?{...t,fieldValue:void 0,formContext:void 0}:t;return JSON.stringify(i)}function Pa(t,a){const i=[],r=a.systemPrompt??"You are a helpful assistant providing concise contextual hints for form fields. Keep responses short (1-3 sentences). Be specific and actionable.";i.push({role:"system",content:r});const n=[];if(t.fieldLabel&&n.push(`Field: "${t.fieldLabel}"`),t.fieldType&&n.push(`Type: ${t.fieldType}`),!a.privacyMode&&t.fieldValue!==void 0){const o=typeof t.fieldValue=="string"?t.fieldValue:JSON.stringify(t.fieldValue);n.push(`Current value: ${o}`)}t.validationRules&&Object.keys(t.validationRules).length>0&&n.push(`Validation: ${JSON.stringify(t.validationRules)}`),t.schema&&Object.keys(t.schema).length>0&&n.push(`Schema: ${JSON.stringify(t.schema)}`),!a.privacyMode&&t.formContext&&Object.keys(t.formContext).length>0&&n.push(`Form context: ${JSON.stringify(t.formContext)}`),t.customPrompt&&n.push(t.customPrompt);const s=n.length>0?`Provide a helpful hint for this field:
|
|
3
3
|
${n.join(`
|
|
4
|
-
`)}`:"Provide a helpful suggestion.";return
|
|
5
|
-
Parse this description and return suggested values for each field as JSON: { ${a.map(
|
|
6
|
-
`))??[],s=(
|
|
4
|
+
`)}`:"Provide a helpful suggestion.";return i.push({role:"user",content:s}),i}function Z(t={},a={}){t=t??{},a=a??{};const{debounceMs:i=500,disabled:r=!1}=a,n=ee(),[s,o]=l.useState(""),[c,m]=l.useState(!1),[p,u]=l.useState(null),[v,w]=l.useState(!1),A=l.useRef(null),R=l.useRef(0),M=l.useCallback(async()=>{var f,k,S;if(!n||!n.enabled||r)return;const{config:d,rateLimiter:j}=n;if(!j.recordRequest()){u("Rate limit exceeded. Please wait before requesting another hint.");return}const y=Be(t,d.privacyMode??!1),I=se.get(y);if(I){o(I),m(!1),u(null),w(!1);return}(f=A.current)==null||f.abort();const b=new AbortController;A.current=b,m(!0),u(null),o(""),w(!1);const h=Pa(t,d),_=d.stream!==!1;try{const N={"Content-Type":"application/json",...d.headers};d.apiKey&&(N.Authorization=`Bearer ${d.apiKey}`);const $=JSON.stringify({model:d.model??"gpt-3.5-turbo",messages:h,temperature:d.temperature??.7,max_tokens:d.maxTokens??256,stream:_}),E=await fetch(d.endpoint,{method:"POST",headers:N,body:$,signal:b.signal});if(!E.ok){const z=await E.text().catch(()=>E.statusText);throw new Error(`AI request failed (${E.status}): ${z}`)}if(_){w(!0);let z="";for await(const F of Qe(E,b.signal))if(b.signal.aborted||(z+=F.token,o(z),(k=F.usage)!=null&&k.completion_tokens&&j.recordTokens(F.usage.completion_tokens),F.done))break;if(z.length>0){const F=Math.ceil(z.length/4);j.recordTokens(F)}se.set(y,z)}else{const z=await Ze(E);o(z.text),se.set(y,z.text),(S=z.usage)!=null&&S.completion_tokens?j.recordTokens(z.usage.completion_tokens):j.recordTokens(Math.ceil(z.text.length/4))}}catch(N){if(N instanceof DOMException&&N.name==="AbortError")return;u(N instanceof Error?N.message:"AI hint request failed")}finally{b.signal.aborted||(m(!1),w(!1))}},[n,t,r]);l.useEffect(()=>{if(!n||!n.enabled||r)return;const d=setTimeout(M,i);return()=>clearTimeout(d)},[t==null?void 0:t.fieldLabel,t==null?void 0:t.fieldType,t==null?void 0:t.fieldValue,t==null?void 0:t.customPrompt,i,r,n==null?void 0:n.enabled,R.current]),l.useEffect(()=>()=>{var d;(d=A.current)==null||d.abort()},[]);const P=l.useCallback(()=>{var d;(d=A.current)==null||d.abort(),m(!1),w(!1)},[]),g=l.useCallback(()=>{if(n){const d=Be(t,n.config.privacyMode??!1);se.delete(d)}R.current+=1,M()},[n,t,M]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:c,error:p,streaming:v,abort:P,refresh:g,hint:s?{content:s}:null,fetchHint:async()=>{await M()}}}function Oa(t,a){if(t!=="auto"||!a)return t==="auto"?"top":t;const i=a.top,r=window.innerHeight-a.bottom,n=a.left,s=window.innerWidth-a.right,o=Math.max(i,r,n,s);return o===i?"top":o===r?"bottom":o===s?"right":"left"}function Ea(t){const a={position:"absolute",zIndex:9999,minWidth:200,maxWidth:320,padding:"8px 12px",borderRadius:8,fontSize:13,lineHeight:1.5,backgroundColor:"var(--ntd-ai-bg, #1e1e2e)",color:"var(--ntd-ai-fg, #cdd6f4)",border:"1px solid var(--ntd-ai-border, #45475a)",boxShadow:"0 4px 16px var(--nice-overlay-25, rgba(0, 0, 0, 0.25))",wordWrap:"break-word"};switch(t){case"top":return{...a,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6};case"bottom":return{...a,top:"100%",left:"50%",transform:"translateX(-50%)",marginTop:6};case"left":return{...a,right:"100%",top:"50%",transform:"translateY(-50%)",marginRight:6};case"right":return{...a,left:"100%",top:"50%",transform:"translateY(-50%)",marginLeft:6};default:return{...a,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6}}}const ea=Object.assign(l.forwardRef(({context:t,position:a="auto",debounceMs:i=500,showOnHover:r=!1,triggerIcon:n,className:s,style:o},c)=>{var I;const{t:m}=T.useNiceTranslation(),p=ee(),[u,v]=l.useState(!1),[w,A]=l.useState(!1),R=l.useRef(null),M=l.useRef(null),P=Z(t,{debounceMs:i,disabled:!w});l.useEffect(()=>{if(!u)return;const b=h=>{var f,k;const _=h.target;(f=R.current)!=null&&f.contains(_)||(k=M.current)!=null&&k.contains(_)||(v(!1),A(!1))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[u]),l.useEffect(()=>{if(!u)return;const b=h=>{h.key==="Escape"&&(v(!1),A(!1),P.abort())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[u,P]);const g=l.useCallback(b=>{if(b.stopPropagation(),r)return;const h=!u;v(h),A(h)},[u,r]),d=l.useCallback(()=>{r&&(v(!0),A(!0))},[r]),j=l.useCallback(()=>{r&&(v(!1),A(!1))},[r]);if(!p||!p.enabled)return null;const y=Oa(a,((I=R.current)==null?void 0:I.getBoundingClientRect())??null);return e.jsxs("span",{ref:c,className:s,style:{position:"relative",display:"inline-flex",...o},onMouseEnter:d,onMouseLeave:j,children:[e.jsx("button",{ref:R,type:"button",onClick:g,"aria-label":m("aiHintBubble.aiHint","AI hint"),"aria-expanded":u,className:"ntd-ai-trigger",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",cursor:"pointer",padding:2,borderRadius:4,color:"var(--ntd-ai-trigger-color, #a78bfa)",opacity:.7,transition:"opacity 0.2s, transform 0.2s"},children:n??e.jsx(T.NiceIcon,{name:"wand",size:16})}),u&&e.jsxs("div",{ref:M,role:"tooltip",className:"ntd-ai-popover",style:Ea(y),children:[P.loading&&!P.text&&e.jsxs("div",{className:"ntd-ai-loading",style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{display:"inline-block",width:12,height:12,border:"2px solid var(--ntd-ai-border, #45475a)",borderTopColor:"var(--ntd-ai-trigger-color, #a78bfa)",borderRadius:"50%",animation:"ntd-ai-spin 0.8s linear infinite"}}),e.jsx("span",{style:{opacity:.6},children:m("aiHintBubble.thinking","Thinking...")})]}),P.text&&e.jsxs("div",{className:"ntd-ai-content",children:[P.text,P.streaming&&e.jsx("span",{className:"ntd-ai-cursor",style:{display:"inline-block",width:2,height:"1em",backgroundColor:"var(--ntd-ai-trigger-color, #a78bfa)",marginLeft:1,animation:"ntd-ai-blink 0.8s step-end infinite",verticalAlign:"text-bottom"}})]}),P.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:P.error}),P.text&&!P.streaming&&e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:4,marginTop:6,paddingTop:6,borderTop:"1px solid var(--ntd-ai-border, #45475a)"},children:[e.jsxs("button",{type:"button",onClick:()=>P.refresh(),className:"ntd-ai-action",style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:[e.jsx(T.NiceIcon,{name:"refresh",size:12})," ",m("aiHintBubble.refresh","Refresh")]}),e.jsxs("button",{type:"button",onClick:()=>{var b;(b=navigator.clipboard)==null||b.writeText(P.text)},className:"ntd-ai-action",style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:[e.jsx(T.NiceIcon,{name:"copy",size:12})," ",m("aiHintBubble.copy","Copy")]})]})]})]})}),{displayName:"NiceAIHintBubble"});function Le(t,a,i){return{fieldLabel:t,fieldType:"text",fieldValue:a,validationRules:{...(i==null?void 0:i.maxLength)!=null?{maxLength:i.maxLength}:{},...i!=null&&i.pattern?{pattern:i.pattern}:{}},customPrompt:i!=null&&i.placeholder?`Placeholder: "${i.placeholder}". Suggest content or correct grammar.`:"Suggest content, correct grammar, or auto-complete the text."}}function ze(t,a,i){return{fieldLabel:t,fieldType:"number",fieldValue:a,validationRules:{...(i==null?void 0:i.min)!=null?{min:i.min}:{},...(i==null?void 0:i.max)!=null?{max:i.max}:{},...(i==null?void 0:i.step)!=null?{step:i.step}:{}},customPrompt:i!=null&&i.unit?`Unit: ${i.unit}. Suggest a reasonable value or range for this field.`:"Suggest a reasonable value or range for this field based on the label and constraints."}}function Me(t,a,i){return{fieldLabel:t,fieldType:i!=null&&i.multiple?"multi-select":"select",fieldValue:a,schema:i!=null&&i.options?{availableOptions:i.options.slice(0,20).map(r=>r.label)}:{},customPrompt:"Suggest the most likely selection. Explain why this option is recommended."}}function $e(t,a,i){const r=a instanceof Date?a.toISOString().split("T")[0]:a;return{fieldLabel:t,fieldType:"date",fieldValue:r,validationRules:{...i!=null&&i.min?{min:i.min}:{},...i!=null&&i.max?{max:i.max}:{},...i!=null&&i.disableWeekends?{noWeekends:!0}:{}},customPrompt:'Suggest a date. For example: "next business day", "end of month", "in 2 weeks". Explain your suggestion briefly.'}}function Pe(t,a,i){return{fieldLabel:t,fieldType:"color",fieldValue:a,schema:i!=null&&i.palette?{currentPalette:i.palette}:{},customPrompt:i!=null&&i.industry?`Industry: ${i.industry}. Suggest a color palette (3-5 hex colors) suitable for this context.`:"Suggest a color or palette of colors that works well for this context. Provide hex values."}}function Da(t,a){return{fieldLabel:t,fieldType:"data-grid",schema:{...a!=null&&a.columns?{columns:a.columns}:{},...(a==null?void 0:a.rowCount)!=null?{totalRows:a.rowCount}:{}},formContext:{...a!=null&&a.currentFilters?{filters:a.currentFilters}:{},...a!=null&&a.currentSorts?{sorts:a.currentSorts}:{}},customPrompt:"Suggest column configuration, useful filters, or highlight potential data anomalies."}}function Ba(t,a){return{fieldLabel:t,fieldType:"chart",schema:{...a!=null&&a.currentType?{chartType:a.currentType}:{},...(a==null?void 0:a.seriesCount)!=null?{series:a.seriesCount}:{},...(a==null?void 0:a.pointCount)!=null?{dataPoints:a.pointCount}:{}},customPrompt:a!=null&&a.dataDescription?`Data: ${a.dataDescription}. Suggest the best chart type and labeling strategy.`:"Suggest the most effective chart type for this data. Explain your recommendation."}}function aa(t,a){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:a},customPrompt:`User description: "${t}"
|
|
5
|
+
Parse this description and return suggested values for each field as JSON: { ${a.map(i=>`"${i.label}": "value"`).join(", ")} }`}}function ia(t,a,i,r,n){return{fieldLabel:t,fieldType:a,fieldValue:i,validationRules:n==null?void 0:n.rules,customPrompt:`Current validation error: "${r}". Provide a friendly, specific error message with an example of a valid value. Do NOT say "field is required" — instead explain what the user should enter.`}}function Fa(t,a,i){const r=l.useMemo(()=>Le(t,a,i),[t,a,i==null?void 0:i.placeholder,i==null?void 0:i.maxLength,i==null?void 0:i.pattern]);return Z(r,i)}function Ja(t,a,i){const r=l.useMemo(()=>ze(t,a,i),[t,a,i==null?void 0:i.min,i==null?void 0:i.max,i==null?void 0:i.step,i==null?void 0:i.unit]);return Z(r,i)}function qa(t,a,i){const r=l.useMemo(()=>Me(t,a,i),[t,a,i==null?void 0:i.multiple]);return Z(r,i)}function Ga(t,a,i){const r=l.useMemo(()=>$e(t,a,i),[t,a,i==null?void 0:i.min,i==null?void 0:i.max,i==null?void 0:i.disableWeekends]);return Z(r,i)}function Ua(t,a,i){const r=l.useMemo(()=>Pe(t,a,i),[t,a,i==null?void 0:i.industry]);return Z(r,i)}function Wa(t,a,i,r,n){const s=l.useMemo(()=>r?ia(t,a,i,r,n):{fieldLabel:t,fieldType:a},[t,a,i,r]);return Z(s,{...n,disabled:!r||(n==null?void 0:n.disabled)})}function Ha(t,a,i){const r=l.useMemo(()=>t?aa(t,a):{fieldLabel:"Form"},[t,a]);return Z(r,{...i,disabled:!t||(i==null?void 0:i.disabled)})}function ta(t,a,i){const n=(a==null?void 0:a.split(`
|
|
6
|
+
`))??[],s=(i==null?void 0:i.cursorLine)!=null?n.slice(Math.max(0,i.cursorLine-8),i.cursorLine+3).join(`
|
|
7
7
|
`):n.slice(0,16).join(`
|
|
8
|
-
`);return{fieldLabel:`Code editor (${
|
|
9
|
-
Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(
|
|
10
|
-
Return the ${(a==null?void 0:a.limit)??5} most semantically relevant icon names from the available set as a JSON array of strings, ordered by relevance. Prefer specific over generic names.`}}function Ja(i,a,t){const r=d.useMemo(()=>Qe(i,a,t),[i,a,t==null?void 0:t.cursorLine,t==null?void 0:t.cursorCol,t==null?void 0:t.framework]);return X(r,t)}function Ha(i,a,t){const r=d.useMemo(()=>Ze(i,a,t),[i,a,t==null?void 0:t.mode,t==null?void 0:t.locale]);return X(r,t)}function Ua(i,a){const t=d.useMemo(()=>ea(i,a),[i,a==null?void 0:a.bpm,a==null?void 0:a.key,a==null?void 0:a.duration,a==null?void 0:a.mode]);return X(t,a)}function Ga(i,a){const t=d.useMemo(()=>aa(i,a),[i,a==null?void 0:a.meshCount,a==null?void 0:a.triangleCount,a==null?void 0:a.targetDevice,a==null?void 0:a.mode]);return X(t,a)}function Wa(i,a){const t=d.useMemo(()=>ta(i,a),[i,a==null?void 0:a.width,a==null?void 0:a.height,a==null?void 0:a.mode,a==null?void 0:a.targetStyle]);return X(t,a)}function Va(i,a){const t=d.useMemo(()=>ia(i,a),[i,a==null?void 0:a.limit,a==null?void 0:a.style]);return X(t,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function ra(i,a){var s;const t=(a==null?void 0:a.mode)??"npc-decision",r=(a==null?void 0:a.genre)??"fantasy",n={"npc-decision":`You are an AI game director. The NPC "${i}" must make a decision. Available BT nodes: ${JSON.stringify((a==null?void 0:a.btStatus)??[])}. Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Return the name of the BT node to activate next, and one sentence of reasoning.`,dialogue:`You are a ${r} RPG writer. Write a short in-character dialogue line for NPC "${i}". Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Max 2 sentences, no narrative descriptions.`,"procedural-level":`You are a ${r} game designer. Suggest a procedural level layout for a zone containing "${i}". Describe room count, enemy placement, loot, and one unique mechanic. Keep it under 150 words.`,"quest-description":`You are a ${r} quest designer. Write a compelling quest description involving "${i}". Include: objective, giver NPC, rewards, and a short flavour paragraph. Keep it under 120 words.`,"item-description":`You are a ${r} lore writer. Write a short item description for an item related to "${i}". Include: item name, rarity, flavour text, and one special property. Keep it under 80 words.`};return{fieldLabel:i,fieldType:`game-engine:${t}`,fieldValue:a==null?void 0:a.gameState,customPrompt:n[t],schema:{genre:r,mode:t,btNodes:(s=a==null?void 0:a.btStatus)==null?void 0:s.map(o=>o.node)}}}function Ka(i,a){const t=d.useMemo(()=>ra(i,a),[i,a==null?void 0:a.mode,a==null?void 0:a.genre,JSON.stringify(a==null?void 0:a.btStatus),JSON.stringify(a==null?void 0:a.gameState)]);return X(t,a)}function na(i,a,t){const r=(t==null?void 0:t.mode)??"layout",n=(t==null?void 0:t.diagramType)??"flowchart",s={layout:`You are a diagram layout optimizer. Given this ${n} with ${i.length} nodes and ${a.length} edges, suggest optimal positions for each node to minimize edge crossings and improve readability. Return JSON: { suggestions: [{ id: string, x: number, y: number, reason: string }] }. Consider flow direction (top-to-bottom or left-to-right) and grouping related nodes.`,structure:`You are a diagram analyst. Analyze this ${n} structure. Identify: 1) Missing connections, 2) Potential bottlenecks, 3) Orphan nodes, 4) Cycles or loops. Return JSON: { issues: [{ type: string, description: string, nodeIds: string[] }], score: number }`,simplify:`You are a diagram simplifier. Suggest how to simplify this ${n} while preserving meaning. Identify: nodes that could be merged, redundant edges, or overly complex branches. Return JSON: { simplifications: [{ action: 'merge'|'remove'|'group', ids: string[], reason: string }] }`,group:`You are a diagram organizer. Suggest logical groupings for nodes in this ${n}. Consider semantic relationships, data flow patterns, and visual clustering. Return JSON: { groups: [{ name: string, nodeIds: string[], color?: string }] }`},o=i.map(h=>{var p;return{id:h.id,type:h.type,label:(p=h.label)==null?void 0:p.slice(0,30),pos:[Math.round(h.x),Math.round(h.y)]}}),c=a.map(h=>({id:h.id,src:h.source,tgt:h.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:o,edges:c}),schema:{diagramType:n,mode:r,nodeCount:i.length,edgeCount:a.length,containerSize:t==null?void 0:t.containerSize},customPrompt:s[r]}}function Ya(i,a,t){const r=d.useMemo(()=>na(i,a,t),[JSON.stringify(i),JSON.stringify(a),t==null?void 0:t.mode,t==null?void 0:t.diagramType]);return X(r,{...t,disabled:i.length===0||(t==null?void 0:t.disabled)})}function sa(i,a){const t=(a==null?void 0:a.mode)??"generate",r=(a==null?void 0:a.presentationType)??"business",n=(a==null?void 0:a.duration)??15,s=Math.ceil(n/2),o={generate:`You are a presentation designer. Create a ${r} presentation outline based on: "${i}". Target audience: ${(a==null?void 0:a.audience)??"general"}. Duration: ${n} minutes (~${s} slides). Return JSON: { title: string, slides: [{ title: string, layout: 'title'|'content'|'two-column'|'chart'|'image', bullets?: string[], chartType?: string, speakerNotes?: string }] }. Include: clear slide titles, 3-5 bullet points per content slide, and brief speaker notes.`,summarize:`You are a presentation optimizer. Summarize this presentation to be more concise: "${i}". Reduce slide count by 30% while preserving key messages. Return JSON: { summary: string, reducedSlides: [{ title: string, keyPoints: string[] }] }`,expand:`You are a presentation expert. Expand this brief outline into a detailed presentation: "${i}". Add supporting details, examples, and transitions. Target: ${s} slides. Return JSON: { slides: [{ title: string, content: string, transitions?: string, animations?: string[] }] }`,improve:`You are a presentation coach. Review and improve this presentation structure: "${i}". Suggest: better flow, stronger opening/closing, clearer data visualization. Return JSON: { improvements: [{ slide: number, issue: string, suggestion: string }], score: number }`};return{fieldLabel:`Presentation (${r})`,fieldType:`presentation:${t}`,fieldValue:i,schema:{presentationType:r,mode:t,duration:n,slideCount:s,audience:a==null?void 0:a.audience,hasData:(a==null?void 0:a.dataContext)!=null},customPrompt:o[t]}}function Xa(i,a){const t=d.useMemo(()=>sa(i,a),[i,a==null?void 0:a.mode,a==null?void 0:a.presentationType,a==null?void 0:a.duration,a==null?void 0:a.audience]);return X(t,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function ca(i,a){var n;const t=(a==null?void 0:a.mode)??"all",r={alignment:"Analyze element alignment on this slide. Suggest adjustments to create visual harmony. Return JSON: { suggestions: [{ elementIndex: number, issue: string, fixX?: number, fixY?: number }] }",contrast:"Analyze color contrast and readability. Suggest improvements for accessibility (WCAG AA). Return JSON: { suggestions: [{ area: string, currentContrast: number, suggestedFix: string }] }",spacing:"Analyze whitespace and element spacing. Apply the rule of thirds and consistent margins. Return JSON: { suggestions: [{ elementIndex: number, issue: string, suggestedMargin: number }] }",typography:"Analyze typography: hierarchy, font sizes, line heights, readability. Return JSON: { suggestions: [{ area: string, issue: string, suggestedFontSize?: number }] }",all:"Perform a complete design review of this slide. Check alignment, contrast, spacing, and typography. Return JSON: { score: number, suggestions: [{ category: string, issue: string, fix: string }] }. Prioritize issues by impact on visual clarity."};return{fieldLabel:i.title??"Slide Design",fieldType:`slide-design:${t}`,fieldValue:JSON.stringify(i),schema:{mode:t,hasElements:(((n=i.elements)==null?void 0:n.length)??0)>0,layout:i.layout,brandColors:a==null?void 0:a.brandColors},customPrompt:r[t]}}function Qa(i,a){const t=d.useMemo(()=>ca(i,a),[JSON.stringify(i),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return X(t,a)}function Za(i,a,t){const r=d.forwardRef((n,s)=>{const{aiEnabled:o=!0,aiPosition:c="right",aiPrompt:h,aiDebounceMs:p=500,aiShowOnHover:m=!1,aiTriggerIcon:b,...w}=n,k=d.useMemo(()=>{const M=a(w);return h&&(M.customPrompt=h),M},[w,h]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(i,{...w,ref:s}),o&&e.jsx(Ie,{context:k,position:c,debounceMs:p,showOnHover:m,triggerIcon:b})]})});return r.displayName=t??`withAIHint(${i.displayName??i.name??"Component"})`,r}function et(i){return Re(i.label??"Text",i.value,{placeholder:i.placeholder,maxLength:i.maxLength})}function at(i){return ze(i.label??"Number",i.value,{min:i.min,max:i.max,step:i.step})}function tt(i){return Me(i.label??"Select",i.value,{options:i.options,multiple:i.multiple})}function it(i){return Le(i.label??"Date",i.value,{min:i.min,max:i.max})}function rt(i){return Pe(i.label??"Color",i.value)}const nt=i=>({id:A.createId(),name:i,type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date}),we={classification:[{id:"logistic-regression",key:"mlStudio.alg.logisticRegression",name:"Logistic Regression"},{id:"random-forest",key:"mlStudio.alg.randomForest",name:"Random Forest"},{id:"gradient-boosting",key:"mlStudio.alg.gradientBoosting",name:"Gradient Boosting"},{id:"svm",key:"mlStudio.alg.svm",name:"Support Vector Machine"},{id:"neural-network",key:"mlStudio.alg.neuralNetwork",name:"Neural Network"},{id:"xgboost",key:"mlStudio.alg.xgboost",name:"XGBoost"}],regression:[{id:"linear-regression",key:"mlStudio.alg.linearRegression",name:"Linear Regression"},{id:"ridge",key:"mlStudio.alg.ridge",name:"Ridge Regression"},{id:"lasso",key:"mlStudio.alg.lasso",name:"Lasso Regression"},{id:"random-forest-reg",key:"mlStudio.alg.randomForest",name:"Random Forest"},{id:"gradient-boosting-reg",key:"mlStudio.alg.gradientBoosting",name:"Gradient Boosting"}],clustering:[{id:"kmeans",key:"mlStudio.alg.kmeans",name:"K-Means"},{id:"dbscan",key:"mlStudio.alg.dbscan",name:"DBSCAN"},{id:"hierarchical",key:"mlStudio.alg.hierarchical",name:"Hierarchical Clustering"}]},st=Object.values(we).flat(),De=(i,a)=>{const t=st.find(r=>r.id===i);return t?a(t.key,t.name):i},ct=[["classification","mlStudio.type.classification","Classification"],["regression","mlStudio.type.regression","Regression"],["clustering","mlStudio.type.clustering","Clustering"],["object-detection","mlStudio.type.objectDetection","Object Detection"],["nlp","mlStudio.type.nlp","NLP"],["time-series","mlStudio.type.timeSeries","Time Series"]],ot=[["data","mlStudio.tab.data","Data"],["experiments","mlStudio.tab.experiments","Experiments"],["models","mlStudio.tab.models","Models"],["deploy","mlStudio.tab.deploy","Deploy"]],lt=[["numeric","mlStudio.colType.numeric","Numeric"],["categorical","mlStudio.colType.categorical","Categorical"],["text","mlStudio.colType.text","Text"],["datetime","mlStudio.colType.datetime","DateTime"],["boolean","mlStudio.colType.boolean","Boolean"],["embedding","mlStudio.colType.embedding","Embedding"]],dt={train:["mlStudio.split.train","Train"],validation:["mlStudio.split.validation","Validation"],test:["mlStudio.split.test","Test"]},ut={pending:["mlStudio.experimentStatus.pending","Pending"],running:["mlStudio.experimentStatus.running","Running"],completed:["mlStudio.experimentStatus.completed","Completed"],failed:["mlStudio.experimentStatus.failed","Failed"],cancelled:["mlStudio.experimentStatus.cancelled","Cancelled"]},pt={draft:["mlStudio.modelStatus.draft","Draft"],registered:["mlStudio.modelStatus.registered","Registered"],staging:["mlStudio.modelStatus.staging","Staging"],production:["mlStudio.modelStatus.production","Production"],archived:["mlStudio.modelStatus.archived","Archived"]},mt={pending:["mlStudio.deploymentStatus.pending","Pending"],deploying:["mlStudio.deploymentStatus.deploying","Deploying"],running:["mlStudio.deploymentStatus.running","Running"],stopped:["mlStudio.deploymentStatus.stopped","Stopped"],failed:["mlStudio.deploymentStatus.failed","Failed"]},se=(i,a,t)=>i?t(i[0],i[1]):a,gt=new Set(["accuracy","precision","recall","f1-score","auc-roc"]),Be=({name:i,value:a},t)=>gt.has(i)?`${(a*100).toLocaleString(t,{minimumFractionDigits:1,maximumFractionDigits:1})}%`:a.toLocaleString(t,{maximumFractionDigits:3}),ht=[{target:".nice-ml-studio",titleKey:"tutorial.mlStudio.intro.title",title:"ML studio",contentKey:"tutorial.mlStudio.intro.content",content:"Work through the tabs: prepare datasets, run experiments, compare and pick models, then deploy the best one.",placement:"auto"}],ft=({project:i,onProjectChange:a,onExperimentRun:t,onModelDeploy:r,onModelDownload:n,className:s="",tutorial:o})=>{var Y;const{t:c,lang:h}=A.useNiceTranslation(),[p,m]=d.useState(()=>i||nt(c("mlStudio.newProject","New ML Project"))),[b,w]=d.useState("data"),[k,M]=d.useState(null),[C,O]=d.useState(null),[_,l]=d.useState(null),[y,S]=d.useState(!1),[f,j]=d.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),g=d.useRef(p),x=d.useCallback(u=>{const R=g.current,B={...R,...typeof u=="function"?u(R):u,updatedAt:new Date};g.current=B,m(B),a==null||a(B)},[a]),v=async u=>{for(const R of Array.from(u)){const B={id:A.createId(),name:R.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:R.name},size:R.size,rowCount:0,columns:[],splits:[{name:"train",ratio:.8,rowCount:0},{name:"validation",ratio:.1,rowCount:0},{name:"test",ratio:.1,rowCount:0}],createdAt:new Date};if(R.name.endsWith(".csv")){const q=(await R.text()).split(`
|
|
11
|
-
`),G=q[0].split(",").map(Q=>Q.trim());B.rowCount=q.length-1,B.columns=G.map(Q=>({name:Q,type:"text",nullable:!0,unique:0,missing:0})),B.splits=B.splits.map(Q=>({...Q,rowCount:Math.floor(B.rowCount*Q.ratio)}))}x(H=>({datasets:[...H.datasets,B]}))}},T=u=>{x({datasets:p.datasets.filter(R=>R.id!==u)}),k===u&&M(null)},I=async()=>{if(!f.algorithm||!k)return;const u={id:A.createId(),name:c("mlStudio.experimentName","Experiment {n}").replace("{n}",String(p.experiments.length+1)),status:"pending",config:f,metrics:[],artifacts:[],logs:[]},R=H=>x(q=>({experiments:q.experiments.map(G=>G.id===u.id?{...G,...H}:G)}));if(x(H=>({experiments:[...H.experiments,u]})),S(!1),!t)return;const B=new Date;R({status:"running",startedAt:B});try{const H=await t(u),q=typeof H=="object"&&H!==null?H:{},G=new Date;R({status:"completed",completedAt:G,duration:q.duration??(G.getTime()-B.getTime())/1e3,metrics:q.metrics??[],artifacts:q.artifacts??[],logs:q.logs??[]})}catch{R({status:"failed"})}},N=u=>{const R=p.experiments.find(q=>q.id===u);if(!R)return;const B=R.artifacts.filter(q=>q.type==="model"),H={id:A.createId(),name:c("mlStudio.modelFrom","Model from {name}").replace("{name}",R.name),version:"1.0.0",algorithm:R.config.algorithm,experimentId:u,status:"registered",metrics:R.metrics,size:B.reduce((q,G)=>q+G.size,0),artifacts:B,deployments:[],createdAt:new Date};x(q=>({models:[...q.models,H]}))},P=async u=>{const R=p.models.find(H=>H.id===u);if(!R||!r)return;const B=await r(R);x(H=>({models:H.models.map(q=>q.id===u?{...q,status:"production",deployments:[...q.deployments,B]}:q)}))},$=u=>u<1024?`${u} B`:u<1024*1024?`${(u/1024).toFixed(1)} KB`:u<1024*1024*1024?`${(u/1024/1024).toFixed(1)} MB`:`${(u/1024/1024/1024).toFixed(1)} GB`,D=u=>{switch(u){case"completed":case"production":case"running":return"status-badge--success";case"pending":case"staging":return"status-badge--pending";case"failed":return"status-badge--error";default:return""}},F=e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:p.name,onChange:u=>x({name:u.target.value}),className:"project-name-input","aria-label":c("mlStudio.projectName","Project name")}),e.jsx("select",{value:p.type,onChange:u=>x({type:u.target.value}),className:"project-type-select","aria-label":c("mlStudio.projectType","Project type"),children:ct.map(([u,R,B])=>e.jsx("option",{value:u,children:c(R,B)},u))})]}),U=e.jsx("div",{className:"header__tabs",children:ot.map(([u,R,B])=>e.jsx("button",{className:`tab-button ${b===u?"tab-button--active":""}`,onClick:()=>w(u),children:c(R,B)},u))}),W=e.jsxs("div",{className:"ml-studio__content",children:[b==="data"&&e.jsxs("div",{className:"data-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:c("mlStudio.datasets","Datasets")}),e.jsxs("label",{className:"upload-button",children:[e.jsx("input",{type:"file",multiple:!0,accept:".csv,.json,.parquet",onChange:u=>u.target.files&&v(u.target.files),hidden:!0}),e.jsx(A.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.uploadDataset","Upload Dataset")]})]}),e.jsx("div",{className:"datasets-grid",children:p.datasets.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("p",{children:c("mlStudio.noDatasets","No datasets uploaded yet")}),e.jsx("p",{className:"hint",children:c("mlStudio.noDatasetsHint","Upload CSV, JSON, or Parquet files to get started")})]}):p.datasets.map(u=>e.jsxs("div",{className:`dataset-card ${k===u.id?"dataset-card--selected":""}`,onClick:()=>M(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"dataset-icon",children:e.jsx(A.NiceIcon,{name:"folder",size:16})}),e.jsx("h3",{children:u.name}),e.jsx("button",{className:"remove-button","aria-label":c("mlStudio.removeDataset","Remove dataset"),onClick:R=>{R.stopPropagation(),T(u.id)},children:e.jsx(A.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"card-stats",children:[e.jsx("span",{children:c("mlStudio.rows","{count} rows").replace("{count}",u.rowCount.toLocaleString(h))}),e.jsx("span",{children:c("mlStudio.columnCount","{count} columns").replace("{count}",String(u.columns.length))}),e.jsx("span",{children:$(u.size)})]}),e.jsx("div",{className:"splits-bar",children:u.splits.map(R=>e.jsx("div",{className:`split split--${R.name}`,style:{width:`${R.ratio*100}%`},title:`${se(dt[R.name],R.name,c)}: ${(R.ratio*100).toFixed(0)}%`},R.name))})]},u.id))}),k&&e.jsx("div",{className:"dataset-details",children:(()=>{const u=p.datasets.find(R=>R.id===k);return u?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:c("mlStudio.columns","Columns")}),e.jsxs("table",{className:"columns-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:c("mlStudio.col.name","Name")}),e.jsx("th",{children:c("mlStudio.col.type","Type")}),e.jsx("th",{children:c("mlStudio.col.missing","Missing")}),e.jsx("th",{children:c("mlStudio.col.unique","Unique")})]})}),e.jsx("tbody",{children:u.columns.map(R=>e.jsxs("tr",{children:[e.jsx("td",{children:R.name}),e.jsx("td",{children:e.jsx("select",{value:R.type,"aria-label":c("mlStudio.col.type","Type"),onChange:B=>{x({datasets:p.datasets.map(H=>H.id===u.id?{...H,columns:H.columns.map(q=>q.name===R.name?{...q,type:B.target.value}:q)}:H)})},children:lt.map(([B,H,q])=>e.jsx("option",{value:B,children:c(H,q)},B))})}),e.jsx("td",{children:R.missing}),e.jsx("td",{children:R.unique})]},R.name))})]})]}):null})()})]}),b==="experiments"&&e.jsxs("div",{className:"experiments-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:c("mlStudio.tab.experiments","Experiments")}),e.jsxs("button",{className:"primary-button",onClick:()=>S(!0),disabled:p.datasets.length===0,children:[e.jsx(A.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.newExperiment","New Experiment")]})]}),y&&e.jsxs("div",{className:"new-experiment-form",children:[e.jsx("h3",{children:c("mlStudio.configureExperiment","Configure Experiment")}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:[c("mlStudio.dataset","Dataset"),e.jsxs("select",{value:k||"",onChange:u=>M(u.target.value),children:[e.jsx("option",{value:"",children:c("mlStudio.selectDataset","Select dataset...")}),p.datasets.map(u=>e.jsx("option",{value:u.id,children:u.name},u.id))]})]}),e.jsxs("label",{children:[c("mlStudio.algorithm","Algorithm"),e.jsxs("select",{value:f.algorithm,onChange:u=>j({...f,algorithm:u.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectAlgorithm","Select algorithm...")}),(we[p.type]||we.classification).map(u=>e.jsx("option",{value:u.id,children:c(u.key,u.name)},u.id))]})]}),k&&e.jsxs("label",{children:[c("mlStudio.targetColumn","Target Column"),e.jsxs("select",{value:f.targetColumn||"",onChange:u=>j({...f,targetColumn:u.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectTarget","Select target...")}),(Y=p.datasets.find(u=>u.id===k))==null?void 0:Y.columns.map(u=>e.jsx("option",{value:u.name,children:u.name},u.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>S(!1),children:c("cancel","Cancel")}),e.jsx("button",{className:"primary-button",onClick:I,disabled:!f.algorithm||!k,children:c("mlStudio.runExperiment","Run Experiment")})]})]}),e.jsx("div",{className:"experiments-list",children:p.experiments.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"flask",size:32})}),e.jsx("p",{children:c("mlStudio.noExperiments","No experiments yet")}),e.jsx("p",{className:"hint",children:c("mlStudio.noExperimentsHint","Create an experiment to train and evaluate models")})]}):p.experiments.map(u=>e.jsxs("div",{className:`experiment-card ${C===u.id?"experiment-card--selected":""}`,onClick:()=>O(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:u.name}),e.jsx("span",{className:`status-badge ${D(u.status)}`,children:se(ut[u.status],u.status,c)})]}),e.jsxs("div",{className:"card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",De(u.config.algorithm,c))}),u.duration!==void 0&&e.jsx("span",{children:c("mlStudio.duration","Duration: {seconds}s").replace("{seconds}",String(Math.round(u.duration)))})]}),u.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:u.metrics.slice(0,3).map(R=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:R.name}),e.jsx("span",{className:"metric-value",children:Be(R,h)})]},R.name))}),u.status==="completed"&&e.jsx("button",{className:"action-button",onClick:R=>{R.stopPropagation(),N(u.id)},children:c("mlStudio.registerModel","Register Model")})]},u.id))})]}),b==="models"&&e.jsxs("div",{className:"models-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:c("mlStudio.tab.models","Models")})}),e.jsx("div",{className:"models-list",children:p.models.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"wand",size:32})}),e.jsx("p",{children:c("mlStudio.noModels","No models registered yet")}),e.jsx("p",{className:"hint",children:c("mlStudio.noModelsHint","Complete experiments and register models")})]}):p.models.map(u=>e.jsxs("div",{className:`model-card ${_===u.id?"model-card--selected":""}`,onClick:()=>l(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:u.name}),e.jsx("span",{className:`status-badge ${D(u.status)}`,children:se(pt[u.status],u.status,c)})]}),e.jsxs("div",{className:"card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",De(u.algorithm,c))}),e.jsx("span",{children:c("mlStudio.version","Version: {version}").replace("{version}",u.version)}),u.size>0&&e.jsx("span",{children:c("mlStudio.size","Size: {size}").replace("{size}",$(u.size))})]}),u.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:u.metrics.slice(0,3).map(R=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:R.name}),e.jsx("span",{className:"metric-value",children:Be(R,h)})]},R.name))}),e.jsxs("div",{className:"card-actions",children:[e.jsx("button",{className:"action-button",onClick:R=>{R.stopPropagation(),n==null||n(u)},disabled:!n,title:n?void 0:c("mlStudio.downloadNotSetUp","Downloading models is not set up"),children:c("download","Download")}),e.jsx("button",{className:"action-button action-button--primary",onClick:R=>{R.stopPropagation(),P(u.id)},disabled:u.status==="production"||!r,title:r?void 0:c("mlStudio.deployNotSetUp","Deploying models is not set up"),children:u.status==="production"?c("mlStudio.deployed","Deployed"):c("mlStudio.deploy","Deploy")})]})]},u.id))})]}),b==="deploy"&&e.jsxs("div",{className:"deploy-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:c("mlStudio.deployments","Deployments")})}),e.jsx("div",{className:"deployments-list",children:p.models.filter(u=>u.deployments.length>0).length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"rocket",size:32})}),e.jsx("p",{children:c("mlStudio.noDeployments","No deployments yet")}),e.jsx("p",{className:"hint",children:c("mlStudio.noDeploymentsHint","Deploy a model to create inference endpoints")})]}):p.models.filter(u=>u.deployments.length>0).flatMap(u=>u.deployments.map(R=>({model:u,deployment:R}))).map(({model:u,deployment:R})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:R.name}),e.jsx("span",{className:`status-badge ${D(R.status)}`,children:se(mt[R.status],R.status,c)})]}),e.jsxs("div",{className:"card-meta",children:[e.jsx("span",{children:c("mlStudio.modelValue","Model: {name}").replace("{name}",u.name)}),e.jsx("span",{children:c("mlStudio.endpoint","Endpoint: {url}").replace("{url}",R.endpoint)})]}),e.jsxs("div",{className:"resources-info",children:[e.jsx("span",{children:c("mlStudio.cpu","CPU: {count} cores").replace("{count}",String(R.resources.cpu))}),e.jsx("span",{children:c("mlStudio.memory","Memory: {gb} GB").replace("{gb}",String(R.resources.memory))}),e.jsx("span",{children:c("mlStudio.replicas","Replicas: {count}").replace("{count}",String(R.resources.replicas))})]})]},R.id))})]})]});return e.jsxs("div",{className:`nice-ml-studio ${s}`,style:{position:"relative"},children:[e.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:e.jsx(A.NiceTutorialButton,{steps:A.resolveTutorial(o,ht)})}),e.jsx(Aa.NiceAppShell,{flush:!0,menubar:F,toolbar:U,children:W})]})},xt={id:A.createId(),name:"New Labeling Project",type:"classification",dataType:"image",status:"setup",labelSchema:{classes:[],attributes:[]},items:[],collaborators:[],statistics:{totalItems:0,labeled:0,reviewed:0,approved:0,byClass:[]},createdAt:new Date},Fe=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)"],bt={label:"Label",schema:"Schema",review:"Review",export:"Export"},yt=({project:i,onProjectChange:a,onLabelSave:t,onExport:r,className:n=""})=>{var ie;const{t:s}=A.useNiceTranslation(),[o,c]=d.useState(i||xt),[h,p]=d.useState("label"),[m,b]=d.useState(0),[w,k]=d.useState(null),[M,C]=d.useState("select"),[O,_]=d.useState(!1),[l,y]=d.useState(null),[S,f]=d.useState(1),[j,g]=d.useState(!1),[x,v]=d.useState("all"),T=d.useRef(null),I=d.useRef(null),N=o.items[m];d.useEffect(()=>{i&&c(i)},[i]);const P=d.useCallback(z=>{const E={...o,...z};E.statistics={totalItems:E.items.length,labeled:E.items.filter(L=>L.status!=="pending").length,reviewed:E.items.filter(L=>L.status==="review"||L.status==="approved").length,approved:E.items.filter(L=>L.status==="approved").length,byClass:E.labelSchema.classes.map(L=>({classId:L.id,count:E.items.flatMap(J=>J.labels).filter(J=>J.classId===L.id).length}))},c(E),a==null||a(E)},[o,a]),$=()=>{const z={id:A.createId(),name:`Class ${o.labelSchema.classes.length+1}`,color:Fe[o.labelSchema.classes.length%Fe.length],shortcut:String(o.labelSchema.classes.length+1)};P({labelSchema:{...o.labelSchema,classes:[...o.labelSchema.classes,z]}})},D=z=>{P({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.filter(E=>E.id!==z)},items:o.items.map(E=>({...E,labels:E.labels.filter(L=>L.classId!==z)}))})},F=(z,E)=>{P({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.map(L=>L.id===z?{...L,...E}:L)}})},U=(z,E)=>{if(!N)return;const L={id:A.createId(),classId:z,type:o.type==="classification"?"class":o.type==="bounding-box"?"bbox":"class",data:E||{},createdBy:"current-user",createdAt:new Date},J={...N,labels:[...N.labels,L],status:"labeled"};P({items:o.items.map(V=>V.id===N.id?J:V)}),t==null||t(J)},W=z=>{if(!N)return;const E={...N,labels:N.labels.filter(L=>L.id!==z),status:N.labels.length<=1?"pending":"labeled"};P({items:o.items.map(L=>L.id===N.id?E:L)})},Y=z=>{var V;if(M!=="bbox"||!w)return;const E=(V=T.current)==null?void 0:V.getBoundingClientRect();if(!E)return;const L=(z.clientX-E.left)/S,J=(z.clientY-E.top)/S;_(!0),y({x:L,y:J,width:0,height:0})},u=z=>{var V;if(!O||!l)return;const E=(V=T.current)==null?void 0:V.getBoundingClientRect();if(!E)return;const L=(z.clientX-E.left)/S,J=(z.clientY-E.top)/S;y({...l,width:L-l.x,height:J-l.y})},R=()=>{!O||!l||!w||(_(!1),Math.abs(l.width)>10&&Math.abs(l.height)>10&&U(w,{x:l.width<0?l.x+l.width:l.x,y:l.height<0?l.y+l.height:l.y,width:Math.abs(l.width),height:Math.abs(l.height)}),y(null))},B=z=>{const E=x==="all"?o.items:o.items.filter(J=>J.status===x),L=E.findIndex(J=>J.id===(N==null?void 0:N.id));if(z==="prev"&&L>0){const J=E[L-1];b(o.items.findIndex(V=>V.id===J.id))}else if(z==="next"&&L<E.length-1){const J=E[L+1];b(o.items.findIndex(V=>V.id===J.id))}},H=()=>{if(!N)return;const z={...N,status:"approved"};P({items:o.items.map(E=>E.id===N.id?z:E)}),B("next")},q=()=>{if(!N)return;const z={...N,status:"rejected"};P({items:o.items.map(E=>E.id===N.id?z:E)}),B("next")},G=async z=>{r&&await r(z)};d.useEffect(()=>{const z=E=>{const L=E.target instanceof HTMLElement?E.target:null;if(h!=="label"||E.defaultPrevented||E.ctrlKey||E.metaKey||E.altKey||L!=null&&L.isContentEditable||L&&/^(INPUT|TEXTAREA|SELECT)$/.test(L.tagName)||E.key==="Enter"&&(L!=null&&L.closest("button, a")))return;const J=E.key,V=o.labelSchema.classes.find(re=>re.shortcut===J);V&&(o.type==="classification"?(U(V.id),B("next")):k(V.id)),E.key==="ArrowLeft"||E.key==="a"?B("prev"):(E.key==="ArrowRight"||E.key==="d")&&B("next"),E.key==="Enter"?H():E.key==="Backspace"&&q()};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[h,N,o.labelSchema.classes,o.type]);const Q=z=>{switch(z){case"approved":return"var(--nice-success, #22c55e)";case"labeled":return"var(--nice-primary, #3b82f6)";case"review":return"var(--nice-warning, #f59e0b)";case"rejected":return"var(--nice-danger, #ef4444)";default:return"var(--nice-text-secondary, #6b7280)"}};return e.jsxs("div",{className:`nice-data-labeler ${n}`,children:[e.jsxs("header",{className:"labeler__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:o.name,onChange:z=>P({name:z.target.value}),className:"project-name-input"}),e.jsxs("div",{className:"progress-bar",children:[e.jsx("div",{className:"progress-fill",style:{width:`${o.statistics.labeled/Math.max(o.statistics.totalItems,1)*100}%`}}),e.jsx("span",{className:"progress-text",children:s("dataLabeler.progress","{labeled} / {total} labeled").replace("{labeled}",String(o.statistics.labeled)).replace("{total}",String(o.statistics.totalItems))})]})]}),e.jsx("div",{className:"header__tabs",children:["label","schema","review","export"].map(z=>e.jsx("button",{className:`tab-button ${h===z?"tab-button--active":""}`,onClick:()=>p(z),children:s(`dataLabeler.tab.${z}`,bt[z])},z))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>g(!j),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"labeler__content",children:[h==="label"&&e.jsxs("div",{className:"label-panel",children:[e.jsxs("div",{className:"label-toolbar",children:[e.jsxs("div",{className:"tool-group",children:[e.jsxs("button",{className:`tool-button ${M==="select"?"tool-button--active":""}`,onClick:()=>C("select"),children:[e.jsx(A.NiceIcon,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(o.type==="bounding-box"||o.type==="multi-label")&&e.jsxs("button",{className:`tool-button ${M==="bbox"?"tool-button--active":""}`,onClick:()=>C("bbox"),children:[e.jsx(A.NiceIcon,{name:"square",size:14})," Box"]}),o.type==="polygon"&&e.jsxs("button",{className:`tool-button ${M==="polygon"?"tool-button--active":""}`,onClick:()=>C("polygon"),children:[e.jsx(A.NiceIcon,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{"aria-label":s("dataLabeler.zoomOut","Zoom out"),onClick:()=>f(Math.max(.25,S-.25)),children:e.jsx(A.NiceIcon,{name:"minus",size:14})}),e.jsxs("span",{children:[Math.round(S*100),"%"]}),e.jsx("button",{"aria-label":s("dataLabeler.zoomIn","Zoom in"),onClick:()=>f(Math.min(4,S+.25)),children:e.jsx(A.NiceIcon,{name:"plus",size:14})})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsxs("button",{onClick:()=>B("prev"),disabled:m===0,children:[e.jsx(A.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[m+1," / ",o.items.length]}),e.jsxs("button",{onClick:()=>B("next"),disabled:m>=o.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx(A.NiceIcon,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:I,children:N?e.jsxs(e.Fragment,{children:[N.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:N.data.url,alt:s("dataLabeler.labelingItem","Labeling item"),className:"labeling-image",style:{transform:`scale(${S})`}}),e.jsx("canvas",{ref:T,className:"labeling-canvas",onMouseDown:Y,onMouseMove:u,onMouseUp:R,onMouseLeave:R,style:{transform:`scale(${S})`,cursor:M==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${S})`},children:[N.labels.filter(z=>z.type==="bbox"&&z.data.x!==void 0).map(z=>{const E=o.labelSchema.classes.find(L=>L.id===z.classId);return e.jsxs("div",{className:"bbox-annotation",style:{left:z.data.x,top:z.data.y,width:z.data.width,height:z.data.height,borderColor:(E==null?void 0:E.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(E==null?void 0:E.color)||"var(--nice-danger, #ff0000)"},children:E==null?void 0:E.name}),e.jsx("button",{className:"bbox-remove","aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>W(z.id),children:e.jsx(A.NiceIcon,{name:"close",size:12})})]},z.id)}),l&&e.jsx("div",{className:"bbox-drawing",style:{left:l.width<0?l.x+l.width:l.x,top:l.height<0?l.y+l.height:l.y,width:Math.abs(l.width),height:Math.abs(l.height),borderColor:(ie=o.labelSchema.classes.find(z=>z.id===w))==null?void 0:ie.color}})]})]}),N.data.type==="text"&&e.jsx("div",{className:"text-labeling",children:e.jsx("p",{className:"text-content",children:N.data.text})})]}):e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"clipboard",size:32})}),e.jsx("p",{children:s("dataLabeler.noItemsToLabel","No items to label")})]})}),e.jsxs("aside",{className:"class-sidebar",children:[e.jsx("h3",{children:s("dataLabeler.classes","Classes")}),e.jsx("div",{className:"class-list",children:o.labelSchema.classes.map(z=>e.jsxs("button",{className:`class-button ${w===z.id?"class-button--active":""}`,style:{borderLeftColor:z.color},onClick:()=>{o.type==="classification"?(U(z.id),B("next")):k(z.id)},children:[e.jsx("span",{className:"class-color",style:{backgroundColor:z.color}}),e.jsx("span",{className:"class-name",children:z.name}),z.shortcut&&e.jsx("span",{className:"class-shortcut",children:z.shortcut})]},z.id))}),N&&N.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),N.labels.map(z=>{const E=o.labelSchema.classes.find(L=>L.id===z.classId);return e.jsxs("div",{className:"label-item",children:[e.jsx("span",{className:"label-color",style:{backgroundColor:E==null?void 0:E.color}}),e.jsx("span",{className:"label-name",children:E==null?void 0:E.name}),e.jsx("button",{"aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>W(z.id),children:e.jsx(A.NiceIcon,{name:"close",size:14})})]},z.id)})]}),h==="label"&&N&&e.jsxs("div",{className:"label-actions",children:[e.jsxs("button",{className:"approve-button",onClick:H,children:[e.jsx(A.NiceIcon,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"reject-button",onClick:q,children:[e.jsx(A.NiceIcon,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),h==="schema"&&e.jsxs("div",{className:"schema-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:s("dataLabeler.labelSchema","Label Schema")}),e.jsxs("button",{className:"primary-button",onClick:$,children:[e.jsx(A.NiceIcon,{name:"plus",size:14})," ",s("dataLabeler.addClass","Add Class")]})]}),e.jsxs("div",{className:"schema-settings",children:[e.jsxs("label",{children:[s("dataLabeler.labelingType","Labeling Type"),e.jsxs("select",{value:o.type,onChange:z=>P({type:z.target.value}),children:[e.jsx("option",{value:"classification",children:s("dataLabeler.singleClassification","Single Classification")}),e.jsx("option",{value:"multi-label",children:s("dataLabeler.multiLabelClassification","Multi-Label Classification")}),e.jsx("option",{value:"bounding-box",children:s("dataLabeler.boundingBox","Bounding Box")}),e.jsx("option",{value:"polygon",children:s("dataLabeler.polygon","Polygon")}),e.jsx("option",{value:"segmentation",children:s("dataLabeler.segmentation","Segmentation")}),e.jsx("option",{value:"ner",children:s("dataLabeler.namedEntityRecognition","Named Entity Recognition")})]})]}),e.jsxs("label",{children:[s("dataLabeler.dataType","Data Type"),e.jsxs("select",{value:o.dataType,onChange:z=>P({dataType:z.target.value}),children:[e.jsx("option",{value:"image",children:s("dataLabeler.image","Image")}),e.jsx("option",{value:"text",children:s("dataLabeler.text","Text")}),e.jsx("option",{value:"audio",children:s("dataLabeler.audio","Audio")}),e.jsx("option",{value:"video",children:s("dataLabeler.video","Video")})]})]})]}),e.jsx("div",{className:"classes-list",children:o.labelSchema.classes.map((z,E)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:z.color,onChange:L=>F(z.id,{color:L.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:z.name,onChange:L=>F(z.id,{name:L.target.value}),className:"class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:z.shortcut||"",onChange:L=>F(z.id,{shortcut:L.target.value}),className:"shortcut-input",placeholder:s("dataLabeler.shortcutKeyPlaceholder","Key"),maxLength:1}),e.jsx("button",{className:"remove-class-button","aria-label":s("dataLabeler.removeClass","Remove class"),onClick:()=>D(z.id),children:e.jsx(A.NiceIcon,{name:"trash",size:16})})]},z.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:o.guidelines||"",onChange:z=>P({guidelines:z.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),h==="review"&&e.jsxs("div",{className:"review-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:s("dataLabeler.reviewLabels","Review Labels")}),e.jsx("div",{className:"filter-group",children:e.jsxs("select",{value:x,onChange:z=>v(z.target.value),children:[e.jsx("option",{value:"all",children:s("dataLabeler.allItems","All Items")}),e.jsx("option",{value:"labeled",children:s("dataLabeler.labeled","Labeled")}),e.jsx("option",{value:"review",children:s("dataLabeler.needsReview","Needs Review")}),e.jsx("option",{value:"approved",children:s("dataLabeler.approved","Approved")}),e.jsx("option",{value:"rejected",children:s("dataLabeler.rejected","Rejected")})]})})]}),e.jsx("div",{className:"items-grid",children:o.items.filter(z=>x==="all"||z.status===x).map((z,E)=>{var L;return e.jsxs("div",{className:`item-card ${m===o.items.indexOf(z)?"item-card--active":""}`,onClick:()=>{b(o.items.indexOf(z)),p("label")},children:[z.data.type==="image"&&e.jsx("img",{src:z.data.url,alt:`Item ${E+1}`,className:"item-thumbnail"}),z.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(L=z.data.text)==null?void 0:L.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:Q(z.status)}}),e.jsx("span",{children:s("dataLabeler.labelCount","{count} labels").replace("{count}",String(z.labels.length))})]})]},z.id)})})]}),h==="export"&&e.jsxs("div",{className:"export-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:s("dataLabeler.exportLabels","Export Labels")})}),e.jsxs("div",{className:"export-stats",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:o.statistics.totalItems}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.totalItems","Total Items")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:o.statistics.labeled}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.labeled","Labeled")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:o.statistics.approved}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.approved","Approved")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:o.labelSchema.classes.length}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.classes","Classes")})]})]}),e.jsxs("div",{className:"export-formats",children:[e.jsx("h3",{children:s("dataLabeler.exportFormat","Export Format")}),e.jsxs("div",{className:"format-grid",children:[e.jsxs("button",{className:"format-button",onClick:()=>G("coco"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(A.NiceIcon,{name:"box",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.cocoJson","COCO JSON")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.cocoDesc","Common format for object detection")})]}),e.jsxs("button",{className:"format-button",onClick:()=>G("voc"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(A.NiceIcon,{name:"file",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.pascalVoc","Pascal VOC")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.vocDesc","XML format for bounding boxes")})]}),e.jsxs("button",{className:"format-button",onClick:()=>G("yolo"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(A.NiceIcon,{name:"zap",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.yolo","YOLO")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.yoloDesc","Text format for YOLO models")})]}),e.jsxs("button",{className:"format-button",onClick:()=>G("csv"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(A.NiceIcon,{name:"bar-chart",size:24})}),e.jsx("span",{className:"format-name",children:"CSV"}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.csvDesc","Tabular format for classification")})]})]})]}),e.jsxs("div",{className:"class-distribution",children:[e.jsx("h3",{children:s("dataLabeler.classDistribution","Class Distribution")}),e.jsx("div",{className:"distribution-bars",children:o.statistics.byClass.map(z=>{const E=o.labelSchema.classes.find(J=>J.id===z.classId),L=z.count/Math.max(o.statistics.labeled,1)*100;return e.jsxs("div",{className:"distribution-row",children:[e.jsx("span",{className:"class-name",style:{color:E==null?void 0:E.color},children:E==null?void 0:E.name}),e.jsx("div",{className:"bar-container",children:e.jsx("div",{className:"bar-fill",style:{width:`${L}%`,backgroundColor:E==null?void 0:E.color}})}),e.jsx("span",{className:"count",children:z.count})]},z.classId)})})]})]})]}),j&&e.jsx("div",{className:"shortcuts-modal",children:e.jsxs("div",{className:"modal-content",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:s("dataLabeler.keyboardShortcuts","Keyboard Shortcuts")}),e.jsx("button",{"aria-label":s("dataLabeler.close","Close"),onClick:()=>g(!1),children:e.jsx(A.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"shortcuts-list",children:[e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"← / A"}),e.jsx("span",{className:"description",children:s("dataLabeler.previousItem","Previous item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"→ / D"}),e.jsx("span",{className:"description",children:s("dataLabeler.nextItem","Next item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:s("dataLabeler.enterKey","Enter")}),e.jsx("span",{className:"description",children:s("dataLabeler.approveItem","Approve item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:s("dataLabeler.backspaceKey","Backspace")}),e.jsx("span",{className:"description",children:s("dataLabeler.rejectItem","Reject item")})]}),o.labelSchema.classes.map(z=>z.shortcut&&e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:z.shortcut}),e.jsx("span",{className:"description",children:s("dataLabeler.labelAs","Label as {name}").replace("{name}",z.name)})]},z.id))]})]})})]})},vt={id:A.createId(),name:"Model Endpoint",modelId:"",modelVersion:"1.0.0",status:"stopped",url:"",authentication:{type:"api-key"},metrics:{requestsTotal:0,requestsPerSecond:0,latencyP50:0,latencyP95:0,latencyP99:0,errorRate:0,successRate:100},logs:[]},_t=({endpoint:i,onInference:a,showMetrics:t=!0,showLogs:r=!0,className:n=""})=>{const[s,o]=d.useState(i||vt),[c,h]=d.useState("test"),[p,m]=d.useState("text"),[b,w]=d.useState(""),[k,M]=d.useState("{}"),[C,O]=d.useState(null),[_,l]=d.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[y,S]=d.useState(null),[f,j]=d.useState(!1),[g,x]=d.useState(null),[v,T]=d.useState([]),[I,N]=d.useState(null),P=d.useRef(null),$=u=>{var B;const R=(B=u.target.files)==null?void 0:B[0];if(R){const H=new FileReader;H.onload=q=>{var G;O((G=q.target)==null?void 0:G.result)},H.readAsDataURL(R)}},D=async()=>{if(!a){x("No inference handler provided");return}j(!0),x(null),S(null);const u=[];switch(p){case"text":u.push({type:"text",data:b});break;case"image":C&&u.push({type:"image",data:C});break;case"json":try{u.push({type:"json",data:JSON.parse(k)})}catch{x("Invalid JSON input"),j(!1);return}break;case"tabular":try{u.push({type:"tabular",data:JSON.parse(k)})}catch{x("Invalid tabular data"),j(!1);return}break}const R={inputs:u,parameters:_};try{const B=Date.now(),H=await a(R),q=Date.now()-B;S(H),o(G=>({...G,metrics:{...G.metrics,requestsTotal:G.metrics.requestsTotal+1,latencyP50:(G.metrics.latencyP50+q)/2},logs:[{timestamp:new Date,requestId:H.requestId,duration:q,status:"success",inputSize:JSON.stringify(u).length,outputSize:JSON.stringify(H.predictions).length},...G.logs.slice(0,99)]}))}catch(B){const H=B instanceof Error?B.message:"Inference failed";x(H),o(q=>({...q,metrics:{...q.metrics,requestsTotal:q.metrics.requestsTotal+1,errorRate:(q.metrics.errorRate*q.metrics.requestsTotal+1)/(q.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:A.createId(),duration:0,status:"error",inputSize:JSON.stringify(u).length,outputSize:0,error:H},...q.logs.slice(0,99)]}))}finally{j(!1)}},F=async u=>{if(a){N(0),T([]);for(let R=0;R<u.length;R++){const B={inputs:[u[R]],parameters:_};try{const H=await a(B);T(q=>[...q,H])}catch(H){console.error("Batch item failed:",H)}N((R+1)/u.length*100)}N(null)}},U=u=>u<1e3?`${u.toFixed(0)}ms`:`${(u/1e3).toFixed(2)}s`,W=u=>u.toLocaleTimeString(),Y=(u,R)=>e.jsxs("div",{className:"prediction-item",children:[u.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:u.label}),u.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${u.confidence*120}, 70%, 40%)`},children:[(u.confidence*100).toFixed(1),"%"]})]}),u.score!==void 0&&e.jsxs("div",{className:"prediction-score",children:[e.jsx("span",{className:"score-label",children:"Score:"}),e.jsx("span",{className:"score-value",children:u.score.toFixed(4)})]}),u.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:u.text})}),u.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",u.bbox.x,", ",u.bbox.y,") - ",u.bbox.width,"×",u.bbox.height]})}),u.raw!==void 0&&u.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(u.raw,null,2)})]})]},R);return e.jsxs("div",{className:`nice-model-inference ${n}`,children:[e.jsxs("header",{className:"inference__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("h2",{children:s.name}),e.jsx("span",{className:`status-badge status-badge--${s.status}`,children:s.status})]}),e.jsxs("div",{className:"header__tabs",children:[e.jsx("button",{className:`tab-button ${c==="test"?"tab-button--active":""}`,onClick:()=>h("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${c==="batch"?"tab-button--active":""}`,onClick:()=>h("batch"),children:"Batch"}),t&&e.jsx("button",{className:`tab-button ${c==="metrics"?"tab-button--active":""}`,onClick:()=>h("metrics"),children:"Metrics"}),r&&e.jsx("button",{className:`tab-button ${c==="logs"?"tab-button--active":""}`,onClick:()=>h("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[c==="test"&&e.jsxs("div",{className:"test-panel",children:[e.jsxs("div",{className:"input-section",children:[e.jsx("div",{className:"input-type-selector",children:["text","image","json","tabular"].map(u=>e.jsx("button",{className:`type-button ${p===u?"type-button--active":""}`,onClick:()=>m(u),children:u.charAt(0).toUpperCase()+u.slice(1)},u))}),e.jsxs("div",{className:"input-area",children:[p==="text"&&e.jsx("textarea",{value:b,onChange:u=>w(u.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),p==="image"&&e.jsx("div",{className:"image-input",children:C?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:C,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>O(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:P,type:"file",accept:"image/*",onChange:$,hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx(A.NiceIcon,{name:"image",size:32})}),e.jsx("span",{children:"Click or drag to upload image"})]})}),(p==="json"||p==="tabular")&&e.jsx("textarea",{value:k,onChange:u=>M(u.target.value),placeholder:p==="json"?`{
|
|
8
|
+
`);return{fieldLabel:`Code editor (${t})`,fieldType:"code-editor",fieldValue:s||a,schema:{language:t,...i!=null&&i.framework?{framework:i.framework}:{},...(i==null?void 0:i.cursorLine)!=null?{cursorLine:i.cursorLine,cursorCol:i.cursorCol}:{}},customPrompt:`Language: ${t}${i!=null&&i.framework?`, framework: ${i.framework}`:""}.
|
|
9
|
+
Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(i==null?void 0:i.maxSuggestLines)??5} lines of code. If unsure, suggest the most idiomatic approach for this language/framework.`}}function ra(t,a,i){var s;const r=(i==null?void 0:i.mode)??"grammar",n={seo:"Analyze this HTML for SEO: missing meta tags, heading hierarchy (h1→h2→h3), keyword density, image alt attributes. Return a prioritized list of improvements.",accessibility:"Audit this HTML for WCAG 2.1 AA issues: missing aria labels, alt text, heading structure, color contrast hints, keyboard navigation. List specific fixes.",grammar:"Fix grammar, punctuation, and writing style in the visible text content. Return the corrected text only (no HTML tags in response).",cleanup:"Clean up malformed, redundant, or overly nested HTML. Simplify structure while preserving semantics and content."};return{fieldLabel:t,fieldType:"html-editor",fieldValue:a==null?void 0:a.slice(0,2e3),schema:{mode:r,...(s=i==null?void 0:i.targetKeywords)!=null&&s.length?{targetKeywords:i.targetKeywords}:{},...i!=null&&i.locale?{locale:i.locale}:{}},customPrompt:n[r]}}function na(t,a){const i=(a==null?void 0:a.mode)??"tag",r=`"${t}"`+((a==null?void 0:a.bpm)!=null?`, BPM: ${a.bpm}`:"")+(a!=null&&a.key?`, Key: ${a.key}`:"")+(a!=null&&a.genre?`, Genre: ${a.genre}`:"")+((a==null?void 0:a.duration)!=null?`, Duration: ${a.duration}s`:""),n={tag:`Audio: ${r}. Suggest genre tags, mood descriptors and playlist categories. Return as JSON array of strings.`,bpm:`Audio: ${r}. Suggest likely BPM range and musical key based on metadata. Return as JSON: { bpm: number, key: string }.`,mix:`Track: ${r}. Suggest EQ curve (JSON array of {freq, gain, q}), compression settings, and 2-3 compatible tracks for mixing.`,transcribe:"Return a transcription of the spoken audio content as JSON: { transcript: string, language: string, confidence: number }."};return{fieldLabel:`Audio: ${t}`,fieldType:"audio",schema:{mode:i,...(a==null?void 0:a.bpm)!=null?{bpm:a.bpm}:{},...a!=null&&a.key?{key:a.key}:{},...(a==null?void 0:a.duration)!=null?{duration:a.duration}:{},...a!=null&&a.genre?{genre:a.genre}:{}},customPrompt:n[i]}}function sa(t,a){var s;const i=(a==null?void 0:a.mode)??"material",r=(a==null?void 0:a.targetDevice)??"web",n={material:`Scene "${t}", ${(a==null?void 0:a.meshCount)??"?"} meshes. Materials: ${((s=a==null?void 0:a.materials)==null?void 0:s.join(", "))||"none"}. Suggest PBR properties (roughness, metalness, baseColor) and texture maps for each material.`,optimize:`Scene "${t}", triangles: ${(a==null?void 0:a.triangleCount)??"?"}, target: ${r}. Identify budget issues and suggest LOD levels, mesh merging, and texture atlas strategy.`,lighting:`Scene "${t}", target: ${r}. Suggest a complete lighting setup (types, intensity, color, shadow settings) for realistic rendering.`,animation:`Rig in scene "${t}". Suggest animation approach (FK/IK, bone count), keyframe timing and easing curves for natural movement.`};return{fieldLabel:`3D scene: ${t}`,fieldType:"3d-scene",schema:{mode:i,...(a==null?void 0:a.meshCount)!=null?{meshes:a.meshCount}:{},...(a==null?void 0:a.triangleCount)!=null?{triangles:a.triangleCount}:{},...a!=null&&a.targetDevice?{target:a.targetDevice}:{}},customPrompt:n[i]}}function ca(t,a){const i=(a==null?void 0:a.mode)??"palette",r=(a==null?void 0:a.width)!=null?`${a.width}×${a.height??"?"}px`:"unknown dimensions",n={filter:`Image "${t}" (${r}). Suggest CSS/SVG filter parameters (brightness, contrast, saturate, hue-rotate, blur) as JSON: { brightness, contrast, saturate, hueRotate, blur }.`,palette:`Image "${t}". Extract or suggest a harmonious 5-color palette as JSON: { primary, secondary, accent, background, text }.`,upscale:`Image "${t}" at ${r}. Recommend upscaling strategy: model (ESRGAN/RealSR/SRCNN), scale factor, and expected quality gain.`,"style-transfer":`Image "${t}", target style: "${(a==null?void 0:a.targetStyle)??"artistic"}". Suggest style-transfer settings as JSON: { contentWeight, styleWeight, iterations, patchSize }.`};return{fieldLabel:`Graphics: ${t}`,fieldType:"graphics",schema:{mode:i,...(a==null?void 0:a.width)!=null?{width:a.width,height:a.height}:{},...a!=null&&a.targetStyle?{targetStyle:a.targetStyle}:{}},customPrompt:n[i]}}function oa(t,a){var i;return{fieldLabel:"Icon search",fieldType:"icon-picker",fieldValue:t,schema:{...a!=null&&a.style?{iconStyle:a.style}:{},...(a==null?void 0:a.limit)!=null?{maxResults:a.limit}:{},...(i=a==null?void 0:a.availableIcons)!=null&&i.length?{sampleIcons:a.availableIcons.slice(0,30)}:{}},customPrompt:`User query: "${t}"
|
|
10
|
+
Return the ${(a==null?void 0:a.limit)??5} most semantically relevant icon names from the available set as a JSON array of strings, ordered by relevance. Prefer specific over generic names.`}}function Ka(t,a,i){const r=l.useMemo(()=>ta(t,a,i),[t,a,i==null?void 0:i.cursorLine,i==null?void 0:i.cursorCol,i==null?void 0:i.framework]);return Z(r,i)}function Ya(t,a,i){const r=l.useMemo(()=>ra(t,a,i),[t,a,i==null?void 0:i.mode,i==null?void 0:i.locale]);return Z(r,i)}function Va(t,a){const i=l.useMemo(()=>na(t,a),[t,a==null?void 0:a.bpm,a==null?void 0:a.key,a==null?void 0:a.duration,a==null?void 0:a.mode]);return Z(i,a)}function Xa(t,a){const i=l.useMemo(()=>sa(t,a),[t,a==null?void 0:a.meshCount,a==null?void 0:a.triangleCount,a==null?void 0:a.targetDevice,a==null?void 0:a.mode]);return Z(i,a)}function Qa(t,a){const i=l.useMemo(()=>ca(t,a),[t,a==null?void 0:a.width,a==null?void 0:a.height,a==null?void 0:a.mode,a==null?void 0:a.targetStyle]);return Z(i,a)}function Za(t,a){const i=l.useMemo(()=>oa(t,a),[t,a==null?void 0:a.limit,a==null?void 0:a.style]);return Z(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function la(t,a){var s;const i=(a==null?void 0:a.mode)??"npc-decision",r=(a==null?void 0:a.genre)??"fantasy",n={"npc-decision":`You are an AI game director. The NPC "${t}" must make a decision. Available BT nodes: ${JSON.stringify((a==null?void 0:a.btStatus)??[])}. Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Return the name of the BT node to activate next, and one sentence of reasoning.`,dialogue:`You are a ${r} RPG writer. Write a short in-character dialogue line for NPC "${t}". Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Max 2 sentences, no narrative descriptions.`,"procedural-level":`You are a ${r} game designer. Suggest a procedural level layout for a zone containing "${t}". Describe room count, enemy placement, loot, and one unique mechanic. Keep it under 150 words.`,"quest-description":`You are a ${r} quest designer. Write a compelling quest description involving "${t}". Include: objective, giver NPC, rewards, and a short flavour paragraph. Keep it under 120 words.`,"item-description":`You are a ${r} lore writer. Write a short item description for an item related to "${t}". Include: item name, rarity, flavour text, and one special property. Keep it under 80 words.`};return{fieldLabel:t,fieldType:`game-engine:${i}`,fieldValue:a==null?void 0:a.gameState,customPrompt:n[i],schema:{genre:r,mode:i,btNodes:(s=a==null?void 0:a.btStatus)==null?void 0:s.map(o=>o.node)}}}function ei(t,a){const i=l.useMemo(()=>la(t,a),[t,a==null?void 0:a.mode,a==null?void 0:a.genre,JSON.stringify(a==null?void 0:a.btStatus),JSON.stringify(a==null?void 0:a.gameState)]);return Z(i,a)}function da(t,a,i){const r=(i==null?void 0:i.mode)??"layout",n=(i==null?void 0:i.diagramType)??"flowchart",s={layout:`You are a diagram layout optimizer. Given this ${n} with ${t.length} nodes and ${a.length} edges, suggest optimal positions for each node to minimize edge crossings and improve readability. Return JSON: { suggestions: [{ id: string, x: number, y: number, reason: string }] }. Consider flow direction (top-to-bottom or left-to-right) and grouping related nodes.`,structure:`You are a diagram analyst. Analyze this ${n} structure. Identify: 1) Missing connections, 2) Potential bottlenecks, 3) Orphan nodes, 4) Cycles or loops. Return JSON: { issues: [{ type: string, description: string, nodeIds: string[] }], score: number }`,simplify:`You are a diagram simplifier. Suggest how to simplify this ${n} while preserving meaning. Identify: nodes that could be merged, redundant edges, or overly complex branches. Return JSON: { simplifications: [{ action: 'merge'|'remove'|'group', ids: string[], reason: string }] }`,group:`You are a diagram organizer. Suggest logical groupings for nodes in this ${n}. Consider semantic relationships, data flow patterns, and visual clustering. Return JSON: { groups: [{ name: string, nodeIds: string[], color?: string }] }`},o=t.map(m=>{var p;return{id:m.id,type:m.type,label:(p=m.label)==null?void 0:p.slice(0,30),pos:[Math.round(m.x),Math.round(m.y)]}}),c=a.map(m=>({id:m.id,src:m.source,tgt:m.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:o,edges:c}),schema:{diagramType:n,mode:r,nodeCount:t.length,edgeCount:a.length,containerSize:i==null?void 0:i.containerSize},customPrompt:s[r]}}function ai(t,a,i){const r=l.useMemo(()=>da(t,a,i),[JSON.stringify(t),JSON.stringify(a),i==null?void 0:i.mode,i==null?void 0:i.diagramType]);return Z(r,{...i,disabled:t.length===0||(i==null?void 0:i.disabled)})}function ua(t,a){const i=(a==null?void 0:a.mode)??"generate",r=(a==null?void 0:a.presentationType)??"business",n=(a==null?void 0:a.duration)??15,s=Math.ceil(n/2),o={generate:`You are a presentation designer. Create a ${r} presentation outline based on: "${t}". Target audience: ${(a==null?void 0:a.audience)??"general"}. Duration: ${n} minutes (~${s} slides). Return JSON: { title: string, slides: [{ title: string, layout: 'title'|'content'|'two-column'|'chart'|'image', bullets?: string[], chartType?: string, speakerNotes?: string }] }. Include: clear slide titles, 3-5 bullet points per content slide, and brief speaker notes.`,summarize:`You are a presentation optimizer. Summarize this presentation to be more concise: "${t}". Reduce slide count by 30% while preserving key messages. Return JSON: { summary: string, reducedSlides: [{ title: string, keyPoints: string[] }] }`,expand:`You are a presentation expert. Expand this brief outline into a detailed presentation: "${t}". Add supporting details, examples, and transitions. Target: ${s} slides. Return JSON: { slides: [{ title: string, content: string, transitions?: string, animations?: string[] }] }`,improve:`You are a presentation coach. Review and improve this presentation structure: "${t}". Suggest: better flow, stronger opening/closing, clearer data visualization. Return JSON: { improvements: [{ slide: number, issue: string, suggestion: string }], score: number }`};return{fieldLabel:`Presentation (${r})`,fieldType:`presentation:${i}`,fieldValue:t,schema:{presentationType:r,mode:i,duration:n,slideCount:s,audience:a==null?void 0:a.audience,hasData:(a==null?void 0:a.dataContext)!=null},customPrompt:o[i]}}function ii(t,a){const i=l.useMemo(()=>ua(t,a),[t,a==null?void 0:a.mode,a==null?void 0:a.presentationType,a==null?void 0:a.duration,a==null?void 0:a.audience]);return Z(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function ma(t,a){var n;const i=(a==null?void 0:a.mode)??"all",r={alignment:"Analyze element alignment on this slide. Suggest adjustments to create visual harmony. Return JSON: { suggestions: [{ elementIndex: number, issue: string, fixX?: number, fixY?: number }] }",contrast:"Analyze color contrast and readability. Suggest improvements for accessibility (WCAG AA). Return JSON: { suggestions: [{ area: string, currentContrast: number, suggestedFix: string }] }",spacing:"Analyze whitespace and element spacing. Apply the rule of thirds and consistent margins. Return JSON: { suggestions: [{ elementIndex: number, issue: string, suggestedMargin: number }] }",typography:"Analyze typography: hierarchy, font sizes, line heights, readability. Return JSON: { suggestions: [{ area: string, issue: string, suggestedFontSize?: number }] }",all:"Perform a complete design review of this slide. Check alignment, contrast, spacing, and typography. Return JSON: { score: number, suggestions: [{ category: string, issue: string, fix: string }] }. Prioritize issues by impact on visual clarity."};return{fieldLabel:t.title??"Slide Design",fieldType:`slide-design:${i}`,fieldValue:JSON.stringify(t),schema:{mode:i,hasElements:(((n=t.elements)==null?void 0:n.length)??0)>0,layout:t.layout,brandColors:a==null?void 0:a.brandColors},customPrompt:r[i]}}function ti(t,a){const i=l.useMemo(()=>ma(t,a),[JSON.stringify(t),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return Z(i,a)}function ri(t,a,i){const r=l.forwardRef((n,s)=>{const{aiEnabled:o=!0,aiPosition:c="right",aiPrompt:m,aiDebounceMs:p=500,aiShowOnHover:u=!1,aiTriggerIcon:v,...w}=n,A=l.useMemo(()=>{const R=a(w);return m&&(R.customPrompt=m),R},[w,m]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(t,{...w,ref:s}),o&&e.jsx(ea,{context:A,position:c,debounceMs:p,showOnHover:u,triggerIcon:v})]})});return r.displayName=i??`withAIHint(${t.displayName??t.name??"Component"})`,r}function ni(t){return Le(t.label??"Text",t.value,{placeholder:t.placeholder,maxLength:t.maxLength})}function si(t){return ze(t.label??"Number",t.value,{min:t.min,max:t.max,step:t.step})}function ci(t){return Me(t.label??"Select",t.value,{options:t.options,multiple:t.multiple})}function oi(t){return $e(t.label??"Date",t.value,{min:t.min,max:t.max})}function li(t){return Pe(t.label??"Color",t.value)}const di=t=>({id:T.createId(),name:t,type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date}),je={classification:[{id:"logistic-regression",key:"mlStudio.alg.logisticRegression",name:"Logistic Regression"},{id:"random-forest",key:"mlStudio.alg.randomForest",name:"Random Forest"},{id:"gradient-boosting",key:"mlStudio.alg.gradientBoosting",name:"Gradient Boosting"},{id:"svm",key:"mlStudio.alg.svm",name:"Support Vector Machine"},{id:"neural-network",key:"mlStudio.alg.neuralNetwork",name:"Neural Network"},{id:"xgboost",key:"mlStudio.alg.xgboost",name:"XGBoost"}],regression:[{id:"linear-regression",key:"mlStudio.alg.linearRegression",name:"Linear Regression"},{id:"ridge",key:"mlStudio.alg.ridge",name:"Ridge Regression"},{id:"lasso",key:"mlStudio.alg.lasso",name:"Lasso Regression"},{id:"random-forest-reg",key:"mlStudio.alg.randomForest",name:"Random Forest"},{id:"gradient-boosting-reg",key:"mlStudio.alg.gradientBoosting",name:"Gradient Boosting"}],clustering:[{id:"kmeans",key:"mlStudio.alg.kmeans",name:"K-Means"},{id:"dbscan",key:"mlStudio.alg.dbscan",name:"DBSCAN"},{id:"hierarchical",key:"mlStudio.alg.hierarchical",name:"Hierarchical Clustering"}]},ui=Object.values(je).flat(),Fe=(t,a)=>{const i=ui.find(r=>r.id===t);return i?a(i.key,i.name):t},mi=[["classification","mlStudio.type.classification","Classification"],["regression","mlStudio.type.regression","Regression"],["clustering","mlStudio.type.clustering","Clustering"],["object-detection","mlStudio.type.objectDetection","Object Detection"],["nlp","mlStudio.type.nlp","NLP"],["time-series","mlStudio.type.timeSeries","Time Series"]],pi=[["data","mlStudio.tab.data","Data"],["experiments","mlStudio.tab.experiments","Experiments"],["models","mlStudio.tab.models","Models"],["deploy","mlStudio.tab.deploy","Deploy"]],gi=[["numeric","mlStudio.colType.numeric","Numeric"],["categorical","mlStudio.colType.categorical","Categorical"],["text","mlStudio.colType.text","Text"],["datetime","mlStudio.colType.datetime","DateTime"],["boolean","mlStudio.colType.boolean","Boolean"],["embedding","mlStudio.colType.embedding","Embedding"]],hi={train:["mlStudio.split.train","Train"],validation:["mlStudio.split.validation","Validation"],test:["mlStudio.split.test","Test"]},fi={pending:["mlStudio.experimentStatus.pending","Pending"],running:["mlStudio.experimentStatus.running","Running"],completed:["mlStudio.experimentStatus.completed","Completed"],failed:["mlStudio.experimentStatus.failed","Failed"],cancelled:["mlStudio.experimentStatus.cancelled","Cancelled"]},xi={draft:["mlStudio.modelStatus.draft","Draft"],registered:["mlStudio.modelStatus.registered","Registered"],staging:["mlStudio.modelStatus.staging","Staging"],production:["mlStudio.modelStatus.production","Production"],archived:["mlStudio.modelStatus.archived","Archived"]},bi={pending:["mlStudio.deploymentStatus.pending","Pending"],deploying:["mlStudio.deploymentStatus.deploying","Deploying"],running:["mlStudio.deploymentStatus.running","Running"],stopped:["mlStudio.deploymentStatus.stopped","Stopped"],failed:["mlStudio.deploymentStatus.failed","Failed"]},ce=(t,a,i)=>t?i(t[0],t[1]):a,yi=new Set(["accuracy","precision","recall","f1-score","auc-roc"]),Je=({name:t,value:a},i)=>yi.has(t)?`${(a*100).toLocaleString(i,{minimumFractionDigits:1,maximumFractionDigits:1})}%`:a.toLocaleString(i,{maximumFractionDigits:3}),vi=[{target:".nice-ml-studio",titleKey:"tutorial.mlStudio.intro.title",title:"ML studio",contentKey:"tutorial.mlStudio.intro.content",content:"Work through the tabs: prepare datasets, run experiments, compare and pick models, then deploy the best one.",placement:"auto"}],_i=({project:t,onProjectChange:a,onExperimentRun:i,onModelDeploy:r,onModelDownload:n,className:s="",tutorial:o})=>{var X;const{t:c,lang:m}=T.useNiceTranslation(),[p,u]=l.useState(()=>t||di(c("mlStudio.newProject","New ML Project"))),[v,w]=l.useState("data"),[A,R]=l.useState(null),[M,P]=l.useState(null),[g,d]=l.useState(null),[j,y]=l.useState(!1),[I,b]=l.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),h=l.useRef(p),_=l.useCallback(C=>{const x=h.current,B={...x,...typeof C=="function"?C(x):C,updatedAt:new Date};h.current=B,u(B),a==null||a(B)},[a]),f=async C=>{for(const x of Array.from(C)){const B={id:T.createId(),name:x.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:x.name},size:x.size,rowCount:0,columns:[],splits:[{name:"train",ratio:.8,rowCount:0},{name:"validation",ratio:.1,rowCount:0},{name:"test",ratio:.1,rowCount:0}],createdAt:new Date};if(x.name.endsWith(".csv")){const q=(await x.text()).split(`
|
|
11
|
+
`),W=q[0].split(",").map(Q=>Q.trim());B.rowCount=q.length-1,B.columns=W.map(Q=>({name:Q,type:"text",nullable:!0,unique:0,missing:0})),B.splits=B.splits.map(Q=>({...Q,rowCount:Math.floor(B.rowCount*Q.ratio)}))}_(G=>({datasets:[...G.datasets,B]}))}},k=C=>{_({datasets:p.datasets.filter(x=>x.id!==C)}),A===C&&R(null)},S=async()=>{if(!I.algorithm||!A)return;const C={id:T.createId(),name:c("mlStudio.experimentName","Experiment {n}").replace("{n}",String(p.experiments.length+1)),status:"pending",config:I,metrics:[],artifacts:[],logs:[]},x=G=>_(q=>({experiments:q.experiments.map(W=>W.id===C.id?{...W,...G}:W)}));if(_(G=>({experiments:[...G.experiments,C]})),y(!1),!i)return;const B=new Date;x({status:"running",startedAt:B});try{const G=await i(C),q=typeof G=="object"&&G!==null?G:{},W=new Date;x({status:"completed",completedAt:W,duration:q.duration??(W.getTime()-B.getTime())/1e3,metrics:q.metrics??[],artifacts:q.artifacts??[],logs:q.logs??[]})}catch{x({status:"failed"})}},N=C=>{const x=p.experiments.find(q=>q.id===C);if(!x)return;const B=x.artifacts.filter(q=>q.type==="model"),G={id:T.createId(),name:c("mlStudio.modelFrom","Model from {name}").replace("{name}",x.name),version:"1.0.0",algorithm:x.config.algorithm,experimentId:C,status:"registered",metrics:x.metrics,size:B.reduce((q,W)=>q+W.size,0),artifacts:B,deployments:[],createdAt:new Date};_(q=>({models:[...q.models,G]}))},$=async C=>{const x=p.models.find(G=>G.id===C);if(!x||!r)return;const B=await r(x);_(G=>({models:G.models.map(q=>q.id===C?{...q,status:"production",deployments:[...q.deployments,B]}:q)}))},E=C=>C<1024?`${C} B`:C<1024*1024?`${(C/1024).toFixed(1)} KB`:C<1024*1024*1024?`${(C/1024/1024).toFixed(1)} MB`:`${(C/1024/1024/1024).toFixed(1)} GB`,z=C=>{switch(C){case"completed":case"production":case"running":return"success";case"pending":case"staging":return"pending";case"failed":return"error";case"deploying":case"stopped":return C;default:return"neutral"}},F=e.jsxs("div",{className:"nice-ml-studio__header-info",children:[e.jsx("input",{type:"text",value:p.name,onChange:C=>_({name:C.target.value}),className:"nice-ml-studio__project-name-input","aria-label":c("mlStudio.projectName","Project name")}),e.jsx("select",{value:p.type,onChange:C=>_({type:C.target.value}),className:"nice-ml-studio__project-type-select","aria-label":c("mlStudio.projectType","Project type"),children:mi.map(([C,x,B])=>e.jsx("option",{value:C,children:c(x,B)},C))})]}),U=e.jsx("div",{className:"nice-ml-studio__header-tabs",children:pi.map(([C,x,B])=>e.jsx("button",{className:`nice-ml-studio__tab-button ${v===C?"nice-ml-studio__tab-button--active":""}`,onClick:()=>w(C),children:c(x,B)},C))}),H=e.jsxs("div",{className:"nice-ml-studio__content",children:[v==="data"&&e.jsxs("div",{className:"nice-ml-studio__data-panel",children:[e.jsxs("div",{className:"nice-ml-studio__panel-header",children:[e.jsx("h2",{children:c("mlStudio.datasets","Datasets")}),e.jsxs("label",{className:"nice-ml-studio__upload-button",children:[e.jsx("input",{type:"file",multiple:!0,accept:".csv,.json,.parquet",onChange:C=>C.target.files&&f(C.target.files),hidden:!0}),e.jsx(T.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.uploadDataset","Upload Dataset")]})]}),e.jsx("div",{className:"nice-ml-studio__datasets-grid",children:p.datasets.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("p",{children:c("mlStudio.noDatasets","No datasets uploaded yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noDatasetsHint","Upload CSV, JSON, or Parquet files to get started")})]}):p.datasets.map(C=>e.jsxs("div",{className:`nice-ml-studio__dataset-card ${A===C.id?"nice-ml-studio__dataset-card--selected":""}`,onClick:()=>R(C.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("span",{className:"nice-ml-studio__dataset-icon",children:e.jsx(T.NiceIcon,{name:"folder",size:16})}),e.jsx("h3",{children:C.name}),e.jsx("button",{className:"nice-ml-studio__remove-button","aria-label":c("mlStudio.removeDataset","Remove dataset"),onClick:x=>{x.stopPropagation(),k(C.id)},children:e.jsx(T.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"nice-ml-studio__card-stats",children:[e.jsx("span",{children:c("mlStudio.rows","{count} rows").replace("{count}",C.rowCount.toLocaleString(m))}),e.jsx("span",{children:c("mlStudio.columnCount","{count} columns").replace("{count}",String(C.columns.length))}),e.jsx("span",{children:E(C.size)})]}),e.jsx("div",{className:"nice-ml-studio__splits-bar",children:C.splits.map(x=>e.jsx("div",{className:`nice-ml-studio__split nice-ml-studio__split--${x.name}`,style:{width:`${x.ratio*100}%`},title:`${ce(hi[x.name],x.name,c)}: ${(x.ratio*100).toFixed(0)}%`},x.name))})]},C.id))}),A&&e.jsx("div",{className:"nice-ml-studio__dataset-details",children:(()=>{const C=p.datasets.find(x=>x.id===A);return C?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:c("mlStudio.columns","Columns")}),e.jsxs("table",{className:"nice-ml-studio__columns-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:c("mlStudio.col.name","Name")}),e.jsx("th",{children:c("mlStudio.col.type","Type")}),e.jsx("th",{children:c("mlStudio.col.missing","Missing")}),e.jsx("th",{children:c("mlStudio.col.unique","Unique")})]})}),e.jsx("tbody",{children:C.columns.map(x=>e.jsxs("tr",{children:[e.jsx("td",{children:x.name}),e.jsx("td",{children:e.jsx("select",{value:x.type,"aria-label":c("mlStudio.col.type","Type"),onChange:B=>{_({datasets:p.datasets.map(G=>G.id===C.id?{...G,columns:G.columns.map(q=>q.name===x.name?{...q,type:B.target.value}:q)}:G)})},children:gi.map(([B,G,q])=>e.jsx("option",{value:B,children:c(G,q)},B))})}),e.jsx("td",{children:x.missing}),e.jsx("td",{children:x.unique})]},x.name))})]})]}):null})()})]}),v==="experiments"&&e.jsxs("div",{className:"nice-ml-studio__experiments-panel",children:[e.jsxs("div",{className:"nice-ml-studio__panel-header",children:[e.jsx("h2",{children:c("mlStudio.tab.experiments","Experiments")}),e.jsxs("button",{className:"nice-ml-studio__primary-button",onClick:()=>y(!0),disabled:p.datasets.length===0,children:[e.jsx(T.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.newExperiment","New Experiment")]})]}),j&&e.jsxs("div",{className:"nice-ml-studio__new-experiment-form",children:[e.jsx("h3",{children:c("mlStudio.configureExperiment","Configure Experiment")}),e.jsxs("div",{className:"nice-ml-studio__form-grid",children:[e.jsxs("label",{children:[c("mlStudio.dataset","Dataset"),e.jsxs("select",{value:A||"",onChange:C=>R(C.target.value),children:[e.jsx("option",{value:"",children:c("mlStudio.selectDataset","Select dataset...")}),p.datasets.map(C=>e.jsx("option",{value:C.id,children:C.name},C.id))]})]}),e.jsxs("label",{children:[c("mlStudio.algorithm","Algorithm"),e.jsxs("select",{value:I.algorithm,onChange:C=>b({...I,algorithm:C.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectAlgorithm","Select algorithm...")}),(je[p.type]||je.classification).map(C=>e.jsx("option",{value:C.id,children:c(C.key,C.name)},C.id))]})]}),A&&e.jsxs("label",{children:[c("mlStudio.targetColumn","Target Column"),e.jsxs("select",{value:I.targetColumn||"",onChange:C=>b({...I,targetColumn:C.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectTarget","Select target...")}),(X=p.datasets.find(C=>C.id===A))==null?void 0:X.columns.map(C=>e.jsx("option",{value:C.name,children:C.name},C.name))]})]})]}),e.jsxs("div",{className:"nice-ml-studio__form-actions",children:[e.jsx("button",{className:"nice-ml-studio__secondary-button",onClick:()=>y(!1),children:c("cancel","Cancel")}),e.jsx("button",{className:"nice-ml-studio__primary-button",onClick:S,disabled:!I.algorithm||!A,children:c("mlStudio.runExperiment","Run Experiment")})]})]}),e.jsx("div",{className:"nice-ml-studio__experiments-list",children:p.experiments.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"flask",size:32})}),e.jsx("p",{children:c("mlStudio.noExperiments","No experiments yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noExperimentsHint","Create an experiment to train and evaluate models")})]}):p.experiments.map(C=>e.jsxs("div",{className:`nice-ml-studio__experiment-card ${M===C.id?"nice-ml-studio__experiment-card--selected":""}`,onClick:()=>P(C.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:C.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${z(C.status)}`,children:ce(fi[C.status],C.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",Fe(C.config.algorithm,c))}),C.duration!==void 0&&e.jsx("span",{children:c("mlStudio.duration","Duration: {seconds}s").replace("{seconds}",String(Math.round(C.duration)))})]}),C.metrics.length>0&&e.jsx("div",{className:"nice-ml-studio__metrics-row",children:C.metrics.slice(0,3).map(x=>e.jsxs("div",{className:"nice-ml-studio__metric-item",children:[e.jsx("span",{className:"nice-ml-studio__metric-name",children:x.name}),e.jsx("span",{className:"nice-ml-studio__metric-value",children:Je(x,m)})]},x.name))}),C.status==="completed"&&e.jsx("button",{className:"nice-ml-studio__action-button",onClick:x=>{x.stopPropagation(),N(C.id)},children:c("mlStudio.registerModel","Register Model")})]},C.id))})]}),v==="models"&&e.jsxs("div",{className:"nice-ml-studio__models-panel",children:[e.jsx("div",{className:"nice-ml-studio__panel-header",children:e.jsx("h2",{children:c("mlStudio.tab.models","Models")})}),e.jsx("div",{className:"nice-ml-studio__models-list",children:p.models.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"wand",size:32})}),e.jsx("p",{children:c("mlStudio.noModels","No models registered yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noModelsHint","Complete experiments and register models")})]}):p.models.map(C=>e.jsxs("div",{className:`nice-ml-studio__model-card ${g===C.id?"nice-ml-studio__model-card--selected":""}`,onClick:()=>d(C.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:C.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${z(C.status)}`,children:ce(xi[C.status],C.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",Fe(C.algorithm,c))}),e.jsx("span",{children:c("mlStudio.version","Version: {version}").replace("{version}",C.version)}),C.size>0&&e.jsx("span",{children:c("mlStudio.size","Size: {size}").replace("{size}",E(C.size))})]}),C.metrics.length>0&&e.jsx("div",{className:"nice-ml-studio__metrics-row",children:C.metrics.slice(0,3).map(x=>e.jsxs("div",{className:"nice-ml-studio__metric-item",children:[e.jsx("span",{className:"nice-ml-studio__metric-name",children:x.name}),e.jsx("span",{className:"nice-ml-studio__metric-value",children:Je(x,m)})]},x.name))}),e.jsxs("div",{className:"nice-ml-studio__card-actions",children:[e.jsx("button",{className:"nice-ml-studio__action-button",onClick:x=>{x.stopPropagation(),n==null||n(C)},disabled:!n,title:n?void 0:c("mlStudio.downloadNotSetUp","Downloading models is not set up"),children:c("download","Download")}),e.jsx("button",{className:"nice-ml-studio__action-button nice-ml-studio__action-button--primary",onClick:x=>{x.stopPropagation(),$(C.id)},disabled:C.status==="production"||!r,title:r?void 0:c("mlStudio.deployNotSetUp","Deploying models is not set up"),children:C.status==="production"?c("mlStudio.deployed","Deployed"):c("mlStudio.deploy","Deploy")})]})]},C.id))})]}),v==="deploy"&&e.jsxs("div",{className:"nice-ml-studio__deploy-panel",children:[e.jsx("div",{className:"nice-ml-studio__panel-header",children:e.jsx("h2",{children:c("mlStudio.deployments","Deployments")})}),e.jsx("div",{className:"nice-ml-studio__deployments-list",children:p.models.filter(C=>C.deployments.length>0).length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"rocket",size:32})}),e.jsx("p",{children:c("mlStudio.noDeployments","No deployments yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noDeploymentsHint","Deploy a model to create inference endpoints")})]}):p.models.filter(C=>C.deployments.length>0).flatMap(C=>C.deployments.map(x=>({model:C,deployment:x}))).map(({model:C,deployment:x})=>e.jsxs("div",{className:"nice-ml-studio__deployment-card",children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:x.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${z(x.status)}`,children:ce(bi[x.status],x.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.modelValue","Model: {name}").replace("{name}",C.name)}),e.jsx("span",{children:c("mlStudio.endpoint","Endpoint: {url}").replace("{url}",x.endpoint)})]}),e.jsxs("div",{className:"nice-ml-studio__resources-info",children:[e.jsx("span",{children:c("mlStudio.cpu","CPU: {count} cores").replace("{count}",String(x.resources.cpu))}),e.jsx("span",{children:c("mlStudio.memory","Memory: {gb} GB").replace("{gb}",String(x.resources.memory))}),e.jsx("span",{children:c("mlStudio.replicas","Replicas: {count}").replace("{count}",String(x.resources.replicas))})]})]},x.id))})]})]});return e.jsxs("div",{className:`nice-ml-studio ${s}`,style:{position:"relative"},children:[e.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:e.jsx(T.NiceTutorialButton,{steps:T.resolveTutorial(o,vi)})}),e.jsx(Ma.NiceAppShell,{flush:!0,menubar:F,toolbar:U,children:H})]})},wi={id:T.createId(),name:"New Labeling Project",type:"classification",dataType:"image",status:"setup",labelSchema:{classes:[],attributes:[]},items:[],collaborators:[],statistics:{totalItems:0,labeled:0,reviewed:0,approved:0,byClass:[]},createdAt:new Date},qe=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)"],ji={label:"Label",schema:"Schema",review:"Review",export:"Export"},ki=({project:t,onProjectChange:a,onLabelSave:i,onExport:r,className:n=""})=>{var re;const{t:s}=T.useNiceTranslation(),[o,c]=l.useState(t||wi),[m,p]=l.useState("label"),[u,v]=l.useState(0),[w,A]=l.useState(null),[R,M]=l.useState("select"),[P,g]=l.useState(!1),[d,j]=l.useState(null),[y,I]=l.useState(1),[b,h]=l.useState(!1),[_,f]=l.useState("all"),k=l.useRef(null),S=l.useRef(null),N=o.items[u];l.useEffect(()=>{t&&c(t)},[t]);const $=l.useCallback(L=>{const O={...o,...L};O.statistics={totalItems:O.items.length,labeled:O.items.filter(J=>J.status!=="pending").length,reviewed:O.items.filter(J=>J.status==="review"||J.status==="approved").length,approved:O.items.filter(J=>J.status==="approved").length,byClass:O.labelSchema.classes.map(J=>({classId:J.id,count:O.items.flatMap(Y=>Y.labels).filter(Y=>Y.classId===J.id).length}))},c(O),a==null||a(O)},[o,a]),E=()=>{const L={id:T.createId(),name:`Class ${o.labelSchema.classes.length+1}`,color:qe[o.labelSchema.classes.length%qe.length],shortcut:String(o.labelSchema.classes.length+1)};$({labelSchema:{...o.labelSchema,classes:[...o.labelSchema.classes,L]}})},z=L=>{$({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.filter(O=>O.id!==L)},items:o.items.map(O=>({...O,labels:O.labels.filter(J=>J.classId!==L)}))})},F=(L,O)=>{$({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.map(J=>J.id===L?{...J,...O}:J)}})},U=(L,O)=>{if(!N)return;const J={id:T.createId(),classId:L,type:o.type==="classification"?"class":o.type==="bounding-box"?"bbox":"class",data:O||{},createdBy:"current-user",createdAt:new Date},Y={...N,labels:[...N.labels,J],status:"labeled"};$({items:o.items.map(D=>D.id===N.id?Y:D)}),i==null||i(Y)},H=L=>{if(!N)return;const O={...N,labels:N.labels.filter(J=>J.id!==L),status:N.labels.length<=1?"pending":"labeled"};$({items:o.items.map(J=>J.id===N.id?O:J)})},X=L=>{var D;if(R!=="bbox"||!w)return;const O=(D=k.current)==null?void 0:D.getBoundingClientRect();if(!O)return;const J=(L.clientX-O.left)/y,Y=(L.clientY-O.top)/y;g(!0),j({x:J,y:Y,width:0,height:0})},C=L=>{var D;if(!P||!d)return;const O=(D=k.current)==null?void 0:D.getBoundingClientRect();if(!O)return;const J=(L.clientX-O.left)/y,Y=(L.clientY-O.top)/y;j({...d,width:J-d.x,height:Y-d.y})},x=()=>{!P||!d||!w||(g(!1),Math.abs(d.width)>10&&Math.abs(d.height)>10&&U(w,{x:d.width<0?d.x+d.width:d.x,y:d.height<0?d.y+d.height:d.y,width:Math.abs(d.width),height:Math.abs(d.height)}),j(null))},B=L=>{const O=_==="all"?o.items:o.items.filter(Y=>Y.status===_),J=O.findIndex(Y=>Y.id===(N==null?void 0:N.id));if(L==="prev"&&J>0){const Y=O[J-1];v(o.items.findIndex(D=>D.id===Y.id))}else if(L==="next"&&J<O.length-1){const Y=O[J+1];v(o.items.findIndex(D=>D.id===Y.id))}},G=()=>{if(!N)return;const L={...N,status:"approved"};$({items:o.items.map(O=>O.id===N.id?L:O)}),B("next")},q=()=>{if(!N)return;const L={...N,status:"rejected"};$({items:o.items.map(O=>O.id===N.id?L:O)}),B("next")},W=async L=>{r&&await r(L)};l.useEffect(()=>{const L=O=>{const J=O.target instanceof HTMLElement?O.target:null;if(m!=="label"||O.defaultPrevented||O.ctrlKey||O.metaKey||O.altKey||J!=null&&J.isContentEditable||J&&/^(INPUT|TEXTAREA|SELECT)$/.test(J.tagName)||O.key==="Enter"&&(J!=null&&J.closest("button, a")))return;const Y=O.key,D=o.labelSchema.classes.find(K=>K.shortcut===Y);D&&(o.type==="classification"?(U(D.id),B("next")):A(D.id)),O.key==="ArrowLeft"||O.key==="a"?B("prev"):(O.key==="ArrowRight"||O.key==="d")&&B("next"),O.key==="Enter"?G():O.key==="Backspace"&&q()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[m,N,o.labelSchema.classes,o.type]);const Q=L=>{switch(L){case"approved":return"var(--nice-success, #22c55e)";case"labeled":return"var(--nice-primary, #3b82f6)";case"review":return"var(--nice-warning, #f59e0b)";case"rejected":return"var(--nice-danger, #ef4444)";default:return"var(--nice-text-secondary, #6b7280)"}};return e.jsxs("div",{className:`nice-data-labeler ${n}`,children:[e.jsxs("header",{className:"nice-data-labeler__header",children:[e.jsxs("div",{className:"nice-data-labeler__header-info",children:[e.jsx("input",{type:"text",value:o.name,onChange:L=>$({name:L.target.value}),className:"nice-data-labeler__project-name-input"}),e.jsxs("div",{className:"nice-data-labeler__progress-bar",children:[e.jsx("div",{className:"nice-data-labeler__progress-fill",style:{width:`${o.statistics.labeled/Math.max(o.statistics.totalItems,1)*100}%`}}),e.jsx("span",{className:"nice-data-labeler__progress-text",children:s("dataLabeler.progress","{labeled} / {total} labeled").replace("{labeled}",String(o.statistics.labeled)).replace("{total}",String(o.statistics.totalItems))})]})]}),e.jsx("div",{className:"nice-data-labeler__header-tabs",children:["label","schema","review","export"].map(L=>e.jsx("button",{className:`nice-data-labeler__tab-button ${m===L?"nice-data-labeler__tab-button--active":""}`,onClick:()=>p(L),children:s(`dataLabeler.tab.${L}`,ji[L])},L))}),e.jsx("button",{className:"nice-data-labeler__shortcuts-button",onClick:()=>h(!b),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"nice-data-labeler__content",children:[m==="label"&&e.jsxs("div",{className:"nice-data-labeler__label-panel",children:[e.jsxs("div",{className:"nice-data-labeler__label-toolbar",children:[e.jsxs("div",{className:"nice-data-labeler__tool-group",children:[e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="select"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>M("select"),children:[e.jsx(T.NiceIcon,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(o.type==="bounding-box"||o.type==="multi-label")&&e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="bbox"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>M("bbox"),children:[e.jsx(T.NiceIcon,{name:"square",size:14})," Box"]}),o.type==="polygon"&&e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="polygon"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>M("polygon"),children:[e.jsx(T.NiceIcon,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"nice-data-labeler__zoom-group",children:[e.jsx("button",{"aria-label":s("dataLabeler.zoomOut","Zoom out"),onClick:()=>I(Math.max(.25,y-.25)),children:e.jsx(T.NiceIcon,{name:"minus",size:14})}),e.jsxs("span",{children:[Math.round(y*100),"%"]}),e.jsx("button",{"aria-label":s("dataLabeler.zoomIn","Zoom in"),onClick:()=>I(Math.min(4,y+.25)),children:e.jsx(T.NiceIcon,{name:"plus",size:14})})]}),e.jsxs("div",{className:"nice-data-labeler__navigation-group",children:[e.jsxs("button",{onClick:()=>B("prev"),disabled:u===0,children:[e.jsx(T.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[u+1," / ",o.items.length]}),e.jsxs("button",{onClick:()=>B("next"),disabled:u>=o.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx(T.NiceIcon,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"nice-data-labeler__label-workspace",children:[e.jsx("div",{className:"nice-data-labeler__canvas-container",ref:S,children:N?e.jsxs(e.Fragment,{children:[N.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:N.data.url,alt:s("dataLabeler.labelingItem","Labeling item"),className:"nice-data-labeler__labeling-image",style:{transform:`scale(${y})`}}),e.jsx("canvas",{ref:k,className:"nice-data-labeler__labeling-canvas",onMouseDown:X,onMouseMove:C,onMouseUp:x,onMouseLeave:x,style:{transform:`scale(${y})`,cursor:R==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"nice-data-labeler__annotations-overlay",style:{transform:`scale(${y})`},children:[N.labels.filter(L=>L.type==="bbox"&&L.data.x!==void 0).map(L=>{const O=o.labelSchema.classes.find(J=>J.id===L.classId);return e.jsxs("div",{className:"nice-data-labeler__bbox-annotation",style:{left:L.data.x,top:L.data.y,width:L.data.width,height:L.data.height,borderColor:(O==null?void 0:O.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"nice-data-labeler__bbox-label",style:{backgroundColor:(O==null?void 0:O.color)||"var(--nice-danger, #ff0000)"},children:O==null?void 0:O.name}),e.jsx("button",{className:"nice-data-labeler__bbox-remove","aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>H(L.id),children:e.jsx(T.NiceIcon,{name:"close",size:12})})]},L.id)}),d&&e.jsx("div",{className:"nice-data-labeler__bbox-drawing",style:{left:d.width<0?d.x+d.width:d.x,top:d.height<0?d.y+d.height:d.y,width:Math.abs(d.width),height:Math.abs(d.height),borderColor:(re=o.labelSchema.classes.find(L=>L.id===w))==null?void 0:re.color}})]})]}),N.data.type==="text"&&e.jsx("div",{className:"nice-data-labeler__text-labeling",children:e.jsx("p",{className:"nice-data-labeler__text-content",children:N.data.text})})]}):e.jsxs("div",{className:"nice-data-labeler__empty-state",children:[e.jsx("span",{className:"nice-data-labeler__icon",children:e.jsx(T.NiceIcon,{name:"clipboard",size:32})}),e.jsx("p",{children:s("dataLabeler.noItemsToLabel","No items to label")})]})}),e.jsxs("aside",{className:"nice-data-labeler__class-sidebar",children:[e.jsx("h3",{children:s("dataLabeler.classes","Classes")}),e.jsx("div",{className:"nice-data-labeler__class-list",children:o.labelSchema.classes.map(L=>e.jsxs("button",{className:`nice-data-labeler__class-button ${w===L.id?"nice-data-labeler__class-button--active":""}`,style:{borderLeftColor:L.color},onClick:()=>{o.type==="classification"?(U(L.id),B("next")):A(L.id)},children:[e.jsx("span",{className:"nice-data-labeler__class-color",style:{backgroundColor:L.color}}),e.jsx("span",{className:"nice-data-labeler__class-name",children:L.name}),L.shortcut&&e.jsx("span",{className:"nice-data-labeler__class-shortcut",children:L.shortcut})]},L.id))}),N&&N.labels.length>0&&e.jsxs("div",{className:"nice-data-labeler__current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),N.labels.map(L=>{const O=o.labelSchema.classes.find(J=>J.id===L.classId);return e.jsxs("div",{className:"nice-data-labeler__label-item",children:[e.jsx("span",{className:"nice-data-labeler__label-color",style:{backgroundColor:O==null?void 0:O.color}}),e.jsx("span",{className:"nice-data-labeler__label-name",children:O==null?void 0:O.name}),e.jsx("button",{"aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>H(L.id),children:e.jsx(T.NiceIcon,{name:"close",size:14})})]},L.id)})]}),m==="label"&&N&&e.jsxs("div",{className:"nice-data-labeler__label-actions",children:[e.jsxs("button",{className:"nice-data-labeler__approve-button",onClick:G,children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"nice-data-labeler__reject-button",onClick:q,children:[e.jsx(T.NiceIcon,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),m==="schema"&&e.jsxs("div",{className:"nice-data-labeler__schema-panel",children:[e.jsxs("div",{className:"nice-data-labeler__panel-header",children:[e.jsx("h2",{children:s("dataLabeler.labelSchema","Label Schema")}),e.jsxs("button",{className:"nice-data-labeler__primary-button",onClick:E,children:[e.jsx(T.NiceIcon,{name:"plus",size:14})," ",s("dataLabeler.addClass","Add Class")]})]}),e.jsxs("div",{className:"nice-data-labeler__schema-settings",children:[e.jsxs("label",{children:[s("dataLabeler.labelingType","Labeling Type"),e.jsxs("select",{value:o.type,onChange:L=>$({type:L.target.value}),children:[e.jsx("option",{value:"classification",children:s("dataLabeler.singleClassification","Single Classification")}),e.jsx("option",{value:"multi-label",children:s("dataLabeler.multiLabelClassification","Multi-Label Classification")}),e.jsx("option",{value:"bounding-box",children:s("dataLabeler.boundingBox","Bounding Box")}),e.jsx("option",{value:"polygon",children:s("dataLabeler.polygon","Polygon")}),e.jsx("option",{value:"segmentation",children:s("dataLabeler.segmentation","Segmentation")}),e.jsx("option",{value:"ner",children:s("dataLabeler.namedEntityRecognition","Named Entity Recognition")})]})]}),e.jsxs("label",{children:[s("dataLabeler.dataType","Data Type"),e.jsxs("select",{value:o.dataType,onChange:L=>$({dataType:L.target.value}),children:[e.jsx("option",{value:"image",children:s("dataLabeler.image","Image")}),e.jsx("option",{value:"text",children:s("dataLabeler.text","Text")}),e.jsx("option",{value:"audio",children:s("dataLabeler.audio","Audio")}),e.jsx("option",{value:"video",children:s("dataLabeler.video","Video")})]})]})]}),e.jsx("div",{className:"nice-data-labeler__classes-list",children:o.labelSchema.classes.map((L,O)=>e.jsxs("div",{className:"nice-data-labeler__class-editor",children:[e.jsx("input",{type:"color",value:L.color,onChange:J=>F(L.id,{color:J.target.value}),className:"nice-data-labeler__color-picker"}),e.jsx("input",{type:"text",value:L.name,onChange:J=>F(L.id,{name:J.target.value}),className:"nice-data-labeler__class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:L.shortcut||"",onChange:J=>F(L.id,{shortcut:J.target.value}),className:"nice-data-labeler__shortcut-input",placeholder:s("dataLabeler.shortcutKeyPlaceholder","Key"),maxLength:1}),e.jsx("button",{className:"nice-data-labeler__remove-class-button","aria-label":s("dataLabeler.removeClass","Remove class"),onClick:()=>z(L.id),children:e.jsx(T.NiceIcon,{name:"trash",size:16})})]},L.id))}),e.jsxs("div",{className:"nice-data-labeler__guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:o.guidelines||"",onChange:L=>$({guidelines:L.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),m==="review"&&e.jsxs("div",{className:"nice-data-labeler__review-panel",children:[e.jsxs("div",{className:"nice-data-labeler__panel-header",children:[e.jsx("h2",{children:s("dataLabeler.reviewLabels","Review Labels")}),e.jsx("div",{className:"nice-data-labeler__filter-group",children:e.jsxs("select",{value:_,onChange:L=>f(L.target.value),children:[e.jsx("option",{value:"all",children:s("dataLabeler.allItems","All Items")}),e.jsx("option",{value:"labeled",children:s("dataLabeler.labeled","Labeled")}),e.jsx("option",{value:"review",children:s("dataLabeler.needsReview","Needs Review")}),e.jsx("option",{value:"approved",children:s("dataLabeler.approved","Approved")}),e.jsx("option",{value:"rejected",children:s("dataLabeler.rejected","Rejected")})]})})]}),e.jsx("div",{className:"nice-data-labeler__items-grid",children:o.items.filter(L=>_==="all"||L.status===_).map((L,O)=>{var J;return e.jsxs("div",{className:`nice-data-labeler__item-card ${u===o.items.indexOf(L)?"nice-data-labeler__item-card--active":""}`,onClick:()=>{v(o.items.indexOf(L)),p("label")},children:[L.data.type==="image"&&e.jsx("img",{src:L.data.url,alt:`Item ${O+1}`,className:"nice-data-labeler__item-thumbnail"}),L.data.type==="text"&&e.jsxs("p",{className:"nice-data-labeler__item-text-preview",children:[(J=L.data.text)==null?void 0:J.slice(0,100),"..."]}),e.jsxs("div",{className:"nice-data-labeler__item-footer",children:[e.jsx("span",{className:"nice-data-labeler__status-dot",style:{backgroundColor:Q(L.status)}}),e.jsx("span",{children:s("dataLabeler.labelCount","{count} labels").replace("{count}",String(L.labels.length))})]})]},L.id)})})]}),m==="export"&&e.jsxs("div",{className:"nice-data-labeler__export-panel",children:[e.jsx("div",{className:"nice-data-labeler__panel-header",children:e.jsx("h2",{children:s("dataLabeler.exportLabels","Export Labels")})}),e.jsxs("div",{className:"nice-data-labeler__export-stats",children:[e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.totalItems}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.totalItems","Total Items")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.labeled}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.labeled","Labeled")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.approved}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.approved","Approved")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.labelSchema.classes.length}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.classes","Classes")})]})]}),e.jsxs("div",{className:"nice-data-labeler__export-formats",children:[e.jsx("h3",{children:s("dataLabeler.exportFormat","Export Format")}),e.jsxs("div",{className:"nice-data-labeler__format-grid",children:[e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>W("coco"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"box",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.cocoJson","COCO JSON")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.cocoDesc","Common format for object detection")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>W("voc"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"file",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.pascalVoc","Pascal VOC")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.vocDesc","XML format for bounding boxes")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>W("yolo"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"zap",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.yolo","YOLO")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.yoloDesc","Text format for YOLO models")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>W("csv"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:"CSV"}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.csvDesc","Tabular format for classification")})]})]})]}),e.jsxs("div",{className:"nice-data-labeler__class-distribution",children:[e.jsx("h3",{children:s("dataLabeler.classDistribution","Class Distribution")}),e.jsx("div",{className:"nice-data-labeler__distribution-bars",children:o.statistics.byClass.map(L=>{const O=o.labelSchema.classes.find(Y=>Y.id===L.classId),J=L.count/Math.max(o.statistics.labeled,1)*100;return e.jsxs("div",{className:"nice-data-labeler__distribution-row",children:[e.jsx("span",{className:"nice-data-labeler__class-name",style:{color:O==null?void 0:O.color},children:O==null?void 0:O.name}),e.jsx("div",{className:"nice-data-labeler__bar-container",children:e.jsx("div",{className:"nice-data-labeler__bar-fill",style:{width:`${J}%`,backgroundColor:O==null?void 0:O.color}})}),e.jsx("span",{className:"nice-data-labeler__count",children:L.count})]},L.classId)})})]})]})]}),b&&e.jsx("div",{className:"nice-data-labeler__shortcuts-modal",children:e.jsxs("div",{className:"nice-data-labeler__modal-content",children:[e.jsxs("div",{className:"nice-data-labeler__modal-header",children:[e.jsx("h3",{children:s("dataLabeler.keyboardShortcuts","Keyboard Shortcuts")}),e.jsx("button",{"aria-label":s("dataLabeler.close","Close"),onClick:()=>h(!1),children:e.jsx(T.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-data-labeler__shortcuts-list",children:[e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsxs("span",{className:"nice-data-labeler__keys",children:[e.jsx(T.NiceIcon,{name:"arrow-left",size:14})," / A"]}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.previousItem","Previous item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsxs("span",{className:"nice-data-labeler__keys",children:[e.jsx(T.NiceIcon,{name:"arrow-right",size:14})," / D"]}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.nextItem","Next item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:s("dataLabeler.enterKey","Enter")}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.approveItem","Approve item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:s("dataLabeler.backspaceKey","Backspace")}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.rejectItem","Reject item")})]}),o.labelSchema.classes.map(L=>L.shortcut&&e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:L.shortcut}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.labelAs","Label as {name}").replace("{name}",L.name)})]},L.id))]})]})})]})},Ni={id:T.createId(),name:"Model Endpoint",modelId:"",modelVersion:"1.0.0",status:"stopped",url:"",authentication:{type:"api-key"},metrics:{requestsTotal:0,requestsPerSecond:0,latencyP50:0,latencyP95:0,latencyP99:0,errorRate:0,successRate:100},logs:[]},Si=({endpoint:t,onInference:a,showMetrics:i=!0,showLogs:r=!0,className:n=""})=>{const{t:s}=T.useNiceTranslation(),[o,c]=l.useState(t||Ni),[m,p]=l.useState("test"),[u,v]=l.useState("text"),[w,A]=l.useState(""),[R,M]=l.useState("{}"),[P,g]=l.useState(null),[d,j]=l.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[y,I]=l.useState(null),[b,h]=l.useState(!1),[_,f]=l.useState(null),[k,S]=l.useState([]),[N,$]=l.useState(null),E=l.useRef(null),z=x=>{var G;const B=(G=x.target.files)==null?void 0:G[0];if(B){const q=new FileReader;q.onload=W=>{var Q;g((Q=W.target)==null?void 0:Q.result)},q.readAsDataURL(B)}},F=async()=>{if(!a){f("No inference handler provided");return}h(!0),f(null),I(null);const x=[];switch(u){case"text":x.push({type:"text",data:w});break;case"image":P&&x.push({type:"image",data:P});break;case"json":try{x.push({type:"json",data:JSON.parse(R)})}catch{f("Invalid JSON input"),h(!1);return}break;case"tabular":try{x.push({type:"tabular",data:JSON.parse(R)})}catch{f("Invalid tabular data"),h(!1);return}break}const B={inputs:x,parameters:d};try{const G=Date.now(),q=await a(B),W=Date.now()-G;I(q),c(Q=>({...Q,metrics:{...Q.metrics,requestsTotal:Q.metrics.requestsTotal+1,latencyP50:(Q.metrics.latencyP50+W)/2},logs:[{timestamp:new Date,requestId:q.requestId,duration:W,status:"success",inputSize:JSON.stringify(x).length,outputSize:JSON.stringify(q.predictions).length},...Q.logs.slice(0,99)]}))}catch(G){const q=G instanceof Error?G.message:"Inference failed";f(q),c(W=>({...W,metrics:{...W.metrics,requestsTotal:W.metrics.requestsTotal+1,errorRate:(W.metrics.errorRate*W.metrics.requestsTotal+1)/(W.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:T.createId(),duration:0,status:"error",inputSize:JSON.stringify(x).length,outputSize:0,error:q},...W.logs.slice(0,99)]}))}finally{h(!1)}},U=async x=>{if(a){$(0),S([]);for(let B=0;B<x.length;B++){const G={inputs:[x[B]],parameters:d};try{const q=await a(G);S(W=>[...W,q])}catch(q){console.error("Batch item failed:",q)}$((B+1)/x.length*100)}$(null)}},H=x=>x<1e3?`${x.toFixed(0)}ms`:`${(x/1e3).toFixed(2)}s`,X=x=>x.toLocaleTimeString(),C=(x,B)=>e.jsxs("div",{className:"nice-model-inference__prediction-item",children:[x.label&&e.jsxs("div",{className:"nice-model-inference__prediction-label",children:[e.jsx("span",{className:"nice-model-inference__label-name",children:x.label}),x.confidence!==void 0&&e.jsxs("span",{className:"nice-model-inference__confidence-badge",style:{backgroundColor:`hsl(${x.confidence*120}, 70%, 40%)`},children:[(x.confidence*100).toFixed(1),"%"]})]}),x.score!==void 0&&e.jsxs("div",{className:"nice-model-inference__prediction-score",children:[e.jsx("span",{className:"nice-model-inference__score-label",children:"Score:"}),e.jsx("span",{className:"nice-model-inference__score-value",children:x.score.toFixed(4)})]}),x.text&&e.jsx("div",{className:"nice-model-inference__prediction-text",children:e.jsx("pre",{children:x.text})}),x.bbox&&e.jsx("div",{className:"nice-model-inference__prediction-bbox",children:e.jsxs("span",{children:["Box: (",x.bbox.x,", ",x.bbox.y,") - ",x.bbox.width,"×",x.bbox.height]})}),x.raw!==void 0&&x.raw!==null&&e.jsxs("details",{className:"nice-model-inference__raw-output",children:[e.jsx("summary",{children:s("modelInference.rawOutput","Raw Output")}),e.jsx("pre",{children:JSON.stringify(x.raw,null,2)})]})]},B);return e.jsxs("div",{className:`nice-model-inference ${n}`,children:[e.jsxs("header",{className:"nice-model-inference__header",children:[e.jsxs("div",{className:"nice-model-inference__header-info",children:[e.jsx("h2",{children:o.name}),e.jsx("span",{className:`nice-model-inference__status-badge nice-model-inference__status-badge--${o.status}`,children:o.status})]}),e.jsxs("div",{className:"nice-model-inference__header-tabs",children:[e.jsx("button",{className:`nice-model-inference__tab-button ${m==="test"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("test"),children:s("modelInference.test","Test")}),e.jsx("button",{className:`nice-model-inference__tab-button ${m==="batch"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("batch"),children:s("modelInference.batch","Batch")}),i&&e.jsx("button",{className:`nice-model-inference__tab-button ${m==="metrics"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("metrics"),children:s("modelInference.metrics","Metrics")}),r&&e.jsx("button",{className:`nice-model-inference__tab-button ${m==="logs"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("logs"),children:s("modelInference.logs","Logs")})]})]}),e.jsxs("div",{className:"nice-model-inference__content",children:[m==="test"&&e.jsxs("div",{className:"nice-model-inference__test-panel",children:[e.jsxs("div",{className:"nice-model-inference__input-section",children:[e.jsx("div",{className:"nice-model-inference__input-type-selector",children:["text","image","json","tabular"].map(x=>e.jsx("button",{className:`nice-model-inference__type-button ${u===x?"nice-model-inference__type-button--active":""}`,onClick:()=>v(x),children:x.charAt(0).toUpperCase()+x.slice(1)},x))}),e.jsxs("div",{className:"nice-model-inference__input-area",children:[u==="text"&&e.jsx("textarea",{value:w,onChange:x=>A(x.target.value),placeholder:s("modelInference.enterTextInput","Enter text input..."),rows:6,className:"nice-model-inference__text-input"}),u==="image"&&e.jsx("div",{className:"nice-model-inference__image-input",children:P?e.jsxs("div",{className:"nice-model-inference__image-preview",children:[e.jsx("img",{src:P,alt:s("modelInference.inputPreview","Input preview")}),e.jsx("button",{className:"nice-model-inference__clear-button",onClick:()=>g(null),children:s("modelInference.clear","Clear")})]}):e.jsxs("label",{className:"nice-model-inference__upload-zone",children:[e.jsx("input",{ref:E,type:"file",accept:"image/*",onChange:z,hidden:!0}),e.jsx("span",{className:"nice-model-inference__upload-icon",children:e.jsx(T.NiceIcon,{name:"image",size:32})}),e.jsx("span",{children:s("modelInference.clickOrDragToUpload","Click or drag to upload image")})]})}),(u==="json"||u==="tabular")&&e.jsx("textarea",{value:R,onChange:x=>M(x.target.value),placeholder:u==="json"?`{
|
|
12
12
|
"key": "value"
|
|
13
13
|
}`:`[
|
|
14
14
|
{"col1": "value1", "col2": "value2"}
|
|
15
|
-
]`,rows:10,className:"
|
|
16
|
-
`);c=
|
|
17
|
-
`);c=
|
|
18
|
-
`);c=
|
|
15
|
+
]`,rows:10,className:"nice-model-inference__json-input"})]}),e.jsxs("div",{className:"nice-model-inference__parameters-section",children:[e.jsx("h4",{children:s("modelInference.parameters","Parameters")}),e.jsxs("div",{className:"nice-model-inference__parameters-grid",children:[e.jsxs("label",{children:[s("modelInference.temperature","Temperature"),e.jsx("input",{type:"number",value:d.temperature,onChange:x=>j({...d,temperature:parseFloat(x.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:[s("modelInference.topK","Top K"),e.jsx("input",{type:"number",value:d.topK,onChange:x=>j({...d,topK:parseInt(x.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:[s("modelInference.topP","Top P"),e.jsx("input",{type:"number",value:d.topP,onChange:x=>j({...d,topP:parseFloat(x.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:[s("modelInference.threshold","Threshold"),e.jsx("input",{type:"number",value:d.threshold,onChange:x=>j({...d,threshold:parseFloat(x.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"nice-model-inference__run-button",onClick:F,disabled:b||!w&&!P&&R==="{}",children:b?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"nice-model-inference__output-section",children:[e.jsx("h3",{children:s("modelInference.output","Output")}),_&&e.jsxs("div",{className:"nice-model-inference__error-message",children:[e.jsx("span",{className:"nice-model-inference__error-icon",children:e.jsx(T.NiceIcon,{name:"warning",size:16})}),_]}),y&&e.jsxs("div",{className:"nice-model-inference__result-container",children:[e.jsxs("div",{className:"nice-model-inference__result-meta",children:[e.jsxs("span",{children:["Request ID: ",y.requestId]}),e.jsxs("span",{children:["Latency: ",H(y.latency)]}),e.jsxs("span",{children:["Model: ",y.modelVersion]})]}),e.jsx("div",{className:"nice-model-inference__predictions-list",children:y.predictions.map((x,B)=>C(x,B))})]}),!_&&!y&&e.jsxs("div",{className:"nice-model-inference__empty-output",children:[e.jsx("span",{className:"nice-model-inference__icon",children:e.jsx(T.NiceIcon,{name:"upload",size:32})}),e.jsx("p",{children:s("modelInference.runInferenceToSeeResults","Run inference to see results")})]})]})]}),m==="batch"&&e.jsxs("div",{className:"nice-model-inference__batch-panel",children:[e.jsxs("div",{className:"nice-model-inference__batch-upload",children:[e.jsx("h3",{children:s("modelInference.batchInference","Batch Inference")}),e.jsx("p",{className:"nice-model-inference__hint",children:s("modelInference.uploadAFileWithMultiple","Upload a file with multiple inputs for batch processing")}),e.jsxs("label",{className:"nice-model-inference__upload-zone",children:[e.jsx("input",{type:"file",accept:".json,.csv,.txt",onChange:async x=>{var G;const B=(G=x.target.files)==null?void 0:G[0];if(B){const q=await B.text();try{const W=JSON.parse(q);if(Array.isArray(W)){const Q=W.map(re=>({type:"json",data:re}));U(Q)}}catch{f("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"nice-model-inference__upload-icon",children:e.jsx(T.NiceIcon,{name:"folder",size:32})}),e.jsx("span",{children:s("modelInference.uploadJsonArrayFile","Upload JSON array file")})]})]}),N!==null&&e.jsxs("div",{className:"nice-model-inference__batch-progress",children:[e.jsx("div",{className:"nice-model-inference__progress-bar",children:e.jsx("div",{className:"nice-model-inference__progress-fill",style:{width:`${N}%`}})}),e.jsxs("span",{children:[Math.round(N),"%"]})]}),k.length>0&&e.jsxs("div",{className:"nice-model-inference__batch-results",children:[e.jsxs("h3",{children:["Results (",k.length,")"]}),e.jsx("div",{className:"nice-model-inference__results-list",children:k.map((x,B)=>e.jsxs("div",{className:"nice-model-inference__batch-result-item",children:[e.jsxs("span",{className:"nice-model-inference__result-index",children:["#",B+1]}),x.predictions.map((G,q)=>e.jsxs("span",{className:"nice-model-inference__result-prediction",children:[G.label,": ",(G.confidence||G.score||0).toFixed(1),"%"]},q))]},B))})]})]}),m==="metrics"&&i&&e.jsxs("div",{className:"nice-model-inference__metrics-panel",children:[e.jsxs("div",{className:"nice-model-inference__metrics-grid",children:[e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:o.metrics.requestsTotal}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.totalRequests","Total Requests")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:o.metrics.requestsPerSecond.toFixed(1)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:"Requests/sec"})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:H(o.metrics.latencyP50)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p50Latency","P50 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:H(o.metrics.latencyP95)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p95Latency","P95 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:H(o.metrics.latencyP99)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p99Latency","P99 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsxs("span",{className:"nice-model-inference__metric-value",children:[o.metrics.successRate.toFixed(1),"%"]}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.successRate","Success Rate")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsxs("span",{className:"nice-model-inference__metric-value",children:[(o.metrics.errorRate*100).toFixed(2),"%"]}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.errorRate","Error Rate")})]})]}),e.jsxs("div",{className:"nice-model-inference__latency-histogram",children:[e.jsx("h3",{children:s("modelInference.latencyDistribution","Latency Distribution")}),e.jsx("div",{className:"nice-model-inference__histogram-bars",children:[10,25,50,75,90,95,99].map(x=>e.jsxs("div",{className:"nice-model-inference__histogram-bar",children:[e.jsx("div",{className:"nice-model-inference__bar-fill",style:{height:`${Math.min(100,o.metrics.latencyP50*x/100)}px`}}),e.jsxs("span",{className:"nice-model-inference__percentile-label",children:["P",x]})]},x))})]})]}),m==="logs"&&r&&e.jsxs("div",{className:"nice-model-inference__logs-panel",children:[e.jsxs("div",{className:"nice-model-inference__logs-header",children:[e.jsx("h3",{children:s("modelInference.requestLogs","Request Logs")}),e.jsx("button",{className:"nice-model-inference__clear-logs-button",onClick:()=>c(x=>({...x,logs:[]})),children:s("modelInference.clearLogs","Clear Logs")})]}),e.jsx("div",{className:"nice-model-inference__logs-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:s("modelInference.time","Time")}),e.jsx("th",{children:s("modelInference.requestId","Request ID")}),e.jsx("th",{children:s("modelInference.duration","Duration")}),e.jsx("th",{children:s("modelInference.status","Status")}),e.jsx("th",{children:s("modelInference.inputSize","Input Size")}),e.jsx("th",{children:s("modelInference.outputSize","Output Size")})]})}),e.jsx("tbody",{children:o.logs.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"nice-model-inference__empty-logs",children:s("modelInference.noLogsYet","No logs yet")})}):o.logs.map((x,B)=>e.jsxs("tr",{className:`nice-model-inference__log-row nice-model-inference__log-row--${x.status}`,children:[e.jsx("td",{children:X(x.timestamp)}),e.jsx("td",{className:"nice-model-inference__request-id",children:x.requestId.slice(0,8)}),e.jsx("td",{children:H(x.duration)}),e.jsx("td",{children:e.jsx("span",{className:`nice-model-inference__status-badge nice-model-inference__status-badge--${x.status}`,children:x.status})}),e.jsxs("td",{children:[x.inputSize," B"]}),e.jsxs("td",{children:[x.outputSize," B"]})]},B))})]})})]})]})]})};class ne{constructor(a){this.abortController=null,this.config={timeout:3e4,maxRetries:3,retryDelay:1e3,...a}}async healthCheck(){try{return(await this.chat({messages:[{role:"user",content:"Hi"}],maxTokens:5})).choices.length>0}catch{return!1}}async fetchWithRetry(a,i,r=this.config.maxRetries){let n=null;for(let s=0;s<=r;s++)try{this.abortController=new AbortController;const o=setTimeout(()=>{var m;return(m=this.abortController)==null?void 0:m.abort()},this.config.timeout),c=await fetch(a,{...i,signal:this.abortController.signal});if(clearTimeout(o),c.ok)return c;if(c.status>=400&&c.status<500){const m=await c.text();throw new Error(`API Error ${c.status}: ${m}`)}n=new Error(`HTTP ${c.status}`)}catch(o){n=o,s<r&&await this.delay(this.config.retryDelay*(s+1))}throw n??new Error("Request failed after retries")}delay(a){return new Promise(i=>setTimeout(i,a))}async parseSSEStream(a,i,r,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:u}=await s.read();if(p)break;c+=o.decode(u,{stream:!0});const v=c.split(`
|
|
16
|
+
`);c=v.pop()||"";for(const w of v)if(w.startsWith("data: ")){const A=w.slice(6).trim();if(A==="[DONE]"){r==null||r();return}try{const R=JSON.parse(A);i(this.normalizeStreamChunk(R))}catch{}}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}}class ke extends ne{constructor(a){super(a),this.type="openai",this.name="OpenAI",this.baseUrl=a.baseUrl||"https://api.openai.com/v1"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(r,a)}async chatStream(a,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseSSEStream(s,i,r,n)}catch(s){n==null||n(s)}}async listModels(){return((await(await this.fetchWithRetry(`${this.baseUrl}/models`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers}})).json()).data||[]).filter(r=>r.id.includes("gpt")).map(r=>r.id)}buildRequestBody(a){return{model:a.model||this.config.model||"gpt-4o-mini",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,top_p:a.topP,frequency_penalty:a.frequencyPenalty,presence_penalty:a.presencePenalty,stop:a.stop,functions:a.functions,function_call:a.functionCall}}normalizeResponse(a,i){const r=a;return{id:r.id,model:r.model,choices:r.choices.map(n=>({index:n.index,message:n.message,finishReason:n.finish_reason})),usage:{promptTokens:r.usage.prompt_tokens,completionTokens:r.usage.completion_tokens,totalTokens:r.usage.total_tokens},estimatedCost:this.estimateCost(r.model,r.usage.prompt_tokens,r.usage.completion_tokens)}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}estimateCost(a,i,r){const n={"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"gpt-4":{input:30,output:60},"gpt-3.5-turbo":{input:.5,output:1.5}},s=Object.keys(n).find(c=>a.includes(c)),o=s?n[s]:n["gpt-4o-mini"];return i/1e6*o.input+r/1e6*o.output}}class pa extends ne{constructor(a){super(a),this.type="anthropic",this.name="Anthropic Claude",this.baseUrl=a.baseUrl||"https://api.anthropic.com/v1"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(r)}async chatStream(a,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseAnthropicStream(s,i,r,n)}catch(s){n==null||n(s)}}buildRequestBody(a){const i=a.messages.find(n=>n.role==="system"),r=a.messages.filter(n=>n.role!=="system");return{model:a.model||this.config.model||"claude-3-5-sonnet-20241022",max_tokens:a.maxTokens??1024,system:i==null?void 0:i.content,messages:r.map(n=>({role:n.role==="assistant"?"assistant":"user",content:n.content})),temperature:a.temperature??.7}}normalizeResponse(a){const i=a,r=i.content.find(n=>n.type==="text");return{id:i.id,model:i.model,choices:[{index:0,message:{role:"assistant",content:(r==null?void 0:r.text)||""},finishReason:i.stop_reason==="end_turn"?"stop":"length"}],usage:{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.input_tokens+i.usage.output_tokens},estimatedCost:this.estimateCost(i.model,i.usage.input_tokens,i.usage.output_tokens)}}normalizeStreamChunk(a){var r;const i=a;return{id:"",choices:[{index:i.index||0,delta:{content:((r=i.delta)==null?void 0:r.text)||""},finishReason:i.type==="message_stop"?"stop":null}]}}async parseAnthropicStream(a,i,r,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:u}=await s.read();if(p)break;c+=o.decode(u,{stream:!0});const v=c.split(`
|
|
17
|
+
`);c=v.pop()||"";for(const w of v)if(w.startsWith("data: "))try{const A=JSON.parse(w.slice(6));if(A.type==="content_block_delta")i(this.normalizeStreamChunk(A));else if(A.type==="message_stop"){r==null||r();return}}catch{}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}estimateCost(a,i,r){const n={"claude-3-5-sonnet":{input:3,output:15},"claude-3-5-haiku":{input:.25,output:1.25},"claude-3-opus":{input:15,output:75},"claude-3-sonnet":{input:3,output:15},"claude-3-haiku":{input:.25,output:1.25}},s=Object.keys(n).find(c=>a.includes(c)),o=s?n[s]:n["claude-3-5-sonnet"];return i/1e6*o.input+r/1e6*o.output}}class ga extends ne{constructor(a){if(super(a),this.type="azure-openai",this.name="Azure OpenAI",!a.baseUrl||!a.deployment)throw new Error("Azure OpenAI requires baseUrl and deployment")}async chat(a){const i=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`,n=await(await this.fetchWithRetry(i,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(n)}async chatStream(a,i,r,n){const s=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`;try{const o=await this.fetchWithRetry(s,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseSSEStream(o,i,r,n)}catch(o){n==null||n(o)}}buildRequestBody(a){return{messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,top_p:a.topP,frequency_penalty:a.frequencyPenalty,presence_penalty:a.presencePenalty,stop:a.stop}}normalizeResponse(a){const i=a;return{id:i.id,model:i.model,choices:i.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:i.usage.prompt_tokens,completionTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens}}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}class ha extends ne{constructor(a){super(a),this.type="ollama",this.name="Ollama (Local)",this.baseUrl=a.baseUrl||"http://localhost:11434"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama3",messages:a.messages,stream:!1,options:{temperature:a.temperature??.7,num_predict:a.maxTokens??1024}})})).json();return this.normalizeResponse(r)}async chatStream(a,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama3",messages:a.messages,stream:!0,options:{temperature:a.temperature??.7,num_predict:a.maxTokens??1024}})});await this.parseOllamaStream(s,i,r,n)}catch(s){n==null||n(s)}}async listModels(){try{return((await(await this.fetchWithRetry(`${this.baseUrl}/api/tags`,{method:"GET"})).json()).models||[]).map(r=>r.name)}catch{return[]}}normalizeResponse(a){const i=a;return{id:`ollama-${Date.now()}`,model:i.model,choices:[{index:0,message:i.message,finishReason:i.done?"stop":null}],usage:{promptTokens:i.prompt_eval_count||0,completionTokens:i.eval_count||0,totalTokens:(i.prompt_eval_count||0)+(i.eval_count||0)},estimatedCost:0}}normalizeStreamChunk(a){var r;const i=a;return{id:`ollama-${Date.now()}`,choices:[{index:0,delta:{content:((r=i.message)==null?void 0:r.content)||""},finishReason:i.done?"stop":null}]}}async parseOllamaStream(a,i,r,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:u}=await s.read();if(p)break;c+=o.decode(u,{stream:!0});const v=c.split(`
|
|
18
|
+
`);c=v.pop()||"";for(const w of v)if(w.trim())try{const A=JSON.parse(w);if(i(this.normalizeStreamChunk(A)),A.done){r==null||r();return}}catch{}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}}class fa extends ne{constructor(a){super(a),this.type="groq",this.name="Groq",this.baseUrl=a.baseUrl||"https://api.groq.com/openai/v1"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama-3.1-70b-versatile",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024})})).json();return this.normalizeResponse(r)}async chatStream(a,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama-3.1-70b-versatile",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,stream:!0})});await this.parseSSEStream(s,i,r,n)}catch(s){n==null||n(s)}}normalizeResponse(a){const i=a;return{id:i.id,model:i.model,choices:i.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:i.usage.prompt_tokens,completionTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens},estimatedCost:0}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}function ae(t){switch(t.type){case"openai":return new ke(t);case"anthropic":return new pa(t);case"azure-openai":return new ga(t);case"ollama":return new ha(t);case"groq":return new fa(t);case"custom":return new ke(t);default:throw new Error(`Unsupported provider type: ${t.type}`)}}function V(t){const a=new URL(t.endpoint),i=a.host.toLowerCase(),r=a.pathname.replace(/\/+$/,""),n=m=>`${a.protocol}//${a.host}${r.endsWith(m)?r.slice(0,-m.length):r}`,s={apiKey:t.apiKey,model:t.model,headers:t.headers},o=/^(.*)\/openai\/deployments\/([^/]+)\/chat\/completions$/.exec(r);if(i.endsWith("azure.com")&&o)return ae({type:"azure-openai",...s,baseUrl:`${a.protocol}//${a.host}${o[1]}`,deployment:o[2],apiVersion:a.searchParams.get("api-version")??void 0});if(i.includes("anthropic.com"))return ae({type:"anthropic",...s,baseUrl:n("/messages")});if(i.endsWith(":11434")||i.includes("ollama"))return ae({type:"ollama",...s,baseUrl:n("/api/chat")});const c=i.includes("openai.com")?"openai":i.includes("groq.com")?"groq":"custom";return ae({type:c,...s,baseUrl:n("/chat/completions")})}function ie(t,a){for(const n of t.variables)if(n.required&&!(n.name in a)&&!n.default)throw new Error(`Missing required variable: ${n.name}`);const i={};for(const n of t.variables)i[n.name]=a[n.name]??n.default;const r=n=>n.replace(/\{\{#if (\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(o,c,m)=>{const p=i[c];return p==null||p===""||p===!1||Array.isArray(p)&&p.length===0?"":m}).replace(/\{\{(\w+)\}\}/g,(o,c)=>{const m=i[c];return m===void 0?`{{${c}}}`:typeof m=="object"?JSON.stringify(m,null,2):String(m)});return{system:r(t.system),user:r(t.user),metadata:{templateId:t.id,variables:i,timestamp:Date.now()}}}const oe={id:"data-grid-filter",name:"DataGrid Natural Language Filter",description:"Convert natural language queries to DataGrid filter configurations",category:"data-query",system:`You are a filter query generator for a data grid component.
|
|
19
19
|
Given column definitions and a natural language query, generate a JSON filter configuration.
|
|
20
20
|
|
|
21
21
|
Available filter operators:
|
|
@@ -48,7 +48,7 @@ Generate the filter configuration:`,variables:[{name:"columns",description:"JSON
|
|
|
48
48
|
{ "column": "city", "operator": "equals", "value": "New York" }
|
|
49
49
|
],
|
|
50
50
|
"logic": "and"
|
|
51
|
-
}`}],suggestedTemperature:.2,maxTokens:512},
|
|
51
|
+
}`}],suggestedTemperature:.2,maxTokens:512},le={id:"data-grid-sort",name:"DataGrid Natural Language Sort",description:"Convert natural language to sort configuration",category:"data-query",system:`You are a sort configuration generator for a data grid.
|
|
52
52
|
Given columns and a natural language request, generate sort configuration.
|
|
53
53
|
|
|
54
54
|
Output format:
|
|
@@ -66,7 +66,7 @@ Keywords mapping:
|
|
|
66
66
|
|
|
67
67
|
Request: "{{query}}"
|
|
68
68
|
|
|
69
|
-
Generate sort configuration:`,variables:[{name:"columns",description:"Column definitions",required:!0,type:"json"},{name:"query",description:"Natural language sort request",required:!0,type:"string"}],suggestedTemperature:.1,maxTokens:256},
|
|
69
|
+
Generate sort configuration:`,variables:[{name:"columns",description:"Column definitions",required:!0,type:"json"},{name:"query",description:"Natural language sort request",required:!0,type:"string"}],suggestedTemperature:.1,maxTokens:256},de={id:"form-builder",name:"Form Generation from Description",description:"Generate form configuration from natural language description",category:"form-generation",system:`You are a form builder AI. Generate form configurations from descriptions.
|
|
70
70
|
|
|
71
71
|
Available field types:
|
|
72
72
|
- text, email, phone, url, password
|
|
@@ -116,7 +116,7 @@ Generate the form configuration:`,variables:[{name:"description",description:"Na
|
|
|
116
116
|
{ "id": "message", "type": "textarea", "label": "Message", "required": true }
|
|
117
117
|
],
|
|
118
118
|
"layout": { "columns": 1 }
|
|
119
|
-
}`}],suggestedTemperature:.5,maxTokens:2048},
|
|
119
|
+
}`}],suggestedTemperature:.5,maxTokens:2048},ue={id:"chart-config",name:"Chart Configuration Generator",description:"Generate chart configuration from data description",category:"chart-config",system:`You are a data visualization expert. Generate chart configurations from descriptions.
|
|
120
120
|
|
|
121
121
|
Available chart types:
|
|
122
122
|
- line, area, bar, column
|
|
@@ -156,7 +156,7 @@ Available data fields: {{data}}
|
|
|
156
156
|
Context: {{context}}
|
|
157
157
|
{{/if}}
|
|
158
158
|
|
|
159
|
-
Generate the chart configuration:`,variables:[{name:"request",description:"Natural language chart request",required:!0,type:"string"},{name:"data",description:"Available data fields",required:!1,type:"json"},{name:"context",description:"Additional context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},
|
|
159
|
+
Generate the chart configuration:`,variables:[{name:"request",description:"Natural language chart request",required:!0,type:"string"},{name:"data",description:"Available data fields",required:!1,type:"json"},{name:"context",description:"Additional context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},me={id:"code-completion",name:"Code Completion",description:"Complete code based on context",category:"code-completion",system:`You are an expert programmer. Complete the code based on context.
|
|
160
160
|
|
|
161
161
|
Rules:
|
|
162
162
|
- Match the existing code style
|
|
@@ -219,7 +219,7 @@ Available roles: {{roles}}
|
|
|
219
219
|
Systems involved: {{systems}}
|
|
220
220
|
{{/if}}
|
|
221
221
|
|
|
222
|
-
Generate the workflow definition:`,variables:[{name:"description",description:"Process description",required:!0,type:"string"},{name:"roles",description:"Available roles/departments",required:!1,type:"array"},{name:"systems",description:"Systems involved",required:!1,type:"array"}],suggestedTemperature:.3,maxTokens:2048},
|
|
222
|
+
Generate the workflow definition:`,variables:[{name:"description",description:"Process description",required:!0,type:"string"},{name:"roles",description:"Available roles/departments",required:!1,type:"array"},{name:"systems",description:"Systems involved",required:!1,type:"array"}],suggestedTemperature:.3,maxTokens:2048},ge={id:"report-layout",name:"Report Layout Generator",description:"Generate report layout from description",category:"report",system:`You are a report designer. Generate report layouts from descriptions.
|
|
223
223
|
|
|
224
224
|
Available report elements:
|
|
225
225
|
- header, footer
|
|
@@ -257,7 +257,7 @@ Output JSON:
|
|
|
257
257
|
Available data sources: {{dataSources}}
|
|
258
258
|
{{/if}}
|
|
259
259
|
|
|
260
|
-
Generate the report layout:`,variables:[{name:"description",description:"Report description",required:!0,type:"string"},{name:"dataSources",description:"Available data sources",required:!1,type:"json"}],suggestedTemperature:.4,maxTokens:2048},
|
|
260
|
+
Generate the report layout:`,variables:[{name:"description",description:"Report description",required:!0,type:"string"},{name:"dataSources",description:"Available data sources",required:!1,type:"json"}],suggestedTemperature:.4,maxTokens:2048},Ne={id:"theme-generator",name:"Theme Generator from Brand Colors",description:"Generate complete theme from brand colors",category:"theme",system:`You are a UI/UX designer specializing in design systems.
|
|
261
261
|
Generate a complete theme from brand colors following accessibility guidelines.
|
|
262
262
|
|
|
263
263
|
Rules:
|
|
@@ -297,7 +297,7 @@ Output JSON:
|
|
|
297
297
|
{{#if industry}}Industry: {{industry}}{{/if}}
|
|
298
298
|
{{#if style}}Style preference: {{style}}{{/if}}
|
|
299
299
|
|
|
300
|
-
Generate the complete theme:`,variables:[{name:"primaryColor",description:"Primary brand color (hex)",required:!0,type:"string"},{name:"secondaryColor",description:"Secondary brand color (hex)",required:!1,type:"string"},{name:"accentColor",description:"Accent color (hex)",required:!1,type:"string"},{name:"industry",description:"Industry (healthcare, finance, etc.)",required:!1,type:"string"},{name:"style",description:"Style preference (modern, classic, playful)",required:!1,type:"string"}],suggestedTemperature:.5,maxTokens:2048},
|
|
300
|
+
Generate the complete theme:`,variables:[{name:"primaryColor",description:"Primary brand color (hex)",required:!0,type:"string"},{name:"secondaryColor",description:"Secondary brand color (hex)",required:!1,type:"string"},{name:"accentColor",description:"Accent color (hex)",required:!1,type:"string"},{name:"industry",description:"Industry (healthcare, finance, etc.)",required:!1,type:"string"},{name:"style",description:"Style preference (modern, classic, playful)",required:!1,type:"string"}],suggestedTemperature:.5,maxTokens:2048},Se={id:"accessibility-checker",name:"Accessibility Checker",description:"Check and fix accessibility issues in HTML/JSX",category:"accessibility",system:`You are a web accessibility expert (WCAG 2.1 AA/AAA certified).
|
|
301
301
|
Analyze code for accessibility issues and provide fixes.
|
|
302
302
|
|
|
303
303
|
Check for:
|
|
@@ -324,7 +324,7 @@ Output JSON:
|
|
|
324
324
|
],
|
|
325
325
|
"score": 0-100,
|
|
326
326
|
"summary": "Brief summary of findings"
|
|
327
|
-
}`,user:"Analyze this code for accessibility issues:\n\n```{{language}}\n{{code}}\n```\n\nReturn accessibility analysis:",variables:[{name:"code",description:"Code to analyze",required:!0,type:"string"},{name:"language",description:"Code language (html, jsx, tsx)",required:!1,type:"string",default:"jsx"}],suggestedTemperature:.2,maxTokens:2048},
|
|
327
|
+
}`,user:"Analyze this code for accessibility issues:\n\n```{{language}}\n{{code}}\n```\n\nReturn accessibility analysis:",variables:[{name:"code",description:"Code to analyze",required:!0,type:"string"},{name:"language",description:"Code language (html, jsx, tsx)",required:!1,type:"string",default:"jsx"}],suggestedTemperature:.2,maxTokens:2048},Ce={id:"translation",name:"UI Translation",description:"Translate UI text maintaining context and formatting",category:"translation",system:`You are a professional UI translator.
|
|
328
328
|
Translate text while:
|
|
329
329
|
- Preserving placeholders like {name}, {{count}}, %s
|
|
330
330
|
- Maintaining ICU message format syntax
|
|
@@ -342,7 +342,7 @@ Output JSON:
|
|
|
342
342
|
|
|
343
343
|
{{texts}}
|
|
344
344
|
|
|
345
|
-
Provide translations:`,variables:[{name:"sourceLanguage",description:"Source language",required:!0,type:"string"},{name:"targetLanguage",description:"Target language",required:!0,type:"string"},{name:"texts",description:"JSON object with keys and texts to translate",required:!0,type:"json"}],suggestedTemperature:.3,maxTokens:2048},
|
|
345
|
+
Provide translations:`,variables:[{name:"sourceLanguage",description:"Source language",required:!0,type:"string"},{name:"targetLanguage",description:"Target language",required:!0,type:"string"},{name:"texts",description:"JSON object with keys and texts to translate",required:!0,type:"json"}],suggestedTemperature:.3,maxTokens:2048},Ie={id:"summarize-data",name:"Data Summarization",description:"Summarize tabular data into insights",category:"summarization",system:`You are a data analyst. Summarize data into actionable insights.
|
|
346
346
|
|
|
347
347
|
Provide:
|
|
348
348
|
- Key statistics (min, max, mean, median)
|
|
@@ -366,7 +366,7 @@ Format output as structured JSON:
|
|
|
366
366
|
|
|
367
367
|
{{#if context}}Context: {{context}}{{/if}}
|
|
368
368
|
|
|
369
|
-
Provide summary and insights:`,variables:[{name:"data",description:"Data to summarize (JSON or CSV)",required:!0,type:"string"},{name:"context",description:"Business context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},fe={[ce.id]:ce,[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[pe.id]:pe,[me.id]:me,[ke.id]:ke,[Ne.id]:Ne,[Se.id]:Se,[Ce.id]:Ce};function wt(i){return fe[i]}function jt(i){return Object.values(fe).filter(a=>a.category===i)}function kt(){return Object.keys(fe)}class $e{constructor(){this.records=new Map}async save(a,t){const r=this.records.get(a)||[];this.records.set(a,[...r,...t])}async load(a,t,r){const n=this.records.get(a)||[];return!t&&!r?n:n.filter(s=>!(t&&s.timestamp<t.getTime()||r&&s.timestamp>r.getTime()))}async clear(a,t){if(!t)this.records.delete(a);else{const r=this.records.get(a)||[];this.records.set(a,r.filter(n=>n.timestamp>=t.getTime()))}}}class pa{constructor(){this.prefix="nice2dev-ai-cost:"}async save(a,t){if(typeof window>"u")return;const r=`${this.prefix}${a}`,s=[...JSON.parse(localStorage.getItem(r)||"[]"),...t],o=Date.now()-720*60*60*1e3,c=s.filter(h=>h.timestamp>o);localStorage.setItem(r,JSON.stringify(c))}async load(a,t,r){if(typeof window>"u")return[];const n=`${this.prefix}${a}`,s=JSON.parse(localStorage.getItem(n)||"[]");return!t&&!r?s:s.filter(o=>!(t&&o.timestamp<t.getTime()||r&&o.timestamp>r.getTime()))}async clear(a,t){if(typeof window>"u")return;const r=`${this.prefix}${a}`;if(!t)localStorage.removeItem(r);else{const n=JSON.parse(localStorage.getItem(r)||"[]");localStorage.setItem(r,JSON.stringify(n.filter(s=>s.timestamp>=t.getTime())))}}}class ma{constructor(a,t){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new $e,this.budgetConfig={monthlyBudget:100,dailyBudget:10,maxTokensPerRequest:4096,maxRequestsPerMinute:30,maxRequestsPerDay:1e3,alertThresholds:[50,80,90,100],...t}}async recordUsage(a,t){const r={...t,id:this.generateId(),timestamp:Date.now()};this.pendingRecords.push(r),this.updateCounters(a),this.scheduleFlush(a);const n=await this.getBudgetStatus(a);this.checkAlerts(a,n)}async canMakeRequest(a){const t=await this.getBudgetStatus(a);return t.isOverBudget?{allowed:!1,reason:"Budget exceeded"}:this.budgetConfig.maxRequestsPerMinute&&t.requestsThisMinute>=this.budgetConfig.maxRequestsPerMinute?{allowed:!1,reason:"Rate limit exceeded (per minute)"}:this.budgetConfig.maxRequestsPerDay&&t.requestsToday>=this.budgetConfig.maxRequestsPerDay?{allowed:!1,reason:"Daily request limit exceeded"}:{allowed:!0}}async getBudgetStatus(a){const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()),n=new Date(t.getFullYear(),t.getMonth(),1),s=await this.storage.load(a,r),o=await this.storage.load(a,n),c=s.reduce((M,C)=>M+C.estimatedCost,0),h=o.reduce((M,C)=>M+C.estimatedCost,0),p=this.budgetConfig.dailyBudget||1/0,m=this.budgetConfig.monthlyBudget||1/0,b=p?c/p*100:0,w=m?h/m*100:0,k=[];for(const M of this.budgetConfig.alertThresholds||[])b>=M&&k.push(`Daily budget ${M}% used`),w>=M&&k.push(`Monthly budget ${M}% used`);return{dailyUsed:c,dailyRemaining:Math.max(0,p-c),dailyPercent:b,monthlyUsed:h,monthlyRemaining:Math.max(0,m-h),monthlyPercent:w,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:c>=p||h>=m,alerts:k}}async getUsageStats(a,t,r){const n=await this.storage.load(a,t,r),s={totalRequests:n.length,totalTokens:0,totalPromptTokens:0,totalCompletionTokens:0,totalCost:0,averageLatency:0,errorCount:0,cacheHitRate:0,byModel:{},byFeature:{},byDay:{}};let o=0,c=0;for(const h of n){s.totalTokens+=h.totalTokens,s.totalPromptTokens+=h.promptTokens,s.totalCompletionTokens+=h.completionTokens,s.totalCost+=h.estimatedCost,o+=h.latencyMs,h.error&&s.errorCount++,h.cached&&c++,s.byModel[h.model]||(s.byModel[h.model]={requests:0,tokens:0,cost:0}),s.byModel[h.model].requests++,s.byModel[h.model].tokens+=h.totalTokens,s.byModel[h.model].cost+=h.estimatedCost;const p=h.feature||"unknown";s.byFeature[p]||(s.byFeature[p]={requests:0,tokens:0,cost:0}),s.byFeature[p].requests++,s.byFeature[p].tokens+=h.totalTokens,s.byFeature[p].cost+=h.estimatedCost;const m=new Date(h.timestamp).toISOString().split("T")[0];s.byDay[m]||(s.byDay[m]={requests:0,tokens:0,cost:0}),s.byDay[m].requests++,s.byDay[m].tokens+=h.totalTokens,s.byDay[m].cost+=h.estimatedCost}return n.length>0&&(s.averageLatency=o/n.length,s.cacheHitRate=c/n.length),s}onAlert(a){return this.alertCallbacks.push(a),()=>{const t=this.alertCallbacks.indexOf(a);t>=0&&this.alertCallbacks.splice(t,1)}}setBudgetConfig(a){this.budgetConfig={...this.budgetConfig,...a}}async clearUsage(a,t){await this.storage.clear(a,t)}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}updateCounters(a){const t=Date.now(),r=t-6e4,n=this.minuteCounter.get(a)||[];n.push(t),this.minuteCounter.set(a,n.filter(c=>c>r));const s=new Date().toISOString().split("T")[0],o=`${a}:${s}`;this.dayCounter.set(o,(this.dayCounter.get(o)||0)+1)}getMinuteCount(a){const r=Date.now()-6e4;return(this.minuteCounter.get(a)||[]).filter(s=>s>r).length}scheduleFlush(a){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.pendingRecords.length>0&&(await this.storage.save(a,this.pendingRecords),this.pendingRecords=[])},1e3))}checkAlerts(a,t){if(t.alerts.length!==0)for(const r of t.alerts)for(const n of this.alertCallbacks)try{n(r,t)}catch{}}}function Nt(i,a){const t=d.useRef(null),[r,n]=d.useState(null),[s,o]=d.useState(null),[c,h]=d.useState(!0);d.useEffect(()=>{const w=typeof window<"u"?new pa:new $e;t.current=new ma(w,a);const k=t.current.onAlert(M=>{console.warn(`[AI Cost Alert] ${M}`)});return()=>{k()}},[]);const p=d.useCallback(async()=>{if(t.current){h(!0);try{const[w,k]=await Promise.all([t.current.getBudgetStatus(i),t.current.getUsageStats(i)]);n(w),o(k)}finally{h(!1)}}},[i]);d.useEffect(()=>{p()},[p]);const m=d.useCallback(async w=>{t.current&&(await t.current.recordUsage(i,w),await p())},[i,p]),b=d.useCallback(async()=>t.current?t.current.canMakeRequest(i):{allowed:!0},[i]);return{status:r,stats:s,loading:c,recordUsage:m,canMakeRequest:b,refresh:p}}class St{constructor(a=100,t=36e5){this.cache=new Map,this.maxSize=a,this.ttl=t}hashRequest(a){const t=JSON.stringify({messages:a.messages,model:a.model,temperature:a.temperature});let r=0;for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);r=(r<<5)-r+s,r=r&r}return r.toString(36)}get(a){const t=this.hashRequest(a),r=this.cache.get(t);return r?Date.now()-r.timestamp>this.ttl?(this.cache.delete(t),null):r.response:null}set(a,t){const r=this.hashRequest(a);if(this.cache.size>=this.maxSize){const n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(r,{request:r,response:t,timestamp:Date.now()})}clear(){this.cache.clear()}}class ga{constructor(a,t){this.backupProviders=[],this.circuitBreakers=new Map,this.primaryProvider=a,this.config={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:[],cacheTTL:36e5,offlineConfig:void 0,circuitBreakerThreshold:5,circuitBreakerResetTime:6e4,onFallback:void 0,...t},this.cache=new St(100,this.config.cacheTTL);for(const r of this.config.backupProviders||[])this.backupProviders.push(ee(r));this.config.offlineConfig&&(this.offlineProvider=ee(this.config.offlineConfig))}async chat(a){if(this.isCircuitOpen(this.primaryProvider.type))return this.executeWithFallback(a,new Error("Circuit breaker open"));try{const t=await this.primaryProvider.chat(a);return this.cache.set(a,t),this.resetCircuitBreaker(this.primaryProvider.type),t}catch(t){return this.recordFailure(this.primaryProvider.type),this.executeWithFallback(a,t)}}async executeWithFallback(a,t){var r,n;for(const s of this.config.strategies)try{const o=await this.executeStrategy(s,a,t);if(o)return(n=(r=this.config).onFallback)==null||n.call(r,s,t),o}catch{}throw new Error(`All fallback strategies failed. Original error: ${t.message}`)}async executeStrategy(a,t,r){switch(a){case"retry":return this.retryStrategy(t);case"failover":return this.failoverStrategy(t);case"cache":return this.cacheStrategy(t);case"offline":return this.offlineStrategy(t);case"graceful-degrade":return this.gracefulDegradeStrategy(t,r);case"circuit-breaker":return this.openCircuitBreaker(this.primaryProvider.type),null;default:return null}}async retryStrategy(a){let t=this.config.retryDelay;for(let r=0;r<this.config.maxRetries;r++){await this.delay(t);try{const n=await this.primaryProvider.chat(a);return this.cache.set(a,n),n}catch{t*=this.config.backoffMultiplier}}return null}async failoverStrategy(a){for(const t of this.backupProviders)if(!this.isCircuitOpen(t.type))try{const r=await t.chat(a);return this.cache.set(a,r),r}catch{this.recordFailure(t.type)}return null}cacheStrategy(a){const t=this.cache.get(a);return t?{...t,id:`cached-${t.id}`}:null}async offlineStrategy(a){if(!this.offlineProvider)return null;try{return await this.offlineProvider.chat(a)}catch{return null}}gracefulDegradeStrategy(a,t){const r=[...a.messages].reverse().find(n=>n.role==="user");return{id:`degraded-${Date.now()}`,model:"fallback",choices:[{index:0,message:{role:"assistant",content:this.generateDegradedResponse((r==null?void 0:r.content)||"",t)},finishReason:"stop"}],usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}generateDegradedResponse(a,t){return a.toLowerCase().includes("filter")||a.toLowerCase().includes("show")?JSON.stringify({filters:[],logic:"and"}):a.toLowerCase().includes("form")||a.toLowerCase().includes("create")?JSON.stringify({title:"Form",fields:[{id:"field1",type:"text",label:"Field 1"}]}):a.toLowerCase().includes("chart")||a.toLowerCase().includes("graph")?JSON.stringify({type:"bar",title:"Chart",data:{source:"data"}}):`I'm sorry, I couldn't process your request at this time. The service is temporarily unavailable. Please try again later or contact support. (Error: ${t.message.substring(0,50)})`}isCircuitOpen(a){const t=this.circuitBreakers.get(a);return t&&t.isOpen?Date.now()-t.lastFailure>this.config.circuitBreakerResetTime?(this.resetCircuitBreaker(a),!1):!0:!1}recordFailure(a){const t=this.circuitBreakers.get(a)||{failures:0,lastFailure:0,isOpen:!1};t.failures++,t.lastFailure=Date.now(),t.failures>=this.config.circuitBreakerThreshold&&(t.isOpen=!0),this.circuitBreakers.set(a,t)}openCircuitBreaker(a){this.circuitBreakers.set(a,{failures:this.config.circuitBreakerThreshold,lastFailure:Date.now(),isOpen:!0})}resetCircuitBreaker(a){this.circuitBreakers.delete(a)}delay(a){return new Promise(t=>setTimeout(t,a))}addBackupProvider(a){this.backupProviders.push(a)}setOfflineProvider(a){this.offlineProvider=a}clearCache(){this.cache.clear()}resetAllCircuitBreakers(){this.circuitBreakers.clear()}getCircuitBreakerStatus(){const a={};for(const[t,r]of this.circuitBreakers)a[t]={...r};return a}async healthCheck(){const a={};a[this.primaryProvider.type]=await this.primaryProvider.healthCheck();for(const t of this.backupProviders)a[`backup-${t.type}`]=await t.healthCheck();return this.offlineProvider&&(a.offline=await this.offlineProvider.healthCheck()),a}}function ha(i,a){const t=ee(i);return new ga(t,a)}function Ct(i,a){const t={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:a?[a]:[],circuitBreakerThreshold:5,circuitBreakerResetTime:6e4};return typeof window>"u"&&(t.offlineConfig={type:"ollama",model:"llama3"}),ha(i,t)}function fa(i){const{columns:a,config:t,onFilterGenerated:r,onSortGenerated:n,onError:s}=i,o=Z(),{t:c,lang:h}=A.useNiceTranslation(),[p,m]=d.useState(!1),[b,w]=d.useState(null),[k,M]=d.useState(null),[C,O]=d.useState([]),_=d.useRef(null),l=t||(o==null?void 0:o.config),y=d.useMemo(()=>a.map(g=>({id:g.id,label:g.label,type:g.type,...g.options?{options:g.options}:{}})),[a]),S=d.useCallback(async g=>{var v;if(!l){const T="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(T),{type:"filter",error:T}}m(!0),w(g);const x=performance.now();(v=_.current)==null||v.abort(),_.current=new AbortController;try{const T=K(l),I=g.toLowerCase(),N=I.includes("sort")||I.includes("order")||I.includes("arrange")||I.includes("by highest")||I.includes("by lowest"),P=I.includes("show")||I.includes("find")||I.includes("filter")||I.includes("where")||I.includes("with")||I.includes("only"),$=h!=="en"&&!N&&!P,D=N||$,F=P||!N,U={type:"combined"};if(F){const W=ae(ce,{columns:y,query:g}),Y=await T.chat({messages:[{role:"system",content:W.system},{role:"user",content:W.user}],temperature:.2,maxTokens:512}),u=Tt(Y);u&&(!$||u.filters.length>0)&&(U.filterConfig=u,U.type="filter",r==null||r(u))}if(D){const W=ae(oe,{columns:y,query:g}),Y=await T.chat({messages:[{role:"system",content:W.system},{role:"user",content:W.user}],temperature:.1,maxTokens:256}),u=At(Y);u&&(!$||u.sort.length>0)&&(U.sortConfig=u,U.type=U.filterConfig?"combined":"sort",n==null||n(u))}return U.latencyMs=performance.now()-x,M(U),O(W=>[...W.slice(-9),{query:g,result:U}]),U}catch(T){const I=T instanceof Error?T.message:c("dataGridAI.requestFailed","AI request failed"),N={type:"filter",error:I,latencyMs:performance.now()-x};return M(N),s==null||s(I),N}finally{m(!1)}},[l,y,r,n,s,c,h]),f=d.useCallback(()=>{w(null),M(null)},[]),j=d.useCallback(()=>{var g;(g=_.current)==null||g.abort(),m(!1)},[]);return d.useEffect(()=>()=>{var g;(g=_.current)==null||g.abort()},[]),{processQuery:S,loading:p,lastQuery:b,lastResult:k,history:C,clearResults:f,abort:j,isConfigured:!!l}}function Tt(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.filters&&Array.isArray(c.filters))return{filters:c.filters,logic:c.logic||"and",confidence:c.confidence,explanation:c.explanation}}catch{}return null}function At(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.sort&&Array.isArray(c.sort))return{sort:c.sort,confidence:c.confidence}}catch{}return null}function It({columns:i,config:a,onFilter:t,onSort:r,placeholder:n,showHistory:s=!0,showSuggestions:o=!0,className:c,style:h}){const{t:p}=A.useNiceTranslation(),[m,b]=d.useState(""),[w,k]=d.useState(!1),M=d.useRef(null),{processQuery:C,loading:O,lastResult:_,history:l,isConfigured:y}=fa({columns:i,config:a,onFilterGenerated:t,onSortGenerated:r}),S=d.useMemo(()=>{if(!o||i.length===0)return[];const v=[],T=(D,F,U)=>p(D,F).replace("{column}",U.label),I=i.filter(D=>D.type==="string");I.length>0&&v.push(T("dataGridAI.suggest.contains",'Show rows where {column} contains "example"',I[0]));const N=i.filter(D=>D.type==="number");N.length>0&&(v.push(T("dataGridAI.suggest.greaterThan","{column} greater than 100",N[0])),v.push(T("dataGridAI.suggest.sortHighest","Sort by highest {column}",N[0])));const P=i.filter(D=>D.type==="date");P.length>0&&(v.push(T("dataGridAI.suggest.lastDays","{column} in the last 7 days",P[0])),v.push(T("dataGridAI.suggest.sortNewest","Sort by newest {column}",P[0])));const $=i.filter(D=>{var F;return D.type==="enum"&&((F=D.options)==null?void 0:F.length)});return $.length>0&&$[0].options&&v.push(T("dataGridAI.suggest.equals","Where {column} is {value}",$[0]).replace("{value}",$[0].options[0])),v.slice(0,5)},[i,o,p]),f=async()=>{!m.trim()||O||(await C(m.trim()),k(!1))},j=v=>{v.key==="Enter"?(v.preventDefault(),f()):v.key==="Escape"&&k(!1)},g=v=>{var T;b(v),k(!1),(T=M.current)==null||T.focus()},x=v=>{b(v),k(!1),C(v)};return y?e.jsxs("div",{className:`nice-datagrid-ai ${c||""}`,style:h,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx(A.NiceIcon,{name:"search",size:16})}),e.jsx("input",{ref:M,type:"text",value:m,onChange:v=>b(v.target.value),onKeyDown:j,onFocus:()=>k(!0),onBlur:()=>setTimeout(()=>k(!1),200),placeholder:n??p("dataGridAI.queryPlaceholder",'Ask AI to filter or sort data... (e.g., "show orders from last week")'),className:"nice-datagrid-ai__input",disabled:O,"aria-label":p("dataGridAI.queryInput","AI query input")}),O?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:f,className:"nice-datagrid-ai__submit",disabled:!m.trim(),"aria-label":p("dataGridAI.submitQuery","Submit query"),children:e.jsx(A.NiceIcon,{name:"send",size:16})})]}),w&&(S.length>0||s&&l.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[o&&S.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:p("dataGridAI.suggestions","Suggestions")}),S.map((v,T)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>g(v),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(A.NiceIcon,{name:"lightbulb",size:14})}),v]},T))]}),s&&l.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:p("dataGridAI.recent","Recent")}),l.slice(-5).reverse().map((v,T)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>x(v.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(A.NiceIcon,{name:"clock",size:14})}),v.query,v.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx(A.NiceIcon,{name:"warning",size:14})})]},T))]})]}),_&&!_.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[_.filterConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:_.filterConfig.filters.length===1?p("dataGridAI.filterApplied","1 filter applied"):p("dataGridAI.filtersApplied","{count} filters applied").replace("{count}",String(_.filterConfig.filters.length))}),_.sortConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:p("dataGridAI.sortedBy","Sorted by {columns}").replace("{columns}",_.sortConfig.sort.map(v=>{var T;return((T=i.find(I=>I.id===v.column))==null?void 0:T.label)??v.column}).join(", "))}),_.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(_.latencyMs),"ms"]})]}),(_==null?void 0:_.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:_.error}),e.jsx("style",{children:`
|
|
369
|
+
Provide summary and insights:`,variables:[{name:"data",description:"Data to summarize (JSON or CSV)",required:!0,type:"string"},{name:"context",description:"Business context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},xe={[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[me.id]:me,[pe.id]:pe,[ge.id]:ge,[Ne.id]:Ne,[Se.id]:Se,[Ce.id]:Ce,[Ie.id]:Ie};function Ci(t){return xe[t]}function Ii(t){return Object.values(xe).filter(a=>a.category===t)}function Ai(){return Object.keys(xe)}class Oe{constructor(){this.records=new Map}async save(a,i){const r=this.records.get(a)||[];this.records.set(a,[...r,...i])}async load(a,i,r){const n=this.records.get(a)||[];return!i&&!r?n:n.filter(s=>!(i&&s.timestamp<i.getTime()||r&&s.timestamp>r.getTime()))}async clear(a,i){if(!i)this.records.delete(a);else{const r=this.records.get(a)||[];this.records.set(a,r.filter(n=>n.timestamp>=i.getTime()))}}}class xa{constructor(){this.prefix="nice2dev-ai-cost:"}async save(a,i){if(typeof window>"u")return;const r=`${this.prefix}${a}`,s=[...JSON.parse(localStorage.getItem(r)||"[]"),...i],o=Date.now()-720*60*60*1e3,c=s.filter(m=>m.timestamp>o);localStorage.setItem(r,JSON.stringify(c))}async load(a,i,r){if(typeof window>"u")return[];const n=`${this.prefix}${a}`,s=JSON.parse(localStorage.getItem(n)||"[]");return!i&&!r?s:s.filter(o=>!(i&&o.timestamp<i.getTime()||r&&o.timestamp>r.getTime()))}async clear(a,i){if(typeof window>"u")return;const r=`${this.prefix}${a}`;if(!i)localStorage.removeItem(r);else{const n=JSON.parse(localStorage.getItem(r)||"[]");localStorage.setItem(r,JSON.stringify(n.filter(s=>s.timestamp>=i.getTime())))}}}class ba{constructor(a,i){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new Oe,this.budgetConfig={monthlyBudget:100,dailyBudget:10,maxTokensPerRequest:4096,maxRequestsPerMinute:30,maxRequestsPerDay:1e3,alertThresholds:[50,80,90,100],...i}}async recordUsage(a,i){const r={...i,id:this.generateId(),timestamp:Date.now()};this.pendingRecords.push(r),this.updateCounters(a),this.scheduleFlush(a);const n=await this.getBudgetStatus(a);this.checkAlerts(a,n)}async canMakeRequest(a){const i=await this.getBudgetStatus(a);return i.isOverBudget?{allowed:!1,reason:"Budget exceeded"}:this.budgetConfig.maxRequestsPerMinute&&i.requestsThisMinute>=this.budgetConfig.maxRequestsPerMinute?{allowed:!1,reason:"Rate limit exceeded (per minute)"}:this.budgetConfig.maxRequestsPerDay&&i.requestsToday>=this.budgetConfig.maxRequestsPerDay?{allowed:!1,reason:"Daily request limit exceeded"}:{allowed:!0}}async getBudgetStatus(a){const i=new Date,r=new Date(i.getFullYear(),i.getMonth(),i.getDate()),n=new Date(i.getFullYear(),i.getMonth(),1),s=await this.storage.load(a,r),o=await this.storage.load(a,n),c=s.reduce((R,M)=>R+M.estimatedCost,0),m=o.reduce((R,M)=>R+M.estimatedCost,0),p=this.budgetConfig.dailyBudget||1/0,u=this.budgetConfig.monthlyBudget||1/0,v=p?c/p*100:0,w=u?m/u*100:0,A=[];for(const R of this.budgetConfig.alertThresholds||[])v>=R&&A.push(`Daily budget ${R}% used`),w>=R&&A.push(`Monthly budget ${R}% used`);return{dailyUsed:c,dailyRemaining:Math.max(0,p-c),dailyPercent:v,monthlyUsed:m,monthlyRemaining:Math.max(0,u-m),monthlyPercent:w,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:c>=p||m>=u,alerts:A}}async getUsageStats(a,i,r){const n=await this.storage.load(a,i,r),s={totalRequests:n.length,totalTokens:0,totalPromptTokens:0,totalCompletionTokens:0,totalCost:0,averageLatency:0,errorCount:0,cacheHitRate:0,byModel:{},byFeature:{},byDay:{}};let o=0,c=0;for(const m of n){s.totalTokens+=m.totalTokens,s.totalPromptTokens+=m.promptTokens,s.totalCompletionTokens+=m.completionTokens,s.totalCost+=m.estimatedCost,o+=m.latencyMs,m.error&&s.errorCount++,m.cached&&c++,s.byModel[m.model]||(s.byModel[m.model]={requests:0,tokens:0,cost:0}),s.byModel[m.model].requests++,s.byModel[m.model].tokens+=m.totalTokens,s.byModel[m.model].cost+=m.estimatedCost;const p=m.feature||"unknown";s.byFeature[p]||(s.byFeature[p]={requests:0,tokens:0,cost:0}),s.byFeature[p].requests++,s.byFeature[p].tokens+=m.totalTokens,s.byFeature[p].cost+=m.estimatedCost;const u=new Date(m.timestamp).toISOString().split("T")[0];s.byDay[u]||(s.byDay[u]={requests:0,tokens:0,cost:0}),s.byDay[u].requests++,s.byDay[u].tokens+=m.totalTokens,s.byDay[u].cost+=m.estimatedCost}return n.length>0&&(s.averageLatency=o/n.length,s.cacheHitRate=c/n.length),s}onAlert(a){return this.alertCallbacks.push(a),()=>{const i=this.alertCallbacks.indexOf(a);i>=0&&this.alertCallbacks.splice(i,1)}}setBudgetConfig(a){this.budgetConfig={...this.budgetConfig,...a}}async clearUsage(a,i){await this.storage.clear(a,i)}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}updateCounters(a){const i=Date.now(),r=i-6e4,n=this.minuteCounter.get(a)||[];n.push(i),this.minuteCounter.set(a,n.filter(c=>c>r));const s=new Date().toISOString().split("T")[0],o=`${a}:${s}`;this.dayCounter.set(o,(this.dayCounter.get(o)||0)+1)}getMinuteCount(a){const r=Date.now()-6e4;return(this.minuteCounter.get(a)||[]).filter(s=>s>r).length}scheduleFlush(a){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.pendingRecords.length>0&&(await this.storage.save(a,this.pendingRecords),this.pendingRecords=[])},1e3))}checkAlerts(a,i){if(i.alerts.length!==0)for(const r of i.alerts)for(const n of this.alertCallbacks)try{n(r,i)}catch{}}}function Ti(t,a){const i=l.useRef(null),[r,n]=l.useState(null),[s,o]=l.useState(null),[c,m]=l.useState(!0);l.useEffect(()=>{const w=typeof window<"u"?new xa:new Oe;i.current=new ba(w,a);const A=i.current.onAlert(R=>{console.warn(`[AI Cost Alert] ${R}`)});return()=>{A()}},[]);const p=l.useCallback(async()=>{if(i.current){m(!0);try{const[w,A]=await Promise.all([i.current.getBudgetStatus(t),i.current.getUsageStats(t)]);n(w),o(A)}finally{m(!1)}}},[t]);l.useEffect(()=>{p()},[p]);const u=l.useCallback(async w=>{i.current&&(await i.current.recordUsage(t,w),await p())},[t,p]),v=l.useCallback(async()=>i.current?i.current.canMakeRequest(t):{allowed:!0},[t]);return{status:r,stats:s,loading:c,recordUsage:u,canMakeRequest:v,refresh:p}}class Ri{constructor(a=100,i=36e5){this.cache=new Map,this.maxSize=a,this.ttl=i}hashRequest(a){const i=JSON.stringify({messages:a.messages,model:a.model,temperature:a.temperature});let r=0;for(let n=0;n<i.length;n++){const s=i.charCodeAt(n);r=(r<<5)-r+s,r=r&r}return r.toString(36)}get(a){const i=this.hashRequest(a),r=this.cache.get(i);return r?Date.now()-r.timestamp>this.ttl?(this.cache.delete(i),null):r.response:null}set(a,i){const r=this.hashRequest(a);if(this.cache.size>=this.maxSize){const n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(r,{request:r,response:i,timestamp:Date.now()})}clear(){this.cache.clear()}}class ya{constructor(a,i){this.backupProviders=[],this.circuitBreakers=new Map,this.primaryProvider=a,this.config={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:[],cacheTTL:36e5,offlineConfig:void 0,circuitBreakerThreshold:5,circuitBreakerResetTime:6e4,onFallback:void 0,...i},this.cache=new Ri(100,this.config.cacheTTL);for(const r of this.config.backupProviders||[])this.backupProviders.push(ae(r));this.config.offlineConfig&&(this.offlineProvider=ae(this.config.offlineConfig))}async chat(a){if(this.isCircuitOpen(this.primaryProvider.type))return this.executeWithFallback(a,new Error("Circuit breaker open"));try{const i=await this.primaryProvider.chat(a);return this.cache.set(a,i),this.resetCircuitBreaker(this.primaryProvider.type),i}catch(i){return this.recordFailure(this.primaryProvider.type),this.executeWithFallback(a,i)}}async executeWithFallback(a,i){var r,n;for(const s of this.config.strategies)try{const o=await this.executeStrategy(s,a,i);if(o)return(n=(r=this.config).onFallback)==null||n.call(r,s,i),o}catch{}throw new Error(`All fallback strategies failed. Original error: ${i.message}`)}async executeStrategy(a,i,r){switch(a){case"retry":return this.retryStrategy(i);case"failover":return this.failoverStrategy(i);case"cache":return this.cacheStrategy(i);case"offline":return this.offlineStrategy(i);case"graceful-degrade":return this.gracefulDegradeStrategy(i,r);case"circuit-breaker":return this.openCircuitBreaker(this.primaryProvider.type),null;default:return null}}async retryStrategy(a){let i=this.config.retryDelay;for(let r=0;r<this.config.maxRetries;r++){await this.delay(i);try{const n=await this.primaryProvider.chat(a);return this.cache.set(a,n),n}catch{i*=this.config.backoffMultiplier}}return null}async failoverStrategy(a){for(const i of this.backupProviders)if(!this.isCircuitOpen(i.type))try{const r=await i.chat(a);return this.cache.set(a,r),r}catch{this.recordFailure(i.type)}return null}cacheStrategy(a){const i=this.cache.get(a);return i?{...i,id:`cached-${i.id}`}:null}async offlineStrategy(a){if(!this.offlineProvider)return null;try{return await this.offlineProvider.chat(a)}catch{return null}}gracefulDegradeStrategy(a,i){const r=[...a.messages].reverse().find(n=>n.role==="user");return{id:`degraded-${Date.now()}`,model:"fallback",choices:[{index:0,message:{role:"assistant",content:this.generateDegradedResponse((r==null?void 0:r.content)||"",i)},finishReason:"stop"}],usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}generateDegradedResponse(a,i){return a.toLowerCase().includes("filter")||a.toLowerCase().includes("show")?JSON.stringify({filters:[],logic:"and"}):a.toLowerCase().includes("form")||a.toLowerCase().includes("create")?JSON.stringify({title:"Form",fields:[{id:"field1",type:"text",label:"Field 1"}]}):a.toLowerCase().includes("chart")||a.toLowerCase().includes("graph")?JSON.stringify({type:"bar",title:"Chart",data:{source:"data"}}):`I'm sorry, I couldn't process your request at this time. The service is temporarily unavailable. Please try again later or contact support. (Error: ${i.message.substring(0,50)})`}isCircuitOpen(a){const i=this.circuitBreakers.get(a);return i&&i.isOpen?Date.now()-i.lastFailure>this.config.circuitBreakerResetTime?(this.resetCircuitBreaker(a),!1):!0:!1}recordFailure(a){const i=this.circuitBreakers.get(a)||{failures:0,lastFailure:0,isOpen:!1};i.failures++,i.lastFailure=Date.now(),i.failures>=this.config.circuitBreakerThreshold&&(i.isOpen=!0),this.circuitBreakers.set(a,i)}openCircuitBreaker(a){this.circuitBreakers.set(a,{failures:this.config.circuitBreakerThreshold,lastFailure:Date.now(),isOpen:!0})}resetCircuitBreaker(a){this.circuitBreakers.delete(a)}delay(a){return new Promise(i=>setTimeout(i,a))}addBackupProvider(a){this.backupProviders.push(a)}setOfflineProvider(a){this.offlineProvider=a}clearCache(){this.cache.clear()}resetAllCircuitBreakers(){this.circuitBreakers.clear()}getCircuitBreakerStatus(){const a={};for(const[i,r]of this.circuitBreakers)a[i]={...r};return a}async healthCheck(){const a={};a[this.primaryProvider.type]=await this.primaryProvider.healthCheck();for(const i of this.backupProviders)a[`backup-${i.type}`]=await i.healthCheck();return this.offlineProvider&&(a.offline=await this.offlineProvider.healthCheck()),a}}function va(t,a){const i=ae(t);return new ya(i,a)}function Li(t,a){const i={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:a?[a]:[],circuitBreakerThreshold:5,circuitBreakerResetTime:6e4};return typeof window>"u"&&(i.offlineConfig={type:"ollama",model:"llama3"}),va(t,i)}const zi=[];function _a(t){const{columns:a,config:i,onFilterGenerated:r,onSortGenerated:n,onError:s}=t,o=ee(),{t:c,lang:m}=T.useNiceTranslation(),[p,u]=l.useState(!1),[v,w]=l.useState(null),[A,R]=l.useState(null),[M,P]=l.useState([]),g=l.useRef(null),d=i||(o==null?void 0:o.config),j=l.useMemo(()=>a.map(h=>({id:h.id,label:h.label,type:h.type,...h.options?{options:h.options}:{}})),[a]),y=l.useCallback(async h=>{var f;if(!d){const k="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(k),{type:"filter",error:k}}u(!0),w(h);const _=performance.now();(f=g.current)==null||f.abort(),g.current=new AbortController;try{const k=V(d),S=h.toLowerCase(),N=S.includes("sort")||S.includes("order")||S.includes("arrange")||S.includes("by highest")||S.includes("by lowest"),$=S.includes("show")||S.includes("find")||S.includes("filter")||S.includes("where")||S.includes("with")||S.includes("only"),E=m!=="en"&&!N&&!$,z=N||E,F=$||!N,U={type:"combined"};if(F){const H=ie(oe,{columns:j,query:h}),X=await k.chat({messages:[{role:"system",content:H.system},{role:"user",content:H.user}],temperature:.2,maxTokens:512}),C=Mi(X);C&&(!E||C.filters.length>0)&&(U.filterConfig=C,U.type="filter",r==null||r(C))}if(z){const H=ie(le,{columns:j,query:h}),X=await k.chat({messages:[{role:"system",content:H.system},{role:"user",content:H.user}],temperature:.1,maxTokens:256}),C=$i(X);C&&(!E||C.sort.length>0)&&(U.sortConfig=C,U.type=U.filterConfig?"combined":"sort",n==null||n(C))}return U.latencyMs=performance.now()-_,R(U),P(H=>[...H.slice(-9),{query:h,result:U}]),U}catch(k){const S=k instanceof Error?k.message:c("dataGridAI.requestFailed","AI request failed"),N={type:"filter",error:S,latencyMs:performance.now()-_};return R(N),s==null||s(S),N}finally{u(!1)}},[d,j,r,n,s,c,m]),I=l.useCallback(()=>{w(null),R(null)},[]),b=l.useCallback(()=>{var h;(h=g.current)==null||h.abort(),u(!1)},[]);return l.useEffect(()=>()=>{var h;(h=g.current)==null||h.abort()},[]),{processQuery:y,loading:p,lastQuery:v,lastResult:A,history:M,clearResults:I,abort:b,isConfigured:!!d}}function Mi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.filters&&Array.isArray(c.filters))return{filters:c.filters,logic:c.logic||"and",confidence:c.confidence,explanation:c.explanation}}catch{}return null}function $i(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.sort&&Array.isArray(c.sort))return{sort:c.sort,confidence:c.confidence}}catch{}return null}function Pi({columns:t=zi,config:a,onFilter:i,onSort:r,placeholder:n,showHistory:s=!0,showSuggestions:o=!0,className:c,style:m}){const{t:p}=T.useNiceTranslation(),[u,v]=l.useState(""),[w,A]=l.useState(!1),R=l.useRef(null),{processQuery:M,loading:P,lastResult:g,history:d,isConfigured:j}=_a({columns:t,config:a,onFilterGenerated:i,onSortGenerated:r}),y=l.useMemo(()=>{if(!o||t.length===0)return[];const f=[],k=(z,F,U)=>p(z,F).replace("{column}",U.label),S=t.filter(z=>z.type==="string");S.length>0&&f.push(k("dataGridAI.suggest.contains",'Show rows where {column} contains "example"',S[0]));const N=t.filter(z=>z.type==="number");N.length>0&&(f.push(k("dataGridAI.suggest.greaterThan","{column} greater than 100",N[0])),f.push(k("dataGridAI.suggest.sortHighest","Sort by highest {column}",N[0])));const $=t.filter(z=>z.type==="date");$.length>0&&(f.push(k("dataGridAI.suggest.lastDays","{column} in the last 7 days",$[0])),f.push(k("dataGridAI.suggest.sortNewest","Sort by newest {column}",$[0])));const E=t.filter(z=>{var F;return z.type==="enum"&&((F=z.options)==null?void 0:F.length)});return E.length>0&&E[0].options&&f.push(k("dataGridAI.suggest.equals","Where {column} is {value}",E[0]).replace("{value}",E[0].options[0])),f.slice(0,5)},[t,o,p]),I=async()=>{!u.trim()||P||(await M(u.trim()),A(!1))},b=f=>{f.key==="Enter"?(f.preventDefault(),I()):f.key==="Escape"&&A(!1)},h=f=>{var k;v(f),A(!1),(k=R.current)==null||k.focus()},_=f=>{v(f),A(!1),M(f)};return j?e.jsxs("div",{className:`nice-datagrid-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx(T.NiceIcon,{name:"search",size:16})}),e.jsx("input",{ref:R,type:"text",value:u,onChange:f=>v(f.target.value),onKeyDown:b,onFocus:()=>A(!0),onBlur:()=>setTimeout(()=>A(!1),200),placeholder:n??p("dataGridAI.queryPlaceholder",'Ask AI to filter or sort data... (e.g., "show orders from last week")'),className:"nice-datagrid-ai__input",disabled:P,"aria-label":p("dataGridAI.queryInput","AI query input")}),P?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:I,className:"nice-datagrid-ai__submit",disabled:!u.trim(),"aria-label":p("dataGridAI.submitQuery","Submit query"),children:e.jsx(T.NiceIcon,{name:"send",size:16})})]}),w&&(y.length>0||s&&d.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[o&&y.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:p("dataGridAI.suggestions","Suggestions")}),y.map((f,k)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>h(f),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(T.NiceIcon,{name:"lightbulb",size:14})}),f]},k))]}),s&&d.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:p("dataGridAI.recent","Recent")}),d.slice(-5).reverse().map((f,k)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>_(f.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(T.NiceIcon,{name:"clock",size:14})}),f.query,f.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx(T.NiceIcon,{name:"warning",size:14})})]},k))]})]}),g&&!g.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[g.filterConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:g.filterConfig.filters.length===1?p("dataGridAI.filterApplied","1 filter applied"):p("dataGridAI.filtersApplied","{count} filters applied").replace("{count}",String(g.filterConfig.filters.length))}),g.sortConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:p("dataGridAI.sortedBy","Sorted by {columns}").replace("{columns}",g.sortConfig.sort.map(f=>{var k;return((k=t.find(S=>S.id===f.column))==null?void 0:k.label)??f.column}).join(", "))}),g.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(g.latencyMs),"ms"]})]}),(g==null?void 0:g.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:g.error}),e.jsx("style",{children:`
|
|
370
370
|
.nice-datagrid-ai {
|
|
371
371
|
position: relative;
|
|
372
372
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
@@ -548,13 +548,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
548
548
|
border-radius: var(--nice-radius-sm, 4px);
|
|
549
549
|
font-size: 13px;
|
|
550
550
|
}
|
|
551
|
-
`})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${c||""}`,style:
|
|
551
|
+
`})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${c||""}`,style:m,children:e.jsx("input",{type:"text",placeholder:p("dataGridAI.notConfigured","AI not configured"),disabled:!0,className:"nice-datagrid-ai__input"})})}function wa(t={}){const{config:a,schema:i,context:r,onFormGenerated:n,onError:s}=t,o=ee(),{t:c}=T.useNiceTranslation(),[m,p]=l.useState(!1),[u,v]=l.useState(null),[w,A]=l.useState(null),[R,M]=l.useState([]),P=l.useRef(null),g=a||(o==null?void 0:o.config),d=l.useCallback(async b=>{var _,f,k;if(!g){const S="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(S),{error:S}}p(!0),v(b);const h=performance.now();(_=P.current)==null||_.abort(),P.current=new AbortController;try{const S=V(g),N=ie(de,{description:b,schema:i?JSON.stringify(i,null,2):void 0,context:r}),$=await S.chat({messages:[{role:"system",content:N.system},{role:"user",content:N.user}],temperature:.5,maxTokens:2048}),E=Oi($),z={config:E||void 0,rawResponse:(k=(f=$.choices[0])==null?void 0:f.message)==null?void 0:k.content,latencyMs:performance.now()-h,error:E?void 0:c("formBuilderAI.parseFailed","Failed to parse form configuration")};return E&&(n==null||n(E)),A(z),M(F=>[...F.slice(-9),{description:b,result:z}]),z}catch(S){const N=S instanceof Error?S.message:c("formBuilderAI.requestFailed","AI request failed"),$={error:N,latencyMs:performance.now()-h};return A($),s==null||s(N),$}finally{p(!1)}},[g,i,r,n,s,c]),j=l.useCallback(async b=>{if(!(w!=null&&w.config))return{error:c("formBuilderAI.nothingToRefine","No form to refine. Generate a form first.")};const h=`
|
|
552
552
|
Modify this existing form based on the following instructions:
|
|
553
553
|
|
|
554
554
|
Current form: ${JSON.stringify(w.config,null,2)}
|
|
555
555
|
|
|
556
|
-
Instructions: ${
|
|
557
|
-
`;return
|
|
556
|
+
Instructions: ${b}
|
|
557
|
+
`;return d(h)},[w,d,c]),y=l.useCallback(()=>{v(null),A(null)},[]),I=l.useCallback(()=>{var b;(b=P.current)==null||b.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var b;(b=P.current)==null||b.abort()},[]),{generateForm:d,refineForm:j,loading:m,lastDescription:u,lastResult:w,history:R,clearResults:y,abort:I,isConfigured:!!g}}function Oi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.fields&&Array.isArray(c.fields))return{title:c.title,description:c.description,fields:c.fields,layout:c.layout,submitLabel:c.submitLabel,validation:c.validation}}catch{}return null}function Ei({config:t,schema:a,context:i,onGenerate:r,placeholder:n,showExamples:s=!0,showPreview:o=!0,className:c,style:m,renderForm:p}){const{t:u}=T.useNiceTranslation(),[v,w]=l.useState(""),[A,R]=l.useState(!1),M=l.useRef(null),{generateForm:P,loading:g,lastResult:d,isConfigured:j}=wa({config:t,schema:a,context:i,onFormGenerated:r}),y=[u("formBuilderAI.example.contact","Simple contact form with name, email, and message"),u("formBuilderAI.example.registration","User registration with email validation and password confirmation"),u("formBuilderAI.example.feedback","Product feedback survey with rating scale and comments"),u("formBuilderAI.example.rsvp","Event RSVP with name, attending status, and dietary restrictions"),u("formBuilderAI.example.jobApplication","Job application with personal info, experience, and file upload"),u("formBuilderAI.example.newsletter","Newsletter subscription with email and preferences")],[I,b=""]=u("formBuilderAI.shortcutHint","Press {keys} to generate").split("{keys}"),h=async()=>{!v.trim()||g||await P(v.trim())},_=S=>{var N;w(S),R(!1),(N=M.current)==null||N.focus()},f=S=>{S.key==="Enter"&&(S.ctrlKey||S.metaKey)&&(S.preventDefault(),h())},k=S=>{w(S.target.value),S.target.style.height="auto",S.target.style.height=Math.min(S.target.scrollHeight,200)+"px"};return j?e.jsxs("div",{className:`nice-form-builder-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-form-builder-ai__input-section",children:[e.jsxs("label",{className:"nice-form-builder-ai__label",children:[e.jsx("span",{className:"nice-form-builder-ai__label-icon",children:e.jsx(T.NiceIcon,{name:"wand",size:16})}),u("formBuilderAI.describeYourForm","Describe your form")]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{"aria-label":u("formBuilderAI.describeYourForm","Describe your form"),ref:M,value:v,onChange:k,onKeyDown:f,placeholder:n??u("formBuilderAI.placeholder",'Describe the form you want to create... (e.g., "Contact form with name, email, subject, and message")'),className:"nice-form-builder-ai__textarea",disabled:g,rows:2}),e.jsxs("div",{className:"nice-form-builder-ai__actions",children:[s&&e.jsxs("div",{className:"nice-form-builder-ai__examples-wrapper",children:[e.jsx("button",{type:"button",onClick:()=>R(!A),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--secondary",children:u("formBuilderAI.examples","Examples")}),A&&e.jsx("div",{className:"nice-form-builder-ai__dropdown",children:y.map((S,N)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>_(S),children:S},N))})]}),e.jsx("button",{type:"button",onClick:h,disabled:!v.trim()||g,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:g?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),u("formBuilderAI.generating","Generating...")]}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"rocket",size:14}),u("formBuilderAI.generateForm","Generate Form")]})})]})]}),e.jsxs("p",{className:"nice-form-builder-ai__hint",children:[I,e.jsx("kbd",{children:u("formBuilderAI.ctrl","Ctrl")}),"+",e.jsx("kbd",{children:u("formBuilderAI.enter","Enter")}),b]})]}),d&&e.jsx("div",{className:"nice-form-builder-ai__result",children:d.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:u("formBuilderAI.errorLabel","Error:")})," ",d.error]}):d.config&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-form-builder-ai__result-header",children:[e.jsx("h3",{className:"nice-form-builder-ai__result-title",children:u("formBuilderAI.generatedForm","Generated Form: {title}").replace("{title}",d.config.title||u("formBuilderAI.untitled","Untitled"))}),d.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(d.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(d.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:u("formBuilderAI.useForm","Use This Form")})]}),d.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:d.config.description}),o&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:p?p(d.config):e.jsx(Di,{config:d.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:u("formBuilderAI.viewJson","View JSON Configuration")}),e.jsx("pre",{children:JSON.stringify(d.config,null,2)})]})]})}),e.jsx("style",{children:`
|
|
558
558
|
.nice-form-builder-ai {
|
|
559
559
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
560
560
|
}
|
|
@@ -775,7 +775,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
775
775
|
color: var(--nice-error, #c62828);
|
|
776
776
|
border-radius: var(--nice-radius-md, 6px);
|
|
777
777
|
}
|
|
778
|
-
`})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${c||""}`,style:
|
|
778
|
+
`})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:u("formBuilderAI.notConfigured","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Di({config:t}){var n,s;const{t:a}=T.useNiceTranslation(),i=o=>{var m,p;const c={id:o.id,placeholder:o.placeholder,required:o.required,disabled:!0};switch(o.type){case"textarea":case"richtext":case"markdown":return e.jsx("textarea",{...c,rows:3,className:"nice-form-preview__input nice-form-preview__textarea"});case"select":case"multiselect":return e.jsxs("select",{...c,className:"nice-form-preview__input nice-form-preview__select",children:[e.jsx("option",{value:"",children:a("formBuilderAI.selectField","Select {label}...").replace("{label}",o.label)}),(m=o.options)==null?void 0:m.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))]});case"radio":return e.jsx("div",{className:"nice-form-preview__radio-group",children:(p=o.options)==null?void 0:p.map(u=>e.jsxs("label",{className:"nice-form-preview__radio",children:[e.jsx("input",{type:"radio",name:o.id,value:u.value,disabled:!0}),u.label]},u.value))});case"checkbox":return e.jsxs("label",{className:"nice-form-preview__checkbox",children:[e.jsx("input",{type:"checkbox",disabled:!0}),o.label]});case"file":case"image":return e.jsx("input",{type:"file",...c,className:"nice-form-preview__input"});case"date":return e.jsx("input",{type:"date",...c,className:"nice-form-preview__input"});case"time":return e.jsx("input",{type:"time",...c,className:"nice-form-preview__input"});case"datetime":return e.jsx("input",{type:"datetime-local",...c,className:"nice-form-preview__input"});case"number":case"currency":case"percentage":return e.jsx("input",{type:"number",...c,className:"nice-form-preview__input"});case"email":return e.jsx("input",{type:"email",...c,className:"nice-form-preview__input"});case"phone":return e.jsx("input",{type:"tel",...c,className:"nice-form-preview__input"});case"url":return e.jsx("input",{type:"url",...c,className:"nice-form-preview__input"});case"password":return e.jsx("input",{type:"password",...c,className:"nice-form-preview__input"});case"color":return e.jsx("input",{type:"color",...c,className:"nice-form-preview__input nice-form-preview__color"});case"slider":case"rating":return e.jsx("input",{type:"range",...c,className:"nice-form-preview__input"});default:return e.jsx("input",{type:"text",...c,className:"nice-form-preview__input"})}},r=((n=t.layout)==null?void 0:n.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":r},children:[(s=t.layout)!=null&&s.sections?t.layout.sections.map((o,c)=>e.jsxs("fieldset",{className:"nice-form-preview__section",children:[o.title&&e.jsx("legend",{children:o.title}),o.description&&e.jsx("p",{className:"nice-form-preview__section-desc",children:o.description}),e.jsx("div",{className:"nice-form-preview__grid",children:o.fields.map(m=>{const p=t.fields.find(u=>u.id===m);return p?e.jsxs("div",{className:"nice-form-preview__field",children:[p.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[p.label,p.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),i(p)]},p.id):null})})]},c)):e.jsx("div",{className:"nice-form-preview__grid",children:t.fields.map(o=>e.jsxs("div",{className:"nice-form-preview__field",children:[o.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[o.label,o.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),i(o)]},o.id))}),e.jsx("div",{className:"nice-form-preview__submit",children:e.jsx("button",{type:"button",disabled:!0,className:"nice-form-preview__submit-btn",children:t.submitLabel||a("submit","Submit")})}),e.jsx("style",{children:`
|
|
779
779
|
.nice-form-preview {
|
|
780
780
|
--columns: 1;
|
|
781
781
|
}
|
|
@@ -880,7 +880,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
880
880
|
cursor: not-allowed;
|
|
881
881
|
opacity: 0.7;
|
|
882
882
|
}
|
|
883
|
-
`})]})}function
|
|
883
|
+
`})]})}function ja(t={}){const{config:a,dataFields:i,context:r,onChartGenerated:n,onError:s}=t,o=ee(),{t:c}=T.useNiceTranslation(),[m,p]=l.useState(!1),[u,v]=l.useState(null),[w,A]=l.useState(null),[R,M]=l.useState([]),P=l.useRef(null),g=a||(o==null?void 0:o.config),d=l.useMemo(()=>{if(i)return i.map(h=>{var _;return{name:h.name,type:h.type,label:h.label||h.name,...(_=h.sampleValues)!=null&&_.length?{samples:h.sampleValues.slice(0,3)}:{}}})},[i]),j=l.useCallback(async h=>{var f,k,S;if(!g){const N="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(N),{error:N}}p(!0),v(h);const _=performance.now();(f=P.current)==null||f.abort(),P.current=new AbortController;try{const N=V(g),$=ie(ue,{request:h,data:d?JSON.stringify(d,null,2):void 0,context:r}),E=await N.chat({messages:[{role:"system",content:$.system},{role:"user",content:$.user}],temperature:.4,maxTokens:1024}),z=Bi(E),F={config:z||void 0,rawResponse:(S=(k=E.choices[0])==null?void 0:k.message)==null?void 0:S.content,latencyMs:performance.now()-_,error:z?void 0:c("chartAI.parseFailed","Failed to parse chart configuration"),suggestions:Fi(z,c)};return z&&(n==null||n(z)),A(F),M(U=>[...U.slice(-9),{request:h,result:F}]),F}catch(N){const $=N instanceof Error?N.message:c("chartAI.requestFailed","AI request failed"),E={error:$,latencyMs:performance.now()-_};return A(E),s==null||s($),E}finally{p(!1)}},[g,d,r,n,s,c]),y=l.useCallback(async()=>w!=null&&w.config?{line:["area","bar","scatter"],area:["line","bar","column"],bar:["column","line","pie"],column:["bar","line","area"],pie:["donut","bar","treemap"],donut:["pie","funnel","gauge"],scatter:["bubble","line","heatmap"],bubble:["scatter","treemap"],heatmap:["treemap","bar"],treemap:["pie","heatmap","bar"],funnel:["bar","donut"],radar:["bar","polar"],polar:["radar","pie"],gauge:["donut","bar"],candlestick:["line","area"],sankey:["funnel","bar"]}[w.config.type]||[]:[],[w]),I=l.useCallback(()=>{v(null),A(null)},[]),b=l.useCallback(()=>{var h;(h=P.current)==null||h.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var h;(h=P.current)==null||h.abort()},[]),{generateChart:j,suggestAlternatives:y,loading:m,lastRequest:u,lastResult:w,history:R,clearResults:I,abort:b,isConfigured:!!g}}function Bi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.type)return{type:c.type,title:c.title,subtitle:c.subtitle,data:c.data||{},xAxis:c.xAxis,yAxis:c.yAxis,options:c.options}}catch{}return null}function Fi(t,a){var r;if(!t)return[];const i=[];return(t.type==="line"||t.type==="bar")&&(i.push(a("chartAI.suggest.trendLine","Add trend line for forecasting")),i.push(a("chartAI.suggest.stack","Stack series for comparison"))),(t.type==="pie"||t.type==="donut")&&(i.push(a("chartAI.suggest.toBar","Convert to bar chart for better comparison")),i.push(a("chartAI.suggest.percentLabels","Add data labels for percentages"))),(r=t.options)!=null&&r.animation||i.push(a("chartAI.suggest.animate","Enable animations for better UX")),i.slice(0,3)}const Ji={line:["chartAI.type.line","Line"],area:["chartAI.type.area","Area"],bar:["chartAI.type.bar","Bar"],column:["chartAI.type.column","Column"],pie:["chartAI.type.pie","Pie"],donut:["chartAI.type.donut","Donut"],scatter:["chartAI.type.scatter","Scatter"],bubble:["chartAI.type.bubble","Bubble"],heatmap:["chartAI.type.heatmap","Heatmap"],treemap:["chartAI.type.treemap","Treemap"],funnel:["chartAI.type.funnel","Funnel"],radar:["chartAI.type.radar","Radar"],polar:["chartAI.type.polar","Polar"],gauge:["chartAI.type.gauge","Gauge"],candlestick:["chartAI.type.candlestick","Candlestick"],sankey:["chartAI.type.sankey","Sankey"]},Ae=(t,a)=>{const i=Ji[t];return i?a(i[0],i[1]):t.charAt(0).toUpperCase()+t.slice(1)};function qi({config:t,dataFields:a,context:i,onGenerate:r,placeholder:n,showTypeSelector:s=!0,showPreview:o=!0,className:c,style:m,renderChart:p}){const{t:u}=T.useNiceTranslation(),[v,w]=l.useState(""),[A,R]=l.useState(null),M=l.useRef(null),{generateChart:P,suggestAlternatives:g,loading:d,lastResult:j,isConfigured:y}=ja({config:t,dataFields:a,context:i,onChartGenerated:r}),I=[["line","line"],["bar","bar-chart"],["pie","circle"],["area","bar-chart"],["scatter","grid"],["donut","circle"],["heatmap","grid"],["funnel","filter"],["gauge","target"],["radar","target"]].map(([k,S])=>({type:k,icon:S,label:Ae(k,u)})),b=async()=>{if(!v.trim()||d)return;const k=A?`Create a ${A} chart: ${v}`:v;await P(k)},h=k=>{k.key==="Enter"&&(k.preventDefault(),b())},_=k=>{R(A===k?null:k)},f=async k=>{if(!(j!=null&&j.config))return;const S={...j.config,type:k};r==null||r(S)};return y?e.jsxs("div",{className:`nice-chart-ai ${c||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:I.map(({type:k,icon:S,label:N})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${A===k?"nice-chart-ai__type--selected":""}`,onClick:()=>_(k),title:N,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:e.jsx(T.NiceIcon,{name:S,size:20})}),e.jsx("span",{className:"nice-chart-ai__type-label",children:N})]},k))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:18})}),e.jsx("input",{ref:M,type:"text",value:v,onChange:k=>w(k.target.value),onKeyDown:h,placeholder:n??u("chartAI.placeholder",'Describe the chart you want... (e.g., "Show monthly sales as a line chart")'),className:"nice-chart-ai__input",disabled:d}),d?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:b,className:"nice-chart-ai__submit",disabled:!v.trim(),children:u("chartAI.generate","Generate")})]}),a&&a.length>0&&e.jsxs("div",{className:"nice-chart-ai__fields",children:[e.jsx("span",{className:"nice-chart-ai__fields-label",children:u("chartAI.availableFields","Available fields:")}),a.map(k=>e.jsx("span",{className:"nice-chart-ai__field-badge",title:k.type,children:k.label||k.name},k.name))]}),j&&e.jsx("div",{className:"nice-chart-ai__result",children:j.error?e.jsx("div",{className:"nice-chart-ai__error",children:j.error}):j.config&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-chart-ai__result-header",children:[e.jsxs("div",{className:"nice-chart-ai__result-info",children:[e.jsxs("span",{className:"nice-chart-ai__chart-type",children:[(()=>{var S;const k=(S=I.find(N=>N.type===j.config.type))==null?void 0:S.icon;return k?e.jsx(T.NiceIcon,{name:k,size:16}):null})(),u("chartAI.chartOfType","{type} Chart").replace("{type}",Ae(j.config.type,u))]}),j.config.title&&e.jsx("span",{className:"nice-chart-ai__chart-title",children:j.config.title})]}),j.latencyMs&&e.jsxs("span",{className:"nice-chart-ai__latency",children:[Math.round(j.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(j.config),className:"nice-chart-ai__use-btn",children:u("chartAI.useChart","Use This Chart")})]}),e.jsxs("div",{className:"nice-chart-ai__alternatives",children:[e.jsx("span",{children:u("chartAI.tryAlso","Try also:")}),I.filter(k=>k.type!==j.config.type).slice(0,4).map(({type:k,icon:S,label:N})=>e.jsx("button",{type:"button",className:"nice-chart-ai__alternative",onClick:()=>f(k),title:u("chartAI.convertTo","Convert to {type}").replace("{type}",N),"aria-label":u("chartAI.convertTo","Convert to {type}").replace("{type}",N),children:e.jsx(T.NiceIcon,{name:S,size:16})},k))]}),o&&e.jsx("div",{className:"nice-chart-ai__preview",children:p?p(j.config):e.jsx(Gi,{config:j.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:u("chartAI.viewConfig","View Configuration")}),e.jsx("pre",{children:JSON.stringify(j.config,null,2)})]})]})}),e.jsx("style",{children:`
|
|
884
884
|
.nice-chart-ai {
|
|
885
885
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
886
886
|
}
|
|
@@ -1124,7 +1124,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
1124
1124
|
color: var(--nice-error, #c62828);
|
|
1125
1125
|
border-radius: var(--nice-radius-md, 6px);
|
|
1126
1126
|
}
|
|
1127
|
-
`})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${c||""}`,style:
|
|
1127
|
+
`})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:u("chartAI.notConfigured","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Gi({config:t}){var n;const{t:a}=T.useNiceTranslation(),i=s=>a("chartAI.series","Series {n}").replace("{n}",String(s)),r=()=>{switch(t.type){case"bar":case"column":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("rect",{x:"20",y:"60",width:"25",height:"30",fill:"var(--nice-success, #4caf50)",rx:"2"}),e.jsx("rect",{x:"55",y:"40",width:"25",height:"50",fill:"var(--nice-primary, #2196f3)",rx:"2"}),e.jsx("rect",{x:"90",y:"20",width:"25",height:"70",fill:"var(--nice-warning, #ff9800)",rx:"2"}),e.jsx("rect",{x:"125",y:"50",width:"25",height:"40",fill:"var(--nice-accent, #9c27b0)",rx:"2"}),e.jsx("rect",{x:"160",y:"30",width:"25",height:"60",fill:"var(--nice-color-accent-pink, #e91e63)",rx:"2"})]});case"line":case"area":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("path",{d:"M 20 70 Q 50 30, 80 50 T 140 40 T 180 60",fill:"none",stroke:"var(--nice-primary, #2196f3)",strokeWidth:"3",strokeLinecap:"round"}),t.type==="area"&&e.jsx("path",{d:"M 20 70 Q 50 30, 80 50 T 140 40 T 180 60 V 90 H 20 Z",fill:"color-mix(in srgb, var(--nice-primary, #2196f3) 20%, transparent)"}),e.jsx("circle",{cx:"20",cy:"70",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"80",cy:"50",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"140",cy:"40",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"180",cy:"60",r:"4",fill:"var(--nice-primary, #2196f3)"})]});case"pie":case"donut":{const s=t.type==="donut"?35:40,o=t.type==="donut"?20:0;return e.jsxs("svg",{viewBox:"0 0 100 100",className:"nice-chart-preview__svg",children:[e.jsx("circle",{cx:"50",cy:"50",r:s,fill:"var(--nice-success, #4caf50)"}),e.jsx("path",{d:"M 50 50 L 50 10 A 40 40 0 0 1 90 50 Z",fill:"var(--nice-primary, #2196f3)"}),e.jsx("path",{d:"M 50 50 L 90 50 A 40 40 0 0 1 70 85 Z",fill:"var(--nice-warning, #ff9800)"}),e.jsx("path",{d:"M 50 50 L 70 85 A 40 40 0 0 1 30 85 Z",fill:"var(--nice-accent, #9c27b0)"}),t.type==="donut"&&e.jsx("circle",{cx:"50",cy:"50",r:o,fill:"white"})]})}case"scatter":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("circle",{cx:"30",cy:"70",r:"5",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"50",cy:"40",r:"7",fill:"var(--nice-success, #4caf50)"}),e.jsx("circle",{cx:"80",cy:"60",r:"4",fill:"var(--nice-warning, #ff9800)"}),e.jsx("circle",{cx:"110",cy:"30",r:"6",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"140",cy:"50",r:"5",fill:"var(--nice-accent, #9c27b0)"}),e.jsx("circle",{cx:"170",cy:"45",r:"8",fill:"var(--nice-success, #4caf50)"})]});case"gauge":return e.jsxs("svg",{viewBox:"0 0 100 60",className:"nice-chart-preview__svg",children:[e.jsx("path",{d:"M 10 50 A 40 40 0 0 1 90 50",fill:"none",stroke:"var(--nice-border, #e0e0e0)",strokeWidth:"8",strokeLinecap:"round"}),e.jsx("path",{d:"M 10 50 A 40 40 0 0 1 60 15",fill:"none",stroke:"var(--nice-success, #4caf50)",strokeWidth:"8",strokeLinecap:"round"}),e.jsx("text",{x:"50",y:"50",textAnchor:"middle",fontSize:"14",fontWeight:"bold",children:"75%"})]});default:return e.jsxs("div",{className:"nice-chart-preview__placeholder",children:[e.jsx("span",{className:"nice-chart-preview__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("span",{children:a("chartAI.chartOfType","{type} Chart").replace("{type}",Ae(t.type,a))})]})}};return e.jsxs("div",{className:"nice-chart-preview",children:[t.title&&e.jsx("div",{className:"nice-chart-preview__title",children:t.title}),t.subtitle&&e.jsx("div",{className:"nice-chart-preview__subtitle",children:t.subtitle}),e.jsx("div",{className:"nice-chart-preview__chart",children:r()}),((n=t.options)==null?void 0:n.legend)&&e.jsxs("div",{className:"nice-chart-preview__legend",children:[e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-success, #4caf50)"}}),i(1)]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-primary, #2196f3)"}}),i(2)]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-warning, #ff9800)"}}),i(3)]})]}),e.jsx("style",{children:`
|
|
1128
1128
|
.nice-chart-preview {
|
|
1129
1129
|
text-align: center;
|
|
1130
1130
|
}
|
|
@@ -1185,12 +1185,12 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
1185
1185
|
height: 12px;
|
|
1186
1186
|
border-radius: var(--nice-radius-sm, 2px);
|
|
1187
1187
|
}
|
|
1188
|
-
`})]})}function
|
|
1189
|
-
`),
|
|
1190
|
-
`),B=[
|
|
1191
|
-
`),
|
|
1188
|
+
`})]})}function ka(t={}){const{config:a,language:i="typescript",context:r,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:o,onError:c}=t,m=ee(),[p,u]=l.useState(!1),[v,w]=l.useState([]),[A,R]=l.useState(-1),M=l.useRef(null),P=l.useRef(null),g=a||(m==null?void 0:m.config),d=l.useCallback(async(N,$)=>{var z,F,U;if(!g)return{suggestions:[],error:"AI not configured"};u(!0),(z=M.current)==null||z.abort(),M.current=new AbortController;const E=performance.now();try{const H=V(g),X=N.split(`
|
|
1189
|
+
`),C=X[$.line]||"",x=[...X.slice(Math.max(0,$.line-20),$.line),C.substring(0,$.column)].join(`
|
|
1190
|
+
`),B=[C.substring($.column),...X.slice($.line+1,$.line+10)].join(`
|
|
1191
|
+
`),G=ie(me,{language:i,prefix:x,suffix:B,context:r}),q=await H.chat({messages:[{role:"system",content:G.system},{role:"user",content:G.user}],temperature:.2,maxTokens:512}),W=Ui(q,$,n),Q={suggestions:W,rawResponse:(U=(F=q.choices[0])==null?void 0:F.message)==null?void 0:U.content,latencyMs:performance.now()-E};return w(W),R(W.length>0?0:-1),o==null||o(W),Q}catch(H){const X=H instanceof Error?H.message:"Completion failed";return c==null||c(X),{suggestions:[],error:X,latencyMs:performance.now()-E}}finally{u(!1)}},[g,i,r,n,o,c]),j=l.useCallback((N,$)=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{d(N,$)},s)},[d,s]),y=l.useCallback(async N=>{if(!g)return null;u(!0);try{const E=await V(g).chat({messages:[{role:"system",content:`You are a code explanation assistant. Explain the following ${i} code clearly and concisely. Return JSON with: { "summary": string, "details": string, "complexity": "low"|"medium"|"high", "suggestions": string[] }`},{role:"user",content:N}],temperature:.3,maxTokens:1024});return Wi(E)}catch{return null}finally{u(!1)}},[g,i]),I=l.useCallback(async N=>{if(!g)return[];u(!0);try{const E=await V(g).chat({messages:[{role:"system",content:`You are a code refactoring assistant. Analyze the following ${i} code and suggest improvements. Return JSON array with: [{ "title": string, "description": string, "before": string, "after": string, "type": "extract-function"|"rename"|"simplify"|"optimize"|"security"|"style" }]`},{role:"user",content:N}],temperature:.4,maxTokens:2048});return Hi(E)}catch{return[]}finally{u(!1)}},[g,i]),b=l.useCallback(async(N,$)=>{var E,z;if(!g)return null;u(!0);try{const F=V(g),U=$||Ki(i);return((z=(E=(await F.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${i} code using ${U}. Include edge cases and error scenarios. Return only the test code.`},{role:"user",content:N}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:E.message)==null?void 0:z.content)||null}catch{return null}finally{u(!1)}},[g,i]),h=l.useCallback(async(N,$)=>{var E,z;if(!g)return null;u(!0);try{const F=V(g),U=$||Yi(i);return((z=(E=(await F.chat({messages:[{role:"system",content:`Generate ${U} documentation for the following ${i} code. Include descriptions for parameters, return values, and examples where appropriate. Return only the documented code.`},{role:"user",content:N}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:E.message)==null?void 0:z.content)||null}catch{return null}finally{u(!1)}},[g,i]),_=l.useCallback((N=A)=>{const $=v[N];return w([]),R(-1),$},[v,A]),f=l.useCallback(()=>{w([]),R(-1)},[]),k=l.useCallback(N=>{v.length!==0&&R($=>N==="up"?$<=0?v.length-1:$-1:$>=v.length-1?0:$+1)},[v.length]),S=l.useCallback(()=>{var N;(N=M.current)==null||N.abort(),P.current&&clearTimeout(P.current),u(!1)},[]);return l.useEffect(()=>()=>{var N;(N=M.current)==null||N.abort(),P.current&&clearTimeout(P.current)},[]),{getCompletions:d,getCompletionsDebounced:j,suggestions:v,activeSuggestion:A,acceptSuggestion:_,dismissSuggestions:f,navigateSuggestions:k,explainCode:y,suggestRefactoring:I,generateTests:b,generateDocs:h,loading:p,abort:S,isConfigured:!!g}}function Ui(t,a,i){var o,c;const r=((c=(o=t.choices[0])==null?void 0:o.message)==null?void 0:c.content)||"",n=/^\s*```[\w+#.-]*\n([\s\S]*?)\n?```\s*$/.exec(r),s=(n?n[1]:r).replace(/^\n+/,"").replace(/\s+$/,"");return!s.trim()||i<1?[]:[{id:`suggestion-${Date.now()}-0`,text:s,type:s.includes(`
|
|
1192
1192
|
`)?"block":"inline",preview:s.trim().split(`
|
|
1193
|
-
`)[0].slice(0,50),confidence:.8,insertPosition:a}]}function
|
|
1193
|
+
`)[0].slice(0,50),confidence:.8,insertPosition:a}]}function Wi(t){var a,i;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",n=r.match(/\{[\s\S]*\}/);return n?JSON.parse(n[0]):{summary:r}}catch{return null}}function Hi(t){var a,i;try{const n=(((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"").match(/\[[\s\S]*\]/);if(n)return JSON.parse(n[0])}catch{}return[]}function Ki(t){return{javascript:"Jest",typescript:"Jest",python:"pytest",java:"JUnit 5",csharp:"xUnit",go:"testing",rust:"cargo test",ruby:"RSpec",php:"PHPUnit",swift:"XCTest",kotlin:"JUnit 5",dart:"flutter_test"}[t]||"unit test"}function Yi(t){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[t]||"jsdoc"}function Vi({code:t="",language:a="typescript",config:i,onChange:r,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:o=!0,placeholder:c,className:m,style:p,renderEditor:u}){const{t:v}=T.useNiceTranslation(),w=c??v("codeEditorAI.startTypingCode","Start typing code..."),[A,R]=l.useState(t),[M,P]=l.useState(null),[g,d]=l.useState(null),[j,y]=l.useState([]),[I,b]=l.useState(null),[h,_]=l.useState(null),f=l.useRef(null),{getCompletionsDebounced:k,suggestions:S,activeSuggestion:N,acceptSuggestion:$,dismissSuggestions:E,navigateSuggestions:z,explainCode:F,suggestRefactoring:U,generateTests:H,generateDocs:X,loading:C,isConfigured:x}=ka({config:i,language:a}),B=D=>{if(R(D),r==null||r(D),o&&f.current){const K=Xi(f.current);k(D,K)}},G=D=>{if(S.length>0)if(D.key==="ArrowUp")D.preventDefault(),z("up");else if(D.key==="ArrowDown")D.preventDefault(),z("down");else if(D.key==="Tab"||D.key==="Enter"){if(N>=0){D.preventDefault();const K=$(N);K&&(q(K),n==null||n(K))}}else D.key==="Escape"&&E()},q=D=>{if(!f.current)return;const K=f.current,te=K.selectionStart,Ee=A.slice(0,te)+D.text+A.slice(te);R(Ee),r==null||r(Ee);const De=te+D.text.length;setTimeout(()=>{K.focus(),K.setSelectionRange(De,De)},0)},W=async()=>{const D=M||A;if(!D.trim())return;_("explain");const K=await F(D);d(K)},Q=async()=>{const D=M||A;if(!D.trim())return;_("refactor");const K=await U(D);y(K)},re=async()=>{if(!A.trim())return;_("tests");const D=await H(A);b(D)},L=async()=>{if(!A.trim())return;_("docs");const D=await X(A);b(D)},O=D=>{const K=A.replace(D.before,D.after);R(K),r==null||r(K),_(null)},J=()=>{I&&navigator.clipboard.writeText(I)},Y=()=>{if(f.current){const D=f.current.selectionStart,K=f.current.selectionEnd;P(D!==K?A.slice(D,K):null)}};return x?u?e.jsx("div",{className:`nice-code-editor-ai ${m||""}`,style:p,children:u({code:A,onChange:B,suggestions:S,onAccept:D=>{const K=$(D);K&&(n==null||n(K))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${m||""}`,style:p,children:[s&&e.jsxs("div",{className:"nice-code-editor-ai__toolbar",children:[e.jsx("span",{className:"nice-code-editor-ai__lang-badge",children:a}),e.jsxs("div",{className:"nice-code-editor-ai__actions",children:[e.jsxs("button",{type:"button",onClick:W,disabled:C||!A.trim(),title:v("codeEditorAI.explainCode","Explain code"),children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," ",v("codeEditorAI.explain","Explain")]}),e.jsxs("button",{type:"button",onClick:Q,disabled:C||!A.trim(),title:v("codeEditorAI.suggestRefactoring","Suggest refactoring"),children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",v("codeEditorAI.refactor","Refactor")]}),e.jsxs("button",{type:"button",onClick:re,disabled:C||!A.trim(),title:v("codeEditorAI.generateTests","Generate tests"),children:[e.jsx(T.NiceIcon,{name:"flask",size:14})," ",v("codeEditorAI.tests","Tests")]}),e.jsxs("button",{type:"button",onClick:L,disabled:C||!A.trim(),title:v("codeEditorAI.generateDocs","Generate docs"),children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",v("codeEditorAI.docs","Docs")]})]}),C&&e.jsx("span",{className:"nice-code-editor-ai__loading",children:v("codeEditorAI.processing","Processing...")})]}),e.jsxs("div",{className:"nice-code-editor-ai__editor-wrapper",children:[e.jsx("textarea",{ref:f,value:A,onChange:D=>B(D.target.value),onKeyDown:G,onSelect:Y,placeholder:w,className:"nice-code-editor-ai__textarea",spellCheck:!1}),S.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[S.map((D,K)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${K===N?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const te=$(K);te&&(q(te),n==null||n(te))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:D.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(D.confidence*100),"%"]})]},D.id)),e.jsxs("div",{className:"nice-code-editor-ai__suggestions-hint",children:[e.jsx(T.NiceIcon,{name:"arrow-up",size:11}),e.jsx(T.NiceIcon,{name:"arrow-down",size:11})," navigate • Tab accept • Esc dismiss"]})]})]}),h&&e.jsxs("div",{className:"nice-code-editor-ai__panel",children:[e.jsxs("div",{className:"nice-code-editor-ai__panel-header",children:[e.jsxs("span",{children:[h==="explain"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," ",v("codeEditorAI.explanation","Explanation")]}),h==="refactor"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",v("codeEditorAI.refactoringSuggestions","Refactoring Suggestions")]}),h==="tests"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"flask",size:14})," ",v("codeEditorAI.generatedTests","Generated Tests")]}),h==="docs"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",v("codeEditorAI.generatedDocumentation","Generated Documentation")]})]}),e.jsx("button",{type:"button",onClick:()=>_(null),"aria-label":v("codeEditorAI.closePanel","Close panel"),children:e.jsx(T.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[h==="explain"&&g&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:g.summary}),g.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:g.details}),g.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${g.complexity}`,children:["Complexity: ",g.complexity]}),g.suggestions&&g.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:g.suggestions.map((D,K)=>e.jsx("li",{children:D},K))})]}),h==="refactor"&&j.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:j.map((D,K)=>e.jsxs("div",{className:"nice-code-editor-ai__refactoring",children:[e.jsxs("div",{className:"nice-code-editor-ai__refactoring-header",children:[e.jsx("span",{className:"nice-code-editor-ai__refactoring-title",children:D.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${D.type}`,children:D.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:D.description}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-diff",children:[e.jsxs("div",{className:"nice-code-editor-ai__refactoring-before",children:[e.jsx("span",{children:"Before:"}),e.jsx("pre",{children:D.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:"After:"}),e.jsx("pre",{children:D.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>O(D),children:v("codeEditorAI.apply","Apply")})]},K))}),(h==="tests"||h==="docs")&&I&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:I}),e.jsxs("button",{type:"button",onClick:J,children:[e.jsx(T.NiceIcon,{name:"clipboard",size:14})," ",v("codeEditorAI.copy","Copy")]})]})]})]}),e.jsx("style",{children:`
|
|
1194
1194
|
.nice-code-editor-ai {
|
|
1195
1195
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
1196
1196
|
display: flex;
|
|
@@ -1496,13 +1496,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
1496
1496
|
border-radius: var(--nice-radius-md, 6px);
|
|
1497
1497
|
cursor: pointer;
|
|
1498
1498
|
}
|
|
1499
|
-
`})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${
|
|
1500
|
-
`);return{line:
|
|
1501
|
-
`)
|
|
1499
|
+
`})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${m||""}`,style:p,children:[e.jsx("p",{children:v("codeEditorAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")}),e.jsx("textarea",{value:A,onChange:D=>B(D.target.value),placeholder:w,className:"nice-code-editor-ai__textarea"})]})}function Xi(t){const i=t.value.substring(0,t.selectionStart).split(`
|
|
1500
|
+
`);return{line:i.length-1,column:i[i.length-1].length}}function Na(t={}){const{config:a,context:i,existingRoles:r,existingVariables:n,onWorkflowGenerated:s,onError:o}=t,c=ee(),[m,p]=l.useState(!1),[u,v]=l.useState(null),[w,A]=l.useState([]),R=l.useRef(null),M=a||(c==null?void 0:c.config),P=l.useCallback(async b=>{var _,f,k;if(!M){const S="AI not configured";return o==null||o(S),{error:S}}p(!0);const h=performance.now();(_=R.current)==null||_.abort(),R.current=new AbortController;try{const S=V(M),N=[i,r!=null&&r.length?`Available roles: ${r.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
|
|
1501
|
+
`),$=ie(pe,{description:N?`${b}
|
|
1502
1502
|
|
|
1503
|
-
${N}`:
|
|
1504
|
-
Current node: ${(
|
|
1505
|
-
Existing nodes: ${
|
|
1503
|
+
${N}`:b}),E=await S.chat({messages:[{role:"system",content:$.system},{role:"user",content:$.user}],temperature:.5,maxTokens:2048}),z=Ge(E),F={workflow:z||void 0,rawResponse:(k=(f=E.choices[0])==null?void 0:f.message)==null?void 0:k.content,latencyMs:performance.now()-h,error:z?void 0:"Failed to generate workflow",suggestions:Zi(z)};return z&&(s==null||s(z)),v(F),A(U=>[...U.slice(-9),{request:b,result:F}]),F}catch(S){const N=S instanceof Error?S.message:"Workflow generation failed",$={error:N,latencyMs:performance.now()-h};return v($),o==null||o(N),$}finally{p(!1)}},[M,i,r,n,s,o]),g=l.useCallback(async b=>{if(!M)return{error:"AI not configured"};p(!0);const h=performance.now();try{const f=await V(M).chat({messages:[{role:"system",content:"You are a workflow optimization expert. Analyze the following BPMN workflow and suggest improvements for efficiency, clarity, and error handling. Return the optimized workflow in JSON format with the same structure."},{role:"user",content:JSON.stringify(b,null,2)}],temperature:.4,maxTokens:2048});return{workflow:Ge(f)||void 0,latencyMs:performance.now()-h}}catch(_){return{error:_ instanceof Error?_.message:"Optimization failed"}}finally{p(!1)}},[M]),d=l.useCallback(async(b,h)=>{var _,f;if(!M)return[];p(!0);try{const k=V(M),S=b.nodes.find(z=>z.id===h),E=(((f=(_=(await k.chat({messages:[{role:"system",content:'Given the current workflow state, suggest 2-3 possible next steps after the specified node. Return JSON array of nodes: [{ "id": string, "type": string, "label": string, "description": string }]'},{role:"user",content:`Workflow: ${b.name}
|
|
1504
|
+
Current node: ${(S==null?void 0:S.label)||h}
|
|
1505
|
+
Existing nodes: ${b.nodes.map(z=>z.label).join(", ")}`}],temperature:.6,maxTokens:512})).choices[0])==null?void 0:_.message)==null?void 0:f.content)||"").match(/\[[\s\S]*\]/);if(E)return JSON.parse(E[0])}catch{}finally{p(!1)}return[]},[M]),j=l.useCallback(async b=>{var h,_;if(!M)return[];p(!0);try{const N=(((_=(h=(await V(M).chat({messages:[{role:"system",content:'Analyze the BPMN workflow for potential issues. Check for: dead ends, unreachable nodes, missing error handling, infinite loops, unclear conditions, missing assignments. Return JSON array of issues: [{ "severity": "error"|"warning"|"info", "message": string, "nodeId": string? }]'},{role:"user",content:JSON.stringify(b,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:h.message)==null?void 0:_.content)||"").match(/\[[\s\S]*\]/);if(N)return JSON.parse(N[0]).map(E=>`[${E.severity}] ${E.message}`)}catch{}finally{p(!1)}return[]},[M]),y=l.useCallback(()=>{v(null)},[]),I=l.useCallback(()=>{var b;(b=R.current)==null||b.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var b;(b=R.current)==null||b.abort()},[]),{generateWorkflow:P,optimizeWorkflow:g,suggestNextStep:d,validateWorkflow:j,loading:m,lastResult:u,history:w,clearResults:y,abort:I,isConfigured:!!M}}function Ge(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.nodes&&Array.isArray(c.nodes)){const m={gateway:"gateway-exclusive",event:"event-intermediate"},p=c.nodes.map((w,A)=>({...w,id:w.id||`node_${A}`,label:w.label??w.name??w.id??`Step ${A+1}`,type:m[w.type]??w.type})),u=Qi(p),v=p.map((w,A)=>({...w,position:w.position||u[A]}));return{id:c.id||`workflow_${Date.now()}`,name:c.name||"Generated Workflow",description:c.description,version:c.version||"1.0",nodes:v,edges:c.edges||[],lanes:c.lanes??c.swimlanes,variables:c.variables,metadata:c.metadata}}}catch{}return null}function Sa(t){return t.type==="start"||t.type==="end"||t.type.startsWith("gateway")?40:Math.round((t.label??"").length*7.2+64)}function Qi(t){let n=20,s=40;return t.map(o=>{const c=Sa(o);n>20&&n+c>640&&(n=20,s+=110);const m={x:n,y:s};return n+=c+48,m})}function Zi(t){if(!t)return[];const a=[];return t.nodes.some(s=>s.type==="event-error")||a.push("Add error boundary events for critical tasks"),!t.nodes.some(s=>s.type==="gateway-parallel")&&t.nodes.length>5&&a.push("Consider parallel gateways for independent tasks"),(!t.lanes||t.lanes.length===0)&&a.push("Add swimlanes to clarify responsibilities"),t.nodes.some(s=>s.type==="event-timer")||a.push("Add timer events for SLA monitoring"),a.slice(0,3)}const et=["Employee onboarding process with HR approval","Purchase order approval with budget check","Customer support ticket escalation workflow","Document review and approval process","Leave request with manager and HR approval"];function at({config:t,context:a,roles:i,onGenerate:r,placeholder:n,showExamples:s=!0,showPreview:o=!0,className:c,style:m,renderWorkflow:p}){const{t:u}=T.useNiceTranslation(),v=n??u("workflowDesignerAI.describeTheWorkflow",'Describe the workflow process... (e.g., "Leave request with manager approval")'),[w,A]=l.useState(""),[R,M]=l.useState([]),P=l.useRef(null),{generateWorkflow:g,validateWorkflow:d,loading:j,lastResult:y,isConfigured:I}=Na({config:t,context:a,existingRoles:i,onWorkflowGenerated:r}),b=async()=>{!w.trim()||j||await g(w)},h=k=>{var S;A(k),(S=P.current)==null||S.focus()},_=async()=>{if(!(y!=null&&y.workflow))return;const k=await d(y.workflow);M(k)},f=()=>{if(!(y!=null&&y.workflow))return;const k=tt(y.workflow),S=new Blob([k],{type:"application/xml"}),N=URL.createObjectURL(S),$=document.createElement("a");$.href=N,$.download=`${y.workflow.name.replace(/\s+/g,"_")}.bpmn`,$.click(),URL.revokeObjectURL(N)};return I?e.jsxs("div",{className:`nice-workflow-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:P,value:w,onChange:k=>A(k.target.value),placeholder:v,className:"nice-workflow-ai__input",rows:3,disabled:j}),e.jsx("button",{type:"button",onClick:b,className:"nice-workflow-ai__submit",disabled:j||!w.trim(),children:j?e.jsx("span",{className:"nice-workflow-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"refresh",size:14})," ",u("workflowDesignerAI.generateWorkflow","Generate Workflow")]})})]}),s&&e.jsxs("div",{className:"nice-workflow-ai__examples",children:[e.jsx("span",{className:"nice-workflow-ai__examples-label",children:"Try:"}),et.slice(0,3).map((k,S)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>h(k),children:k},S))]}),y&&e.jsx("div",{className:"nice-workflow-ai__result",children:y.error?e.jsx("div",{className:"nice-workflow-ai__error",children:y.error}):y.workflow&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-workflow-ai__result-header",children:[e.jsxs("div",{className:"nice-workflow-ai__workflow-info",children:[e.jsx("span",{className:"nice-workflow-ai__workflow-name",children:y.workflow.name}),y.workflow.description&&e.jsx("span",{className:"nice-workflow-ai__workflow-desc",children:y.workflow.description})]}),e.jsxs("div",{className:"nice-workflow-ai__result-meta",children:[e.jsxs("span",{className:"nice-workflow-ai__stat",children:[y.workflow.nodes.length," nodes"]}),e.jsxs("span",{className:"nice-workflow-ai__stat",children:[y.workflow.edges.length," connections"]}),y.latencyMs&&e.jsxs("span",{className:"nice-workflow-ai__latency",children:[Math.round(y.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-workflow-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(y.workflow),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",u("workflowDesignerAI.useWorkflow","Use Workflow")]}),e.jsxs("button",{type:"button",onClick:_,children:[e.jsx(T.NiceIcon,{name:"search",size:14})," ",u("workflowDesignerAI.validate","Validate")]}),e.jsxs("button",{type:"button",onClick:f,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",u("workflowDesignerAI.exportBpmn","Export BPMN")]})]}),R.length>0&&e.jsxs("div",{className:"nice-workflow-ai__validation",children:[e.jsx("div",{className:"nice-workflow-ai__validation-title",children:"Validation Issues:"}),e.jsx("ul",{children:R.map((k,S)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${k.startsWith("[error]")?"error":k.startsWith("[warning]")?"warning":"info"}`,children:k},S))})]}),o&&e.jsx("div",{className:"nice-workflow-ai__preview",children:p?p(y.workflow):e.jsx(it,{workflow:y.workflow})}),y.suggestions&&y.suggestions.length>0&&e.jsxs("div",{className:"nice-workflow-ai__suggestions",children:[e.jsxs("span",{className:"nice-workflow-ai__suggestions-title",children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:y.suggestions.map((k,S)=>e.jsx("li",{children:k},S))})]}),e.jsxs("details",{className:"nice-workflow-ai__json",children:[e.jsx("summary",{children:u("workflowDesignerAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(y.workflow,null,2)})]})]})}),e.jsx("style",{children:`
|
|
1506
1506
|
.nice-workflow-ai {
|
|
1507
1507
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
1508
1508
|
}
|
|
@@ -1766,7 +1766,7 @@ Existing nodes: ${j.nodes.map(D=>D.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1766
1766
|
color: var(--nice-error, #c62828);
|
|
1767
1767
|
border-radius: var(--nice-radius-md, 6px);
|
|
1768
1768
|
}
|
|
1769
|
-
`})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${c||""}`,style:
|
|
1769
|
+
`})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:u("workflowDesignerAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function it({workflow:t}){const a=r=>({start:"play",end:"stop",task:"clipboard",userTask:"user",serviceTask:"settings",scriptTask:"file","gateway-exclusive":"hexagon","gateway-parallel":"plus","gateway-inclusive":"circle","event-timer":"clock","event-message":"mail","event-error":"warning"})[r]||"clipboard",i=r=>r==="start"?"var(--nice-success, #4caf50)":r==="end"?"var(--nice-danger, #f44336)":r.startsWith("gateway")?"var(--nice-warning, #ff9800)":r.startsWith("event")?"var(--nice-accent, #9c27b0)":"var(--nice-primary, #2196f3)";return e.jsxs("div",{className:"workflow-preview",children:[e.jsxs("div",{className:"workflow-preview__diagram",children:[t.nodes.map(r=>{var n,s;return e.jsxs("div",{className:`workflow-preview__node workflow-preview__node--${r.type.split("-")[0]}`,style:{left:(n=r.position)==null?void 0:n.x,top:(s=r.position)==null?void 0:s.y,borderColor:i(r.type)},children:[e.jsx("span",{className:"workflow-preview__node-icon",children:e.jsx(T.NiceIcon,{name:a(r.type),size:16})}),e.jsx("span",{className:"workflow-preview__node-label",children:r.label})]},r.id)}),e.jsxs("svg",{className:"workflow-preview__connections",children:[t.edges.map(r=>{const n=t.nodes.find(u=>u.id===r.source),s=t.nodes.find(u=>u.id===r.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const o=n.position.x+Sa(n),c=n.position.y+20,m=s.position.x,p=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:o,y1:c,x2:m,y2:p,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(o+m)/2,y:(c+p)/2-5,fontSize:"10",fill:"var(--nice-text-secondary, #666)",textAnchor:"middle",children:r.label})]},r.id)}),e.jsx("defs",{children:e.jsx("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"var(--nice-text-secondary, #666)"})})})]})]}),t.lanes&&t.lanes.length>0&&e.jsxs("div",{className:"workflow-preview__lanes",children:[e.jsx("span",{className:"workflow-preview__lanes-title",children:"Swimlanes:"}),t.lanes.map(r=>e.jsx("span",{className:"workflow-preview__lane",children:r.name},r.id))]}),e.jsx("style",{children:`
|
|
1770
1770
|
.workflow-preview {
|
|
1771
1771
|
min-height: 200px;
|
|
1772
1772
|
}
|
|
@@ -1871,23 +1871,23 @@ Existing nodes: ${j.nodes.map(D=>D.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1871
1871
|
border-radius: var(--nice-radius-sm, 4px);
|
|
1872
1872
|
font-size: 12px;
|
|
1873
1873
|
}
|
|
1874
|
-
`})]})}function
|
|
1875
|
-
`),r=
|
|
1874
|
+
`})]})}function tt(t){const a={start:"bpmn:startEvent",end:"bpmn:endEvent",task:"bpmn:task",userTask:"bpmn:userTask",serviceTask:"bpmn:serviceTask",scriptTask:"bpmn:scriptTask","gateway-exclusive":"bpmn:exclusiveGateway","gateway-parallel":"bpmn:parallelGateway","gateway-inclusive":"bpmn:inclusiveGateway"},i=t.nodes.map(n=>` <${a[n.type]||"bpmn:task"} id="${n.id}" name="${be(n.label)}" />`).join(`
|
|
1875
|
+
`),r=t.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${be(n.label)}"`:""} />`).join(`
|
|
1876
1876
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
1877
1877
|
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
|
|
1878
1878
|
xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
|
|
1879
|
-
id="${
|
|
1879
|
+
id="${t.id}"
|
|
1880
1880
|
targetNamespace="http://nice2dev.com/bpmn">
|
|
1881
|
-
<bpmn:process id="Process_${
|
|
1882
|
-
${
|
|
1881
|
+
<bpmn:process id="Process_${t.id}" name="${be(t.name)}" isExecutable="true">
|
|
1882
|
+
${i}
|
|
1883
1883
|
${r}
|
|
1884
1884
|
</bpmn:process>
|
|
1885
|
-
</bpmn:definitions>`}function
|
|
1886
|
-
`):void 0,N=
|
|
1885
|
+
</bpmn:definitions>`}function be(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ca(t={}){const{config:a,dataSources:i,context:r,onReportGenerated:n,onError:s}=t,o=ee(),[c,m]=l.useState(!1),[p,u]=l.useState(null),[v,w]=l.useState([]),A=l.useRef(null),R=a||(o==null?void 0:o.config),M=l.useCallback(async I=>{var h,_,f;if(!R){const k="AI not configured";return s==null||s(k),{error:k}}m(!0);const b=performance.now();(h=A.current)==null||h.abort(),A.current=new AbortController;try{const k=V(R),S=i?i.map(F=>`- ${F.name} (${F.id}): ${F.fields.join(", ")}`).join(`
|
|
1886
|
+
`):void 0,N=ie(ge,{description:r?`${I}
|
|
1887
1887
|
|
|
1888
|
-
Context: ${r}`:
|
|
1889
|
-
Existing sections: ${
|
|
1890
|
-
Purpose: ${
|
|
1888
|
+
Context: ${r}`:I,dataSources:S}),$=await k.chat({messages:[{role:"system",content:N.system},{role:"user",content:N.user}],temperature:.5,maxTokens:2048}),E=st($),z={layout:E||void 0,rawResponse:(f=(_=$.choices[0])==null?void 0:_.message)==null?void 0:f.content,latencyMs:performance.now()-b,error:E?void 0:"Failed to generate report layout",suggestions:ct(E)};return E&&(n==null||n(E)),u(z),w(F=>[...F.slice(-9),{request:I,result:z}]),z}catch(k){const S=k instanceof Error?k.message:"Report generation failed",N={error:S,latencyMs:performance.now()-b};return u(N),s==null||s(S),N}finally{m(!1)}},[R,i,r,n,s]),P=l.useCallback(async I=>{var b,h;if(!R)return[];m(!0);try{const S=(((h=(b=(await V(R).chat({messages:[{role:"system",content:"Given the existing report layout, suggest 2-3 additional sections that would enhance it. Return JSON array of sections with: id, type, title, order, config."},{role:"user",content:`Report: ${I.name}
|
|
1889
|
+
Existing sections: ${I.sections.map(N=>N.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:b.message)==null?void 0:h.content)||"").match(/\[[\s\S]*\]/);if(S)return JSON.parse(S[0])}catch{}finally{m(!1)}return[]},[R]),g=l.useCallback(async I=>{var b,h;if(!R)return null;m(!0);try{return((h=(b=(await V(R).chat({messages:[{role:"system",content:"Generate a concise executive summary (2-3 paragraphs) based on the provided data. Highlight key metrics, trends, and actionable insights."},{role:"user",content:JSON.stringify(I,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:b.message)==null?void 0:h.content)||null}catch{return null}finally{m(!1)}},[R]),d=l.useCallback(async(I,b)=>{var h,_,f;if(!R)return"bar";try{const k=V(R),S=I.slice(0,5),$=(f=(_=(h=(await k.chat({messages:[{role:"system",content:"Based on the data sample and description, recommend the best chart type. Return only the chart type: line, bar, pie, donut, area, column, scatter, combo, gauge, or heatmap."},{role:"user",content:`Data: ${JSON.stringify(S)}
|
|
1890
|
+
Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:h.message)==null?void 0:_.content)==null?void 0:f.toLowerCase().trim();return["line","bar","pie","donut","area","column","scatter","combo","gauge","heatmap"].find(z=>$==null?void 0:$.includes(z))||"bar"}catch{return"bar"}},[R]),j=l.useCallback(()=>{u(null)},[]),y=l.useCallback(()=>{var I;(I=A.current)==null||I.abort(),m(!1)},[]);return l.useEffect(()=>()=>{var I;(I=A.current)==null||I.abort()},[]),{generateReport:M,suggestSections:P,generateSummary:g,suggestChartType:d,loading:c,lastResult:p,history:v,clearResults:j,abort:y,isConfigured:!!R}}const rt=new Set(["header","summary","kpi","table","chart","text","image","divider","spacer","pageBreak","footer","toc","customBlock"]),nt={title:"header",subtitle:"text","kpi-card":"kpi",metric:"kpi","pivot-table":"table","page-break":"pageBreak","section-break":"divider",logo:"image"};function Ue(t){const a=typeof t=="string"?t:"";return nt[a]??(rt.has(a)?a:"customBlock")}function st(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.sections&&Array.isArray(c.sections)){const m=c.sections.flatMap(u=>Array.isArray(u.elements)&&!u.type?u.elements.map((v,w)=>({type:Ue(v.type),title:w===0?u.title:void 0,config:v.config??{}})):[{...u,type:Ue(u.type)}]);c.header&&!m.some(u=>u.type==="header")&&m.unshift({type:"header",title:"Header",config:c.header}),c.footer&&!m.some(u=>u.type==="footer")&&m.push({type:"footer",title:"Footer",config:c.footer});const p=m.map((u,v)=>({...u,id:u.id||`section_${v}`,order:u.order??v,config:u.config||{}}));return{id:c.id||`report_${Date.now()}`,name:c.name||c.title||"Generated Report",description:c.description,orientation:c.orientation||"portrait",pageSize:c.pageSize||"A4",margins:c.margins||{top:20,right:20,bottom:20,left:20},sections:p,dataSources:c.dataSources,parameters:c.parameters,styles:c.styles}}}catch{}return null}function ct(t){if(!t)return[];const a=[],i=new Set(t.sections.map(r=>r.type));return i.has("summary")||a.push("Add an executive summary for quick insights"),i.has("kpi")||a.push("Include KPI cards for key metrics"),i.has("chart")||a.push("Add visualizations to make data more accessible"),i.has("footer")||a.push("Add a footer with page numbers and date"),t.sections.length>5&&!i.has("toc")&&a.push("Consider adding a table of contents"),a.slice(0,3)}const ot=[{icon:"bar-chart",name:"Sales Report",prompt:"Monthly sales report with revenue KPIs, sales by region chart, and top products table"},{icon:"bar-chart",name:"Financial Summary",prompt:"Quarterly financial summary with P&L, cash flow chart, and expense breakdown"},{icon:"users",name:"HR Dashboard",prompt:"Employee report with headcount KPIs, department breakdown, and turnover trends"},{icon:"box",name:"Inventory Report",prompt:"Inventory status report with stock levels, low stock alerts, and turnover analysis"},{icon:"target",name:"KPI Dashboard",prompt:"Executive KPI dashboard with performance metrics, trends, and target comparison"}];function lt({config:t,dataSources:a,context:i,onGenerate:r,placeholder:n,showTemplates:s=!0,showPreview:o=!0,className:c,style:m,renderReport:p}){const{t:u}=T.useNiceTranslation(),v=n??u("reportBuilderAI.describeTheReport",'Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")'),[w,A]=l.useState(""),R=l.useRef(null),{generateReport:M,loading:P,lastResult:g,isConfigured:d}=Ca({config:t,dataSources:a,context:i,onReportGenerated:r}),j=async()=>{!w.trim()||P||await M(w)},y=b=>{var h;A(b.prompt),(h=R.current)==null||h.focus()},I=()=>{if(!(g!=null&&g.layout))return;const b=JSON.stringify(g.layout,null,2),h=new Blob([b],{type:"application/json"}),_=URL.createObjectURL(h),f=document.createElement("a");f.href=_,f.download=`${g.layout.name.replace(/\s+/g,"_")}.json`,f.click(),URL.revokeObjectURL(_)};return d?e.jsxs("div",{className:`nice-report-ai ${c||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:ot.map((b,h)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>y(b),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:e.jsx(T.NiceIcon,{name:b.icon,size:24})}),e.jsx("span",{className:"nice-report-ai__template-name",children:b.name})]},h))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:R,value:w,onChange:b=>A(b.target.value),placeholder:v,className:"nice-report-ai__input",rows:3,disabled:P}),e.jsx("button",{type:"button",onClick:j,className:"nice-report-ai__submit",disabled:P||!w.trim(),children:P?e.jsx("span",{className:"nice-report-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"file",size:14})," ",u("reportBuilderAI.generateReport","Generate Report")]})})]}),a&&a.length>0&&e.jsxs("div",{className:"nice-report-ai__datasources",children:[e.jsx("span",{className:"nice-report-ai__datasources-label",children:"Available data:"}),a.map(b=>e.jsx("span",{className:"nice-report-ai__datasource",children:b.name},b.id))]}),g&&e.jsx("div",{className:"nice-report-ai__result",children:g.error?e.jsx("div",{className:"nice-report-ai__error",children:g.error}):g.layout&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-report-ai__result-header",children:[e.jsxs("div",{className:"nice-report-ai__report-info",children:[e.jsx("span",{className:"nice-report-ai__report-name",children:g.layout.name}),g.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:g.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[g.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[g.layout.pageSize," ",g.layout.orientation]}),g.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(g.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(g.layout),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",u("reportBuilderAI.useReport","Use Report")]}),e.jsxs("button",{type:"button",onClick:I,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",u("reportBuilderAI.exportJson","Export JSON")]})]}),e.jsxs("div",{className:"nice-report-ai__sections",children:[e.jsx("div",{className:"nice-report-ai__sections-title",children:"Report Structure:"}),e.jsx("div",{className:"nice-report-ai__sections-list",children:g.layout.sections.map((b,h)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:h+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:e.jsx(T.NiceIcon,{name:Ia(b.type),size:16})}),e.jsx("span",{className:"nice-report-ai__section-type",children:b.type}),b.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:b.title})]},b.id))})]}),o&&e.jsx("div",{className:"nice-report-ai__preview",children:p?p(g.layout):e.jsx(dt,{layout:g.layout})}),g.suggestions&&g.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsxs("span",{className:"nice-report-ai__suggestions-title",children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:g.suggestions.map((b,h)=>e.jsx("li",{children:b},h))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:u("reportBuilderAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(g.layout,null,2)})]})]})}),e.jsx("style",{children:`
|
|
1891
1891
|
.nice-report-ai {
|
|
1892
1892
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
1893
1893
|
}
|
|
@@ -2199,7 +2199,7 @@ Purpose: ${j}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:g.messa
|
|
|
2199
2199
|
color: var(--nice-error, #c62828);
|
|
2200
2200
|
border-radius: var(--nice-radius-md, 6px);
|
|
2201
2201
|
}
|
|
2202
|
-
`})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${c||""}`,style:
|
|
2202
|
+
`})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:u("reportBuilderAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Ia(t){return{header:"file",summary:"edit",kpi:"bar-chart",table:"clipboard",chart:"bar-chart",text:"file",image:"image",divider:"minus",spacer:"square",pageBreak:"file",footer:"file",toc:"book",customBlock:"puzzle"}[t]||"file"}function dt({layout:t}){return e.jsxs("div",{className:"report-preview",style:{aspectRatio:t.orientation==="landscape"?"1.414":"0.707",maxWidth:t.orientation==="landscape"?"100%":"60%"},children:[e.jsx("div",{className:"report-preview__paper",children:t.sections.map(a=>e.jsxs("div",{className:`report-preview__section report-preview__section--${a.type}`,children:[e.jsx("span",{className:"report-preview__section-icon",children:e.jsx(T.NiceIcon,{name:Ia(a.type),size:14})}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
|
|
2203
2203
|
.report-preview {
|
|
2204
2204
|
display: flex;
|
|
2205
2205
|
justify-content: center;
|
|
@@ -2279,7 +2279,7 @@ Purpose: ${j}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:g.messa
|
|
|
2279
2279
|
text-overflow: ellipsis;
|
|
2280
2280
|
white-space: nowrap;
|
|
2281
2281
|
}
|
|
2282
|
-
`})]})}function
|
|
2282
|
+
`})]})}function ut(t,a){return{system:`You are a UI/UX designer specializing in design systems. Create a complete theme for the request, with WCAG 2.1 AA contrast (4.5:1 for text).
|
|
2283
2283
|
Return only JSON: ${a?'{ "light": THEME, "dark": THEME }, the dark one with "mode": "dark",':'{ "light": THEME },'} where THEME is
|
|
2284
2284
|
{
|
|
2285
2285
|
"name": "Theme name",
|
|
@@ -2294,19 +2294,19 @@ Return only JSON: ${a?'{ "light": THEME, "dark": THEME }, the dark one with "mod
|
|
|
2294
2294
|
},
|
|
2295
2295
|
"typography": { "fontFamily": "...", "fontFamilyMono": "..." },
|
|
2296
2296
|
"borderRadius": { "sm": "4px", "md": "8px", "lg": "12px" }
|
|
2297
|
-
}`,user:
|
|
2298
|
-
${JSON.stringify(
|
|
2299
|
-
|
|
2300
|
-
Adjustments: ${
|
|
2301
|
-
/* Typography */`),Object.entries(
|
|
2302
|
-
/* Spacing */`),Object.entries(
|
|
2303
|
-
/* Border Radius */`),Object.entries(
|
|
2304
|
-
/* Shadows */`),Object.entries(
|
|
2305
|
-
/* Animations */`),Object.entries(
|
|
2306
|
-
${
|
|
2297
|
+
}`,user:t}}function Aa(t={}){const{config:a,generateDarkMode:i=!0,onThemeGenerated:r,onError:n}=t,s=ee(),[o,c]=l.useState(!1),[m,p]=l.useState(null),u=l.useRef(null),v=a||(s==null?void 0:s.config),w=l.useCallback(async d=>{var y,I,b,h;if(!v){const _="AI not configured";return n==null||n(_),{error:_}}c(!0);const j=performance.now();(y=u.current)==null||y.abort(),u.current=new AbortController;try{const _=V(v);let f="";switch(d.type){case"description":f=d.value;break;case"brand":f=`Create a theme for "${d.value.name}"${d.value.industry?` in the ${d.value.industry} industry`:""}${(I=d.value.keywords)!=null&&I.length?`. Keywords: ${d.value.keywords.join(", ")}`:""}`;break;case"colors":f=`Create a theme based on primary color ${d.value.primary}${d.value.secondary?` and secondary color ${d.value.secondary}`:""}`;break;case"image":f="Extract colors and create a theme from the provided image palette";break}const k=ut(f,i),S=await _.chat({messages:[{role:"system",content:k.system},{role:"user",content:k.user}],temperature:.6,maxTokens:2048}),N=We(S),$={theme:N.light||void 0,darkTheme:N.dark||void 0,rawResponse:(h=(b=S.choices[0])==null?void 0:b.message)==null?void 0:h.content,latencyMs:performance.now()-j,error:N.light?void 0:"Failed to generate theme",suggestions:mt(N.light)};return N.light&&(r==null||r(N.light,N.dark??void 0)),p($),$}catch(_){const f=_ instanceof Error?_.message:"Theme generation failed",k={error:f,latencyMs:performance.now()-j};return p(k),n==null||n(f),k}finally{c(!1)}},[v,i,r,n]),A=l.useCallback(async(d,j)=>{if(!v)return null;c(!0);try{const I=await V(v).chat({messages:[{role:"system",content:"Adjust the theme based on the user's request. Return the complete adjusted theme in JSON format."},{role:"user",content:`Current theme:
|
|
2298
|
+
${JSON.stringify(d,null,2)}
|
|
2299
|
+
|
|
2300
|
+
Adjustments: ${j}`}],temperature:.4,maxTokens:2048});return We(I).light||null}catch{return null}finally{c(!1)}},[v]),R=l.useCallback(d=>{const j=[];return j.push(" /* Colors */"),Object.entries(d.colors).forEach(([y,I])=>{j.push(` --nice-${ve(y)}: ${I};`)}),j.push(`
|
|
2301
|
+
/* Typography */`),Object.entries(d.typography).forEach(([y,I])=>{j.push(` --nice-${ve(y)}: ${I};`)}),j.push(`
|
|
2302
|
+
/* Spacing */`),Object.entries(d.spacing).forEach(([y,I])=>{j.push(` --nice-spacing-${y}: ${I};`)}),j.push(`
|
|
2303
|
+
/* Border Radius */`),Object.entries(d.borderRadius).forEach(([y,I])=>{j.push(` --nice-radius-${y}: ${I};`)}),j.push(`
|
|
2304
|
+
/* Shadows */`),Object.entries(d.shadows).forEach(([y,I])=>{j.push(` --nice-shadow-${y}: ${I};`)}),j.push(`
|
|
2305
|
+
/* Animations */`),Object.entries(d.animations).forEach(([y,I])=>{j.push(` --nice-${ve(y)}: ${I};`)}),`:root {
|
|
2306
|
+
${j.join(`
|
|
2307
2307
|
`)}
|
|
2308
|
-
}`},[]),
|
|
2309
|
-
module.exports = ${JSON.stringify(
|
|
2308
|
+
}`},[]),M=l.useCallback(d=>{const j={theme:{extend:{colors:{primary:{DEFAULT:d.colors.primary,light:d.colors.primaryLight,dark:d.colors.primaryDark},secondary:{DEFAULT:d.colors.secondary,light:d.colors.secondaryLight,dark:d.colors.secondaryDark},accent:d.colors.accent,success:d.colors.success,warning:d.colors.warning,error:d.colors.error,info:d.colors.info},fontFamily:{sans:[d.typography.fontFamily],mono:[d.typography.fontFamilyMono]},borderRadius:d.borderRadius,boxShadow:d.shadows}}};return`// tailwind.config.js
|
|
2309
|
+
module.exports = ${JSON.stringify(j,null,2)}`},[]),P=l.useCallback(()=>{p(null)},[]),g=l.useCallback(()=>{var d;(d=u.current)==null||d.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var d;(d=u.current)==null||d.abort()},[]),{generateTheme:w,adjustTheme:A,toCSSVariables:R,toTailwindConfig:M,loading:o,lastResult:m,clearResults:P,abort:g,isConfigured:!!v}}function We(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.light||c.theme)return{light:ye(c.light||c.theme),dark:c.dark?ye(c.dark):null};if(c.colors)return{light:ye(c),dark:null}}catch{}return{light:null,dark:null}}function ye(t){return{id:t.id||`theme_${Date.now()}`,name:t.name||"Generated Theme",description:t.description,mode:t.mode||"light",colors:{primary:"#0066cc",primaryLight:"#4d94db",primaryDark:"#004499",secondary:"#6c757d",secondaryLight:"#9ca3af",secondaryDark:"#4b5563",accent:"#ff6b35",background:"#ffffff",surface:"#f8f9fa",text:"#212529",textMuted:"#6c757d",textInverse:"#ffffff",border:"#dee2e6",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",...t.colors},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontFamilyMono:"ui-monospace, monospace",fontSizeBase:"16px",fontSizeXs:"12px",fontSizeSm:"14px",fontSizeMd:"16px",fontSizeLg:"18px",fontSizeXl:"20px",fontSize2xl:"24px",fontSize3xl:"30px",fontWeightLight:300,fontWeightNormal:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700,lineHeightTight:1.25,lineHeightNormal:1.5,lineHeightRelaxed:1.75,letterSpacing:"normal",...t.typography},spacing:{xs:"4px",sm:"8px",md:"16px",lg:"24px",xl:"32px","2xl":"48px","3xl":"64px","4xl":"80px",...t.spacing},borderRadius:{none:"0",sm:"4px",md:"8px",lg:"12px",xl:"16px",full:"9999px",...t.borderRadius},shadows:{none:"none",sm:"0 1px 2px rgba(0, 0, 0, 0.05)",md:"0 4px 6px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px rgba(0, 0, 0, 0.1)",xl:"0 20px 25px rgba(0, 0, 0, 0.1)",...t.shadows},animations:{durationFast:"150ms",durationNormal:"300ms",durationSlow:"500ms",easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)",...t.animations},components:t.components,cssVariables:t.cssVariables}}function mt(t){if(!t)return[];const a=[];return a.push("Verify WCAG contrast ratios for text on background"),a.push("Test the theme in both light and dark environments"),a.push("Ensure button and input styles are consistent"),a.slice(0,3)}function ve(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const pt=[{icon:"building",name:"Corporate",prompt:"Professional corporate theme with blue and gray tones"},{icon:"palette",name:"Creative",prompt:"Vibrant creative agency theme with bold colors"},{icon:"tree",name:"Natural",prompt:"Organic natural theme with earth tones and greens"},{icon:"moon",name:"Dark Pro",prompt:"Modern dark theme for developer tools"},{icon:"gift",name:"Playful",prompt:"Fun playful theme with candy colors for kids"},{icon:"star",name:"Luxury",prompt:"Elegant luxury brand theme with gold accents"}];function gt({config:t,generateDarkMode:a=!0,onGenerate:i,showPresets:r=!0,showPreview:n=!0,className:s,style:o}){const{t:c}=T.useNiceTranslation(),[m,p]=l.useState("description"),[u,v]=l.useState(""),[w,A]=l.useState(""),[R,M]=l.useState(""),[P,g]=l.useState("#0066cc"),[d,j]=l.useState("light"),{generateTheme:y,toCSSVariables:I,toTailwindConfig:b,loading:h,lastResult:_,isConfigured:f}=Aa({config:t,generateDarkMode:a,onThemeGenerated:i}),k=async()=>{if(h)return;let z;switch(m){case"brand":if(!w.trim())return;z={type:"brand",value:{name:w,industry:R||void 0}};break;case"colors":z={type:"colors",value:{primary:P}};break;default:if(!u.trim())return;z={type:"description",value:u}}await y(z)},S=z=>{p("description"),v(z.prompt)},N=()=>{if(!(_!=null&&_.theme))return;const z=I(_.theme),F=new Blob([z],{type:"text/css"}),U=URL.createObjectURL(F),H=document.createElement("a");H.href=U,H.download=`${_.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,H.click(),URL.revokeObjectURL(U)},$=()=>{if(!(_!=null&&_.theme))return;const z=b(_.theme),F=new Blob([z],{type:"text/javascript"}),U=URL.createObjectURL(F),H=document.createElement("a");H.href=U,H.download="tailwind.config.js",H.click(),URL.revokeObjectURL(U)},E=d==="dark"&&(_!=null&&_.darkTheme)?_.darkTheme:_==null?void 0:_.theme;return f?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:o,children:[r&&e.jsx("div",{className:"nice-theme-ai__presets",children:pt.map((z,F)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>S(z),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:e.jsx(T.NiceIcon,{name:z.icon,size:24})}),e.jsx("span",{className:"nice-theme-ai__preset-name",children:z.name})]},F))}),e.jsxs("div",{className:"nice-theme-ai__tabs",children:[e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("description"),children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",c("themeGeneratorAI.description","Description")]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("brand"),children:[e.jsx(T.NiceIcon,{name:"tag",size:14})," ",c("themeGeneratorAI.brand","Brand")]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("colors"),children:[e.jsx(T.NiceIcon,{name:"palette",size:14})," ",c("themeGeneratorAI.colors","Colors")]})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[m==="description"&&e.jsx("textarea",{value:u,onChange:z=>v(z.target.value),placeholder:c("themeGeneratorAI.describeTheThemeYouWant","Describe the theme you want... (e.g., 'Modern tech startup with blue and green')"),className:"nice-theme-ai__textarea",rows:3,disabled:h}),m==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:w,onChange:z=>A(z.target.value),placeholder:c("themeGeneratorAI.brandName","Brand name"),className:"nice-theme-ai__input",disabled:h}),e.jsx("input",{type:"text",value:R,onChange:z=>M(z.target.value),placeholder:c("themeGeneratorAI.industryOptional","Industry (optional)"),className:"nice-theme-ai__input",disabled:h})]}),m==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:P,onChange:z=>g(z.target.value),className:"nice-theme-ai__color-picker",disabled:h}),e.jsx("span",{className:"nice-theme-ai__color-value",children:P})]})}),e.jsx("button",{type:"button",onClick:k,className:"nice-theme-ai__submit",disabled:h,children:h?e.jsx("span",{className:"nice-theme-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"wand",size:14})," ",c("themeGeneratorAI.generateTheme","Generate Theme")]})})]}),(_==null?void 0:_.error)&&e.jsx("div",{className:"nice-theme-ai__error",role:"alert",children:_.error}),_&&E&&e.jsxs("div",{className:"nice-theme-ai__result",children:[e.jsxs("div",{className:"nice-theme-ai__result-header",children:[e.jsxs("div",{className:"nice-theme-ai__theme-info",children:[e.jsx("span",{className:"nice-theme-ai__theme-name",children:E.name}),E.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:E.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[_.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button","aria-label":c("themeGeneratorAI.lightMode","Light mode"),className:d==="light"?"active":"",onClick:()=>j("light"),children:e.jsx(T.NiceIcon,{name:"sun",size:16})}),e.jsx("button",{type:"button","aria-label":c("themeGeneratorAI.darkMode","Dark mode"),className:d==="dark"?"active":"",onClick:()=>j("dark"),children:e.jsx(T.NiceIcon,{name:"moon",size:16})})]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:$,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",c("themeGeneratorAI.tailwind","Tailwind")]})]})]}),n&&e.jsx(ht,{theme:E}),e.jsxs("div",{className:"nice-theme-ai__palette",children:[e.jsx("div",{className:"nice-theme-ai__palette-title",children:c("themeGeneratorAI.colorPalette","Color Palette")}),e.jsx("div",{className:"nice-theme-ai__colors",children:Object.entries(E.colors).map(([z,F])=>e.jsxs("div",{className:"nice-theme-ai__color",children:[e.jsx("div",{className:"nice-theme-ai__color-swatch",style:{backgroundColor:F}}),e.jsx("span",{className:"nice-theme-ai__color-name",children:z}),e.jsx("span",{className:"nice-theme-ai__color-hex",children:F})]},z))})]}),e.jsxs("div",{className:"nice-theme-ai__typography",children:[e.jsx("div",{className:"nice-theme-ai__typography-title",children:c("themeGeneratorAI.typography","Typography")}),e.jsxs("div",{style:{fontFamily:E.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:E.typography.fontSize3xl,fontWeight:E.typography.fontWeightBold},children:c("themeGeneratorAI.heading1","Heading 1")}),e.jsx("p",{style:{fontSize:E.typography.fontSizeLg},children:"Body text: The quick brown fox jumps over the lazy dog."}),e.jsx("p",{style:{fontFamily:E.typography.fontFamilyMono,fontSize:E.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
|
|
2310
2310
|
.nice-theme-ai {
|
|
2311
2311
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
2312
2312
|
}
|
|
@@ -2587,7 +2587,7 @@ module.exports = ${JSON.stringify(y,null,2)}`},[]),O=d.useCallback(()=>{p(null)}
|
|
|
2587
2587
|
color: var(--nice-error, #c62828);
|
|
2588
2588
|
border-radius: var(--nice-radius-md, 6px);
|
|
2589
2589
|
}
|
|
2590
|
-
`})]}):e.jsx("div",{className:`nice-theme-ai nice-theme-ai--disabled ${s||""}`,style:o,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function
|
|
2590
|
+
`})]}):e.jsx("div",{className:`nice-theme-ai nice-theme-ai--disabled ${s||""}`,style:o,children:e.jsx("p",{children:c("themeGeneratorAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function ht({theme:t}){const{t:a}=T.useNiceTranslation();return e.jsxs("div",{className:"theme-preview",style:{"--preview-primary":t.colors.primary,"--preview-bg":t.colors.background,"--preview-surface":t.colors.surface,"--preview-text":t.colors.text,"--preview-border":t.colors.border,"--preview-radius":t.borderRadius.md,fontFamily:t.typography.fontFamily},children:[e.jsxs("div",{className:"theme-preview__header",children:[e.jsx("span",{style:{color:t.colors.primary,fontWeight:t.typography.fontWeightBold},children:t.name}),e.jsxs("div",{className:"theme-preview__dots",children:[e.jsx("span",{style:{background:t.colors.error}}),e.jsx("span",{style:{background:t.colors.warning}}),e.jsx("span",{style:{background:t.colors.success}})]})]}),e.jsxs("div",{className:"theme-preview__content",children:[e.jsx("button",{style:{background:t.colors.primary,color:t.colors.textInverse,borderRadius:t.borderRadius.md,padding:`${t.spacing.sm} ${t.spacing.md}`},children:a("themeGeneratorAI.primaryButton","Primary Button")}),e.jsx("button",{style:{background:t.colors.secondary,color:t.colors.textInverse,borderRadius:t.borderRadius.md,padding:`${t.spacing.sm} ${t.spacing.md}`},children:a("themeGeneratorAI.secondary","Secondary")}),e.jsx("input",{type:"text",placeholder:a("themeGeneratorAI.inputField","Input field"),readOnly:!0,style:{border:`1px solid ${t.colors.border}`,borderRadius:t.borderRadius.md,padding:t.spacing.sm,background:t.colors.surface}})]}),e.jsx("style",{children:`
|
|
2591
2591
|
.theme-preview {
|
|
2592
2592
|
background: var(--preview-bg);
|
|
2593
2593
|
border: 1px solid var(--preview-border);
|
|
@@ -2633,13 +2633,13 @@ module.exports = ${JSON.stringify(y,null,2)}`},[]),O=d.useCallback(()=>{p(null)}
|
|
|
2633
2633
|
cursor: text;
|
|
2634
2634
|
width: 150px;
|
|
2635
2635
|
}
|
|
2636
|
-
`})]})}function
|
|
2636
|
+
`})]})}function Ta(t={}){const{config:a,targetDevice:i="responsive",onLayoutGenerated:r,onError:n}=t,s=ee(),[o,c]=l.useState(!1),[m,p]=l.useState(null),u=l.useRef(null),v=a||(s==null?void 0:s.config),w=l.useCallback(async(g,d)=>{var y,I,b;if(!v){const h="AI not configured";return n==null||n(h),{error:h}}c(!0);const j=performance.now();(y=u.current)==null||y.abort(),u.current=new AbortController;try{const h=V(v),_=`You are a UI layout expert. Generate a responsive layout based on the description.
|
|
2637
2637
|
Return JSON with this structure:
|
|
2638
2638
|
{
|
|
2639
2639
|
"id": "unique_id",
|
|
2640
2640
|
"name": "Layout Name",
|
|
2641
2641
|
"description": "Description",
|
|
2642
|
-
"type": "${
|
|
2642
|
+
"type": "${d||"dashboard"}",
|
|
2643
2643
|
"container": {
|
|
2644
2644
|
"direction": "row|column|grid",
|
|
2645
2645
|
"gap": "16px",
|
|
@@ -2668,45 +2668,45 @@ Return JSON with this structure:
|
|
|
2668
2668
|
"xl": "1280px",
|
|
2669
2669
|
"2xl": "1536px"
|
|
2670
2670
|
}
|
|
2671
|
-
}`,
|
|
2672
|
-
`;if(
|
|
2673
|
-
`,
|
|
2674
|
-
`}
|
|
2675
|
-
`)}else
|
|
2676
|
-
`,
|
|
2677
|
-
`);return
|
|
2678
|
-
`),
|
|
2679
|
-
`),
|
|
2680
|
-
`),
|
|
2681
|
-
`),
|
|
2682
|
-
|
|
2683
|
-
`,
|
|
2684
|
-
`,(
|
|
2685
|
-
`),(
|
|
2686
|
-
`),(j
|
|
2687
|
-
`),(
|
|
2688
|
-
`),(
|
|
2689
|
-
`),(
|
|
2690
|
-
`),
|
|
2691
|
-
|
|
2692
|
-
`}),
|
|
2693
|
-
`,
|
|
2694
|
-
`,(
|
|
2695
|
-
`),(
|
|
2696
|
-
`),
|
|
2697
|
-
`}),
|
|
2698
|
-
|
|
2699
|
-
`)}),
|
|
2671
|
+
}`,f=await h.chat({messages:[{role:"system",content:_},{role:"user",content:`Create a ${i} layout: ${g}${d?` (type: ${d})`:""}`}],temperature:.5,maxTokens:2048}),k=ft(f),S={layout:k||void 0,rawResponse:(b=(I=f.choices[0])==null?void 0:I.message)==null?void 0:b.content,latencyMs:performance.now()-j,error:k?void 0:"Failed to generate layout",suggestions:xt(k)};return k&&(r==null||r(k)),p(S),S}catch(h){const _=h instanceof Error?h.message:"Layout generation failed",f={error:_,latencyMs:performance.now()-j};return p(f),n==null||n(_),f}finally{c(!1)}},[v,i,r,n]),A=l.useCallback(g=>{let d=`.${g.id} {
|
|
2672
|
+
`;if(d+=` display: ${g.container.direction==="grid"?"grid":"flex"};
|
|
2673
|
+
`,g.container.direction==="grid"){if(g.container.gridColumns){const j=typeof g.container.gridColumns=="number"?`repeat(${g.container.gridColumns}, 1fr)`:g.container.gridColumns;d+=` grid-template-columns: ${j};
|
|
2674
|
+
`}g.container.gridRows&&(d+=` grid-template-rows: ${g.container.gridRows};
|
|
2675
|
+
`)}else d+=` flex-direction: ${g.container.direction};
|
|
2676
|
+
`,g.container.wrap&&(d+=` flex-wrap: wrap;
|
|
2677
|
+
`);return g.container.gap&&(d+=` gap: ${g.container.gap};
|
|
2678
|
+
`),g.container.padding&&(d+=` padding: ${g.container.padding};
|
|
2679
|
+
`),g.container.align&&(d+=` align-items: ${g.container.align};
|
|
2680
|
+
`),g.container.justify&&(d+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[g.container.justify]||g.container.justify};
|
|
2681
|
+
`),d+=`}
|
|
2682
|
+
|
|
2683
|
+
`,g.regions.forEach(j=>{var y,I,b,h,_,f;d+=`.${g.id}__${j.id} {
|
|
2684
|
+
`,(y=j.position)!=null&&y.gridColumn&&(d+=` grid-column: ${j.position.gridColumn};
|
|
2685
|
+
`),(I=j.position)!=null&&I.gridRow&&(d+=` grid-row: ${j.position.gridRow};
|
|
2686
|
+
`),(b=j.size)!=null&&b.width&&(d+=` width: ${j.size.width};
|
|
2687
|
+
`),(h=j.size)!=null&&h.height&&(d+=` height: ${j.size.height};
|
|
2688
|
+
`),(_=j.size)!=null&&_.minWidth&&(d+=` min-width: ${j.size.minWidth};
|
|
2689
|
+
`),(f=j.size)!=null&&f.maxWidth&&(d+=` max-width: ${j.size.maxWidth};
|
|
2690
|
+
`),d+=`}
|
|
2691
|
+
|
|
2692
|
+
`}),g.breakpoints&&Object.entries(g.breakpoints).forEach(([j,y])=>{const I=g.regions.filter(b=>{var h;return(h=b.responsive)==null?void 0:h[j]});I.length>0&&(d+=`@media (max-width: ${y}) {
|
|
2693
|
+
`,I.forEach(b=>{var _,f;const h=b.responsive[j];d+=` .${g.id}__${b.id} {
|
|
2694
|
+
`,(_=h.size)!=null&&_.width&&(d+=` width: ${h.size.width};
|
|
2695
|
+
`),(f=h.size)!=null&&f.height&&(d+=` height: ${h.size.height};
|
|
2696
|
+
`),d+=` }
|
|
2697
|
+
`}),d+=`}
|
|
2698
|
+
|
|
2699
|
+
`)}),d},[]),R=l.useCallback(g=>{const d=g.regions.map(j=>` <div className="${g.id}__${j.id}">{/* ${j.type} */}</div>`).join(`
|
|
2700
2700
|
`);return`import React from 'react';
|
|
2701
|
-
import './${
|
|
2701
|
+
import './${g.id}.css';
|
|
2702
2702
|
|
|
2703
|
-
export function ${
|
|
2703
|
+
export function ${Ra(g.name)}() {
|
|
2704
2704
|
return (
|
|
2705
|
-
<div className="${
|
|
2706
|
-
${
|
|
2705
|
+
<div className="${g.id}">
|
|
2706
|
+
${d}
|
|
2707
2707
|
</div>
|
|
2708
2708
|
);
|
|
2709
|
-
}`},[]),
|
|
2709
|
+
}`},[]),M=l.useCallback(()=>{p(null)},[]),P=l.useCallback(()=>{var g;(g=u.current)==null||g.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var g;(g=u.current)==null||g.abort()},[]),{generateLayout:w,toCSS:A,toReactComponent:R,loading:o,lastResult:m,clearResults:M,abort:P,isConfigured:!!v}}function ft(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.regions||c.container)return{id:c.id||`layout_${Date.now()}`,name:c.name||"Generated Layout",description:c.description,type:c.type||"dashboard",container:{direction:"grid",gap:"16px",padding:"20px",gridColumns:12,...c.container},regions:c.regions||[],breakpoints:c.breakpoints||{xs:"320px",sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},cssGrid:c.cssGrid,cssVariables:c.cssVariables}}catch{}return null}function xt(t){if(!t)return[];const a=[],i=new Set(t.regions.map(r=>r.type));return i.has("header")||a.push("Consider adding a header region for navigation"),!i.has("sidebar")&&t.type==="dashboard"&&a.push("Add a sidebar for dashboard navigation"),t.regions.some(r=>!r.responsive)&&a.push("Add responsive breakpoints for mobile compatibility"),a.slice(0,3)}function Ra(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(a,i)=>i.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const bt=[{type:"dashboard",icon:"bar-chart",label:"Dashboard"},{type:"form",icon:"edit",label:"Form"},{type:"list",icon:"list",label:"List"},{type:"detail",icon:"file",label:"Detail"},{type:"landing",icon:"home",label:"Landing"},{type:"settings",icon:"settings",label:"Settings"},{type:"wizard",icon:"wand",label:"Wizard"},{type:"split",icon:"grid",label:"Split"},{type:"grid",icon:"grid",label:"Grid"},{type:"kanban",icon:"columns",label:"Kanban"}];function yt({config:t,targetDevice:a="responsive",onGenerate:i,showTypeSelector:r=!0,showPreview:n=!0,className:s,style:o,renderLayout:c}){const{t:m}=T.useNiceTranslation(),[p,u]=l.useState(""),[v,w]=l.useState(null),{generateLayout:A,toCSS:R,toReactComponent:M,loading:P,lastResult:g,isConfigured:d}=Ta({config:t,targetDevice:a,onLayoutGenerated:i}),j=async()=>{!p.trim()||P||await A(p,v||void 0)},y=()=>{if(!(g!=null&&g.layout))return;const b=R(g.layout),h=new Blob([b],{type:"text/css"}),_=URL.createObjectURL(h),f=document.createElement("a");f.href=_,f.download=`${g.layout.id}.css`,f.click(),URL.revokeObjectURL(_)},I=()=>{if(!(g!=null&&g.layout))return;const b=M(g.layout),h=new Blob([b],{type:"text/javascript"}),_=URL.createObjectURL(h),f=document.createElement("a");f.href=_,f.download=`${Ra(g.layout.name)}.tsx`,f.click(),URL.revokeObjectURL(_)};return d?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:o,children:[r&&e.jsx("div",{className:"nice-layout-ai__types",children:bt.map(({type:b,icon:h,label:_})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${v===b?"nice-layout-ai__type--selected":""}`,onClick:()=>w(v===b?null:b),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:e.jsx(T.NiceIcon,{name:h,size:20})}),e.jsx("span",{className:"nice-layout-ai__type-label",children:_})]},b))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:p,onChange:b=>u(b.target.value),placeholder:m("layoutAI.describeTheLayoutYouNeed","Describe the layout you need... (e.g., 'Admin dashboard with sidebar navigation and header')"),className:"nice-layout-ai__input",rows:3,disabled:P}),e.jsx("button",{type:"button",onClick:j,className:"nice-layout-ai__submit",disabled:P||!p.trim(),children:P?e.jsx("span",{className:"nice-layout-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"palette",size:14})," ",m("layoutAI.generateLayout","Generate Layout")]})})]}),(g==null?void 0:g.error)&&e.jsx("div",{className:"nice-layout-ai__error",role:"alert",children:g.error}),g&&g.layout&&e.jsxs("div",{className:"nice-layout-ai__result",children:[e.jsxs("div",{className:"nice-layout-ai__result-header",children:[e.jsxs("div",{className:"nice-layout-ai__layout-info",children:[e.jsx("span",{className:"nice-layout-ai__layout-name",children:g.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:g.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>i==null?void 0:i(g.layout),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",m("layoutAI.useLayout","Use Layout")]}),e.jsxs("button",{type:"button",onClick:y,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:I,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",m("layoutAI.react","React")]})]})]}),e.jsxs("div",{className:"nice-layout-ai__regions",children:[e.jsx("div",{className:"nice-layout-ai__regions-title",children:"Regions:"}),e.jsx("div",{className:"nice-layout-ai__regions-list",children:g.layout.regions.map(b=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${b.type}`,children:b.type},b.id))})]}),n&&e.jsx("div",{className:"nice-layout-ai__preview",children:c?c(g.layout):e.jsx(vt,{layout:g.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:m("layoutAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(g.layout,null,2)})]})]}),e.jsx("style",{children:`
|
|
2710
2710
|
.nice-layout-ai {
|
|
2711
2711
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
2712
2712
|
}
|
|
@@ -2941,7 +2941,7 @@ ${l}
|
|
|
2941
2941
|
color: var(--nice-error, #c62828);
|
|
2942
2942
|
border-radius: var(--nice-radius-md, 6px);
|
|
2943
2943
|
}
|
|
2944
|
-
`})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:o,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function
|
|
2944
|
+
`})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:o,children:e.jsx("p",{children:m("layoutAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function vt({layout:t}){const a=i=>({header:"var(--nice-primary-bg, #e3f2fd)",sidebar:"var(--nice-success-bg, #e8f5e9)",aside:"var(--nice-success-bg, #e8f5e9)",main:"var(--nice-warning-bg, #fff3e0)",content:"var(--nice-warning-bg, #fff3e0)",footer:"var(--nice-bg-secondary, #f5f5f5)",nav:"var(--nice-accent-tint-10, #fce4ec)"})[i]||"var(--nice-bg-secondary, #f5f5f5)";return e.jsx("div",{className:"layout-preview",style:{display:t.container.direction==="grid"?"grid":"flex",flexDirection:t.container.direction==="column"?"column":"row",gridTemplateColumns:t.container.direction==="grid"&&t.container.gridColumns?typeof t.container.gridColumns=="number"?`repeat(${t.container.gridColumns}, 1fr)`:t.container.gridColumns:void 0,gap:t.container.gap||"8px",minHeight:"300px"},children:t.regions.map(i=>{var r,n,s,o,c,m;return e.jsx("div",{className:"layout-preview__region",style:{gridColumn:(r=i.position)==null?void 0:r.gridColumn,gridRow:(n=i.position)==null?void 0:n.gridRow,width:(s=i.size)==null?void 0:s.width,height:((o=i.size)==null?void 0:o.height)||"80px",minWidth:(c=i.size)==null?void 0:c.minWidth,maxWidth:(m=i.size)==null?void 0:m.maxWidth,background:a(i.type),borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:500,color:"var(--nice-text-secondary, #666)",border:"1px dashed var(--nice-border, #ccc)"},children:i.type},i.id)})})}function La(t={}){const{config:a,wcagLevel:i="AA",onAuditComplete:r,onError:n}=t,s=ee(),[o,c]=l.useState(!1),[m,p]=l.useState(null),u=l.useRef(null),v=a||(s==null?void 0:s.config),w=l.useCallback(async(d,j)=>{var y;if(!v){const I="AI not configured";return n==null||n(I),Te("html",i,I)}c(!0),(y=u.current)==null||y.abort(),u.current=new AbortController;try{const I=V(v),b=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${i} level.
|
|
2945
2945
|
|
|
2946
2946
|
Return JSON with this exact structure:
|
|
2947
2947
|
{
|
|
@@ -2975,10 +2975,10 @@ Focus on:
|
|
|
2975
2975
|
7. Heading hierarchy
|
|
2976
2976
|
8. Landmark regions
|
|
2977
2977
|
9. Semantic HTML usage
|
|
2978
|
-
10. Language attributes`,
|
|
2979
|
-
${
|
|
2978
|
+
10. Language attributes`,h=await I.chat({messages:[{role:"system",content:b},{role:"user",content:`Analyze this HTML for accessibility:
|
|
2979
|
+
${j?`Context: ${j}
|
|
2980
2980
|
|
|
2981
|
-
`:""}${
|
|
2981
|
+
`:""}${d}`}],temperature:.3,maxTokens:4096}),_=_t(h,"html",i);return p(_),r==null||r(_),_}catch(I){const b=I instanceof Error?I.message:"Audit failed";return n==null||n(b),Te("html",i,b)}finally{c(!1)}},[v,i,r,n]),A=l.useCallback((d,j)=>{const y=fe(he(d)),I=fe(he(j)),b=(Math.max(y,I)+.05)/(Math.min(y,I)+.05),h={foreground:d,background:j,ratio:Math.round(b*100)/100,passesAA:b>=4.5,passesAALarge:b>=3,passesAAA:b>=7,passesAAALarge:b>=4.5};return h.passesAA||(h.suggestions=jt(d,j,4.5)),h},[]),R=l.useCallback(async d=>{var j,y;if(!v)return n==null||n("AI not configured"),[];try{const f=(((y=(j=(await V(v).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
|
|
2982
2982
|
Return JSON array:
|
|
2983
2983
|
[{
|
|
2984
2984
|
"element": "<button>...",
|
|
@@ -2989,10 +2989,10 @@ Return JSON array:
|
|
|
2989
2989
|
"issues": ["Missing aria-label"],
|
|
2990
2990
|
"suggestions": ["Add aria-label='Submit form'"]
|
|
2991
2991
|
}]`},{role:"user",content:`Validate ARIA in:
|
|
2992
|
-
${
|
|
2992
|
+
${d}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:j.message)==null?void 0:y.content)||"").match(/\[[\s\S]*\]/);if(f)return JSON.parse(f[0])}catch{}return[]},[v,n]),M=l.useCallback(async d=>{var j,y;if(!v)return n==null||n("AI not configured"),d;try{const h=((y=(j=(await V(v).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${i} compliant.
|
|
2993
2993
|
Add proper ARIA attributes, semantic HTML, keyboard handlers, focus management.
|
|
2994
2994
|
Return only the improved HTML code.`},{role:"user",content:`Make this accessible:
|
|
2995
|
-
${
|
|
2995
|
+
${d}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:j.message)==null?void 0:y.content)||"",_=h.match(/```(?:html)?\s*([\s\S]*?)```/);return _?_[1].trim():h.trim()}catch{return d}},[v,i,n]),P=l.useCallback(()=>{p(null)},[]),g=l.useCallback(()=>{var d;(d=u.current)==null||d.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var d;(d=u.current)==null||d.abort()},[]),{analyzeHTML:w,checkContrast:A,validateARIA:R,suggestAccessibleCode:M,loading:o,lastAudit:m,clearAudit:P,abort:g,isConfigured:!!v}}function Te(t,a,i){return{timestamp:new Date,target:t,wcagLevel:a,issues:i?[{id:"error",category:"semantic-html",severity:"critical",wcagCriteria:"N/A",wcagLevel:"A",title:"Audit Error",description:i,impact:"Audit could not complete",suggestion:"Try again or check configuration"}]:[],score:i?0:100,summary:{critical:i?1:0,serious:0,moderate:0,minor:0,passed:0},recommendations:[]}}function _t(t,a,i){var r,n,s;try{const o=((n=(r=t.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"",m=((s=(o.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,o])[1])==null?void 0:s.trim())||o,p=JSON.parse(m),u=(p.issues||[]).map((w,A)=>({id:w.id||`issue_${A}`,category:w.category||"semantic-html",severity:w.severity||"moderate",wcagCriteria:w.wcagCriteria||"N/A",wcagLevel:w.wcagLevel||"A",title:w.title||"Unknown Issue",description:w.description||"",element:w.element,selector:w.selector,impact:w.impact||"",suggestion:w.suggestion||"",codeExample:w.codeExample})),v={critical:u.filter(w=>w.severity==="critical").length,serious:u.filter(w=>w.severity==="serious").length,moderate:u.filter(w=>w.severity==="moderate").length,minor:u.filter(w=>w.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:i,issues:u,score:p.score??wt(v),summary:v,recommendations:p.recommendations||[]}}catch{return Te(a,i,"Failed to parse audit results")}}function wt(t){const a=t.critical*25+t.serious*15+t.moderate*5+t.minor*2;return Math.max(0,100-a)}function he(t){const a=t.replace("#","");return a.length===3?{r:parseInt(a[0]+a[0],16),g:parseInt(a[1]+a[1],16),b:parseInt(a[2]+a[2],16)}:{r:parseInt(a.slice(0,2),16),g:parseInt(a.slice(2,4),16),b:parseInt(a.slice(4,6),16)}}function fe(t){const[a,i,r]=[t.r,t.g,t.b].map(n=>(n/=255,n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)));return .2126*a+.7152*i+.0722*r}function jt(t,a,i){const r=[],n=he(t),s=he(a),o={r:Math.max(0,n.r-40),g:Math.max(0,n.g-40),b:Math.max(0,n.b-40)},c=`#${o.r.toString(16).padStart(2,"0")}${o.g.toString(16).padStart(2,"0")}${o.b.toString(16).padStart(2,"0")}`,m=fe(o),p=fe(s);(Math.max(m,p)+.05)/(Math.min(m,p)+.05)>=i&&r.push(`Try darker foreground: ${c}`);const v={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},w=`#${v.r.toString(16).padStart(2,"0")}${v.g.toString(16).padStart(2,"0")}${v.b.toString(16).padStart(2,"0")}`;return r.push(`Try lighter background: ${w}`),r}const _e={critical:{bg:"var(--nice-danger-bg, #ffebee)",color:"var(--nice-danger-dark, #c62828)",icon:"error"},serious:{bg:"var(--nice-warning-bg, #fff3e0)",color:"var(--nice-warning-dark, #e65100)",icon:"warning"},moderate:{bg:"var(--nice-warning-bg, #fff8e1)",color:"var(--nice-warning-dark, #f57f17)",icon:"zap"},minor:{bg:"var(--nice-primary-bg, #e3f2fd)",color:"var(--nice-primary-dark, #1565c0)",icon:"info"}};function kt({config:t,wcagLevel:a="AA",onAuditComplete:i,showContrastChecker:r=!0,className:n,style:s,renderIssue:o}){const{t:c}=T.useNiceTranslation(),[m,p]=l.useState(""),[u,v]=l.useState("#333333"),[w,A]=l.useState("#ffffff"),[R,M]=l.useState(null),{analyzeHTML:P,checkContrast:g,suggestAccessibleCode:d,loading:j,lastAudit:y,isConfigured:I}=La({config:t,wcagLevel:a,onAuditComplete:i}),b=async()=>{!m.trim()||j||await P(m)},h=()=>{const f=g(u,w);M(f)},_=async()=>{if(!m.trim())return;const f=await d(m);p(f)};return I?e.jsxs("div",{className:`nice-a11y-ai ${n||""}`,style:s,children:[r&&e.jsxs("div",{className:"nice-a11y-ai__contrast",children:[e.jsx("h3",{children:c("accessibilityAI.colorContrastChecker","Color Contrast Checker")}),e.jsxs("div",{className:"nice-a11y-ai__contrast-inputs",children:[e.jsxs("label",{children:[c("accessibilityAI.foreground","Foreground"),e.jsx("input",{type:"color",value:u,onChange:f=>v(f.target.value)}),e.jsx("input",{type:"text",value:u,onChange:f=>v(f.target.value)})]}),e.jsxs("label",{children:[c("accessibilityAI.background","Background"),e.jsx("input",{type:"color",value:w,onChange:f=>A(f.target.value)}),e.jsx("input",{type:"text",value:w,onChange:f=>A(f.target.value)})]}),e.jsx("button",{type:"button",onClick:h,children:c("accessibilityAI.check","Check")})]}),R&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:u,background:w},children:c("accessibilityAI.sampleTextAa","Sample Text Aa")}),e.jsxs("div",{className:"nice-a11y-ai__contrast-ratio",children:[e.jsxs("span",{className:"nice-a11y-ai__ratio-value",children:[R.ratio,":1"]}),e.jsxs("div",{className:"nice-a11y-ai__passes",children:[e.jsxs("span",{className:R.passesAA?"pass":"fail",children:["AA: ",e.jsx(T.NiceIcon,{name:R.passesAA?"check":"close",size:14})]}),e.jsxs("span",{className:R.passesAALarge?"pass":"fail",children:["AA Large:"," ",e.jsx(T.NiceIcon,{name:R.passesAALarge?"check":"close",size:14})]}),e.jsxs("span",{className:R.passesAAA?"pass":"fail",children:["AAA: ",e.jsx(T.NiceIcon,{name:R.passesAAA?"check":"close",size:14})]})]})]}),R.suggestions&&R.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:R.suggestions.map((f,k)=>e.jsx("div",{children:f},k))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsxs("h3",{children:["HTML Accessibility Analyzer (WCAG ",a,")"]}),e.jsx("textarea",{value:m,onChange:f=>p(f.target.value),placeholder:c("accessibilityAI.pasteHtmlCodeToAnalyze","Paste HTML code to analyze..."),className:"nice-a11y-ai__input",rows:8,disabled:j}),e.jsxs("div",{className:"nice-a11y-ai__actions",children:[e.jsx("button",{type:"button",onClick:b,disabled:j||!m.trim(),children:j?e.jsx("span",{className:"nice-a11y-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"search",size:14})," ",c("accessibilityAI.analyze","Analyze")]})}),e.jsxs("button",{type:"button",onClick:_,disabled:j||!m.trim(),children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",c("accessibilityAI.autoFix","Auto-Fix")]})]})]}),y&&e.jsxs("div",{className:"nice-a11y-ai__audit",children:[e.jsxs("div",{className:"nice-a11y-ai__audit-header",children:[e.jsxs("div",{className:"nice-a11y-ai__score",children:[e.jsx("span",{className:"nice-a11y-ai__score-value",children:y.score}),e.jsx("span",{className:"nice-a11y-ai__score-label",children:c("accessibilityAI.score","Score")})]}),e.jsxs("div",{className:"nice-a11y-ai__summary",children:[e.jsx("span",{className:"critical",children:c("accessibilityAI.critical","{critical} Critical").replace("{critical}",String(y.summary.critical))}),e.jsx("span",{className:"serious",children:c("accessibilityAI.serious","{serious} Serious").replace("{serious}",String(y.summary.serious))}),e.jsx("span",{className:"moderate",children:c("accessibilityAI.moderate","{moderate} Moderate").replace("{moderate}",String(y.summary.moderate))}),e.jsx("span",{className:"minor",children:c("accessibilityAI.minor","{minor} Minor").replace("{minor}",String(y.summary.minor))})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:y.issues.map(f=>o?o(f):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:_e[f.severity].bg,borderLeftColor:_e[f.severity].color},children:[e.jsxs("div",{className:"nice-a11y-ai__issue-header",children:[e.jsx("span",{className:"nice-a11y-ai__issue-icon",children:e.jsx(T.NiceIcon,{name:_e[f.severity].icon,size:16})}),e.jsx("span",{className:"nice-a11y-ai__issue-title",children:f.title}),e.jsx("span",{className:"nice-a11y-ai__issue-wcag",children:c("accessibilityAI.wcag","WCAG {wcagCriteria} ({wcagLevel})").replace("{wcagCriteria}",String(f.wcagCriteria)).replace("{wcagLevel}",String(f.wcagLevel))})]}),e.jsx("p",{className:"nice-a11y-ai__issue-desc",children:f.description}),f.element&&e.jsx("code",{className:"nice-a11y-ai__issue-element",children:f.element}),e.jsxs("div",{className:"nice-a11y-ai__issue-suggestion",children:[e.jsx("strong",{children:"Fix:"})," ",f.suggestion]}),f.codeExample&&e.jsx("pre",{className:"nice-a11y-ai__issue-example",children:f.codeExample})]},f.id))}),y.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:c("accessibilityAI.generalRecommendations","General Recommendations")}),e.jsx("ul",{children:y.recommendations.map((f,k)=>e.jsx("li",{children:f},k))})]})]}),e.jsx("style",{children:`
|
|
2996
2996
|
.nice-a11y-ai {
|
|
2997
2997
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
2998
2998
|
}
|
|
@@ -3291,14 +3291,16 @@ ${l}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:y.message)==nu
|
|
|
3291
3291
|
margin-bottom: var(--nice-space-1-5, 6px);
|
|
3292
3292
|
font-size: 14px;
|
|
3293
3293
|
}
|
|
3294
|
-
`})]}):e.jsx("div",{className:`nice-a11y-ai nice-a11y-ai--disabled ${n||""}`,style:s,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}const _e=[{name:"home",category:"navigation",keywords:["home","house","start","main"],svgPath:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"},{name:"menu",category:"navigation",keywords:["menu","hamburger","nav","bars"],svgPath:"M4 6h16M4 12h16M4 18h16"},{name:"arrow-left",category:"navigation",keywords:["back","previous","left","arrow"],svgPath:"M10 19l-7-7m0 0l7-7m-7 7h18"},{name:"arrow-right",category:"navigation",keywords:["next","forward","right","arrow"],svgPath:"M14 5l7 7m0 0l-7 7m7-7H3"},{name:"chevron-down",category:"navigation",keywords:["expand","dropdown","down","chevron"],svgPath:"M19 9l-7 7-7-7"},{name:"chevron-up",category:"navigation",keywords:["collapse","up","chevron"],svgPath:"M5 15l7-7 7 7"},{name:"plus",category:"action",keywords:["add","create","new","plus"],svgPath:"M12 4v16m8-8H4"},{name:"minus",category:"action",keywords:["remove","subtract","minus"],svgPath:"M20 12H4"},{name:"x",category:"action",keywords:["close","cancel","delete","remove","x"],svgPath:"M6 18L18 6M6 6l12 12"},{name:"check",category:"action",keywords:["done","complete","success","check","tick"],svgPath:"M5 13l4 4L19 7"},{name:"edit",category:"action",keywords:["edit","modify","pencil","write"],svgPath:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"},{name:"trash",category:"action",keywords:["delete","remove","trash","bin"],svgPath:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"},{name:"search",category:"action",keywords:["search","find","magnify","lookup"],svgPath:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"},{name:"filter",category:"action",keywords:["filter","sort","funnel"],svgPath:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"},{name:"download",category:"action",keywords:["download","save","export"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"},{name:"upload",category:"action",keywords:["upload","import","send"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"},{name:"refresh",category:"action",keywords:["refresh","reload","sync"],svgPath:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"},{name:"copy",category:"action",keywords:["copy","duplicate","clone"],svgPath:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"mail",category:"communication",keywords:["email","mail","message","envelope"],svgPath:"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"},{name:"phone",category:"communication",keywords:["phone","call","telephone","contact"],svgPath:"M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"},{name:"chat",category:"communication",keywords:["chat","message","comment","bubble"],svgPath:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"},{name:"bell",category:"notification",keywords:["notification","bell","alert","alarm"],svgPath:"M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"},{name:"file",category:"file",keywords:["file","document","page"],svgPath:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"},{name:"folder",category:"file",keywords:["folder","directory","category"],svgPath:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"},{name:"image",category:"image",keywords:["image","photo","picture","gallery"],svgPath:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"video",category:"av",keywords:["video","movie","film","camera"],svgPath:"M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"user",category:"social",keywords:["user","person","account","profile"],svgPath:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"},{name:"users",category:"social",keywords:["users","group","team","people"],svgPath:"M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"},{name:"settings",category:"action",keywords:["settings","config","gear","cog","preferences"],svgPath:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z"},{name:"calendar",category:"business",keywords:["calendar","date","schedule","event"],svgPath:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"clock",category:"business",keywords:["time","clock","schedule","hour"],svgPath:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"credit-card",category:"finance",keywords:["payment","card","credit","money"],svgPath:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"},{name:"chart",category:"business",keywords:["chart","graph","analytics","statistics"],svgPath:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"},{name:"lock",category:"security",keywords:["lock","secure","private","password"],svgPath:"M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"},{name:"unlock",category:"security",keywords:["unlock","open","access"],svgPath:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"},{name:"shield",category:"security",keywords:["shield","security","protect","safe"],svgPath:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"},{name:"eye",category:"action",keywords:["view","show","visible","eye","visibility"],svgPath:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"},{name:"eye-off",category:"action",keywords:["hide","invisible","hidden","eye-off"],svgPath:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"},{name:"info",category:"alert",keywords:["info","information","help","about"],svgPath:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"warning",category:"alert",keywords:["warning","caution","alert","attention"],svgPath:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"},{name:"error",category:"alert",keywords:["error","danger","fail","problem"],svgPath:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"success",category:"alert",keywords:["success","done","complete","check-circle"],svgPath:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"star",category:"action",keywords:["star","favorite","bookmark","rating"],svgPath:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"},{name:"heart",category:"social",keywords:["heart","love","like","favorite"],svgPath:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"},{name:"share",category:"social",keywords:["share","send","forward"],svgPath:"M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"},{name:"link",category:"action",keywords:["link","url","chain","hyperlink"],svgPath:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"},{name:"external-link",category:"action",keywords:["external","open","new-window"],svgPath:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"}];function Ta(i={}){const{config:a,defaultLibrary:t="lucide",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:o}=i,c=Z(),[h,p]=d.useState(!1),[m,b]=d.useState(null),w=d.useRef(null),k=a||(c==null?void 0:c.config),M=d.useCallback(S=>{const f=S.toLowerCase(),j=f.split(/\s+/);return _e.map(g=>{let x=0;return g.name===f?x+=100:g.name.includes(f)&&(x+=50),j.forEach(v=>{g.keywords.forEach(T=>{T===v?x+=30:(T.includes(v)||v.includes(T))&&(x+=15)})}),g.category===f&&(x+=20),{id:`icon_${g.name}`,name:g.name,displayName:g.name.replace(/-/g," ").replace(/\b\w/g,v=>v.toUpperCase()),category:g.category,style:r,library:t,relevanceScore:x,keywords:g.keywords,svgPath:g.svgPath}}).filter(g=>g.relevanceScore>0).sort((g,x)=>x.relevanceScore-g.relevanceScore).slice(0,n)},[t,r,n]),C=d.useCallback(async(S,f)=>{var x,v,T,I;const j=performance.now(),g=M(S);if(!k){const N={query:S,suggestions:g,latencyMs:performance.now()-j};return b(N),s==null||s(N),N}p(!0),(x=w.current)==null||x.abort(),w.current=new AbortController;try{const N=K(k),P=f?`
|
|
3294
|
+
`})]}):e.jsx("div",{className:`nice-a11y-ai nice-a11y-ai--disabled ${n||""}`,style:s,children:e.jsx("p",{children:c("accessibilityAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}const Re=[{name:"home",category:"navigation",keywords:["home","house","start","main"]},{name:"menu",category:"navigation",keywords:["menu","hamburger","nav","bars"]},{name:"arrow-left",category:"navigation",keywords:["back","previous","left","arrow"]},{name:"arrow-right",category:"navigation",keywords:["next","forward","right","arrow"]},{name:"chevron-down",category:"navigation",keywords:["expand","dropdown","down","chevron"]},{name:"chevron-up",category:"navigation",keywords:["collapse","up","chevron"]},{name:"plus",category:"action",keywords:["add","create","new","plus"]},{name:"minus",category:"action",keywords:["remove","subtract","minus"]},{name:"close",category:"action",keywords:["close","cancel","delete","remove","x"]},{name:"check",category:"action",keywords:["done","complete","success","check","tick"]},{name:"edit",category:"action",keywords:["edit","modify","pencil","write"]},{name:"trash",category:"action",keywords:["delete","remove","trash","bin"]},{name:"search",category:"action",keywords:["search","find","magnify","lookup"]},{name:"filter",category:"action",keywords:["filter","sort","funnel"]},{name:"download",category:"action",keywords:["download","save","export"]},{name:"upload",category:"action",keywords:["upload","import","send"]},{name:"refresh",category:"action",keywords:["refresh","reload","sync"]},{name:"copy",category:"action",keywords:["copy","duplicate","clone"]},{name:"mail",category:"communication",keywords:["email","mail","message","envelope"]},{name:"phone",category:"communication",keywords:["phone","call","telephone","contact"]},{name:"message",category:"communication",keywords:["chat","message","comment","bubble"]},{name:"bell",category:"notification",keywords:["notification","bell","alert","alarm"]},{name:"file",category:"file",keywords:["file","document","page"]},{name:"folder",category:"file",keywords:["folder","directory","category"]},{name:"image",category:"image",keywords:["image","photo","picture","gallery"]},{name:"video",category:"av",keywords:["video","movie","film","camera"]},{name:"user",category:"social",keywords:["user","person","account","profile"]},{name:"users",category:"social",keywords:["users","group","team","people"]},{name:"settings",category:"action",keywords:["settings","config","gear","cog","preferences"]},{name:"calendar",category:"business",keywords:["calendar","date","schedule","event"]},{name:"clock",category:"business",keywords:["time","clock","schedule","hour"]},{name:"card",category:"finance",keywords:["payment","card","credit","money","credit-card"]},{name:"bar-chart",category:"business",keywords:["chart","graph","analytics","statistics"]},{name:"lock",category:"security",keywords:["lock","secure","private","password"]},{name:"unlock",category:"security",keywords:["unlock","open","access"]},{name:"shield",category:"security",keywords:["shield","security","protect","safe"]},{name:"eye",category:"action",keywords:["view","show","visible","eye","visibility"]},{name:"eye-off",category:"action",keywords:["hide","invisible","hidden","eye-off"]},{name:"info",category:"alert",keywords:["info","information","help","about"]},{name:"warning",category:"alert",keywords:["warning","caution","alert","attention"]},{name:"error",category:"alert",keywords:["error","danger","fail","problem"]},{name:"success",category:"alert",keywords:["success","done","complete","check-circle"]},{name:"star",category:"action",keywords:["star","favorite","bookmark","rating"]},{name:"heart",category:"social",keywords:["heart","love","like","favorite"]},{name:"send",category:"social",keywords:["share","send","forward"]},{name:"link",category:"action",keywords:["link","url","chain","hyperlink"]},{name:"external-link",category:"action",keywords:["external","open","new-window"]}];let we=null,He=null;function Nt(){if(!we){const t=new Map(Re.map(a=>[a.name,a]));we=T.NICE_BUILTIN_ICONS.map(a=>t.get(a)??{name:a,category:"content",keywords:a.split("-")})}return we}function St(t){return He??(He=new Set(T.NICE_BUILTIN_ICONS)),He.has(t)}function za(t={}){const{config:a,defaultLibrary:i="nice",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:o}=t,c=ee(),[m,p]=l.useState(!1),[u,v]=l.useState(null),w=l.useRef(null),A=a||(c==null?void 0:c.config),R=l.useCallback(y=>{const I=y.toLowerCase(),b=I.split(/\s+/);return Nt().map(h=>{let _=0;return h.name===I?_+=100:h.name.includes(I)&&(_+=50),b.forEach(f=>{h.keywords.forEach(k=>{k===f?_+=30:k.length>=3&&f.length>=3&&(k.includes(f)||f.includes(k))&&(_+=15)})}),h.category===I&&(_+=20),{id:`icon_${h.name}`,name:h.name,displayName:h.name.replace(/-/g," ").replace(/\b\w/g,f=>f.toUpperCase()),category:h.category,style:r,library:i,relevanceScore:_,keywords:h.keywords}}).filter(h=>h.relevanceScore>0).sort((h,_)=>_.relevanceScore-h.relevanceScore).slice(0,n)},[i,r,n]),M=l.useCallback(async(y,I)=>{var _,f,k,S;const b=performance.now(),h=R(y);if(!A){const N={query:y,suggestions:h,latencyMs:performance.now()-b};return v(N),s==null||s(N),N}p(!0),(_=w.current)==null||_.abort(),w.current=new AbortController;try{const N=V(A),$=I?`
|
|
3295
3295
|
Context:
|
|
3296
|
-
- Component type: ${
|
|
3297
|
-
- Purpose: ${
|
|
3298
|
-
- Related icons: ${((
|
|
3299
|
-
- Theme: ${
|
|
3300
|
-
- Preferred style: ${
|
|
3301
|
-
|
|
3296
|
+
- Component type: ${I.componentType||"any"}
|
|
3297
|
+
- Purpose: ${I.purpose||"general"}
|
|
3298
|
+
- Related icons: ${((f=I.relatedIcons)==null?void 0:f.join(", "))||"none"}
|
|
3299
|
+
- Theme: ${I.theme||"light"}
|
|
3300
|
+
- Preferred style: ${I.preferredStyle||r}`:"",F=(((S=(k=(await N.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
|
|
3301
|
+
Choose ONLY from this icon set (NiceIcon names), and use the names exactly as written:
|
|
3302
|
+
${T.NICE_BUILTIN_ICONS.join(", ")}
|
|
3303
|
+
|
|
3302
3304
|
Return JSON array of 5-10 icon suggestions:
|
|
3303
3305
|
[{
|
|
3304
3306
|
"name": "icon-name",
|
|
@@ -3309,7 +3311,7 @@ Return JSON array of 5-10 icon suggestions:
|
|
|
3309
3311
|
"usage": "Brief usage description"
|
|
3310
3312
|
}]
|
|
3311
3313
|
|
|
3312
|
-
Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${
|
|
3314
|
+
Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${y}"${$}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:k.message)==null?void 0:S.content)||"").match(/\[[\s\S]*\]/);let U=[];if(F)try{U=JSON.parse(F[0]).filter(x=>typeof x.name=="string"&&St(x.name)).map((x,B)=>({id:x.id||`ai_icon_${B}`,name:x.name,displayName:x.displayName||x.name,category:x.category||"action",style:(I==null?void 0:I.preferredStyle)||r,library:i,relevanceScore:x.relevanceScore||50,keywords:x.keywords||[],usage:x.usage}))}catch{}const H=Ct(h,U,n),X={query:y,suggestions:H,latencyMs:performance.now()-b};return v(X),s==null||s(X),X}catch(N){const $=N instanceof Error?N.message:"Suggestion failed",E={query:y,suggestions:h,latencyMs:performance.now()-b,error:$};return v(E),o==null||o($),E}finally{p(!1)}},[A,i,r,n,R,s,o]),P=l.useCallback(y=>Re.filter(I=>I.category===y).map(I=>({id:`icon_${I.name}`,name:I.name,displayName:I.name.replace(/-/g," ").replace(/\b\w/g,b=>b.toUpperCase()),category:I.category,style:r,library:i,relevanceScore:100,keywords:I.keywords})),[i,r]),g=l.useMemo(()=>{const y=new Set;return Re.forEach(I=>y.add(I.category)),Array.from(y)},[]),d=l.useCallback(()=>{v(null)},[]),j=l.useCallback(()=>{var y;(y=w.current)==null||y.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var y;(y=w.current)==null||y.abort()},[]),{suggestIcons:M,localSearch:R,getByCategory:P,categories:g,loading:m,lastResult:u,clearResults:d,abort:j,isConfigured:!!A}}function Ct(t,a,i){const r=new Set,n=[];for(const s of t)r.has(s.name)||(r.add(s.name),n.push(s));for(const s of a)!r.has(s.name)&&n.length<i&&(r.add(s.name),n.push(s));return n.slice(0,i)}function It({config:t,defaultLibrary:a="nice",defaultStyle:i="outline",maxSuggestions:r=10,onSelect:n,showCategories:s=!0,showPreview:o=!0,className:c,style:m}){const{t:p}=T.useNiceTranslation(),u=S=>p(`iconSuggestor.category.${S}`,S.charAt(0).toUpperCase()+S.slice(1)),[v,w]=l.useState(""),[A,R]=l.useState(null),[M,P]=l.useState(null),{suggestIcons:g,getByCategory:d,categories:j,loading:y,lastResult:I}=za({config:t,defaultLibrary:a,defaultStyle:i,maxSuggestions:r}),b=async()=>{v.trim()&&(R(null),await g(v))},h=S=>{S.key==="Enter"&&b()},_=S=>{A===S?R(null):(R(S),w(""))},f=S=>{P(S),n==null||n(S)},k=A?d(A):(I==null?void 0:I.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:v,onChange:S=>w(S.target.value),onKeyDown:h,placeholder:p("iconSuggestor.placeholder","Search icons... (e.g., 'save', 'notification', 'user profile')"),"aria-label":p("iconSuggestor.query","Icon search"),className:"nice-icon-ai__input",disabled:y}),e.jsx("button",{type:"button",onClick:b,className:"nice-icon-ai__search-btn",disabled:y||!v.trim(),"aria-label":p("iconSuggestor.search","Search icons"),children:y?e.jsx("span",{className:"nice-icon-ai__spinner"}):e.jsx(T.NiceIcon,{name:"search",size:16})})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:j.map(S=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${A===S?"nice-icon-ai__category--selected":""}`,onClick:()=>_(S),children:u(S)},S))}),k.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:k.map(S=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${(M==null?void 0:M.id)===S.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>f(S),title:S.displayName,children:[e.jsx(Ke,{icon:S}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:S.displayName})]},S.id))}),o&&M&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(Ke,{icon:M,size:64})}),e.jsxs("div",{className:"nice-icon-ai__preview-info",children:[e.jsx("div",{className:"nice-icon-ai__preview-name",children:M.displayName}),e.jsxs("div",{className:"nice-icon-ai__preview-details",children:[e.jsx("span",{children:p("iconSuggestor.categoryLabel","Category: {category}").replace("{category}",u(M.category))}),e.jsx("code",{className:"nice-icon-ai__preview-code",children:Ye(M)})]}),e.jsx("div",{className:"nice-icon-ai__preview-keywords",children:M.keywords.map(S=>e.jsx("span",{className:"nice-icon-ai__keyword",children:S},S))}),M.usage&&e.jsx("div",{className:"nice-icon-ai__preview-usage",children:M.usage}),e.jsxs("div",{className:"nice-icon-ai__preview-actions",children:[e.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(M),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",p("iconSuggestor.useIcon","Use Icon")]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(M.name)},children:[e.jsx(T.NiceIcon,{name:"clipboard",size:14})," ",p("iconSuggestor.copyName","Copy Name")]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(Ye(M))},children:[e.jsx(T.NiceIcon,{name:"code",size:14})," ",p("iconSuggestor.copyJsx","Copy JSX")]})]})]})]}),e.jsx("style",{children:`
|
|
3313
3315
|
.nice-icon-ai {
|
|
3314
3316
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
3315
3317
|
}
|
|
@@ -3462,12 +3464,18 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
|
|
|
3462
3464
|
|
|
3463
3465
|
.nice-icon-ai__preview-details {
|
|
3464
3466
|
display: flex;
|
|
3467
|
+
flex-wrap: wrap;
|
|
3465
3468
|
gap: var(--nice-space-4, 16px);
|
|
3466
3469
|
font-size: 13px;
|
|
3467
3470
|
color: var(--nice-text-muted, #666);
|
|
3468
3471
|
margin-bottom: var(--nice-space-3, 12px);
|
|
3469
3472
|
}
|
|
3470
3473
|
|
|
3474
|
+
.nice-icon-ai__preview-code {
|
|
3475
|
+
font-family: var(--nice-font-mono, ui-monospace, monospace);
|
|
3476
|
+
color: var(--nice-text-primary);
|
|
3477
|
+
}
|
|
3478
|
+
|
|
3471
3479
|
.nice-icon-ai__preview-keywords {
|
|
3472
3480
|
display: flex;
|
|
3473
3481
|
flex-wrap: wrap;
|
|
@@ -3510,4 +3518,4 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
|
|
|
3510
3518
|
color: white;
|
|
3511
3519
|
border: none;
|
|
3512
3520
|
}
|
|
3513
|
-
`})]})}function
|
|
3521
|
+
`})]})}function Ke({icon:t,size:a=32}){return e.jsx(T.NiceIcon,{name:t.name,size:a})}function Ye(t){return`<NiceIcon name="${t.name}" />`}exports.ACCESSIBILITY_CHECKER_TEMPLATE=Se;exports.AnthropicProvider=pa;exports.AzureOpenAIProvider=ga;exports.CHART_CONFIG_TEMPLATE=ue;exports.CODE_COMPLETION_TEMPLATE=me;exports.CostTracker=ba;exports.DATA_GRID_FILTER_TEMPLATE=oe;exports.DATA_GRID_SORT_TEMPLATE=le;exports.FORM_BUILDER_TEMPLATE=de;exports.GroqProvider=fa;exports.InMemoryCostStorage=Oe;exports.LocalStorageCostStorage=xa;exports.NiceAIHintBubble=ea;exports.NiceAIProvider=$a;exports.NiceAccessibilityAI=kt;exports.NiceChartAI=qi;exports.NiceCodeEditorAI=Vi;exports.NiceDataGridAI=Pi;exports.NiceDataLabeler=ki;exports.NiceFormBuilderAI=Ei;exports.NiceIconSuggestorAI=It;exports.NiceLayoutAI=yt;exports.NiceMLStudio=_i;exports.NiceModelInference=Si;exports.NiceReportBuilderAI=lt;exports.NiceThemeGeneratorAI=gt;exports.NiceWorkflowDesignerAI=at;exports.OllamaProvider=ha;exports.OpenAIProvider=ke;exports.PROMPT_TEMPLATES=xe;exports.REPORT_LAYOUT_TEMPLATE=ge;exports.RateLimiter=Ve;exports.ResilientLLMClient=ya;exports.SUMMARIZE_DATA_TEMPLATE=Ie;exports.THEME_GENERATOR_TEMPLATE=Ne;exports.TRANSLATION_TEMPLATE=Ce;exports.WORKFLOW_GENERATOR_TEMPLATE=pe;exports.build3DSceneContext=sa;exports.buildAudioContext=na;exports.buildChartContext=Ba;exports.buildCodeEditorContext=ta;exports.buildColorPickerContext=Pe;exports.buildDataGridContext=Da;exports.buildDatePickerContext=$e;exports.buildDiagramLayoutContext=da;exports.buildFormFillContext=aa;exports.buildGameEngineContext=la;exports.buildGraphicsContext=ca;exports.buildHtmlEditorContext=ra;exports.buildIconSearchContext=oa;exports.buildNumberInputContext=ze;exports.buildPresentationGenerateContext=ua;exports.buildSelectContext=Me;exports.buildSlideDesignContext=ma;exports.buildTextInputContext=Le;exports.buildValidationContext=ia;exports.colorControlContext=li;exports.compileTemplate=ie;exports.createLLMProvider=ae;exports.createProviderFromConfig=V;exports.createResilientClient=va;exports.createResilientClientWithDefaults=Li;exports.dateControlContext=oi;exports.getTemplate=Ci;exports.getTemplatesByCategory=Ii;exports.listTemplates=Ai;exports.numberControlContext=si;exports.parseJSONResponse=Ze;exports.parseSSEStream=Qe;exports.selectControlContext=ci;exports.textControlContext=ni;exports.useAI3DHint=Xa;exports.useAIAudioHint=Va;exports.useAICodeHint=Ka;exports.useAIColorHint=Ua;exports.useAIContext=ee;exports.useAIDateHint=Ga;exports.useAIDiagramLayout=ai;exports.useAIFormFill=Ha;exports.useAIGraphicsHint=Qa;exports.useAIHtmlHint=Ya;exports.useAIIconSearch=Za;exports.useAINpcHint=ei;exports.useAINumberHint=Ja;exports.useAIPresentationGenerate=ii;exports.useAISelectHint=qa;exports.useAISlideDesign=ti;exports.useAITextHint=Fa;exports.useAIValidation=Wa;exports.useAccessibilityAI=La;exports.useChartAI=ja;exports.useCodeEditorAI=ka;exports.useCostTracker=Ti;exports.useDataGridAI=_a;exports.useFormBuilderAI=wa;exports.useIconSuggestorAI=za;exports.useLayoutAI=Ta;exports.useNiceAIHint=Z;exports.useReportBuilderAI=Ca;exports.useThemeGeneratorAI=Aa;exports.useWorkflowDesignerAI=Na;exports.withAIHint=ri;
|