TopBar.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /** @jsx h */
  2. import { h } from "preact";
  3. import { useEffect, useState } from "preact/hooks";
  4. interface TopBarProps {
  5. allowMode: "edit" | "read" | "both";
  6. }
  7. export default function TopBar(props: TopBarProps) {
  8. const [mode, setMode] = useState(props.allowMode);
  9. const [isLogin, setIsLogin] = useState(false);
  10. // Event listener
  11. const modeChangeListener = (e: CustomEvent) => {
  12. if (
  13. e.detail &&
  14. (props.allowMode === e.detail || props.allowMode === "both")
  15. ) {
  16. setMode(e.detail);
  17. }
  18. };
  19. // Event dispatche
  20. const modeChangeDispatcher = (mode: string) => {
  21. dispatchEvent(new CustomEvent("ModeChange", { detail: mode }));
  22. };
  23. const checkUserLogin = async () => {
  24. const resp = await fetch("/api/user/login");
  25. const respJson = await resp.json();
  26. if (respJson.success) {
  27. setIsLogin(true);
  28. return true;
  29. }
  30. // Redirect to login page if not valid
  31. location.href = "/login";
  32. return false;
  33. };
  34. // Init event listeners
  35. useEffect(() => {
  36. checkUserLogin();
  37. addEventListener("ModeChange", modeChangeListener);
  38. return () => {
  39. removeEventListener("ModeChange", modeChangeListener);
  40. };
  41. }, []);
  42. return (
  43. <div className="pd-top-bar">
  44. <div className="pd-top-bar-mode-switcher">
  45. <button
  46. className={`pd-top-bar-btn${mode === "edit" ? " active" : ""}${
  47. props.allowMode === "read" ? " disabled" : ""
  48. }`}
  49. id="edit"
  50. type="button"
  51. onClick={() => {
  52. modeChangeDispatcher("edit");
  53. }}
  54. >
  55. Edit
  56. </button>
  57. <button
  58. className={`pd-top-bar-btn${mode === "read" ? " active" : ""}${
  59. props.allowMode === "edit" ? " disabled" : ""
  60. }`}
  61. id="read"
  62. type="button"
  63. onClick={() => {
  64. modeChangeDispatcher("read");
  65. }}
  66. >
  67. Read
  68. </button>
  69. <button
  70. className={`pd-top-bar-btn${mode === "both" ? " active" : ""}${
  71. props.allowMode !== "both" ? " disabled" : ""
  72. }`}
  73. id="both"
  74. type="button"
  75. onClick={() => {
  76. modeChangeDispatcher("both");
  77. }}
  78. >
  79. Both
  80. </button>
  81. </div>
  82. {isLogin ? (
  83. <div className="pd-top-bar-tool-icons">
  84. <i className="bi bi-house-door" />
  85. <i className="bi bi-share" />
  86. <i className="bi bi-gear" />
  87. </div>
  88. ) : null}
  89. </div>
  90. );
  91. }