@nice2dev/ui-ai 1.1.7 → 1.1.9
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 +53 -0
- package/dist/index.cjs +212 -143
- package/dist/index.mjs +2633 -2478
- package/dist/llm-providers.d.ts +7 -1
- package/dist/ui-ai.css +1 -1
- package/package.json +3 -3
- package/dist/NiceAIHintBubble.d.ts.map +0 -1
- package/dist/NiceAIProvider.d.ts.map +0 -1
- package/dist/NiceAccessibilityAI.d.ts.map +0 -1
- package/dist/NiceChartAI.d.ts.map +0 -1
- package/dist/NiceCodeEditorAI.d.ts.map +0 -1
- package/dist/NiceDataGridAI.d.ts.map +0 -1
- package/dist/NiceDataLabeler.d.ts.map +0 -1
- package/dist/NiceFormBuilderAI.d.ts.map +0 -1
- package/dist/NiceIconSuggestorAI.d.ts.map +0 -1
- package/dist/NiceLayoutAI.d.ts.map +0 -1
- package/dist/NiceMLStudio.d.ts.map +0 -1
- package/dist/NiceModelInference.d.ts.map +0 -1
- package/dist/NiceReportBuilderAI.d.ts.map +0 -1
- package/dist/NiceThemeGeneratorAI.d.ts.map +0 -1
- package/dist/NiceWorkflowDesignerAI.d.ts.map +0 -1
- package/dist/cost-tracker.d.ts.map +0 -1
- package/dist/fallback-strategies.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/integrations.d.ts.map +0 -1
- package/dist/llm-providers.d.ts.map +0 -1
- package/dist/ml-types.d.ts.map +0 -1
- package/dist/prompt-templates.d.ts.map +0 -1
- package/dist/rateLimiter.d.ts.map +0 -1
- package/dist/streaming.d.ts.map +0 -1
- package/dist/style.css +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/useNiceAIHint.d.ts.map +0 -1
- package/dist/wrappers.d.ts.map +0 -1
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"),d=require("react"),L=require("@nice2dev/ui-core"),
|
|
2
|
-
`);n=I.pop()??"";for(const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),d=require("react"),L=require("@nice2dev/ui-core"),Ca=require("@nice2dev/ui");class Ue{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 qe=d.createContext(null);function Sa({config:t,rateLimits:a,enabled:i=!0,onRateLimitWarning:r,children:n}){const s=d.useRef(null);s.current||(s.current=new Ue(a,r));const c=d.useCallback(()=>s.current.getStatus(),[]),l=d.useMemo(()=>({config:t,enabled:i,rateLimiter:s.current,getRateLimitStatus:c}),[t,i,c]);return e.jsx(qe.Provider,{value:l,children:n})}function Z(){return d.useContext(qe)}async function*He(t,a){var s,c,l,p,f,g,y,w,S;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:z,value:k}=await i.read();if(z)break;n+=r.decode(k,{stream:!0});const I=n.split(`
|
|
2
|
+
`);n=I.pop()??"";for(const j of I){const o=j.trim();if(!(!o||o===":")){if(o.startsWith("data:")){const N=o.slice(5).trim();if(N==="[DONE]"){yield{token:"",done:!0};return}try{const _=JSON.parse(N),m=((p=(l=(c=_.choices)==null?void 0:c[0])==null?void 0:l.delta)==null?void 0:p.content)??"",v=((g=(f=_.choices)==null?void 0:f[0])==null?void 0:g.finish_reason)==="stop";(m||v)&&(yield{token:m,done:v,usage:_.usage})}catch{N&&(yield{token:N,done:!1})}continue}try{const N=JSON.parse(o),_=N.text??N.content??N.token??"";_&&(yield{token:_,done:!1})}catch{o&&(yield{token:o,done:!1})}}}}if(n.trim()){const z=n.trim();if(z.startsWith("data:")){const k=z.slice(5).trim();if(k&&k!=="[DONE]")try{const j=((S=(w=(y=JSON.parse(k).choices)==null?void 0:y[0])==null?void 0:w.delta)==null?void 0:S.content)??"";j&&(yield{token:j,done:!0})}catch{yield{token:k,done:!0}}}}}finally{i.releaseLock()}}async function We(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 ne=new Map;function Pe(t,a){const i=a?{...t,fieldValue:void 0,formContext:void 0}:t;return JSON.stringify(i)}function Ta(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 c=typeof t.fieldValue=="string"?t.fieldValue:JSON.stringify(t.fieldValue);n.push(`Current value: ${c}`)}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 i.push({role:"user",content:s}),i}function X(t={},a={}){t=t??{},a=a??{};const{debounceMs:i=500,disabled:r=!1}=a,n=
|
|
5
|
-
Parse this description and return suggested values for each field as JSON: { ${a.map(i=>`"${i.label}": "value"`).join(", ")} }`}}function
|
|
4
|
+
`)}`:"Provide a helpful suggestion.";return i.push({role:"user",content:s}),i}function X(t={},a={}){t=t??{},a=a??{};const{debounceMs:i=500,disabled:r=!1}=a,n=Z(),[s,c]=d.useState(""),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState(!1),S=d.useRef(null),z=d.useRef(0),k=d.useCallback(async()=>{var h,$,D;if(!n||!n.enabled||r)return;const{config:o,rateLimiter:N}=n;if(!N.recordRequest()){g("Rate limit exceeded. Please wait before requesting another hint.");return}const _=Pe(t,o.privacyMode??!1),m=ne.get(_);if(m){c(m),p(!1),g(null),w(!1);return}(h=S.current)==null||h.abort();const v=new AbortController;S.current=v,p(!0),g(null),c(""),w(!1);const x=Ta(t,o),u=o.stream!==!1;try{const C={"Content-Type":"application/json",...o.headers};o.apiKey&&(C.Authorization=`Bearer ${o.apiKey}`);const A=JSON.stringify({model:o.model??"gpt-3.5-turbo",messages:x,temperature:o.temperature??.7,max_tokens:o.maxTokens??256,stream:u}),O=await fetch(o.endpoint,{method:"POST",headers:C,body:A,signal:v.signal});if(!O.ok){const B=await O.text().catch(()=>O.statusText);throw new Error(`AI request failed (${O.status}): ${B}`)}if(u){w(!0);let B="";for await(const b of He(O,v.signal))if(v.signal.aborted||(B+=b.token,c(B),($=b.usage)!=null&&$.completion_tokens&&N.recordTokens(b.usage.completion_tokens),b.done))break;if(B.length>0){const b=Math.ceil(B.length/4);N.recordTokens(b)}ne.set(_,B)}else{const B=await We(O);c(B.text),ne.set(_,B.text),(D=B.usage)!=null&&D.completion_tokens?N.recordTokens(B.usage.completion_tokens):N.recordTokens(Math.ceil(B.text.length/4))}}catch(C){if(C instanceof DOMException&&C.name==="AbortError")return;g(C instanceof Error?C.message:"AI hint request failed")}finally{v.signal.aborted||(p(!1),w(!1))}},[n,t,r]);d.useEffect(()=>{if(!n||!n.enabled||r)return;const o=setTimeout(k,i);return()=>clearTimeout(o)},[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,z.current]),d.useEffect(()=>()=>{var o;(o=S.current)==null||o.abort()},[]);const I=d.useCallback(()=>{var o;(o=S.current)==null||o.abort(),p(!1),w(!1)},[]),j=d.useCallback(()=>{if(n){const o=Pe(t,n.config.privacyMode??!1);ne.delete(o)}z.current+=1,k()},[n,t,k]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:l,error:f,streaming:y,abort:I,refresh:j,hint:s?{content:s}:null,fetchHint:async()=>{await k()}}}function Aa(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,c=Math.max(i,r,n,s);return c===i?"top":c===r?"bottom":c===s?"right":"left"}function Ra(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 Se=d.forwardRef(({context:t,position:a="auto",debounceMs:i=500,showOnHover:r=!1,triggerIcon:n,className:s,style:c},l)=>{var _;const p=Z(),[f,g]=d.useState(!1),[y,w]=d.useState(!1),S=d.useRef(null),z=d.useRef(null),k=X(t,{debounceMs:i,disabled:!y});d.useEffect(()=>{if(!f)return;const m=v=>{var u,h;const x=v.target;(u=S.current)!=null&&u.contains(x)||(h=z.current)!=null&&h.contains(x)||(g(!1),w(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[f]),d.useEffect(()=>{if(!f)return;const m=v=>{v.key==="Escape"&&(g(!1),w(!1),k.abort())};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[f,k]);const I=d.useCallback(m=>{if(m.stopPropagation(),r)return;const v=!f;g(v),w(v)},[f,r]),j=d.useCallback(()=>{r&&(g(!0),w(!0))},[r]),o=d.useCallback(()=>{r&&(g(!1),w(!1))},[r]);if(!p||!p.enabled)return null;const N=Aa(a,((_=S.current)==null?void 0:_.getBoundingClientRect())??null);return e.jsxs("span",{ref:l,className:s,style:{position:"relative",display:"inline-flex",...c},onMouseEnter:j,onMouseLeave:o,children:[e.jsx("button",{ref:S,type:"button",onClick:I,"aria-label":"AI hint","aria-expanded":f,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(L.NiceIcon,{name:"wand",size:16})}),f&&e.jsxs("div",{ref:z,role:"tooltip",className:"ntd-ai-popover",style:Ra(N),children:[k.loading&&!k.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:"Thinking..."})]}),k.text&&e.jsxs("div",{className:"ntd-ai-content",children:[k.text,k.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"}})]}),k.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:k.error}),k.text&&!k.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:()=>k.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(L.NiceIcon,{name:"refresh",size:12})," Refresh"]}),e.jsxs("button",{type:"button",onClick:()=>{var m;(m=navigator.clipboard)==null||m.writeText(k.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(L.NiceIcon,{name:"copy",size:12})," Copy"]})]})]})]})});Se.displayName="NiceAIHintBubble";function Te(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 Ae(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 Re(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 Ie(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 ze(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 Ia(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 za(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 Ge(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 Ve(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 Ma(t,a,i){const r=d.useMemo(()=>Te(t,a,i),[t,a,i==null?void 0:i.placeholder,i==null?void 0:i.maxLength,i==null?void 0:i.pattern]);return X(r,i)}function La(t,a,i){const r=d.useMemo(()=>Ae(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 X(r,i)}function Pa(t,a,i){const r=d.useMemo(()=>Re(t,a,i),[t,a,i==null?void 0:i.multiple]);return X(r,i)}function $a(t,a,i){const r=d.useMemo(()=>Ie(t,a,i),[t,a,i==null?void 0:i.min,i==null?void 0:i.max,i==null?void 0:i.disableWeekends]);return X(r,i)}function Oa(t,a,i){const r=d.useMemo(()=>ze(t,a,i),[t,a,i==null?void 0:i.industry]);return X(r,i)}function Ea(t,a,i,r,n){const s=d.useMemo(()=>r?Ve(t,a,i,r,n):{fieldLabel:t,fieldType:a},[t,a,i,r]);return X(s,{...n,disabled:!r||(n==null?void 0:n.disabled)})}function Da(t,a,i){const r=d.useMemo(()=>t?Ge(t,a):{fieldLabel:"Form"},[t,a]);return X(r,{...i,disabled:!t||(i==null?void 0:i.disabled)})}function Ke(t,a,i){const n=(a==null?void 0:a.split(`
|
|
6
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
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
|
|
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 Ea(t,a,i){const r=d.useMemo(()=>Ge(t,a,i),[t,a,i==null?void 0:i.cursorLine,i==null?void 0:i.cursorCol,i==null?void 0:i.framework]);return X(r,i)}function Da(t,a,i){const r=d.useMemo(()=>Ve(t,a,i),[t,a,i==null?void 0:i.mode,i==null?void 0:i.locale]);return X(r,i)}function Ba(t,a){const i=d.useMemo(()=>Ke(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 X(i,a)}function Fa(t,a){const i=d.useMemo(()=>Ye(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 X(i,a)}function Ja(t,a){const i=d.useMemo(()=>Xe(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 X(i,a)}function qa(t,a){const i=d.useMemo(()=>Qe(t,a),[t,a==null?void 0:a.limit,a==null?void 0:a.style]);return X(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function Ze(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(c=>c.node)}}}function Ua(t,a){const i=d.useMemo(()=>Ze(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 X(i,a)}function ea(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 }] }`},c=t.map(m=>{var g;return{id:m.id,type:m.type,label:(g=m.label)==null?void 0:g.slice(0,30),pos:[Math.round(m.x),Math.round(m.y)]}}),l=a.map(m=>({id:m.id,src:m.source,tgt:m.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:c,edges:l}),schema:{diagramType:n,mode:r,nodeCount:t.length,edgeCount:a.length,containerSize:i==null?void 0:i.containerSize},customPrompt:s[r]}}function Ha(t,a,i){const r=d.useMemo(()=>ea(t,a,i),[JSON.stringify(t),JSON.stringify(a),i==null?void 0:i.mode,i==null?void 0:i.diagramType]);return X(r,{...i,disabled:t.length===0||(i==null?void 0:i.disabled)})}function aa(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),c={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:c[i]}}function Wa(t,a){const i=d.useMemo(()=>aa(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 X(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function ia(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 Ga(t,a){const i=d.useMemo(()=>ia(t,a),[JSON.stringify(t),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return X(i,a)}function Va(t,a,i){const r=d.forwardRef((n,s)=>{const{aiEnabled:c=!0,aiPosition:l="right",aiPrompt:m,aiDebounceMs:g=500,aiShowOnHover:x=!1,aiTriggerIcon:w,...N}=n,S=d.useMemo(()=>{const R=a(N);return m&&(R.customPrompt=m),R},[N,m]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(t,{...N,ref:s}),c&&e.jsx(Ne,{context:S,position:l,debounceMs:g,showOnHover:x,triggerIcon:w})]})});return r.displayName=i??`withAIHint(${t.displayName??t.name??"Component"})`,r}function Ka(t){return Ce(t.label??"Text",t.value,{placeholder:t.placeholder,maxLength:t.maxLength})}function Ya(t){return Se(t.label??"Number",t.value,{min:t.min,max:t.max,step:t.step})}function Xa(t){return Te(t.label??"Select",t.value,{options:t.options,multiple:t.multiple})}function Qa(t){return Ae(t.label??"Date",t.value,{min:t.min,max:t.max})}function Za(t){return Re(t.label??"Color",t.value)}const ei={id:crypto.randomUUID(),name:"New ML Project",type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date},Pe={classification:[{id:"logistic-regression",name:"Logistic Regression"},{id:"random-forest",name:"Random Forest"},{id:"gradient-boosting",name:"Gradient Boosting"},{id:"svm",name:"Support Vector Machine"},{id:"neural-network",name:"Neural Network"},{id:"xgboost",name:"XGBoost"}],regression:[{id:"linear-regression",name:"Linear Regression"},{id:"ridge",name:"Ridge Regression"},{id:"lasso",name:"Lasso Regression"},{id:"random-forest-reg",name:"Random Forest"},{id:"gradient-boosting-reg",name:"Gradient Boosting"}],clustering:[{id:"kmeans",name:"K-Means"},{id:"dbscan",name:"DBSCAN"},{id:"hierarchical",name:"Hierarchical Clustering"}]},$e={classification:["accuracy","precision","recall","f1-score","auc-roc"],regression:["mse","rmse","mae","r2"],clustering:["silhouette","calinski-harabasz","davies-bouldin"]},ai=[{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"}],ii=({project:t,onProjectChange:a,onExperimentRun:i,onModelDeploy:r,className:n="",tutorial:s})=>{var B;const[c,l]=d.useState(t||ei),[m,g]=d.useState("data"),[x,w]=d.useState(null),[N,S]=d.useState(null),[R,j]=d.useState(null),[I,_]=d.useState(!1),[o,k]=d.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),y=d.useCallback(f=>{const z={...c,...f,updatedAt:new Date};l(z),a==null||a(z)},[c,a]),p=async f=>{for(const z of Array.from(f)){const U={id:crypto.randomUUID(),name:z.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:z.name},size:z.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(z.name.endsWith(".csv")){const P=(await z.text()).split(`
|
|
11
|
-
`),J=P[0].split(",").map(q=>q.trim());U.rowCount=P.length-1,U.columns=J.map(q=>({name:q,type:"text",nullable:!0,unique:0,missing:0})),U.splits=U.splits.map(q=>({...q,rowCount:Math.floor(U.rowCount*q.ratio)}))}y({datasets:[...c.datasets,U]})}},b=f=>{y({datasets:c.datasets.filter(z=>z.id!==f)}),x===f&&w(null)},v=async()=>{if(!o.algorithm||!x)return;const f={id:crypto.randomUUID(),name:`Experiment ${c.experiments.length+1}`,status:"pending",config:o,metrics:[],artifacts:[],logs:[]};if(y({experiments:[...c.experiments,f]}),_(!1),i){y({experiments:c.experiments.map(z=>z.id===f.id?{...z,status:"running",startedAt:new Date}:z)});try{await i(f);const z=($e[c.type]||$e.classification).map(U=>({name:U,value:Math.random()*.3+.7,split:"validation"}));y({experiments:c.experiments.map(U=>U.id===f.id?{...U,status:"completed",completedAt:new Date,metrics:z}:U)})}catch{y({experiments:c.experiments.map(z=>z.id===f.id?{...z,status:"failed"}:z)})}}},u=f=>{const z=c.experiments.find(H=>H.id===f);if(!z)return;const U={id:crypto.randomUUID(),name:`Model from ${z.name}`,version:"1.0.0",algorithm:z.config.algorithm,experimentId:f,status:"registered",metrics:z.metrics,size:Math.floor(Math.random()*100)*1024*1024,artifacts:[],deployments:[],createdAt:new Date};y({models:[...c.models,U]})},h=async f=>{const z=c.models.find(H=>H.id===f);if(!z||!r)return;const U=await r(z);y({models:c.models.map(H=>H.id===f?{...H,status:"production",deployments:[...H.deployments,U]}:H)})},$=f=>f<1024?`${f} B`:f<1024*1024?`${(f/1024).toFixed(1)} KB`:f<1024*1024*1024?`${(f/1024/1024).toFixed(1)} MB`:`${(f/1024/1024/1024).toFixed(1)} GB`,E=f=>{switch(f){case"completed":case"production":case"running":return"status-badge--success";case"pending":case"staging":return"status-badge--warning";case"failed":return"status-badge--error";default:return""}},C=e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:c.name,onChange:f=>y({name:f.target.value}),className:"project-name-input"}),e.jsxs("select",{value:c.type,onChange:f=>y({type:f.target.value}),className:"project-type-select",children:[e.jsx("option",{value:"classification",children:"Classification"}),e.jsx("option",{value:"regression",children:"Regression"}),e.jsx("option",{value:"clustering",children:"Clustering"}),e.jsx("option",{value:"object-detection",children:"Object Detection"}),e.jsx("option",{value:"nlp",children:"NLP"}),e.jsx("option",{value:"time-series",children:"Time Series"})]})]}),A=e.jsx("div",{className:"header__tabs",children:["data","experiments","models","deploy"].map(f=>e.jsx("button",{className:`tab-button ${m===f?"tab-button--active":""}`,onClick:()=>g(f),children:f.charAt(0).toUpperCase()+f.slice(1)},f))}),O=e.jsxs("div",{className:"ml-studio__content",children:[m==="data"&&e.jsxs("div",{className:"data-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Datasets"}),e.jsxs("label",{className:"upload-button",children:[e.jsx("input",{type:"file",multiple:!0,accept:".csv,.json,.parquet",onChange:f=>f.target.files&&p(f.target.files),hidden:!0}),e.jsx(L.NiceIcon,{name:"plus",size:14})," Upload Dataset"]})]}),e.jsx("div",{className:"datasets-grid",children:c.datasets.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("p",{children:"No datasets uploaded yet"}),e.jsx("p",{className:"hint",children:"Upload CSV, JSON, or Parquet files to get started"})]}):c.datasets.map(f=>e.jsxs("div",{className:`dataset-card ${x===f.id?"dataset-card--selected":""}`,onClick:()=>w(f.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"dataset-icon",children:e.jsx(L.NiceIcon,{name:"folder",size:16})}),e.jsx("h3",{children:f.name}),e.jsx("button",{className:"remove-button","aria-label":"Remove dataset",onClick:z=>{z.stopPropagation(),b(f.id)},children:e.jsx(L.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"card-stats",children:[e.jsxs("span",{children:[f.rowCount.toLocaleString()," rows"]}),e.jsxs("span",{children:[f.columns.length," columns"]}),e.jsx("span",{children:$(f.size)})]}),e.jsx("div",{className:"splits-bar",children:f.splits.map(z=>e.jsx("div",{className:`split split--${z.name}`,style:{width:`${z.ratio*100}%`},title:`${z.name}: ${(z.ratio*100).toFixed(0)}%`},z.name))})]},f.id))}),x&&e.jsx("div",{className:"dataset-details",children:(()=>{const f=c.datasets.find(z=>z.id===x);return f?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:"Columns"}),e.jsxs("table",{className:"columns-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Missing"}),e.jsx("th",{children:"Unique"})]})}),e.jsx("tbody",{children:f.columns.map(z=>e.jsxs("tr",{children:[e.jsx("td",{children:z.name}),e.jsx("td",{children:e.jsxs("select",{value:z.type,onChange:U=>{y({datasets:c.datasets.map(H=>H.id===f.id?{...H,columns:H.columns.map(P=>P.name===z.name?{...P,type:U.target.value}:P)}:H)})},children:[e.jsx("option",{value:"numeric",children:"Numeric"}),e.jsx("option",{value:"categorical",children:"Categorical"}),e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"datetime",children:"DateTime"}),e.jsx("option",{value:"boolean",children:"Boolean"})]})}),e.jsx("td",{children:z.missing}),e.jsx("td",{children:z.unique})]},z.name))})]})]}):null})()})]}),m==="experiments"&&e.jsxs("div",{className:"experiments-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Experiments"}),e.jsxs("button",{className:"primary-button",onClick:()=>_(!0),disabled:c.datasets.length===0,children:[e.jsx(L.NiceIcon,{name:"plus",size:14})," New Experiment"]})]}),I&&e.jsxs("div",{className:"new-experiment-form",children:[e.jsx("h3",{children:"Configure Experiment"}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Dataset",e.jsxs("select",{value:x||"",onChange:f=>w(f.target.value),children:[e.jsx("option",{value:"",children:"Select dataset..."}),c.datasets.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]})]}),e.jsxs("label",{children:["Algorithm",e.jsxs("select",{value:o.algorithm,onChange:f=>k({...o,algorithm:f.target.value}),children:[e.jsx("option",{value:"",children:"Select algorithm..."}),(Pe[c.type]||Pe.classification).map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]})]}),x&&e.jsxs("label",{children:["Target Column",e.jsxs("select",{value:o.targetColumn||"",onChange:f=>k({...o,targetColumn:f.target.value}),children:[e.jsx("option",{value:"",children:"Select target..."}),(B=c.datasets.find(f=>f.id===x))==null?void 0:B.columns.map(f=>e.jsx("option",{value:f.name,children:f.name},f.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>_(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",onClick:v,disabled:!o.algorithm||!x,children:"Run Experiment"})]})]}),e.jsx("div",{className:"experiments-list",children:c.experiments.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"flask",size:32})}),e.jsx("p",{children:"No experiments yet"}),e.jsx("p",{className:"hint",children:"Create an experiment to train and evaluate models"})]}):c.experiments.map(f=>e.jsxs("div",{className:`experiment-card ${N===f.id?"experiment-card--selected":""}`,onClick:()=>S(f.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:f.name}),e.jsx("span",{className:`status-badge ${E(f.status)}`,children:f.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",f.config.algorithm]}),f.duration&&e.jsxs("span",{children:["Duration: ",Math.round(f.duration),"s"]})]}),f.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:f.metrics.slice(0,3).map(z=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:z.name}),e.jsxs("span",{className:"metric-value",children:[(z.value*100).toFixed(1),"%"]})]},z.name))}),f.status==="completed"&&e.jsx("button",{className:"action-button",onClick:z=>{z.stopPropagation(),u(f.id)},children:"Register Model"})]},f.id))})]}),m==="models"&&e.jsxs("div",{className:"models-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:"Models"})}),e.jsx("div",{className:"models-list",children:c.models.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"wand",size:32})}),e.jsx("p",{children:"No models registered yet"}),e.jsx("p",{className:"hint",children:"Complete experiments and register models"})]}):c.models.map(f=>e.jsxs("div",{className:`model-card ${R===f.id?"model-card--selected":""}`,onClick:()=>j(f.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:f.name}),e.jsx("span",{className:`status-badge ${E(f.status)}`,children:f.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",f.algorithm]}),e.jsxs("span",{children:["Version: ",f.version]}),e.jsxs("span",{children:["Size: ",$(f.size)]})]}),f.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:f.metrics.slice(0,3).map(z=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:z.name}),e.jsxs("span",{className:"metric-value",children:[(z.value*100).toFixed(1),"%"]})]},z.name))}),e.jsxs("div",{className:"card-actions",children:[e.jsx("button",{className:"action-button",children:"Download"}),e.jsx("button",{className:"action-button action-button--primary",onClick:z=>{z.stopPropagation(),h(f.id)},disabled:f.status==="production",children:f.status==="production"?"Deployed":"Deploy"})]})]},f.id))})]}),m==="deploy"&&e.jsxs("div",{className:"deploy-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:"Deployments"})}),e.jsx("div",{className:"deployments-list",children:c.models.filter(f=>f.deployments.length>0).length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"rocket",size:32})}),e.jsx("p",{children:"No deployments yet"}),e.jsx("p",{className:"hint",children:"Deploy a model to create inference endpoints"})]}):c.models.filter(f=>f.deployments.length>0).flatMap(f=>f.deployments.map(z=>({model:f,deployment:z}))).map(({model:f,deployment:z})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:z.name}),e.jsx("span",{className:`status-badge ${E(z.status)}`,children:z.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Model: ",f.name]}),e.jsxs("span",{children:["Endpoint: ",z.endpoint]})]}),e.jsxs("div",{className:"resources-info",children:[e.jsxs("span",{children:["CPU: ",z.resources.cpu," cores"]}),e.jsxs("span",{children:["Memory: ",z.resources.memory," GB"]}),e.jsxs("span",{children:["Replicas: ",z.resources.replicas]})]})]},z.id))})]})]});return e.jsxs("div",{className:`nice-ml-studio ${n}`,style:{position:"relative"},children:[e.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:e.jsx(L.NiceTutorialButton,{steps:L.resolveTutorial(s,ai)})}),e.jsx(ka.NiceAppShell,{flush:!0,menubar:C,toolbar:A,children:O})]})},ti={id:crypto.randomUUID(),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},Oe=["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-accent-pink, #d946ef)","var(--nice-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)"],ri=({project:t,onProjectChange:a,onLabelSave:i,onExport:r,className:n=""})=>{var Z;const{t:s}=L.useNiceTranslation(),[c,l]=d.useState(t||ti),[m,g]=d.useState("label"),[x,w]=d.useState(0),[N,S]=d.useState(null),[R,j]=d.useState("select"),[I,_]=d.useState(!1),[o,k]=d.useState(null),[y,p]=d.useState(1),[b,v]=d.useState(!1),[u,h]=d.useState("all"),$=d.useRef(null),E=d.useRef(null),C=c.items[x];d.useEffect(()=>{t&&l(t)},[t]);const A=d.useCallback(T=>{const D={...c,...T};D.statistics={totalItems:D.items.length,labeled:D.items.filter(M=>M.status!=="pending").length,reviewed:D.items.filter(M=>M.status==="review"||M.status==="approved").length,approved:D.items.filter(M=>M.status==="approved").length,byClass:D.labelSchema.classes.map(M=>({classId:M.id,count:D.items.flatMap(F=>F.labels).filter(F=>F.classId===M.id).length}))},l(D),a==null||a(D)},[c,a]),O=()=>{const T={id:crypto.randomUUID(),name:`Class ${c.labelSchema.classes.length+1}`,color:Oe[c.labelSchema.classes.length%Oe.length],shortcut:String(c.labelSchema.classes.length+1)};A({labelSchema:{...c.labelSchema,classes:[...c.labelSchema.classes,T]}})},B=T=>{A({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.filter(D=>D.id!==T)},items:c.items.map(D=>({...D,labels:D.labels.filter(M=>M.classId!==T)}))})},f=(T,D)=>{A({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.map(M=>M.id===T?{...M,...D}:M)}})},z=(T,D)=>{if(!C)return;const M={id:crypto.randomUUID(),classId:T,type:c.type==="classification"?"class":c.type==="bounding-box"?"bbox":"class",data:D||{},createdBy:"current-user",createdAt:new Date},F={...C,labels:[...C.labels,M],status:"labeled"};A({items:c.items.map(K=>K.id===C.id?F:K)}),i==null||i(F)},U=T=>{if(!C)return;const D={...C,labels:C.labels.filter(M=>M.id!==T),status:C.labels.length<=1?"pending":"labeled"};A({items:c.items.map(M=>M.id===C.id?D:M)})},H=T=>{var K;if(R!=="bbox"||!N)return;const D=(K=$.current)==null?void 0:K.getBoundingClientRect();if(!D)return;const M=(T.clientX-D.left)/y,F=(T.clientY-D.top)/y;_(!0),k({x:M,y:F,width:0,height:0})},P=T=>{var K;if(!I||!o)return;const D=(K=$.current)==null?void 0:K.getBoundingClientRect();if(!D)return;const M=(T.clientX-D.left)/y,F=(T.clientY-D.top)/y;k({...o,width:M-o.x,height:F-o.y})},J=()=>{!I||!o||!N||(_(!1),Math.abs(o.width)>10&&Math.abs(o.height)>10&&z(N,{x:o.width<0?o.x+o.width:o.x,y:o.height<0?o.y+o.height:o.y,width:Math.abs(o.width),height:Math.abs(o.height)}),k(null))},q=T=>{const D=u==="all"?c.items:c.items.filter(F=>F.status===u),M=D.findIndex(F=>F.id===(C==null?void 0:C.id));if(T==="prev"&&M>0){const F=D[M-1];w(c.items.findIndex(K=>K.id===F.id))}else if(T==="next"&&M<D.length-1){const F=D[M+1];w(c.items.findIndex(K=>K.id===F.id))}},W=()=>{if(!C)return;const T={...C,status:"approved"};A({items:c.items.map(D=>D.id===C.id?T:D)}),q("next")},G=()=>{if(!C)return;const T={...C,status:"rejected"};A({items:c.items.map(D=>D.id===C.id?T:D)}),q("next")},Y=async T=>{r&&await r(T)};d.useEffect(()=>{const T=D=>{const M=D.key,F=c.labelSchema.classes.find(K=>K.shortcut===M);F&&(c.type==="classification"?(z(F.id),q("next")):S(F.id)),D.key==="ArrowLeft"||D.key==="a"?q("prev"):(D.key==="ArrowRight"||D.key==="d")&&q("next"),D.key==="Enter"?W():D.key==="Backspace"&&G()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[C,c.labelSchema.classes,c.type]);const ae=T=>{switch(T){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:c.name,onChange:T=>A({name:T.target.value}),className:"project-name-input"}),e.jsxs("div",{className:"progress-bar",children:[e.jsx("div",{className:"progress-fill",style:{width:`${c.statistics.labeled/Math.max(c.statistics.totalItems,1)*100}%`}}),e.jsxs("span",{className:"progress-text",children:[c.statistics.labeled," / ",c.statistics.totalItems," labeled"]})]})]}),e.jsx("div",{className:"header__tabs",children:["label","schema","review","export"].map(T=>e.jsx("button",{className:`tab-button ${m===T?"tab-button--active":""}`,onClick:()=>g(T),children:T.charAt(0).toUpperCase()+T.slice(1)},T))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>v(!b),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"labeler__content",children:[m==="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 ${R==="select"?"tool-button--active":""}`,onClick:()=>j("select"),children:[e.jsx(L.NiceIcon,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(c.type==="bounding-box"||c.type==="multi-label")&&e.jsxs("button",{className:`tool-button ${R==="bbox"?"tool-button--active":""}`,onClick:()=>j("bbox"),children:[e.jsx(L.NiceIcon,{name:"square",size:14})," Box"]}),c.type==="polygon"&&e.jsxs("button",{className:`tool-button ${R==="polygon"?"tool-button--active":""}`,onClick:()=>j("polygon"),children:[e.jsx(L.NiceIcon,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{onClick:()=>p(Math.max(.25,y-.25)),children:"-"}),e.jsxs("span",{children:[Math.round(y*100),"%"]}),e.jsx("button",{onClick:()=>p(Math.min(4,y+.25)),children:"+"})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsxs("button",{onClick:()=>q("prev"),disabled:x===0,children:[e.jsx(L.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[x+1," / ",c.items.length]}),e.jsxs("button",{onClick:()=>q("next"),disabled:x>=c.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx(L.NiceIcon,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:E,children:C?e.jsxs(e.Fragment,{children:[C.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:C.data.url,alt:s("dataLabeler.labelingItem","Labeling item"),className:"labeling-image",style:{transform:`scale(${y})`}}),e.jsx("canvas",{ref:$,className:"labeling-canvas",onMouseDown:H,onMouseMove:P,onMouseUp:J,onMouseLeave:J,style:{transform:`scale(${y})`,cursor:R==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${y})`},children:[C.labels.filter(T=>T.type==="bbox"&&T.data.x!==void 0).map(T=>{const D=c.labelSchema.classes.find(M=>M.id===T.classId);return e.jsxs("div",{className:"bbox-annotation",style:{left:T.data.x,top:T.data.y,width:T.data.width,height:T.data.height,borderColor:(D==null?void 0:D.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(D==null?void 0:D.color)||"var(--nice-danger, #ff0000)"},children:D==null?void 0:D.name}),e.jsx("button",{className:"bbox-remove",onClick:()=>U(T.id),children:"×"})]},T.id)}),o&&e.jsx("div",{className:"bbox-drawing",style:{left:o.width<0?o.x+o.width:o.x,top:o.height<0?o.y+o.height:o.y,width:Math.abs(o.width),height:Math.abs(o.height),borderColor:(Z=c.labelSchema.classes.find(T=>T.id===N))==null?void 0:Z.color}})]})]}),C.data.type==="text"&&e.jsx("div",{className:"text-labeling",children:e.jsx("p",{className:"text-content",children:C.data.text})})]}):e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.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:c.labelSchema.classes.map(T=>e.jsxs("button",{className:`class-button ${N===T.id?"class-button--active":""}`,style:{borderLeftColor:T.color},onClick:()=>{c.type==="classification"?(z(T.id),q("next")):S(T.id)},children:[e.jsx("span",{className:"class-color",style:{backgroundColor:T.color}}),e.jsx("span",{className:"class-name",children:T.name}),T.shortcut&&e.jsx("span",{className:"class-shortcut",children:T.shortcut})]},T.id))}),C&&C.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),C.labels.map(T=>{const D=c.labelSchema.classes.find(M=>M.id===T.classId);return e.jsxs("div",{className:"label-item",children:[e.jsx("span",{className:"label-color",style:{backgroundColor:D==null?void 0:D.color}}),e.jsx("span",{className:"label-name",children:D==null?void 0:D.name}),e.jsx("button",{"aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>U(T.id),children:e.jsx(L.NiceIcon,{name:"close",size:14})})]},T.id)})]}),m==="label"&&C&&e.jsxs("div",{className:"label-actions",children:[e.jsxs("button",{className:"approve-button",onClick:W,children:[e.jsx(L.NiceIcon,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"reject-button",onClick:G,children:[e.jsx(L.NiceIcon,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),m==="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:O,children:[e.jsx(L.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:c.type,onChange:T=>A({type:T.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:c.dataType,onChange:T=>A({dataType:T.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:c.labelSchema.classes.map((T,D)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:T.color,onChange:M=>f(T.id,{color:M.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:T.name,onChange:M=>f(T.id,{name:M.target.value}),className:"class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:T.shortcut||"",onChange:M=>f(T.id,{shortcut:M.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:()=>B(T.id),children:e.jsx(L.NiceIcon,{name:"trash",size:16})})]},T.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:c.guidelines||"",onChange:T=>A({guidelines:T.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),m==="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:u,onChange:T=>h(T.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:c.items.filter(T=>u==="all"||T.status===u).map((T,D)=>{var M;return e.jsxs("div",{className:`item-card ${x===c.items.indexOf(T)?"item-card--active":""}`,onClick:()=>{w(c.items.indexOf(T)),g("label")},children:[T.data.type==="image"&&e.jsx("img",{src:T.data.url,alt:`Item ${D+1}`,className:"item-thumbnail"}),T.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(M=T.data.text)==null?void 0:M.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:ae(T.status)}}),e.jsxs("span",{children:[T.labels.length," labels"]})]})]},T.id)})})]}),m==="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:c.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:c.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:c.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:c.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:()=>Y("coco"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.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:()=>Y("voc"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.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:()=>Y("yolo"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.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:()=>Y("csv"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.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:c.statistics.byClass.map(T=>{const D=c.labelSchema.classes.find(F=>F.id===T.classId),M=T.count/Math.max(c.statistics.labeled,1)*100;return e.jsxs("div",{className:"distribution-row",children:[e.jsx("span",{className:"class-name",style:{color:D==null?void 0:D.color},children:D==null?void 0:D.name}),e.jsx("div",{className:"bar-container",children:e.jsx("div",{className:"bar-fill",style:{width:`${M}%`,backgroundColor:D==null?void 0:D.color}})}),e.jsx("span",{className:"count",children:T.count})]},T.classId)})})]})]})]}),b&&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:()=>v(!1),children:e.jsx(L.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")})]}),c.labelSchema.classes.map(T=>T.shortcut&&e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:T.shortcut}),e.jsxs("span",{className:"description",children:["Label as ",T.name]})]},T.id))]})]})})]})},ni={id:crypto.randomUUID(),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[s,c]=d.useState(t||ni),[l,m]=d.useState("test"),[g,x]=d.useState("text"),[w,N]=d.useState(""),[S,R]=d.useState("{}"),[j,I]=d.useState(null),[_,o]=d.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[k,y]=d.useState(null),[p,b]=d.useState(!1),[v,u]=d.useState(null),[h,$]=d.useState([]),[E,C]=d.useState(null),A=d.useRef(null),O=P=>{var q;const J=(q=P.target.files)==null?void 0:q[0];if(J){const W=new FileReader;W.onload=G=>{var Y;I((Y=G.target)==null?void 0:Y.result)},W.readAsDataURL(J)}},B=async()=>{if(!a){u("No inference handler provided");return}b(!0),u(null),y(null);const P=[];switch(g){case"text":P.push({type:"text",data:w});break;case"image":j&&P.push({type:"image",data:j});break;case"json":try{P.push({type:"json",data:JSON.parse(S)})}catch{u("Invalid JSON input"),b(!1);return}break;case"tabular":try{P.push({type:"tabular",data:JSON.parse(S)})}catch{u("Invalid tabular data"),b(!1);return}break}const J={inputs:P,parameters:_};try{const q=Date.now(),W=await a(J),G=Date.now()-q;y(W),c(Y=>({...Y,metrics:{...Y.metrics,requestsTotal:Y.metrics.requestsTotal+1,latencyP50:(Y.metrics.latencyP50+G)/2},logs:[{timestamp:new Date,requestId:W.requestId,duration:G,status:"success",inputSize:JSON.stringify(P).length,outputSize:JSON.stringify(W.predictions).length},...Y.logs.slice(0,99)]}))}catch(q){const W=q instanceof Error?q.message:"Inference failed";u(W),c(G=>({...G,metrics:{...G.metrics,requestsTotal:G.metrics.requestsTotal+1,errorRate:(G.metrics.errorRate*G.metrics.requestsTotal+1)/(G.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:crypto.randomUUID(),duration:0,status:"error",inputSize:JSON.stringify(P).length,outputSize:0,error:W},...G.logs.slice(0,99)]}))}finally{b(!1)}},f=async P=>{if(a){C(0),$([]);for(let J=0;J<P.length;J++){const q={inputs:[P[J]],parameters:_};try{const W=await a(q);$(G=>[...G,W])}catch(W){console.error("Batch item failed:",W)}C((J+1)/P.length*100)}C(null)}},z=P=>P<1e3?`${P.toFixed(0)}ms`:`${(P/1e3).toFixed(2)}s`,U=P=>P.toLocaleTimeString(),H=(P,J)=>e.jsxs("div",{className:"prediction-item",children:[P.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:P.label}),P.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${P.confidence*120}, 70%, 40%)`},children:[(P.confidence*100).toFixed(1),"%"]})]}),P.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:P.score.toFixed(4)})]}),P.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:P.text})}),P.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",P.bbox.x,", ",P.bbox.y,") - ",P.bbox.width,"×",P.bbox.height]})}),P.raw!==void 0&&P.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(P.raw,null,2)})]})]},J);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 ${l==="test"?"tab-button--active":""}`,onClick:()=>m("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${l==="batch"?"tab-button--active":""}`,onClick:()=>m("batch"),children:"Batch"}),i&&e.jsx("button",{className:`tab-button ${l==="metrics"?"tab-button--active":""}`,onClick:()=>m("metrics"),children:"Metrics"}),r&&e.jsx("button",{className:`tab-button ${l==="logs"?"tab-button--active":""}`,onClick:()=>m("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[l==="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(P=>e.jsx("button",{className:`type-button ${g===P?"type-button--active":""}`,onClick:()=>x(P),children:P.charAt(0).toUpperCase()+P.slice(1)},P))}),e.jsxs("div",{className:"input-area",children:[g==="text"&&e.jsx("textarea",{value:w,onChange:P=>N(P.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),g==="image"&&e.jsx("div",{className:"image-input",children:j?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:j,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>I(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:A,type:"file",accept:"image/*",onChange:O,hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx(L.NiceIcon,{name:"image",size:32})}),e.jsx("span",{children:"Click or drag to upload image"})]})}),(g==="json"||g==="tabular")&&e.jsx("textarea",{value:S,onChange:P=>R(P.target.value),placeholder:g==="json"?`{
|
|
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 Ye(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 Xe(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 Ze(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 Qe(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 ea(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 Ba(t,a,i){const r=d.useMemo(()=>Ke(t,a,i),[t,a,i==null?void 0:i.cursorLine,i==null?void 0:i.cursorCol,i==null?void 0:i.framework]);return X(r,i)}function Fa(t,a,i){const r=d.useMemo(()=>Ye(t,a,i),[t,a,i==null?void 0:i.mode,i==null?void 0:i.locale]);return X(r,i)}function Ja(t,a){const i=d.useMemo(()=>Xe(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 X(i,a)}function Ua(t,a){const i=d.useMemo(()=>Ze(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 X(i,a)}function qa(t,a){const i=d.useMemo(()=>Qe(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 X(i,a)}function Ha(t,a){const i=d.useMemo(()=>ea(t,a),[t,a==null?void 0:a.limit,a==null?void 0:a.style]);return X(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function aa(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(c=>c.node)}}}function Wa(t,a){const i=d.useMemo(()=>aa(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 X(i,a)}function ia(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 }] }`},c=t.map(p=>{var f;return{id:p.id,type:p.type,label:(f=p.label)==null?void 0:f.slice(0,30),pos:[Math.round(p.x),Math.round(p.y)]}}),l=a.map(p=>({id:p.id,src:p.source,tgt:p.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:c,edges:l}),schema:{diagramType:n,mode:r,nodeCount:t.length,edgeCount:a.length,containerSize:i==null?void 0:i.containerSize},customPrompt:s[r]}}function Ga(t,a,i){const r=d.useMemo(()=>ia(t,a,i),[JSON.stringify(t),JSON.stringify(a),i==null?void 0:i.mode,i==null?void 0:i.diagramType]);return X(r,{...i,disabled:t.length===0||(i==null?void 0:i.disabled)})}function ta(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),c={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:c[i]}}function Va(t,a){const i=d.useMemo(()=>ta(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 X(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function ra(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 Ka(t,a){const i=d.useMemo(()=>ra(t,a),[JSON.stringify(t),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return X(i,a)}function Ya(t,a,i){const r=d.forwardRef((n,s)=>{const{aiEnabled:c=!0,aiPosition:l="right",aiPrompt:p,aiDebounceMs:f=500,aiShowOnHover:g=!1,aiTriggerIcon:y,...w}=n,S=d.useMemo(()=>{const z=a(w);return p&&(z.customPrompt=p),z},[w,p]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(t,{...w,ref:s}),c&&e.jsx(Se,{context:S,position:l,debounceMs:f,showOnHover:g,triggerIcon:y})]})});return r.displayName=i??`withAIHint(${t.displayName??t.name??"Component"})`,r}function Xa(t){return Te(t.label??"Text",t.value,{placeholder:t.placeholder,maxLength:t.maxLength})}function Za(t){return Ae(t.label??"Number",t.value,{min:t.min,max:t.max,step:t.step})}function Qa(t){return Re(t.label??"Select",t.value,{options:t.options,multiple:t.multiple})}function ei(t){return Ie(t.label??"Date",t.value,{min:t.min,max:t.max})}function ai(t){return ze(t.label??"Color",t.value)}const ii={id:crypto.randomUUID(),name:"New ML Project",type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date},$e={classification:[{id:"logistic-regression",name:"Logistic Regression"},{id:"random-forest",name:"Random Forest"},{id:"gradient-boosting",name:"Gradient Boosting"},{id:"svm",name:"Support Vector Machine"},{id:"neural-network",name:"Neural Network"},{id:"xgboost",name:"XGBoost"}],regression:[{id:"linear-regression",name:"Linear Regression"},{id:"ridge",name:"Ridge Regression"},{id:"lasso",name:"Lasso Regression"},{id:"random-forest-reg",name:"Random Forest"},{id:"gradient-boosting-reg",name:"Gradient Boosting"}],clustering:[{id:"kmeans",name:"K-Means"},{id:"dbscan",name:"DBSCAN"},{id:"hierarchical",name:"Hierarchical Clustering"}]},Oe={classification:["accuracy","precision","recall","f1-score","auc-roc"],regression:["mse","rmse","mae","r2"],clustering:["silhouette","calinski-harabasz","davies-bouldin"]},ti=[{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"}],ri=({project:t,onProjectChange:a,onExperimentRun:i,onModelDeploy:r,className:n="",tutorial:s})=>{var B;const[c,l]=d.useState(t||ii),[p,f]=d.useState("data"),[g,y]=d.useState(null),[w,S]=d.useState(null),[z,k]=d.useState(null),[I,j]=d.useState(!1),[o,N]=d.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),_=d.useCallback(b=>{const P={...c,...b,updatedAt:new Date};l(P),a==null||a(P)},[c,a]),m=async b=>{for(const P of Array.from(b)){const H={id:crypto.randomUUID(),name:P.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:P.name},size:P.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(P.name.endsWith(".csv")){const M=(await P.text()).split(`
|
|
11
|
+
`),U=M[0].split(",").map(q=>q.trim());H.rowCount=M.length-1,H.columns=U.map(q=>({name:q,type:"text",nullable:!0,unique:0,missing:0})),H.splits=H.splits.map(q=>({...q,rowCount:Math.floor(H.rowCount*q.ratio)}))}_({datasets:[...c.datasets,H]})}},v=b=>{_({datasets:c.datasets.filter(P=>P.id!==b)}),g===b&&y(null)},x=async()=>{if(!o.algorithm||!g)return;const b={id:crypto.randomUUID(),name:`Experiment ${c.experiments.length+1}`,status:"pending",config:o,metrics:[],artifacts:[],logs:[]},P=[...c.experiments,b];if(_({experiments:P}),j(!1),i){const H=P.map(J=>J.id===b.id?{...J,status:"running",startedAt:new Date}:J);_({experiments:H});try{await i(b);const J=(Oe[c.type]||Oe.classification).map(M=>({name:M,value:Math.random()*.3+.7,split:"validation"}));_({experiments:H.map(M=>M.id===b.id?{...M,status:"completed",completedAt:new Date,metrics:J}:M)})}catch{_({experiments:H.map(J=>J.id===b.id?{...J,status:"failed"}:J)})}}},u=b=>{const P=c.experiments.find(J=>J.id===b);if(!P)return;const H={id:crypto.randomUUID(),name:`Model from ${P.name}`,version:"1.0.0",algorithm:P.config.algorithm,experimentId:b,status:"registered",metrics:P.metrics,size:Math.floor(Math.random()*100)*1024*1024,artifacts:[],deployments:[],createdAt:new Date};_({models:[...c.models,H]})},h=async b=>{const P=c.models.find(J=>J.id===b);if(!P||!r)return;const H=await r(P);_({models:c.models.map(J=>J.id===b?{...J,status:"production",deployments:[...J.deployments,H]}:J)})},$=b=>b<1024?`${b} B`:b<1024*1024?`${(b/1024).toFixed(1)} KB`:b<1024*1024*1024?`${(b/1024/1024).toFixed(1)} MB`:`${(b/1024/1024/1024).toFixed(1)} GB`,D=b=>{switch(b){case"completed":case"production":case"running":return"status-badge--success";case"pending":case"staging":return"status-badge--warning";case"failed":return"status-badge--error";default:return""}},C=e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:c.name,onChange:b=>_({name:b.target.value}),className:"project-name-input"}),e.jsxs("select",{value:c.type,onChange:b=>_({type:b.target.value}),className:"project-type-select",children:[e.jsx("option",{value:"classification",children:"Classification"}),e.jsx("option",{value:"regression",children:"Regression"}),e.jsx("option",{value:"clustering",children:"Clustering"}),e.jsx("option",{value:"object-detection",children:"Object Detection"}),e.jsx("option",{value:"nlp",children:"NLP"}),e.jsx("option",{value:"time-series",children:"Time Series"})]})]}),A=e.jsx("div",{className:"header__tabs",children:["data","experiments","models","deploy"].map(b=>e.jsx("button",{className:`tab-button ${p===b?"tab-button--active":""}`,onClick:()=>f(b),children:b.charAt(0).toUpperCase()+b.slice(1)},b))}),O=e.jsxs("div",{className:"ml-studio__content",children:[p==="data"&&e.jsxs("div",{className:"data-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Datasets"}),e.jsxs("label",{className:"upload-button",children:[e.jsx("input",{type:"file",multiple:!0,accept:".csv,.json,.parquet",onChange:b=>b.target.files&&m(b.target.files),hidden:!0}),e.jsx(L.NiceIcon,{name:"plus",size:14})," Upload Dataset"]})]}),e.jsx("div",{className:"datasets-grid",children:c.datasets.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("p",{children:"No datasets uploaded yet"}),e.jsx("p",{className:"hint",children:"Upload CSV, JSON, or Parquet files to get started"})]}):c.datasets.map(b=>e.jsxs("div",{className:`dataset-card ${g===b.id?"dataset-card--selected":""}`,onClick:()=>y(b.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"dataset-icon",children:e.jsx(L.NiceIcon,{name:"folder",size:16})}),e.jsx("h3",{children:b.name}),e.jsx("button",{className:"remove-button","aria-label":"Remove dataset",onClick:P=>{P.stopPropagation(),v(b.id)},children:e.jsx(L.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"card-stats",children:[e.jsxs("span",{children:[b.rowCount.toLocaleString()," rows"]}),e.jsxs("span",{children:[b.columns.length," columns"]}),e.jsx("span",{children:$(b.size)})]}),e.jsx("div",{className:"splits-bar",children:b.splits.map(P=>e.jsx("div",{className:`split split--${P.name}`,style:{width:`${P.ratio*100}%`},title:`${P.name}: ${(P.ratio*100).toFixed(0)}%`},P.name))})]},b.id))}),g&&e.jsx("div",{className:"dataset-details",children:(()=>{const b=c.datasets.find(P=>P.id===g);return b?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:"Columns"}),e.jsxs("table",{className:"columns-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Missing"}),e.jsx("th",{children:"Unique"})]})}),e.jsx("tbody",{children:b.columns.map(P=>e.jsxs("tr",{children:[e.jsx("td",{children:P.name}),e.jsx("td",{children:e.jsxs("select",{value:P.type,onChange:H=>{_({datasets:c.datasets.map(J=>J.id===b.id?{...J,columns:J.columns.map(M=>M.name===P.name?{...M,type:H.target.value}:M)}:J)})},children:[e.jsx("option",{value:"numeric",children:"Numeric"}),e.jsx("option",{value:"categorical",children:"Categorical"}),e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"datetime",children:"DateTime"}),e.jsx("option",{value:"boolean",children:"Boolean"})]})}),e.jsx("td",{children:P.missing}),e.jsx("td",{children:P.unique})]},P.name))})]})]}):null})()})]}),p==="experiments"&&e.jsxs("div",{className:"experiments-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Experiments"}),e.jsxs("button",{className:"primary-button",onClick:()=>j(!0),disabled:c.datasets.length===0,children:[e.jsx(L.NiceIcon,{name:"plus",size:14})," New Experiment"]})]}),I&&e.jsxs("div",{className:"new-experiment-form",children:[e.jsx("h3",{children:"Configure Experiment"}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Dataset",e.jsxs("select",{value:g||"",onChange:b=>y(b.target.value),children:[e.jsx("option",{value:"",children:"Select dataset..."}),c.datasets.map(b=>e.jsx("option",{value:b.id,children:b.name},b.id))]})]}),e.jsxs("label",{children:["Algorithm",e.jsxs("select",{value:o.algorithm,onChange:b=>N({...o,algorithm:b.target.value}),children:[e.jsx("option",{value:"",children:"Select algorithm..."}),($e[c.type]||$e.classification).map(b=>e.jsx("option",{value:b.id,children:b.name},b.id))]})]}),g&&e.jsxs("label",{children:["Target Column",e.jsxs("select",{value:o.targetColumn||"",onChange:b=>N({...o,targetColumn:b.target.value}),children:[e.jsx("option",{value:"",children:"Select target..."}),(B=c.datasets.find(b=>b.id===g))==null?void 0:B.columns.map(b=>e.jsx("option",{value:b.name,children:b.name},b.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>j(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",onClick:x,disabled:!o.algorithm||!g,children:"Run Experiment"})]})]}),e.jsx("div",{className:"experiments-list",children:c.experiments.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"flask",size:32})}),e.jsx("p",{children:"No experiments yet"}),e.jsx("p",{className:"hint",children:"Create an experiment to train and evaluate models"})]}):c.experiments.map(b=>e.jsxs("div",{className:`experiment-card ${w===b.id?"experiment-card--selected":""}`,onClick:()=>S(b.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:b.name}),e.jsx("span",{className:`status-badge ${D(b.status)}`,children:b.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",b.config.algorithm]}),b.duration&&e.jsxs("span",{children:["Duration: ",Math.round(b.duration),"s"]})]}),b.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:b.metrics.slice(0,3).map(P=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:P.name}),e.jsxs("span",{className:"metric-value",children:[(P.value*100).toFixed(1),"%"]})]},P.name))}),b.status==="completed"&&e.jsx("button",{className:"action-button",onClick:P=>{P.stopPropagation(),u(b.id)},children:"Register Model"})]},b.id))})]}),p==="models"&&e.jsxs("div",{className:"models-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:"Models"})}),e.jsx("div",{className:"models-list",children:c.models.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"wand",size:32})}),e.jsx("p",{children:"No models registered yet"}),e.jsx("p",{className:"hint",children:"Complete experiments and register models"})]}):c.models.map(b=>e.jsxs("div",{className:`model-card ${z===b.id?"model-card--selected":""}`,onClick:()=>k(b.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:b.name}),e.jsx("span",{className:`status-badge ${D(b.status)}`,children:b.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",b.algorithm]}),e.jsxs("span",{children:["Version: ",b.version]}),e.jsxs("span",{children:["Size: ",$(b.size)]})]}),b.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:b.metrics.slice(0,3).map(P=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:P.name}),e.jsxs("span",{className:"metric-value",children:[(P.value*100).toFixed(1),"%"]})]},P.name))}),e.jsxs("div",{className:"card-actions",children:[e.jsx("button",{className:"action-button",children:"Download"}),e.jsx("button",{className:"action-button action-button--primary",onClick:P=>{P.stopPropagation(),h(b.id)},disabled:b.status==="production",children:b.status==="production"?"Deployed":"Deploy"})]})]},b.id))})]}),p==="deploy"&&e.jsxs("div",{className:"deploy-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:"Deployments"})}),e.jsx("div",{className:"deployments-list",children:c.models.filter(b=>b.deployments.length>0).length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"rocket",size:32})}),e.jsx("p",{children:"No deployments yet"}),e.jsx("p",{className:"hint",children:"Deploy a model to create inference endpoints"})]}):c.models.filter(b=>b.deployments.length>0).flatMap(b=>b.deployments.map(P=>({model:b,deployment:P}))).map(({model:b,deployment:P})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:P.name}),e.jsx("span",{className:`status-badge ${D(P.status)}`,children:P.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Model: ",b.name]}),e.jsxs("span",{children:["Endpoint: ",P.endpoint]})]}),e.jsxs("div",{className:"resources-info",children:[e.jsxs("span",{children:["CPU: ",P.resources.cpu," cores"]}),e.jsxs("span",{children:["Memory: ",P.resources.memory," GB"]}),e.jsxs("span",{children:["Replicas: ",P.resources.replicas]})]})]},P.id))})]})]});return e.jsxs("div",{className:`nice-ml-studio ${n}`,style:{position:"relative"},children:[e.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:e.jsx(L.NiceTutorialButton,{steps:L.resolveTutorial(s,ti)})}),e.jsx(Ca.NiceAppShell,{flush:!0,menubar:C,toolbar:A,children:O})]})},ni={id:crypto.randomUUID(),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},Ee=["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)"],si=({project:t,onProjectChange:a,onLabelSave:i,onExport:r,className:n=""})=>{var Q;const{t:s}=L.useNiceTranslation(),[c,l]=d.useState(t||ni),[p,f]=d.useState("label"),[g,y]=d.useState(0),[w,S]=d.useState(null),[z,k]=d.useState("select"),[I,j]=d.useState(!1),[o,N]=d.useState(null),[_,m]=d.useState(1),[v,x]=d.useState(!1),[u,h]=d.useState("all"),$=d.useRef(null),D=d.useRef(null),C=c.items[g];d.useEffect(()=>{t&&l(t)},[t]);const A=d.useCallback(T=>{const E={...c,...T};E.statistics={totalItems:E.items.length,labeled:E.items.filter(R=>R.status!=="pending").length,reviewed:E.items.filter(R=>R.status==="review"||R.status==="approved").length,approved:E.items.filter(R=>R.status==="approved").length,byClass:E.labelSchema.classes.map(R=>({classId:R.id,count:E.items.flatMap(F=>F.labels).filter(F=>F.classId===R.id).length}))},l(E),a==null||a(E)},[c,a]),O=()=>{const T={id:crypto.randomUUID(),name:`Class ${c.labelSchema.classes.length+1}`,color:Ee[c.labelSchema.classes.length%Ee.length],shortcut:String(c.labelSchema.classes.length+1)};A({labelSchema:{...c.labelSchema,classes:[...c.labelSchema.classes,T]}})},B=T=>{A({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.filter(E=>E.id!==T)},items:c.items.map(E=>({...E,labels:E.labels.filter(R=>R.classId!==T)}))})},b=(T,E)=>{A({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.map(R=>R.id===T?{...R,...E}:R)}})},P=(T,E)=>{if(!C)return;const R={id:crypto.randomUUID(),classId:T,type:c.type==="classification"?"class":c.type==="bounding-box"?"bbox":"class",data:E||{},createdBy:"current-user",createdAt:new Date},F={...C,labels:[...C.labels,R],status:"labeled"};A({items:c.items.map(V=>V.id===C.id?F:V)}),i==null||i(F)},H=T=>{if(!C)return;const E={...C,labels:C.labels.filter(R=>R.id!==T),status:C.labels.length<=1?"pending":"labeled"};A({items:c.items.map(R=>R.id===C.id?E:R)})},J=T=>{var V;if(z!=="bbox"||!w)return;const E=(V=$.current)==null?void 0:V.getBoundingClientRect();if(!E)return;const R=(T.clientX-E.left)/_,F=(T.clientY-E.top)/_;j(!0),N({x:R,y:F,width:0,height:0})},M=T=>{var V;if(!I||!o)return;const E=(V=$.current)==null?void 0:V.getBoundingClientRect();if(!E)return;const R=(T.clientX-E.left)/_,F=(T.clientY-E.top)/_;N({...o,width:R-o.x,height:F-o.y})},U=()=>{!I||!o||!w||(j(!1),Math.abs(o.width)>10&&Math.abs(o.height)>10&&P(w,{x:o.width<0?o.x+o.width:o.x,y:o.height<0?o.y+o.height:o.y,width:Math.abs(o.width),height:Math.abs(o.height)}),N(null))},q=T=>{const E=u==="all"?c.items:c.items.filter(F=>F.status===u),R=E.findIndex(F=>F.id===(C==null?void 0:C.id));if(T==="prev"&&R>0){const F=E[R-1];y(c.items.findIndex(V=>V.id===F.id))}else if(T==="next"&&R<E.length-1){const F=E[R+1];y(c.items.findIndex(V=>V.id===F.id))}},W=()=>{if(!C)return;const T={...C,status:"approved"};A({items:c.items.map(E=>E.id===C.id?T:E)}),q("next")},G=()=>{if(!C)return;const T={...C,status:"rejected"};A({items:c.items.map(E=>E.id===C.id?T:E)}),q("next")},Y=async T=>{r&&await r(T)};d.useEffect(()=>{const T=E=>{const R=E.target instanceof HTMLElement?E.target:null;if(p!=="label"||E.defaultPrevented||E.ctrlKey||E.metaKey||E.altKey||R!=null&&R.isContentEditable||R&&/^(INPUT|TEXTAREA|SELECT)$/.test(R.tagName)||E.key==="Enter"&&(R!=null&&R.closest("button, a")))return;const F=E.key,V=c.labelSchema.classes.find(re=>re.shortcut===F);V&&(c.type==="classification"?(P(V.id),q("next")):S(V.id)),E.key==="ArrowLeft"||E.key==="a"?q("prev"):(E.key==="ArrowRight"||E.key==="d")&&q("next"),E.key==="Enter"?W():E.key==="Backspace"&&G()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[p,C,c.labelSchema.classes,c.type]);const ee=T=>{switch(T){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:c.name,onChange:T=>A({name:T.target.value}),className:"project-name-input"}),e.jsxs("div",{className:"progress-bar",children:[e.jsx("div",{className:"progress-fill",style:{width:`${c.statistics.labeled/Math.max(c.statistics.totalItems,1)*100}%`}}),e.jsxs("span",{className:"progress-text",children:[c.statistics.labeled," / ",c.statistics.totalItems," labeled"]})]})]}),e.jsx("div",{className:"header__tabs",children:["label","schema","review","export"].map(T=>e.jsx("button",{className:`tab-button ${p===T?"tab-button--active":""}`,onClick:()=>f(T),children:T.charAt(0).toUpperCase()+T.slice(1)},T))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>x(!v),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"labeler__content",children:[p==="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 ${z==="select"?"tool-button--active":""}`,onClick:()=>k("select"),children:[e.jsx(L.NiceIcon,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(c.type==="bounding-box"||c.type==="multi-label")&&e.jsxs("button",{className:`tool-button ${z==="bbox"?"tool-button--active":""}`,onClick:()=>k("bbox"),children:[e.jsx(L.NiceIcon,{name:"square",size:14})," Box"]}),c.type==="polygon"&&e.jsxs("button",{className:`tool-button ${z==="polygon"?"tool-button--active":""}`,onClick:()=>k("polygon"),children:[e.jsx(L.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:()=>m(Math.max(.25,_-.25)),children:e.jsx(L.NiceIcon,{name:"minus",size:14})}),e.jsxs("span",{children:[Math.round(_*100),"%"]}),e.jsx("button",{"aria-label":s("dataLabeler.zoomIn","Zoom in"),onClick:()=>m(Math.min(4,_+.25)),children:e.jsx(L.NiceIcon,{name:"plus",size:14})})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsxs("button",{onClick:()=>q("prev"),disabled:g===0,children:[e.jsx(L.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[g+1," / ",c.items.length]}),e.jsxs("button",{onClick:()=>q("next"),disabled:g>=c.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx(L.NiceIcon,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:D,children:C?e.jsxs(e.Fragment,{children:[C.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:C.data.url,alt:s("dataLabeler.labelingItem","Labeling item"),className:"labeling-image",style:{transform:`scale(${_})`}}),e.jsx("canvas",{ref:$,className:"labeling-canvas",onMouseDown:J,onMouseMove:M,onMouseUp:U,onMouseLeave:U,style:{transform:`scale(${_})`,cursor:z==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${_})`},children:[C.labels.filter(T=>T.type==="bbox"&&T.data.x!==void 0).map(T=>{const E=c.labelSchema.classes.find(R=>R.id===T.classId);return e.jsxs("div",{className:"bbox-annotation",style:{left:T.data.x,top:T.data.y,width:T.data.width,height:T.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:()=>H(T.id),children:e.jsx(L.NiceIcon,{name:"close",size:12})})]},T.id)}),o&&e.jsx("div",{className:"bbox-drawing",style:{left:o.width<0?o.x+o.width:o.x,top:o.height<0?o.y+o.height:o.y,width:Math.abs(o.width),height:Math.abs(o.height),borderColor:(Q=c.labelSchema.classes.find(T=>T.id===w))==null?void 0:Q.color}})]})]}),C.data.type==="text"&&e.jsx("div",{className:"text-labeling",children:e.jsx("p",{className:"text-content",children:C.data.text})})]}):e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.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:c.labelSchema.classes.map(T=>e.jsxs("button",{className:`class-button ${w===T.id?"class-button--active":""}`,style:{borderLeftColor:T.color},onClick:()=>{c.type==="classification"?(P(T.id),q("next")):S(T.id)},children:[e.jsx("span",{className:"class-color",style:{backgroundColor:T.color}}),e.jsx("span",{className:"class-name",children:T.name}),T.shortcut&&e.jsx("span",{className:"class-shortcut",children:T.shortcut})]},T.id))}),C&&C.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),C.labels.map(T=>{const E=c.labelSchema.classes.find(R=>R.id===T.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:()=>H(T.id),children:e.jsx(L.NiceIcon,{name:"close",size:14})})]},T.id)})]}),p==="label"&&C&&e.jsxs("div",{className:"label-actions",children:[e.jsxs("button",{className:"approve-button",onClick:W,children:[e.jsx(L.NiceIcon,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"reject-button",onClick:G,children:[e.jsx(L.NiceIcon,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),p==="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:O,children:[e.jsx(L.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:c.type,onChange:T=>A({type:T.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:c.dataType,onChange:T=>A({dataType:T.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:c.labelSchema.classes.map((T,E)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:T.color,onChange:R=>b(T.id,{color:R.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:T.name,onChange:R=>b(T.id,{name:R.target.value}),className:"class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:T.shortcut||"",onChange:R=>b(T.id,{shortcut:R.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:()=>B(T.id),children:e.jsx(L.NiceIcon,{name:"trash",size:16})})]},T.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:c.guidelines||"",onChange:T=>A({guidelines:T.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),p==="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:u,onChange:T=>h(T.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:c.items.filter(T=>u==="all"||T.status===u).map((T,E)=>{var R;return e.jsxs("div",{className:`item-card ${g===c.items.indexOf(T)?"item-card--active":""}`,onClick:()=>{y(c.items.indexOf(T)),f("label")},children:[T.data.type==="image"&&e.jsx("img",{src:T.data.url,alt:`Item ${E+1}`,className:"item-thumbnail"}),T.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(R=T.data.text)==null?void 0:R.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:ee(T.status)}}),e.jsxs("span",{children:[T.labels.length," labels"]})]})]},T.id)})})]}),p==="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:c.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:c.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:c.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:c.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:()=>Y("coco"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.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:()=>Y("voc"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.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:()=>Y("yolo"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.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:()=>Y("csv"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.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:c.statistics.byClass.map(T=>{const E=c.labelSchema.classes.find(F=>F.id===T.classId),R=T.count/Math.max(c.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:`${R}%`,backgroundColor:E==null?void 0:E.color}})}),e.jsx("span",{className:"count",children:T.count})]},T.classId)})})]})]})]}),v&&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:()=>x(!1),children:e.jsx(L.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")})]}),c.labelSchema.classes.map(T=>T.shortcut&&e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:T.shortcut}),e.jsxs("span",{className:"description",children:["Label as ",T.name]})]},T.id))]})]})})]})},ci={id:crypto.randomUUID(),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:[]},oi=({endpoint:t,onInference:a,showMetrics:i=!0,showLogs:r=!0,className:n=""})=>{const[s,c]=d.useState(t||ci),[l,p]=d.useState("test"),[f,g]=d.useState("text"),[y,w]=d.useState(""),[S,z]=d.useState("{}"),[k,I]=d.useState(null),[j,o]=d.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[N,_]=d.useState(null),[m,v]=d.useState(!1),[x,u]=d.useState(null),[h,$]=d.useState([]),[D,C]=d.useState(null),A=d.useRef(null),O=M=>{var q;const U=(q=M.target.files)==null?void 0:q[0];if(U){const W=new FileReader;W.onload=G=>{var Y;I((Y=G.target)==null?void 0:Y.result)},W.readAsDataURL(U)}},B=async()=>{if(!a){u("No inference handler provided");return}v(!0),u(null),_(null);const M=[];switch(f){case"text":M.push({type:"text",data:y});break;case"image":k&&M.push({type:"image",data:k});break;case"json":try{M.push({type:"json",data:JSON.parse(S)})}catch{u("Invalid JSON input"),v(!1);return}break;case"tabular":try{M.push({type:"tabular",data:JSON.parse(S)})}catch{u("Invalid tabular data"),v(!1);return}break}const U={inputs:M,parameters:j};try{const q=Date.now(),W=await a(U),G=Date.now()-q;_(W),c(Y=>({...Y,metrics:{...Y.metrics,requestsTotal:Y.metrics.requestsTotal+1,latencyP50:(Y.metrics.latencyP50+G)/2},logs:[{timestamp:new Date,requestId:W.requestId,duration:G,status:"success",inputSize:JSON.stringify(M).length,outputSize:JSON.stringify(W.predictions).length},...Y.logs.slice(0,99)]}))}catch(q){const W=q instanceof Error?q.message:"Inference failed";u(W),c(G=>({...G,metrics:{...G.metrics,requestsTotal:G.metrics.requestsTotal+1,errorRate:(G.metrics.errorRate*G.metrics.requestsTotal+1)/(G.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:crypto.randomUUID(),duration:0,status:"error",inputSize:JSON.stringify(M).length,outputSize:0,error:W},...G.logs.slice(0,99)]}))}finally{v(!1)}},b=async M=>{if(a){C(0),$([]);for(let U=0;U<M.length;U++){const q={inputs:[M[U]],parameters:j};try{const W=await a(q);$(G=>[...G,W])}catch(W){console.error("Batch item failed:",W)}C((U+1)/M.length*100)}C(null)}},P=M=>M<1e3?`${M.toFixed(0)}ms`:`${(M/1e3).toFixed(2)}s`,H=M=>M.toLocaleTimeString(),J=(M,U)=>e.jsxs("div",{className:"prediction-item",children:[M.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:M.label}),M.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${M.confidence*120}, 70%, 40%)`},children:[(M.confidence*100).toFixed(1),"%"]})]}),M.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:M.score.toFixed(4)})]}),M.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:M.text})}),M.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",M.bbox.x,", ",M.bbox.y,") - ",M.bbox.width,"×",M.bbox.height]})}),M.raw!==void 0&&M.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(M.raw,null,2)})]})]},U);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 ${l==="test"?"tab-button--active":""}`,onClick:()=>p("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${l==="batch"?"tab-button--active":""}`,onClick:()=>p("batch"),children:"Batch"}),i&&e.jsx("button",{className:`tab-button ${l==="metrics"?"tab-button--active":""}`,onClick:()=>p("metrics"),children:"Metrics"}),r&&e.jsx("button",{className:`tab-button ${l==="logs"?"tab-button--active":""}`,onClick:()=>p("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[l==="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(M=>e.jsx("button",{className:`type-button ${f===M?"type-button--active":""}`,onClick:()=>g(M),children:M.charAt(0).toUpperCase()+M.slice(1)},M))}),e.jsxs("div",{className:"input-area",children:[f==="text"&&e.jsx("textarea",{value:y,onChange:M=>w(M.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),f==="image"&&e.jsx("div",{className:"image-input",children:k?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:k,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>I(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:A,type:"file",accept:"image/*",onChange:O,hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx(L.NiceIcon,{name:"image",size:32})}),e.jsx("span",{children:"Click or drag to upload image"})]})}),(f==="json"||f==="tabular")&&e.jsx("textarea",{value:S,onChange:M=>z(M.target.value),placeholder:f==="json"?`{
|
|
12
12
|
"key": "value"
|
|
13
13
|
}`:`[
|
|
14
14
|
{"col1": "value1", "col2": "value2"}
|
|
15
|
-
]`,rows:10,className:"json-input"})]}),e.jsxs("div",{className:"parameters-section",children:[e.jsx("h4",{children:"Parameters"}),e.jsxs("div",{className:"parameters-grid",children:[e.jsxs("label",{children:["Temperature",e.jsx("input",{type:"number",value:
|
|
16
|
-
`);l=
|
|
17
|
-
`);l=
|
|
18
|
-
`);l=
|
|
15
|
+
]`,rows:10,className:"json-input"})]}),e.jsxs("div",{className:"parameters-section",children:[e.jsx("h4",{children:"Parameters"}),e.jsxs("div",{className:"parameters-grid",children:[e.jsxs("label",{children:["Temperature",e.jsx("input",{type:"number",value:j.temperature,onChange:M=>o({...j,temperature:parseFloat(M.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:["Top K",e.jsx("input",{type:"number",value:j.topK,onChange:M=>o({...j,topK:parseInt(M.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:["Top P",e.jsx("input",{type:"number",value:j.topP,onChange:M=>o({...j,topP:parseFloat(M.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:["Threshold",e.jsx("input",{type:"number",value:j.threshold,onChange:M=>o({...j,threshold:parseFloat(M.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"run-button",onClick:B,disabled:m||!y&&!k&&S==="{}",children:m?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"output-section",children:[e.jsx("h3",{children:"Output"}),x&&e.jsxs("div",{className:"error-message",children:[e.jsx("span",{className:"error-icon",children:e.jsx(L.NiceIcon,{name:"warning",size:16})}),x]}),N&&e.jsxs("div",{className:"result-container",children:[e.jsxs("div",{className:"result-meta",children:[e.jsxs("span",{children:["Request ID: ",N.requestId]}),e.jsxs("span",{children:["Latency: ",P(N.latency)]}),e.jsxs("span",{children:["Model: ",N.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:N.predictions.map((M,U)=>J(M,U))})]}),!x&&!N&&e.jsxs("div",{className:"empty-output",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"upload",size:32})}),e.jsx("p",{children:"Run inference to see results"})]})]})]}),l==="batch"&&e.jsxs("div",{className:"batch-panel",children:[e.jsxs("div",{className:"batch-upload",children:[e.jsx("h3",{children:"Batch Inference"}),e.jsx("p",{className:"hint",children:"Upload a file with multiple inputs for batch processing"}),e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{type:"file",accept:".json,.csv,.txt",onChange:async M=>{var q;const U=(q=M.target.files)==null?void 0:q[0];if(U){const W=await U.text();try{const G=JSON.parse(W);if(Array.isArray(G)){const Y=G.map(ee=>({type:"json",data:ee}));b(Y)}}catch{u("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx(L.NiceIcon,{name:"folder",size:32})}),e.jsx("span",{children:"Upload JSON array file"})]})]}),D!==null&&e.jsxs("div",{className:"batch-progress",children:[e.jsx("div",{className:"progress-bar",children:e.jsx("div",{className:"progress-fill",style:{width:`${D}%`}})}),e.jsxs("span",{children:[Math.round(D),"%"]})]}),h.length>0&&e.jsxs("div",{className:"batch-results",children:[e.jsxs("h3",{children:["Results (",h.length,")"]}),e.jsx("div",{className:"results-list",children:h.map((M,U)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",U+1]}),M.predictions.map((q,W)=>e.jsxs("span",{className:"result-prediction",children:[q.label,": ",(q.confidence||q.score||0).toFixed(1),"%"]},W))]},U))})]})]}),l==="metrics"&&i&&e.jsxs("div",{className:"metrics-panel",children:[e.jsxs("div",{className:"metrics-grid",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsTotal}),e.jsx("span",{className:"metric-label",children:"Total Requests"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsPerSecond.toFixed(1)}),e.jsx("span",{className:"metric-label",children:"Requests/sec"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:P(s.metrics.latencyP50)}),e.jsx("span",{className:"metric-label",children:"P50 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:P(s.metrics.latencyP95)}),e.jsx("span",{className:"metric-label",children:"P95 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:P(s.metrics.latencyP99)}),e.jsx("span",{className:"metric-label",children:"P99 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("span",{className:"metric-value",children:[s.metrics.successRate.toFixed(1),"%"]}),e.jsx("span",{className:"metric-label",children:"Success Rate"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("span",{className:"metric-value",children:[(s.metrics.errorRate*100).toFixed(2),"%"]}),e.jsx("span",{className:"metric-label",children:"Error Rate"})]})]}),e.jsxs("div",{className:"latency-histogram",children:[e.jsx("h3",{children:"Latency Distribution"}),e.jsx("div",{className:"histogram-bars",children:[10,25,50,75,90,95,99].map(M=>e.jsxs("div",{className:"histogram-bar",children:[e.jsx("div",{className:"bar-fill",style:{height:`${Math.min(100,s.metrics.latencyP50*M/100)}px`}}),e.jsxs("span",{className:"percentile-label",children:["P",M]})]},M))})]})]}),l==="logs"&&r&&e.jsxs("div",{className:"logs-panel",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("h3",{children:"Request Logs"}),e.jsx("button",{className:"clear-logs-button",onClick:()=>c(M=>({...M,logs:[]})),children:"Clear Logs"})]}),e.jsx("div",{className:"logs-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Time"}),e.jsx("th",{children:"Request ID"}),e.jsx("th",{children:"Duration"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Input Size"}),e.jsx("th",{children:"Output Size"})]})}),e.jsx("tbody",{children:s.logs.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty-logs",children:"No logs yet"})}):s.logs.map((M,U)=>e.jsxs("tr",{className:`log-row log-row--${M.status}`,children:[e.jsx("td",{children:H(M.timestamp)}),e.jsx("td",{className:"request-id",children:M.requestId.slice(0,8)}),e.jsx("td",{children:P(M.duration)}),e.jsx("td",{children:e.jsx("span",{className:`status-badge status-badge--${M.status}`,children:M.status})}),e.jsxs("td",{children:[M.inputSize," B"]}),e.jsxs("td",{children:[M.outputSize," B"]})]},U))})]})})]})]})]})};class te{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 c=setTimeout(()=>{var p;return(p=this.abortController)==null?void 0:p.abort()},this.config.timeout),l=await fetch(a,{...i,signal:this.abortController.signal});if(clearTimeout(c),l.ok)return l;if(l.status>=400&&l.status<500){const p=await l.text();throw new Error(`API Error ${l.status}: ${p}`)}n=new Error(`HTTP ${l.status}`)}catch(c){n=c,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 p;const s=(p=a.body)==null?void 0:p.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;l+=c.decode(g,{stream:!0});const y=l.split(`
|
|
16
|
+
`);l=y.pop()||"";for(const w of y)if(w.startsWith("data: ")){const S=w.slice(6).trim();if(S==="[DONE]"){r==null||r();return}try{const z=JSON.parse(S);i(this.normalizeStreamChunk(z))}catch{}}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class _e extends te{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(l=>a.includes(l)),c=s?n[s]:n["gpt-4o-mini"];return i/1e6*c.input+r/1e6*c.output}}class na extends te{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 p;const s=(p=a.body)==null?void 0:p.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;l+=c.decode(g,{stream:!0});const y=l.split(`
|
|
17
|
+
`);l=y.pop()||"";for(const w of y)if(w.startsWith("data: "))try{const S=JSON.parse(w.slice(6));if(S.type==="content_block_delta")i(this.normalizeStreamChunk(S));else if(S.type==="message_stop"){r==null||r();return}}catch{}}r==null||r()}catch(f){n==null||n(f)}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(l=>a.includes(l)),c=s?n[s]:n["claude-3-5-sonnet"];return i/1e6*c.input+r/1e6*c.output}}class sa extends te{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 c=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(c,i,r,n)}catch(c){n==null||n(c)}}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 ca extends te{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 p;const s=(p=a.body)==null?void 0:p.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;l+=c.decode(g,{stream:!0});const y=l.split(`
|
|
18
|
+
`);l=y.pop()||"";for(const w of y)if(w.trim())try{const S=JSON.parse(w);if(i(this.normalizeStreamChunk(S)),S.done){r==null||r();return}}catch{}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class oa extends te{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 _e(t);case"anthropic":return new na(t);case"azure-openai":return new sa(t);case"ollama":return new ca(t);case"groq":return new oa(t);case"custom":return new _e(t);default:throw new Error(`Unsupported provider type: ${t.type}`)}}function K(t){const a=new URL(t.endpoint),i=a.host.toLowerCase(),r=a.pathname.replace(/\/+$/,""),n=p=>`${a.protocol}//${a.host}${r.endsWith(p)?r.slice(0,-p.length):r}`,s={apiKey:t.apiKey,model:t.model,headers:t.headers},c=/^(.*)\/openai\/deployments\/([^/]+)\/chat\/completions$/.exec(r);if(i.endsWith("azure.com")&&c)return ae({type:"azure-openai",...s,baseUrl:`${a.protocol}//${a.host}${c[1]}`,deployment:c[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 l=i.includes("openai.com")?"openai":i.includes("groq.com")?"groq":"custom";return ae({type:l,...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,(c,l,p)=>{const f=i[l];return f==null||f===""||f===!1||Array.isArray(f)&&f.length===0?"":p}).replace(/\{\{(\w+)\}\}/g,(c,l)=>{const p=i[l];return p===void 0?`{{${l}}}`:typeof p=="object"?JSON.stringify(p,null,2):String(p)});return{system:r(t.system),user:r(t.user),metadata:{templateId:t.id,variables:i,timestamp:Date.now()}}}const se={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},ce={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},oe={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},le={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,14 +156,14 @@ 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},de={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
|
|
163
163
|
- Use the same language features and patterns
|
|
164
164
|
- Keep completions concise and focused
|
|
165
165
|
- Do not repeat existing code
|
|
166
|
-
- Only output the completion, not the full code`,user:"Language: {{language}}\n\nContext (code before cursor):\n```{{language}}\n{{prefix}}\n```\n\nContext (code after cursor):\n```{{language}}\n{{suffix}}\n```\n\nComplete the code at the cursor position:",variables:[{name:"language",description:"Programming language",required:!0,type:"string"},{name:"prefix",description:"Code before cursor",required:!0,type:"string"},{name:"suffix",description:"Code after cursor",required:!1,type:"string",default:""}],suggestedModel:"gpt-4o",suggestedTemperature:.2,maxTokens:512},
|
|
166
|
+
- Only output the completion, not the full code`,user:"Language: {{language}}\n\nContext (code before cursor):\n```{{language}}\n{{prefix}}\n```\n\nContext (code after cursor):\n```{{language}}\n{{suffix}}\n```\n\nComplete the code at the cursor position:",variables:[{name:"language",description:"Programming language",required:!0,type:"string"},{name:"prefix",description:"Code before cursor",required:!0,type:"string"},{name:"suffix",description:"Code after cursor",required:!1,type:"string",default:""}],suggestedModel:"gpt-4o",suggestedTemperature:.2,maxTokens:512},ue={id:"workflow-generator",name:"Workflow/BPMN Generator",description:"Generate workflow definition from process description",category:"workflow",system:`You are a business process expert. Generate workflow definitions from descriptions.
|
|
167
167
|
|
|
168
168
|
Output BPMN-compatible JSON:
|
|
169
169
|
{
|
|
@@ -205,7 +205,7 @@ Available roles: {{roles}}
|
|
|
205
205
|
Systems involved: {{systems}}
|
|
206
206
|
{{/if}}
|
|
207
207
|
|
|
208
|
-
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},
|
|
208
|
+
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},pe={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.
|
|
209
209
|
|
|
210
210
|
Available report elements:
|
|
211
211
|
- header, footer
|
|
@@ -243,7 +243,7 @@ Output JSON:
|
|
|
243
243
|
Available data sources: {{dataSources}}
|
|
244
244
|
{{/if}}
|
|
245
245
|
|
|
246
|
-
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},
|
|
246
|
+
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},we={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.
|
|
247
247
|
Generate a complete theme from brand colors following accessibility guidelines.
|
|
248
248
|
|
|
249
249
|
Rules:
|
|
@@ -283,7 +283,7 @@ Output JSON:
|
|
|
283
283
|
{{#if industry}}Industry: {{industry}}{{/if}}
|
|
284
284
|
{{#if style}}Style preference: {{style}}{{/if}}
|
|
285
285
|
|
|
286
|
-
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},
|
|
286
|
+
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},je={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).
|
|
287
287
|
Analyze code for accessibility issues and provide fixes.
|
|
288
288
|
|
|
289
289
|
Check for:
|
|
@@ -310,7 +310,7 @@ Output JSON:
|
|
|
310
310
|
],
|
|
311
311
|
"score": 0-100,
|
|
312
312
|
"summary": "Brief summary of findings"
|
|
313
|
-
}`,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},
|
|
313
|
+
}`,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},ke={id:"translation",name:"UI Translation",description:"Translate UI text maintaining context and formatting",category:"translation",system:`You are a professional UI translator.
|
|
314
314
|
Translate text while:
|
|
315
315
|
- Preserving placeholders like {name}, {{count}}, %s
|
|
316
316
|
- Maintaining ICU message format syntax
|
|
@@ -328,7 +328,7 @@ Output JSON:
|
|
|
328
328
|
|
|
329
329
|
{{texts}}
|
|
330
330
|
|
|
331
|
-
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},
|
|
331
|
+
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},Ne={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.
|
|
332
332
|
|
|
333
333
|
Provide:
|
|
334
334
|
- Key statistics (min, max, mean, median)
|
|
@@ -352,7 +352,7 @@ Format output as structured JSON:
|
|
|
352
352
|
|
|
353
353
|
{{#if context}}Context: {{context}}{{/if}}
|
|
354
354
|
|
|
355
|
-
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},ge={[ne.id]:ne,[se.id]:se,[ce.id]:ce,[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[pe.id]:pe,[_e.id]:_e,[we.id]:we,[je.id]:je};function ci(t){return ge[t]}function oi(t){return Object.values(ge).filter(a=>a.category===t)}function li(){return Object.keys(ge)}class Ie{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 oa{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],c=Date.now()-720*60*60*1e3,l=s.filter(m=>m.timestamp>c);localStorage.setItem(r,JSON.stringify(l))}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(c=>!(i&&c.timestamp<i.getTime()||r&&c.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 la{constructor(a,i){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new Ie,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),c=await this.storage.load(a,n),l=s.reduce((R,j)=>R+j.estimatedCost,0),m=c.reduce((R,j)=>R+j.estimatedCost,0),g=this.budgetConfig.dailyBudget||1/0,x=this.budgetConfig.monthlyBudget||1/0,w=g?l/g*100:0,N=x?m/x*100:0,S=[];for(const R of this.budgetConfig.alertThresholds||[])w>=R&&S.push(`Daily budget ${R}% used`),N>=R&&S.push(`Monthly budget ${R}% used`);return{dailyUsed:l,dailyRemaining:Math.max(0,g-l),dailyPercent:w,monthlyUsed:m,monthlyRemaining:Math.max(0,x-m),monthlyPercent:N,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:l>=g||m>=x,alerts:S}}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 c=0,l=0;for(const m of n){s.totalTokens+=m.totalTokens,s.totalPromptTokens+=m.promptTokens,s.totalCompletionTokens+=m.completionTokens,s.totalCost+=m.estimatedCost,c+=m.latencyMs,m.error&&s.errorCount++,m.cached&&l++,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 g=m.feature||"unknown";s.byFeature[g]||(s.byFeature[g]={requests:0,tokens:0,cost:0}),s.byFeature[g].requests++,s.byFeature[g].tokens+=m.totalTokens,s.byFeature[g].cost+=m.estimatedCost;const x=new Date(m.timestamp).toISOString().split("T")[0];s.byDay[x]||(s.byDay[x]={requests:0,tokens:0,cost:0}),s.byDay[x].requests++,s.byDay[x].tokens+=m.totalTokens,s.byDay[x].cost+=m.estimatedCost}return n.length>0&&(s.averageLatency=c/n.length,s.cacheHitRate=l/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(l=>l>r));const s=new Date().toISOString().split("T")[0],c=`${a}:${s}`;this.dayCounter.set(c,(this.dayCounter.get(c)||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 di(t,a){const i=d.useRef(null),[r,n]=d.useState(null),[s,c]=d.useState(null),[l,m]=d.useState(!0);d.useEffect(()=>{const N=typeof window<"u"?new oa:new Ie;i.current=new la(N,a);const S=i.current.onAlert(R=>{console.warn(`[AI Cost Alert] ${R}`)});return()=>{S()}},[]);const g=d.useCallback(async()=>{if(i.current){m(!0);try{const[N,S]=await Promise.all([i.current.getBudgetStatus(t),i.current.getUsageStats(t)]);n(N),c(S)}finally{m(!1)}}},[t]);d.useEffect(()=>{g()},[g]);const x=d.useCallback(async N=>{i.current&&(await i.current.recordUsage(t,N),await g())},[t,g]),w=d.useCallback(async()=>i.current?i.current.canMakeRequest(t):{allowed:!0},[t]);return{status:r,stats:s,loading:l,recordUsage:x,canMakeRequest:w,refresh:g}}class ui{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 da{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 ui(100,this.config.cacheTTL);for(const r of this.config.backupProviders||[])this.backupProviders.push(ie(r));this.config.offlineConfig&&(this.offlineProvider=ie(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 c=await this.executeStrategy(s,a,i);if(c)return(n=(r=this.config).onFallback)==null||n.call(r,s,i),c}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 ua(t,a){const i=ie(t);return new da(i,a)}function pi(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"}),ua(t,i)}function pa(t){const{columns:a,config:i,onFilterGenerated:r,onSortGenerated:n,onError:s}=t,c=Q(),[l,m]=d.useState(!1),[g,x]=d.useState(null),[w,N]=d.useState(null),[S,R]=d.useState([]),j=d.useRef(null),I=i||(c==null?void 0:c.config),_=d.useMemo(()=>a.map(p=>({id:p.id,label:p.label,type:p.type,...p.options?{options:p.options}:{}})),[a]),o=d.useCallback(async p=>{var v;if(!I){const u="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(u),{type:"filter",error:u}}m(!0),x(p);const b=performance.now();(v=j.current)==null||v.abort(),j.current=new AbortController;try{const u=V(I),h=p.toLowerCase(),$=h.includes("sort")||h.includes("order")||h.includes("arrange")||h.includes("by highest")||h.includes("by lowest"),E=h.includes("show")||h.includes("find")||h.includes("filter")||h.includes("where")||h.includes("with")||h.includes("only")||!$,C={type:"combined"};if(E){const A=ee(ne,{columns:_,query:p}),O=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.2,maxTokens:512}),B=mi(O);B&&(C.filterConfig=B,C.type="filter",r==null||r(B))}if($){const A=ee(se,{columns:_,query:p}),O=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.1,maxTokens:256}),B=hi(O);B&&(C.sortConfig=B,C.type=C.filterConfig?"combined":"sort",n==null||n(B))}return C.latencyMs=performance.now()-b,N(C),R(A=>[...A.slice(-9),{query:p,result:C}]),C}catch(u){const h=u instanceof Error?u.message:"AI request failed",$={type:"filter",error:h,latencyMs:performance.now()-b};return N($),s==null||s(h),$}finally{m(!1)}},[I,_,r,n,s]),k=d.useCallback(()=>{x(null),N(null)},[]),y=d.useCallback(()=>{var p;(p=j.current)==null||p.abort(),m(!1)},[]);return d.useEffect(()=>()=>{var p;(p=j.current)==null||p.abort()},[]),{processQuery:o,loading:l,lastQuery:g,lastResult:w,history:S,clearResults:k,abort:y,isConfigured:!!I}}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)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.filters&&Array.isArray(l.filters))return{filters:l.filters,logic:l.logic||"and",confidence:l.confidence,explanation:l.explanation}}catch{}return null}function hi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.sort&&Array.isArray(l.sort))return{sort:l.sort,confidence:l.confidence}}catch{}return null}function gi({columns:t,config:a,onFilter:i,onSort:r,placeholder:n='Ask AI to filter or sort data... (e.g., "show orders from last week")',showHistory:s=!0,showSuggestions:c=!0,className:l,style:m}){const[g,x]=d.useState(""),[w,N]=d.useState(!1),S=d.useRef(null),{processQuery:R,loading:j,lastResult:I,history:_,isConfigured:o}=pa({columns:t,config:a,onFilterGenerated:i,onSortGenerated:r}),k=d.useMemo(()=>{if(!c||t.length===0)return[];const u=[],h=t.filter(A=>A.type==="string");h.length>0&&u.push(`Show ${h[0].label}s containing "example"`);const $=t.filter(A=>A.type==="number");$.length>0&&(u.push(`${$[0].label} greater than 100`),u.push(`Sort by highest ${$[0].label}`));const E=t.filter(A=>A.type==="date");E.length>0&&(u.push(`${E[0].label} in the last 7 days`),u.push(`Sort by newest ${E[0].label}`));const C=t.filter(A=>{var O;return A.type==="enum"&&((O=A.options)==null?void 0:O.length)});return C.length>0&&C[0].options&&u.push(`Where ${C[0].label} is ${C[0].options[0]}`),u.slice(0,5)},[t,c]),y=async()=>{!g.trim()||j||(await R(g.trim()),N(!1))},p=u=>{u.key==="Enter"?(u.preventDefault(),y()):u.key==="Escape"&&N(!1)},b=u=>{var h;x(u),N(!1),(h=S.current)==null||h.focus()},v=u=>{x(u),N(!1),R(u)};return o?e.jsxs("div",{className:`nice-datagrid-ai ${l||""}`,style:m,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx(L.NiceIcon,{name:"search",size:16})}),e.jsx("input",{ref:S,type:"text",value:g,onChange:u=>x(u.target.value),onKeyDown:p,onFocus:()=>N(!0),onBlur:()=>setTimeout(()=>N(!1),200),placeholder:n,className:"nice-datagrid-ai__input",disabled:j,"aria-label":"AI query input"}),j?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:y,className:"nice-datagrid-ai__submit",disabled:!g.trim(),"aria-label":"Submit query",children:e.jsx(L.NiceIcon,{name:"send",size:16})})]}),w&&(k.length>0||s&&_.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[c&&k.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Suggestions"}),k.map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>b(u),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(L.NiceIcon,{name:"lightbulb",size:14})}),u]},h))]}),s&&_.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Recent"}),_.slice(-5).reverse().map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>v(u.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(L.NiceIcon,{name:"clock",size:14})}),u.query,u.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx(L.NiceIcon,{name:"warning",size:14})})]},h))]})]}),I&&!I.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[I.filterConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:[I.filterConfig.filters.length," filter",I.filterConfig.filters.length!==1?"s":""," applied"]}),I.sortConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:["Sorted by ",I.sortConfig.sort.map(u=>u.column).join(", ")]}),I.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(I.latencyMs),"ms"]})]}),(I==null?void 0:I.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:I.error}),e.jsx("style",{children:`
|
|
355
|
+
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},ge={[se.id]:se,[ce.id]:ce,[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[pe.id]:pe,[we.id]:we,[je.id]:je,[ke.id]:ke,[Ne.id]:Ne};function li(t){return ge[t]}function di(t){return Object.values(ge).filter(a=>a.category===t)}function ui(){return Object.keys(ge)}class Me{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 la{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],c=Date.now()-720*60*60*1e3,l=s.filter(p=>p.timestamp>c);localStorage.setItem(r,JSON.stringify(l))}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(c=>!(i&&c.timestamp<i.getTime()||r&&c.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 da{constructor(a,i){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new Me,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),c=await this.storage.load(a,n),l=s.reduce((z,k)=>z+k.estimatedCost,0),p=c.reduce((z,k)=>z+k.estimatedCost,0),f=this.budgetConfig.dailyBudget||1/0,g=this.budgetConfig.monthlyBudget||1/0,y=f?l/f*100:0,w=g?p/g*100:0,S=[];for(const z of this.budgetConfig.alertThresholds||[])y>=z&&S.push(`Daily budget ${z}% used`),w>=z&&S.push(`Monthly budget ${z}% used`);return{dailyUsed:l,dailyRemaining:Math.max(0,f-l),dailyPercent:y,monthlyUsed:p,monthlyRemaining:Math.max(0,g-p),monthlyPercent:w,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:l>=f||p>=g,alerts:S}}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 c=0,l=0;for(const p of n){s.totalTokens+=p.totalTokens,s.totalPromptTokens+=p.promptTokens,s.totalCompletionTokens+=p.completionTokens,s.totalCost+=p.estimatedCost,c+=p.latencyMs,p.error&&s.errorCount++,p.cached&&l++,s.byModel[p.model]||(s.byModel[p.model]={requests:0,tokens:0,cost:0}),s.byModel[p.model].requests++,s.byModel[p.model].tokens+=p.totalTokens,s.byModel[p.model].cost+=p.estimatedCost;const f=p.feature||"unknown";s.byFeature[f]||(s.byFeature[f]={requests:0,tokens:0,cost:0}),s.byFeature[f].requests++,s.byFeature[f].tokens+=p.totalTokens,s.byFeature[f].cost+=p.estimatedCost;const g=new Date(p.timestamp).toISOString().split("T")[0];s.byDay[g]||(s.byDay[g]={requests:0,tokens:0,cost:0}),s.byDay[g].requests++,s.byDay[g].tokens+=p.totalTokens,s.byDay[g].cost+=p.estimatedCost}return n.length>0&&(s.averageLatency=c/n.length,s.cacheHitRate=l/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(l=>l>r));const s=new Date().toISOString().split("T")[0],c=`${a}:${s}`;this.dayCounter.set(c,(this.dayCounter.get(c)||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 pi(t,a){const i=d.useRef(null),[r,n]=d.useState(null),[s,c]=d.useState(null),[l,p]=d.useState(!0);d.useEffect(()=>{const w=typeof window<"u"?new la:new Me;i.current=new da(w,a);const S=i.current.onAlert(z=>{console.warn(`[AI Cost Alert] ${z}`)});return()=>{S()}},[]);const f=d.useCallback(async()=>{if(i.current){p(!0);try{const[w,S]=await Promise.all([i.current.getBudgetStatus(t),i.current.getUsageStats(t)]);n(w),c(S)}finally{p(!1)}}},[t]);d.useEffect(()=>{f()},[f]);const g=d.useCallback(async w=>{i.current&&(await i.current.recordUsage(t,w),await f())},[t,f]),y=d.useCallback(async()=>i.current?i.current.canMakeRequest(t):{allowed:!0},[t]);return{status:r,stats:s,loading:l,recordUsage:g,canMakeRequest:y,refresh:f}}class mi{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 ua{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 mi(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 c=await this.executeStrategy(s,a,i);if(c)return(n=(r=this.config).onFallback)==null||n.call(r,s,i),c}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 pa(t,a){const i=ae(t);return new ua(i,a)}function hi(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"}),pa(t,i)}function ma(t){const{columns:a,config:i,onFilterGenerated:r,onSortGenerated:n,onError:s}=t,c=Z(),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState(null),[S,z]=d.useState([]),k=d.useRef(null),I=i||(c==null?void 0:c.config),j=d.useMemo(()=>a.map(m=>({id:m.id,label:m.label,type:m.type,...m.options?{options:m.options}:{}})),[a]),o=d.useCallback(async m=>{var x;if(!I){const u="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(u),{type:"filter",error:u}}p(!0),g(m);const v=performance.now();(x=k.current)==null||x.abort(),k.current=new AbortController;try{const u=K(I),h=m.toLowerCase(),$=h.includes("sort")||h.includes("order")||h.includes("arrange")||h.includes("by highest")||h.includes("by lowest"),D=h.includes("show")||h.includes("find")||h.includes("filter")||h.includes("where")||h.includes("with")||h.includes("only")||!$,C={type:"combined"};if(D){const A=ie(se,{columns:j,query:m}),O=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.2,maxTokens:512}),B=gi(O);B&&(C.filterConfig=B,C.type="filter",r==null||r(B))}if($){const A=ie(ce,{columns:j,query:m}),O=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.1,maxTokens:256}),B=fi(O);B&&(C.sortConfig=B,C.type=C.filterConfig?"combined":"sort",n==null||n(B))}return C.latencyMs=performance.now()-v,w(C),z(A=>[...A.slice(-9),{query:m,result:C}]),C}catch(u){const h=u instanceof Error?u.message:"AI request failed",$={type:"filter",error:h,latencyMs:performance.now()-v};return w($),s==null||s(h),$}finally{p(!1)}},[I,j,r,n,s]),N=d.useCallback(()=>{g(null),w(null)},[]),_=d.useCallback(()=>{var m;(m=k.current)==null||m.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var m;(m=k.current)==null||m.abort()},[]),{processQuery:o,loading:l,lastQuery:f,lastResult:y,history:S,clearResults:N,abort:_,isConfigured:!!I}}function gi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.filters&&Array.isArray(l.filters))return{filters:l.filters,logic:l.logic||"and",confidence:l.confidence,explanation:l.explanation}}catch{}return null}function fi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.sort&&Array.isArray(l.sort))return{sort:l.sort,confidence:l.confidence}}catch{}return null}function xi({columns:t,config:a,onFilter:i,onSort:r,placeholder:n='Ask AI to filter or sort data... (e.g., "show orders from last week")',showHistory:s=!0,showSuggestions:c=!0,className:l,style:p}){const[f,g]=d.useState(""),[y,w]=d.useState(!1),S=d.useRef(null),{processQuery:z,loading:k,lastResult:I,history:j,isConfigured:o}=ma({columns:t,config:a,onFilterGenerated:i,onSortGenerated:r}),N=d.useMemo(()=>{if(!c||t.length===0)return[];const u=[],h=t.filter(A=>A.type==="string");h.length>0&&u.push(`Show ${h[0].label}s containing "example"`);const $=t.filter(A=>A.type==="number");$.length>0&&(u.push(`${$[0].label} greater than 100`),u.push(`Sort by highest ${$[0].label}`));const D=t.filter(A=>A.type==="date");D.length>0&&(u.push(`${D[0].label} in the last 7 days`),u.push(`Sort by newest ${D[0].label}`));const C=t.filter(A=>{var O;return A.type==="enum"&&((O=A.options)==null?void 0:O.length)});return C.length>0&&C[0].options&&u.push(`Where ${C[0].label} is ${C[0].options[0]}`),u.slice(0,5)},[t,c]),_=async()=>{!f.trim()||k||(await z(f.trim()),w(!1))},m=u=>{u.key==="Enter"?(u.preventDefault(),_()):u.key==="Escape"&&w(!1)},v=u=>{var h;g(u),w(!1),(h=S.current)==null||h.focus()},x=u=>{g(u),w(!1),z(u)};return o?e.jsxs("div",{className:`nice-datagrid-ai ${l||""}`,style:p,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx(L.NiceIcon,{name:"search",size:16})}),e.jsx("input",{ref:S,type:"text",value:f,onChange:u=>g(u.target.value),onKeyDown:m,onFocus:()=>w(!0),onBlur:()=>setTimeout(()=>w(!1),200),placeholder:n,className:"nice-datagrid-ai__input",disabled:k,"aria-label":"AI query input"}),k?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:_,className:"nice-datagrid-ai__submit",disabled:!f.trim(),"aria-label":"Submit query",children:e.jsx(L.NiceIcon,{name:"send",size:16})})]}),y&&(N.length>0||s&&j.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[c&&N.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Suggestions"}),N.map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>v(u),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(L.NiceIcon,{name:"lightbulb",size:14})}),u]},h))]}),s&&j.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Recent"}),j.slice(-5).reverse().map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>x(u.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(L.NiceIcon,{name:"clock",size:14})}),u.query,u.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx(L.NiceIcon,{name:"warning",size:14})})]},h))]})]}),I&&!I.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[I.filterConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:[I.filterConfig.filters.length," filter",I.filterConfig.filters.length!==1?"s":""," applied"]}),I.sortConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:["Sorted by ",I.sortConfig.sort.map(u=>u.column).join(", ")]}),I.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(I.latencyMs),"ms"]})]}),(I==null?void 0:I.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:I.error}),e.jsx("style",{children:`
|
|
356
356
|
.nice-datagrid-ai {
|
|
357
357
|
position: relative;
|
|
358
358
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
@@ -368,7 +368,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
368
368
|
gap: var(--nice-space-2, 8px);
|
|
369
369
|
padding: var(--nice-space-2, 8px) var(--nice-space-3, 12px);
|
|
370
370
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
371
|
-
border-radius: var(--nice-
|
|
371
|
+
border-radius: var(--nice-radius-lg, 8px);
|
|
372
372
|
background: var(--nice-input-bg, #fff);
|
|
373
373
|
transition: border-color 0.2s, box-shadow 0.2s;
|
|
374
374
|
}
|
|
@@ -442,9 +442,9 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
442
442
|
left: 0;
|
|
443
443
|
right: 0;
|
|
444
444
|
margin-top: var(--nice-space-1, 4px);
|
|
445
|
-
background: var(--nice-
|
|
445
|
+
background: var(--nice-bg-elevated, #fff);
|
|
446
446
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
447
|
-
border-radius: var(--nice-
|
|
447
|
+
border-radius: var(--nice-radius-lg, 8px);
|
|
448
448
|
box-shadow: 0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1));
|
|
449
449
|
z-index: 100;
|
|
450
450
|
max-height: 300px;
|
|
@@ -512,12 +512,12 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
512
512
|
}
|
|
513
513
|
|
|
514
514
|
.nice-datagrid-ai__badge--filter {
|
|
515
|
-
background: var(--nice-info-
|
|
515
|
+
background: var(--nice-info-bg, #e3f2fd);
|
|
516
516
|
color: var(--nice-info, #1976d2);
|
|
517
517
|
}
|
|
518
518
|
|
|
519
519
|
.nice-datagrid-ai__badge--sort {
|
|
520
|
-
background: var(--nice-success-
|
|
520
|
+
background: var(--nice-success-bg, #e8f5e9);
|
|
521
521
|
color: var(--nice-success, #2e7d32);
|
|
522
522
|
}
|
|
523
523
|
|
|
@@ -529,18 +529,18 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
529
529
|
.nice-datagrid-ai__error {
|
|
530
530
|
margin-top: var(--nice-space-2, 8px);
|
|
531
531
|
padding: var(--nice-space-2, 8px) var(--nice-space-3, 12px);
|
|
532
|
-
background: var(--nice-
|
|
532
|
+
background: var(--nice-danger-bg, #ffebee);
|
|
533
533
|
color: var(--nice-error, #c62828);
|
|
534
534
|
border-radius: var(--nice-radius-sm, 4px);
|
|
535
535
|
font-size: 13px;
|
|
536
536
|
}
|
|
537
|
-
`})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${l||""}`,style:
|
|
537
|
+
`})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${l||""}`,style:p,children:e.jsx("input",{type:"text",placeholder:"AI not configured",disabled:!0,className:"nice-datagrid-ai__input"})})}function ha(t={}){const{config:a,schema:i,context:r,onFormGenerated:n,onError:s}=t,c=Z(),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState(null),[S,z]=d.useState([]),k=d.useRef(null),I=a||(c==null?void 0:c.config),j=d.useCallback(async m=>{var x,u,h;if(!I){const $="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s($),{error:$}}p(!0),g(m);const v=performance.now();(x=k.current)==null||x.abort(),k.current=new AbortController;try{const $=K(I),D=ie(oe,{description:m,schema:i?JSON.stringify(i,null,2):void 0,context:r}),C=await $.chat({messages:[{role:"system",content:D.system},{role:"user",content:D.user}],temperature:.5,maxTokens:2048}),A=bi(C),O={config:A||void 0,rawResponse:(h=(u=C.choices[0])==null?void 0:u.message)==null?void 0:h.content,latencyMs:performance.now()-v,error:A?void 0:"Failed to parse form configuration"};return A&&(n==null||n(A)),w(O),z(B=>[...B.slice(-9),{description:m,result:O}]),O}catch($){const D=$ instanceof Error?$.message:"AI request failed",C={error:D,latencyMs:performance.now()-v};return w(C),s==null||s(D),C}finally{p(!1)}},[I,i,r,n,s]),o=d.useCallback(async m=>{if(!(y!=null&&y.config))return{error:"No form to refine. Generate a form first."};const v=`
|
|
538
538
|
Modify this existing form based on the following instructions:
|
|
539
539
|
|
|
540
|
-
Current form: ${JSON.stringify(
|
|
540
|
+
Current form: ${JSON.stringify(y.config,null,2)}
|
|
541
541
|
|
|
542
|
-
Instructions: ${
|
|
543
|
-
`;return
|
|
542
|
+
Instructions: ${m}
|
|
543
|
+
`;return j(v)},[y,j]),N=d.useCallback(()=>{g(null),w(null)},[]),_=d.useCallback(()=>{var m;(m=k.current)==null||m.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var m;(m=k.current)==null||m.abort()},[]),{generateForm:j,refineForm:o,loading:l,lastDescription:f,lastResult:y,history:S,clearResults:N,abort:_,isConfigured:!!I}}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)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.fields&&Array.isArray(l.fields))return{title:l.title,description:l.description,fields:l.fields,layout:l.layout,submitLabel:l.submitLabel,validation:l.validation}}catch{}return null}function yi({config:t,schema:a,context:i,onGenerate:r,placeholder:n='Describe the form you want to create... (e.g., "Contact form with name, email, subject, and message")',showExamples:s=!0,showPreview:c=!0,className:l,style:p,renderForm:f}){const[g,y]=d.useState(""),[w,S]=d.useState(!1),z=d.useRef(null),{generateForm:k,loading:I,lastResult:j,isConfigured:o}=ha({config:t,schema:a,context:i,onFormGenerated:r}),N=["Simple contact form with name, email, and message","User registration with email validation and password confirmation","Product feedback survey with rating scale and comments","Event RSVP with name, attending status, and dietary restrictions","Job application with personal info, experience, and file upload","Newsletter subscription with email and preferences"],_=async()=>{!g.trim()||I||await k(g.trim())},m=u=>{var h;y(u),S(!1),(h=z.current)==null||h.focus()},v=u=>{u.key==="Enter"&&(u.ctrlKey||u.metaKey)&&(u.preventDefault(),_())},x=u=>{y(u.target.value),u.target.style.height="auto",u.target.style.height=Math.min(u.target.scrollHeight,200)+"px"};return o?e.jsxs("div",{className:`nice-form-builder-ai ${l||""}`,style:p,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(L.NiceIcon,{name:"wand",size:16})}),"Describe your form"]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{ref:z,value:g,onChange:x,onKeyDown:v,placeholder:n,className:"nice-form-builder-ai__textarea",disabled:I,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:()=>S(!w),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--secondary",children:"Examples"}),w&&e.jsx("div",{className:"nice-form-builder-ai__dropdown",children:N.map((u,h)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>m(u),children:u},h))})]}),e.jsx("button",{type:"button",onClick:_,disabled:!g.trim()||I,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:I?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"rocket",size:14}),"Generate Form"]})})]})]}),e.jsxs("p",{className:"nice-form-builder-ai__hint",children:["Press ",e.jsx("kbd",{children:"Ctrl"}),"+",e.jsx("kbd",{children:"Enter"})," to generate"]})]}),j&&e.jsx("div",{className:"nice-form-builder-ai__result",children:j.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:"Error:"})," ",j.error]}):j.config&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-form-builder-ai__result-header",children:[e.jsxs("h3",{className:"nice-form-builder-ai__result-title",children:["Generated Form: ",j.config.title||"Untitled"]}),j.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(j.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(j.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:"Use This Form"})]}),j.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:j.config.description}),c&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:f?f(j.config):e.jsx(vi,{config:j.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:"View JSON Configuration"}),e.jsx("pre",{children:JSON.stringify(j.config,null,2)})]})]})}),e.jsx("style",{children:`
|
|
544
544
|
.nice-form-builder-ai {
|
|
545
545
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
546
546
|
}
|
|
@@ -749,7 +749,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
749
749
|
.nice-form-builder-ai__json pre {
|
|
750
750
|
margin: var(--nice-space-2, 8px) 0 0;
|
|
751
751
|
padding: var(--nice-space-3, 12px);
|
|
752
|
-
background: var(--nice-
|
|
752
|
+
background: var(--nice-bg-tertiary, #f5f5f5);
|
|
753
753
|
border-radius: var(--nice-radius-md, 6px);
|
|
754
754
|
font-size: 12px;
|
|
755
755
|
overflow-x: auto;
|
|
@@ -757,11 +757,11 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
757
757
|
|
|
758
758
|
.nice-form-builder-ai__error {
|
|
759
759
|
padding: var(--nice-space-3, 12px);
|
|
760
|
-
background: var(--nice-
|
|
760
|
+
background: var(--nice-danger-bg, #ffebee);
|
|
761
761
|
color: var(--nice-error, #c62828);
|
|
762
762
|
border-radius: var(--nice-radius-md, 6px);
|
|
763
763
|
}
|
|
764
|
-
`})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${l||""}`,style:
|
|
764
|
+
`})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${l||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function vi({config:t}){var r,n;const a=s=>{var l,p;const c={id:s.id,placeholder:s.placeholder,required:s.required,disabled:!0};switch(s.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.jsxs("option",{value:"",children:["Select ",s.label,"..."]}),(l=s.options)==null?void 0:l.map(f=>e.jsx("option",{value:f.value,children:f.label},f.value))]});case"radio":return e.jsx("div",{className:"nice-form-preview__radio-group",children:(p=s.options)==null?void 0:p.map(f=>e.jsxs("label",{className:"nice-form-preview__radio",children:[e.jsx("input",{type:"radio",name:s.id,value:f.value,disabled:!0}),f.label]},f.value))});case"checkbox":return e.jsxs("label",{className:"nice-form-preview__checkbox",children:[e.jsx("input",{type:"checkbox",disabled:!0}),s.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"})}},i=((r=t.layout)==null?void 0:r.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":i},children:[(n=t.layout)!=null&&n.sections?t.layout.sections.map((s,c)=>e.jsxs("fieldset",{className:"nice-form-preview__section",children:[s.title&&e.jsx("legend",{children:s.title}),s.description&&e.jsx("p",{className:"nice-form-preview__section-desc",children:s.description}),e.jsx("div",{className:"nice-form-preview__grid",children:s.fields.map(l=>{const p=t.fields.find(f=>f.id===l);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:"*"})]}),a(p)]},p.id):null})})]},c)):e.jsx("div",{className:"nice-form-preview__grid",children:t.fields.map(s=>e.jsxs("div",{className:"nice-form-preview__field",children:[s.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[s.label,s.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),a(s)]},s.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||"Submit"})}),e.jsx("style",{children:`
|
|
765
765
|
.nice-form-preview {
|
|
766
766
|
--columns: 1;
|
|
767
767
|
}
|
|
@@ -866,7 +866,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
866
866
|
cursor: not-allowed;
|
|
867
867
|
opacity: 0.7;
|
|
868
868
|
}
|
|
869
|
-
`})]})}function
|
|
869
|
+
`})]})}function ga(t={}){const{config:a,dataFields:i,context:r,onChartGenerated:n,onError:s}=t,c=Z(),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState(null),[S,z]=d.useState([]),k=d.useRef(null),I=a||(c==null?void 0:c.config),j=d.useMemo(()=>{if(i)return i.map(v=>{var x;return{name:v.name,type:v.type,label:v.label||v.name,...(x=v.sampleValues)!=null&&x.length?{samples:v.sampleValues.slice(0,3)}:{}}})},[i]),o=d.useCallback(async v=>{var u,h,$;if(!I){const D="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(D),{error:D}}p(!0),g(v);const x=performance.now();(u=k.current)==null||u.abort(),k.current=new AbortController;try{const D=K(I),C=ie(le,{request:v,data:j?JSON.stringify(j,null,2):void 0,context:r}),A=await D.chat({messages:[{role:"system",content:C.system},{role:"user",content:C.user}],temperature:.4,maxTokens:1024}),O=_i(A),B={config:O||void 0,rawResponse:($=(h=A.choices[0])==null?void 0:h.message)==null?void 0:$.content,latencyMs:performance.now()-x,error:O?void 0:"Failed to parse chart configuration",suggestions:wi(O)};return O&&(n==null||n(O)),w(B),z(b=>[...b.slice(-9),{request:v,result:B}]),B}catch(D){const C=D instanceof Error?D.message:"AI request failed",A={error:C,latencyMs:performance.now()-x};return w(A),s==null||s(C),A}finally{p(!1)}},[I,j,r,n,s]),N=d.useCallback(async()=>y!=null&&y.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"]}[y.config.type]||[]:[],[y]),_=d.useCallback(()=>{g(null),w(null)},[]),m=d.useCallback(()=>{var v;(v=k.current)==null||v.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var v;(v=k.current)==null||v.abort()},[]),{generateChart:o,suggestAlternatives:N,loading:l,lastRequest:f,lastResult:y,history:S,clearResults:_,abort:m,isConfigured:!!I}}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)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.type)return{type:l.type,title:l.title,subtitle:l.subtitle,data:l.data||{},xAxis:l.xAxis,yAxis:l.yAxis,options:l.options}}catch{}return null}function wi(t){var i;if(!t)return[];const a=[];return(t.type==="line"||t.type==="bar")&&(a.push("Add trend line for forecasting"),a.push("Stack series for comparison")),(t.type==="pie"||t.type==="donut")&&(a.push("Convert to bar chart for better comparison"),a.push("Add data labels for percentages")),(i=t.options)!=null&&i.animation||a.push("Enable animations for better UX"),a.slice(0,3)}function ji({config:t,dataFields:a,context:i,onGenerate:r,placeholder:n='Describe the chart you want... (e.g., "Show monthly sales as a line chart")',showTypeSelector:s=!0,showPreview:c=!0,className:l,style:p,renderChart:f}){const[g,y]=d.useState(""),[w,S]=d.useState(null),z=d.useRef(null),{generateChart:k,suggestAlternatives:I,loading:j,lastResult:o,isConfigured:N}=ga({config:t,dataFields:a,context:i,onChartGenerated:r}),_=[{type:"line",icon:"line",label:"Line"},{type:"bar",icon:"bar-chart",label:"Bar"},{type:"pie",icon:"circle",label:"Pie"},{type:"area",icon:"bar-chart",label:"Area"},{type:"scatter",icon:"grid",label:"Scatter"},{type:"donut",icon:"circle",label:"Donut"},{type:"heatmap",icon:"grid",label:"Heatmap"},{type:"funnel",icon:"filter",label:"Funnel"},{type:"gauge",icon:"target",label:"Gauge"},{type:"radar",icon:"target",label:"Radar"}],m=async()=>{if(!g.trim()||j)return;const h=w?`Create a ${w} chart: ${g}`:g;await k(h)},v=h=>{h.key==="Enter"&&(h.preventDefault(),m())},x=h=>{S(w===h?null:h)},u=async h=>{if(!(o!=null&&o.config))return;const $={...o.config,type:h};r==null||r($)};return N?e.jsxs("div",{className:`nice-chart-ai ${l||""}`,style:p,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:_.map(({type:h,icon:$,label:D})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${w===h?"nice-chart-ai__type--selected":""}`,onClick:()=>x(h),title:D,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:e.jsx(L.NiceIcon,{name:$,size:20})}),e.jsx("span",{className:"nice-chart-ai__type-label",children:D})]},h))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:e.jsx(L.NiceIcon,{name:"bar-chart",size:18})}),e.jsx("input",{ref:z,type:"text",value:g,onChange:h=>y(h.target.value),onKeyDown:v,placeholder:n,className:"nice-chart-ai__input",disabled:j}),j?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:m,className:"nice-chart-ai__submit",disabled:!g.trim(),children:"Generate"})]}),a&&a.length>0&&e.jsxs("div",{className:"nice-chart-ai__fields",children:[e.jsx("span",{className:"nice-chart-ai__fields-label",children:"Available fields:"}),a.map(h=>e.jsx("span",{className:"nice-chart-ai__field-badge",title:h.type,children:h.label||h.name},h.name))]}),o&&e.jsx("div",{className:"nice-chart-ai__result",children:o.error?e.jsx("div",{className:"nice-chart-ai__error",children:o.error}):o.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 $;const h=($=_.find(D=>D.type===o.config.type))==null?void 0:$.icon;return h?e.jsx(L.NiceIcon,{name:h,size:16}):null})(),o.config.type.charAt(0).toUpperCase()+o.config.type.slice(1)," ","Chart"]}),o.config.title&&e.jsx("span",{className:"nice-chart-ai__chart-title",children:o.config.title})]}),o.latencyMs&&e.jsxs("span",{className:"nice-chart-ai__latency",children:[Math.round(o.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(o.config),className:"nice-chart-ai__use-btn",children:"Use This Chart"})]}),e.jsxs("div",{className:"nice-chart-ai__alternatives",children:[e.jsx("span",{children:"Try also:"}),_.filter(h=>h.type!==o.config.type).slice(0,4).map(({type:h,icon:$})=>e.jsx("button",{type:"button",className:"nice-chart-ai__alternative",onClick:()=>u(h),title:`Convert to ${h}`,"aria-label":`Convert to ${h}`,children:e.jsx(L.NiceIcon,{name:$,size:16})},h))]}),c&&e.jsx("div",{className:"nice-chart-ai__preview",children:f?f(o.config):e.jsx(ki,{config:o.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:"View Configuration"}),e.jsx("pre",{children:JSON.stringify(o.config,null,2)})]})]})}),e.jsx("style",{children:`
|
|
870
870
|
.nice-chart-ai {
|
|
871
871
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
872
872
|
}
|
|
@@ -1098,7 +1098,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
1098
1098
|
.nice-chart-ai__json pre {
|
|
1099
1099
|
margin: var(--nice-space-2, 8px) 0 0;
|
|
1100
1100
|
padding: var(--nice-space-3, 12px);
|
|
1101
|
-
background: var(--nice-
|
|
1101
|
+
background: var(--nice-bg-tertiary, #f5f5f5);
|
|
1102
1102
|
border-radius: var(--nice-radius-md, 6px);
|
|
1103
1103
|
font-size: 12px;
|
|
1104
1104
|
overflow-x: auto;
|
|
@@ -1106,11 +1106,11 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
1106
1106
|
|
|
1107
1107
|
.nice-chart-ai__error {
|
|
1108
1108
|
padding: var(--nice-space-3, 12px);
|
|
1109
|
-
background: var(--nice-
|
|
1109
|
+
background: var(--nice-danger-bg, #ffebee);
|
|
1110
1110
|
color: var(--nice-error, #c62828);
|
|
1111
1111
|
border-radius: var(--nice-radius-md, 6px);
|
|
1112
1112
|
}
|
|
1113
|
-
`})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${l||""}`,style:
|
|
1113
|
+
`})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${l||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function ki({config:t}){var i;const a=()=>{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:"rgba(33, 150, 243, 0.2)"}),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 r=t.type==="donut"?35:40,n=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,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:n,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(L.NiceIcon,{name:"bar-chart",size:32})}),e.jsxs("span",{children:[t.type.charAt(0).toUpperCase()+t.type.slice(1)," Chart"]})]})}};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:a()}),((i=t.options)==null?void 0:i.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)"}}),"Series 1"]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-primary, #2196f3)"}}),"Series 2"]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-warning, #ff9800)"}}),"Series 3"]})]}),e.jsx("style",{children:`
|
|
1114
1114
|
.nice-chart-preview {
|
|
1115
1115
|
text-align: center;
|
|
1116
1116
|
}
|
|
@@ -1171,11 +1171,11 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
1171
1171
|
height: 12px;
|
|
1172
1172
|
border-radius: var(--nice-radius-sm, 2px);
|
|
1173
1173
|
}
|
|
1174
|
-
`})]})}function
|
|
1175
|
-
`),
|
|
1176
|
-
`),G=
|
|
1177
|
-
`),Y=
|
|
1178
|
-
`).filter(l=>l.trim()).slice(0,i).map((l,
|
|
1174
|
+
`})]})}function fa(t={}){const{config:a,language:i="typescript",context:r,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:c,onError:l}=t,p=Z(),[f,g]=d.useState(!1),[y,w]=d.useState([]),[S,z]=d.useState(-1),k=d.useRef(null),I=d.useRef(null),j=a||(p==null?void 0:p.config),o=d.useCallback(async(C,A)=>{var B,b,P;if(!j)return{suggestions:[],error:"AI not configured"};g(!0),(B=k.current)==null||B.abort(),k.current=new AbortController;const O=performance.now();try{const H=K(j),J=C.split(`
|
|
1175
|
+
`),M=J[A.line]||"",U=M.substring(0,A.column),q=M.substring(A.column),W=J.slice(Math.max(0,A.line-20),A.line).join(`
|
|
1176
|
+
`),G=J.slice(A.line+1,A.line+10).join(`
|
|
1177
|
+
`),Y=ie(de,{language:i,code_context:W,prefix:U,suffix:q,context_after:G,context:r}),ee=await H.chat({messages:[{role:"system",content:Y.system},{role:"user",content:Y.user}],temperature:.2,maxTokens:512}),Q=Ni(ee,A,n),T={suggestions:Q,rawResponse:(P=(b=ee.choices[0])==null?void 0:b.message)==null?void 0:P.content,latencyMs:performance.now()-O};return w(Q),z(Q.length>0?0:-1),c==null||c(Q),T}catch(H){const J=H instanceof Error?H.message:"Completion failed";return l==null||l(J),{suggestions:[],error:J,latencyMs:performance.now()-O}}finally{g(!1)}},[j,i,r,n,c,l]),N=d.useCallback((C,A)=>{I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{o(C,A)},s)},[o,s]),_=d.useCallback(async C=>{if(!j)return null;g(!0);try{const O=await K(j).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:C}],temperature:.3,maxTokens:1024});return Ci(O)}catch{return null}finally{g(!1)}},[j,i]),m=d.useCallback(async C=>{if(!j)return[];g(!0);try{const O=await K(j).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:C}],temperature:.4,maxTokens:2048});return Si(O)}catch{return[]}finally{g(!1)}},[j,i]),v=d.useCallback(async(C,A)=>{var O,B;if(!j)return null;g(!0);try{const b=K(j),P=A||Ti(i);return((B=(O=(await b.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${i} code using ${P}. Include edge cases and error scenarios. Return only the test code.`},{role:"user",content:C}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:O.message)==null?void 0:B.content)||null}catch{return null}finally{g(!1)}},[j,i]),x=d.useCallback(async(C,A)=>{var O,B;if(!j)return null;g(!0);try{const b=K(j),P=A||Ai(i);return((B=(O=(await b.chat({messages:[{role:"system",content:`Generate ${P} documentation for the following ${i} code. Include descriptions for parameters, return values, and examples where appropriate. Return only the documented code.`},{role:"user",content:C}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:O.message)==null?void 0:B.content)||null}catch{return null}finally{g(!1)}},[j,i]),u=d.useCallback((C=S)=>{const A=y[C];return w([]),z(-1),A},[y,S]),h=d.useCallback(()=>{w([]),z(-1)},[]),$=d.useCallback(C=>{y.length!==0&&z(A=>C==="up"?A<=0?y.length-1:A-1:A>=y.length-1?0:A+1)},[y.length]),D=d.useCallback(()=>{var C;(C=k.current)==null||C.abort(),I.current&&clearTimeout(I.current),g(!1)},[]);return d.useEffect(()=>()=>{var C;(C=k.current)==null||C.abort(),I.current&&clearTimeout(I.current)},[]),{getCompletions:o,getCompletionsDebounced:N,suggestions:y,activeSuggestion:S,acceptSuggestion:u,dismissSuggestions:h,navigateSuggestions:$,explainCode:_,suggestRefactoring:m,generateTests:v,generateDocs:x,loading:f,abort:D,isConfigured:!!j}}function Ni(t,a,i){var r,n;try{return(((n=(r=t.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"").split(`
|
|
1178
|
+
`).filter(l=>l.trim()).slice(0,i).map((l,p)=>({id:`suggestion-${Date.now()}-${p}`,text:l.trim(),type:"inline",preview:l.trim().slice(0,50),confidence:.8-p*.1,insertPosition:a}))}catch{return[]}}function Ci(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 Si(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 Ti(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 Ai(t){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[t]||"jsdoc"}function Ri({code:t="",language:a="typescript",config:i,onChange:r,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:c=!0,placeholder:l="Start typing code...",className:p,style:f,renderEditor:g}){const[y,w]=d.useState(t),[S,z]=d.useState(null),[k,I]=d.useState(null),[j,o]=d.useState([]),[N,_]=d.useState(null),[m,v]=d.useState(null),x=d.useRef(null),{getCompletionsDebounced:u,suggestions:h,activeSuggestion:$,acceptSuggestion:D,dismissSuggestions:C,navigateSuggestions:A,explainCode:O,suggestRefactoring:B,generateTests:b,generateDocs:P,loading:H,isConfigured:J}=fa({config:i,language:a}),M=R=>{if(w(R),r==null||r(R),c&&x.current){const F=Ii(x.current);u(R,F)}},U=R=>{if(h.length>0)if(R.key==="ArrowUp")R.preventDefault(),A("up");else if(R.key==="ArrowDown")R.preventDefault(),A("down");else if(R.key==="Tab"||R.key==="Enter"){if($>=0){R.preventDefault();const F=D($);F&&(q(F),n==null||n(F))}}else R.key==="Escape"&&C()},q=R=>{if(!x.current)return;const F=x.current,V=F.selectionStart,re=y.slice(0,V)+R.text+y.slice(V);w(re),r==null||r(re);const Le=V+R.text.length;setTimeout(()=>{F.focus(),F.setSelectionRange(Le,Le)},0)},W=async()=>{const R=S||y;if(!R.trim())return;v("explain");const F=await O(R);I(F)},G=async()=>{const R=S||y;if(!R.trim())return;v("refactor");const F=await B(R);o(F)},Y=async()=>{if(!y.trim())return;v("tests");const R=await b(y);_(R)},ee=async()=>{if(!y.trim())return;v("docs");const R=await P(y);_(R)},Q=R=>{const F=y.replace(R.before,R.after);w(F),r==null||r(F),v(null)},T=()=>{N&&navigator.clipboard.writeText(N)},E=()=>{if(x.current){const R=x.current.selectionStart,F=x.current.selectionEnd;z(R!==F?y.slice(R,F):null)}};return J?g?e.jsx("div",{className:`nice-code-editor-ai ${p||""}`,style:f,children:g({code:y,onChange:M,suggestions:h,onAccept:R=>{const F=D(R);F&&(n==null||n(F))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${p||""}`,style:f,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:H||!y.trim(),title:"Explain code",children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Explain"]}),e.jsxs("button",{type:"button",onClick:G,disabled:H||!y.trim(),title:"Suggest refactoring",children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Refactor"]}),e.jsxs("button",{type:"button",onClick:Y,disabled:H||!y.trim(),title:"Generate tests",children:[e.jsx(L.NiceIcon,{name:"flask",size:14})," Tests"]}),e.jsxs("button",{type:"button",onClick:ee,disabled:H||!y.trim(),title:"Generate docs",children:[e.jsx(L.NiceIcon,{name:"edit",size:14})," Docs"]})]}),H&&e.jsx("span",{className:"nice-code-editor-ai__loading",children:"Processing..."})]}),e.jsxs("div",{className:"nice-code-editor-ai__editor-wrapper",children:[e.jsx("textarea",{ref:x,value:y,onChange:R=>M(R.target.value),onKeyDown:U,onSelect:E,placeholder:l,className:"nice-code-editor-ai__textarea",spellCheck:!1}),h.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[h.map((R,F)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${F===$?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const V=D(F);V&&(q(V),n==null||n(V))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:R.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(R.confidence*100),"%"]})]},R.id)),e.jsxs("div",{className:"nice-code-editor-ai__suggestions-hint",children:[e.jsx(L.NiceIcon,{name:"arrow-up",size:11}),e.jsx(L.NiceIcon,{name:"arrow-down",size:11})," navigate • Tab accept • Esc dismiss"]})]})]}),m&&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:[m==="explain"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Explanation"]}),m==="refactor"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Refactoring Suggestions"]}),m==="tests"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"flask",size:14})," Generated Tests"]}),m==="docs"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"edit",size:14})," Generated Documentation"]})]}),e.jsx("button",{type:"button",onClick:()=>v(null),"aria-label":"Close panel",children:e.jsx(L.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[m==="explain"&&k&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:k.summary}),k.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:k.details}),k.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${k.complexity}`,children:["Complexity: ",k.complexity]}),k.suggestions&&k.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:k.suggestions.map((R,F)=>e.jsx("li",{children:R},F))})]}),m==="refactor"&&j.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:j.map((R,F)=>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:R.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${R.type}`,children:R.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:R.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:R.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:"After:"}),e.jsx("pre",{children:R.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>Q(R),children:"Apply"})]},F))}),(m==="tests"||m==="docs")&&N&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:N}),e.jsxs("button",{type:"button",onClick:T,children:[e.jsx(L.NiceIcon,{name:"clipboard",size:14})," Copy"]})]})]})]}),e.jsx("style",{children:`
|
|
1179
1179
|
.nice-code-editor-ai {
|
|
1180
1180
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
1181
1181
|
display: flex;
|
|
@@ -1374,17 +1374,17 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
1374
1374
|
}
|
|
1375
1375
|
|
|
1376
1376
|
.nice-code-editor-ai__complexity--low {
|
|
1377
|
-
background: var(--nice-success-
|
|
1377
|
+
background: var(--nice-success-bg, #e8f5e9);
|
|
1378
1378
|
color: var(--nice-success, #2e7d32);
|
|
1379
1379
|
}
|
|
1380
1380
|
|
|
1381
1381
|
.nice-code-editor-ai__complexity--medium {
|
|
1382
|
-
background: var(--nice-warning-
|
|
1382
|
+
background: var(--nice-warning-bg, #fff3e0);
|
|
1383
1383
|
color: var(--nice-warning, #f57c00);
|
|
1384
1384
|
}
|
|
1385
1385
|
|
|
1386
1386
|
.nice-code-editor-ai__complexity--high {
|
|
1387
|
-
background: var(--nice-
|
|
1387
|
+
background: var(--nice-danger-bg, #ffebee);
|
|
1388
1388
|
color: var(--nice-error, #c62828);
|
|
1389
1389
|
}
|
|
1390
1390
|
|
|
@@ -1481,11 +1481,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
|
|
|
1481
1481
|
border-radius: var(--nice-radius-md, 6px);
|
|
1482
1482
|
cursor: pointer;
|
|
1483
1483
|
}
|
|
1484
|
-
`})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${
|
|
1485
|
-
`);return{line:i.length-1,column:i[i.length-1].length}}function
|
|
1486
|
-
`),A=
|
|
1487
|
-
|
|
1488
|
-
|
|
1484
|
+
`})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${p||""}`,style:f,children:[e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."}),e.jsx("textarea",{value:y,onChange:R=>M(R.target.value),placeholder:l,className:"nice-code-editor-ai__textarea"})]})}function Ii(t){const i=t.value.substring(0,t.selectionStart).split(`
|
|
1485
|
+
`);return{line:i.length-1,column:i[i.length-1].length}}function xa(t={}){const{config:a,context:i,existingRoles:r,existingVariables:n,onWorkflowGenerated:s,onError:c}=t,l=Z(),[p,f]=d.useState(!1),[g,y]=d.useState(null),[w,S]=d.useState([]),z=d.useRef(null),k=a||(l==null?void 0:l.config),I=d.useCallback(async v=>{var u,h,$;if(!k){const D="AI not configured";return c==null||c(D),{error:D}}f(!0);const x=performance.now();(u=z.current)==null||u.abort(),z.current=new AbortController;try{const D=K(k),C=[i,r!=null&&r.length?`Available roles: ${r.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
|
|
1486
|
+
`),A=ie(ue,{description:C?`${v}
|
|
1487
|
+
|
|
1488
|
+
${C}`:v}),O=await D.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.5,maxTokens:2048}),B=De(O),b={workflow:B||void 0,rawResponse:($=(h=O.choices[0])==null?void 0:h.message)==null?void 0:$.content,latencyMs:performance.now()-x,error:B?void 0:"Failed to generate workflow",suggestions:Mi(B)};return B&&(s==null||s(B)),y(b),S(P=>[...P.slice(-9),{request:v,result:b}]),b}catch(D){const C=D instanceof Error?D.message:"Workflow generation failed",A={error:C,latencyMs:performance.now()-x};return y(A),c==null||c(C),A}finally{f(!1)}},[k,i,r,n,s,c]),j=d.useCallback(async v=>{if(!k)return{error:"AI not configured"};f(!0);const x=performance.now();try{const h=await K(k).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(v,null,2)}],temperature:.4,maxTokens:2048});return{workflow:De(h)||void 0,latencyMs:performance.now()-x}}catch(u){return{error:u instanceof Error?u.message:"Optimization failed"}}finally{f(!1)}},[k]),o=d.useCallback(async(v,x)=>{var u,h;if(!k)return[];f(!0);try{const $=K(k),D=v.nodes.find(B=>B.id===x),O=(((h=(u=(await $.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: ${v.name}
|
|
1489
|
+
Current node: ${(D==null?void 0:D.label)||x}
|
|
1490
|
+
Existing nodes: ${v.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxTokens:512})).choices[0])==null?void 0:u.message)==null?void 0:h.content)||"").match(/\[[\s\S]*\]/);if(O)return JSON.parse(O[0])}catch{}finally{f(!1)}return[]},[k]),N=d.useCallback(async v=>{var x,u;if(!k)return[];f(!0);try{const C=(((u=(x=(await K(k).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(v,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:x.message)==null?void 0:u.content)||"").match(/\[[\s\S]*\]/);if(C)return JSON.parse(C[0]).map(O=>`[${O.severity}] ${O.message}`)}catch{}finally{f(!1)}return[]},[k]),_=d.useCallback(()=>{y(null)},[]),m=d.useCallback(()=>{var v;(v=z.current)==null||v.abort(),f(!1)},[]);return d.useEffect(()=>()=>{var v;(v=z.current)==null||v.abort()},[]),{generateWorkflow:I,optimizeWorkflow:j,suggestNextStep:o,validateWorkflow:N,loading:p,lastResult:g,history:w,clearResults:_,abort:m,isConfigured:!!k}}function De(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.nodes&&Array.isArray(l.nodes)){const p={gateway:"gateway-exclusive",event:"event-intermediate"},f=l.nodes.map((w,S)=>({...w,id:w.id||`node_${S}`,label:w.label??w.name??w.id??`Step ${S+1}`,type:p[w.type]??w.type})),g=zi(f),y=f.map((w,S)=>({...w,position:w.position||g[S]}));return{id:l.id||`workflow_${Date.now()}`,name:l.name||"Generated Workflow",description:l.description,version:l.version||"1.0",nodes:y,edges:l.edges||[],lanes:l.lanes??l.swimlanes,variables:l.variables,metadata:l.metadata}}}catch{}return null}function ba(t){return t.type==="start"||t.type==="end"||t.type.startsWith("gateway")?40:Math.round((t.label??"").length*7.2+64)}function zi(t){let n=20,s=40;return t.map(c=>{const l=ba(c);n>20&&n+l>640&&(n=20,s+=110);const p={x:n,y:s};return n+=l+48,p})}function Mi(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 Li=["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 Pi({config:t,context:a,roles:i,onGenerate:r,placeholder:n='Describe the workflow process... (e.g., "Leave request with manager approval")',showExamples:s=!0,showPreview:c=!0,className:l,style:p,renderWorkflow:f}){const[g,y]=d.useState(""),[w,S]=d.useState([]),z=d.useRef(null),{generateWorkflow:k,validateWorkflow:I,loading:j,lastResult:o,isConfigured:N}=xa({config:t,context:a,existingRoles:i,onWorkflowGenerated:r}),_=async()=>{!g.trim()||j||await k(g)},m=u=>{var h;y(u),(h=z.current)==null||h.focus()},v=async()=>{if(!(o!=null&&o.workflow))return;const u=await I(o.workflow);S(u)},x=()=>{if(!(o!=null&&o.workflow))return;const u=Oi(o.workflow),h=new Blob([u],{type:"application/xml"}),$=URL.createObjectURL(h),D=document.createElement("a");D.href=$,D.download=`${o.workflow.name.replace(/\s+/g,"_")}.bpmn`,D.click(),URL.revokeObjectURL($)};return N?e.jsxs("div",{className:`nice-workflow-ai ${l||""}`,style:p,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:z,value:g,onChange:u=>y(u.target.value),placeholder:n,className:"nice-workflow-ai__input",rows:3,disabled:j}),e.jsx("button",{type:"button",onClick:_,className:"nice-workflow-ai__submit",disabled:j||!g.trim(),children:j?e.jsx("span",{className:"nice-workflow-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"refresh",size:14})," Generate Workflow"]})})]}),s&&e.jsxs("div",{className:"nice-workflow-ai__examples",children:[e.jsx("span",{className:"nice-workflow-ai__examples-label",children:"Try:"}),Li.slice(0,3).map((u,h)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>m(u),children:u},h))]}),o&&e.jsx("div",{className:"nice-workflow-ai__result",children:o.error?e.jsx("div",{className:"nice-workflow-ai__error",children:o.error}):o.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:o.workflow.name}),o.workflow.description&&e.jsx("span",{className:"nice-workflow-ai__workflow-desc",children:o.workflow.description})]}),e.jsxs("div",{className:"nice-workflow-ai__result-meta",children:[e.jsxs("span",{className:"nice-workflow-ai__stat",children:[o.workflow.nodes.length," nodes"]}),e.jsxs("span",{className:"nice-workflow-ai__stat",children:[o.workflow.edges.length," connections"]}),o.latencyMs&&e.jsxs("span",{className:"nice-workflow-ai__latency",children:[Math.round(o.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-workflow-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(o.workflow),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Workflow"]}),e.jsxs("button",{type:"button",onClick:v,children:[e.jsx(L.NiceIcon,{name:"search",size:14})," Validate"]}),e.jsxs("button",{type:"button",onClick:x,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," Export BPMN"]})]}),w.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:w.map((u,h)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${u.startsWith("[error]")?"error":u.startsWith("[warning]")?"warning":"info"}`,children:u},h))})]}),c&&e.jsx("div",{className:"nice-workflow-ai__preview",children:f?f(o.workflow):e.jsx($i,{workflow:o.workflow})}),o.suggestions&&o.suggestions.length>0&&e.jsxs("div",{className:"nice-workflow-ai__suggestions",children:[e.jsxs("span",{className:"nice-workflow-ai__suggestions-title",children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:o.suggestions.map((u,h)=>e.jsx("li",{children:u},h))})]}),e.jsxs("details",{className:"nice-workflow-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(o.workflow,null,2)})]})]})}),e.jsx("style",{children:`
|
|
1489
1491
|
.nice-workflow-ai {
|
|
1490
1492
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
1491
1493
|
}
|
|
@@ -1573,7 +1575,8 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1573
1575
|
padding: var(--nice-space-1-5, 6px) var(--nice-space-3, 12px);
|
|
1574
1576
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
1575
1577
|
border-radius: var(--nice-radius-xl, 16px);
|
|
1576
|
-
background:
|
|
1578
|
+
background: var(--nice-bg-primary, #fff);
|
|
1579
|
+
color: var(--nice-text-primary, #1f2937);
|
|
1577
1580
|
font-size: 12px;
|
|
1578
1581
|
cursor: pointer;
|
|
1579
1582
|
transition: all 0.2s;
|
|
@@ -1641,7 +1644,8 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1641
1644
|
padding: var(--nice-space-2, 8px) var(--nice-space-4, 16px);
|
|
1642
1645
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
1643
1646
|
border-radius: var(--nice-radius-md, 6px);
|
|
1644
|
-
background:
|
|
1647
|
+
background: var(--nice-bg-primary, #fff);
|
|
1648
|
+
color: var(--nice-text-primary, #1f2937);
|
|
1645
1649
|
font-size: 13px;
|
|
1646
1650
|
cursor: pointer;
|
|
1647
1651
|
transition: all 0.2s;
|
|
@@ -1661,7 +1665,7 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1661
1665
|
.nice-workflow-ai__validation {
|
|
1662
1666
|
margin-bottom: var(--nice-space-4, 16px);
|
|
1663
1667
|
padding: var(--nice-space-3, 12px);
|
|
1664
|
-
background: var(--nice-warning-
|
|
1668
|
+
background: var(--nice-warning-bg, #fff3e0);
|
|
1665
1669
|
border-radius: var(--nice-radius-md, 6px);
|
|
1666
1670
|
}
|
|
1667
1671
|
|
|
@@ -1694,7 +1698,8 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1694
1698
|
|
|
1695
1699
|
.nice-workflow-ai__preview {
|
|
1696
1700
|
padding: var(--nice-space-5, 20px);
|
|
1697
|
-
background:
|
|
1701
|
+
background: var(--nice-bg-primary, #fff);
|
|
1702
|
+
color: var(--nice-text-primary, #1f2937);
|
|
1698
1703
|
border-radius: var(--nice-radius-lg, 8px);
|
|
1699
1704
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
1700
1705
|
margin-bottom: var(--nice-space-4, 16px);
|
|
@@ -1704,7 +1709,7 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1704
1709
|
.nice-workflow-ai__suggestions {
|
|
1705
1710
|
margin-bottom: var(--nice-space-4, 16px);
|
|
1706
1711
|
padding: var(--nice-space-3, 12px);
|
|
1707
|
-
background: var(--nice-info-
|
|
1712
|
+
background: var(--nice-info-bg, #e3f2fd);
|
|
1708
1713
|
border-radius: var(--nice-radius-md, 6px);
|
|
1709
1714
|
}
|
|
1710
1715
|
|
|
@@ -1742,11 +1747,11 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1742
1747
|
|
|
1743
1748
|
.nice-workflow-ai__error {
|
|
1744
1749
|
padding: var(--nice-space-3, 12px);
|
|
1745
|
-
background: var(--nice-
|
|
1750
|
+
background: var(--nice-danger-bg, #ffebee);
|
|
1746
1751
|
color: var(--nice-error, #c62828);
|
|
1747
1752
|
border-radius: var(--nice-radius-md, 6px);
|
|
1748
1753
|
}
|
|
1749
|
-
`})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${l||""}`,style:
|
|
1754
|
+
`})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${l||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function $i({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(L.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(g=>g.id===r.source),s=t.nodes.find(g=>g.id===r.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const c=n.position.x+ba(n),l=n.position.y+20,p=s.position.x,f=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:c,y1:l,x2:p,y2:f,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(c+p)/2,y:(l+f)/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:`
|
|
1750
1755
|
.workflow-preview {
|
|
1751
1756
|
min-height: 200px;
|
|
1752
1757
|
}
|
|
@@ -1763,7 +1768,8 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1763
1768
|
align-items: center;
|
|
1764
1769
|
gap: var(--nice-space-2, 8px);
|
|
1765
1770
|
padding: var(--nice-space-2-5, 10px) var(--nice-space-4, 16px);
|
|
1766
|
-
background:
|
|
1771
|
+
background: var(--nice-bg-primary, #fff);
|
|
1772
|
+
color: var(--nice-text-primary, #1f2937);
|
|
1767
1773
|
border: 2px solid;
|
|
1768
1774
|
border-radius: var(--nice-radius-lg, 8px);
|
|
1769
1775
|
font-size: 13px;
|
|
@@ -1798,6 +1804,21 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1798
1804
|
transform: rotate(-45deg);
|
|
1799
1805
|
}
|
|
1800
1806
|
|
|
1807
|
+
/* The diamond is the symbol; its question sits under the bottom vertex, upright,
|
|
1808
|
+
instead of turning with the diamond across the arrows. */
|
|
1809
|
+
.workflow-preview__node--gateway .workflow-preview__node-icon {
|
|
1810
|
+
display: none;
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
.workflow-preview__node--gateway .workflow-preview__node-label {
|
|
1814
|
+
position: absolute;
|
|
1815
|
+
top: 100%;
|
|
1816
|
+
left: 100%;
|
|
1817
|
+
transform-origin: 0 0;
|
|
1818
|
+
transform: rotate(-45deg) translate(-50%, 6px);
|
|
1819
|
+
font-size: 11px;
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1801
1822
|
.workflow-preview__node-icon {
|
|
1802
1823
|
font-size: 16px;
|
|
1803
1824
|
}
|
|
@@ -1835,7 +1856,7 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1835
1856
|
border-radius: var(--nice-radius-sm, 4px);
|
|
1836
1857
|
font-size: 12px;
|
|
1837
1858
|
}
|
|
1838
|
-
`})]})}function
|
|
1859
|
+
`})]})}function Oi(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="${fe(n.label)}" />`).join(`
|
|
1839
1860
|
`),r=t.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${fe(n.label)}"`:""} />`).join(`
|
|
1840
1861
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
1841
1862
|
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
|
|
@@ -1846,10 +1867,12 @@ Existing nodes: ${b.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
|
|
|
1846
1867
|
${i}
|
|
1847
1868
|
${r}
|
|
1848
1869
|
</bpmn:process>
|
|
1849
|
-
</bpmn:definitions>`}function fe(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function
|
|
1850
|
-
`):void 0,C=
|
|
1851
|
-
|
|
1852
|
-
|
|
1870
|
+
</bpmn:definitions>`}function fe(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ya(t={}){const{config:a,dataSources:i,context:r,onReportGenerated:n,onError:s}=t,c=Z(),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState([]),S=d.useRef(null),z=a||(c==null?void 0:c.config),k=d.useCallback(async m=>{var x,u,h;if(!z){const $="AI not configured";return s==null||s($),{error:$}}p(!0);const v=performance.now();(x=S.current)==null||x.abort(),S.current=new AbortController;try{const $=K(z),D=i?i.map(b=>`- ${b.name} (${b.id}): ${b.fields.join(", ")}`).join(`
|
|
1871
|
+
`):void 0,C=ie(pe,{description:r?`${m}
|
|
1872
|
+
|
|
1873
|
+
Context: ${r}`:m,dataSources:D}),A=await $.chat({messages:[{role:"system",content:C.system},{role:"user",content:C.user}],temperature:.5,maxTokens:2048}),O=Bi(A),B={layout:O||void 0,rawResponse:(h=(u=A.choices[0])==null?void 0:u.message)==null?void 0:h.content,latencyMs:performance.now()-v,error:O?void 0:"Failed to generate report layout",suggestions:Fi(O)};return O&&(n==null||n(O)),g(B),w(b=>[...b.slice(-9),{request:m,result:B}]),B}catch($){const D=$ instanceof Error?$.message:"Report generation failed",C={error:D,latencyMs:performance.now()-v};return g(C),s==null||s(D),C}finally{p(!1)}},[z,i,r,n,s]),I=d.useCallback(async m=>{var v,x;if(!z)return[];p(!0);try{const D=(((x=(v=(await K(z).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: ${m.name}
|
|
1874
|
+
Existing sections: ${m.sections.map(C=>C.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:v.message)==null?void 0:x.content)||"").match(/\[[\s\S]*\]/);if(D)return JSON.parse(D[0])}catch{}finally{p(!1)}return[]},[z]),j=d.useCallback(async m=>{var v,x;if(!z)return null;p(!0);try{return((x=(v=(await K(z).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(m,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:v.message)==null?void 0:x.content)||null}catch{return null}finally{p(!1)}},[z]),o=d.useCallback(async(m,v)=>{var x,u,h;if(!z)return"bar";try{const $=K(z),D=m.slice(0,5),A=(h=(u=(x=(await $.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(D)}
|
|
1875
|
+
Purpose: ${v}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:x.message)==null?void 0:u.content)==null?void 0:h.toLowerCase().trim();return["line","bar","pie","donut","area","column","scatter","combo","gauge","heatmap"].find(B=>A==null?void 0:A.includes(B))||"bar"}catch{return"bar"}},[z]),N=d.useCallback(()=>{g(null)},[]),_=d.useCallback(()=>{var m;(m=S.current)==null||m.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var m;(m=S.current)==null||m.abort()},[]),{generateReport:k,suggestSections:I,generateSummary:j,suggestChartType:o,loading:l,lastResult:f,history:y,clearResults:N,abort:_,isConfigured:!!z}}const Ei=new Set(["header","summary","kpi","table","chart","text","image","divider","spacer","pageBreak","footer","toc","customBlock"]),Di={title:"header",subtitle:"text","kpi-card":"kpi",metric:"kpi","pivot-table":"table","page-break":"pageBreak","section-break":"divider",logo:"image"};function Be(t){const a=typeof t=="string"?t:"";return Di[a]??(Ei.has(a)?a:"customBlock")}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)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.sections&&Array.isArray(l.sections)){const p=l.sections.flatMap(g=>Array.isArray(g.elements)&&!g.type?g.elements.map((y,w)=>({type:Be(y.type),title:w===0?g.title:void 0,config:y.config??{}})):[{...g,type:Be(g.type)}]);l.header&&!p.some(g=>g.type==="header")&&p.unshift({type:"header",title:"Header",config:l.header}),l.footer&&!p.some(g=>g.type==="footer")&&p.push({type:"footer",title:"Footer",config:l.footer});const f=p.map((g,y)=>({...g,id:g.id||`section_${y}`,order:g.order??y,config:g.config||{}}));return{id:l.id||`report_${Date.now()}`,name:l.name||l.title||"Generated Report",description:l.description,orientation:l.orientation||"portrait",pageSize:l.pageSize||"A4",margins:l.margins||{top:20,right:20,bottom:20,left:20},sections:f,dataSources:l.dataSources,parameters:l.parameters,styles:l.styles}}}catch{}return null}function Fi(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 Ji=[{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 Ui({config:t,dataSources:a,context:i,onGenerate:r,placeholder:n='Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")',showTemplates:s=!0,showPreview:c=!0,className:l,style:p,renderReport:f}){const[g,y]=d.useState(""),w=d.useRef(null),{generateReport:S,loading:z,lastResult:k,isConfigured:I}=ya({config:t,dataSources:a,context:i,onReportGenerated:r}),j=async()=>{!g.trim()||z||await S(g)},o=_=>{var m;y(_.prompt),(m=w.current)==null||m.focus()},N=()=>{if(!(k!=null&&k.layout))return;const _=JSON.stringify(k.layout,null,2),m=new Blob([_],{type:"application/json"}),v=URL.createObjectURL(m),x=document.createElement("a");x.href=v,x.download=`${k.layout.name.replace(/\s+/g,"_")}.json`,x.click(),URL.revokeObjectURL(v)};return I?e.jsxs("div",{className:`nice-report-ai ${l||""}`,style:p,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:Ji.map((_,m)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>o(_),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:e.jsx(L.NiceIcon,{name:_.icon,size:24})}),e.jsx("span",{className:"nice-report-ai__template-name",children:_.name})]},m))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:w,value:g,onChange:_=>y(_.target.value),placeholder:n,className:"nice-report-ai__input",rows:3,disabled:z}),e.jsx("button",{type:"button",onClick:j,className:"nice-report-ai__submit",disabled:z||!g.trim(),children:z?e.jsx("span",{className:"nice-report-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"file",size:14})," 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(_=>e.jsx("span",{className:"nice-report-ai__datasource",children:_.name},_.id))]}),k&&e.jsx("div",{className:"nice-report-ai__result",children:k.error?e.jsx("div",{className:"nice-report-ai__error",children:k.error}):k.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:k.layout.name}),k.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:k.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[k.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[k.layout.pageSize," ",k.layout.orientation]}),k.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(k.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(k.layout),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Report"]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," 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:k.layout.sections.map((_,m)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:m+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:e.jsx(L.NiceIcon,{name:va(_.type),size:16})}),e.jsx("span",{className:"nice-report-ai__section-type",children:_.type}),_.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:_.title})]},_.id))})]}),c&&e.jsx("div",{className:"nice-report-ai__preview",children:f?f(k.layout):e.jsx(qi,{layout:k.layout})}),k.suggestions&&k.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsxs("span",{className:"nice-report-ai__suggestions-title",children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:k.suggestions.map((_,m)=>e.jsx("li",{children:_},m))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(k.layout,null,2)})]})]})}),e.jsx("style",{children:`
|
|
1853
1876
|
.nice-report-ai {
|
|
1854
1877
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
1855
1878
|
}
|
|
@@ -1876,7 +1899,8 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
1876
1899
|
padding: var(--nice-space-3, 12px) var(--nice-space-4, 16px);
|
|
1877
1900
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
1878
1901
|
border-radius: var(--nice-radius-lg, 8px);
|
|
1879
|
-
background:
|
|
1902
|
+
background: var(--nice-bg-primary, #fff);
|
|
1903
|
+
color: var(--nice-text-primary, #1f2937);
|
|
1880
1904
|
cursor: pointer;
|
|
1881
1905
|
transition: all 0.2s;
|
|
1882
1906
|
min-width: 100px;
|
|
@@ -2033,7 +2057,8 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
2033
2057
|
padding: var(--nice-space-2, 8px) var(--nice-space-4, 16px);
|
|
2034
2058
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
2035
2059
|
border-radius: var(--nice-radius-md, 6px);
|
|
2036
|
-
background:
|
|
2060
|
+
background: var(--nice-bg-primary, #fff);
|
|
2061
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2037
2062
|
font-size: 13px;
|
|
2038
2063
|
cursor: pointer;
|
|
2039
2064
|
transition: all 0.2s;
|
|
@@ -2070,7 +2095,8 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
2070
2095
|
align-items: center;
|
|
2071
2096
|
gap: var(--nice-space-2, 8px);
|
|
2072
2097
|
padding: var(--nice-space-2, 8px) var(--nice-space-3, 12px);
|
|
2073
|
-
background:
|
|
2098
|
+
background: var(--nice-bg-primary, #fff);
|
|
2099
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2074
2100
|
border-radius: var(--nice-radius-md, 6px);
|
|
2075
2101
|
border: 1px solid var(--nice-border-light, #f0f0f0);
|
|
2076
2102
|
}
|
|
@@ -2105,7 +2131,8 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
2105
2131
|
|
|
2106
2132
|
.nice-report-ai__preview {
|
|
2107
2133
|
padding: var(--nice-space-5, 20px);
|
|
2108
|
-
background:
|
|
2134
|
+
background: var(--nice-bg-primary, #fff);
|
|
2135
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2109
2136
|
border-radius: var(--nice-radius-lg, 8px);
|
|
2110
2137
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
2111
2138
|
margin-bottom: var(--nice-space-4, 16px);
|
|
@@ -2115,7 +2142,7 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
2115
2142
|
.nice-report-ai__suggestions {
|
|
2116
2143
|
margin-bottom: var(--nice-space-4, 16px);
|
|
2117
2144
|
padding: var(--nice-space-3, 12px);
|
|
2118
|
-
background: var(--nice-info-
|
|
2145
|
+
background: var(--nice-info-bg, #e3f2fd);
|
|
2119
2146
|
border-radius: var(--nice-radius-md, 6px);
|
|
2120
2147
|
}
|
|
2121
2148
|
|
|
@@ -2153,11 +2180,11 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
2153
2180
|
|
|
2154
2181
|
.nice-report-ai__error {
|
|
2155
2182
|
padding: var(--nice-space-3, 12px);
|
|
2156
|
-
background: var(--nice-
|
|
2183
|
+
background: var(--nice-danger-bg, #ffebee);
|
|
2157
2184
|
color: var(--nice-error, #c62828);
|
|
2158
2185
|
border-radius: var(--nice-radius-md, 6px);
|
|
2159
2186
|
}
|
|
2160
|
-
`})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${l||""}`,style:
|
|
2187
|
+
`})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${l||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function va(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 qi({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(L.NiceIcon,{name:va(a.type),size:14})}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
|
|
2161
2188
|
.report-preview {
|
|
2162
2189
|
display: flex;
|
|
2163
2190
|
justify-content: center;
|
|
@@ -2170,7 +2197,8 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
2170
2197
|
width: 100%;
|
|
2171
2198
|
max-width: 300px;
|
|
2172
2199
|
padding: var(--nice-space-5, 20px);
|
|
2173
|
-
background:
|
|
2200
|
+
background: var(--nice-bg-primary, #fff);
|
|
2201
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2174
2202
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
2175
2203
|
border-radius: var(--nice-radius-sm, 4px);
|
|
2176
2204
|
box-shadow: 0 2px 8px var(--nice-overlay-10, rgba(0, 0, 0, 0.1));
|
|
@@ -2198,16 +2226,16 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
2198
2226
|
}
|
|
2199
2227
|
|
|
2200
2228
|
.report-preview__section--kpi {
|
|
2201
|
-
background: var(--nice-success-
|
|
2229
|
+
background: var(--nice-success-bg, #e8f5e9);
|
|
2202
2230
|
}
|
|
2203
2231
|
|
|
2204
2232
|
.report-preview__section--table {
|
|
2205
|
-
background: var(--nice-info-
|
|
2233
|
+
background: var(--nice-info-bg, #e3f2fd);
|
|
2206
2234
|
min-height: 40px;
|
|
2207
2235
|
}
|
|
2208
2236
|
|
|
2209
2237
|
.report-preview__section--chart {
|
|
2210
|
-
background: var(--nice-warning-
|
|
2238
|
+
background: var(--nice-warning-bg, #fff3e0);
|
|
2211
2239
|
min-height: 50px;
|
|
2212
2240
|
}
|
|
2213
2241
|
|
|
@@ -2236,19 +2264,34 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
|
|
|
2236
2264
|
text-overflow: ellipsis;
|
|
2237
2265
|
white-space: nowrap;
|
|
2238
2266
|
}
|
|
2239
|
-
`})]})}function
|
|
2267
|
+
`})]})}function Hi(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).
|
|
2268
|
+
Return only JSON: ${a?'{ "light": THEME, "dark": THEME }, the dark one with "mode": "dark",':'{ "light": THEME },'} where THEME is
|
|
2269
|
+
{
|
|
2270
|
+
"name": "Theme name",
|
|
2271
|
+
"description": "One sentence",
|
|
2272
|
+
"mode": "light",
|
|
2273
|
+
"colors": {
|
|
2274
|
+
"primary": "#hex", "primaryLight": "#hex", "primaryDark": "#hex",
|
|
2275
|
+
"secondary": "#hex", "secondaryLight": "#hex", "secondaryDark": "#hex",
|
|
2276
|
+
"accent": "#hex", "background": "#hex", "surface": "#hex",
|
|
2277
|
+
"text": "#hex", "textMuted": "#hex", "textInverse": "#hex", "border": "#hex",
|
|
2278
|
+
"success": "#hex", "warning": "#hex", "error": "#hex", "info": "#hex"
|
|
2279
|
+
},
|
|
2280
|
+
"typography": { "fontFamily": "...", "fontFamilyMono": "..." },
|
|
2281
|
+
"borderRadius": { "sm": "4px", "md": "8px", "lg": "12px" }
|
|
2282
|
+
}`,user:t}}function _a(t={}){const{config:a,generateDarkMode:i=!0,onThemeGenerated:r,onError:n}=t,s=Z(),[c,l]=d.useState(!1),[p,f]=d.useState(null),g=d.useRef(null),y=a||(s==null?void 0:s.config),w=d.useCallback(async o=>{var _,m,v,x;if(!y){const u="AI not configured";return n==null||n(u),{error:u}}l(!0);const N=performance.now();(_=g.current)==null||_.abort(),g.current=new AbortController;try{const u=K(y);let h="";switch(o.type){case"description":h=o.value;break;case"brand":h=`Create a theme for "${o.value.name}"${o.value.industry?` in the ${o.value.industry} industry`:""}${(m=o.value.keywords)!=null&&m.length?`. Keywords: ${o.value.keywords.join(", ")}`:""}`;break;case"colors":h=`Create a theme based on primary color ${o.value.primary}${o.value.secondary?` and secondary color ${o.value.secondary}`:""}`;break;case"image":h="Extract colors and create a theme from the provided image palette";break}const $=Hi(h,i),D=await u.chat({messages:[{role:"system",content:$.system},{role:"user",content:$.user}],temperature:.6,maxTokens:2048}),C=Fe(D),A={theme:C.light||void 0,darkTheme:C.dark||void 0,rawResponse:(x=(v=D.choices[0])==null?void 0:v.message)==null?void 0:x.content,latencyMs:performance.now()-N,error:C.light?void 0:"Failed to generate theme",suggestions:Wi(C.light)};return C.light&&(r==null||r(C.light,C.dark??void 0)),f(A),A}catch(u){const h=u instanceof Error?u.message:"Theme generation failed",$={error:h,latencyMs:performance.now()-N};return f($),n==null||n(h),$}finally{l(!1)}},[y,i,r,n]),S=d.useCallback(async(o,N)=>{if(!y)return null;l(!0);try{const m=await K(y).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:
|
|
2240
2283
|
${JSON.stringify(o,null,2)}
|
|
2241
2284
|
|
|
2242
|
-
Adjustments: ${
|
|
2243
|
-
/* Typography */`),Object.entries(o.typography).forEach(([
|
|
2244
|
-
/* Spacing */`),Object.entries(o.spacing).forEach(([
|
|
2245
|
-
/* Border Radius */`),Object.entries(o.borderRadius).forEach(([
|
|
2246
|
-
/* Shadows */`),Object.entries(o.shadows).forEach(([
|
|
2247
|
-
/* Animations */`),Object.entries(o.animations).forEach(([
|
|
2248
|
-
${
|
|
2285
|
+
Adjustments: ${N}`}],temperature:.4,maxTokens:2048});return Fe(m).light||null}catch{return null}finally{l(!1)}},[y]),z=d.useCallback(o=>{const N=[];return N.push(" /* Colors */"),Object.entries(o.colors).forEach(([_,m])=>{N.push(` --nice-${be(_)}: ${m};`)}),N.push(`
|
|
2286
|
+
/* Typography */`),Object.entries(o.typography).forEach(([_,m])=>{N.push(` --nice-${be(_)}: ${m};`)}),N.push(`
|
|
2287
|
+
/* Spacing */`),Object.entries(o.spacing).forEach(([_,m])=>{N.push(` --nice-spacing-${_}: ${m};`)}),N.push(`
|
|
2288
|
+
/* Border Radius */`),Object.entries(o.borderRadius).forEach(([_,m])=>{N.push(` --nice-radius-${_}: ${m};`)}),N.push(`
|
|
2289
|
+
/* Shadows */`),Object.entries(o.shadows).forEach(([_,m])=>{N.push(` --nice-shadow-${_}: ${m};`)}),N.push(`
|
|
2290
|
+
/* Animations */`),Object.entries(o.animations).forEach(([_,m])=>{N.push(` --nice-${be(_)}: ${m};`)}),`:root {
|
|
2291
|
+
${N.join(`
|
|
2249
2292
|
`)}
|
|
2250
|
-
}`},[]),
|
|
2251
|
-
module.exports = ${JSON.stringify(
|
|
2293
|
+
}`},[]),k=d.useCallback(o=>{const N={theme:{extend:{colors:{primary:{DEFAULT:o.colors.primary,light:o.colors.primaryLight,dark:o.colors.primaryDark},secondary:{DEFAULT:o.colors.secondary,light:o.colors.secondaryLight,dark:o.colors.secondaryDark},accent:o.colors.accent,success:o.colors.success,warning:o.colors.warning,error:o.colors.error,info:o.colors.info},fontFamily:{sans:[o.typography.fontFamily],mono:[o.typography.fontFamilyMono]},borderRadius:o.borderRadius,boxShadow:o.shadows}}};return`// tailwind.config.js
|
|
2294
|
+
module.exports = ${JSON.stringify(N,null,2)}`},[]),I=d.useCallback(()=>{f(null)},[]),j=d.useCallback(()=>{var o;(o=g.current)==null||o.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var o;(o=g.current)==null||o.abort()},[]),{generateTheme:w,adjustTheme:S,toCSSVariables:z,toTailwindConfig:k,loading:c,lastResult:p,clearResults:I,abort:j,isConfigured:!!y}}function Fe(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.light||l.theme)return{light:xe(l.light||l.theme),dark:l.dark?xe(l.dark):null};if(l.colors)return{light:xe(l),dark:null}}catch{}return{light:null,dark:null}}function xe(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 Wi(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 be(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const Gi=[{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 Vi({config:t,generateDarkMode:a=!0,onGenerate:i,showPresets:r=!0,showPreview:n=!0,className:s,style:c}){const[l,p]=d.useState("description"),[f,g]=d.useState(""),[y,w]=d.useState(""),[S,z]=d.useState(""),[k,I]=d.useState("#0066cc"),[j,o]=d.useState("light"),{generateTheme:N,toCSSVariables:_,toTailwindConfig:m,loading:v,lastResult:x,isConfigured:u}=_a({config:t,generateDarkMode:a,onThemeGenerated:i}),h=async()=>{if(v)return;let O;switch(l){case"brand":if(!y.trim())return;O={type:"brand",value:{name:y,industry:S||void 0}};break;case"colors":O={type:"colors",value:{primary:k}};break;default:if(!f.trim())return;O={type:"description",value:f}}await N(O)},$=O=>{p("description"),g(O.prompt)},D=()=>{if(!(x!=null&&x.theme))return;const O=_(x.theme),B=new Blob([O],{type:"text/css"}),b=URL.createObjectURL(B),P=document.createElement("a");P.href=b,P.download=`${x.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,P.click(),URL.revokeObjectURL(b)},C=()=>{if(!(x!=null&&x.theme))return;const O=m(x.theme),B=new Blob([O],{type:"text/javascript"}),b=URL.createObjectURL(B),P=document.createElement("a");P.href=b,P.download="tailwind.config.js",P.click(),URL.revokeObjectURL(b)},A=j==="dark"&&(x!=null&&x.darkTheme)?x.darkTheme:x==null?void 0:x.theme;return u?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:c,children:[r&&e.jsx("div",{className:"nice-theme-ai__presets",children:Gi.map((O,B)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>$(O),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:e.jsx(L.NiceIcon,{name:O.icon,size:24})}),e.jsx("span",{className:"nice-theme-ai__preset-name",children:O.name})]},B))}),e.jsxs("div",{className:"nice-theme-ai__tabs",children:[e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${l==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("description"),children:[e.jsx(L.NiceIcon,{name:"edit",size:14})," Description"]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${l==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("brand"),children:[e.jsx(L.NiceIcon,{name:"tag",size:14})," Brand"]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${l==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("colors"),children:[e.jsx(L.NiceIcon,{name:"palette",size:14})," Colors"]})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[l==="description"&&e.jsx("textarea",{value:f,onChange:O=>g(O.target.value),placeholder:"Describe the theme you want... (e.g., 'Modern tech startup with blue and green')",className:"nice-theme-ai__textarea",rows:3,disabled:v}),l==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:y,onChange:O=>w(O.target.value),placeholder:"Brand name",className:"nice-theme-ai__input",disabled:v}),e.jsx("input",{type:"text",value:S,onChange:O=>z(O.target.value),placeholder:"Industry (optional)",className:"nice-theme-ai__input",disabled:v})]}),l==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:k,onChange:O=>I(O.target.value),className:"nice-theme-ai__color-picker",disabled:v}),e.jsx("span",{className:"nice-theme-ai__color-value",children:k})]})}),e.jsx("button",{type:"button",onClick:h,className:"nice-theme-ai__submit",disabled:v,children:v?e.jsx("span",{className:"nice-theme-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"wand",size:14})," Generate Theme"]})})]}),(x==null?void 0:x.error)&&e.jsx("div",{className:"nice-theme-ai__error",role:"alert",children:x.error}),x&&A&&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:A.name}),A.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:A.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[x.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button","aria-label":"Light mode",className:j==="light"?"active":"",onClick:()=>o("light"),children:e.jsx(L.NiceIcon,{name:"sun",size:16})}),e.jsx("button",{type:"button","aria-label":"Dark mode",className:j==="dark"?"active":"",onClick:()=>o("dark"),children:e.jsx(L.NiceIcon,{name:"moon",size:16})})]}),e.jsxs("button",{type:"button",onClick:D,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:C,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," Tailwind"]})]})]}),n&&e.jsx(Ki,{theme:A}),e.jsxs("div",{className:"nice-theme-ai__palette",children:[e.jsx("div",{className:"nice-theme-ai__palette-title",children:"Color Palette"}),e.jsx("div",{className:"nice-theme-ai__colors",children:Object.entries(A.colors).map(([O,B])=>e.jsxs("div",{className:"nice-theme-ai__color",children:[e.jsx("div",{className:"nice-theme-ai__color-swatch",style:{backgroundColor:B}}),e.jsx("span",{className:"nice-theme-ai__color-name",children:O}),e.jsx("span",{className:"nice-theme-ai__color-hex",children:B})]},O))})]}),e.jsxs("div",{className:"nice-theme-ai__typography",children:[e.jsx("div",{className:"nice-theme-ai__typography-title",children:"Typography"}),e.jsxs("div",{style:{fontFamily:A.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:A.typography.fontSize3xl,fontWeight:A.typography.fontWeightBold},children:"Heading 1"}),e.jsx("p",{style:{fontSize:A.typography.fontSizeLg},children:"Body text: The quick brown fox jumps over the lazy dog."}),e.jsx("p",{style:{fontFamily:A.typography.fontFamilyMono,fontSize:A.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
|
|
2252
2295
|
.nice-theme-ai {
|
|
2253
2296
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
2254
2297
|
}
|
|
@@ -2275,7 +2318,8 @@ module.exports = ${JSON.stringify(k,null,2)}`},[]),I=d.useCallback(()=>{g(null)}
|
|
|
2275
2318
|
padding: var(--nice-space-3, 12px) var(--nice-space-4, 16px);
|
|
2276
2319
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
2277
2320
|
border-radius: var(--nice-radius-lg, 8px);
|
|
2278
|
-
background:
|
|
2321
|
+
background: var(--nice-bg-primary, #fff);
|
|
2322
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2279
2323
|
cursor: pointer;
|
|
2280
2324
|
transition: all 0.2s;
|
|
2281
2325
|
min-width: 80px;
|
|
@@ -2449,7 +2493,8 @@ module.exports = ${JSON.stringify(k,null,2)}`},[]),I=d.useCallback(()=>{g(null)}
|
|
|
2449
2493
|
padding: var(--nice-space-1-5, 6px) var(--nice-space-3, 12px);
|
|
2450
2494
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
2451
2495
|
border-radius: var(--nice-radius-md, 6px);
|
|
2452
|
-
background:
|
|
2496
|
+
background: var(--nice-bg-primary, #fff);
|
|
2497
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2453
2498
|
font-size: 12px;
|
|
2454
2499
|
cursor: pointer;
|
|
2455
2500
|
}
|
|
@@ -2519,7 +2564,15 @@ module.exports = ${JSON.stringify(k,null,2)}`},[]),I=d.useCallback(()=>{g(null)}
|
|
|
2519
2564
|
.nice-theme-ai__typography {
|
|
2520
2565
|
margin-top: var(--nice-space-5, 20px);
|
|
2521
2566
|
}
|
|
2522
|
-
|
|
2567
|
+
|
|
2568
|
+
.nice-theme-ai__error {
|
|
2569
|
+
margin-top: var(--nice-space-4, 16px);
|
|
2570
|
+
padding: var(--nice-space-3, 12px);
|
|
2571
|
+
background: var(--nice-danger-bg, #ffebee);
|
|
2572
|
+
color: var(--nice-error, #c62828);
|
|
2573
|
+
border-radius: var(--nice-radius-md, 6px);
|
|
2574
|
+
}
|
|
2575
|
+
`})]}):e.jsx("div",{className:`nice-theme-ai nice-theme-ai--disabled ${s||""}`,style:c,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Ki({theme:t}){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:"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:"Secondary"}),e.jsx("input",{type:"text",placeholder:"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:`
|
|
2523
2576
|
.theme-preview {
|
|
2524
2577
|
background: var(--preview-bg);
|
|
2525
2578
|
border: 1px solid var(--preview-border);
|
|
@@ -2565,7 +2618,7 @@ module.exports = ${JSON.stringify(k,null,2)}`},[]),I=d.useCallback(()=>{g(null)}
|
|
|
2565
2618
|
cursor: text;
|
|
2566
2619
|
width: 150px;
|
|
2567
2620
|
}
|
|
2568
|
-
`})]})}function
|
|
2621
|
+
`})]})}function wa(t={}){const{config:a,targetDevice:i="responsive",onLayoutGenerated:r,onError:n}=t,s=Z(),[c,l]=d.useState(!1),[p,f]=d.useState(null),g=d.useRef(null),y=a||(s==null?void 0:s.config),w=d.useCallback(async(j,o)=>{var _,m,v;if(!y){const x="AI not configured";return n==null||n(x),{error:x}}l(!0);const N=performance.now();(_=g.current)==null||_.abort(),g.current=new AbortController;try{const x=K(y),u=`You are a UI layout expert. Generate a responsive layout based on the description.
|
|
2569
2622
|
Return JSON with this structure:
|
|
2570
2623
|
{
|
|
2571
2624
|
"id": "unique_id",
|
|
@@ -2600,45 +2653,45 @@ Return JSON with this structure:
|
|
|
2600
2653
|
"xl": "1280px",
|
|
2601
2654
|
"2xl": "1536px"
|
|
2602
2655
|
}
|
|
2603
|
-
}`,h=await
|
|
2604
|
-
`;if(o+=` display: ${
|
|
2605
|
-
`,
|
|
2606
|
-
`}
|
|
2607
|
-
`)}else o+=` flex-direction: ${
|
|
2608
|
-
`,
|
|
2609
|
-
`);return
|
|
2610
|
-
`),
|
|
2611
|
-
`),
|
|
2612
|
-
`),
|
|
2656
|
+
}`,h=await x.chat({messages:[{role:"system",content:u},{role:"user",content:`Create a ${i} layout: ${j}${o?` (type: ${o})`:""}`}],temperature:.5,maxTokens:2048}),$=Yi(h),D={layout:$||void 0,rawResponse:(v=(m=h.choices[0])==null?void 0:m.message)==null?void 0:v.content,latencyMs:performance.now()-N,error:$?void 0:"Failed to generate layout",suggestions:Xi($)};return $&&(r==null||r($)),f(D),D}catch(x){const u=x instanceof Error?x.message:"Layout generation failed",h={error:u,latencyMs:performance.now()-N};return f(h),n==null||n(u),h}finally{l(!1)}},[y,i,r,n]),S=d.useCallback(j=>{let o=`.${j.id} {
|
|
2657
|
+
`;if(o+=` display: ${j.container.direction==="grid"?"grid":"flex"};
|
|
2658
|
+
`,j.container.direction==="grid"){if(j.container.gridColumns){const N=typeof j.container.gridColumns=="number"?`repeat(${j.container.gridColumns}, 1fr)`:j.container.gridColumns;o+=` grid-template-columns: ${N};
|
|
2659
|
+
`}j.container.gridRows&&(o+=` grid-template-rows: ${j.container.gridRows};
|
|
2660
|
+
`)}else o+=` flex-direction: ${j.container.direction};
|
|
2661
|
+
`,j.container.wrap&&(o+=` flex-wrap: wrap;
|
|
2662
|
+
`);return j.container.gap&&(o+=` gap: ${j.container.gap};
|
|
2663
|
+
`),j.container.padding&&(o+=` padding: ${j.container.padding};
|
|
2664
|
+
`),j.container.align&&(o+=` align-items: ${j.container.align};
|
|
2665
|
+
`),j.container.justify&&(o+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[j.container.justify]||j.container.justify};
|
|
2613
2666
|
`),o+=`}
|
|
2614
2667
|
|
|
2615
|
-
`,
|
|
2616
|
-
`,(
|
|
2617
|
-
`),(
|
|
2618
|
-
`),(
|
|
2619
|
-
`),(
|
|
2620
|
-
`),(u=
|
|
2621
|
-
`),(h=
|
|
2668
|
+
`,j.regions.forEach(N=>{var _,m,v,x,u,h;o+=`.${j.id}__${N.id} {
|
|
2669
|
+
`,(_=N.position)!=null&&_.gridColumn&&(o+=` grid-column: ${N.position.gridColumn};
|
|
2670
|
+
`),(m=N.position)!=null&&m.gridRow&&(o+=` grid-row: ${N.position.gridRow};
|
|
2671
|
+
`),(v=N.size)!=null&&v.width&&(o+=` width: ${N.size.width};
|
|
2672
|
+
`),(x=N.size)!=null&&x.height&&(o+=` height: ${N.size.height};
|
|
2673
|
+
`),(u=N.size)!=null&&u.minWidth&&(o+=` min-width: ${N.size.minWidth};
|
|
2674
|
+
`),(h=N.size)!=null&&h.maxWidth&&(o+=` max-width: ${N.size.maxWidth};
|
|
2622
2675
|
`),o+=`}
|
|
2623
2676
|
|
|
2624
|
-
`}),
|
|
2625
|
-
`,
|
|
2626
|
-
`,(u=
|
|
2627
|
-
`),(h=
|
|
2677
|
+
`}),j.breakpoints&&Object.entries(j.breakpoints).forEach(([N,_])=>{const m=j.regions.filter(v=>{var x;return(x=v.responsive)==null?void 0:x[N]});m.length>0&&(o+=`@media (max-width: ${_}) {
|
|
2678
|
+
`,m.forEach(v=>{var u,h;const x=v.responsive[N];o+=` .${j.id}__${v.id} {
|
|
2679
|
+
`,(u=x.size)!=null&&u.width&&(o+=` width: ${x.size.width};
|
|
2680
|
+
`),(h=x.size)!=null&&h.height&&(o+=` height: ${x.size.height};
|
|
2628
2681
|
`),o+=` }
|
|
2629
2682
|
`}),o+=`}
|
|
2630
2683
|
|
|
2631
|
-
`)}),o},[]),
|
|
2684
|
+
`)}),o},[]),z=d.useCallback(j=>{const o=j.regions.map(N=>` <div className="${j.id}__${N.id}">{/* ${N.type} */}</div>`).join(`
|
|
2632
2685
|
`);return`import React from 'react';
|
|
2633
|
-
import './${
|
|
2686
|
+
import './${j.id}.css';
|
|
2634
2687
|
|
|
2635
|
-
export function ${
|
|
2688
|
+
export function ${ja(j.name)}() {
|
|
2636
2689
|
return (
|
|
2637
|
-
<div className="${
|
|
2690
|
+
<div className="${j.id}">
|
|
2638
2691
|
${o}
|
|
2639
2692
|
</div>
|
|
2640
2693
|
);
|
|
2641
|
-
}`},[]),
|
|
2694
|
+
}`},[]),k=d.useCallback(()=>{f(null)},[]),I=d.useCallback(()=>{var j;(j=g.current)==null||j.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var j;(j=g.current)==null||j.abort()},[]),{generateLayout:w,toCSS:S,toReactComponent:z,loading:c,lastResult:p,clearResults:k,abort:I,isConfigured:!!y}}function Yi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.regions||l.container)return{id:l.id||`layout_${Date.now()}`,name:l.name||"Generated Layout",description:l.description,type:l.type||"dashboard",container:{direction:"grid",gap:"16px",padding:"20px",gridColumns:12,...l.container},regions:l.regions||[],breakpoints:l.breakpoints||{xs:"320px",sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},cssGrid:l.cssGrid,cssVariables:l.cssVariables}}catch{}return null}function Xi(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 ja(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(a,i)=>i.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const Zi=[{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 Qi({config:t,targetDevice:a="responsive",onGenerate:i,showTypeSelector:r=!0,showPreview:n=!0,className:s,style:c,renderLayout:l}){const[p,f]=d.useState(""),[g,y]=d.useState(null),{generateLayout:w,toCSS:S,toReactComponent:z,loading:k,lastResult:I,isConfigured:j}=wa({config:t,targetDevice:a,onLayoutGenerated:i}),o=async()=>{!p.trim()||k||await w(p,g||void 0)},N=()=>{if(!(I!=null&&I.layout))return;const m=S(I.layout),v=new Blob([m],{type:"text/css"}),x=URL.createObjectURL(v),u=document.createElement("a");u.href=x,u.download=`${I.layout.id}.css`,u.click(),URL.revokeObjectURL(x)},_=()=>{if(!(I!=null&&I.layout))return;const m=z(I.layout),v=new Blob([m],{type:"text/javascript"}),x=URL.createObjectURL(v),u=document.createElement("a");u.href=x,u.download=`${ja(I.layout.name)}.tsx`,u.click(),URL.revokeObjectURL(x)};return j?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:c,children:[r&&e.jsx("div",{className:"nice-layout-ai__types",children:Zi.map(({type:m,icon:v,label:x})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${g===m?"nice-layout-ai__type--selected":""}`,onClick:()=>y(g===m?null:m),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:e.jsx(L.NiceIcon,{name:v,size:20})}),e.jsx("span",{className:"nice-layout-ai__type-label",children:x})]},m))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:p,onChange:m=>f(m.target.value),placeholder:"Describe the layout you need... (e.g., 'Admin dashboard with sidebar navigation and header')",className:"nice-layout-ai__input",rows:3,disabled:k}),e.jsx("button",{type:"button",onClick:o,className:"nice-layout-ai__submit",disabled:k||!p.trim(),children:k?e.jsx("span",{className:"nice-layout-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"palette",size:14})," Generate Layout"]})})]}),(I==null?void 0:I.error)&&e.jsx("div",{className:"nice-layout-ai__error",role:"alert",children:I.error}),I&&I.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:I.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:I.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>i==null?void 0:i(I.layout),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Layout"]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:_,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," 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:I.layout.regions.map(m=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${m.type}`,children:m.type},m.id))})]}),n&&e.jsx("div",{className:"nice-layout-ai__preview",children:l?l(I.layout):e.jsx(et,{layout:I.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(I.layout,null,2)})]})]}),e.jsx("style",{children:`
|
|
2642
2695
|
.nice-layout-ai {
|
|
2643
2696
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
2644
2697
|
}
|
|
@@ -2665,7 +2718,8 @@ ${o}
|
|
|
2665
2718
|
padding: var(--nice-space-2, 8px) var(--nice-space-3, 12px);
|
|
2666
2719
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
2667
2720
|
border-radius: var(--nice-radius-lg, 8px);
|
|
2668
|
-
background:
|
|
2721
|
+
background: var(--nice-bg-primary, #fff);
|
|
2722
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2669
2723
|
cursor: pointer;
|
|
2670
2724
|
transition: all 0.2s;
|
|
2671
2725
|
}
|
|
@@ -2779,7 +2833,8 @@ ${o}
|
|
|
2779
2833
|
padding: var(--nice-space-1-5, 6px) var(--nice-space-3, 12px);
|
|
2780
2834
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
2781
2835
|
border-radius: var(--nice-radius-md, 6px);
|
|
2782
|
-
background:
|
|
2836
|
+
background: var(--nice-bg-primary, #fff);
|
|
2837
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2783
2838
|
font-size: 12px;
|
|
2784
2839
|
cursor: pointer;
|
|
2785
2840
|
}
|
|
@@ -2819,13 +2874,13 @@ ${o}
|
|
|
2819
2874
|
|
|
2820
2875
|
.nice-layout-ai__region--sidebar,
|
|
2821
2876
|
.nice-layout-ai__region--aside {
|
|
2822
|
-
background: var(--nice-success-
|
|
2877
|
+
background: var(--nice-success-bg, #e8f5e9);
|
|
2823
2878
|
color: var(--nice-success, #2e7d32);
|
|
2824
2879
|
}
|
|
2825
2880
|
|
|
2826
2881
|
.nice-layout-ai__region--main,
|
|
2827
2882
|
.nice-layout-ai__region--content {
|
|
2828
|
-
background: var(--nice-info-
|
|
2883
|
+
background: var(--nice-info-bg, #e3f2fd);
|
|
2829
2884
|
color: var(--nice-info, #0288d1);
|
|
2830
2885
|
}
|
|
2831
2886
|
|
|
@@ -2835,14 +2890,15 @@ ${o}
|
|
|
2835
2890
|
}
|
|
2836
2891
|
|
|
2837
2892
|
.nice-layout-ai__region--nav {
|
|
2838
|
-
background: var(--nice-warning-
|
|
2893
|
+
background: var(--nice-warning-bg, #fff3e0);
|
|
2839
2894
|
color: var(--nice-warning, #f57c00);
|
|
2840
2895
|
}
|
|
2841
2896
|
|
|
2842
2897
|
.nice-layout-ai__preview {
|
|
2843
2898
|
margin-bottom: var(--nice-space-4, 16px);
|
|
2844
2899
|
padding: var(--nice-space-5, 20px);
|
|
2845
|
-
background:
|
|
2900
|
+
background: var(--nice-bg-primary, #fff);
|
|
2901
|
+
color: var(--nice-text-primary, #1f2937);
|
|
2846
2902
|
border-radius: var(--nice-radius-lg, 8px);
|
|
2847
2903
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
2848
2904
|
}
|
|
@@ -2862,7 +2918,15 @@ ${o}
|
|
|
2862
2918
|
font-size: 12px;
|
|
2863
2919
|
overflow-x: auto;
|
|
2864
2920
|
}
|
|
2865
|
-
|
|
2921
|
+
|
|
2922
|
+
.nice-layout-ai__error {
|
|
2923
|
+
margin-top: var(--nice-space-4, 16px);
|
|
2924
|
+
padding: var(--nice-space-3, 12px);
|
|
2925
|
+
background: var(--nice-danger-bg, #ffebee);
|
|
2926
|
+
color: var(--nice-error, #c62828);
|
|
2927
|
+
border-radius: var(--nice-radius-md, 6px);
|
|
2928
|
+
}
|
|
2929
|
+
`})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:c,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function et({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,c,l,p;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:((c=i.size)==null?void 0:c.height)||"80px",minWidth:(l=i.size)==null?void 0:l.minWidth,maxWidth:(p=i.size)==null?void 0:p.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 ka(t={}){const{config:a,wcagLevel:i="AA",onAuditComplete:r,onError:n}=t,s=Z(),[c,l]=d.useState(!1),[p,f]=d.useState(null),g=d.useRef(null),y=a||(s==null?void 0:s.config),w=d.useCallback(async(o,N)=>{var _;if(!y){const m="AI not configured";return n==null||n(m),Ce("html",i,m)}l(!0),(_=g.current)==null||_.abort(),g.current=new AbortController;try{const m=K(y),v=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${i} level.
|
|
2866
2930
|
|
|
2867
2931
|
Return JSON with this exact structure:
|
|
2868
2932
|
{
|
|
@@ -2896,10 +2960,10 @@ Focus on:
|
|
|
2896
2960
|
7. Heading hierarchy
|
|
2897
2961
|
8. Landmark regions
|
|
2898
2962
|
9. Semantic HTML usage
|
|
2899
|
-
10. Language attributes`,
|
|
2900
|
-
${
|
|
2963
|
+
10. Language attributes`,x=await m.chat({messages:[{role:"system",content:v},{role:"user",content:`Analyze this HTML for accessibility:
|
|
2964
|
+
${N?`Context: ${N}
|
|
2901
2965
|
|
|
2902
|
-
`:""}${o}`}],temperature:.3,maxTokens:4096}),u=
|
|
2966
|
+
`:""}${o}`}],temperature:.3,maxTokens:4096}),u=at(x,"html",i);return f(u),r==null||r(u),u}catch(m){const v=m instanceof Error?m.message:"Audit failed";return n==null||n(v),Ce("html",i,v)}finally{l(!1)}},[y,i,r,n]),S=d.useCallback((o,N)=>{const _=he(me(o)),m=he(me(N)),v=(Math.max(_,m)+.05)/(Math.min(_,m)+.05),x={foreground:o,background:N,ratio:Math.round(v*100)/100,passesAA:v>=4.5,passesAALarge:v>=3,passesAAA:v>=7,passesAAALarge:v>=4.5};return x.passesAA||(x.suggestions=tt(o,N,4.5)),x},[]),z=d.useCallback(async o=>{var N,_;if(!y)return n==null||n("AI not configured"),[];try{const h=(((_=(N=(await K(y).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
|
|
2903
2967
|
Return JSON array:
|
|
2904
2968
|
[{
|
|
2905
2969
|
"element": "<button>...",
|
|
@@ -2910,10 +2974,10 @@ Return JSON array:
|
|
|
2910
2974
|
"issues": ["Missing aria-label"],
|
|
2911
2975
|
"suggestions": ["Add aria-label='Submit form'"]
|
|
2912
2976
|
}]`},{role:"user",content:`Validate ARIA in:
|
|
2913
|
-
${o}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:
|
|
2977
|
+
${o}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:N.message)==null?void 0:_.content)||"").match(/\[[\s\S]*\]/);if(h)return JSON.parse(h[0])}catch{}return[]},[y,n]),k=d.useCallback(async o=>{var N,_;if(!y)return n==null||n("AI not configured"),o;try{const x=((_=(N=(await K(y).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${i} compliant.
|
|
2914
2978
|
Add proper ARIA attributes, semantic HTML, keyboard handlers, focus management.
|
|
2915
2979
|
Return only the improved HTML code.`},{role:"user",content:`Make this accessible:
|
|
2916
|
-
${o}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:
|
|
2980
|
+
${o}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:N.message)==null?void 0:_.content)||"",u=x.match(/```(?:html)?\s*([\s\S]*?)```/);return u?u[1].trim():x.trim()}catch{return o}},[y,i,n]),I=d.useCallback(()=>{f(null)},[]),j=d.useCallback(()=>{var o;(o=g.current)==null||o.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var o;(o=g.current)==null||o.abort()},[]),{analyzeHTML:w,checkContrast:S,validateARIA:z,suggestAccessibleCode:k,loading:c,lastAudit:p,clearAudit:I,abort:j,isConfigured:!!y}}function Ce(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 at(t,a,i){var r,n,s;try{const c=((n=(r=t.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"",p=((s=(c.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,c])[1])==null?void 0:s.trim())||c,f=JSON.parse(p),g=(f.issues||[]).map((w,S)=>({id:w.id||`issue_${S}`,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})),y={critical:g.filter(w=>w.severity==="critical").length,serious:g.filter(w=>w.severity==="serious").length,moderate:g.filter(w=>w.severity==="moderate").length,minor:g.filter(w=>w.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:i,issues:g,score:f.score??it(y),summary:y,recommendations:f.recommendations||[]}}catch{return Ce(a,i,"Failed to parse audit results")}}function it(t){const a=t.critical*25+t.serious*15+t.moderate*5+t.minor*2;return Math.max(0,100-a)}function me(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 he(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 tt(t,a,i){const r=[],n=me(t),s=me(a),c={r:Math.max(0,n.r-40),g:Math.max(0,n.g-40),b:Math.max(0,n.b-40)},l=`#${c.r.toString(16).padStart(2,"0")}${c.g.toString(16).padStart(2,"0")}${c.b.toString(16).padStart(2,"0")}`,p=he(c),f=he(s);(Math.max(p,f)+.05)/(Math.min(p,f)+.05)>=i&&r.push(`Try darker foreground: ${l}`);const y={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},w=`#${y.r.toString(16).padStart(2,"0")}${y.g.toString(16).padStart(2,"0")}${y.b.toString(16).padStart(2,"0")}`;return r.push(`Try lighter background: ${w}`),r}const ye={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 rt({config:t,wcagLevel:a="AA",onAuditComplete:i,showContrastChecker:r=!0,className:n,style:s,renderIssue:c}){const[l,p]=d.useState(""),[f,g]=d.useState("#333333"),[y,w]=d.useState("#ffffff"),[S,z]=d.useState(null),{analyzeHTML:k,checkContrast:I,suggestAccessibleCode:j,loading:o,lastAudit:N,isConfigured:_}=ka({config:t,wcagLevel:a,onAuditComplete:i}),m=async()=>{!l.trim()||o||await k(l)},v=()=>{const u=I(f,y);z(u)},x=async()=>{if(!l.trim())return;const u=await j(l);p(u)};return _?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:"Color Contrast Checker"}),e.jsxs("div",{className:"nice-a11y-ai__contrast-inputs",children:[e.jsxs("label",{children:["Foreground",e.jsx("input",{type:"color",value:f,onChange:u=>g(u.target.value)}),e.jsx("input",{type:"text",value:f,onChange:u=>g(u.target.value)})]}),e.jsxs("label",{children:["Background",e.jsx("input",{type:"color",value:y,onChange:u=>w(u.target.value)}),e.jsx("input",{type:"text",value:y,onChange:u=>w(u.target.value)})]}),e.jsx("button",{type:"button",onClick:v,children:"Check"})]}),S&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:f,background:y},children:"Sample Text Aa"}),e.jsxs("div",{className:"nice-a11y-ai__contrast-ratio",children:[e.jsxs("span",{className:"nice-a11y-ai__ratio-value",children:[S.ratio,":1"]}),e.jsxs("div",{className:"nice-a11y-ai__passes",children:[e.jsxs("span",{className:S.passesAA?"pass":"fail",children:["AA: ",e.jsx(L.NiceIcon,{name:S.passesAA?"check":"close",size:14})]}),e.jsxs("span",{className:S.passesAALarge?"pass":"fail",children:["AA Large:"," ",e.jsx(L.NiceIcon,{name:S.passesAALarge?"check":"close",size:14})]}),e.jsxs("span",{className:S.passesAAA?"pass":"fail",children:["AAA: ",e.jsx(L.NiceIcon,{name:S.passesAAA?"check":"close",size:14})]})]})]}),S.suggestions&&S.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:S.suggestions.map((u,h)=>e.jsx("div",{children:u},h))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsxs("h3",{children:["HTML Accessibility Analyzer (WCAG ",a,")"]}),e.jsx("textarea",{value:l,onChange:u=>p(u.target.value),placeholder:"Paste HTML code to analyze...",className:"nice-a11y-ai__input",rows:8,disabled:o}),e.jsxs("div",{className:"nice-a11y-ai__actions",children:[e.jsx("button",{type:"button",onClick:m,disabled:o||!l.trim(),children:o?e.jsx("span",{className:"nice-a11y-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"search",size:14})," Analyze"]})}),e.jsxs("button",{type:"button",onClick:x,disabled:o||!l.trim(),children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Auto-Fix"]})]})]}),N&&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:N.score}),e.jsx("span",{className:"nice-a11y-ai__score-label",children:"Score"})]}),e.jsxs("div",{className:"nice-a11y-ai__summary",children:[e.jsxs("span",{className:"critical",children:[N.summary.critical," Critical"]}),e.jsxs("span",{className:"serious",children:[N.summary.serious," Serious"]}),e.jsxs("span",{className:"moderate",children:[N.summary.moderate," Moderate"]}),e.jsxs("span",{className:"minor",children:[N.summary.minor," Minor"]})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:N.issues.map(u=>c?c(u):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:ye[u.severity].bg,borderLeftColor:ye[u.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(L.NiceIcon,{name:ye[u.severity].icon,size:16})}),e.jsx("span",{className:"nice-a11y-ai__issue-title",children:u.title}),e.jsxs("span",{className:"nice-a11y-ai__issue-wcag",children:["WCAG ",u.wcagCriteria," (",u.wcagLevel,")"]})]}),e.jsx("p",{className:"nice-a11y-ai__issue-desc",children:u.description}),u.element&&e.jsx("code",{className:"nice-a11y-ai__issue-element",children:u.element}),e.jsxs("div",{className:"nice-a11y-ai__issue-suggestion",children:[e.jsx("strong",{children:"Fix:"})," ",u.suggestion]}),u.codeExample&&e.jsx("pre",{className:"nice-a11y-ai__issue-example",children:u.codeExample})]},u.id))}),N.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:"General Recommendations"}),e.jsx("ul",{children:N.recommendations.map((u,h)=>e.jsx("li",{children:u},h))})]})]}),e.jsx("style",{children:`
|
|
2917
2981
|
.nice-a11y-ai {
|
|
2918
2982
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
2919
2983
|
}
|
|
@@ -3012,7 +3076,7 @@ ${o}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:k.message)==nu
|
|
|
3012
3076
|
|
|
3013
3077
|
.nice-a11y-ai__suggestions {
|
|
3014
3078
|
padding: var(--nice-space-3, 12px);
|
|
3015
|
-
background: var(--nice-warning-
|
|
3079
|
+
background: var(--nice-warning-bg, #fff8e1);
|
|
3016
3080
|
border-radius: var(--nice-radius-md, 6px);
|
|
3017
3081
|
font-size: 13px;
|
|
3018
3082
|
}
|
|
@@ -3083,7 +3147,8 @@ ${o}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:k.message)==nu
|
|
|
3083
3147
|
|
|
3084
3148
|
.nice-a11y-ai__audit {
|
|
3085
3149
|
padding: var(--nice-space-5, 20px);
|
|
3086
|
-
background:
|
|
3150
|
+
background: var(--nice-bg-primary, #fff);
|
|
3151
|
+
color: var(--nice-text-primary, #1f2937);
|
|
3087
3152
|
border-radius: var(--nice-radius-lg, 8px);
|
|
3088
3153
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
3089
3154
|
}
|
|
@@ -3211,14 +3276,14 @@ ${o}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:k.message)==nu
|
|
|
3211
3276
|
margin-bottom: var(--nice-space-1-5, 6px);
|
|
3212
3277
|
font-size: 14px;
|
|
3213
3278
|
}
|
|
3214
|
-
`})]}):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 ye=[{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 ja(t={}){const{config:a,defaultLibrary:i="lucide",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:c}=t,l=Q(),[m,g]=d.useState(!1),[x,w]=d.useState(null),N=d.useRef(null),S=a||(l==null?void 0:l.config),R=d.useCallback(y=>{const p=y.toLowerCase(),b=p.split(/\s+/);return ye.map(v=>{let u=0;return v.name===p?u+=100:v.name.includes(p)&&(u+=50),b.forEach(h=>{v.keywords.forEach($=>{$===h?u+=30:($.includes(h)||h.includes($))&&(u+=15)})}),v.category===p&&(u+=20),{id:`icon_${v.name}`,name:v.name,displayName:v.name.replace(/-/g," ").replace(/\b\w/g,h=>h.toUpperCase()),category:v.category,style:r,library:i,relevanceScore:u,keywords:v.keywords,svgPath:v.svgPath}}).filter(v=>v.relevanceScore>0).sort((v,u)=>u.relevanceScore-v.relevanceScore).slice(0,n)},[i,r,n]),j=d.useCallback(async(y,p)=>{var u,h,$,E;const b=performance.now(),v=R(y);if(!S){const C={query:y,suggestions:v,latencyMs:performance.now()-b};return w(C),s==null||s(C),C}g(!0),(u=N.current)==null||u.abort(),N.current=new AbortController;try{const C=V(S),A=p?`
|
|
3279
|
+
`})]}):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 ve=[{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 Na(t={}){const{config:a,defaultLibrary:i="lucide",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:c}=t,l=Z(),[p,f]=d.useState(!1),[g,y]=d.useState(null),w=d.useRef(null),S=a||(l==null?void 0:l.config),z=d.useCallback(_=>{const m=_.toLowerCase(),v=m.split(/\s+/);return ve.map(x=>{let u=0;return x.name===m?u+=100:x.name.includes(m)&&(u+=50),v.forEach(h=>{x.keywords.forEach($=>{$===h?u+=30:($.includes(h)||h.includes($))&&(u+=15)})}),x.category===m&&(u+=20),{id:`icon_${x.name}`,name:x.name,displayName:x.name.replace(/-/g," ").replace(/\b\w/g,h=>h.toUpperCase()),category:x.category,style:r,library:i,relevanceScore:u,keywords:x.keywords,svgPath:x.svgPath}}).filter(x=>x.relevanceScore>0).sort((x,u)=>u.relevanceScore-x.relevanceScore).slice(0,n)},[i,r,n]),k=d.useCallback(async(_,m)=>{var u,h,$,D;const v=performance.now(),x=z(_);if(!S){const C={query:_,suggestions:x,latencyMs:performance.now()-v};return y(C),s==null||s(C),C}f(!0),(u=w.current)==null||u.abort(),w.current=new AbortController;try{const C=K(S),A=m?`
|
|
3215
3280
|
Context:
|
|
3216
|
-
- Component type: ${
|
|
3217
|
-
- Purpose: ${
|
|
3218
|
-
- Related icons: ${((h=
|
|
3219
|
-
- Theme: ${
|
|
3220
|
-
- Preferred style: ${
|
|
3221
|
-
- Preferred library: ${
|
|
3281
|
+
- Component type: ${m.componentType||"any"}
|
|
3282
|
+
- Purpose: ${m.purpose||"general"}
|
|
3283
|
+
- Related icons: ${((h=m.relatedIcons)==null?void 0:h.join(", "))||"none"}
|
|
3284
|
+
- Theme: ${m.theme||"light"}
|
|
3285
|
+
- Preferred style: ${m.preferredStyle||r}
|
|
3286
|
+
- Preferred library: ${m.preferredLibrary||i}`:"",b=(((D=($=(await C.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
|
|
3222
3287
|
Return JSON array of 5-10 icon suggestions:
|
|
3223
3288
|
[{
|
|
3224
3289
|
"name": "icon-name",
|
|
@@ -3229,7 +3294,7 @@ Return JSON array of 5-10 icon suggestions:
|
|
|
3229
3294
|
"usage": "Brief usage description"
|
|
3230
3295
|
}]
|
|
3231
3296
|
|
|
3232
|
-
Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${
|
|
3297
|
+
Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${_}"${A}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:$.message)==null?void 0:D.content)||"").match(/\[[\s\S]*\]/);let P=[];if(b)try{P=JSON.parse(b[0]).map((U,q)=>({id:U.id||`ai_icon_${q}`,name:U.name||"unknown",displayName:U.displayName||U.name||"Unknown",category:U.category||"action",style:(m==null?void 0:m.preferredStyle)||r,library:(m==null?void 0:m.preferredLibrary)||i,relevanceScore:U.relevanceScore||50,keywords:U.keywords||[],usage:U.usage}))}catch{}const H=nt(x,P,n),J={query:_,suggestions:H,latencyMs:performance.now()-v};return y(J),s==null||s(J),J}catch(C){const A=C instanceof Error?C.message:"Suggestion failed",O={query:_,suggestions:x,latencyMs:performance.now()-v,error:A};return y(O),c==null||c(A),O}finally{f(!1)}},[S,i,r,n,z,s,c]),I=d.useCallback(_=>ve.filter(m=>m.category===_).map(m=>({id:`icon_${m.name}`,name:m.name,displayName:m.name.replace(/-/g," ").replace(/\b\w/g,v=>v.toUpperCase()),category:m.category,style:r,library:i,relevanceScore:100,keywords:m.keywords,svgPath:m.svgPath})),[i,r]),j=d.useMemo(()=>{const _=new Set;return ve.forEach(m=>_.add(m.category)),Array.from(_)},[]),o=d.useCallback(()=>{y(null)},[]),N=d.useCallback(()=>{var _;(_=w.current)==null||_.abort(),f(!1)},[]);return d.useEffect(()=>()=>{var _;(_=w.current)==null||_.abort()},[]),{suggestIcons:k,localSearch:z,getByCategory:I,categories:j,loading:p,lastResult:g,clearResults:o,abort:N,isConfigured:!!S}}function nt(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 st({config:t,defaultLibrary:a="lucide",defaultStyle:i="outline",maxSuggestions:r=10,onSelect:n,showCategories:s=!0,showPreview:c=!0,className:l,style:p}){const[f,g]=d.useState(""),[y,w]=d.useState(null),[S,z]=d.useState(null),{suggestIcons:k,getByCategory:I,categories:j,loading:o,lastResult:N}=Na({config:t,defaultLibrary:a,defaultStyle:i,maxSuggestions:r}),_=async()=>{f.trim()&&(w(null),await k(f))},m=h=>{h.key==="Enter"&&_()},v=h=>{y===h?w(null):(w(h),g(""))},x=h=>{z(h),n==null||n(h)},u=y?I(y):(N==null?void 0:N.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${l||""}`,style:p,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:f,onChange:h=>g(h.target.value),onKeyDown:m,placeholder:"Search icons... (e.g., 'save', 'notification', 'user profile')",className:"nice-icon-ai__input",disabled:o}),e.jsx("button",{type:"button",onClick:_,className:"nice-icon-ai__search-btn",disabled:o||!f.trim(),children:o?e.jsx("span",{className:"nice-icon-ai__spinner"}):e.jsx(L.NiceIcon,{name:"search",size:16})})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:j.map(h=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${y===h?"nice-icon-ai__category--selected":""}`,onClick:()=>v(h),children:h},h))}),u.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:u.map(h=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${(S==null?void 0:S.id)===h.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>x(h),title:h.displayName,children:[e.jsx(Je,{icon:h}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:h.displayName})]},h.id))}),c&&S&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(Je,{icon:S,size:64})}),e.jsxs("div",{className:"nice-icon-ai__preview-info",children:[e.jsx("div",{className:"nice-icon-ai__preview-name",children:S.displayName}),e.jsxs("div",{className:"nice-icon-ai__preview-details",children:[e.jsxs("span",{children:["Category: ",S.category]}),e.jsxs("span",{children:["Library: ",S.library]})]}),e.jsx("div",{className:"nice-icon-ai__preview-keywords",children:S.keywords.map(h=>e.jsx("span",{className:"nice-icon-ai__keyword",children:h},h))}),S.usage&&e.jsx("div",{className:"nice-icon-ai__preview-usage",children:S.usage}),e.jsxs("div",{className:"nice-icon-ai__preview-actions",children:[e.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(S),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Icon"]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(S.name)},children:[e.jsx(L.NiceIcon,{name:"clipboard",size:14})," Copy Name"]}),S.svgPath&&e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(`<svg viewBox="0 0 24 24"><path d="${S.svgPath}" /></svg>`)},children:[e.jsx(L.NiceIcon,{name:"clipboard",size:14})," Copy SVG"]})]})]})]}),e.jsx("style",{children:`
|
|
3233
3298
|
.nice-icon-ai {
|
|
3234
3299
|
font-family: var(--nice-font-family, system-ui, sans-serif);
|
|
3235
3300
|
}
|
|
@@ -3292,7 +3357,8 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
|
|
|
3292
3357
|
padding: var(--nice-space-1-5, 6px) var(--nice-space-3, 12px);
|
|
3293
3358
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
3294
3359
|
border-radius: var(--nice-radius-xl, 20px);
|
|
3295
|
-
background:
|
|
3360
|
+
background: var(--nice-bg-primary, #fff);
|
|
3361
|
+
color: var(--nice-text-primary, #1f2937);
|
|
3296
3362
|
font-size: 12px;
|
|
3297
3363
|
cursor: pointer;
|
|
3298
3364
|
text-transform: capitalize;
|
|
@@ -3324,7 +3390,8 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
|
|
|
3324
3390
|
padding: var(--nice-space-4, 16px) var(--nice-space-2, 8px);
|
|
3325
3391
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
3326
3392
|
border-radius: var(--nice-radius-lg, 8px);
|
|
3327
|
-
background:
|
|
3393
|
+
background: var(--nice-bg-primary, #fff);
|
|
3394
|
+
color: var(--nice-text-primary, #1f2937);
|
|
3328
3395
|
cursor: pointer;
|
|
3329
3396
|
transition: all 0.2s;
|
|
3330
3397
|
}
|
|
@@ -3362,7 +3429,8 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
|
|
|
3362
3429
|
justify-content: center;
|
|
3363
3430
|
width: 100px;
|
|
3364
3431
|
height: 100px;
|
|
3365
|
-
background:
|
|
3432
|
+
background: var(--nice-bg-primary, #fff);
|
|
3433
|
+
color: var(--nice-text-primary, #1f2937);
|
|
3366
3434
|
border-radius: var(--nice-radius-xl, 12px);
|
|
3367
3435
|
box-shadow: 0 2px 8px var(--nice-overlay-5, rgba(0, 0, 0, 0.05));
|
|
3368
3436
|
}
|
|
@@ -3416,7 +3484,8 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
|
|
|
3416
3484
|
padding: var(--nice-space-2, 8px) var(--nice-space-4, 16px);
|
|
3417
3485
|
border: 1px solid var(--nice-border-color, #e0e0e0);
|
|
3418
3486
|
border-radius: var(--nice-radius-md, 6px);
|
|
3419
|
-
background:
|
|
3487
|
+
background: var(--nice-bg-primary, #fff);
|
|
3488
|
+
color: var(--nice-text-primary, #1f2937);
|
|
3420
3489
|
font-size: 12px;
|
|
3421
3490
|
cursor: pointer;
|
|
3422
3491
|
}
|
|
@@ -3426,4 +3495,4 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
|
|
|
3426
3495
|
color: white;
|
|
3427
3496
|
border: none;
|
|
3428
3497
|
}
|
|
3429
|
-
`})]})}function
|
|
3498
|
+
`})]})}function Je({icon:t,size:a=32}){return t.svgPath?e.jsx("svg",{viewBox:"0 0 24 24",width:a,height:a,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:t.svgPath})}):e.jsx("div",{style:{width:a,height:a,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-bg-secondary, #f0f0f0)",borderRadius:6,fontSize:a*.5,fontWeight:600,color:"var(--nice-text-secondary, #666)"},children:t.name.charAt(0).toUpperCase()})}exports.ACCESSIBILITY_CHECKER_TEMPLATE=je;exports.AnthropicProvider=na;exports.AzureOpenAIProvider=sa;exports.CHART_CONFIG_TEMPLATE=le;exports.CODE_COMPLETION_TEMPLATE=de;exports.CostTracker=da;exports.DATA_GRID_FILTER_TEMPLATE=se;exports.DATA_GRID_SORT_TEMPLATE=ce;exports.FORM_BUILDER_TEMPLATE=oe;exports.GroqProvider=oa;exports.InMemoryCostStorage=Me;exports.LocalStorageCostStorage=la;exports.NiceAIHintBubble=Se;exports.NiceAIProvider=Sa;exports.NiceAccessibilityAI=rt;exports.NiceChartAI=ji;exports.NiceCodeEditorAI=Ri;exports.NiceDataGridAI=xi;exports.NiceDataLabeler=si;exports.NiceFormBuilderAI=yi;exports.NiceIconSuggestorAI=st;exports.NiceLayoutAI=Qi;exports.NiceMLStudio=ri;exports.NiceModelInference=oi;exports.NiceReportBuilderAI=Ui;exports.NiceThemeGeneratorAI=Vi;exports.NiceWorkflowDesignerAI=Pi;exports.OllamaProvider=ca;exports.OpenAIProvider=_e;exports.PROMPT_TEMPLATES=ge;exports.REPORT_LAYOUT_TEMPLATE=pe;exports.RateLimiter=Ue;exports.ResilientLLMClient=ua;exports.SUMMARIZE_DATA_TEMPLATE=Ne;exports.THEME_GENERATOR_TEMPLATE=we;exports.TRANSLATION_TEMPLATE=ke;exports.WORKFLOW_GENERATOR_TEMPLATE=ue;exports.build3DSceneContext=Ze;exports.buildAudioContext=Xe;exports.buildChartContext=za;exports.buildCodeEditorContext=Ke;exports.buildColorPickerContext=ze;exports.buildDataGridContext=Ia;exports.buildDatePickerContext=Ie;exports.buildDiagramLayoutContext=ia;exports.buildFormFillContext=Ge;exports.buildGameEngineContext=aa;exports.buildGraphicsContext=Qe;exports.buildHtmlEditorContext=Ye;exports.buildIconSearchContext=ea;exports.buildNumberInputContext=Ae;exports.buildPresentationGenerateContext=ta;exports.buildSelectContext=Re;exports.buildSlideDesignContext=ra;exports.buildTextInputContext=Te;exports.buildValidationContext=Ve;exports.colorControlContext=ai;exports.compileTemplate=ie;exports.createLLMProvider=ae;exports.createProviderFromConfig=K;exports.createResilientClient=pa;exports.createResilientClientWithDefaults=hi;exports.dateControlContext=ei;exports.getTemplate=li;exports.getTemplatesByCategory=di;exports.listTemplates=ui;exports.numberControlContext=Za;exports.parseJSONResponse=We;exports.parseSSEStream=He;exports.selectControlContext=Qa;exports.textControlContext=Xa;exports.useAI3DHint=Ua;exports.useAIAudioHint=Ja;exports.useAICodeHint=Ba;exports.useAIColorHint=Oa;exports.useAIContext=Z;exports.useAIDateHint=$a;exports.useAIDiagramLayout=Ga;exports.useAIFormFill=Da;exports.useAIGraphicsHint=qa;exports.useAIHtmlHint=Fa;exports.useAIIconSearch=Ha;exports.useAINpcHint=Wa;exports.useAINumberHint=La;exports.useAIPresentationGenerate=Va;exports.useAISelectHint=Pa;exports.useAISlideDesign=Ka;exports.useAITextHint=Ma;exports.useAIValidation=Ea;exports.useAccessibilityAI=ka;exports.useChartAI=ga;exports.useCodeEditorAI=fa;exports.useCostTracker=pi;exports.useDataGridAI=ma;exports.useFormBuilderAI=ha;exports.useIconSuggestorAI=Na;exports.useLayoutAI=wa;exports.useNiceAIHint=X;exports.useReportBuilderAI=ya;exports.useThemeGeneratorAI=_a;exports.useWorkflowDesignerAI=xa;exports.withAIHint=Ya;
|