123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- "use client";
- import { useSystemStore } from "@/stores/useSystemStore";
- import { Button, Popup } from "antd-mobile";
- import { useTranslations } from "next-intl";
- import Image from "next/image";
- import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
- /**
- * @description 检测pwa是否下载
- * if 下载 不弹窗 , else 弹窗
- *
- */
- export interface DesktopRefProps {
- onOpen: () => void;
- onClose: () => void;
- }
- interface Props {}
- const Desktop = forwardRef<DesktopRefProps, Props>(function Desktop(props, ref) {
- const prompt = useRef<Event | null>(null);
- const t = useTranslations("HomePage");
- const { isHasDesktop, setHasDesktop } = useSystemStore((state) => {
- return {
- isHasDesktop: state.isHasDesktop,
- setHasDesktop: state.setHasDesktop,
- };
- });
- const downloadHandler = () => {
- // @ts-ignore
- prompt.current?.prompt();
- // 不判断是否真的包含
- setHasDesktop(false);
- };
- const initDesktop = (e: Event) => {
- if (window.matchMedia("(display-mode: standalone)").matches) {
- setHasDesktop(false);
- return;
- }
- // 有pwa 则不会触发
- prompt.current = e;
- // 只触发一次
- if (useSystemStore.getState().isHasDesktop === undefined) {
- setHasDesktop(true);
- }
- };
- useEffect(() => {
- window.addEventListener("beforeinstallprompt", initDesktop);
- // @ts-ignore
- window.onappinstalled = function (ev) {
- // 安装完成
- console.log("The application was installed.");
- };
- return () => window.removeEventListener("beforeinstallprompt", initDesktop);
- }, []);
- useImperativeHandle(ref, () => {
- return {
- onClose: () => setHasDesktop(false),
- onOpen: () => {
- setHasDesktop(true);
- },
- };
- });
- return (
- <Popup
- visible={!!isHasDesktop}
- getContainer={null}
- bodyStyle={{ padding: "0.2rem", background: "#fff" }}
- >
- <div className={"flex text-[0.12rem] text-[#8d8d8d]"}>
- <Image
- src={"/icon-192x192.png"}
- alt={"logo"}
- className={"mr-[10px] flex-shrink-0"}
- width={80}
- height={80}
- />
- {t("saveTips")}
- </div>
- <div className={"mb-[0.16rem] mt-[0.1rem] text-right"}>
- <Button
- color="default"
- className={"mr-[10px]"}
- style={{ "--text-color": "#8d8d8d" }}
- fill="none"
- onClick={() => setHasDesktop(false)}
- >
- {t("cancel")}
- </Button>
- <Button
- color="primary"
- style={{
- "--text-color": "#ff6a01",
- "--border-color": "#ff6a01",
- "--border-radius": "10px",
- }}
- fill="outline"
- onClick={downloadHandler}
- >
- {t("save")}
- </Button>
- </div>
- </Popup>
- );
- });
- export default Desktop;
|