BossBey File Manager
PHP:
8.2.30
OS:
Linux
User:
imagivibe
Root
/
home
/
imagivibe
/
www
/
app.imagivibe.com
/
public
/
build
/
assets
📤 Upload
📝 New File
📁 New Folder
Close
Editing: app-d9de7e52.js
import"./createEcho-b711dbcd.js";import{f as I,e as d,m as P,L as M}from"./fetch-f400bdf7.js";import{c as V}from"./clipboard-f64d1f4d.js";function E(i={show:!1,focusable:!1}){return{show:i.show,focusable:i.focusable,closeModal(){this.show=!1},openModal(){this.show=!0},focusables(){let e="a, button, input:not([type='hidden']), textarea, select, details, [tabindex]:not([tabindex='-1'])";return[...this.$el.querySelectorAll(e)].filter(t=>!t.hasAttribute("disabled"))},firstFocusable(){return this.focusables()[0]},lastFocusable(){return this.focusables().slice(-1)[0]},nextFocusable(){return this.focusables()[this.nextFocusableIndex()]||this.firstFocusable()},prevFocusable(){return this.focusables()[this.prevFocusableIndex()]||this.lastFocusable()},nextFocusableIndex(){return(this.focusables().indexOf(document.activeElement)+1)%(this.focusables().length+1)},prevFocusableIndex(){return Math.max(0,this.focusables().indexOf(document.activeElement))-1},init(){this.$watch("show",e=>{e?(document.body.classList.add("overflow-y-hidden"),this.focusable!==!1&&setTimeout(()=>this.firstFocusable().focus(),100)):document.body.classList.remove("overflow-y-hidden")})}}}function L(i={}){return{isShared:i.isShared??!1,limits:i.limits??{},init(){},pushToAiEngines(e){this.aiEngines.push(e)}}}class D{constructor(){this.playbackNode=null}async init(e){this.audioContext=new AudioContext({sampleRate:e}),await this.audioContext.audioWorklet.addModule("/themes/default/assets/js/audio/playback-worklet.js"),this.playbackNode=new AudioWorkletNode(this.audioContext,"playback-worklet"),this.playbackNode.connect(this.audioContext.destination)}play(e){this.playbackNode&&this.playbackNode.port.postMessage(e)}clear(){this.playbackNode&&this.playbackNode.port.postMessage(null)}}class R{constructor(e){this.onDataAvailable=e,this.audioContext=null,this.mediaStream=null,this.mediaStreamSource=null,this.workletNode=null}async start(e){try{this.audioContext=new AudioContext({sampleRate:24e3}),await this.audioContext.audioWorklet.addModule("/themes/default/assets/js/audio/audio-worklet-processor.js"),this.mediaStream=e,this.mediaStreamSource=this.audioContext.createMediaStreamSource(this.mediaStream),this.workletNode=new AudioWorkletNode(this.audioContext,"audio-worklet-processor"),this.workletNode.port.onmessage=t=>this.onDataAvailable(t.data.buffer),this.mediaStreamSource.connect(this.workletNode)}catch(t){console.error("Error in recorder start:",t),this.stop()}}stop(){this.mediaStream&&this.mediaStream.getTracks().forEach(e=>e.stop()),this.audioContext&&this.audioContext.state!=="closed"&&this.audioContext.close()}getMediaStreamSource(){return this.mediaStreamSource}}function b(i,e,t,s){function a(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function l(u){try{n(s.next(u))}catch(h){o(h)}}function c(u){try{n(s.throw(u))}catch(h){o(h)}}function n(u){u.done?r(u.value):a(u.value).then(l,c)}n((s=s.apply(i,e||[])).next())})}function g(i,e){var t={label:0,sent:function(){if(r[0]&1)throw r[1];return r[1]},trys:[],ops:[]},s,a,r,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=l(0),o.throw=l(1),o.return=l(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function l(n){return function(u){return c([n,u])}}function c(n){if(s)throw new TypeError("Generator is already executing.");for(;o&&(o=0,n[0]&&(t=0)),t;)try{if(s=1,a&&(r=n[0]&2?a.return:n[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,n[1])).done)return r;switch(a=0,r&&(n=[n[0]&2,r.value]),n[0]){case 0:case 1:r=n;break;case 4:return t.label++,{value:n[1],done:!1};case 5:t.label++,a=n[1],n=[0];continue;case 7:n=t.ops.pop(),t.trys.pop();continue;default:if(r=t.trys,!(r=r.length>0&&r[r.length-1])&&(n[0]===6||n[0]===2)){t=0;continue}if(n[0]===3&&(!r||n[1]>r[0]&&n[1]<r[3])){t.label=n[1];break}if(n[0]===6&&t.label<r[1]){t.label=r[1],r=n;break}if(r&&t.label<r[2]){t.label=r[2],t.ops.push(n);break}r[2]&&t.ops.pop(),t.trys.pop();continue}n=e.call(i,t)}catch(u){n=[6,u],a=0}finally{s=r=0}if(n[0]&5)throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}}function T(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],s=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function k(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var s=t.call(i),a,r=[],o;try{for(;(e===void 0||e-- >0)&&!(a=s.next()).done;)r.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return r}function y(i){return this instanceof y?(this.v=i,this):new y(i)}function F(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),a,r=[];return a=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),l("next"),l("throw"),l("return",o),a[Symbol.asyncIterator]=function(){return this},a;function o(f){return function(m){return Promise.resolve(m).then(f,h)}}function l(f,m){s[f]&&(a[f]=function(v){return new Promise(function(w,C){r.push([f,v,w,C])>1||c(f,v)})},m&&(a[f]=m(a[f])))}function c(f,m){try{n(s[f](m))}catch(v){p(r[0][3],v)}}function n(f){f.value instanceof y?Promise.resolve(f.value.v).then(u,h):p(r[0][2],f)}function u(f){c("next",f)}function h(f){c("throw",f)}function p(f,m){f(m),r.shift(),r.length&&c(r[0][0],r[0][1])}}function q(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof T=="function"?T(i):i[Symbol.iterator](),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(r){t[r]=i[r]&&function(o){return new Promise(function(l,c){o=i[r](o),a(l,c,o.done,o.value)})}}function a(r,o,l,c){Promise.resolve(c).then(function(n){r({value:n,done:l})},o)}}var z=function(i){return typeof i=="object"&&i!==null&&"type"in i},B=function(i){return z(i)&&["error","session.created","session.updated","input_audio_buffer.committed","input_audio_buffer.cleared","input_audio_buffer.speech_started","input_audio_buffer.speech_stopped","conversation.item.created","conversation.item.truncated","conversation.item.deleted","conversation.item.input_audio_transcription.completed","conversation.item.input_audio_transcription.failed","response.created","response.done","response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.text.delta","response.text.done","response.audio_transcript.delta","response.audio_transcript.done","response.audio.delta","response.audio.done","response.function_call_arguments.delta","response.function_call_arguments.done","rate_limits.updated"].includes(i.type)},N=WebSocket,W=function(i,e){return i.readyState!==WebSocket.OPEN?Promise.reject(new Error("Socket is not open")):(i.send(e),Promise.resolve())},O=function(i){return{success:!0,message:i}},x=function(i){return{success:!1,error:i}},U=function(i){return i.success},j=function(){function i(e,t){var s=this;this.closedPromise=void 0,this.messageQueue=[],this.receiverQueue=[],this.done=!1,this.validate=t.validate,this.serialize=t.serialize,this.connectedPromise=new Promise(function(a,r){return b(s,void 0,void 0,function(){var o,l,c,n,u=this;return g(this,function(h){switch(h.label){case 0:return e.policy!==void 0?[3,1]:(n=e,[3,3]);case 1:return[4,e.policy(e)];case 2:n=h.sent(),h.label=3;case 3:return o=n,l=o.uri,c=o.protocols,this.socket=new N(l.toString(),c),this.socket.onopen=function(){u.socket.onmessage=u.getMessageHandler(),u.closedPromise=new Promise(function(p){u.socket.onclose=u.getClosedHandler(p)}),u.socket.onerror=u.handleError,a()},this.socket.onerror=function(p){u.error=p.error,r(p)},[2]}})})})}return i.prototype.handleError=function(e){for(this.error=e.error;this.receiverQueue.length>0;){var t=k(this.receiverQueue.shift(),2);t[0];var s=t[1];s(e.error)}},i.prototype.getClosedHandler=function(e){var t=this;return function(s){for(t.done=!0;t.receiverQueue.length>0;){var a=k(t.receiverQueue.shift(),2),r=a[0],o=a[1];t.error?o(t.error):r({value:void 0,done:!0})}e()}},i.prototype.getMessageHandler=function(){var e=this;return function(t){var s=e.validate(t);if(U(s)){var a=s.message;if(e.receiverQueue.length>0){var r=k(e.receiverQueue.shift(),2),o=r[0];r[1],o({value:a,done:!1})}else e.messageQueue.push(a)}else e.error=s.error,e.socket.close(1e3,"Unexpected message received")}},i.prototype[Symbol.asyncIterator]=function(){var e=this;return{next:function(){if(e.error)return Promise.reject(e.error);if(e.done)return Promise.resolve({value:void 0,done:!0});if(e.messageQueue.length>0){var t=e.messageQueue.shift();return Promise.resolve({value:t,done:!1})}else return new Promise(function(s,a){e.receiverQueue.push([s,a])})}}},i.prototype.send=function(e){return b(this,void 0,void 0,function(){var t;return g(this,function(s){switch(s.label){case 0:return[4,this.connectedPromise];case 1:if(s.sent(),this.error)throw this.error;return t=this.serialize(e),[2,W(this.socket,t)]}})})},i.prototype.close=function(){return b(this,void 0,void 0,function(){return g(this,function(e){switch(e.label){case 0:return[4,this.connectedPromise];case 1:return e.sent(),this.done?[2]:(this.socket.close(),[4,this.closedPromise]);case 2:return e.sent(),[2]}})})},i}();function _(i){return typeof i=="object"&&i!==null&&"key"in i&&typeof i.key=="string"}function Z(i){return typeof i=="object"&&i!==null&&"getToken"in i&&typeof i.getToken=="function"}var H=function(i){return _(i)||Z(i)},K=function(i){return typeof i=="object"&&i!==null&&"model"in i&&typeof i.model=="string"},Q=function(i){return typeof i=="object"&&i!==null&&"deployment"in i&&typeof i.deployment=="string"},J=function(){function i(e,t,s){var a=this,r=function(){if(_(e)&&K(t))return a.openAISettings(e,t);if(H(t)&&Q(s))return a.azureOpenAISettings(e,t,s);throw new Error("Invalid combination of arguments to initialize the Realtime client")}();this.client=this.getWebsocket(r)}return i.prototype.azureOpenAISettings=function(e,t,s){var a=this,r=["https://cognitiveservices.azure.com/.default"];return this.requestId=crypto.randomUUID(),e.searchParams.set("api-version","2024-10-01-preview"),e.searchParams.set("x-ms-client-request-id",this.requestId),e.searchParams.set("deployment",s.deployment),e.pathname="openai/realtime",{uri:e,policy:function(o){return b(a,void 0,void 0,function(){var l;return g(this,function(c){switch(c.label){case 0:return _(t)?(o.uri.searchParams.set("api-key",t.key),[3,3]):[3,1];case 1:return[4,t.getToken(r)];case 2:l=c.sent(),o.uri.searchParams.set("Authorization","Bearer ".concat(l.token)),c.label=3;case 3:return[2,o]}})})}}},i.prototype.openAISettings=function(e,t){var s=new URL("wss://api.openai.com/v1/realtime");return s.searchParams.set("model",t.model),{uri:s,protocols:["realtime","openai-insecure-api-key.".concat(e.key),"openai-beta.realtime-v1"]}},i.prototype.getWebsocket=function(e){var t={validate:function(s){if(typeof s.data!="string")return x(new Error("Invalid message type"));try{var a=JSON.parse(s.data);return B(a)?O(a):x(new Error("Invalid message type"))}catch{return x(new Error("Invalid JSON message"))}},serialize:function(s){return JSON.stringify(s)}};return new j(e,t)},i.prototype.messages=function(){return F(this,arguments,function(){var t,s,a,r,o,l,c,n,u;return g(this,function(h){switch(h.label){case 0:h.trys.push([0,7,8,13]),t=!0,s=q(this.client),h.label=1;case 1:return[4,y(s.next())];case 2:return a=h.sent(),l=a.done,!l?(u=a.value,t=!1,r=u,[4,y(r)]):[3,6];case 3:return[4,h.sent()];case 4:h.sent(),h.label=5;case 5:return t=!0,[3,1];case 6:return[3,13];case 7:return o=h.sent(),c={error:o},[3,13];case 8:return h.trys.push([8,,11,12]),!t&&!l&&(n=s.return)?[4,y(n.call(s))]:[3,10];case 9:h.sent(),h.label=10;case 10:return[3,12];case 11:if(c)throw c.error;return[7];case 12:return[7];case 13:return[2]}})})},i.prototype.send=function(e){return b(this,void 0,void 0,function(){return g(this,function(t){switch(t.label){case 0:return[4,this.client.send(e)];case 1:return t.sent(),[2]}})})},i.prototype.close=function(){return b(this,void 0,void 0,function(){return g(this,function(e){switch(e.label){case 0:return[4,this.client.close()];case 1:return e.sent(),[2]}})})},i}();const G=(i,e,t)=>({apiKey:"",active:!1,recordingActive:!1,buffer:new Uint8Array,wsConnection:null,audioRecorder:null,audioPlayer:null,activeVisulaizer:"idle",audioVisWrap:null,audioVisBars:null,audioVisDotWrap:null,audioVisLoader:null,conversationArea:document.querySelector(".conversation-area"),chatsContainer:document.querySelector(".chats-container"),userBubbleTemplate:document.querySelector("#chat_user_bubble"),aiBubbleTemplate:document.querySelector("#chat_ai_bubble"),lastAiBubble:null,lastUserBubble:null,get isActive(){return this.active},init(){var o,l,c;const s=atob(i),a=atob(e),r=atob(t);this.apiKey=s+a+r,this.audioVisWrap=document.querySelector(".lqd-audio-vis-wrap"),this.audioVisBars=(o=this.audioVisWrap)==null?void 0:o.querySelectorAll(".lqd-audio-vis-bar"),this.audioVisDotWrap=(l=this.audioVisWrap)==null?void 0:l.querySelector(".lqd-audio-vis-dot-wrap"),this.audioVisLoader=(c=this.audioVisWrap)==null?void 0:c.querySelector(".lqd-audio-vis-loader"),this.processAudioRecordingBuffer=this.processAudioRecordingBuffer.bind(this),this.onActiveChange=this.onActiveChange.bind(this),this.$watch("active",this.onActiveChange)},async start(){this.active=!0,this.switchVisualizers("waiting"),this.wsConnection=new J({key:this.apiKey},{model:"gpt-4o-realtime-preview-2024-10-01"});try{console.log("sending session config"),await this.wsConnection.send(this.createConfigMessage())}catch(s){console.log(s);return}await Promise.all([this.startRecorder(),this.startPlayer()]),this.handleRealtimeMessages(),this.startBarsVisualizer(),this.startDotVisualizer(),this.switchVisualizers("idle")},stop(){this.resetPlayers(),this.wsConnection&&this.wsConnection.close(),this.switchVisualizers(""),this.active=!1},async startPlayer(){try{this.audioPlayer=new D,await this.audioPlayer.init(24e3)}catch(s){console.error("Error starting audio player:",s)}},async startRecorder(){try{this.audioRecorder=new R(this.processAudioRecordingBuffer);const s=await navigator.mediaDevices.getUserMedia({audio:!0});await this.audioRecorder.start(s),this.recordingActive=!0}catch(s){console.error("Error starting audio recorder:",s)}},onActiveChange(s){var a,r;this.$el.classList.toggle("active",s),(r=(a=this.audioVisWrap)==null?void 0:a.classList)==null||r.toggle("active",s)},createConfigMessage(){let s={type:"session.update",session:{turn_detection:{type:"server_vad",silence_duration_ms:500},input_audio_transcription:{model:"whisper-1"}}};const a=this.getSystemMessage(),r=this.getTemperature(),o=this.getVoice();return a&&(s.session.instructions=a),isNaN(r)||(s.session.temperature=r),o&&(s.session.voice=o),s},async handleRealtimeMessages(){for await(const s of this.wsConnection.messages()){let a=""+s.type;switch(s.type){case"session.created":this.switchVisualizers("idle");break;case"response.content_part.added":this.createChatBubble("ai");break;case"response.audio_transcript.delta":this.appendToChatBubble("ai",s.delta);break;case"response.audio.delta":{this.switchVisualizers("playing");const r=atob(s.delta),o=Uint8Array.from(r,c=>c.charCodeAt(0)),l=new Int16Array(o.buffer);this.audioPlayer.play(l);break}case"input_audio_buffer.speech_started":{this.createChatBubble("user"),this.switchVisualizers("recording"),this.audioPlayer.clear();break}case"conversation.item.input_audio_transcription.completed":this.appendToChatBubble("user",s.transcript);break;case"response.output_item.done":"highlightCode"in window&&this.lastAiBubble&&highlightCode(this.lastAiBubble);break;case"conversation.item.truncated":this.appendToChatBubble("ai","...");break;case"conversation.item.deleted":break;case"response.done":break;default:a=JSON.stringify(s,null,2);break}a&&console.log(a)}this.resetPlayers()},combineArray(s){const a=new Uint8Array(this.buffer.length+s.length);a.set(this.buffer),a.set(s,this.buffer.length),this.buffer=a},processAudioRecordingBuffer(s){const a=new Uint8Array(s);if(this.combineArray(a),this.buffer.length>=4800){const r=new Uint8Array(this.buffer.slice(0,4800));this.buffer=new Uint8Array(this.buffer.slice(4800));const o=String.fromCharCode(...r),l=btoa(o);this.recordingActive&&this.wsConnection.send({type:"input_audio_buffer.append",audio:l})}},async resetPlayers(){var s,a;this.recordingActive=!1,(s=this.audioRecorder)==null||s.stop(),(a=this.audioPlayer)==null||a.clear()},getSystemMessage(){return""},getTemperature(){return parseFloat(.8)},getVoice(){return"alloy"},switchVisualizers(s){var a;this.activeVisulaizer=s,(a=this.audioVisWrap)==null||a.setAttribute("data-state",this.activeVisulaizer)},createChatBubble(s){const r=(s==="user"?this.userBubbleTemplate:this.aiBubbleTemplate).content.cloneNode(!0),o=r.querySelector(".chat-content");this.chatsContainer.appendChild(r),s==="user"?this.lastUserBubble=o:this.lastAiBubble=o,this.scrollConversationAreaToBottom()},appendToChatBubble(s,a){const r=s==="user"?this.lastUserBubble:this.lastAiBubble;r?(r.textContent+=a,this.scrollConversationAreaToBottom()):(this.createChatBubble(s),this.appendToChatBubble(s,a))},scrollConversationAreaToBottom(){this.conversationArea.scrollTo({top:this.conversationArea.scrollHeight+200,left:0})},startBarsVisualizer(){var n;if(!((n=this.audioVisBars)!=null&&n.length))return;const s=this.audioPlayer.audioContext.createAnalyser();s.fftSize=4096;const a=s.frequencyBinCount,r=new Uint8Array(a),o=this.audioVisBars.length;this.audioPlayer.playbackNode.connect(s);const l=[[85,150],[150,250],[250,400],[400,600],[600,1e3]];this.barHeights=this.barHeights||new Array(o).fill(0);const c=()=>{s.getByteFrequencyData(r),this.audioVisBars.forEach((u,h)=>{const[p,f]=l[h],m=Math.floor(p/(this.audioPlayer.audioContext.sampleRate/s.fftSize)),v=Math.ceil(f/(this.audioPlayer.audioContext.sampleRate/s.fftSize));let w=0;for(let S=m;S<=v&&S<r.length;S++)r[S]>w&&(w=r[S]);let C=w/255*80;this.barHeights[h]+=(C-this.barHeights[h])*.4,this.barHeights[h]+=(Math.random()-.5)*2,this.barHeights[h]=Math.max(5,Math.min(100,this.barHeights[h])),u.animate([{height:u.style.height},{height:`${this.barHeights[h]}%`}],{duration:30,fill:"forwards",easing:"linear"})}),requestAnimationFrame(c)};c()},startDotVisualizer(){if(!this.audioRecorder||!this.audioVisDotWrap)return;const s=this.audioRecorder.audioContext.createAnalyser();s.fftSize=256;const a=s.frequencyBinCount,r=new Uint8Array(a);this.audioRecorder.getMediaStreamSource().connect(s);const o=this.audioVisDotWrap.querySelector(".lqd-audio-vis-dot");if(!o)return;const l=()=>{s.getByteFrequencyData(r);let c=0;for(let p=0;p<a;p++)c+=r[p];const u=1+c/a/256*1.5,h=Math.max(.2,1-(u-1)/1.5);o.style.transform=`scale(${u})`,o.style.opacity=h.toFixed(2),requestAnimationFrame(l)};l()}}),X=(i={})=>({prevViews:[],currentView:"home",sidebarCollapsed:!1,modalShow:!1,activeModal:null,activeModalId:null,activeModalIdPrefix:null,currentToolsCat:"primary",predefinedPrompts:i.predefinedPrompts||[],tools:i.tools||[],primaryToolKeys:i.primaryToolKeys||[],uploadingFile:{},showImageDetails:!1,zoomLevel:1,reachedMinZoom:!1,reachedMaxZoom:!1,newItems:[],showNotif:!1,editingImageDimensions:{width:0,height:0},painting:!1,brushSize:40,canvasCtx:null,_busy:!1,_template:"",_prompt:"",_selectedTemplateDescription:"",_selectedPromptDescription:"",_selectedTool:"",_prevEditingImage:{},_editingImage:{},get busy(){return this._busy},set busy(e){this._busy=e},get selectedTemplate(){return this._template.trim()},set selectedTemplate(e){var t;this._template=e,(t=this.$refs.promptInput)==null||t.focus()},get prompt(){return this._prompt},set prompt(e){var t;this._prompt=e.trim(),(t=this.$refs.promptInput)==null||t.focus()},get selectedTemplateDescription(){return this._selectedTemplateDescription},set selectedTemplateDescription(e){this._selectedTemplateDescription!==e&&(this._selectedTemplateDescription=e)},get selectedPromptDescription(){return this._selectedPromptDescription},set selectedPromptDescription(e){this._selectedPromptDescription!==e&&(this._selectedPromptDescription=e)},get selectedTool(){return this._selectedTool},set selectedTool(e){this._selectedTool!==e&&(this._selectedTool=e,this.makeCanvasEditable(this._selectedTool==="sketch_to_image"?{width:1024,height:1024}:{}))},get prevEditingImage(){return this._prevEditingImage},get editingImage(){return this._editingImage},set editingImage(e){this._prevEditingImage=this._editingImage,this._editingImage=e,this.showImageDetails=!1,this.zoomLevel=1,fetch(e.output).then(t=>t.blob()).then(t=>{var r,o;const s=new File([t],((o=(r=e.title)==null?void 0:r.split("."))==null?void 0:o.at(0))||"image",{type:t.type}),a=new DataTransfer;a.items.add(s),this.$refs.uploadedImageInput.files=a.files}).catch(t=>{toastr.error("Failed to load image"),console.error("Error creating file from URL:",t)})},init(){this.onViewChange=this.onViewChange.bind(this),this.onZoomLevelChange=this.onZoomLevelChange.bind(this),this.makeCanvasEditable=this.makeCanvasEditable.bind(this),this.startPainting=this.startPainting.bind(this),this.stopPainting=this.stopPainting.bind(this),this.paint=this.paint.bind(this),document.documentElement.style.scrollbarGutter="stable",this.$watch("currentView",this.onViewChange),this.$watch("zoomLevel",this.onZoomLevelChange)},switchView(e){if(e==="<"){this.currentView=this.prevViews.pop()||"home";return}this.prevViews.push(this.currentView),this.currentView=e||"home"},switchSidebarCollapsed(e){if(e!=null){this.sidebarCollapsed=e;return}this.sidebarCollapsed=!this.sidebarCollapsed,this.$nextTick(()=>{this.zoomLevel>1&&this.fitToScreen()}),this.$refs.imageEditorSidebar.addEventListener("transitionend",t=>{t.target!==this.$refs.imageEditorSidebar&&t.propertyName!=="transform"||this.reachedMaxZoom&&this.fitToScreen()})},onViewChange(e){const t=e==="editor";document.documentElement.style.overflow=t?"hidden":""},setRandomPrompt(){this.prompt=this.predefinedPrompts[Math.floor(Math.random()*this.predefinedPrompts.length)]},setActiveModal(e,t="modal"){this.activeModal=e,this.activeModalId=e.id,this.activeModalIdPrefix=t},prevImageModal(){const e=document.querySelector(`.image-result[data-id='${this.activeModalId}'][data-id-prefix=${this.activeModalIdPrefix}]`),t=e==null?void 0:e.previousElementSibling;if(!t)return;const s=JSON.parse(t.getAttribute("data-payload")||{});this.setActiveModal(s,e.getAttribute("data-id-prefix"))},nextImageModal(){const e=document.querySelector(`.image-result[data-id='${this.activeModalId}'][data-id-prefix=${this.activeModalIdPrefix}]`),t=e==null?void 0:e.nextElementSibling;if(!t)return;const s=JSON.parse(t.getAttribute("data-payload")||{});this.setActiveModal(s,e.getAttribute("data-id-prefix"))},getSelectedToolCat(){return this.getToolCat(this.selectedTool)},switchToolsCat(e={}){if(e.cat)return this.currentToolsCat=e.cat;if(e.toolKey)return this.currentToolsCat=this.getToolCat(e.toolKey);if(!e.cat&&!e.toolKey)return this.currentToolsCat=this.currentToolsCat==="primary"?"secondary":"primary"},getToolCat(e){return this.primaryToolKeys.findIndex(t=>t===e)>=0?"primary":"secondary"},handleDragOver(){this.$refs.dropArea.classList.add("drag-over")},handleDragLeave(){this.$refs.dropArea.classList.remove("drag-over")},handleDrop(e){const{dataTransfer:t}=e,{files:s}=t;s&&(this.handleFiles(s),this.$refs.dropArea.classList.remove("drag-over"))},handleFileChange(e){const{files:t}=e.target;t&&this.handleFiles(t)},handleFiles(e){const t=e[0];this.editingImage={output:URL.createObjectURL(t),name:t.name},this.$refs.uploadedImageInput.files=e},resetUploadedImageInput(){this.zoomLevel=1,this.editingImage={},this.$refs.editorFileInput.value="",this.$refs.uploadedImageInput.value="",this.selectedTool==="sketch_to_image"&&this.makeCanvasEditable({width:1024,height:1024})},downloadImage(e,t){const s=document.createElement("a");s.href=e,s.download=t?t.replaceAll(" ","-"):"image",s.click(),s.remove()},getMaxZoom(){const e=this.$refs.editorCanvas,t=e.offsetWidth,s=window.getComputedStyle(e);return 1+(parseFloat(s.marginLeft)+parseFloat(s.marginRight)-20)/t},setZoomLevel(e){const t=this.getMaxZoom();this.zoomLevel=Math.max(.1,Math.min(t,e)),this.reachedMinZoom=this.zoomLevel===.1,this.reachedMaxZoom=this.zoomLevel>=t},zoomIn(){this.setZoomLevel(this.zoomLevel+.1)},zoomOut(){this.setZoomLevel(this.zoomLevel-.1)},fitToScreen(){const e=this.getMaxZoom();this.setZoomLevel(e)},onZoomLevelChange(){const e=this.$refs.editorCanvas;e.style.setProperty("--zoom-level",this.zoomLevel.toFixed(3)),e.style.setProperty("--zoom-offset","0px");const t=window.getComputedStyle(e),s=parseFloat(t.getPropertyValue("--header-h")),r=e.getBoundingClientRect().top+this.$refs.editorCanvasWrap.scrollTop;r<s&&e.style.setProperty("--zoom-offset",`${(r>=0?s-r:s+Math.abs(r)).toFixed(0)}px`)},submitEditorForm(e){this.busy=!0;const t=new FormData(e.target);fetch(e.target.action,{method:"POST",body:t,headers:{Accept:"application/json"}}).then(s=>{if(!s.ok)throw new Error("Network response was not ok");return s.json()}).then(s=>{if(s.status==="error")throw new Error(s.message);this.editingImage=s.data,this.newItems.push(s.data),this.showNotif=!0,this.selectedTool==="sketch_to_image"&&(this.switchToolsCat({toolKey:this.primaryToolKeys[0]}),this.selectedTool=this.primaryToolKeys[0]);const a=setTimeout(()=>{this.showNotif=!1,clearTimeout(a)},3e3)}).catch(s=>{console.error(s),toastr.error(s)}).finally(()=>{this.busy=!1})},async makeCanvasEditable(e={}){var s;this.editingImageDimensions={width:e.width||this.$refs.editorImagePreview.naturalWidth,height:e.height||this.$refs.editorImagePreview.naturalHeight},await this.$nextTick();const t=this.$refs.editorMaskCanvas;(s=this.canvasCtx)==null||s.reset(),this.canvasCtx=t.getContext("2d"),this.canvasCtx.fillStyle="black",this.canvasCtx.fillRect(0,0,t.width,t.height)},startPainting(e){this.painting=!0,this.painted=!1,this.paint(e)},stopPainting(){if(!this.painted)return;this.painting=!1,this.canvasCtx.beginPath();const e=this.$refs.editorMaskCanvas,t=document.createElement("canvas");t.width=this.editingImageDimensions.width,t.height=this.editingImageDimensions.height,t.getContext("2d").drawImage(e,0,0,t.width,t.height),t.toBlob(a=>{const r=new File([a],"mask.png",{type:"image/png"}),o=new DataTransfer;o.items.add(r),this.$refs[this.selectedTool==="sketch_to_image"?"sketchFileInput":"maskFileInput"].files=o.files,t.remove()},"image/png"),this.painted=!1},paint(e){if(!this.painting)return;const t=this.$refs.editorMaskCanvas,s=t.getBoundingClientRect(),a=(e.clientX-s.left)*(t.width/s.width),r=(e.clientY-s.top)*(t.height/s.height);this.canvasCtx.lineWidth=this.brushSize,this.canvasCtx.lineCap="round",this.canvasCtx.strokeStyle="white",this.canvasCtx.lineTo(a,r),this.canvasCtx.stroke(),this.canvasCtx.beginPath(),this.canvasCtx.moveTo(a,r),this.painted=!0},setBrushSize(e){e==="-"?e=Math.max(this.brushSize-10,10):e==="+"&&(e=Math.min(this.brushSize+10,100)),this.brushSize=parseInt(e,10)}});window.fetchEventSource=I;const Y=localStorage.getItem("lqdDarkMode"),ee=localStorage.getItem("docsViewMode"),te=localStorage.getItem("lqdNavbarShrinked"),A=document.querySelector("body").getAttribute("data-theme"),se=localStorage.getItem(A+":lqdFocusModeEnabled");window.collectCreditsToFormData=function(i){document.querySelectorAll('input[name^="entities"]').forEach(t=>{const s=t.name,a=t.type==="checkbox"||t.type==="radio"?t.checked:t.value;i.append(s,a)})};window.Alpine=d;d.plugin(P);document.addEventListener("alpine:init",()=>{const i=d.$persist;d.data("modal",e=>E(e)),d.data("clipboard",e=>V(e)),d.data("assignViewCredits",e=>L(e)),d.store("navbarShrink",{active:i(!!te).as("lqdNavbarShrinked"),toggle(e){this.active=e?e==="shrink":!this.active,document.body.classList.toggle("navbar-shrinked",this.active)}}),d.data("navbarItem",()=>({dropdownOpen:!1,toggleDropdownOpen(e){this.dropdownOpen=e?e==="collapse":!this.dropdownOpen},item:{"x-ref":"item","@mouseenter"(){if(!d.store("navbarShrink").active)return;const e=this.$el.getBoundingClientRect(),t=this.$refs.item.querySelector(".lqd-navbar-dropdown");if(["y","height","bottom"].forEach(s=>this.$refs.item.style.setProperty(`--item-${s}`,`${e[s]}px`)),t){const s=t.getBoundingClientRect();["height"].forEach(a=>this.$refs.item.style.setProperty(`--dropdown-${a}`,`${s[a]}px`))}}}})),d.store("mobileNav",{navCollapse:!0,toggleNav(e){this.navCollapse=e?e==="collapse":!this.navCollapse},templatesCollapse:!0,toggleTemplates(e){this.templatesCollapse=e?e==="collapse":!this.templatesCollapse},searchCollapse:!0,toggleSearch(e){this.searchCollapse=e?e==="collapse":!this.searchCollapse}}),d.store("darkMode",{on:i(!!Y).as("lqdDarkMode"),toggle(){this.on=!this.on,document.body.classList.toggle("theme-dark",this.on),document.body.classList.toggle("theme-light",!this.on)}}),d.store("appLoadingIndicator",{showing:!1,show(){this.showing=!0},hide(){this.showing=!1},toggle(){this.showing=!this.showing}}),d.store("docsViewMode",{docsViewMode:i(ee||"list").as("docsViewMode"),change(e){this.docsViewMode=e}}),d.store("generatorsFilter",{init(){const e=new URLSearchParams(window.location.search);this.filter=e.get("filter")||"all"},filter:"all",changeFilter(e){if(this.filter!==e){if(!document.startViewTransition)return this.filter=e;document.startViewTransition(()=>this.filter=e)}}}),d.store("documentsFilter",{init(){const e=new URLSearchParams(window.location.search);this.sort=e.get("sort")||"created_at",this.sortAscDesc=e.get("sortAscDesc")||"desc",this.filter=e.get("filter")||"all",this.page=e.get("page")||"1"},sort:"created_at",sortAscDesc:"desc",filter:"all",page:"1",changeSort(e){e===this.sort?this.sortAscDesc=this.sortAscDesc==="desc"?"asc":"desc":this.sortAscDesc="desc",this.sort=e},changeAscDesc(e){this.ascDesc!==e&&(this.ascDesc=e)},changeFilter(e){this.filter!==e&&(this.filter=e)},changePage(e){(e===">"||e==="<")&&(e=e===">"?Number(this.page)+1:Number(this.page)-1),this.page!==e&&(this.page=e)}}),d.store("chatsFilter",{init(){const e=new URLSearchParams(window.location.search);this.filter=e.get("filter")||"all",this.setSearchStr(e.get("search")||"")},searchStr:"",setSearchStr(e){this.searchStr=e.trim().toLowerCase()},filter:"all",changeFilter(e){if(this.filter!==e){if(!document.startViewTransition)return this.filter=e;document.startViewTransition(()=>this.filter=e)}}}),d.data("generatorV2",()=>({itemsSearchStr:"",setItemsSearchStr(e){this.itemsSearchStr=e.trim().toLowerCase(),this.itemsSearchStr!==""?this.$el.closest(".lqd-generator-sidebar").classList.add("lqd-showing-search-results"):this.$el.closest(".lqd-generator-sidebar").classList.remove("lqd-showing-search-results")},sideNavCollapsed:!1,toggleSideNavCollapse(e){var t;this.sideNavCollapsed=e?e==="collapse":!this.sideNavCollapsed,this.sideNavCollapsed&&((t=tinymce==null?void 0:tinymce.activeEditor)==null||t.focus())},generatorStep:0,setGeneratorStep(e){if(e!==this.generatorStep){if(!document.startViewTransition)return this.generatorStep=Number(e);document.startViewTransition(()=>this.generatorStep=Number(e))}},selectedGenerator:null})),d.store("mobileChat",{sidebarOpen:!1,toggleSidebar(e){this.sidebarOpen=e?!1:!this.sidebarOpen}}),d.data("dropdown",({triggerType:e="hover"})=>({open:!1,toggle(t){this.open=t?t!=="collapse":!this.open,this.$refs.parent.classList.toggle("lqd-is-active",this.open)},parent:{"@mouseenter"(){e==="hover"&&this.toggle("expand")},"@mouseleave"(){e==="hover"&&this.toggle("collapse")},"@click.outside"(){this.toggle("collapse")}},trigger:{"@click.prevent"(){e==="click"&&this.toggle()}},dropdown:{}})),d.store("notifications",{notifications:[],loading:!1,add(e){this.notifications.unshift(e)},remove(e){this.notifications.splice(e,1)},markThenHref(e){const t=this.notifications.indexOf(e);if(t!==-1){var s=new FormData;s.append("id",e.id),this.loading=!0,$.ajax({url:"/dashboard/notifications/mark-as-read",type:"POST",data:s,cache:!1,contentType:!1,processData:!1,success:a=>{},error:a=>{console.error(a)},complete:()=>{this.markAsRead(t),window.location=e.link,this.loading=!1}})}},markAsRead(e){this.notifications=this.notifications.map((t,s)=>(s===e&&(t.unread=!1),t))},markAllAsRead(){this.loading=!0,$.ajax({url:"/dashboard/notifications/mark-as-read",type:"POST",success:e=>{e.success&&this.notifications.forEach((t,s)=>{this.markAsRead(s)})},error:e=>{console.error(e)},complete:()=>{this.loading=!1}})},setNotifications(e){this.notifications=e},hasUnread:function(){return this.notifications.some(e=>e.unread)}}),d.data("notifications",e=>({notifications:e||[]})),d.store("focusMode",{active:d.$persist(!!se).as(A+":lqdFocusModeEnabled"),toggle(e){console.log(A),this.active=e?e==="activate":!this.active,document.body.classList.toggle("focus-mode",this.active)}}),d.data("openaiRealtime",G),d.data("advancedImageEditor",X)});M.start();
Save
Cancel