SentTabCopy.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { App, Dropdown, Tooltip } from "antd";
  2. import {
  3. CopyOutlined,
  4. ShoppingCartOutlined,
  5. CheckOutlined,
  6. DownOutlined,
  7. } from "@ant-design/icons";
  8. import { useEffect, useState } from "react";
  9. import store from "../../store";
  10. import { modeChange, type TCopyMode } from "../../reducers/cart-mode";
  11. import { useAppSelector } from "../../hooks";
  12. import { mode as _mode } from "../../reducers/cart-mode";
  13. import type { IWbw } from "../../types/wbw";
  14. import { addToCart } from "./utils";
  15. interface IWidget {
  16. text?: string;
  17. wbwData?: IWbw[];
  18. }
  19. const SentTabCopyWidget = ({ text, wbwData }: IWidget) => {
  20. const { notification } = App.useApp();
  21. // ✅ 直接读取 Redux,不再维护镜像 local state
  22. const mode = useAppSelector(_mode);
  23. const [success, setSuccess] = useState(false);
  24. // ✅ Redux 变化时同步写入 localStorage(外部系统同步,effect 正当用途)
  25. useEffect(() => {
  26. if (mode) {
  27. localStorage.setItem("cart/mode", mode);
  28. }
  29. }, [mode]);
  30. const handleCopy = (targetMode: TCopyMode) => {
  31. if (!text) return;
  32. if (targetMode === "single") {
  33. navigator.clipboard.writeText(text).then(() => {
  34. setSuccess(true);
  35. setTimeout(() => setSuccess(false), 3000);
  36. });
  37. } else {
  38. const paliText =
  39. wbwData
  40. ?.filter((item) => item.type?.value !== ".ctl.")
  41. .map((item) => item.word.value)
  42. .join(" ") ?? "";
  43. addToCart([{ id: text, text: paliText }]);
  44. notification.success({ message: "句子已经添加到Cart" });
  45. setSuccess(true);
  46. setTimeout(() => setSuccess(false), 3000);
  47. }
  48. };
  49. const handleMenuClick = (key: string) => {
  50. const newMode = key as TCopyMode;
  51. store.dispatch(modeChange(newMode));
  52. handleCopy(newMode);
  53. };
  54. const icon = success ? (
  55. <CheckOutlined />
  56. ) : mode === "single" ? (
  57. <CopyOutlined />
  58. ) : (
  59. <ShoppingCartOutlined />
  60. );
  61. return (
  62. <Dropdown.Button
  63. size="small"
  64. type="link"
  65. icon={<DownOutlined />}
  66. menu={{
  67. items: [
  68. { label: "copy", key: "copy", icon: <CopyOutlined /> },
  69. { label: "add to cart", key: "cart", icon: <ShoppingCartOutlined /> },
  70. ],
  71. onClick: (e) => handleMenuClick(e.key),
  72. }}
  73. onClick={() => handleCopy(mode)}
  74. >
  75. <Tooltip title={`${success ? "已完成:" : ""}${mode}`}>{icon}</Tooltip>
  76. </Dropdown.Button>
  77. );
  78. };
  79. export default SentTabCopyWidget;