Navigate.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { useEffect, useState } from "react";
  2. import { get } from "../../request";
  3. import type { ArticleType } from "./Article";
  4. import React from "react";
  5. import NavigateButton from "./NavigateButton";
  6. import type { ITocPathNode } from "../corpus/TocPath";
  7. interface INavButton {
  8. title: string;
  9. subtitle: string;
  10. id: string;
  11. }
  12. interface INavResponse {
  13. ok: boolean;
  14. message: string;
  15. data: {
  16. prev?: INavButton;
  17. next?: INavButton;
  18. };
  19. }
  20. interface IWidget {
  21. type?: ArticleType;
  22. articleId?: string;
  23. path?: ITocPathNode[];
  24. onChange?: (
  25. event: React.MouseEvent<HTMLElement, MouseEvent>,
  26. id: string
  27. ) => void;
  28. onPathChange?: (key: string) => void;
  29. }
  30. const NavigateWidget = ({
  31. type,
  32. articleId,
  33. path,
  34. onChange,
  35. onPathChange,
  36. }: IWidget) => {
  37. const [prev, setPrev] = useState<INavButton>();
  38. const [next, setNext] = useState<INavButton>();
  39. useEffect(() => {
  40. if (type && articleId) {
  41. get<INavResponse>(`/v2/article-nav?type=${type}&id=${articleId}`).then(
  42. (json) => {
  43. if (json.ok) {
  44. setPrev(json.data.prev);
  45. setNext(json.data.next);
  46. }
  47. }
  48. );
  49. }
  50. }, [articleId, type]);
  51. return (
  52. <NavigateButton
  53. prevTitle={prev?.title}
  54. nextTitle={next?.title}
  55. path={path}
  56. onPrev={(event: React.MouseEvent<HTMLElement, MouseEvent>) => {
  57. if (typeof onChange !== "undefined" && prev) {
  58. onChange(event, prev.id);
  59. }
  60. }}
  61. onNext={(event: React.MouseEvent<HTMLElement, MouseEvent>) => {
  62. if (typeof onChange !== "undefined" && next) {
  63. onChange(event, next.id);
  64. }
  65. }}
  66. onPathChange={(key: string) => {
  67. if (typeof onPathChange !== "undefined") {
  68. onPathChange(key);
  69. }
  70. }}
  71. />
  72. );
  73. };
  74. export default NavigateWidget;