Bläddra i källkod

fix: 修复tabbar 与普通二级页窗口高度不一致需重新获取

王晓东 2 veckor sedan
förälder
incheckning
794f72bf6b

+ 4 - 46
project.private.config.json

@@ -9,58 +9,16 @@
     "miniprogram": {
       "list": [
         {
-          "name": "pages/chat/index",
-          "pathName": "pages/chat/index",
-          "query": "agentId=p_2e73c9d7efaYfDo2-agent_3111&isVisitor=false",
+          "name": "pages/profile/index",
+          "pathName": "pages/profile/index",
+          "query": "agentId=p_391b4d3fdeaY2zRc-agent_2775",
           "scene": null,
           "launchMode": "default"
         },
         {
           "name": "pages/profile/index",
           "pathName": "pages/profile/index",
-          "query": "agentId=p_2e73c9d7efaYfDo2-agent_2747&shareKey=2%241%24AAADJVaNamEqHCG%2FJ8rQloPjNu6BaGv5PqdIw081Yet%2BROuk5MwyAhuwauvV1dt3XgK7JnY2%2BAO6qDCDzQeF2qqhC4YSK%2FkewwevYKd6jPM%2FQO1u",
-          "launchMode": "default",
-          "scene": null
-        },
-        {
-          "name": "pages/chat/index",
-          "pathName": "pages/chat/index",
-          "query": "agentId=p_2e73c9d7efaYfDo2-agent_2747&isVisitor=false",
-          "launchMode": "default",
-          "scene": null
-        },
-        {
-          "name": "pages/editor-contact/index",
-          "pathName": "pages/editor-contact/index",
-          "query": "agentId=p_2e73c9d7efaYfDo2-agent_2731",
-          "launchMode": "default",
-          "scene": null
-        },
-        {
-          "name": "pages/agent-gen/index",
-          "pathName": "pages/agent-gen/index",
-          "query": "avatarUrl=https%3A%2F%2Fxlb-xly.oss-cn-hangzhou.aliyuncs.com%2Fu260727532%2F20250923%2FZgKVD10MiT_831383c0bbaa4f128cca7ebf92dddc68.jpeg",
-          "launchMode": "default",
-          "scene": null
-        },
-        {
-          "name": "pages/agent-avatars/index",
-          "pathName": "pages/agent-avatars/index",
-          "query": "",
-          "launchMode": "default",
-          "scene": null
-        },
-        {
-          "name": "pages/agent/index",
-          "pathName": "pages/agent/index",
-          "query": "agentId=p_2e73c9d7efaYfDo2-agent_2689",
-          "launchMode": "default",
-          "scene": null
-        },
-        {
-          "name": "pages/agent/index",
-          "pathName": "pages/agent/index",
-          "query": "",
+          "query": "agentId=p_2e73c9d7efaYfDo2-agent_3111&shareKey=2%241%24AAABSUpQ0nQXN5a4xNIfMbQKVG3v5DTlxCsNAxgHBEda7IoGdYnJ%2BH6auz2jwoCu0FzODnGgcOF6uyAUOMIbQNu%2Bms6XM8hDFvFaSf9B2%2B%2FglMEC",
           "launchMode": "default",
           "scene": null
         }

+ 2 - 2
src/app.tsx

@@ -1,7 +1,7 @@
 import Taro, { useLaunch } from "@tarojs/taro";
 import { PropsWithChildren } from "react";
 import "./app.less";
-import { useAppStore } from "./store/appStore";
+import { useAppStoreActions } from "./store/appStore";
 import { generateRandomId } from '@/utils/index'
 import {LOGIN_ID_STORAGE_KEY } from '@/xiaolanbenlib/constant'
 import dayjs from "dayjs";
@@ -16,7 +16,7 @@ if (process.env.TARO_ENV == "h5") {
   new VConsole();
 }
 function App({ children }: PropsWithChildren<any>) {
-  const { setSystemInfo } = useAppStore();
+  const { setSystemInfo } = useAppStoreActions();
 
   useLaunch((options) => {
     console.log("App launched.", options.query);

+ 11 - 9
src/components/page-wrapper/CustomBg.tsx

@@ -17,16 +17,18 @@ const Index: React.FC<Props> = ({styleBg}) => {
   // const [offsetMargin, setOffsetMargin] = useState({ x: 0, y: 0 });
   // const [bgSize, setBgSize] = useState({ width: windowWidth, height: windowHeight });
 
-  const  bg =  styleBg || ''  
-  
+  const  bg =  styleBg || ''
+  const isMp4 = bg?.lastIndexOf('.mp4') > -1
+  const minHeight = `${(750 / windowWidth) * windowHeight}rpx`
+  // console.log(windowWidth, windowHeight)
   const bgImageStyle = {
-    height: `${(750 / windowWidth) * windowHeight}rpx`,
+    minHeight,
     backgroundImage: `url(${bg})`,
     backgroundSize: 'auto 100%!important',
     backgroundPosition: 'center center'
   };
 
-  const isMp4 = bg?.lastIndexOf('.mp4') > -1
+
 
   //todo: 无法计算图的大小来设置位置,因为获取图片宽,高信息需要异步获取
   if(!bg) {
@@ -37,8 +39,8 @@ const Index: React.FC<Props> = ({styleBg}) => {
   if(bg === DEFAULT_AVATAR_BG){
     return <View className={pageStyle.bg} style={bgImageStyle}></View>
   }
-
-  if(isMp4){ 
+  // 如果是 mp4 背景
+  if(isMp4){
     return <Video
       controls={false}
       showCenterPlayBtn={false}
@@ -47,13 +49,13 @@ const Index: React.FC<Props> = ({styleBg}) => {
       autoplay
       objectFit="cover"
       className={pageStyle.bg}
-      style={bgImageStyle}
+      style={{minHeight}}
       src={bg}
     />
   }
 
-  
-  
+  // 图片背景
+
   return <Image className={pageStyle.bg} style={bgImageStyle} src={bg} mode='aspectFill'></Image>
 };
 

+ 3 - 0
src/pages/contact/index.tsx

@@ -15,8 +15,10 @@ import CheckLoginPopup from "@/components/CheckLoginPopup";
 import BlurContainer from "@/components/BlurContainer";
 import SliderAction from "@/components/SliderAction";
 import PageTitle from '@/components/PageTitle'
+import { useAppStoreActions } from "@/store/appStore";
 export default function Index() {
   const [searchValue, setSearchValue] = useState("");
+  const { syncWindowHeight } = useAppStoreActions();
   // const [scrollIng, setScrolling] = useState(false);
 
   const fetcher = async ([_url, params, keyword]) => {
@@ -112,6 +114,7 @@ export default function Index() {
 
   useDidShow(() => {
     mutate();
+    syncWindowHeight()
   });
   const onLoginEnd = () => {
     mutate();

+ 6 - 2
src/pages/index/index.tsx

@@ -1,13 +1,15 @@
 import DefaultAgent from "@/components/AgentPage";
 import InitView from "./components/InitView";
-import { useDidShow } from "@tarojs/taro";
+import Taro, { useDidShow } from "@tarojs/taro";
 import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
 import { useIsLogin } from "@/xiaolanbenlib/hooks/data/useAuth";
 import { useEffect } from "react";
+import { useAppStoreActions } from "@/store/appStore";
+
 
 export default function Index() {
   const isLogin = useIsLogin();
-
+  const { syncWindowHeight } = useAppStoreActions();
   const defaultAgent = useAgentStore((state) => state.defaultAgent);
   const { fetchAgents, resetData } = useAgentStoreActions();
 
@@ -17,6 +19,8 @@ export default function Index() {
     if (isLogin) {
       fetchAgents();
     }
+
+    syncWindowHeight()
   });
 
   // 如果登出,则重置当前 agent store

+ 121 - 85
src/pages/profile/index.tsx

@@ -1,6 +1,6 @@
 import PageCustom from "@/components/page-custom/index";
 import { View, Image } from "@tarojs/components";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
 import ComponentList from "@/components/component-list";
 
 import NavBarNormal from "@/components/NavBarNormal/index";
@@ -10,63 +10,73 @@ import { isSuccess } from "@/utils";
 import IconArrowLeft from "@/components/icon/icon-arrow-left";
 import IconHomeOutline from "@/components/icon/IconHomeOutline";
 import AgentActionBar from "@/components/AgentPage/components/AgentActionBar";
-import {
-  getAgent,
-} from "@/service/agent";
+import { getAgent } from "@/service/agent";
 import style from "./index.module.less";
-import {  DEFAULT_AVATAR_BG } from '@/config'
+import { DEFAULT_AVATAR_BG } from "@/config";
 import { sceneUnzip } from "@/service/wechat";
 import { postLog } from "./profile";
 import { useIsLogin } from "@/xiaolanbenlib/hooks/data/useAuth";
 import useSWR from "swr";
 import type { TAgentDetail } from "@/types/agent";
-import { useAppStore } from "@/store/appStore";
+import { useAppStore, useAppStoreActions } from "@/store/appStore";
 
 export default function Profile() {
-  const [agentProfile, setAgentProfile] = useState<TAgentDetail|null>(null)
+  const [agentProfile, setAgentProfile] = useState<TAgentDetail | null>(null);
   // const { agentProfile, clearProfileAgent } = useAgentStore();
   const params = useRouter().params;
   const isLogin = useIsLogin();
-  const windowHeight = useAppStore((state)=>  state.windowHeight);
-  const headerHeight = useAppStore((state)=>  state.headerHeight);
+  const { syncWindowHeight } = useAppStoreActions();
 
-  const components = agentProfile?.components ?? []
+  const windowHeight = useAppStore((state) => state.windowHeight);
+  const headerHeight = useAppStore((state) => state.headerHeight);
 
-  const [agentId, setCurrentAgentId]  = useState<null|string>(null)
-  const [shareKey, setShareKey] = useState<null|string>(null)
-  const [bg, setBg] = useState('')
+  const components = agentProfile?.components ?? [];
+
+  const [agentId, setCurrentAgentId] = useState<null | string>(null);
+  const [shareKey, setShareKey] = useState<null | string>(null);
+  const [bg, setBg] = useState("");
   const [marginTop, setMarginTop] = useState(0);
 
-  console.log(agentProfile, agentProfile?.status)
+  // console.log(agentProfile, agentProfile?.status);
+
+  useLayoutEffect(() => {
+    syncWindowHeight();
+  }, [agentId]);
 
-  const fetchAgentProfile = async (agentId: string, shareKey?:string) => {
-    if(shareKey){
-      shareKey = decodeURIComponent(shareKey)
+  const fetchAgentProfile = async (agentId: string, shareKey?: string) => {
+    if (shareKey) {
+      shareKey = decodeURIComponent(shareKey);
     }
     const response = await getAgent(agentId, shareKey);
-    const result = isSuccess(response.status)
-    const agent = response.data
+    const result = isSuccess(response.status);
+    const agent = response.data;
     if (result && agent) {
-      agent.components = (agent.components ?? []).filter(item => item.enabled)
-      setAgentProfile(agent)
+      agent.components = (agent.components ?? []).filter(
+        (item) => item.enabled
+      );
+      setAgentProfile(agent);
     }
-    return agent
-  }
+    return agent;
+  };
 
-  const setPageBg = (_agent:TAgentDetail)=> {
-    setBg(_agent?.avatarUrl ?? DEFAULT_AVATAR_BG)
-  }
+  const setPageBg = (_agent: TAgentDetail) => {
+    setBg(_agent?.avatarUrl ?? DEFAULT_AVATAR_BG);
+  };
 
   // 定时 30 秒请求一次 log 接口
-  useSWR( (agentId && (agentProfile?.status === 'normal')) ? ['/blue-aiagent/api/v1/agent/visitor/log', {
-    agentId: agentId,
-    shareKey: shareKey,
-    }] : false
-    ,
+  useSWR(
+    agentId && agentProfile?.status === "normal"
+      ? [
+          "/blue-aiagent/api/v1/agent/visitor/log",
+          {
+            agentId: agentId,
+            shareKey: shareKey,
+          },
+        ]
+      : false,
     ([_url, data]) => {
-
-      if(isLogin){
-        postLog(data.agentId, data.shareKey ?? '')
+      if (isLogin) {
+        postLog(data.agentId, data.shareKey ?? "");
       }
     },
     {
@@ -91,9 +101,9 @@ export default function Profile() {
             originalScene.agentId,
             originalScene.shareKey ?? ""
           );
-          _agent && setPageBg(_agent)
-          setCurrentAgentId(originalScene.agentId)
-          setShareKey(originalScene.shareKey ?? "")
+          _agent && setPageBg(_agent);
+          setCurrentAgentId(originalScene.agentId);
+          setShareKey(originalScene.shareKey ?? "");
 
           // postLog(originalScene.agentId, originalScene.shareKey ?? "");
         }
@@ -107,13 +117,15 @@ export default function Profile() {
   };
   console.log(params.scene, "场景值");
 
-
-  const fetchPageData = async (params:any)=> {
-    const _agent = await fetchAgentProfile(params.agentId, params.shareKey ?? "");
-    _agent && setPageBg(_agent)
-    setCurrentAgentId(params.agentId)
-    setShareKey(params.shareKey ?? "")
-  }
+  const fetchPageData = async (params: any) => {
+    const _agent = await fetchAgentProfile(
+      params.agentId,
+      params.shareKey ?? ""
+    );
+    _agent && setPageBg(_agent);
+    setCurrentAgentId(params.agentId);
+    setShareKey(params.shareKey ?? "");
+  };
 
   useEffect(() => {
     // 通过小程序码识别打开的页面
@@ -124,43 +136,44 @@ export default function Profile() {
       decodeSceneValue(scene);
     }
 
-    return ()=> {
-      setCurrentAgentId(null)
-      setShareKey(null)
-    }
+    return () => {
+      setCurrentAgentId(null);
+      setShareKey(null);
+    };
   }, []);
 
-
-
   // 正常分享出来的页面
   useEffect(() => {
     if (params.agentId) {
-      fetchPageData(params)
+      fetchPageData(params);
     }
   }, [params.agentId]);
 
-
-  useEffect(()=> {
+  useEffect(() => {
     const query = Taro.createSelectorQuery();
     // 获取滚动容器高度
     query
-      .select('#BlurRoundedContainer')
+      .select("#BlurRoundedContainer")
       .boundingClientRect((rect: any) => {
         if (rect) {
-          console.log('ScrollView height:', rect.height, windowHeight, headerHeight)
-          if(rect.height + 296 < windowHeight - headerHeight){
+          console.log(
+            "ScrollView height:",
+            rect.height,
+            windowHeight,
+            headerHeight
+          );
+          if (rect.height + 296 < windowHeight - headerHeight) {
             setMarginTop(windowHeight - headerHeight - rect.height);
-          }else{
+          } else {
             setMarginTop(296);
           }
         }
       })
       .exec();
-  }, [components])
+  }, [components]);
 
   const renderNavBarLeft = () => {
     const pages = getCurrentPages();
-    console.log(pages, "当前页面");
     // 有后退页,则不显示 home 按钮
 
     if (pages.length > 1 && pages[0].route !== "pages/profile/index") {
@@ -193,35 +206,49 @@ export default function Profile() {
     );
   };
 
-  const renderButton = ()=> {
+  const renderButton = () => {
     // 如果智能体交接了,则可以跳去新智能体
-    if(agentProfile?.toAgentId){
-      return <View className="button-rounded-big" onClick={()=> {
-        Taro.redirectTo({
-          url: `/pages/profile/index?agentId=${agentProfile?.toAgentId}`
-        });
-      }}>前往访问</View>
+    if (agentProfile?.toAgentId) {
+      return (
+        <View
+          className="button-rounded-big"
+          onClick={() => {
+            Taro.redirectTo({
+              url: `/pages/profile/index?agentId=${agentProfile?.toAgentId}`,
+            });
+          }}
+        >
+          前往访问
+        </View>
+      );
     }
 
     // 下线了
-    return <View className="button-rounded-big" onClick={()=> {
-      Taro.navigateBack()
-    }}>知道了</View>
-  }
+    return (
+      <View
+        className="button-rounded-big"
+        onClick={() => {
+          Taro.navigateBack();
+        }}
+      >
+        知道了
+      </View>
+    );
+  };
 
-   // 如果智能体被删除或其它异常情况
-   if (agentProfile?.status === "deleted" || agentProfile?.deletedTip?.length) {
+  // 如果智能体被删除或其它异常情况
+  if (agentProfile?.status === "deleted" || agentProfile?.deletedTip?.length) {
     return (
       <PageCustom fullPage>
         <View className="w-full h-full">
           <NavBarNormal leftColumn={renderNavBarLeft}></NavBarNormal>
-        <View className="w-full h-full flex flex-col items-center justify-center">
-          <View className="max-w-[280px]">
-            <View className="mb-12">{agentProfile?.deletedTip}</View>
-            {renderButton()}
+          <View className="w-full h-full flex flex-col items-center justify-center">
+            <View className="max-w-[280px]">
+              <View className="mb-12">{agentProfile?.deletedTip}</View>
+              {renderButton()}
+            </View>
           </View>
         </View>
-      </View>
       </PageCustom>
     );
   }
@@ -229,15 +256,24 @@ export default function Profile() {
   return (
     <PageCustom styleBg={bg}>
       <View className="w-full">
-        <NavBarNormal blur scrollFadeIn scrollFadeInDelta={240}  leftColumn={renderNavBarLeft}></NavBarNormal>
-        {agentProfile && <View className="blur-rounded-container" id="BlurRoundedContainer" style={{marginTop: `${marginTop}px`}}>
-          <AgentActionBar isVisitor agent={agentProfile}></AgentActionBar>
-          <View className="flex flex-col w-full p-16 gap-12">
-            <ComponentList
-              components={components}
-            ></ComponentList>
+        <NavBarNormal
+          blur
+          scrollFadeIn
+          scrollFadeInDelta={240}
+          leftColumn={renderNavBarLeft}
+        ></NavBarNormal>
+        {agentProfile && (
+          <View
+            className="blur-rounded-container"
+            id="BlurRoundedContainer"
+            style={{ marginTop: `${marginTop}px` }}
+          >
+            <AgentActionBar isVisitor agent={agentProfile}></AgentActionBar>
+            <View className="flex flex-col w-full p-16 gap-12">
+              <ComponentList components={components}></ComponentList>
+            </View>
           </View>
-        </View>}
+        )}
       </View>
     </PageCustom>
   );

+ 49 - 38
src/store/appStore.ts

@@ -21,9 +21,11 @@ export interface AppState {
   appConfig: TModelAppConfig | null
   keyboardHeight: number
   desktopPopupTips: boolean
-  setSystemInfo: (info: Taro.getSystemInfoSync.Result)=> void
-  setKeyboardHeight: (height: number) => void
-  fetchAppConfig: ()=> Promise<TModelAppConfig | null>
+  actions: {
+    setSystemInfo: (info: Taro.getSystemInfoSync.Result)=> void
+    setKeyboardHeight: (height: number) => void
+    syncWindowHeight: ()=> void
+  }
 }
 
 export const useAppStore = create<AppState>((set) => ({
@@ -59,53 +61,62 @@ export const useAppStore = create<AppState>((set) => ({
   vipPopupVisible: false,
   desktopPopupTips: false,
   bottomSafeHeight: 0,
-  setKeyboardHeight: (height: number)=> {
-    set({keyboardHeight: height})
-  },
-  setSystemInfo: (info) => {
-    // 状态栏高度 - 6 偏差值为垂直居中对齐胶囊按钮
-    // statusBarHeight 离顶部导航栏位置
-    const statusBarHeight = (isNaN(info.statusBarHeight!) ? 24 : info.statusBarHeight || 47) - 6;
-    const system = info.system.toLowerCase()
-    const isIos = system.includes('ios')
-    let bottomSafeHeight = 0
-    let desktopPopupTips = false;
-    const capsuleInfo = Taro.getMenuButtonBoundingClientRect()
+  actions: {
+    setKeyboardHeight: (height: number)=> {
+      set({keyboardHeight: height})
+    },
+    setSystemInfo: (info) => {
+      // 状态栏高度 - 6 偏差值为垂直居中对齐胶囊按钮
+      // statusBarHeight 离顶部导航栏位置
+      const statusBarHeight = (isNaN(info.statusBarHeight!) ? 24 : info.statusBarHeight || 47) - 6;
+      const system = info.system.toLowerCase()
+      const isIos = system.includes('ios')
+      let bottomSafeHeight = 0
+      let desktopPopupTips = false;
+      const capsuleInfo = Taro.getMenuButtonBoundingClientRect()
 
-    const screenHeight = info.screenHeight
-    const windowWidth = info.windowWidth
-    const windowHeight = info.windowHeight // 更精确的可用高度(减去状态栏等)
-    const ratio = 750 / windowWidth
+      const screenHeight = info.screenHeight
+      const windowWidth = info.windowWidth
+      const windowHeight = info.windowHeight // 更精确的可用高度(减去状态栏等)
+      const ratio = 750 / windowWidth
 
-    // 导航栏高度 = 胶囊和状态栏之间的留白 * 2 胶囊高度
-    let navbarHeight = (capsuleInfo.top - statusBarHeight) * 2 + capsuleInfo.height
+      // 导航栏高度 = 胶囊和状态栏之间的留白 * 2 胶囊高度
+      let navbarHeight = (capsuleInfo.top - statusBarHeight) * 2 + capsuleInfo.height
 
-    // Android 导航栏高度多加 4
-    navbarHeight = isIos ? navbarHeight : navbarHeight + 4
+      // Android 导航栏高度多加 4
+      navbarHeight = isIos ? navbarHeight : navbarHeight + 4
 
-    // 整个 header 高度
-    const headerHeight = statusBarHeight + navbarHeight
+      // 整个 header 高度
+      const headerHeight = statusBarHeight + navbarHeight
 
-    // console.log({ systemInfo: info, statusBarHeight: statusBarHeight, headerHeight, capsuleInfo, navbarHeight})
+      // console.log({ systemInfo: info, statusBarHeight: statusBarHeight, headerHeight, capsuleInfo, navbarHeight})
 
-    // 如果是 Mac 或 windows 电脑平台则不允许使用 并 显示小程序二维码
-    if (!system.includes('android') && !system.includes('ios')) {
-      desktopPopupTips = true
-    }
-    if(info.safeArea?.bottom){
-      bottomSafeHeight = screenHeight - info.safeArea?.bottom;
-    }
+      // 如果是 Mac 或 windows 电脑平台则不允许使用 并 显示小程序二维码
+      if (!system.includes('android') && !system.includes('ios')) {
+        desktopPopupTips = true
+      }
+      if(info.safeArea?.bottom){
+        bottomSafeHeight = screenHeight - info.safeArea?.bottom;
+      }
 
 
-    set({ systemInfo: info, capsuleInfo, statusBarHeight, headerHeight, isIos, desktopPopupTips, bottomSafeHeight, screenHeight, windowHeight, windowWidth, ratio})
+      set({ systemInfo: info, capsuleInfo, statusBarHeight, headerHeight, isIos, desktopPopupTips, bottomSafeHeight, screenHeight, windowHeight, windowWidth, ratio})
 
 
-  },
-  fetchAppConfig: async ()=> {
+    },
+    syncWindowHeight:  ()=> {
+
+      const res = Taro.getSystemInfoSync()
+      set({ windowHeight: res.windowHeight})
+    },
+  }
 
-    return null
-  },
 
 }))
 
+export const useAppStoreActions = () => {
+  const actions = useAppStore(state => state.actions);
+  return actions;
+};
+