warqadui 0.0.69 → 0.0.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1515,8 +1515,8 @@ var useModal = (initialState = false) => {
1515
1515
  resetState();
1516
1516
  }, []);
1517
1517
  const toggle = (0, import_react10.useCallback)(() => setIsOpen((prev) => !prev), []);
1518
- const openState = (0, import_react10.useCallback)((data2) => {
1519
- setState(data2);
1518
+ const openState = (0, import_react10.useCallback)((data) => {
1519
+ setState(data);
1520
1520
  open();
1521
1521
  }, []);
1522
1522
  const ModalComponent = (0, import_react10.useMemo)(() => {
@@ -2193,7 +2193,7 @@ var useApi = () => {
2193
2193
  withCredentials: true
2194
2194
  });
2195
2195
  }, [configApi]);
2196
- const [data2, setData] = (0, import_react14.useState)();
2196
+ const [data, setData] = (0, import_react14.useState)();
2197
2197
  const [isLoading, setIsLoading] = (0, import_react14.useState)(false);
2198
2198
  const [pdfLoading, setPdfLoading] = (0, import_react14.useState)(false);
2199
2199
  const [error, setError] = (0, import_react14.useState)(null);
@@ -2333,7 +2333,7 @@ var useApi = () => {
2333
2333
  }
2334
2334
  };
