All files / applications/go-by-transit/src/state/bookmarks BookmarksProvider.tsx

92.94% Statements 79/85
77.77% Branches 14/18
90.9% Functions 40/44
94.8% Lines 73/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247                                                                                                  53x 11x   42x 3x         39x               11x           58x   232x 232x   8x 8x 8x     58x                       42x 42x   3x 3x         11x 11x 11x         4x 4x       58x   7x     6x 6x 6x       2x 2x 2x       4x 4x       5x 5x 5x 5x 5x   5x 4x 4x               4x 4x 4x 4x 4x 4x       2x 2x 2x       2x   2x 2x       6x     2x           1x     4x                   17x     17x         90x 90x 90x                   175x 175x 175x       113x 113x   113x       13x 13x 16x   13x       5x 5x              
import React, { createContext, useContext, useMemo, useReducer } from "react";
import {
  addStoredRouteToBookmarkGroup,
  fetchStoredBookmarkSections,
  fetchStoredBookmarks,
  fetchStoredRouteBookmarkGroups,
  fetchStoredRouteBookmarks,
  removeAllStoredBookmarksInSection,
  removeStoredBookmark,
  removeStoredBookmarkFromSection,
  removeStoredBookmarkSection,
  removeStoredRouteBookmark,
  removeStoredRouteBookmarkGroup,
  removeStoredRouteFromAllBookmarkGroups,
  removeStoredRouteFromBookmarkGroup,
  storeBookmarkSection,
  storeLocationBookmark,
  storeRouteBookmark,
  updateStoredBookmarkSection,
  updateStoredBookmarkSectionName,
  type BookmarkSectionsProps,
  type RouteBookmark,
  type RouteBookmarkGroups,
  type RouteBookmarks,
  type StoredBookmarks,
} from "@overworld/bookmarks";
import type { StopLocation } from "@overworld/trimet-client";
 
type Domain = "stops" | "routes" | "sections" | "routeGroups";
type BookmarkErrors = Partial<Record<Domain, string>>;
 
interface BookmarkState {
  stops: StoredBookmarks;
  routes: RouteBookmarks;
  sections: BookmarkSectionsProps;
  routeGroups: RouteBookmarkGroups;
  sectionName: string;
  errors: BookmarkErrors;
}
 
type Action =
  | { type: "stops"; value: StoredBookmarks }
  | { type: "routes"; value: RouteBookmarks }
  | { type: "sections"; value: BookmarkSectionsProps }
  | { type: "routeGroups"; value: RouteBookmarkGroups }
  | { type: "sectionName"; value: string }
  | { type: "error"; domain: Domain; message: string };
 
function reducer(state: BookmarkState, action: Action): BookmarkState {
  if (action.type === "sectionName") {
    return { ...state, sectionName: action.value };
  }
  if (action.type === "error") {
    return {
      ...state,
      errors: { ...state.errors, [action.domain]: action.message },
    };
  }
  return {
    ...state,
    [action.type]: action.value,
    errors: { ...state.errors, [action.type]: undefined },
  };
}
 
function errorMessage(error: unknown): string {
  return error instanceof Error
    ? error.message
    : "Browser storage is unavailable.";
}
 
function loadInitialState(): BookmarkState {
  const errors: BookmarkErrors = {};
  function read<T>(domain: Domain, load: () => T, empty: T): T {
    try {
      return load();
    } catch (error) {
      console.warn(`Could not load bookmark ${domain}.`, error);
      errors[domain] = errorMessage(error);
      return empty;
    }
  }
  return {
    stops: read("stops", fetchStoredBookmarks, {}),
    routes: read("routes", fetchStoredRouteBookmarks, {}),
    sections: read("sections", fetchStoredBookmarkSections, {}),
    routeGroups: read("routeGroups", fetchStoredRouteBookmarkGroups, {}),
    sectionName: "",
    errors,
  };
}
 
