GrammarPop.tsx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { useState } from "react";
  2. import { Popover, Typography } from "antd";
  3. import { get } from "../../request";
  4. import { get as getLang } from "../../locales";
  5. import type { IGuideResponse } from "../../api/Guide";
  6. import Marked from "../general/Marked";
  7. const { Link, Paragraph } = Typography;
  8. interface IWidget {
  9. text: string;
  10. gid: string;
  11. }
  12. const GrammarPopWidget = ({ text, gid }: IWidget) => {
  13. const [guide, setGuide] = useState("Loading");
  14. const grammarPrefix = "guide-grammar-";
  15. const handleMouseMouseEnter = () => {
  16. //sessionStorage缓存
  17. const value = sessionStorage.getItem(grammarPrefix + gid);
  18. if (value === null) {
  19. fetchData(gid);
  20. } else {
  21. const sGuide: string = value ? value : "";
  22. setGuide(sGuide);
  23. }
  24. };
  25. function fetchData(key: string) {
  26. const uiLang = getLang();
  27. const url = `/v2/grammar-guide/${key}_${uiLang}`;
  28. get<IGuideResponse>(url).then((json) => {
  29. if (json.ok) {
  30. sessionStorage.setItem(grammarPrefix + key, json.data);
  31. setGuide(json.data);
  32. }
  33. });
  34. }
  35. return (
  36. <Popover
  37. content={
  38. <Paragraph style={{ maxWidth: 500, minWidth: 300, margin: 0 }}>
  39. <Marked text={guide} />
  40. </Paragraph>
  41. }
  42. placement="bottom"
  43. >
  44. <Link onMouseEnter={handleMouseMouseEnter}>{text}</Link>
  45. </Popover>
  46. );
  47. };
  48. interface IWidgetShell {
  49. props: string;
  50. }
  51. export const GrammarPopShell = ({ props }: IWidgetShell) => {
  52. const prop = JSON.parse(atob(props)) as IWidget;
  53. return (
  54. <>
  55. <GrammarPopWidget {...prop} />
  56. </>
  57. );
  58. };
  59. export default GrammarPopWidget;