mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
Modernize ESLint setup to v10 with defineConfig
Replaces the deprecated `tseslint.config(...)` helper with ESLint core's
`defineConfig()` (available since ESLint 9.22, recommended in 10.x) and
upgrades the lint stack to the latest majors:
eslint 9.39 -> 10.2
@eslint/js 10.0 -> 10.0
typescript-eslint 8.0 -> 8.59
eslint-plugin-react-hooks 5.1 -> 7.1
eslint-plugin-react-refresh 0.4 -> 0.5
@html-eslint/{eslint-plugin,parser} 0.41 -> 0.59
globals 15.9 -> 17.5
Config changes:
- Use `defineConfig` + `globalIgnores()` instead of `tseslint.config`.
- Adopt `reactHooks.configs.flat.recommended` (adds React Compiler rules:
purity, refs, set-state-in-effect, etc.).
- Adopt `reactRefresh.configs.vite` (matches the Vite setup exactly).
- Adopt `@html-eslint` `flat/recommended` (adds indent, quotes,
use-baseline, require-closing-tags, etc.).
- Disable `@html-eslint/use-baseline` for the `rel="manifest"` false
positive.
Custom rule fixes for ESLint 10:
- `context.getSourceCode()` -> `context.sourceCode`
- `context.getFilename()` -> `context.filename`
Code fixes for the stricter new presets:
- NostrProvider: lazy-init NPool via `useState(() => new NPool(...))` and
move `ref.current = x` assignments into effects to satisfy the new
`react-hooks/refs` rule.
- useIsMobile: drop the redundant setState-in-effect by initialising
`useState` from the media query synchronously.
- AuthDialog: move `loginRef.current = login` into an effect.
- sidebar.tsx: derive skeleton width from `useId()` instead of
`Math.random()` so the render is pure.
- index.html: reindent to 4 spaces to satisfy `@html-eslint/indent`.
- .agents/skills/**: add `{ cause: err }` to `throw new Error(...)` calls
inside catch blocks (new `preserve-caught-error` rule) and a handful
of targeted `eslint-disable` comments for legitimate external-system
sync / state-reset-on-prop-change patterns.
The six intentional template failures (missing manifest, missing title /
description / OG tags, two FIXME comments) are unchanged -- they're the
template's way of nudging downstream users to fill the site in.
Re: "someday maybe tseslint won't be needed" -- still in the future.
ESLint 10 now loads `eslint.config.ts` natively (via jiti or Node's
`--experimental-strip-types`), but that only parses the config file. For
linting .ts/.tsx source you still need @typescript-eslint/parser and its
rules, which the `typescript-eslint` package bundles together. So the
"typescript" prefix is gone from rule names in practice, but the package
stays.
This commit is contained in:
16 files changed
+939
-587
No files matched your search
@@ -204,7 +204,7 @@ export function useShakespeare() {
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
throw new Error(errorMessage, { cause: err });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -302,7 +302,7 @@ export function useShakespeare() {
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
throw new Error(errorMessage, { cause: err });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -351,7 +351,7 @@ export function useShakespeare() {
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
throw new Error(errorMessage, { cause: err });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
@@ -59,7 +59,9 @@ export function useSecureLocalStorage<T>(
|
||||
// Track the most-recently-requested key so stale async reads don't clobber
|
||||
// state after the caller swapped to a different key.
|
||||
const currentKeyRef = useRef(key);
|
||||
currentKeyRef.current = key;
|
||||
useEffect(() => {
|
||||
currentKeyRef.current = key;
|
||||
}, [key]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -87,6 +89,9 @@ export function useSecureLocalStorage<T>(
|
||||
}
|
||||
}
|
||||
|
||||
// Reset `ready` before kicking off the new async load — this is a
|
||||
// deliberate external-system sync pattern.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setReady(false);
|
||||
load();
|
||||
|
||||
|
||||
@@ -251,6 +251,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setComment('Zapped with MKStack!');
|
||||
}
|
||||
}, [target]);
|
||||
@@ -312,6 +313,10 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Reset dialog state when opened/closed. The canonical React pattern
|
||||
// for this is a `key` prop on the caller, but the dialog's public API
|
||||
// is a simple open/close boolean.
|
||||
/* eslint-disable react-hooks/set-state-in-effect */
|
||||
if (open) {
|
||||
setAmount(100);
|
||||
setInvoice(null);
|
||||
@@ -324,6 +329,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
setCopied(false);
|
||||
setQrCodeUrl('');
|
||||
}
|
||||
/* eslint-enable react-hooks/set-state-in-effect */
|
||||
}, [open, setInvoice]);
|
||||
|
||||
const handleZap = () => {
|
||||
|
||||
@@ -170,7 +170,7 @@ export function useNWCInternal() {
|
||||
client = new LN(connection.connectionString);
|
||||
} catch (error) {
|
||||
console.error('Failed to create NWC client:', error);
|
||||
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -194,17 +194,17 @@ export function useNWCInternal() {
|
||||
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('timeout')) {
|
||||
throw new Error('Payment timed out. Please try again.');
|
||||
throw new Error('Payment timed out. Please try again.', { cause: error });
|
||||
} else if (error.message.includes('insufficient')) {
|
||||
throw new Error('Insufficient balance in connected wallet.');
|
||||
throw new Error('Insufficient balance in connected wallet.', { cause: error });
|
||||
} else if (error.message.includes('invalid')) {
|
||||
throw new Error('Invalid invoice or connection. Please check your wallet.');
|
||||
throw new Error('Invalid invoice or connection. Please check your wallet.', { cause: error });
|
||||
} else {
|
||||
throw new Error(`Payment failed: ${error.message}`);
|
||||
throw new Error(`Payment failed: ${error.message}`, { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Payment failed with unknown error');
|
||||
throw new Error('Payment failed with unknown error', { cause: error });
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -25,8 +25,12 @@ export function RelayListManager() {
|
||||
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
|
||||
const [newRelayUrl, setNewRelayUrl] = useState('');
|
||||
|
||||
// Sync local state with config when it changes (e.g., from NostrProvider sync)
|
||||
// Sync local state with config when it changes (e.g., from NostrProvider sync).
|
||||
// This is a legitimate "mirror external source of truth" pattern: the local
|
||||
// `relays` state is what the UI edits optimistically, and we need to reset
|
||||
// it when the authoritative config changes from outside.
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setRelays(config.relayMetadata.relays);
|
||||
}, [config.relayMetadata.relays]);
|
||||
|
||||
@@ -107,6 +111,8 @@ export function RelayListManager() {
|
||||
};
|
||||
|
||||
const saveRelays = (newRelays: Relay[]) => {
|
||||
// Only called from event handlers, not during render, so Date.now() is safe.
|
||||
// eslint-disable-next-line react-hooks/purity
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Update local config
|
||||
|
||||
@@ -19,7 +19,7 @@ export default {
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.getSourceCode();
|
||||
const { sourceCode } = context;
|
||||
|
||||
return {
|
||||
Program() {
|
||||
|
||||
@@ -18,8 +18,8 @@ export default {
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
const { filename } = context;
|
||||
|
||||
// Only run this rule on HTML files
|
||||
if (!filename.endsWith('.html')) {
|
||||
return {};
|
||||
@@ -27,7 +27,7 @@ export default {
|
||||
|
||||
return {
|
||||
Program(node) {
|
||||
const sourceCode = context.getSourceCode();
|
||||
const { sourceCode } = context;
|
||||
const htmlContent = sourceCode.getText();
|
||||
|
||||
// Check for manifest link tag in HTML
|
||||
|
||||
+26
-33
@@ -1,74 +1,67 @@
|
||||
// @ts-check
|
||||
import js from "@eslint/js";
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import globals from "globals";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
import reactRefresh from "eslint-plugin-react-refresh";
|
||||
import tseslint from "typescript-eslint";
|
||||
import htmlEslint from "@html-eslint/eslint-plugin";
|
||||
import htmlParser from "@html-eslint/parser";
|
||||
import customRules from "./eslint-rules/index.js";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist"] },
|
||||
export default defineConfig(
|
||||
globalIgnores(["dist"]),
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
name: "app/ts",
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
linterOptions: {
|
||||
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
|
||||
reportUnusedDisableDirectives: "error",
|
||||
},
|
||||
plugins: {
|
||||
"react-hooks": reactHooks,
|
||||
"react-refresh": reactRefresh,
|
||||
"custom": customRules,
|
||||
custom: customRules,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
"react-refresh/only-export-components": [
|
||||
"warn",
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
"argsIgnorePattern": "^_",
|
||||
"varsIgnorePattern": "^_",
|
||||
"ignoreRestSiblings": true,
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
ignoreRestSiblings: true,
|
||||
},
|
||||
],
|
||||
"custom/no-placeholder-comments": "error",
|
||||
"no-warning-comments": [
|
||||
"error",
|
||||
{ terms: ["fixme"] },
|
||||
],
|
||||
"no-warning-comments": ["error", { terms: ["fixme"] }],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "app/html",
|
||||
files: ["**/*.html"],
|
||||
extends: [htmlEslint.configs["flat/recommended"]],
|
||||
plugins: {
|
||||
"@html-eslint": htmlEslint,
|
||||
"custom": customRules,
|
||||
},
|
||||
languageOptions: {
|
||||
parser: htmlParser,
|
||||
custom: customRules,
|
||||
},
|
||||
rules: {
|
||||
"@html-eslint/require-title": "error",
|
||||
"@html-eslint/require-meta-charset": "error",
|
||||
"@html-eslint/require-meta-description": "error",
|
||||
"@html-eslint/require-meta-viewport": "error",
|
||||
"@html-eslint/require-open-graph-protocol": [
|
||||
"error",
|
||||
[
|
||||
"og:type",
|
||||
"og:title",
|
||||
"og:description",
|
||||
],
|
||||
["og:type", "og:title", "og:description"],
|
||||
],
|
||||
// The manifest link below intentionally uses `rel="manifest"`; the
|
||||
// baseline data currently flags this attribute value as not widely
|
||||
// available, which is a false positive for our use case.
|
||||
"@html-eslint/use-baseline": "off",
|
||||
"custom/no-inline-script": "error",
|
||||
"custom/require-webmanifest": "error",
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
+10
-10
@@ -1,13 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+771
-446
File diff suppressed because it is too large.
Load diff
+8
-8
@@ -38,9 +38,9 @@
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.9.0",
|
||||
"@html-eslint/eslint-plugin": "^0.41.0",
|
||||
"@html-eslint/parser": "^0.41.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@html-eslint/eslint-plugin": "^0.59.0",
|
||||
"@html-eslint/parser": "^0.59.0",
|
||||
"@tailwindcss/vite": "^4.2.4",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
@@ -49,14 +49,14 @@
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"eslint": "^9.9.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.9",
|
||||
"globals": "^15.9.0",
|
||||
"eslint": "^10.2.1",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"tailwindcss": "^4.2.4",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"typescript-eslint": "^8.59.0",
|
||||
"vite": "^8.0.10",
|
||||
"vitest": "^4.1.2"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useMemo, useRef } from 'react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { type NostrSigner, NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
|
||||
import { NostrContext } from '@nostrify/react';
|
||||
import { NUser, useNostrLogin } from '@nostrify/react/login';
|
||||
@@ -16,17 +16,70 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Create NPool instance only once
|
||||
const pool = useRef<NPool | undefined>(undefined);
|
||||
|
||||
// Use refs so the pool always has the latest data
|
||||
const relayMetadata = useRef(config.relayMetadata);
|
||||
// Use refs so the pool callbacks always see the latest data without
|
||||
// recreating the pool. The refs are written from effects (never during
|
||||
// render) to satisfy React's purity rules.
|
||||
const relayMetadataRef = useRef(config.relayMetadata);
|
||||
|
||||
// Stable ref to the current user's signer for NIP-42 AUTH.
|
||||
// The `open()` callback reads from this ref when a relay sends an AUTH
|
||||
// challenge, so it always uses the latest signer without recreating the pool.
|
||||
const signerRef = useRef<NostrSigner | undefined>(undefined);
|
||||
|
||||
// Lazily create the pool once, via useState's initializer. This keeps
|
||||
// the render body pure (no ref writes) while guaranteeing a single
|
||||
// NPool instance per provider. The initializer runs exactly once at
|
||||
// mount, so reading refs inside its closures is safe.
|
||||
// eslint-disable-next-line react-hooks/refs
|
||||
const [pool] = useState<NPool>(() => new NPool({
|
||||
open(url: string) {
|
||||
return new NRelay1(url, {
|
||||
// NIP-42: Respond to relay AUTH challenges by signing a kind
|
||||
// 22242 ephemeral event with the current user's signer.
|
||||
auth: async (challenge: string) => {
|
||||
const signer = signerRef.current;
|
||||
if (!signer) {
|
||||
throw new Error('AUTH failed: no signer available (user not logged in)');
|
||||
}
|
||||
return signer.signEvent({
|
||||
kind: 22242,
|
||||
content: '',
|
||||
tags: [
|
||||
['relay', url],
|
||||
['challenge', challenge],
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
},
|
||||
});
|
||||
},
|
||||
reqRouter(filters: NostrFilter[]) {
|
||||
const routes = new Map<string, NostrFilter[]>();
|
||||
|
||||
// Route to all read relays
|
||||
const readRelays = relayMetadataRef.current.relays
|
||||
.filter(r => r.read)
|
||||
.map(r => r.url);
|
||||
|
||||
for (const url of readRelays) {
|
||||
routes.set(url, filters);
|
||||
}
|
||||
|
||||
return routes;
|
||||
},
|
||||
eventRouter(_event: NostrEvent) {
|
||||
// Get write relays from metadata
|
||||
const writeRelays = relayMetadataRef.current.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
|
||||
const allRelays = new Set<string>(writeRelays);
|
||||
|
||||
return [...allRelays];
|
||||
},
|
||||
eoseTimeout: 200,
|
||||
}));
|
||||
|
||||
// Derive the current signer from the active login. This mirrors the
|
||||
// logic in useCurrentUser but avoids a circular dependency (useCurrentUser
|
||||
// depends on NostrContext which we are providing here).
|
||||
@@ -38,10 +91,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
case 'nsec':
|
||||
return NUser.fromNsecLogin(currentLogin).signer;
|
||||
case 'bunker':
|
||||
// pool.current is guaranteed to exist here: the pool is created
|
||||
// synchronously during the first render (below), and useMemo runs
|
||||
// after the render body has executed.
|
||||
return NUser.fromBunkerLogin(currentLogin, pool.current!).signer;
|
||||
return NUser.fromBunkerLogin(currentLogin, pool).signer;
|
||||
case 'extension':
|
||||
return NUser.fromExtensionLogin(currentLogin).signer;
|
||||
default:
|
||||
@@ -50,74 +100,27 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}, [currentLogin]);
|
||||
}, [currentLogin, pool]);
|
||||
|
||||
// Keep the ref in sync so the AUTH callback always sees the latest signer.
|
||||
signerRef.current = currentSigner;
|
||||
|
||||
// Invalidate Nostr queries when relay metadata changes
|
||||
// Writing refs from an effect (not during render) satisfies purity rules.
|
||||
useEffect(() => {
|
||||
relayMetadata.current = config.relayMetadata;
|
||||
signerRef.current = currentSigner;
|
||||
}, [currentSigner]);
|
||||
|
||||
// Invalidate Nostr queries when relay metadata changes.
|
||||
useEffect(() => {
|
||||
relayMetadataRef.current = config.relayMetadata;
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
||||
}, [config.relayMetadata, queryClient]);
|
||||
|
||||
// Initialize NPool only once
|
||||
if (!pool.current) {
|
||||
pool.current = new NPool({
|
||||
open(url: string) {
|
||||
return new NRelay1(url, {
|
||||
// NIP-42: Respond to relay AUTH challenges by signing a kind
|
||||
// 22242 ephemeral event with the current user's signer.
|
||||
auth: async (challenge: string) => {
|
||||
const signer = signerRef.current;
|
||||
if (!signer) {
|
||||
throw new Error('AUTH failed: no signer available (user not logged in)');
|
||||
}
|
||||
return signer.signEvent({
|
||||
kind: 22242,
|
||||
content: '',
|
||||
tags: [
|
||||
['relay', url],
|
||||
['challenge', challenge],
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
},
|
||||
});
|
||||
},
|
||||
reqRouter(filters: NostrFilter[]) {
|
||||
const routes = new Map<string, NostrFilter[]>();
|
||||
|
||||
// Route to all read relays
|
||||
const readRelays = relayMetadata.current.relays
|
||||
.filter(r => r.read)
|
||||
.map(r => r.url);
|
||||
|
||||
for (const url of readRelays) {
|
||||
routes.set(url, filters);
|
||||
}
|
||||
|
||||
return routes;
|
||||
},
|
||||
eventRouter(_event: NostrEvent) {
|
||||
// Get write relays from metadata
|
||||
const writeRelays = relayMetadata.current.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
|
||||
const allRelays = new Set<string>(writeRelays);
|
||||
|
||||
return [...allRelays];
|
||||
},
|
||||
eoseTimeout: 200,
|
||||
});
|
||||
}
|
||||
const contextValue = useMemo(() => ({ nostr: pool }), [pool]);
|
||||
|
||||
return (
|
||||
<NostrContext.Provider value={{ nostr: pool.current }}>
|
||||
<NostrContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</NostrContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export default NostrProvider;
|
||||
export default NostrProvider;
|
||||
@@ -98,7 +98,9 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
|
||||
const login = useLoginActions();
|
||||
// Stable ref so the nostrconnect effect doesn't restart on every render.
|
||||
const loginRef = useRef(login);
|
||||
loginRef.current = login;
|
||||
useEffect(() => {
|
||||
loginRef.current = login;
|
||||
}, [login]);
|
||||
|
||||
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
@@ -110,8 +112,13 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
|
||||
const hasExtension = typeof window !== 'undefined' && 'nostr' in window;
|
||||
|
||||
// Reset state when the dialog closes.
|
||||
// This is the "reset state when a prop changes" pattern; the usual
|
||||
// React-preferred alternative is a `key` prop on the caller, but the
|
||||
// public API of this component is a simple open/close boolean, so we
|
||||
// reset here. The multiple setState calls are intentional.
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
/* eslint-disable react-hooks/set-state-in-effect */
|
||||
setStep('welcome');
|
||||
setNsec('');
|
||||
setLoginNsec('');
|
||||
@@ -128,6 +135,7 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
|
||||
setUriCopied(false);
|
||||
setShowBunkerInput(false);
|
||||
setBunkerUri('');
|
||||
/* eslint-enable react-hooks/set-state-in-effect */
|
||||
abortControllerRef.current?.abort();
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
|
||||
@@ -93,6 +93,9 @@ function Carousel({
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) return
|
||||
// Prime state from the external carousel API, then subscribe for updates.
|
||||
// This is the canonical external-system sync pattern for useEffect.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
|
||||
@@ -568,10 +568,14 @@ function SidebarMenuSkeleton({
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
// Deterministic random-looking width derived from useId so the skeleton
|
||||
// is stable across re-renders but varies between instances.
|
||||
const id = React.useId()
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
let h = 0
|
||||
for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) | 0
|
||||
return `${(Math.abs(h) % 40) + 50}%`
|
||||
}, [id])
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react"
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
|
||||
export function useIsMobile(): boolean {
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
const [isMobile, setIsMobile] = useState(() => window.innerWidth < MOBILE_BREAKPOINT);
|
||||
|
||||
useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
@@ -11,9 +11,8 @@ export function useIsMobile(): boolean {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
}
|
||||
mql.addEventListener("change", onChange);
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
return () => mql.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
|
||||
return !!isMobile;
|
||||
return isMobile;
|
||||
}
|
||||
Reference in new issue
Block a user