function createCommands(dispatch: React.Dispatch<Action>) {
  function run(domain: Domain, operation: () => void) {
    try {
      operation();
    } catch (error) {
      console.warn(`Could not save bookmark ${domain}.`, error);
      dispatch({ type: "error", domain, message: errorMessage(error) });
    }
  }
 
  function updateSections(write: () => void) {
    run("sections", () => {
      write();
      dispatch({ type: "sections", value: fetchStoredBookmarkSections() });
    });
  }
 
  function updateGroups(write: () => RouteBookmarkGroups) {
    run("routeGroups", () => {
      dispatch({ type: "routeGroups", value: write() });
    });
  }
 
  return {
    setSectionName(value: string) {
      dispatch({ type: "sectionName", value });
    },
    bookmarkStop(stop: StopLocation) {
      run("stops", () => {
        storeLocationBookmark(stop);
        dispatch({ type: "stops", value: fetchStoredBookmarks() });
      });
    },
    removeStop(locationId: number) {
      run("stops", () => {
        removeStoredBookmark(locationId);
        dispatch({ type: "stops", value: fetchStoredBookmarks() });
      });
    },
    bookmarkRoute(route: RouteBookmark) {
      run("routes", () => {
        dispatch({ type: "routes", value: storeRouteBookmark(route) });
      });
    },
    removeRoute(routeId: number) {
      let groupsRemoved = false;
      run("routeGroups", () => {
        const value = removeStoredRouteFromAllBookmarkGroups(routeId);
        dispatch({ type: "routeGroups", value });
        groupsRemoved = true;
      });
      if (groupsRemoved) {
        run("routes", () => {
          dispatch({
            type: "routes",
            value: removeStoredRouteBookmark(routeId),
          });
        });
      }
    },
    createSection(name: string) {
      run("sections", () => {
        const sections = fetchStoredBookmarkSections();
        const nextId = Math.max(-1, ...Object.keys(sections).map(Number)) + 1;
        storeBookmarkSection(nextId, { name, order: 0, bookmarkedStops: [] });
        dispatch({ type: "sections", value: fetchStoredBookmarkSections() });
        dispatch({ type: "sectionName", value: "" });
      });
    },
    removeSection(sectionId: number) {
      let groupsRemoved = false;
      run("routeGroups", () => {
        dispatch({
          type: "routeGroups",
          value: removeStoredRouteBookmarkGroup(sectionId),
        });
        groupsRemoved = true;
      });
      Eif (groupsRemoved) {
        updateSections(() => removeStoredBookmarkSection(sectionId));
      }
    },
    renameSection(sectionId: number, name: string) {
      updateSections(() => updateStoredBookmarkSectionName(sectionId, name));
    },
    addStopToSection(sectionId: number, stopId: number) {
      updateSections(() => updateStoredBookmarkSection(sectionId, stopId));
    },
    removeStopFromSection(sectionId: number, stopId: number) {
      updateSections(() => removeStoredBookmarkFromSection(sectionId, stopId));
    },
    clearSectionStops(sectionId: number) {
      updateSections(() => removeAllStoredBookmarksInSection(sectionId));
    },
    addRouteToSection(sectionId: number, routeId: number) {
      updateGroups(() => addStoredRouteToBookmarkGroup(sectionId, routeId));
    },
    removeRouteFromSection(sectionId: number, routeId: number) {
      updateGroups(() =>
        removeStoredRouteFromBookmarkGroup(sectionId, routeId),
      );
    },
  };
}
 
const BookmarkStateContext = createContext<BookmarkState | undefined>(
  undefined,
);
const BookmarkCommandsContext = createContext<
  ReturnType<typeof createCommands> | undefined
>(undefined);
 
export function BookmarksProvider({ children }: { children: React.ReactNode }) {
  const [state, dispatch] = useReducer(reducer, undefined, loadInitialState);
  const commands = useMemo(() => createCommands(dispatch), [dispatch]);
  return (
    <BookmarkCommandsContext.Provider value={commands}>
      <BookmarkStateContext.Provider value={state}>
        {children}
      </BookmarkStateContext.Provider>
    </BookmarkCommandsContext.Provider>
  );
}
 
export function useBookmarks() {
  const state = useContext(BookmarkStateContext);
  Iif (!state) throw new Error("Bookmark consumers require BookmarksProvider.");
  return state;
}
 
export function useBookmarkCommands() {
  const commands = useContext(BookmarkCommandsContext);
  Iif (!commands)
    throw new Error("Bookmark commands require BookmarksProvider.");
  return commands;
}
 
export function useBookmarkError(...domains: Domain[]) {
  const { errors } = useBookmarks();
  const messages = domains.length
    ? domains.map((domain) => errors[domain])
    : Object.values(errors);
  return messages.filter(Boolean).join(" ");
}
 
export function BookmarkStorageErrors() {
  const error = useBookmarkError();
  return error ? (
    <p role="alert">
      Bookmarks could not be loaded or saved. {error} Check browser storage and
      try again.
    </p>
  ) : null;
}