2335
2335
  return {
2336
- data: data2,
2336
+ data,
2337
2337
  error,
2338
2338
  isLoading,
2339
2339
  pdfLoading,
@@ -3144,7 +3144,7 @@ var import_lucide_react11 = require("lucide-react");
3144
3144
  var import_jsx_runtime24 = require("react/jsx-runtime");
3145
3145
  function DataTable({
3146
3146
  columns: userColumns,
3147
- data: data2,
3147
+ data,
3148
3148
  isLoading = false,
3149
3149
  pageRows,
3150
3150
  searchPlaceholder = "Search all columns...",
@@ -3192,8 +3192,8 @@ function DataTable({
3192
3192
  }, [pageRows]);
3193
3193
  const [expanded, setExpanded] = (0, import_react17.useState)(() => {
3194
3194
  const initialState = {};
3195
- if (defaultExpanded && renderSubComponent && data2) {
3196
- data2.forEach((row, idx) => {
3195
+ if (defaultExpanded && renderSubComponent && data) {
3196
+ data.forEach((row, idx) => {
3197
3197
  if (hasSubComponent(row)) {
3198
3198
  initialState[idx] = true;
3199
3199
  }
@@ -3224,7 +3224,7 @@ function DataTable({
3224
3224
  ];
3225
3225
  }, [userColumns, index, selectable]);
3226
3226
  const table = (0, import_react_table.useReactTable)({
3227
- data: data2,
3227
+ data,
3228
3228
  columns,
3229
3229
  onSortingChange: setSorting,
3230
3230
  onColumnFiltersChange: setColumnFilters,
@@ -3563,16 +3563,16 @@ function PostTable({
3563
3563
  });
3564
3564
  const [internalData, setInternalData] = (0, import_react18.useState)(controlledData || []);
3565
3565
  const isControlled = controlledData !== void 0;
3566
- const data2 = isControlled ? controlledData : internalData;
3566
+ const data = isControlled ? controlledData : internalData;
3567
3567
  const entryRowRef = (0, import_react18.useRef)(null);
3568
3568
  (0, import_react18.useEffect)(() => {
3569
- if (defaultExpanded && renderSubComponent && (data2 || []).length > 0) {
3569
+ if (defaultExpanded && renderSubComponent && (data || []).length > 0) {
3570
3570
  setExpanded((prev) => {
3571
3571
  const isAllExpanded = prev === true;
3572
3572
  if (isAllExpanded) return prev;
3573
3573
  const newState = typeof prev === "object" ? { ...prev } : {};
3574
3574
  let changed = false;
3575
- data2.forEach((row, idx) => {
3575
+ data.forEach((row, idx) => {
3576
3576
  const id = idx.toString();
3577
3577
  if (hasSubComponent(row) && newState[id] === void 0) {
3578
3578
  newState[id] = true;
@@ -3582,7 +3582,7 @@ function PostTable({
3582
3582
  return changed ? newState : prev;
3583
3583
  });
3584
3584
  }
3585
- }, [data2, defaultExpanded, hasSubComponent, renderSubComponent]);
3585
+ }, [data, defaultExpanded, hasSubComponent, renderSubComponent]);
3586
3586
  const focusAndScrollEntryRow = () => {
3587
3587
  setTimeout(() => {
3588
3588
  if (entryRowRef.current) {
@@ -3607,7 +3607,7 @@ function PostTable({
3607
3607
  const [isSavingAsync, setIsSavingAsync] = (0, import_react18.useState)(false);
3608
3608
  const [fieldErrors, setFieldErrors] = (0, import_react18.useState)({});
3609
3609
  const latestStateRef = (0, import_react18.useRef)({
3610
- data: data2,
3610
+ data,
3611
3611
  entryData,
3612
3612
  editingIndex,
3613
3613
  isSavingAsync,
@@ -3620,7 +3620,7 @@ function PostTable({
3620
3620
  });
3621
3621
  (0, import_react18.useEffect)(() => {
3622
3622
  latestStateRef.current = {
3623
- data: data2,
3623
+ data,
3624
3624
  entryData,
3625
3625
  editingIndex,
3626
3626
  isSavingAsync,
@@ -3633,11 +3633,11 @@ function PostTable({
3633
3633
  };
3634
3634
  });
3635
3635
  const handleSaveField = (0, import_react18.useCallback)(async () => {
3636
- const { data: data3, entryData: entryData2, editingIndex: editingIndex2, onChange: onChange2 } = latestStateRef.current;
3636
+ const { data: data2, entryData: entryData2, editingIndex: editingIndex2, onChange: onChange2 } = latestStateRef.current;
3637
3637
  if (Object.keys(entryData2).length === 0) return;
3638
3638
  const actionType = editingIndex2 !== null ? "edit" : "add";
3639
3639
  const entryToSave = { ...entryData2 };
3640
- const updated = [...data3];
3640
+ const updated = [...data2];
3641
3641
  let entryToPass;
3642
3642
  if (actionType === "edit" && editingIndex2 !== null) {
3643
3643
  updated[editingIndex2] = {
@@ -3713,9 +3713,9 @@ function PostTable({
3713
3713
  }, []);
3714
3714
  const handleDelete = (0, import_react18.useCallback)(
3715
3715
  async (index2) => {
3716
- const { data: data3, editingIndex: editingIndex2, onChange: onChange2, onDelete: onDelete2 } = latestStateRef.current;
3717
- const rowToDelete = data3[index2];
3718
- const updated = data3.filter((_, i) => i !== index2);
3716
+ const { data: data2, editingIndex: editingIndex2, onChange: onChange2, onDelete: onDelete2 } = latestStateRef.current;
3717
+ const rowToDelete = data2[index2];
3718
+ const updated = data2.filter((_, i) => i !== index2);
3719
3719
  if (onChange2) {
3720
3720
  setIsSavingAsync(true);
3721
3721
  try {
@@ -3831,7 +3831,7 @@ function PostTable({
3831
3831
  return finalColumns;
3832
3832
  }, [userColumns, actionColumn, index, renderSubComponent, hasSubComponent]);
3833
3833
  const table = (0, import_react_table2.useReactTable)({
3834
- data: data2,
3834
+ data,
3835
3835
  columns,
3836
3836
  onSortingChange: setSorting,
3837
3837
  onColumnFiltersChange: setColumnFilters,
@@ -4141,7 +4141,7 @@ var import_react_table3 = require("@tanstack/react-table");
4141
4141
  var import_jsx_runtime26 = require("react/jsx-runtime");
4142
4142
  function SimpleTable({
4143
4143
  columns: userColumns,
4144
- data: data2,
4144
+ data,
4145
4145
  className = "",
4146
4146
  renderFooter: componentFooter,
4147
4147
  rowPadding = "py-3",
@@ -4176,7 +4176,7 @@ function SimpleTable({
4176
4176
  return cols;
4177
4177
  }, [userColumns, index, startIndex]);
4178
4178
  const table = (0, import_react_table3.useReactTable)({
4179
- data: data2,
4179
+ data,
4180
4180
  columns,
4181
4181
  getCoreRowModel: (0, import_react_table3.getCoreRowModel)()
4182
4182
  });
@@ -4216,7 +4216,7 @@ function SimpleTable({
4216
4216
  },
4217
4217
  headerGroup.id
4218
4218
  )) }),
4219
- /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("tbody", { className: "text-black dark:text-white font-semibold font-sans tabular-nums", children: isLoading && data2.length === 0 ? Array.from({ length: skeletonCount }).map((_, i) => /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
4219
+ /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("tbody", { className: "text-black dark:text-white font-semibold font-sans tabular-nums", children: isLoading && data.length === 0 ? Array.from({ length: skeletonCount }).map((_, i) => /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
4220
4220
  "tr",
4221
4221
  {
4222
4222
  className: `border-b ${verticalLines ? "border-black dark:border-white" : "border-gray-100 dark:border-zinc-800/60 last:border-0"}`,
@@ -4235,7 +4235,7 @@ function SimpleTable({
4235
4235
  ))
4236
4236
  },
4237
4237
  `skeleton-row-${i}`
4238
- )) : data2.length === 0 && !isLoading ? /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("tr", { children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
4238
+ )) : data.length === 0 && !isLoading ? /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("tr", { children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
4239
4239
  "td",
4240
4240
  {
4241
4241
  colSpan: columns.length,
@@ -5297,7 +5297,7 @@ var useA4StatementView = ({
5297
5297
  renderFooter: (value) => value.reduce((acc, item) => acc + item.amount, 0)
5298
5298
  }
5299
5299
  ],
5300
- data: data2 = [],
5300
+ data = [],
5301
5301
  error = apiError,
5302
5302
  info,
5303
5303
  index,
@@ -5320,7 +5320,7 @@ var useA4StatementView = ({
5320
5320
  const [currentPageIndex, setCurrentPageIndex] = (0, import_react26.useState)(0);
5321
5321
  const [pageSearch, setPageSearch] = (0, import_react26.useState)("");
5322
5322
  const displayColumnsForSearch = columns.filter((col) => !col.hide);
5323
- const filteredDisplayData = data2.filter((row) => {
5323
+ const filteredDisplayData = data.filter((row) => {
5324
5324
  if (!globalFilter) return true;
5325
5325
  const lowerFilter = globalFilter.toLowerCase();
5326
5326
  return displayColumnsForSearch.some((col) => {
@@ -5463,7 +5463,7 @@ var useA4StatementView = ({
5463
5463
  isLoading: isActuallyLoading
5464
5464
  }
5465
5465
  ) }) : null;
5466
- const statusOverlay = isActuallyLoading || error || !data2 || data2.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "flex flex-col relative w-full items-center justify-center py-12 min-h-[400px]", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "flex flex-col items-center justify-center p-8 bg-gray-50/50 dark:bg-zinc-900/30 rounded-2xl border border-dashed border-gray-300 dark:border-zinc-700 w-full max-w-lg text-center shadow-sm", children: [
5466
+ const statusOverlay = isActuallyLoading || error || !data || data.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "flex flex-col relative w-full items-center justify-center py-12 min-h-[400px]", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "flex flex-col items-center justify-center p-8 bg-gray-50/50 dark:bg-zinc-900/30 rounded-2xl border border-dashed border-gray-300 dark:border-zinc-700 w-full max-w-lg text-center shadow-sm", children: [
5467
5467
  isActuallyLoading ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "mb-4", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(ClassicSpin, {}) }) : error ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "w-14 h-14 bg-red-100 dark:bg-red-500/10 rounded-full flex items-center justify-center mb-4", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react16.AlertCircle, { className: "w-7 h-7 text-red-600 dark:text-red-500" }) }) : /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "w-14 h-14 bg-gray-200 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react16.FileX, { className: "w-7 h-7 text-gray-500 dark:text-gray-400" }) }),
5468
5468
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("h3", { className: "text-lg font-bold text-gray-900 dark:text-white mb-2", children: isActuallyLoading ? "Loading data..." : error ? "Failed to Load Statement" : "No Records Found" }),
5469
5469
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("p", { className: "text-sm text-gray-500 dark:text-gray-400 max-w-xs mb-6 leading-relaxed", children: isActuallyLoading ? "Please wait while we prepare your statement." : error ? typeof error === "string" ? error : "An unexpected error occurred while fetching the statement data." : "There are no transactions or records available in this requested statement." }),
@@ -5706,7 +5706,7 @@ var useA4CategoryView = ({
5706
5706
  getData();
5707
5707
  }, [url, v, JSON.stringify(params), delay]);
5708
5708
  const A4CategoryView = ({
5709
- data: data2,
5709
+ data,
5710
5710
  groups: incomingGroups,
5711
5711
  error = apiError,
5712
5712
  info,
@@ -5729,7 +5729,7 @@ var useA4CategoryView = ({
5729
5729
  const [pageSearch, setPageSearch] = (0, import_react27.useState)("");
5730
5730
  const groups = incomingGroups ? [...incomingGroups].sort(
5731
5731
  (a, b) => a.title.localeCompare(b.title)
5732
- ) : data2 ? [{ title: gridTitle, items: data2 }] : [];
5732
+ ) : data ? [{ title: gridTitle, items: data }] : [];
5733
5733
  const flattenedNodes = groups.map((group) => {
5734
5734
  const sortedItems = [...group.items].sort(
5735
5735
  (a, b) => String(a.name).localeCompare(String(b.name))
@@ -6074,7 +6074,7 @@ var useTransaction = ({
6074
6074
  hide: true
6075
6075
  }
6076
6076
  ],
6077
- data: data2 = [],
6077
+ data = [],
6078
6078
  error = apiError,
6079
6079
  pageRows,
6080
6080
  searchPlaceholder = "Search transactions...",
@@ -6091,7 +6091,7 @@ var useTransaction = ({
6091
6091
  createTitle = "Add New",
6092
6092
  ...rest
6093
6093
  }) => {
6094
- const emptyState = !isLoading && (error || !data2 || data2.length === 0) ? /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
6094
+ const emptyState = !isLoading && (error || !data || data.length === 0) ? /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
6095
6095
  "div",
6096
6096
  {
6097
6097
  className: `flex flex-col relative w-full items-center justify-center py-12 min-h-[300px] ${className}`,
@@ -6158,7 +6158,7 @@ var useTransaction = ({
6158
6158
  DataTable,
6159
6159
  {
6160
6160
  columns,
6161
- data: data2,
6161
+ data,
6162
6162
  isLoading,
6163
6163
  pageRows,
6164
6164
  searchPlaceholder,
@@ -7864,11 +7864,11 @@ var useAuthStore = (0, import_zustand.create)((set, get) => ({
7864
7864
  isLoggedIn: false,
7865
7865
  isFetched: true
7866
7866
  }),
7867
- updateAuth: (data2) => set((state) => ({
7868
- auth: state.auth ? { ...state.auth, ...data2 } : state.auth
7867
+ updateAuth: (data) => set((state) => ({
7868
+ auth: state.auth ? { ...state.auth, ...data } : state.auth
7869
7869
  })),
7870
- updateAccount: (data2) => set((state) => ({
7871
- account: state.account ? { ...state.account, ...data2 } : state.account
7870
+ updateAccount: (data) => set((state) => ({
7871
+ account: state.account ? { ...state.account, ...data } : state.account
7872
7872
  })),
7873
7873
  hasPermission: (key) => !!get().auth?.permissions?.[key]
7874
7874
  }));
@@ -7912,13 +7912,13 @@ var useAuth = () => {
7912
7912
  setIsLoggedIn,
7913
7913
  setIsFetched,
7914
7914
  setAuth,
7915
- login: (data2) => {
7916
- if (data2?.auth && data2?.account) {
7917
- setAuth(data2.auth, data2.account);
7918
- } else if (data2?.user && data2?.account) {
7919
- setAuth(data2.user, data2.account);
7915
+ login: (data) => {
7916
+ if (data?.auth && data?.account) {
7917
+ setAuth(data.auth, data.account);
7918
+ } else if (data?.user && data?.account) {
7919
+ setAuth(data.user, data.account);
7920
7920
  } else {
7921
- setAuth(data2, data2?.account || data2);
7921
+ setAuth(data, data?.account || data);
7922
7922
  }
7923
7923
  },
7924
7924
  updateAuth,
@@ -7992,28 +7992,28 @@ function Accounts({ v, url }) {
7992
7992
  const [deleteAccount, setDeleteAccount] = (0, import_react33.useState)(null);
7993
7993
  const { isLoading, remove } = useApis_default();
7994
7994
  const isEmployee = type === "employee";
7995
- const { data: data2, TransactionViewComponent, reload } = useTransaction_default({
7995
+ const { data, TransactionViewComponent, reload } = useTransaction_default({
7996
7996
  url: url || `/accounts/get/${type}`,
7997
7997
  v,
7998
7998
  dateFilter: false
7999
7999
  });
8000
8000
  const { Modal: Modal2 } = useModal();
8001
8001
  const navigate = (0, import_react_router_dom5.useNavigate)();
8002
- const items = (data3) => [
8002
+ const items = (data2) => [
8003
8003
  {
8004
8004
  label: `Edit ${type}`,
8005
8005
  icon: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_lucide_react19.FilePenLine, { size: 16 }),
8006
- onClick: () => navigate(`update?id=${data3?._id}`)
8006
+ onClick: () => navigate(`update?id=${data2?._id}`)
8007
8007
  },
8008
8008
  {
8009
8009
  label: `Delete ${type}`,
8010
8010
  icon: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_lucide_react19.Trash2, { className: "text-red-500", size: 16 }),
8011
- onClick: () => setDeleteAccount(data3)
8011
+ onClick: () => setDeleteAccount(data2)
8012
8012
  },
8013
- isEmployee && !data3?.user && {
8013
+ isEmployee && !data2?.user && {
8014
8014
  label: `Link User`,
8015
8015
  icon: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_lucide_react19.Cable, { size: 16 }),
8016
- onClick: () => navigate(`link-user?id=${data3?._id}`)
8016
+ onClick: () => navigate(`link-user?id=${data2?._id}`)
8017
8017
  }
8018
8018
  ].filter(Boolean);
8019
8019
  const columns = [
@@ -8061,12 +8061,12 @@ function Accounts({ v, url }) {
8061
8061
  accessorKey: "actions",
8062
8062
  header: "Actions",
8063
8063
  cell: ({ row }) => {
8064
- const data3 = row.original;
8064
+ const data2 = row.original;
8065
8065
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
8066
8066
  Dropdown,
8067
8067
  {
8068
8068
  className: "cursor-pointer w-[150px]",
8069
- items: items(data3),
8069
+ items: items(data2),
8070
8070
  triggerMode: "hover",
8071
8071
  children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_lucide_react19.EllipsisVertical, {})
8072
8072
  }
@@ -8074,7 +8074,7 @@ function Accounts({ v, url }) {
8074
8074
  }
8075
8075
  }
8076
8076
  ].filter(Boolean);
8077
- const accounts = data2?.data || [];
8077
+ const accounts = data?.data || [];
8078
8078
  const onDelete = async (id) => {
8079
8079
  try {
8080
8080
  await remove({ url: `/accounts/delete/${id}` });
@@ -8119,2505 +8119,110 @@ function Accounts({ v, url }) {
8119
8119
  }
8120
8120
  var Accounts_default = Accounts;
8121
8121
 
8122
- // ../../node_modules/react-router/dist/development/chunk-LFPYN7LY.mjs
8123
- var React24 = __toESM(require("react"), 1);
8124
- var React25 = __toESM(require("react"), 1);
8125
- var React32 = __toESM(require("react"), 1);
8126
- var React42 = __toESM(require("react"), 1);
8127
- var React92 = __toESM(require("react"), 1);
8128
- var React82 = __toESM(require("react"), 1);
8129
- var React72 = __toESM(require("react"), 1);
8130
- var React62 = __toESM(require("react"), 1);
8131
- var React52 = __toESM(require("react"), 1);
8132
- var React102 = __toESM(require("react"), 1);
8133
- var React112 = __toESM(require("react"), 1);
8134
- var import_meta = {};
8135
- function invariant(value, message13) {
8136
- if (value === false || value === null || typeof value === "undefined") {
8137
- throw new Error(message13);
8138
- }
8139
- }
8140
- function warning3(cond, message13) {
8141
- if (!cond) {
8142
- if (typeof console !== "undefined") console.warn(message13);
8143
- try {
8144
- throw new Error(message13);
8145
- } catch (e) {
8146
- }
8147
- }
8148
- }
8149
- function createPath({
8150
- pathname = "/",
8151
- search = "",
8152
- hash = ""
8153
- }) {
8154
- if (search && search !== "?")
8155
- pathname += search.charAt(0) === "?" ? search : "?" + search;
8156
- if (hash && hash !== "#")
8157
- pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
8158
- return pathname;
8159
- }
8160
- function parsePath(path) {
8161
- let parsedPath = {};
8162
- if (path) {
8163
- let hashIndex = path.indexOf("#");
8164
- if (hashIndex >= 0) {
8165
- parsedPath.hash = path.substring(hashIndex);
8166
- path = path.substring(0, hashIndex);
8167
- }
8168
- let searchIndex = path.indexOf("?");
8169
- if (searchIndex >= 0) {
8170
- parsedPath.search = path.substring(searchIndex);
8171
- path = path.substring(0, searchIndex);
8172
- }
8173
- if (path) {
8174
- parsedPath.pathname = path;
8175
- }
8176
- }
8177
- return parsedPath;
8178
- }
8179
- var _map;
8180
- _map = /* @__PURE__ */ new WeakMap();
8181
- function matchRoutes(routes, locationArg, basename = "/") {
8182
- return matchRoutesImpl(routes, locationArg, basename, false);
8183
- }
8184
- function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
8185
- let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
8186
- let pathname = stripBasename(location.pathname || "/", basename);
8187
- if (pathname == null) {
8188
- return null;
8189
- }
8190
- let branches = flattenRoutes(routes);
8191
- rankRouteBranches(branches);
8192
- let matches = null;
8193
- for (let i = 0; matches == null && i < branches.length; ++i) {
8194
- let decoded = decodePath(pathname);
8195
- matches = matchRouteBranch(
8196
- branches[i],
8197
- decoded,
8198
- allowPartial
8199
- );
8200
- }
8201
- return matches;
8202
- }
8203
- function convertRouteMatchToUiMatch(match, loaderData) {
8204
- let { route, pathname, params } = match;
8205
- return {
8206
- id: route.id,
8207
- pathname,
8208
- params,
8209
- data: loaderData[route.id],
8210
- loaderData: loaderData[route.id],
8211
- handle: route.handle
8212
- };
8213
- }
8214
- function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
8215
- let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
8216
- let meta = {
8217
- relativePath: relativePath === void 0 ? route.path || "" : relativePath,
8218
- caseSensitive: route.caseSensitive === true,
8219
- childrenIndex: index,
8220
- route
8221
- };
8222
- if (meta.relativePath.startsWith("/")) {
8223
- if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
8224
- return;
8225
- }
8226
- invariant(
8227
- meta.relativePath.startsWith(parentPath),
8228
- `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`
8229
- );
8230
- meta.relativePath = meta.relativePath.slice(parentPath.length);
8231
- }
8232
- let path = joinPaths([parentPath, meta.relativePath]);
8233
- let routesMeta = parentsMeta.concat(meta);
8234
- if (route.children && route.children.length > 0) {
8235
- invariant(
8236
- // Our types know better, but runtime JS may not!
8237
- // @ts-expect-error
8238
- route.index !== true,
8239
- `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
8240
- );
8241
- flattenRoutes(
8242
- route.children,
8243
- branches,
8244
- routesMeta,
8245
- path,
8246
- hasParentOptionalSegments
8247
- );
8248
- }
8249
- if (route.path == null && !route.index) {
8250
- return;
8251
- }
8252
- branches.push({
8253
- path,
8254
- score: computeScore(path, route.index),
8255
- routesMeta
8256
- });
8122
+ // src/hooks/useApp.tsx
8123
+ var import_react_router_dom6 = require("react-router-dom");
8124
+ var useApp = () => {
8125
+ const [searchParams] = (0, import_react_router_dom6.useSearchParams)();
8126
+ const navigate = (0, import_react_router_dom6.useNavigate)();
8127
+ const getParams = (key) => {
8128
+ const params = (0, import_react_router_dom6.useParams)();
8129
+ if (key) return params[key];
8130
+ return params;
8257
8131
  };
8258
- routes.forEach((route, index) => {
8259
- if (route.path === "" || !route.path?.includes("?")) {
8260
- flattenRoute(route, index);
8261
- } else {
8262
- for (let exploded of explodeOptionalSegments(route.path)) {
8263
- flattenRoute(route, index, true, exploded);
8264
- }
8265
- }
8266
- });
8267
- return branches;
8268
- }
8269
- function explodeOptionalSegments(path) {
8270
- let segments = path.split("/");
8271
- if (segments.length === 0) return [];
8272
- let [first, ...rest] = segments;
8273
- let isOptional = first.endsWith("?");
8274
- let required = first.replace(/\?$/, "");
8275
- if (rest.length === 0) {
8276
- return isOptional ? [required, ""] : [required];
8277
- }
8278
- let restExploded = explodeOptionalSegments(rest.join("/"));
8279
- let result = [];
8280
- result.push(
8281
- ...restExploded.map(
8282
- (subpath) => subpath === "" ? required : [required, subpath].join("/")
8283
- )
8284
- );
8285
- if (isOptional) {
8286
- result.push(...restExploded);
8287
- }
8288
- return result.map(
8289
- (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
8290
- );
8291
- }
8292
- function rankRouteBranches(branches) {
8293
- branches.sort(
8294
- (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
8295
- a.routesMeta.map((meta) => meta.childrenIndex),
8296
- b.routesMeta.map((meta) => meta.childrenIndex)
8297
- )
8298
- );
8299
- }
8300
- var paramRe = /^:[\w-]+$/;
8301
- var dynamicSegmentValue = 3;
8302
- var indexRouteValue = 2;
8303
- var emptySegmentValue = 1;
8304
- var staticSegmentValue = 10;
8305
- var splatPenalty = -2;
8306
- var isSplat = (s) => s === "*";
8307
- function computeScore(path, index) {
8308
- let segments = path.split("/");
8309
- let initialScore = segments.length;
8310
- if (segments.some(isSplat)) {
8311
- initialScore += splatPenalty;
8312
- }
8313
- if (index) {
8314
- initialScore += indexRouteValue;
8315
- }
8316
- return segments.filter((s) => !isSplat(s)).reduce(
8317
- (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
8318
- initialScore
8319
- );
8320
- }
8321
- function compareIndexes(a, b) {
8322
- let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
8323
- return siblings ? (
8324
- // If two routes are siblings, we should try to match the earlier sibling
8325
- // first. This allows people to have fine-grained control over the matching
8326
- // behavior by simply putting routes with identical paths in the order they
8327
- // want them tried.
8328
- a[a.length - 1] - b[b.length - 1]
8329
- ) : (
8330
- // Otherwise, it doesn't really make sense to rank non-siblings by index,
8331
- // so they sort equally.
8332
- 0
8333
- );
8334
- }
8335
- function matchRouteBranch(branch, pathname, allowPartial = false) {
8336
- let { routesMeta } = branch;
8337
- let matchedParams = {};
8338
- let matchedPathname = "/";
8339
- let matches = [];
8340
- for (let i = 0; i < routesMeta.length; ++i) {
8341
- let meta = routesMeta[i];
8342
- let end = i === routesMeta.length - 1;
8343
- let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
8344
- let match = matchPath(
8345
- { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
8346
- remainingPathname
8347
- );
8348
- let route = meta.route;
8349
- if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
8350
- match = matchPath(
8351
- {
8352
- path: meta.relativePath,
8353
- caseSensitive: meta.caseSensitive,
8354
- end: false
8355
- },
8356
- remainingPathname
8357
- );
8358
- }
8359
- if (!match) {
8360
- return null;
8361
- }
8362
- Object.assign(matchedParams, match.params);
8363
- matches.push({
8364
- // TODO: Can this as be avoided?
8365
- params: matchedParams,
8366
- pathname: joinPaths([matchedPathname, match.pathname]),
8367
- pathnameBase: normalizePathname(
8368
- joinPaths([matchedPathname, match.pathnameBase])
8369
- ),
8370
- route
8371
- });
8372
- if (match.pathnameBase !== "/") {
8373
- matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
8374
- }
8375
- }
8376
- return matches;
8377
- }
8378
- function matchPath(pattern, pathname) {
8379
- if (typeof pattern === "string") {
8380
- pattern = { path: pattern, caseSensitive: false, end: true };
8381
- }
8382
- let [matcher, compiledParams] = compilePath(
8383
- pattern.path,
8384
- pattern.caseSensitive,
8385
- pattern.end
8386
- );
8387
- let match = pathname.match(matcher);
8388
- if (!match) return null;
8389
- let matchedPathname = match[0];
8390
- let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
8391
- let captureGroups = match.slice(1);
8392
- let params = compiledParams.reduce(
8393
- (memo2, { paramName, isOptional }, index) => {
8394
- if (paramName === "*") {
8395
- let splatValue = captureGroups[index] || "";
8396
- pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
8397
- }
8398
- const value = captureGroups[index];
8399
- if (isOptional && !value) {
8400
- memo2[paramName] = void 0;
8401
- } else {
8402
- memo2[paramName] = (value || "").replace(/%2F/g, "/");
8403
- }
8404
- return memo2;
8405
- },
8406
- {}
8407
- );
8408
- return {
8409
- params,
8410
- pathname: matchedPathname,
8411
- pathnameBase,
8412
- pattern
8132
+ const getQuery = (key) => {
8133
+ if (key) return searchParams.get(key);
8134
+ return Object.fromEntries(searchParams.entries());
8413
8135
  };
8414
- }
8415
- function compilePath(path, caseSensitive = false, end = true) {
8416
- warning3(
8417
- path === "*" || !path.endsWith("*") || path.endsWith("/*"),
8418
- `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
8419
- );
8420
- let params = [];
8421
- let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
8422
- /\/:([\w-]+)(\?)?/g,
8423
- (match, paramName, isOptional, index, str) => {
8424
- params.push({ paramName, isOptional: isOptional != null });
8425
- if (isOptional) {
8426
- let nextChar = str.charAt(index + match.length);
8427
- if (nextChar && nextChar !== "/") {
8428
- return "/([^\\/]*)";
8429
- }
8430
- return "(?:/([^\\/]*))?";
8431
- }
8432
- return "/([^\\/]+)";
8433
- }
8434
- ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
8435
- if (path.endsWith("*")) {
8436
- params.push({ paramName: "*" });
8437
- regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
8438
- } else if (end) {
8439
- regexpSource += "\\/*$";
8440
- } else if (path !== "" && path !== "/") {
8441
- regexpSource += "(?:(?=\\/|$))";
8442
- } else {
8443
- }
8444
- let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
8445
- return [matcher, params];
8446
- }
8447
- function decodePath(value) {
8448
- try {
8449
- return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
8450
- } catch (error) {
8451
- warning3(
8452
- false,
8453
- `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
8454
- );
8455
- return value;
8456
- }
8457
- }
8458
- function stripBasename(pathname, basename) {
8459
- if (basename === "/") return pathname;
8460
- if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
8461
- return null;
8462
- }
8463
- let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
8464
- let nextChar = pathname.charAt(startIndex);
8465
- if (nextChar && nextChar !== "/") {
8466
- return null;
8467
- }
8468
- return pathname.slice(startIndex) || "/";
8469
- }
8470
- var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
8471
- function resolvePath(to, fromPathname = "/") {
8472
- let {
8473
- pathname: toPathname,
8474
- search = "",
8475
- hash = ""
8476
- } = typeof to === "string" ? parsePath(to) : to;
8477
- let pathname;
8478
- if (toPathname) {
8479
- toPathname = toPathname.replace(/\/\/+/g, "/");
8480
- if (toPathname.startsWith("/")) {
8481
- pathname = resolvePathname(toPathname.substring(1), "/");
8482
- } else {
8483
- pathname = resolvePathname(toPathname, fromPathname);
8484
- }
8485
- } else {
8486
- pathname = fromPathname;
8487
- }
8488
8136
  return {
8489
- pathname,
8490
- search: normalizeSearch(search),
8491
- hash: normalizeHash(hash)
8137
+ navigate,
8138
+ getQuery,
8139
+ getParams
8492
8140
  };
8493
- }
8494
- function resolvePathname(relativePath, fromPathname) {
8495
- let segments = fromPathname.replace(/\/+$/, "").split("/");
8496
- let relativeSegments = relativePath.split("/");
8497
- relativeSegments.forEach((segment) => {
8498
- if (segment === "..") {
8499
- if (segments.length > 1) segments.pop();
8500
- } else if (segment !== ".") {
8501
- segments.push(segment);
8502
- }
8503
- });
8504
- return segments.length > 1 ? segments.join("/") : "/";
8505
- }
8506
- function getInvalidPathError(char, field, dest, path) {
8507
- return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
8508
- path
8509
- )}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
8510
- }
8511
- function getPathContributingMatches(matches) {
8512
- return matches.filter(
8513
- (match, index) => index === 0 || match.route.path && match.route.path.length > 0
8514
- );
8515
- }
8516
- function getResolveToMatches(matches) {
8517
- let pathMatches = getPathContributingMatches(matches);
8518
- return pathMatches.map(
8519
- (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
8520
- );
8521
- }
8522
- function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
8523
- let to;
8524
- if (typeof toArg === "string") {
8525
- to = parsePath(toArg);
8526
- } else {
8527
- to = { ...toArg };
8528
- invariant(
8529
- !to.pathname || !to.pathname.includes("?"),
8530
- getInvalidPathError("?", "pathname", "search", to)
8531
- );
8532
- invariant(
8533
- !to.pathname || !to.pathname.includes("#"),
8534
- getInvalidPathError("#", "pathname", "hash", to)
8535
- );
8536
- invariant(
8537
- !to.search || !to.search.includes("#"),
8538
- getInvalidPathError("#", "search", "hash", to)
8539
- );
8540
- }
8541
- let isEmptyPath = toArg === "" || to.pathname === "";
8542
- let toPathname = isEmptyPath ? "/" : to.pathname;
8543
- let from;
8544
- if (toPathname == null) {
8545
- from = locationPathname;
8546
- } else {
8547
- let routePathnameIndex = routePathnames.length - 1;
8548
- if (!isPathRelative && toPathname.startsWith("..")) {
8549
- let toSegments = toPathname.split("/");
8550
- while (toSegments[0] === "..") {
8551
- toSegments.shift();
8552
- routePathnameIndex -= 1;
8553
- }
8554
- to.pathname = toSegments.join("/");
8555
- }
8556
- from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
8557
- }
8558
- let path = resolvePath(to, from);
8559
- let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
8560
- let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
8561
- if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
8562
- path.pathname += "/";
8563
- }
8564
- return path;
8565
- }
8566
- var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
8567
- var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
8568
- var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
8569
- var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
8570
- var ErrorResponseImpl = class {
8571
- constructor(status, statusText, data2, internal = false) {
8572
- this.status = status;
8573
- this.statusText = statusText || "";
8574
- this.internal = internal;
8575
- if (data2 instanceof Error) {
8576
- this.data = data2.toString();
8577
- this.error = data2;
8578
- } else {
8579
- this.data = data2;
8580
- }
8581
- }
8582
8141
  };
8583
- function isRouteErrorResponse(error) {
8584
- return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
8585
- }
8586
- function getRoutePattern(matches) {
8587
- return matches.map((m) => m.route.path).filter(Boolean).join("/").replace(/\/\/*/g, "/") || "/";
8588
- }
8589
- var isBrowser2 = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
8590
- function parseToInfo(_to, basename) {
8591
- let to = _to;
8592
- if (typeof to !== "string" || !ABSOLUTE_URL_REGEX.test(to)) {
8593
- return {
8594
- absoluteURL: void 0,
8595
- isExternal: false,
8596
- to
8597
- };
8598
- }
8599
- let absoluteURL = to;
8600
- let isExternal = false;
8601
- if (isBrowser2) {
8142
+ var useApp_default = useApp;
8143
+
8144
+ // src/utils/Enums.ts
8145
+ var Enums = {
8146
+ roles: ["admin", "staff"],
8147
+ sex: ["male", "female"],
8148
+ accountTypes: ["employee", "supplier", "customer", "investor"],
8149
+ verificationTypes: ["email_verification", "password_reset"],
8150
+ auditActions: ["create", "update", "delete", "login", "logout"]
8151
+ };
8152
+ var Enums_default = Enums;
8153
+
8154
+ // src/components/accounts/schema.tsx
8155
+ var import_zod2 = require("zod");
8156
+ var createAccountSchema = import_zod2.z.object({
8157
+ name: import_zod2.z.string().min(2, { message: "Name must be at least 2 characters" }),
8158
+ email: import_zod2.z.string().optional().refine((val) => !val || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val), {
8159
+ message: "Please enter a valid email address"
8160
+ }).transform((val) => val?.toLowerCase()),
8161
+ phoneNumber: import_zod2.z.string().optional(),
8162
+ sex: import_zod2.z.enum(Enums_default.sex)
8163
+ });
8164
+
8165
+ // src/components/accounts/AccountForm.tsx
8166
+ var import_react_hook_form8 = require("react-hook-form");
8167
+ var import_zod3 = require("@hookform/resolvers/zod");
8168
+ var import_antd7 = require("antd");
8169
+ var import_react34 = require("react");
8170
+ var import_jsx_runtime43 = require("react/jsx-runtime");
8171
+ function AccountForm() {
8172
+ const { getQuery, getParams, navigate } = useApp_default();
8173
+ const id = getQuery("id");
8174
+ const type = getParams("type");
8175
+ const isEdit = !!id;
8176
+ const { post, put, isLoading } = useApis_default();
8177
+ const { isLoading: isLoadingGet, get } = useApis_default();
8178
+ const methods = (0, import_react_hook_form8.useForm)({
8179
+ resolver: (0, import_zod3.zodResolver)(createAccountSchema),
8180
+ defaultValues: {
8181
+ name: "",
8182
+ email: "",
8183
+ phoneNumber: "",
8184
+ sex: "male"
8185
+ },
8186
+ shouldUnregister: false
8187
+ });
8188
+ const { handleSubmit } = methods;
8189
+ const onSubmit = async (data) => {
8602
8190
  try {
8603
- let currentUrl = new URL(window.location.href);
8604
- let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
8605
- let path = stripBasename(targetUrl.pathname, basename);
8606
- if (targetUrl.origin === currentUrl.origin && path != null) {
8607
- to = path + targetUrl.search + targetUrl.hash;
8191
+ const payload = {
8192
+ ...data,
8193
+ type
8194
+ };
8195
+ if (isEdit) {
8196
+ await put({
8197
+ url: `/accounts/update/${id}`,
8198
+ body: payload
8199
+ });
8608
8200
  } else {
8609
- isExternal = true;
8201
+ await post({
8202
+ url: "/accounts/create",
8203
+ body: payload
8204
+ });
8610
8205
  }
8611
- } catch (e) {
8612
- warning3(
8613
- false,
8614
- `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`
8615
- );
8206
+ import_antd7.message.success(`${type} ${isEdit ? "updated" : "created"} successfully`);
8207
+ navigate(-1);
8208
+ } catch (error) {
8209
+ import_antd7.message.error(error?.message || "Something went wrong");
8616
8210
  }
8617
- }
8618
- return {
8619
- absoluteURL,
8620
- isExternal,
8621
- to
8622
8211
  };
8623
- }
8624
- var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
8625
- var validMutationMethodsArr = [
8626
- "POST",
8627
- "PUT",
8628
- "PATCH",
8629
- "DELETE"
8630
- ];
8631
- var validMutationMethods = new Set(
8632
- validMutationMethodsArr
8633
- );
8634
- var validRequestMethodsArr = [
8635
- "GET",
8636
- ...validMutationMethodsArr
8637
- ];
8638
- var validRequestMethods = new Set(validRequestMethodsArr);
8639
- var DataRouterContext = React24.createContext(null);
8640
- DataRouterContext.displayName = "DataRouter";
8641
- var DataRouterStateContext = React24.createContext(null);
8642
- DataRouterStateContext.displayName = "DataRouterState";
8643
- var RSCRouterContext = React24.createContext(false);
8644
- var ViewTransitionContext = React24.createContext({
8645
- isTransitioning: false
8646
- });
8647
- ViewTransitionContext.displayName = "ViewTransition";
8648
- var FetchersContext = React24.createContext(
8649
- /* @__PURE__ */ new Map()
8650
- );
8651
- FetchersContext.displayName = "Fetchers";
8652
- var AwaitContext = React24.createContext(null);
8653
- AwaitContext.displayName = "Await";
8654
- var NavigationContext = React24.createContext(
8655
- null
8656
- );
8657
- NavigationContext.displayName = "Navigation";
8658
- var LocationContext = React24.createContext(
8659
- null
8660
- );
8661
- LocationContext.displayName = "Location";
8662
- var RouteContext = React24.createContext({
8663
- outlet: null,
8664
- matches: [],
8665
- isDataRoute: false
8666
- });
8667
- RouteContext.displayName = "Route";
8668
- var RouteErrorContext = React24.createContext(null);
8669
- RouteErrorContext.displayName = "RouteError";
8670
- var ENABLE_DEV_WARNINGS = true;
8671
- var ERROR_DIGEST_BASE = "REACT_ROUTER_ERROR";
8672
- var ERROR_DIGEST_REDIRECT = "REDIRECT";
8673
- var ERROR_DIGEST_ROUTE_ERROR_RESPONSE = "ROUTE_ERROR_RESPONSE";
8674
- function decodeRedirectErrorDigest(digest) {
8675
- if (digest.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`)) {
8212
+ const fetches = async () => {
8676
8213
  try {
8677
- let parsed = JSON.parse(digest.slice(28));
8678
- if (typeof parsed === "object" && parsed && typeof parsed.status === "number" && typeof parsed.statusText === "string" && typeof parsed.location === "string" && typeof parsed.reloadDocument === "boolean" && typeof parsed.replace === "boolean") {
8679
- return parsed;
8680
- }
8681
- } catch {
8214
+ const res = await get({
8215
+ url: `/accounts/get/${type}?id=${id}`
8216
+ });
8217
+ const data = res.data;
8218
+ methods.reset(data);
8219
+ } catch (error) {
8220
+ import_antd7.message.error(error?.message || "Something went wrong");
8682
8221
  }
8683
- }
8684
- }
8685
- function decodeRouteErrorResponseDigest(digest) {
8686
- if (digest.startsWith(
8687
- `${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`
8688
- )) {
8689
- try {
8690
- let parsed = JSON.parse(digest.slice(40));
8691
- if (typeof parsed === "object" && parsed && typeof parsed.status === "number" && typeof parsed.statusText === "string") {
8692
- return new ErrorResponseImpl(
8693
- parsed.status,
8694
- parsed.statusText,
8695
- parsed.data
8696
- );
8697
- }
8698
- } catch {
8699
- }
8700
- }
8701
- }
8702
- function useHref(to, { relative } = {}) {
8703
- invariant(
8704
- useInRouterContext(),
8705
- // TODO: This error is probably because they somehow have 2 versions of the
8706
- // router loaded. We can help them understand how to avoid that.
8707
- `useHref() may be used only in the context of a <Router> component.`
8708
- );
8709
- let { basename, navigator: navigator2 } = React25.useContext(NavigationContext);
8710
- let { hash, pathname, search } = useResolvedPath(to, { relative });
8711
- let joinedPathname = pathname;
8712
- if (basename !== "/") {
8713
- joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
8714
- }
8715
- return navigator2.createHref({ pathname: joinedPathname, search, hash });
8716
- }
8717
- function useInRouterContext() {
8718
- return React25.useContext(LocationContext) != null;
8719
- }
8720
- function useLocation3() {
8721
- invariant(
8722
- useInRouterContext(),
8723
- // TODO: This error is probably because they somehow have 2 versions of the
8724
- // router loaded. We can help them understand how to avoid that.
8725
- `useLocation() may be used only in the context of a <Router> component.`
8726
- );
8727
- return React25.useContext(LocationContext).location;
8728
- }
8729
- var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
8730
- function useIsomorphicLayoutEffect(cb) {
8731
- let isStatic = React25.useContext(NavigationContext).static;
8732
- if (!isStatic) {
8733
- React25.useLayoutEffect(cb);
8734
- }
8735
- }
8736
- function useNavigate5() {
8737
- let { isDataRoute } = React25.useContext(RouteContext);
8738
- return isDataRoute ? useNavigateStable() : useNavigateUnstable();
8739
- }
8740
- function useNavigateUnstable() {
8741
- invariant(
8742
- useInRouterContext(),
8743
- // TODO: This error is probably because they somehow have 2 versions of the
8744
- // router loaded. We can help them understand how to avoid that.
8745
- `useNavigate() may be used only in the context of a <Router> component.`
8746
- );
8747
- let dataRouterContext = React25.useContext(DataRouterContext);
8748
- let { basename, navigator: navigator2 } = React25.useContext(NavigationContext);
8749
- let { matches } = React25.useContext(RouteContext);
8750
- let { pathname: locationPathname } = useLocation3();
8751
- let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
8752
- let activeRef = React25.useRef(false);
8753
- useIsomorphicLayoutEffect(() => {
8754
- activeRef.current = true;
8755
- });
8756
- let navigate = React25.useCallback(
8757
- (to, options = {}) => {
8758
- warning3(activeRef.current, navigateEffectWarning);
8759
- if (!activeRef.current) return;
8760
- if (typeof to === "number") {
8761
- navigator2.go(to);
8762
- return;
8763
- }
8764
- let path = resolveTo(
8765
- to,
8766
- JSON.parse(routePathnamesJson),
8767
- locationPathname,
8768
- options.relative === "path"
8769
- );
8770
- if (dataRouterContext == null && basename !== "/") {
8771
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
8772
- }
8773
- (!!options.replace ? navigator2.replace : navigator2.push)(
8774
- path,
8775
- options.state,
8776
- options
8777
- );
8778
- },
8779
- [
8780
- basename,
8781
- navigator2,
8782
- routePathnamesJson,
8783
- locationPathname,
8784
- dataRouterContext
8785
- ]
8786
- );
8787
- return navigate;
8788
- }
8789
- var OutletContext = React25.createContext(null);
8790
- function useParams2() {
8791
- let { matches } = React25.useContext(RouteContext);
8792
- let routeMatch = matches[matches.length - 1];
8793
- return routeMatch ? routeMatch.params : {};
8794
- }
8795
- function useResolvedPath(to, { relative } = {}) {
8796
- let { matches } = React25.useContext(RouteContext);
8797
- let { pathname: locationPathname } = useLocation3();
8798
- let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
8799
- return React25.useMemo(
8800
- () => resolveTo(
8801
- to,
8802
- JSON.parse(routePathnamesJson),
8803
- locationPathname,
8804
- relative === "path"
8805
- ),
8806
- [to, routePathnamesJson, locationPathname, relative]
8807
- );
8808
- }
8809
- function useRoutesImpl(routes, locationArg, dataRouterOpts) {
8810
- invariant(
8811
- useInRouterContext(),
8812
- // TODO: This error is probably because they somehow have 2 versions of the
8813
- // router loaded. We can help them understand how to avoid that.
8814
- `useRoutes() may be used only in the context of a <Router> component.`
8815
- );
8816
- let { navigator: navigator2 } = React25.useContext(NavigationContext);
8817
- let { matches: parentMatches } = React25.useContext(RouteContext);
8818
- let routeMatch = parentMatches[parentMatches.length - 1];
8819
- let parentParams = routeMatch ? routeMatch.params : {};
8820
- let parentPathname = routeMatch ? routeMatch.pathname : "/";
8821
- let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
8822
- let parentRoute = routeMatch && routeMatch.route;
8823
- if (ENABLE_DEV_WARNINGS) {
8824
- let parentPath = parentRoute && parentRoute.path || "";
8825
- warningOnce2(
8826
- parentPathname,
8827
- !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"),
8828
- `You rendered descendant <Routes> (or called \`useRoutes()\`) at "${parentPathname}" (under <Route path="${parentPath}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
8829
-
8830
- Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
8831
- );
8832
- }
8833
- let locationFromContext = useLocation3();
8834
- let location;
8835
- if (locationArg) {
8836
- let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
8837
- invariant(
8838
- parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase),
8839
- `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${parentPathnameBase}" but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`
8840
- );
8841
- location = parsedLocationArg;
8842
- } else {
8843
- location = locationFromContext;
8844
- }
8845
- let pathname = location.pathname || "/";
8846
- let remainingPathname = pathname;
8847
- if (parentPathnameBase !== "/") {
8848
- let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
8849
- let segments = pathname.replace(/^\//, "").split("/");
8850
- remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
8851
- }
8852
- let matches = matchRoutes(routes, { pathname: remainingPathname });
8853
- if (ENABLE_DEV_WARNINGS) {
8854
- warning3(
8855
- parentRoute || matches != null,
8856
- `No routes matched location "${location.pathname}${location.search}${location.hash}" `
8857
- );
8858
- warning3(
8859
- matches == null || matches[matches.length - 1].route.element !== void 0 || matches[matches.length - 1].route.Component !== void 0 || matches[matches.length - 1].route.lazy !== void 0,
8860
- `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`
8861
- );
8862
- }
8863
- let renderedMatches = _renderMatches(
8864
- matches && matches.map(
8865
- (match) => Object.assign({}, match, {
8866
- params: Object.assign({}, parentParams, match.params),
8867
- pathname: joinPaths([
8868
- parentPathnameBase,
8869
- // Re-encode pathnames that were decoded inside matchRoutes.
8870
- // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
8871
- // `new URL()` internally and we need to prevent it from treating
8872
- // them as separators
8873
- navigator2.encodeLocation ? navigator2.encodeLocation(
8874
- match.pathname.replace(/\?/g, "%3F").replace(/#/g, "%23")
8875
- ).pathname : match.pathname
8876
- ]),
8877
- pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
8878
- parentPathnameBase,
8879
- // Re-encode pathnames that were decoded inside matchRoutes
8880
- // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
8881
- // `new URL()` internally and we need to prevent it from treating
8882
- // them as separators
8883
- navigator2.encodeLocation ? navigator2.encodeLocation(
8884
- match.pathnameBase.replace(/\?/g, "%3F").replace(/#/g, "%23")
8885
- ).pathname : match.pathnameBase
8886
- ])
8887
- })
8888
- ),
8889
- parentMatches,
8890
- dataRouterOpts
8891
- );
8892
- if (locationArg && renderedMatches) {
8893
- return /* @__PURE__ */ React25.createElement(
8894
- LocationContext.Provider,
8895
- {
8896
- value: {
8897
- location: {
8898
- pathname: "/",
8899
- search: "",
8900
- hash: "",
8901
- state: null,
8902
- key: "default",
8903
- unstable_mask: void 0,
8904
- ...location
8905
- },
8906
- navigationType: "POP"
8907
- /* Pop */
8908
- }
8909
- },
8910
- renderedMatches
8911
- );
8912
- }
8913
- return renderedMatches;
8914
- }
8915
- function DefaultErrorComponent() {
8916
- let error = useRouteError();
8917
- let message13 = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
8918
- let stack = error instanceof Error ? error.stack : null;
8919
- let lightgrey = "rgba(200,200,200, 0.5)";
8920
- let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
8921
- let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
8922
- let devInfo = null;
8923
- if (ENABLE_DEV_WARNINGS) {
8924
- console.error(
8925
- "Error handled by React Router default ErrorBoundary:",
8926
- error
8927
- );
8928
- devInfo = /* @__PURE__ */ React25.createElement(React25.Fragment, null, /* @__PURE__ */ React25.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */ React25.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ React25.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ React25.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
8929
- }
8930
- return /* @__PURE__ */ React25.createElement(React25.Fragment, null, /* @__PURE__ */ React25.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ React25.createElement("h3", { style: { fontStyle: "italic" } }, message13), stack ? /* @__PURE__ */ React25.createElement("pre", { style: preStyles }, stack) : null, devInfo);
8931
- }
8932
- var defaultErrorElement = /* @__PURE__ */ React25.createElement(DefaultErrorComponent, null);
8933
- var RenderErrorBoundary = class extends React25.Component {
8934
- constructor(props) {
8935
- super(props);
8936
- this.state = {
8937
- location: props.location,
8938
- revalidation: props.revalidation,
8939
- error: props.error
8940
- };
8941
- }
8942
- static getDerivedStateFromError(error) {
8943
- return { error };
8944
- }
8945
- static getDerivedStateFromProps(props, state) {
8946
- if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
8947
- return {
8948
- error: props.error,
8949
- location: props.location,
8950
- revalidation: props.revalidation
8951
- };
8952
- }
8953
- return {
8954
- error: props.error !== void 0 ? props.error : state.error,
8955
- location: state.location,
8956
- revalidation: props.revalidation || state.revalidation
8957
- };
8958
- }
8959
- componentDidCatch(error, errorInfo) {
8960
- if (this.props.onError) {
8961
- this.props.onError(error, errorInfo);
8962
- } else {
8963
- console.error(
8964
- "React Router caught the following error during render",
8965
- error
8966
- );
8967
- }
8968
- }
8969
- render() {
8970
- let error = this.state.error;
8971
- if (this.context && typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
8972
- const decoded = decodeRouteErrorResponseDigest(error.digest);
8973
- if (decoded) error = decoded;
8974
- }
8975
- let result = error !== void 0 ? /* @__PURE__ */ React25.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React25.createElement(
8976
- RouteErrorContext.Provider,
8977
- {
8978
- value: error,
8979
- children: this.props.component
8980
- }
8981
- )) : this.props.children;
8982
- if (this.context) {
8983
- return /* @__PURE__ */ React25.createElement(RSCErrorHandler, { error }, result);
8984
- }
8985
- return result;
8986
- }
8987
- };
8988
- RenderErrorBoundary.contextType = RSCRouterContext;
8989
- var errorRedirectHandledMap = /* @__PURE__ */ new WeakMap();
8990
- function RSCErrorHandler({
8991
- children,
8992
- error
8993
- }) {
8994
- let { basename } = React25.useContext(NavigationContext);
8995
- if (typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
8996
- let redirect2 = decodeRedirectErrorDigest(error.digest);
8997
- if (redirect2) {
8998
- let existingRedirect = errorRedirectHandledMap.get(error);
8999
- if (existingRedirect) throw existingRedirect;
9000
- let parsed = parseToInfo(redirect2.location, basename);
9001
- if (isBrowser2 && !errorRedirectHandledMap.get(error)) {
9002
- if (parsed.isExternal || redirect2.reloadDocument) {
9003
- window.location.href = parsed.absoluteURL || parsed.to;
9004
- } else {
9005
- const redirectPromise = Promise.resolve().then(
9006
- () => window.__reactRouterDataRouter.navigate(parsed.to, {
9007
- replace: redirect2.replace
9008
- })
9009
- );
9010
- errorRedirectHandledMap.set(error, redirectPromise);
9011
- throw redirectPromise;
9012
- }
9013
- }
9014
- return /* @__PURE__ */ React25.createElement(
9015
- "meta",
9016
- {
9017
- httpEquiv: "refresh",
9018
- content: `0;url=${parsed.absoluteURL || parsed.to}`
9019
- }
9020
- );
9021
- }
9022
- }
9023
- return children;
9024
- }
9025
- function RenderedRoute({ routeContext, match, children }) {
9026
- let dataRouterContext = React25.useContext(DataRouterContext);
9027
- if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
9028
- dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
9029
- }
9030
- return /* @__PURE__ */ React25.createElement(RouteContext.Provider, { value: routeContext }, children);
9031
- }
9032
- function _renderMatches(matches, parentMatches = [], dataRouterOpts) {
9033
- let dataRouterState = dataRouterOpts?.state;
9034
- if (matches == null) {
9035
- if (!dataRouterState) {
9036
- return null;
9037
- }
9038
- if (dataRouterState.errors) {
9039
- matches = dataRouterState.matches;
9040
- } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
9041
- matches = dataRouterState.matches;
9042
- } else {
9043
- return null;
9044
- }
9045
- }
9046
- let renderedMatches = matches;
9047
- let errors = dataRouterState?.errors;
9048
- if (errors != null) {
9049
- let errorIndex = renderedMatches.findIndex(
9050
- (m) => m.route.id && errors?.[m.route.id] !== void 0
9051
- );
9052
- invariant(
9053
- errorIndex >= 0,
9054
- `Could not find a matching route for errors on route IDs: ${Object.keys(
9055
- errors
9056
- ).join(",")}`
9057
- );
9058
- renderedMatches = renderedMatches.slice(
9059
- 0,
9060
- Math.min(renderedMatches.length, errorIndex + 1)
9061
- );
9062
- }
9063
- let renderFallback = false;
9064
- let fallbackIndex = -1;
9065
- if (dataRouterOpts && dataRouterState) {
9066
- renderFallback = dataRouterState.renderFallback;
9067
- for (let i = 0; i < renderedMatches.length; i++) {
9068
- let match = renderedMatches[i];
9069
- if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
9070
- fallbackIndex = i;
9071
- }
9072
- if (match.route.id) {
9073
- let { loaderData, errors: errors2 } = dataRouterState;
9074
- let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0);
9075
- if (match.route.lazy || needsToRunLoader) {
9076
- if (dataRouterOpts.isStatic) {
9077
- renderFallback = true;
9078
- }
9079
- if (fallbackIndex >= 0) {
9080
- renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
9081
- } else {
9082
- renderedMatches = [renderedMatches[0]];
9083
- }
9084
- break;
9085
- }
9086
- }
9087
- }
9088
- }
9089
- let onErrorHandler = dataRouterOpts?.onError;
9090
- let onError = dataRouterState && onErrorHandler ? (error, errorInfo) => {
9091
- onErrorHandler(error, {
9092
- location: dataRouterState.location,
9093
- params: dataRouterState.matches?.[0]?.params ?? {},
9094
- unstable_pattern: getRoutePattern(dataRouterState.matches),
9095
- errorInfo
9096
- });
9097
- } : void 0;
9098
- return renderedMatches.reduceRight(
9099
- (outlet, match, index) => {
9100
- let error;
9101
- let shouldRenderHydrateFallback = false;
9102
- let errorElement = null;
9103
- let hydrateFallbackElement = null;
9104
- if (dataRouterState) {
9105
- error = errors && match.route.id ? errors[match.route.id] : void 0;
9106
- errorElement = match.route.errorElement || defaultErrorElement;
9107
- if (renderFallback) {
9108
- if (fallbackIndex < 0 && index === 0) {
9109
- warningOnce2(
9110
- "route-fallback",
9111
- false,
9112
- "No `HydrateFallback` element provided to render during initial hydration"
9113
- );
9114
- shouldRenderHydrateFallback = true;
9115
- hydrateFallbackElement = null;
9116
- } else if (fallbackIndex === index) {
9117
- shouldRenderHydrateFallback = true;
9118
- hydrateFallbackElement = match.route.hydrateFallbackElement || null;
9119
- }
9120
- }
9121
- }
9122
- let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
9123
- let getChildren = () => {
9124
- let children;
9125
- if (error) {
9126
- children = errorElement;
9127
- } else if (shouldRenderHydrateFallback) {
9128
- children = hydrateFallbackElement;
9129
- } else if (match.route.Component) {
9130
- children = /* @__PURE__ */ React25.createElement(match.route.Component, null);
9131
- } else if (match.route.element) {
9132
- children = match.route.element;
9133
- } else {
9134
- children = outlet;
9135
- }
9136
- return /* @__PURE__ */ React25.createElement(
9137
- RenderedRoute,
9138
- {
9139
- match,
9140
- routeContext: {
9141
- outlet,
9142
- matches: matches2,
9143
- isDataRoute: dataRouterState != null
9144
- },
9145
- children
9146
- }
9147
- );
9148
- };
9149
- return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React25.createElement(
9150
- RenderErrorBoundary,
9151
- {
9152
- location: dataRouterState.location,
9153
- revalidation: dataRouterState.revalidation,
9154
- component: errorElement,
9155
- error,
9156
- children: getChildren(),
9157
- routeContext: { outlet: null, matches: matches2, isDataRoute: true },
9158
- onError
9159
- }
9160
- ) : getChildren();
9161
- },
9162
- null
9163
- );
9164
- }
9165
- function getDataRouterConsoleError(hookName) {
9166
- return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
9167
- }
9168
- function useDataRouterContext(hookName) {
9169
- let ctx = React25.useContext(DataRouterContext);
9170
- invariant(ctx, getDataRouterConsoleError(hookName));
9171
- return ctx;
9172
- }
9173
- function useDataRouterState(hookName) {
9174
- let state = React25.useContext(DataRouterStateContext);
9175
- invariant(state, getDataRouterConsoleError(hookName));
9176
- return state;
9177
- }
9178
- function useRouteContext(hookName) {
9179
- let route = React25.useContext(RouteContext);
9180
- invariant(route, getDataRouterConsoleError(hookName));
9181
- return route;
9182
- }
9183
- function useCurrentRouteId(hookName) {
9184
- let route = useRouteContext(hookName);
9185
- let thisRoute = route.matches[route.matches.length - 1];
9186
- invariant(
9187
- thisRoute.route.id,
9188
- `${hookName} can only be used on routes that contain a unique "id"`
9189
- );
9190
- return thisRoute.route.id;
9191
- }
9192
- function useRouteId() {
9193
- return useCurrentRouteId(
9194
- "useRouteId"
9195
- /* UseRouteId */
9196
- );
9197
- }
9198
- function useNavigation() {
9199
- let state = useDataRouterState(
9200
- "useNavigation"
9201
- /* UseNavigation */
9202
- );
9203
- return state.navigation;
9204
- }
9205
- function useMatches() {
9206
- let { matches, loaderData } = useDataRouterState(
9207
- "useMatches"
9208
- /* UseMatches */
9209
- );
9210
- return React25.useMemo(
9211
- () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),
9212
- [matches, loaderData]
9213
- );
9214
- }
9215
- function useRouteError() {
9216
- let error = React25.useContext(RouteErrorContext);
9217
- let state = useDataRouterState(
9218
- "useRouteError"
9219
- /* UseRouteError */
9220
- );
9221
- let routeId = useCurrentRouteId(
9222
- "useRouteError"
9223
- /* UseRouteError */
9224
- );
9225
- if (error !== void 0) {
9226
- return error;
9227
- }
9228
- return state.errors?.[routeId];
9229
- }
9230
- function useNavigateStable() {
9231
- let { router } = useDataRouterContext(
9232
- "useNavigate"
9233
- /* UseNavigateStable */
9234
- );
9235
- let id = useCurrentRouteId(
9236
- "useNavigate"
9237
- /* UseNavigateStable */
9238
- );
9239
- let activeRef = React25.useRef(false);
9240
- useIsomorphicLayoutEffect(() => {
9241
- activeRef.current = true;
9242
- });
9243
- let navigate = React25.useCallback(
9244
- async (to, options = {}) => {
9245
- warning3(activeRef.current, navigateEffectWarning);
9246
- if (!activeRef.current) return;
9247
- if (typeof to === "number") {
9248
- await router.navigate(to);
9249
- } else {
9250
- await router.navigate(to, { fromRouteId: id, ...options });
9251
- }
9252
- },
9253
- [router, id]
9254
- );
9255
- return navigate;
9256
- }
9257
- var alreadyWarned = {};
9258
- function warningOnce2(key, cond, message13) {
9259
- if (!cond && !alreadyWarned[key]) {
9260
- alreadyWarned[key] = true;
9261
- warning3(false, message13);
9262
- }
9263
- }
9264
- var USE_OPTIMISTIC = "useOptimistic";
9265
- var useOptimisticImpl = React32[USE_OPTIMISTIC];
9266
- var MemoizedDataRoutes = React32.memo(DataRoutes);
9267
- function DataRoutes({
9268
- routes,
9269
- future,
9270
- state,
9271
- isStatic,
9272
- onError
9273
- }) {
9274
- return useRoutesImpl(routes, void 0, { state, isStatic, onError, future });
9275
- }
9276
- function Router({
9277
- basename: basenameProp = "/",
9278
- children = null,
9279
- location: locationProp,
9280
- navigationType = "POP",
9281
- navigator: navigator2,
9282
- static: staticProp = false,
9283
- unstable_useTransitions
9284
- }) {
9285
- invariant(
9286
- !useInRouterContext(),
9287
- `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`
9288
- );
9289
- let basename = basenameProp.replace(/^\/*/, "/");
9290
- let navigationContext = React32.useMemo(
9291
- () => ({
9292
- basename,
9293
- navigator: navigator2,
9294
- static: staticProp,
9295
- unstable_useTransitions,
9296
- future: {}
9297
- }),
9298
- [basename, navigator2, staticProp, unstable_useTransitions]
9299
- );
9300
- if (typeof locationProp === "string") {
9301
- locationProp = parsePath(locationProp);
9302
- }
9303
- let {
9304
- pathname = "/",
9305
- search = "",
9306
- hash = "",
9307
- state = null,
9308
- key = "default",
9309
- unstable_mask
9310
- } = locationProp;
9311
- let locationContext = React32.useMemo(() => {
9312
- let trailingPathname = stripBasename(pathname, basename);
9313
- if (trailingPathname == null) {
9314
- return null;
9315
- }
9316
- return {
9317
- location: {
9318
- pathname: trailingPathname,
9319
- search,
9320
- hash,
9321
- state,
9322
- key,
9323
- unstable_mask
9324
- },
9325
- navigationType
9326
- };
9327
- }, [
9328
- basename,
9329
- pathname,
9330
- search,
9331
- hash,
9332
- state,
9333
- key,
9334
- navigationType,
9335
- unstable_mask
9336
- ]);
9337
- warning3(
9338
- locationContext != null,
9339
- `<Router basename="${basename}"> is not able to match the URL "${pathname}${search}${hash}" because it does not start with the basename, so the <Router> won't render anything.`
9340
- );
9341
- if (locationContext == null) {
9342
- return null;
9343
- }
9344
- return /* @__PURE__ */ React32.createElement(NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ React32.createElement(LocationContext.Provider, { children, value: locationContext }));
9345
- }
9346
- var defaultMethod = "get";
9347
- var defaultEncType = "application/x-www-form-urlencoded";
9348
- function isHtmlElement(object3) {
9349
- return typeof HTMLElement !== "undefined" && object3 instanceof HTMLElement;
9350
- }
9351
- function isButtonElement(object3) {
9352
- return isHtmlElement(object3) && object3.tagName.toLowerCase() === "button";
9353
- }
9354
- function isFormElement(object3) {
9355
- return isHtmlElement(object3) && object3.tagName.toLowerCase() === "form";
9356
- }
9357
- function isInputElement(object3) {
9358
- return isHtmlElement(object3) && object3.tagName.toLowerCase() === "input";
9359
- }
9360
- function isModifiedEvent(event) {
9361
- return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
9362
- }
9363
- function shouldProcessLinkClick(event, target) {
9364
- return event.button === 0 && // Ignore everything but left clicks
9365
- (!target || target === "_self") && // Let browser handle "target=_blank" etc.
9366
- !isModifiedEvent(event);
9367
- }
9368
- function createSearchParams(init = "") {
9369
- return new URLSearchParams(
9370
- typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo2, key) => {
9371
- let value = init[key];
9372
- return memo2.concat(
9373
- Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]
9374
- );
9375
- }, [])
9376
- );
9377
- }
9378
- function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
9379
- let searchParams = createSearchParams(locationSearch);
9380
- if (defaultSearchParams) {
9381
- defaultSearchParams.forEach((_, key) => {
9382
- if (!searchParams.has(key)) {
9383
- defaultSearchParams.getAll(key).forEach((value) => {
9384
- searchParams.append(key, value);
9385
- });
9386
- }
9387
- });
9388
- }
9389
- return searchParams;
9390
- }
9391
- var _formDataSupportsSubmitter = null;
9392
- function isFormDataSubmitterSupported() {
9393
- if (_formDataSupportsSubmitter === null) {
9394
- try {
9395
- new FormData(
9396
- document.createElement("form"),
9397
- // @ts-expect-error if FormData supports the submitter parameter, this will throw
9398
- 0
9399
- );
9400
- _formDataSupportsSubmitter = false;
9401
- } catch (e) {
9402
- _formDataSupportsSubmitter = true;
9403
- }
9404
- }
9405
- return _formDataSupportsSubmitter;
9406
- }
9407
- var supportedFormEncTypes = /* @__PURE__ */ new Set([
9408
- "application/x-www-form-urlencoded",
9409
- "multipart/form-data",
9410
- "text/plain"
9411
- ]);
9412
- function getFormEncType(encType) {
9413
- if (encType != null && !supportedFormEncTypes.has(encType)) {
9414
- warning3(
9415
- false,
9416
- `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`
9417
- );
9418
- return null;
9419
- }
9420
- return encType;
9421
- }
9422
- function getFormSubmissionInfo(target, basename) {
9423
- let method;
9424
- let action;
9425
- let encType;
9426
- let formData;
9427
- let body;
9428
- if (isFormElement(target)) {
9429
- let attr = target.getAttribute("action");
9430
- action = attr ? stripBasename(attr, basename) : null;
9431
- method = target.getAttribute("method") || defaultMethod;
9432
- encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
9433
- formData = new FormData(target);
9434
- } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
9435
- let form = target.form;
9436
- if (form == null) {
9437
- throw new Error(
9438
- `Cannot submit a <button> or <input type="submit"> without a <form>`
9439
- );
9440
- }
9441
- let attr = target.getAttribute("formaction") || form.getAttribute("action");
9442
- action = attr ? stripBasename(attr, basename) : null;
9443
- method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
9444
- encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
9445
- formData = new FormData(form, target);
9446
- if (!isFormDataSubmitterSupported()) {
9447
- let { name, type, value } = target;
9448
- if (type === "image") {
9449
- let prefix = name ? `${name}.` : "";
9450
- formData.append(`${prefix}x`, "0");
9451
- formData.append(`${prefix}y`, "0");
9452
- } else if (name) {
9453
- formData.append(name, value);
9454
- }
9455
- }
9456
- } else if (isHtmlElement(target)) {
9457
- throw new Error(
9458
- `Cannot submit element that is not <form>, <button>, or <input type="submit|image">`
9459
- );
9460
- } else {
9461
- method = defaultMethod;
9462
- action = null;
9463
- encType = defaultEncType;
9464
- body = target;
9465
- }
9466
- if (formData && encType === "text/plain") {
9467
- body = formData;
9468
- formData = void 0;
9469
- }
9470
- return { action, method: method.toLowerCase(), encType, formData, body };
9471
- }
9472
- var objectProtoNames2 = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
9473
- var ESCAPE_LOOKUP = {
9474
- "&": "\\u0026",
9475
- ">": "\\u003e",
9476
- "<": "\\u003c",
9477
- "\u2028": "\\u2028",
9478
- "\u2029": "\\u2029"
9479
- };
9480
- var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
9481
- function escapeHtml(html) {
9482
- return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
9483
- }
9484
- function invariant2(value, message13) {
9485
- if (value === false || value === null || typeof value === "undefined") {
9486
- throw new Error(message13);
9487
- }
9488
- }
9489
- function singleFetchUrl(reqUrl, basename, trailingSlashAware, extension) {
9490
- let url = typeof reqUrl === "string" ? new URL(
9491
- reqUrl,
9492
- // This can be called during the SSR flow via PrefetchPageLinksImpl so
9493
- // don't assume window is available
9494
- typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
9495
- ) : reqUrl;
9496
- if (trailingSlashAware) {
9497
- if (url.pathname.endsWith("/")) {
9498
- url.pathname = `${url.pathname}_.${extension}`;
9499
- } else {
9500
- url.pathname = `${url.pathname}.${extension}`;
9501
- }
9502
- } else {
9503
- if (url.pathname === "/") {
9504
- url.pathname = `_root.${extension}`;
9505
- } else if (basename && stripBasename(url.pathname, basename) === "/") {
9506
- url.pathname = `${basename.replace(/\/$/, "")}/_root.${extension}`;
9507
- } else {
9508
- url.pathname = `${url.pathname.replace(/\/$/, "")}.${extension}`;
9509
- }
9510
- }
9511
- return url;
9512
- }
9513
- async function loadRouteModule(route, routeModulesCache) {
9514
- if (route.id in routeModulesCache) {
9515
- return routeModulesCache[route.id];
9516
- }
9517
- try {
9518
- let routeModule = await import(
9519
- /* @vite-ignore */
9520
- /* webpackIgnore: true */
9521
- route.module
9522
- );
9523
- routeModulesCache[route.id] = routeModule;
9524
- return routeModule;
9525
- } catch (error) {
9526
- console.error(
9527
- `Error loading route module \`${route.module}\`, reloading page...`
9528
- );
9529
- console.error(error);
9530
- if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
9531
- import_meta.hot) {
9532
- throw error;
9533
- }
9534
- window.location.reload();
9535
- return new Promise(() => {
9536
- });
9537
- }
9538
- }
9539
- function isPageLinkDescriptor(object3) {
9540
- return object3 != null && typeof object3.page === "string";
9541
- }
9542
- function isHtmlLinkDescriptor(object3) {
9543
- if (object3 == null) {
9544
- return false;
9545
- }
9546
- if (object3.href == null) {
9547
- return object3.rel === "preload" && typeof object3.imageSrcSet === "string" && typeof object3.imageSizes === "string";
9548
- }
9549
- return typeof object3.rel === "string" && typeof object3.href === "string";
9550
- }
9551
- async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
9552
- let links = await Promise.all(
9553
- matches.map(async (match) => {
9554
- let route = manifest.routes[match.route.id];
9555
- if (route) {
9556
- let mod = await loadRouteModule(route, routeModules);
9557
- return mod.links ? mod.links() : [];
9558
- }
9559
- return [];
9560
- })
9561
- );
9562
- return dedupeLinkDescriptors(
9563
- links.flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map(
9564
- (link) => link.rel === "stylesheet" ? { ...link, rel: "prefetch", as: "style" } : { ...link, rel: "prefetch" }
9565
- )
9566
- );
9567
- }
9568
- function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, mode) {
9569
- let isNew = (match, index) => {
9570
- if (!currentMatches[index]) return true;
9571
- return match.route.id !== currentMatches[index].route.id;
9572
- };
9573
- let matchPathChanged = (match, index) => {
9574
- return (
9575
- // param change, /users/123 -> /users/456
9576
- currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path
9577
- // e.g. /files/images/avatar.jpg -> files/finances.xls
9578
- currentMatches[index].route.path?.endsWith("*") && currentMatches[index].params["*"] !== match.params["*"]
9579
- );
9580
- };
9581
- if (mode === "assets") {
9582
- return nextMatches.filter(
9583
- (match, index) => isNew(match, index) || matchPathChanged(match, index)
9584
- );
9585
- }
9586
- if (mode === "data") {
9587
- return nextMatches.filter((match, index) => {
9588
- let manifestRoute = manifest.routes[match.route.id];
9589
- if (!manifestRoute || !manifestRoute.hasLoader) {
9590
- return false;
9591
- }
9592
- if (isNew(match, index) || matchPathChanged(match, index)) {
9593
- return true;
9594
- }
9595
- if (match.route.shouldRevalidate) {
9596
- let routeChoice = match.route.shouldRevalidate({
9597
- currentUrl: new URL(
9598
- location.pathname + location.search + location.hash,
9599
- window.origin
9600
- ),
9601
- currentParams: currentMatches[0]?.params || {},
9602
- nextUrl: new URL(page, window.origin),
9603
- nextParams: match.params,
9604
- defaultShouldRevalidate: true
9605
- });
9606
- if (typeof routeChoice === "boolean") {
9607
- return routeChoice;
9608
- }
9609
- }
9610
- return true;
9611
- });
9612
- }
9613
- return [];
9614
- }
9615
- function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
9616
- return dedupeHrefs(
9617
- matches.map((match) => {
9618
- let route = manifest.routes[match.route.id];
9619
- if (!route) return [];
9620
- let hrefs = [route.module];
9621
- if (route.clientActionModule) {
9622
- hrefs = hrefs.concat(route.clientActionModule);
9623
- }
9624
- if (route.clientLoaderModule) {
9625
- hrefs = hrefs.concat(route.clientLoaderModule);
9626
- }
9627
- if (includeHydrateFallback && route.hydrateFallbackModule) {
9628
- hrefs = hrefs.concat(route.hydrateFallbackModule);
9629
- }
9630
- if (route.imports) {
9631
- hrefs = hrefs.concat(route.imports);
9632
- }
9633
- return hrefs;
9634
- }).flat(1)
9635
- );
9636
- }
9637
- function dedupeHrefs(hrefs) {
9638
- return [...new Set(hrefs)];
9639
- }
9640
- function sortKeys(obj) {
9641
- let sorted = {};
9642
- let keys = Object.keys(obj).sort();
9643
- for (let key of keys) {
9644
- sorted[key] = obj[key];
9645
- }
9646
- return sorted;
9647
- }
9648
- function dedupeLinkDescriptors(descriptors, preloads) {
9649
- let set = /* @__PURE__ */ new Set();
9650
- let preloadsSet = new Set(preloads);
9651
- return descriptors.reduce((deduped, descriptor) => {
9652
- let alreadyModulePreload = preloads && !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href);
9653
- if (alreadyModulePreload) {
9654
- return deduped;
9655
- }
9656
- let key = JSON.stringify(sortKeys(descriptor));
9657
- if (!set.has(key)) {
9658
- set.add(key);
9659
- deduped.push({ key, link: descriptor });
9660
- }
9661
- return deduped;
9662
- }, []);
9663
- }
9664
- function useDataRouterContext2() {
9665
- let context = React82.useContext(DataRouterContext);
9666
- invariant2(
9667
- context,
9668
- "You must render this element inside a <DataRouterContext.Provider> element"
9669
- );
9670
- return context;
9671
- }
9672
- function useDataRouterStateContext() {
9673
- let context = React82.useContext(DataRouterStateContext);
9674
- invariant2(
9675
- context,
9676
- "You must render this element inside a <DataRouterStateContext.Provider> element"
9677
- );
9678
- return context;
9679
- }
9680
- var FrameworkContext = React82.createContext(void 0);
9681
- FrameworkContext.displayName = "FrameworkContext";
9682
- function useFrameworkContext() {
9683
- let context = React82.useContext(FrameworkContext);
9684
- invariant2(
9685
- context,
9686
- "You must render this element inside a <HydratedRouter> element"
9687
- );
9688
- return context;
9689
- }
9690
- function usePrefetchBehavior(prefetch, theirElementProps) {
9691
- let frameworkContext = React82.useContext(FrameworkContext);
9692
- let [maybePrefetch, setMaybePrefetch] = React82.useState(false);
9693
- let [shouldPrefetch, setShouldPrefetch] = React82.useState(false);
9694
- let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
9695
- let ref = React82.useRef(null);
9696
- React82.useEffect(() => {
9697
- if (prefetch === "render") {
9698
- setShouldPrefetch(true);
9699
- }
9700
- if (prefetch === "viewport") {
9701
- let callback = (entries) => {
9702
- entries.forEach((entry) => {
9703
- setShouldPrefetch(entry.isIntersecting);
9704
- });
9705
- };
9706
- let observer = new IntersectionObserver(callback, { threshold: 0.5 });
9707
- if (ref.current) observer.observe(ref.current);
9708
- return () => {
9709
- observer.disconnect();
9710
- };
9711
- }
9712
- }, [prefetch]);
9713
- React82.useEffect(() => {
9714
- if (maybePrefetch) {
9715
- let id = setTimeout(() => {
9716
- setShouldPrefetch(true);
9717
- }, 100);
9718
- return () => {
9719
- clearTimeout(id);
9720
- };
9721
- }
9722
- }, [maybePrefetch]);
9723
- let setIntent = () => {
9724
- setMaybePrefetch(true);
9725
- };
9726
- let cancelIntent = () => {
9727
- setMaybePrefetch(false);
9728
- setShouldPrefetch(false);
9729
- };
9730
- if (!frameworkContext) {
9731
- return [false, ref, {}];
9732
- }
9733
- if (prefetch !== "intent") {
9734
- return [shouldPrefetch, ref, {}];
9735
- }
9736
- return [
9737
- shouldPrefetch,
9738
- ref,
9739
- {
9740
- onFocus: composeEventHandlers(onFocus, setIntent),
9741
- onBlur: composeEventHandlers(onBlur, cancelIntent),
9742
- onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
9743
- onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
9744
- onTouchStart: composeEventHandlers(onTouchStart, setIntent)
9745
- }
9746
- ];
9747
- }
9748
- function composeEventHandlers(theirHandler, ourHandler) {
9749
- return (event) => {
9750
- theirHandler && theirHandler(event);
9751
- if (!event.defaultPrevented) {
9752
- ourHandler(event);
9753
- }
9754
- };
9755
- }
9756
- function PrefetchPageLinks({ page, ...linkProps }) {
9757
- let { router } = useDataRouterContext2();
9758
- let matches = React82.useMemo(
9759
- () => matchRoutes(router.routes, page, router.basename),
9760
- [router.routes, page, router.basename]
9761
- );
9762
- if (!matches) {
9763
- return null;
9764
- }
9765
- return /* @__PURE__ */ React82.createElement(PrefetchPageLinksImpl, { page, matches, ...linkProps });
9766
- }
9767
- function useKeyedPrefetchLinks(matches) {
9768
- let { manifest, routeModules } = useFrameworkContext();
9769
- let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React82.useState([]);
9770
- React82.useEffect(() => {
9771
- let interrupted = false;
9772
- void getKeyedPrefetchLinks(matches, manifest, routeModules).then(
9773
- (links) => {
9774
- if (!interrupted) {
9775
- setKeyedPrefetchLinks(links);
9776
- }
9777
- }
9778
- );
9779
- return () => {
9780
- interrupted = true;
9781
- };
9782
- }, [matches, manifest, routeModules]);
9783
- return keyedPrefetchLinks;
9784
- }
9785
- function PrefetchPageLinksImpl({
9786
- page,
9787
- matches: nextMatches,
9788
- ...linkProps
9789
- }) {
9790
- let location = useLocation3();
9791
- let { future, manifest, routeModules } = useFrameworkContext();
9792
- let { basename } = useDataRouterContext2();
9793
- let { loaderData, matches } = useDataRouterStateContext();
9794
- let newMatchesForData = React82.useMemo(
9795
- () => getNewMatchesForLinks(
9796
- page,
9797
- nextMatches,
9798
- matches,
9799
- manifest,
9800
- location,
9801
- "data"
9802
- ),
9803
- [page, nextMatches, matches, manifest, location]
9804
- );
9805
- let newMatchesForAssets = React82.useMemo(
9806
- () => getNewMatchesForLinks(
9807
- page,
9808
- nextMatches,
9809
- matches,
9810
- manifest,
9811
- location,
9812
- "assets"
9813
- ),
9814
- [page, nextMatches, matches, manifest, location]
9815
- );
9816
- let dataHrefs = React82.useMemo(() => {
9817
- if (page === location.pathname + location.search + location.hash) {
9818
- return [];
9819
- }
9820
- let routesParams = /* @__PURE__ */ new Set();
9821
- let foundOptOutRoute = false;
9822
- nextMatches.forEach((m) => {
9823
- let manifestRoute = manifest.routes[m.route.id];
9824
- if (!manifestRoute || !manifestRoute.hasLoader) {
9825
- return;
9826
- }
9827
- if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && routeModules[m.route.id]?.shouldRevalidate) {
9828
- foundOptOutRoute = true;
9829
- } else if (manifestRoute.hasClientLoader) {
9830
- foundOptOutRoute = true;
9831
- } else {
9832
- routesParams.add(m.route.id);
9833
- }
9834
- });
9835
- if (routesParams.size === 0) {
9836
- return [];
9837
- }
9838
- let url = singleFetchUrl(
9839
- page,
9840
- basename,
9841
- future.unstable_trailingSlashAwareDataRequests,
9842
- "data"
9843
- );
9844
- if (foundOptOutRoute && routesParams.size > 0) {
9845
- url.searchParams.set(
9846
- "_routes",
9847
- nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
9848
- );
9849
- }
9850
- return [url.pathname + url.search];
9851
- }, [
9852
- basename,
9853
- future.unstable_trailingSlashAwareDataRequests,
9854
- loaderData,
9855
- location,
9856
- manifest,
9857
- newMatchesForData,
9858
- nextMatches,
9859
- page,
9860
- routeModules
9861
- ]);
9862
- let moduleHrefs = React82.useMemo(
9863
- () => getModuleLinkHrefs(newMatchesForAssets, manifest),
9864
- [newMatchesForAssets, manifest]
9865
- );
9866
- let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
9867
- return /* @__PURE__ */ React82.createElement(React82.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React82.createElement("link", { key: href, rel: "prefetch", as: "fetch", href, ...linkProps })), moduleHrefs.map((href) => /* @__PURE__ */ React82.createElement("link", { key: href, rel: "modulepreload", href, ...linkProps })), keyedPrefetchLinks.map(({ key, link }) => (
9868
- // these don't spread `linkProps` because they are full link descriptors
9869
- // already with their own props
9870
- /* @__PURE__ */ React82.createElement(
9871
- "link",
9872
- {
9873
- key,
9874
- nonce: linkProps.nonce,
9875
- ...link,
9876
- crossOrigin: link.crossOrigin ?? linkProps.crossOrigin
9877
- }
9878
- )
9879
- )));
9880
- }
9881
- function mergeRefs(...refs) {
9882
- return (value) => {
9883
- refs.forEach((ref) => {
9884
- if (typeof ref === "function") {
9885
- ref(value);
9886
- } else if (ref != null) {
9887
- ref.current = value;
9888
- }
9889
- });
9890
- };
9891
- }
9892
- var isBrowser22 = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
9893
- try {
9894
- if (isBrowser22) {
9895
- window.__reactRouterVersion = // @ts-expect-error
9896
- "7.13.1";
9897
- }
9898
- } catch (e) {
9899
- }
9900
- function HistoryRouter({
9901
- basename,
9902
- children,
9903
- history,
9904
- unstable_useTransitions
9905
- }) {
9906
- let [state, setStateImpl] = React102.useState({
9907
- action: history.action,
9908
- location: history.location
9909
- });
9910
- let setState = React102.useCallback(
9911
- (newState) => {
9912
- if (unstable_useTransitions === false) {
9913
- setStateImpl(newState);
9914
- } else {
9915
- React102.startTransition(() => setStateImpl(newState));
9916
- }
9917
- },
9918
- [unstable_useTransitions]
9919
- );
9920
- React102.useLayoutEffect(() => history.listen(setState), [history, setState]);
9921
- return /* @__PURE__ */ React102.createElement(
9922
- Router,
9923
- {
9924
- basename,
9925
- children,
9926
- location: state.location,
9927
- navigationType: state.action,
9928
- navigator: history,
9929
- unstable_useTransitions
9930
- }
9931
- );
9932
- }
9933
- HistoryRouter.displayName = "unstable_HistoryRouter";
9934
- var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
9935
- var Link = React102.forwardRef(
9936
- function LinkWithRef({
9937
- onClick,
9938
- discover = "render",
9939
- prefetch = "none",
9940
- relative,
9941
- reloadDocument,
9942
- replace: replace2,
9943
- unstable_mask,
9944
- state,
9945
- target,
9946
- to,
9947
- preventScrollReset,
9948
- viewTransition,
9949
- unstable_defaultShouldRevalidate,
9950
- ...rest
9951
- }, forwardedRef) {
9952
- let { basename, navigator: navigator2, unstable_useTransitions } = React102.useContext(NavigationContext);
9953
- let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX2.test(to);
9954
- let parsed = parseToInfo(to, basename);
9955
- to = parsed.to;
9956
- let href = useHref(to, { relative });
9957
- let location = useLocation3();
9958
- let maskedHref = null;
9959
- if (unstable_mask) {
9960
- let resolved = resolveTo(
9961
- unstable_mask,
9962
- [],
9963
- location.unstable_mask ? location.unstable_mask.pathname : "/",
9964
- true
9965
- );
9966
- if (basename !== "/") {
9967
- resolved.pathname = resolved.pathname === "/" ? basename : joinPaths([basename, resolved.pathname]);
9968
- }
9969
- maskedHref = navigator2.createHref(resolved);
9970
- }
9971
- let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(
9972
- prefetch,
9973
- rest
9974
- );
9975
- let internalOnClick = useLinkClickHandler(to, {
9976
- replace: replace2,
9977
- unstable_mask,
9978
- state,
9979
- target,
9980
- preventScrollReset,
9981
- relative,
9982
- viewTransition,
9983
- unstable_defaultShouldRevalidate,
9984
- unstable_useTransitions
9985
- });
9986
- function handleClick(event) {
9987
- if (onClick) onClick(event);
9988
- if (!event.defaultPrevented) {
9989
- internalOnClick(event);
9990
- }
9991
- }
9992
- let isSpaLink = !(parsed.isExternal || reloadDocument);
9993
- let link = (
9994
- // eslint-disable-next-line jsx-a11y/anchor-has-content
9995
- /* @__PURE__ */ React102.createElement(
9996
- "a",
9997
- {
9998
- ...rest,
9999
- ...prefetchHandlers,
10000
- href: (isSpaLink ? maskedHref : void 0) || parsed.absoluteURL || href,
10001
- onClick: isSpaLink ? handleClick : onClick,
10002
- ref: mergeRefs(forwardedRef, prefetchRef),
10003
- target,
10004
- "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
10005
- }
10006
- )
10007
- );
10008
- return shouldPrefetch && !isAbsolute ? /* @__PURE__ */ React102.createElement(React102.Fragment, null, link, /* @__PURE__ */ React102.createElement(PrefetchPageLinks, { page: href })) : link;
10009
- }
10010
- );
10011
- Link.displayName = "Link";
10012
- var NavLink = React102.forwardRef(
10013
- function NavLinkWithRef({
10014
- "aria-current": ariaCurrentProp = "page",
10015
- caseSensitive = false,
10016
- className: classNameProp = "",
10017
- end = false,
10018
- style: styleProp,
10019
- to,
10020
- viewTransition,
10021
- children,
10022
- ...rest
10023
- }, ref) {
10024
- let path = useResolvedPath(to, { relative: rest.relative });
10025
- let location = useLocation3();
10026
- let routerState = React102.useContext(DataRouterStateContext);
10027
- let { navigator: navigator2, basename } = React102.useContext(NavigationContext);
10028
- let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
10029
- // eslint-disable-next-line react-hooks/rules-of-hooks
10030
- useViewTransitionState(path) && viewTransition === true;
10031
- let toPathname = navigator2.encodeLocation ? navigator2.encodeLocation(path).pathname : path.pathname;
10032
- let locationPathname = location.pathname;
10033
- let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
10034
- if (!caseSensitive) {
10035
- locationPathname = locationPathname.toLowerCase();
10036
- nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
10037
- toPathname = toPathname.toLowerCase();
10038
- }
10039
- if (nextLocationPathname && basename) {
10040
- nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
10041
- }
10042
- const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
10043
- let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
10044
- let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
10045
- let renderProps = {
10046
- isActive,
10047
- isPending,
10048
- isTransitioning
10049
- };
10050
- let ariaCurrent = isActive ? ariaCurrentProp : void 0;
10051
- let className;
10052
- if (typeof classNameProp === "function") {
10053
- className = classNameProp(renderProps);
10054
- } else {
10055
- className = [
10056
- classNameProp,
10057
- isActive ? "active" : null,
10058
- isPending ? "pending" : null,
10059
- isTransitioning ? "transitioning" : null
10060
- ].filter(Boolean).join(" ");
10061
- }
10062
- let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
10063
- return /* @__PURE__ */ React102.createElement(
10064
- Link,
10065
- {
10066
- ...rest,
10067
- "aria-current": ariaCurrent,
10068
- className,
10069
- ref,
10070
- style,
10071
- to,
10072
- viewTransition
10073
- },
10074
- typeof children === "function" ? children(renderProps) : children
10075
- );
10076
- }
10077
- );
10078
- NavLink.displayName = "NavLink";
10079
- var Form = React102.forwardRef(
10080
- ({
10081
- discover = "render",
10082
- fetcherKey,
10083
- navigate,
10084
- reloadDocument,
10085
- replace: replace2,
10086
- state,
10087
- method = defaultMethod,
10088
- action,
10089
- onSubmit,
10090
- relative,
10091
- preventScrollReset,
10092
- viewTransition,
10093
- unstable_defaultShouldRevalidate,
10094
- ...props
10095
- }, forwardedRef) => {
10096
- let { unstable_useTransitions } = React102.useContext(NavigationContext);
10097
- let submit = useSubmit();
10098
- let formAction = useFormAction(action, { relative });
10099
- let formMethod = method.toLowerCase() === "get" ? "get" : "post";
10100
- let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX2.test(action);
10101
- let submitHandler = (event) => {
10102
- onSubmit && onSubmit(event);
10103
- if (event.defaultPrevented) return;
10104
- event.preventDefault();
10105
- let submitter = event.nativeEvent.submitter;
10106
- let submitMethod = submitter?.getAttribute("formmethod") || method;
10107
- let doSubmit = () => submit(submitter || event.currentTarget, {
10108
- fetcherKey,
10109
- method: submitMethod,
10110
- navigate,
10111
- replace: replace2,
10112
- state,
10113
- relative,
10114
- preventScrollReset,
10115
- viewTransition,
10116
- unstable_defaultShouldRevalidate
10117
- });
10118
- if (unstable_useTransitions && navigate !== false) {
10119
- React102.startTransition(() => doSubmit());
10120
- } else {
10121
- doSubmit();
10122
- }
10123
- };
10124
- return /* @__PURE__ */ React102.createElement(
10125
- "form",
10126
- {
10127
- ref: forwardedRef,
10128
- method: formMethod,
10129
- action: formAction,
10130
- onSubmit: reloadDocument ? onSubmit : submitHandler,
10131
- ...props,
10132
- "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
10133
- }
10134
- );
10135
- }
10136
- );
10137
- Form.displayName = "Form";
10138
- function ScrollRestoration({
10139
- getKey,
10140
- storageKey,
10141
- ...props
10142
- }) {
10143
- let remixContext = React102.useContext(FrameworkContext);
10144
- let { basename } = React102.useContext(NavigationContext);
10145
- let location = useLocation3();
10146
- let matches = useMatches();
10147
- useScrollRestoration({ getKey, storageKey });
10148
- let ssrKey = React102.useMemo(
10149
- () => {
10150
- if (!remixContext || !getKey) return null;
10151
- let userKey = getScrollRestorationKey(
10152
- location,
10153
- matches,
10154
- basename,
10155
- getKey
10156
- );
10157
- return userKey !== location.key ? userKey : null;
10158
- },
10159
- // Nah, we only need this the first time for the SSR render
10160
- // eslint-disable-next-line react-hooks/exhaustive-deps
10161
- []
10162
- );
10163
- if (!remixContext || remixContext.isSpaMode) {
10164
- return null;
10165
- }
10166
- let restoreScroll = ((storageKey2, restoreKey) => {
10167
- if (!window.history.state || !window.history.state.key) {
10168
- let key = Math.random().toString(32).slice(2);
10169
- window.history.replaceState({ key }, "");
10170
- }
10171
- try {
10172
- let positions = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
10173
- let storedY = positions[restoreKey || window.history.state.key];
10174
- if (typeof storedY === "number") {
10175
- window.scrollTo(0, storedY);
10176
- }
10177
- } catch (error) {
10178
- console.error(error);
10179
- sessionStorage.removeItem(storageKey2);
10180
- }
10181
- }).toString();
10182
- return /* @__PURE__ */ React102.createElement(
10183
- "script",
10184
- {
10185
- ...props,
10186
- suppressHydrationWarning: true,
10187
- dangerouslySetInnerHTML: {
10188
- __html: `(${restoreScroll})(${escapeHtml(
10189
- JSON.stringify(storageKey || SCROLL_RESTORATION_STORAGE_KEY)
10190
- )}, ${escapeHtml(JSON.stringify(ssrKey))})`
10191
- }
10192
- }
10193
- );
10194
- }
10195
- ScrollRestoration.displayName = "ScrollRestoration";
10196
- function getDataRouterConsoleError2(hookName) {
10197
- return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
10198
- }
10199
- function useDataRouterContext3(hookName) {
10200
- let ctx = React102.useContext(DataRouterContext);
10201
- invariant(ctx, getDataRouterConsoleError2(hookName));
10202
- return ctx;
10203
- }
10204
- function useDataRouterState2(hookName) {
10205
- let state = React102.useContext(DataRouterStateContext);
10206
- invariant(state, getDataRouterConsoleError2(hookName));
10207
- return state;
10208
- }
10209
- function useLinkClickHandler(to, {
10210
- target,
10211
- replace: replaceProp,
10212
- unstable_mask,
10213
- state,
10214
- preventScrollReset,
10215
- relative,
10216
- viewTransition,
10217
- unstable_defaultShouldRevalidate,
10218
- unstable_useTransitions
10219
- } = {}) {
10220
- let navigate = useNavigate5();
10221
- let location = useLocation3();
10222
- let path = useResolvedPath(to, { relative });
10223
- return React102.useCallback(
10224
- (event) => {
10225
- if (shouldProcessLinkClick(event, target)) {
10226
- event.preventDefault();
10227
- let replace2 = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
10228
- let doNavigate = () => navigate(to, {
10229
- replace: replace2,
10230
- unstable_mask,
10231
- state,
10232
- preventScrollReset,
10233
- relative,
10234
- viewTransition,
10235
- unstable_defaultShouldRevalidate
10236
- });
10237
- if (unstable_useTransitions) {
10238
- React102.startTransition(() => doNavigate());
10239
- } else {
10240
- doNavigate();
10241
- }
10242
- }
10243
- },
10244
- [
10245
- location,
10246
- navigate,
10247
- path,
10248
- replaceProp,
10249
- unstable_mask,
10250
- state,
10251
- target,
10252
- to,
10253
- preventScrollReset,
10254
- relative,
10255
- viewTransition,
10256
- unstable_defaultShouldRevalidate,
10257
- unstable_useTransitions
10258
- ]
10259
- );
10260
- }
10261
- function useSearchParams(defaultInit) {
10262
- warning3(
10263
- typeof URLSearchParams !== "undefined",
10264
- `You cannot use the \`useSearchParams\` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.`
10265
- );
10266
- let defaultSearchParamsRef = React102.useRef(createSearchParams(defaultInit));
10267
- let hasSetSearchParamsRef = React102.useRef(false);
10268
- let location = useLocation3();
10269
- let searchParams = React102.useMemo(
10270
- () => (
10271
- // Only merge in the defaults if we haven't yet called setSearchParams.
10272
- // Once we call that we want those to take precedence, otherwise you can't
10273
- // remove a param with setSearchParams({}) if it has an initial value
10274
- getSearchParamsForLocation(
10275
- location.search,
10276
- hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current
10277
- )
10278
- ),
10279
- [location.search]
10280
- );
10281
- let navigate = useNavigate5();
10282
- let setSearchParams = React102.useCallback(
10283
- (nextInit, navigateOptions) => {
10284
- const newSearchParams = createSearchParams(
10285
- typeof nextInit === "function" ? nextInit(new URLSearchParams(searchParams)) : nextInit
10286
- );
10287
- hasSetSearchParamsRef.current = true;
10288
- navigate("?" + newSearchParams, navigateOptions);
10289
- },
10290
- [navigate, searchParams]
10291
- );
10292
- return [searchParams, setSearchParams];
10293
- }
10294
- var fetcherId = 0;
10295
- var getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
10296
- function useSubmit() {
10297
- let { router } = useDataRouterContext3(
10298
- "useSubmit"
10299
- /* UseSubmit */
10300
- );
10301
- let { basename } = React102.useContext(NavigationContext);
10302
- let currentRouteId = useRouteId();
10303
- let routerFetch = router.fetch;
10304
- let routerNavigate = router.navigate;
10305
- return React102.useCallback(
10306
- async (target, options = {}) => {
10307
- let { action, method, encType, formData, body } = getFormSubmissionInfo(
10308
- target,
10309
- basename
10310
- );
10311
- if (options.navigate === false) {
10312
- let key = options.fetcherKey || getUniqueFetcherId();
10313
- await routerFetch(key, currentRouteId, options.action || action, {
10314
- unstable_defaultShouldRevalidate: options.unstable_defaultShouldRevalidate,
10315
- preventScrollReset: options.preventScrollReset,
10316
- formData,
10317
- body,
10318
- formMethod: options.method || method,
10319
- formEncType: options.encType || encType,
10320
- flushSync: options.flushSync
10321
- });
10322
- } else {
10323
- await routerNavigate(options.action || action, {
10324
- unstable_defaultShouldRevalidate: options.unstable_defaultShouldRevalidate,
10325
- preventScrollReset: options.preventScrollReset,
10326
- formData,
10327
- body,
10328
- formMethod: options.method || method,
10329
- formEncType: options.encType || encType,
10330
- replace: options.replace,
10331
- state: options.state,
10332
- fromRouteId: currentRouteId,
10333
- flushSync: options.flushSync,
10334
- viewTransition: options.viewTransition
10335
- });
10336
- }
10337
- },
10338
- [routerFetch, routerNavigate, basename, currentRouteId]
10339
- );
10340
- }
10341
- function useFormAction(action, { relative } = {}) {
10342
- let { basename } = React102.useContext(NavigationContext);
10343
- let routeContext = React102.useContext(RouteContext);
10344
- invariant(routeContext, "useFormAction must be used inside a RouteContext");
10345
- let [match] = routeContext.matches.slice(-1);
10346
- let path = { ...useResolvedPath(action ? action : ".", { relative }) };
10347
- let location = useLocation3();
10348
- if (action == null) {
10349
- path.search = location.search;
10350
- let params = new URLSearchParams(path.search);
10351
- let indexValues = params.getAll("index");
10352
- let hasNakedIndexParam = indexValues.some((v) => v === "");
10353
- if (hasNakedIndexParam) {
10354
- params.delete("index");
10355
- indexValues.filter((v) => v).forEach((v) => params.append("index", v));
10356
- let qs = params.toString();
10357
- path.search = qs ? `?${qs}` : "";
10358
- }
10359
- }
10360
- if ((!action || action === ".") && match.route.index) {
10361
- path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
10362
- }
10363
- if (basename !== "/") {
10364
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
10365
- }
10366
- return createPath(path);
10367
- }
10368
- var SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
10369
- var savedScrollPositions = {};
10370
- function getScrollRestorationKey(location, matches, basename, getKey) {
10371
- let key = null;
10372
- if (getKey) {
10373
- if (basename !== "/") {
10374
- key = getKey(
10375
- {
10376
- ...location,
10377
- pathname: stripBasename(location.pathname, basename) || location.pathname
10378
- },
10379
- matches
10380
- );
10381
- } else {
10382
- key = getKey(location, matches);
10383
- }
10384
- }
10385
- if (key == null) {
10386
- key = location.key;
10387
- }
10388
- return key;
10389
- }
10390
- function useScrollRestoration({
10391
- getKey,
10392
- storageKey
10393
- } = {}) {
10394
- let { router } = useDataRouterContext3(
10395
- "useScrollRestoration"
10396
- /* UseScrollRestoration */
10397
- );
10398
- let { restoreScrollPosition, preventScrollReset } = useDataRouterState2(
10399
- "useScrollRestoration"
10400
- /* UseScrollRestoration */
10401
- );
10402
- let { basename } = React102.useContext(NavigationContext);
10403
- let location = useLocation3();
10404
- let matches = useMatches();
10405
- let navigation = useNavigation();
10406
- React102.useEffect(() => {
10407
- window.history.scrollRestoration = "manual";
10408
- return () => {
10409
- window.history.scrollRestoration = "auto";
10410
- };
10411
- }, []);
10412
- usePageHide(
10413
- React102.useCallback(() => {
10414
- if (navigation.state === "idle") {
10415
- let key = getScrollRestorationKey(location, matches, basename, getKey);
10416
- savedScrollPositions[key] = window.scrollY;
10417
- }
10418
- try {
10419
- sessionStorage.setItem(
10420
- storageKey || SCROLL_RESTORATION_STORAGE_KEY,
10421
- JSON.stringify(savedScrollPositions)
10422
- );
10423
- } catch (error) {
10424
- warning3(
10425
- false,
10426
- `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`
10427
- );
10428
- }
10429
- window.history.scrollRestoration = "auto";
10430
- }, [navigation.state, getKey, basename, location, matches, storageKey])
10431
- );
10432
- if (typeof document !== "undefined") {
10433
- React102.useLayoutEffect(() => {
10434
- try {
10435
- let sessionPositions = sessionStorage.getItem(
10436
- storageKey || SCROLL_RESTORATION_STORAGE_KEY
10437
- );
10438
- if (sessionPositions) {
10439
- savedScrollPositions = JSON.parse(sessionPositions);
10440
- }
10441
- } catch (e) {
10442
- }
10443
- }, [storageKey]);
10444
- React102.useLayoutEffect(() => {
10445
- let disableScrollRestoration = router?.enableScrollRestoration(
10446
- savedScrollPositions,
10447
- () => window.scrollY,
10448
- getKey ? (location2, matches2) => getScrollRestorationKey(location2, matches2, basename, getKey) : void 0
10449
- );
10450
- return () => disableScrollRestoration && disableScrollRestoration();
10451
- }, [router, basename, getKey]);
10452
- React102.useLayoutEffect(() => {
10453
- if (restoreScrollPosition === false) {
10454
- return;
10455
- }
10456
- if (typeof restoreScrollPosition === "number") {
10457
- window.scrollTo(0, restoreScrollPosition);
10458
- return;
10459
- }
10460
- try {
10461
- if (location.hash) {
10462
- let el = document.getElementById(
10463
- decodeURIComponent(location.hash.slice(1))
10464
- );
10465
- if (el) {
10466
- el.scrollIntoView();
10467
- return;
10468
- }
10469
- }
10470
- } catch {
10471
- warning3(
10472
- false,
10473
- `"${location.hash.slice(
10474
- 1
10475
- )}" is not a decodable element ID. The view will not scroll to it.`
10476
- );
10477
- }
10478
- if (preventScrollReset === true) {
10479
- return;
10480
- }
10481
- window.scrollTo(0, 0);
10482
- }, [location, restoreScrollPosition, preventScrollReset]);
10483
- }
10484
- }
10485
- function usePageHide(callback, options) {
10486
- let { capture } = options || {};
10487
- React102.useEffect(() => {
10488
- let opts = capture != null ? { capture } : void 0;
10489
- window.addEventListener("pagehide", callback, opts);
10490
- return () => {
10491
- window.removeEventListener("pagehide", callback, opts);
10492
- };
10493
- }, [callback, capture]);
10494
- }
10495
- function useViewTransitionState(to, { relative } = {}) {
10496
- let vtContext = React102.useContext(ViewTransitionContext);
10497
- invariant(
10498
- vtContext != null,
10499
- "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?"
10500
- );
10501
- let { basename } = useDataRouterContext3(
10502
- "useViewTransitionState"
10503
- /* useViewTransitionState */
10504
- );
10505
- let path = useResolvedPath(to, { relative });
10506
- if (!vtContext.isTransitioning) {
10507
- return false;
10508
- }
10509
- let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
10510
- let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
10511
- return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
10512
- }
10513
-
10514
- // src/hooks/useApp.tsx
10515
- var useApp = () => {
10516
- const [searchParams] = useSearchParams();
10517
- const navigate = useNavigate5();
10518
- const getParams = (key) => {
10519
- const params = useParams2();
10520
- if (key) return params[key];
10521
- return params;
10522
- };
10523
- const getQuery = (key) => {
10524
- if (key) return searchParams.get(key);
10525
- return Object.fromEntries(searchParams.entries());
10526
- };
10527
- return {
10528
- navigate,
10529
- getQuery,
10530
- getParams
10531
- };
10532
- };
10533
- var useApp_default = useApp;
10534
-
10535
- // src/utils/Enums.ts
10536
- var Enums = {
10537
- roles: ["admin", "staff"],
10538
- sex: ["male", "female"],
10539
- accountTypes: ["employee", "supplier", "customer", "investor"],
10540
- verificationTypes: ["email_verification", "password_reset"],
10541
- auditActions: ["create", "update", "delete", "login", "logout"]
10542
- };
10543
- var Enums_default = Enums;
10544
-
10545
- // src/components/accounts/schema.tsx
10546
- var import_zod2 = require("zod");
10547
- var createAccountSchema = import_zod2.z.object({
10548
- name: import_zod2.z.string().min(2, { message: "Name must be at least 2 characters" }),
10549
- email: import_zod2.z.string().optional().refine((val) => !val || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val), {
10550
- message: "Please enter a valid email address"
10551
- }).transform((val) => val?.toLowerCase()),
10552
- phoneNumber: import_zod2.z.string().optional(),
10553
- sex: import_zod2.z.enum(Enums_default.sex),
10554
- owner: import_zod2.z.string().min(1, { message: "Owner is required" }),
10555
- host: import_zod2.z.string().min(1, { message: "Host is required" })
10556
- });
10557
-
10558
- // src/components/accounts/AccountForm.tsx
10559
- var import_react_hook_form8 = require("react-hook-form");
10560
- var import_zod3 = require("@hookform/resolvers/zod");
10561
- var import_antd7 = require("antd");
10562
- var import_react34 = require("react");
10563
- var import_jsx_runtime43 = require("react/jsx-runtime");
10564
- function AccountForm() {
10565
- const { getQuery, getParams, navigate } = useApp_default();
10566
- const id = getQuery("id");
10567
- const type = getParams("type");
10568
- const isEdit = !!id;
10569
- const { post, put, isLoading } = useApis_default();
10570
- const { isLoading: isLoadingGet, get } = useApis_default();
10571
- const methods = (0, import_react_hook_form8.useForm)({
10572
- resolver: (0, import_zod3.zodResolver)(createAccountSchema),
10573
- defaultValues: {
10574
- name: "",
10575
- email: "",
10576
- phoneNumber: "",
10577
- sex: "male",
10578
- owner: "",
10579
- host: ""
10580
- },
10581
- shouldUnregister: false
10582
- });
10583
- const { handleSubmit } = methods;
10584
- const onSubmit = async (data2) => {
10585
- try {
10586
- const payload = {
10587
- ...data2,
10588
- type
10589
- };
10590
- if (isEdit) {
10591
- await put({
10592
- url: `/accounts/update/${id}`,
10593
- body: payload
10594
- });
10595
- } else {
10596
- await post({
10597
- url: "/accounts/create",
10598
- body: payload
10599
- });
10600
- }
10601
- import_antd7.message.success(`${type} ${isEdit ? "updated" : "created"} successfully`);
10602
- navigate(-1);
10603
- } catch (error) {
10604
- import_antd7.message.error(error?.message || "Something went wrong");
10605
- }
10606
- };
10607
- const fetches = async () => {
10608
- try {
10609
- const res = await get({
10610
- url: `/accounts/get/${type}?id=${id}`
10611
- });
10612
- const data2 = res.data;
10613
- methods.reset(data2);
10614
- } catch (error) {
10615
- import_antd7.message.error(error?.message || "Something went wrong");
10616
- }
10617
- };
10618
- (0, import_react34.useEffect)(() => {
10619
- if (isEdit) {
10620
- fetches();
8222
+ };
8223
+ (0, import_react34.useEffect)(() => {
8224
+ if (isEdit) {
8225
+ fetches();
10621
8226
  }
10622
8227
  }, [id]);
10623
8228
  return /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(
@@ -10678,28 +8283,6 @@ function AccountForm() {
10678
8283
  name: "phoneNumber",
10679
8284
  placeholder: "Enter phone number"
10680
8285
  }
10681
- ),
10682
- /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
10683
- Fields_default.SearchApi,
10684
- {
10685
- label: "Owner",
10686
- form: methods,
10687
- name: "owner",
10688
- api: "/accounts/get/customer",
10689
- placeholder: "Search for account owner...",
10690
- required: true
10691
- }
10692
- ),
10693
- /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
10694
- Fields_default.Input,
10695
- {
10696
- label: "Host",
10697
- form: methods,
10698
- name: "host",
10699
- type: "text",
10700
- placeholder: "Unique host name",
10701
- required: true
10702
- }
10703
8286
  )
10704
8287
  ] }),
10705
8288
  /* @__PURE__ */ (0, import_jsx_runtime43.jsx)("footer", { className: "flex justify-end mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
@@ -10769,10 +8352,10 @@ function LinkUser({ type: initialType = "employee" }) {
10769
8352
  shouldUnregister: false
10770
8353
  });
10771
8354
  const { handleSubmit } = methods;
10772
- const onSubmit = async (data2) => {
8355
+ const onSubmit = async (data) => {
10773
8356
  try {
10774
8357
  const payload = {
10775
- ...data2
8358
+ ...data
10776
8359
  };
10777
8360
  await post({
10778
8361
  url: `/accounts/link-user/${id}`,
@@ -10789,13 +8372,13 @@ function LinkUser({ type: initialType = "employee" }) {
10789
8372
  const res = await get({
10790
8373
  url: `/accounts/get/${type}?id=${id}`
10791
8374
  });
10792
- const data2 = res.data;
10793
- if (data2?.user) {
8375
+ const data = res.data;
8376
+ if (data?.user) {
10794
8377
  import_antd8.message.error("Account Already Has A Login User");
10795
8378
  navigate(-1);
10796
8379
  return;
10797
8380
  }
10798
- methods.reset(data2);
8381
+ methods.reset(data);
10799
8382
  } catch (error) {
10800
8383
  import_antd8.message.error(error?.message || "Something went wrong");
10801
8384
  }
@@ -10882,23 +8465,23 @@ var import_react36 = require("react");
10882
8465
  var import_jsx_runtime45 = require("react/jsx-runtime");
10883
8466
  var { Countdown } = import_antd9.Statistic;
10884
8467
  function VerifyEmailForm({
10885
- data: data2,
8468
+ data,
10886
8469
  close,
10887
8470
  reload
10888
8471
  }) {
10889
8472
  const { put, isLoading } = useApis_default();
10890
- const [datas, setDatas] = (0, import_react36.useState)(data2);
8473
+ const [datas, setDatas] = (0, import_react36.useState)(data);
10891
8474
  const [hasPassed, setHasPassed] = (0, import_react36.useState)(
10892
- data2?.emailVerification?.passed || !data2?.emailVerification?.createdAt
8475
+ data?.emailVerification?.passed || !data?.emailVerification?.createdAt
10893
8476
  );
10894
8477
  (0, import_react36.useEffect)(() => {
10895
- setDatas(data2);
8478
+ setDatas(data);
10896
8479
  setHasPassed(
10897
- data2?.emailVerification?.passed || !data2?.emailVerification?.createdAt
8480
+ data?.emailVerification?.passed || !data?.emailVerification?.createdAt
10898
8481
  );
10899
- }, [data2]);
10900
- const email = data2?.emailVerification?.email;
10901
- const oldEmail = data2?.emailVerification?.email !== data2?.email ? data2?.emailVerification?.email : null;
8482
+ }, [data]);
8483
+ const email = data?.emailVerification?.email;
8484
+ const oldEmail = data?.emailVerification?.email !== data?.email ? data?.emailVerification?.email : null;
10902
8485
  const methods = (0, import_react_hook_form10.useForm)({
10903
8486
  resolver: (0, import_zod6.zodResolver)(verifyUserEmailSchema),
10904
8487
  defaultValues: {
@@ -10914,7 +8497,7 @@ function VerifyEmailForm({
10914
8497
  ...datas2
10915
8498
  };
10916
8499
  await put({
10917
- url: `/users/verify_email/${data2._id}`,
8500
+ url: `/users/verify_email/${data._id}`,
10918
8501
  body: payload
10919
8502
  });
10920
8503
  import_antd9.message.success(`Email Verified successfully`);
@@ -10931,9 +8514,9 @@ function VerifyEmailForm({
10931
8514
  const resend = async () => {
10932
8515
  try {
10933
8516
  const res = await put({
10934
- url: `/users/resend_email_verification/${data2._id}`,
8517
+ url: `/users/resend_email_verification/${data._id}`,
10935
8518
  body: {
10936
- email: data2?.emailVerification?.email || data2?.email
8519
+ email: data?.emailVerification?.email || data?.email
10937
8520
  }
10938
8521
  });
10939
8522
  setDatas((prev) => ({
@@ -11023,12 +8606,12 @@ var import_zod7 = require("@hookform/resolvers/zod");
11023
8606
  var import_antd10 = require("antd");
11024
8607
  var import_jsx_runtime46 = require("react/jsx-runtime");
11025
8608
  function UpdateEmailForm({
11026
- data: data2,
8609
+ data,
11027
8610
  close,
11028
8611
  reload
11029
8612
  }) {
11030
8613
  const { put, isLoading } = useApis_default();
11031
- const currentEmail = data2?.email;
8614
+ const currentEmail = data?.email;
11032
8615
  const methods = (0, import_react_hook_form11.useForm)({
11033
8616
  resolver: (0, import_zod7.zodResolver)(updateUserEmailSchema),
11034
8617
  defaultValues: {
@@ -11040,7 +8623,7 @@ function UpdateEmailForm({
11040
8623
  const onSubmit = async (formData) => {
11041
8624
  try {
11042
8625
  await put({
11043
- url: `/users/change_email/${data2._id}`,
8626
+ url: `/users/change_email/${data._id}`,
11044
8627
  body: {
11045
8628
  email: formData.newEmail
11046
8629
  }
@@ -11111,20 +8694,20 @@ var import_react37 = require("react");
11111
8694
  var import_jsx_runtime47 = require("react/jsx-runtime");
11112
8695
  var { Countdown: Countdown2 } = import_antd11.Statistic;
11113
8696
  function ResetPasswordForm({
11114
- data: data2,
8697
+ data,
11115
8698
  close,
11116
8699
  reload
11117
8700
  }) {
11118
8701
  const { put, isLoading } = useApis_default();
11119
- const [datas, setDatas] = (0, import_react37.useState)(data2);
8702
+ const [datas, setDatas] = (0, import_react37.useState)(data);
11120
8703
  const [hasPassed, setHasPassed] = (0, import_react37.useState)(
11121
- data2?.passwordReset?.passed || !data2?.passwordReset?.createdAt
8704
+ data?.passwordReset?.passed || !data?.passwordReset?.createdAt
11122
8705
  );
11123
8706
  (0, import_react37.useEffect)(() => {
11124
- setDatas(data2);
11125
- setHasPassed(data2?.passwordReset?.passed || !data2?.passwordReset?.createdAt);
11126
- }, [data2]);
11127
- const userEmail = data2?.email;
8707
+ setDatas(data);
8708
+ setHasPassed(data?.passwordReset?.passed || !data?.passwordReset?.createdAt);
8709
+ }, [data]);
8710
+ const userEmail = data?.email;
11128
8711
  const methods = (0, import_react_hook_form12.useForm)({
11129
8712
  defaultValues: {
11130
8713
  email: userEmail
@@ -11145,7 +8728,7 @@ function ResetPasswordForm({
11145
8728
  const resendToken = async () => {
11146
8729
  try {
11147
8730
  const res = await put({
11148
- url: `/users/reset_password/${data2._id}`,
8731
+ url: `/users/reset_password/${data._id}`,
11149
8732
  body: {
11150
8733
  email: userEmail
11151
8734
  }
@@ -11216,15 +8799,15 @@ var ResetPasswordForm_default = ResetPasswordForm;
11216
8799
  var import_antd12 = require("antd");
11217
8800
  var import_react38 = require("react");
11218
8801
  var import_jsx_runtime48 = require("react/jsx-runtime");
11219
- var ActivateUser = ({ data: data2 }) => {
11220
- const [checked, setChecked] = (0, import_react38.useState)(data2?.isActive);
8802
+ var ActivateUser = ({ data }) => {
8803
+ const [checked, setChecked] = (0, import_react38.useState)(data?.isActive);
11221
8804
  const { put, isLoading } = useApis_default();
11222
8805
  return /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_jsx_runtime48.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
11223
8806
  import_antd12.Switch,
11224
8807
  {
11225
8808
  onChange: async (e) => {
11226
8809
  const res = await put({
11227
- url: `/users/activate/${data2?._id}`,
8810
+ url: `/users/activate/${data?._id}`,
11228
8811
  v: 1,
11229
8812
  body: { isActive: e }
11230
8813
  });
@@ -11244,14 +8827,14 @@ var Activate_default = ActivateUser;
11244
8827
  // src/components/users/users.tsx
11245
8828
  var import_jsx_runtime49 = require("react/jsx-runtime");
11246
8829
  function Users() {
11247
- const { data: data2, TransactionViewComponent, reload } = useTransaction_default({
8830
+ const { data, TransactionViewComponent, reload } = useTransaction_default({
11248
8831
  url: "/users/get",
11249
8832
  v: 1,
11250
8833
  dateFilter: false
11251
8834
  });
11252
8835
  const { Modal: Modal2, openState, close } = useModal();
11253
8836
  const { put, isLoading } = useApis_default();
11254
- const items = (data3) => [
8837
+ const items = (data2) => [
11255
8838
  {
11256
8839
  label: `Reset Password`,
11257
8840
  icon: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_lucide_react20.Key, { size: 16 }),
@@ -11261,7 +8844,7 @@ function Users() {
11261
8844
  content: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
11262
8845
  ResetPasswordForm_default,
11263
8846
  {
11264
- data: data3,
8847
+ data: data2,
11265
8848
  close: () => close(),
11266
8849
  reload: () => reload()
11267
8850
  }
@@ -11278,7 +8861,7 @@ function Users() {
11278
8861
  content: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
11279
8862
  UpdateEmailForm_default,
11280
8863
  {
11281
- data: data3,
8864
+ data: data2,
11282
8865
  close: () => close(),
11283
8866
  reload: () => reload()
11284
8867
  }
@@ -11286,7 +8869,7 @@ function Users() {
11286
8869
  width: 600
11287
8870
  })
11288
8871
  },
11289
- data3?.emailVerification && {
8872
+ data2?.emailVerification && {
11290
8873
  label: `Verify Email`,
11291
8874
  icon: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_lucide_react20.ShieldCheck, {}),
11292
8875
  onClick: () => openState({
@@ -11295,7 +8878,7 @@ function Users() {
11295
8878
  content: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
11296
8879
  VerifyEmailForm_default,
11297
8880
  {
11298
- data: data3,
8881
+ data: data2,
11299
8882
  close: () => close(),
11300
8883
  reload: () => reload()
11301
8884
  }
@@ -11310,15 +8893,15 @@ function Users() {
11310
8893
  accessorKey: "email",
11311
8894
  header: "Email",
11312
8895
  cell: ({ row }) => {
11313
- const data3 = row.original;
11314
- const emailVerification = data3?.emailVerification;
11315
- const newEmail = emailVerification?.email !== data3?.email ? emailVerification?.email : null;
8896
+ const data2 = row.original;
8897
+ const emailVerification = data2?.emailVerification;
8898
+ const newEmail = emailVerification?.email !== data2?.email ? emailVerification?.email : null;
11316
8899
  return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)("div", { className: "space-y-1", children: [
11317
8900
  /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)("section", { className: "flex items-center gap-2", children: [
11318
8901
  " ",
11319
- /* @__PURE__ */ (0, import_jsx_runtime49.jsx)("p", { children: data3?.email }),
11320
- data3?.isEmailVerified && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Badge, { variant: "success", size: "sm", children: "Verified" }),
11321
- !data3?.isEmailVerified && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Badge, { variant: "warning", size: "sm", children: "Not Verified" })
8902
+ /* @__PURE__ */ (0, import_jsx_runtime49.jsx)("p", { children: data2?.email }),
8903
+ data2?.isEmailVerified && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Badge, { variant: "success", size: "sm", children: "Verified" }),
8904
+ !data2?.isEmailVerified && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Badge, { variant: "warning", size: "sm", children: "Not Verified" })
11322
8905
  ] }),
11323
8906
  newEmail && /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)("section", { className: "flex items-center gap-2", children: [
11324
8907
  /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_lucide_react20.Info, { size: 16, className: "text-orange-600" }),
@@ -11339,20 +8922,20 @@ function Users() {
11339
8922
  accessorKey: "status",
11340
8923
  header: "Status",
11341
8924
  cell: ({ row }) => {
11342
- const data3 = row.original;
11343
- return /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Activate_default, { data: data3 });
8925
+ const data2 = row.original;
8926
+ return /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Activate_default, { data: data2 });
11344
8927
  }
11345
8928
  },
11346
8929
  {
11347
8930
  accessorKey: "actions",
11348
8931
  header: "Actions",
11349
8932
  cell: ({ row }) => {
11350
- const data3 = row.original;
8933
+ const data2 = row.original;
11351
8934
  return /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
11352
8935
  Dropdown,
11353
8936
  {
11354
8937
  className: "w-fit! cursor-pointer",
11355
- items: items(data3),
8938
+ items: items(data2),
11356
8939
  triggerMode: "hover",
11357
8940
  children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_lucide_react20.EllipsisVertical, {})
11358
8941
  }
@@ -11362,7 +8945,7 @@ function Users() {
11362
8945
  ],
11363
8946
  [items]
11364
8947
  );
11365
- const users = data2?.data || [];
8948
+ const users = data?.data || [];
11366
8949
  return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(import_jsx_runtime49.Fragment, { children: [
11367
8950
  /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Modal2, {}),
11368
8951
  /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
@@ -11382,7 +8965,7 @@ var users_default = Users;
11382
8965
 
11383
8966
  // src/components/users/ResetPasswordPage.tsx
11384
8967
  var import_react40 = require("react");
11385
- var import_react_router_dom6 = require("react-router-dom");
8968
+ var import_react_router_dom7 = require("react-router-dom");
11386
8969
  var import_lucide_react21 = require("lucide-react");
11387
8970
  var import_react_hook_form13 = require("react-hook-form");
11388
8971
  var import_zod8 = require("@hookform/resolvers/zod");
@@ -11392,13 +8975,13 @@ var import_jsx_runtime50 = require("react/jsx-runtime");
11392
8975
  var resetPageSchema = z4.object({
11393
8976
  password: z4.string().min(6, "Password must be at least 6 characters"),
11394
8977
  confirmPassword: z4.string().min(6, "Password must be at least 6 characters")
11395
- }).refine((data2) => data2.password === data2.confirmPassword, {
8978
+ }).refine((data) => data.password === data.confirmPassword, {
11396
8979
  message: "Passwords don't match",
11397
8980
  path: ["confirmPassword"]
11398
8981
  });
11399
8982
  function ResetPasswordPage() {
11400
- const [searchParams] = (0, import_react_router_dom6.useSearchParams)();
11401
- const navigate = (0, import_react_router_dom6.useNavigate)();
8983
+ const [searchParams] = (0, import_react_router_dom7.useSearchParams)();
8984
+ const navigate = (0, import_react_router_dom7.useNavigate)();
11402
8985
  const { put, isLoading } = useApis_default();
11403
8986
  const [isVerified, setIsVerified] = (0, import_react40.useState)(false);
11404
8987
  const [verifying, setVerifying] = (0, import_react40.useState)(true);
@@ -11435,14 +9018,14 @@ function ResetPasswordPage() {
11435
9018
  };
11436
9019
  verifyToken();
11437
9020
  }, [token, email]);
11438
- const onSubmit = async (data2) => {
9021
+ const onSubmit = async (data) => {
11439
9022
  try {
11440
9023
  await put({
11441
9024
  url: `/users/set_password/${id}`,
11442
9025
  body: {
11443
9026
  token,
11444
9027
  email,
11445
- password: data2.password
9028
+ password: data.password
11446
9029
  }
11447
9030
  });
11448
9031
  import_antd13.message.success(
@@ -11570,7 +9153,7 @@ var ResetPasswordPage_default = ResetPasswordPage;
11570
9153
 
11571
9154
  // src/components/users/UserProfile.tsx
11572
9155
  var import_lucide_react22 = require("lucide-react");
11573
- var import_react_router_dom7 = require("react-router-dom");
9156
+ var import_react_router_dom8 = require("react-router-dom");
11574
9157
  var import_antd14 = require("antd");
11575
9158
  var import_jsx_runtime51 = require("react/jsx-runtime");
11576
9159
  var UserProfile = ({
@@ -11583,7 +9166,7 @@ var UserProfile = ({
11583
9166
  }) => {
11584
9167
  const { post } = useApis_default();
11585
9168
  const { user, logout: authLogout, account } = useAuth_default();
11586
- const navigate = (0, import_react_router_dom7.useNavigate)();
9169
+ const navigate = (0, import_react_router_dom8.useNavigate)();
11587
9170
  const logout = async () => {
11588
9171
  if (onLogout) {
11589
9172
  onLogout();
@@ -11635,11 +9218,11 @@ var UserProfile = ({
11635
9218
  var UserProfile_default = UserProfile;
11636
9219
 
11637
9220
  // src/components/users/ProfilePage.tsx
11638
- var import_react_router_dom8 = require("react-router-dom");
9221
+ var import_react_router_dom9 = require("react-router-dom");
11639
9222
  var import_lucide_react23 = require("lucide-react");
11640
9223
  var import_jsx_runtime52 = require("react/jsx-runtime");
11641
9224
  var ProfilePage = () => {
11642
- const navigate = (0, import_react_router_dom8.useNavigate)();
9225
+ const navigate = (0, import_react_router_dom9.useNavigate)();
11643
9226
  const { user, account } = useAuth();
11644
9227
  if (!user) {
11645
9228
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("div", { className: "flex items-center justify-center min-h-[400px]", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("h1", { children: "Please login to view your profile" }) });
@@ -11769,18 +9352,3 @@ var ProfilePage_default = ProfilePage;
11769
9352
  useWarqadConfig,
11770
9353
  verifyUserEmailSchema
11771
9354
  });
11772
- /*! Bundled license information:
11773
-
11774
- react-router/dist/development/chunk-LFPYN7LY.mjs:
11775
- react-router/dist/development/index.mjs:
11776
- (**
11777
- * react-router v7.13.1
11778
- *
11779
- * Copyright (c) Remix Software Inc.
11780
- *
11781
- * This source code is licensed under the MIT license found in the
11782
- * LICENSE.md file in the root directory of this source tree.
11783
- *
11784
- * @license MIT
11785
- *)
11786
- */