brackt/app/hooks/useDraftNotifications.ts
Chris Parsons 4bffa40606
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196)
* Fix no-shadow and consistent-function-scoping lint violations

Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint
warnings and promotes both rules to errors in .oxlintrc.json.

no-shadow: renamed Drizzle callback params (sports→s, matches→m,
seasons→s) to avoid shadowing outer imports; removed shadowed
destructures (eq, inArray) from where callbacks; renamed inner
template→bracketTemplate, prev→currentTimers, season→ss, name→teamName
(with name: teamName fix to preserve semantics).

consistent-function-scoping: moved formatDate, getRankBadge,
getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr,
elo (×2), weightedPick, sortByMatchNumber (×2) to module scope;
moved formatTime (×2), isValidLeagueName, getDraftTimes,
makeSeasonQueues to file scope in test files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix no-non-null-assertion lint violations and promote to error

Eliminates all 208 no-non-null-assertion warnings across 38 files.
Promotes typescript/no-non-null-assertion from warn to error in
.oxlintrc.json.

Fix patterns applied:
- Map.get(key)! after .has() check → extract with get() + null guard
- Map.get(key)! on pre-populated count maps → ?? 0 default
- .set(id, map.get(id)! + 1) increment → ?? 0 before adding
- participant1Id!/participant2Id! on DB matches → ?? "" fallback
- array.find()! in tests → guard + throw or expect().toBeDefined()
- bracketTemplateCache.get(id)! → null guard extract
- Various nullable field accesses → optional chain or ?? default

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers

Resolves all 9 remaining non-console lint warnings and promotes all
three rules to errors in .oxlintrc.json.

- prefer-add-event-listener: converted onchange/onclick/onload
  assignments to addEventListener in useDraftNotifications.ts and
  admin.data-sync.tsx; stored changeHandler ref for proper cleanup
  with removeEventListener
- no-unassigned-import: configured rule with allow list for legitimate
  side-effect imports (*.css, @testing-library/jest-dom,
  @testing-library/cypress/add-commands)
- require-module-specifiers: removed redundant `export {}` from
  cypress/support/e2e.ts (file already has an import)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix TypeScript errors from no-non-null-assertion fixes

Two fixes introduced by the non-null assertion cleanup produced type
errors:

- scoring-event.ts: `?? ""` was wrong type for a participant object map;
  restructured to explicit null guards so TypeScript can narrow correctly
- standings-sync/index.ts: `?? null` after name-match lookup lost the
  truthy guarantee, causing TS18047 on the write-back block; added
  `participant &&` guard before accessing its properties

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add npm run typecheck as Stop hook in Claude settings

Runs a full project typecheck at the end of each Claude turn so type
errors surface as feedback before the next message.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00

138 lines
4.2 KiB
TypeScript

import { useState, useEffect, useCallback } from "react";
export type NotificationMode = "my_turn" | "all_picks";
function getEnabledKey(userId: string, seasonId: string) {
return `draftNotifications-${userId}-${seasonId}`;
}
function getModeKey(userId: string, seasonId: string) {
return `draftNotificationMode-${userId}-${seasonId}`;
}
export function useDraftNotifications(seasonId: string, userId: string) {
const [permissionState, setPermissionState] = useState<
NotificationPermission | "unsupported"
>("unsupported");
const [enabled, setEnabledState] = useState(false);
const [mode, setModeState] = useState<NotificationMode>("my_turn");
// Check browser support, restore persisted preferences, and watch for permission changes
useEffect(() => {
if (typeof window === "undefined" || !("Notification" in window)) {
return;
}
setPermissionState(Notification.permission);
// Restore preferences from localStorage only if permission is granted
if (Notification.permission === "granted") {
const storedEnabled = localStorage.getItem(getEnabledKey(userId, seasonId));
if (storedEnabled === "true") {
setEnabledState(true);
}
}
const storedMode = localStorage.getItem(getModeKey(userId, seasonId));
if (storedMode === "my_turn" || storedMode === "all_picks") {
setModeState(storedMode);
}
// Watch for the user revoking/granting permission in browser settings.
// Use an abort flag so that if the component unmounts before the promise
// resolves, the cleanup doesn't fail to clear onchange (permissionStatus
// would still be null at that point without the flag).
let aborted = false;
let permissionStatus: PermissionStatus | null = null;
let changeHandler: (() => void) | null = null;
navigator.permissions
.query({ name: "notifications" })
.then((status) => {
if (aborted) return;
permissionStatus = status;
changeHandler = () => {
setPermissionState(status.state as NotificationPermission);
// If permission was revoked, disable notifications
if (status.state !== "granted") {
setEnabledState(false);
}
};
status.addEventListener("change", changeHandler);
})
.catch(() => {
// Permissions API not available in all environments; silently ignore
});
return () => {
aborted = true;
if (permissionStatus && changeHandler) {
permissionStatus.removeEventListener("change", changeHandler);
}
};
}, [seasonId, userId]);
const setEnabled = useCallback(
async (value: boolean) => {
if (typeof window === "undefined" || !("Notification" in window)) return;
if (value) {
// Request permission if not yet granted
if (Notification.permission === "default") {
const result = await Notification.requestPermission();
setPermissionState(result);
if (result !== "granted") {
return;
}
} else if (Notification.permission === "denied") {
return;
}
setEnabledState(true);
localStorage.setItem(getEnabledKey(userId, seasonId), "true");
} else {
setEnabledState(false);
localStorage.setItem(getEnabledKey(userId, seasonId), "false");
}
},
[userId, seasonId]
);
const setMode = useCallback(
(value: NotificationMode) => {
setModeState(value);
localStorage.setItem(getModeKey(userId, seasonId), value);
},
[userId, seasonId]
);
const sendNotification = useCallback(
(title: string, body: string) => {
if (
!enabled ||
typeof window === "undefined" ||
!("Notification" in window) ||
Notification.permission !== "granted" ||
typeof document === "undefined" ||
!document.hidden
) {
return;
}
const n = new Notification(title, {
body,
tag: `draft-${seasonId}`,
});
n.addEventListener("click", () => window.focus());
},
[enabled, seasonId]
);
return {
permissionState,
enabled,
setEnabled,
mode,
setMode,
sendNotification,
};
}