Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions ui/src/components/ai-chat/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,14 @@ provide('getSelectModelList', (params: any) => {
return loadSharedApi({ type: 'model', systemType: 'workspace' }).getSelectModelList(params)
}
})
provide('chatUserProfile', () => {
if (props.type === 'ai-chat') {
if (chatUser.chat_profile?.authentication_type === 'login') {
return chatUser.getChatUserProfile()
}
}
return Promise.resolve(null)
})

const transcribing = ref<boolean>(false)
defineOptions({ name: 'AiChat' })
Expand Down Expand Up @@ -798,16 +806,6 @@ const handleScroll = () => {
}
}
}
onBeforeMount(() => {
window.chatUserProfile = () => {
if (props.type === 'ai-chat') {
if (chatUser.chat_profile?.authentication_type === 'login') {
return chatUser.getChatUserProfile()
}
}
return Promise.resolve(null)
}
})

function parseTransform(transformStr: string) {
const result = { scale: 1, translateX: 0, translateY: 0, translateZ: 0 }
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code has several improvements and optimizations that can be applied:

  1. Remove Redundant Declarations: Remove commented-out lines like window.chatUserProfile.

  2. Use provide with Proper Function Reference for Reusability: The provide usage is correct, but ensure it provides a function reference rather than its evaluation.

  3. Simplify Conditional Logic: Inline some conditional logic where possible to reduce nesting and make the code more readable.

  4. Optimize Data Types and Variable Assignments: Ensure that variable assignments are clear and minimize reassignment without necessary changes.

  5. Consistent Naming Conventions: Use consistent naming conventions across similar variables or functions.

Here's an optimized version of the code:

import { ref } from 'vue'
import { onBeforeUnmount } from 'vue'

export default {
  setup(props) {
    const chatUser = props.currentUser || {} // Assuming currentUser exists

    provide('getSelectModelList', (params: any) => {
      return loadSharedApi<{ type: 'model'; systemType: 'workspace' }>({ type: 'model', systemType: 'workspace' }).getSelectModelList(params)
    })

    provide('chatUserProfile', () => {
      if (props.type !== 'ai-chat') return null

      if (
        chatUser.chat_profile &&
        chatUser.chat_profile.authentication_type === 'login'
      ) {
        return chatUser.getChatUserProfile()
      }

      return Promise.resolve(null)
    })

    const transcribing = ref(false)

    defineOptions({ name: 'AiChat' })

    const handleScroll = (event: WheelEvent) => {
      const container = document.getElementById('textArea')
      if (!container) return

      if (Math.abs(event.deltaY) < 50 && !transcribing.value) {
        event.preventDefault()

        const newCursorPos = Math.min(
          container.scrollLeft + ((event.deltaY > 0 ? event.deltaY : -event.deltaY) * 5),
          container.scrollWidth - container.clientWidth,
        )

        container.scrollTo({
          left: Math.round(newCursorPos),
        })
      }
    }

    let lastMousePress: number | null = null

    document.addEventListener('mousedown', () => {
      lastMousePress = Date.now()
    })
    document.addEventListener('mouseup', () => {
      lastMousePress = null
    })
    document.addEventListener('mousemove', (e) => {
      if (
        e.target instanceof HTMLTextAreaElement ||
        e.target.closest('.code-editor-textarea-wrapper') !== null
      )
        return

      if (lastMousePress) {
        const container =	document.getElementById('textInputFieldWrapper')

        if (!container) return

        const delta = e.clientX - container.offsetLeft - container.clientWidth / 2
        const scrollRange = container.offsetWidth - container.clientWidth
        const newPos = Math.max(-scrollRange, Math.min(scrollRange, deltaX))
        
        container.style.scrollLeft += newPos
      }
    }, true)

    onBeforeUnmount(() => {
      document.removeEventListener('wheel', handleScroll)
      document.removeEventListener('mousedown', () => {})
      document.removeEventListener('mouseup', () => {})
      document.removeEventListener('mousemove', (e) => {})
    })

    function parseTransform(transformStr: string) {
      const result = transformStr.match(/^([-+]?\d+(\.\d+)?)([pxcm])?$/i)?.map(Number);
      
      if (result) return {
        scale: result[2] ? parseFloat(result[1]) : 1,
        translateX: result[1],
        translateY: result[1],
        translateZ: result[1],
      };

      return result;
    }

    return {
      transcribing,
      handleScroll,
    };
  },
}

Key Changes:

  • Removed redundant assignment to window.chatUserProfile.
  • Simplified and clarified conditional logic in chatUserProfile.
  • Improved readability and maintainability throughout the component.

Expand Down
53 changes: 50 additions & 3 deletions ui/src/components/markdown/HtmlRander.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onBeforeUnmount } from 'vue'

import { computed, ref, onMounted, onBeforeUnmount, inject } from 'vue'
const chatUserProfile = inject('chatUserProfile') as any
const htmlRef = ref<HTMLIFrameElement>()
const props = withDefaults(
defineProps<{
Expand All @@ -37,6 +37,40 @@ function createIframeHtml(sourceHtml: string) {
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { margin: 0 !important; padding: 0 !important; overflow: hidden; }
</style>
<script>
const _INSTANCE_ID = '${instanceId}';
window.chatUserProfile=function chatUserProfile() {
return new Promise((resolve, reject) => {
const requestId = Date.now() + '_' + Math.random()

function handler(e) {
const data = e.data

if (
data?.type === 'chatUserProfile:response' &&
data.requestId === requestId
) {
window.removeEventListener('message', handler)
resolve(data.data)
}
}
window.addEventListener('message', handler)
parent.postMessage(
{
type: 'chatUserProfile',
requestId,
instanceId: _INSTANCE_ID
},
'*'
)

setTimeout(() => {
window.removeEventListener('message', handler)
reject(new Error('timeout'))
}, 10000)
})
}
<\/script>
</head>
<body>
${sourceHtml}
Expand All @@ -46,7 +80,6 @@ const INSTANCE_ID = '${instanceId}';
function sendMessage(message) {
parent.postMessage({ type: 'chatMessage', instanceId: INSTANCE_ID, message }, '*');
}

let lastSentHeight = 0;
let timer = null;

Expand Down Expand Up @@ -88,6 +121,20 @@ function onMessage(e: MessageEvent) {
if (e.data.type === 'chatMessage') {
props.sendMessage?.(e.data.message, 'new')
}
if (e.data?.type === 'chatUserProfile') {
const iframe = htmlRef.value
if (!iframe) return
chatUserProfile().then((ok: any) => {
iframe.contentWindow?.postMessage(
{
type: 'chatUserProfile:response',
requestId: e.data.requestId,
data: ok,
},
'*',
)
})
}
}

onMounted(() => {
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is an issue with the use of inject('chatUserProfile'). The provided code does not handle cases where there might not be a valid value injected for this key. It should include checks to ensure that chatUserProfile exists before making further calls. Also, the <script> block at the very beginning seems out of place and should be moved after closing the <style> tags or inside the template section.

Additionally, the _INSTANCE_ID variable is defined but used without prefixing it with $, which suggests it's likely meant to be part of another object. If this is intentional, make sure to include a proper JavaScript module export for such values.

Here are some corrections:

  1. Check if chatUserProfile is available before calling its methods.
  2. Move non-template script blocks closer to their respective elements or wrap them properly.
  3. Ensure _INSTANCE_ID is correctly referenced within any JavaScript variables.

These changes will help improve robustness and maintainability of the Vue component.

Expand Down
Loading