Skip to article
Documentation

src/features/reviews/return-path.ts

Linked repository file from this build.

const LAST_KEY = "qccrm.last-path";
const RETURN_KEY = "qccrm.return-path";
export const RETURN_FALLBACK = "/dashboard";

function read(key: string) {
  try {
    return sessionStorage.getItem(key);
  } catch {
    return null;
  }
}

function write(key: string, value: string) {
  try {
    sessionStorage.setItem(key, value);
  } catch {
    // Private mode or quota: Return falls back to Home.
  }
}

function safePath(value: string | null) {
  if (!value || !value.startsWith("/") || value.startsWith("//")) return null;
  return value;
}

/** Keep the previous in-app path so Return can leave a review for that page. */
export function rememberPath(path: string) {
  const current = safePath(path);
  if (!current) return;
  const last = safePath(read(LAST_KEY));
  if (last && last !== current) write(RETURN_KEY, last);
  write(LAST_KEY, current);
}

export function returnPath(currentPath?: string) {
  const href = safePath(read(RETURN_KEY));
  if (!href) return RETURN_FALLBACK;
  const current = currentPath ?? (typeof window === "undefined" ? "" : window.location.pathname);
  if (current && (href === current || href.startsWith(`${current}?`))) return RETURN_FALLBACK;
  return href;
}