Compare commits
155
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8e96c2e56 | ||
|
|
57fb7f1583 | ||
|
|
083e6f566a | ||
|
|
cc2d30eb2b | ||
|
|
17e17fea8f | ||
|
|
32a26a7849 | ||
|
|
52bcabcd22 | ||
|
|
b381981cec | ||
|
|
26b5a7708c | ||
|
|
0c6b76d332 | ||
|
|
bf39419746 | ||
|
|
a31dea9c16 | ||
|
|
1353ac5678 | ||
|
|
a177f18eb4 | ||
|
|
ef757e4a4a | ||
|
|
9c421e0f99 | ||
|
|
3f4f95a925 | ||
|
|
5aab0a2436 | ||
|
|
86fce11bfe | ||
|
|
26fd570e53 | ||
|
|
196fa1a173 | ||
|
|
42146c0ac7 | ||
|
|
9bd9dae2d3 | ||
|
|
bbffa428bc | ||
|
|
ae851e0a20 | ||
|
|
71177d6076 | ||
|
|
2ddaba948a | ||
|
|
645ac31f4b | ||
|
|
84b58e84de | ||
|
|
15d99ed837 | ||
|
|
315b339c52 | ||
|
|
d1119beae7 | ||
|
|
1476e763dc | ||
|
|
6c37b60967 | ||
|
|
b0cfc00bd0 | ||
|
|
0d013f6356 | ||
|
|
30ea59b62f | ||
|
|
970da40a28 | ||
|
|
c3edd6efad | ||
|
|
612f84a863 | ||
|
|
6e9ea3e906 | ||
|
|
d4e024c312 | ||
|
|
cc6e1c6542 | ||
|
|
eb15d18676 | ||
|
|
1bbc0b5bb5 | ||
|
|
9ec1fc6c20 | ||
|
|
516a2af892 | ||
|
|
876eaa725a | ||
|
|
b3a0f1e26a | ||
|
|
d445bc00c4 | ||
|
|
7feb3e4e14 | ||
|
|
d8fdda0edf | ||
|
|
8ad4839304 | ||
|
|
6f6a731da9 | ||
|
|
dcc47bba03 | ||
|
|
8f62d0bdde | ||
|
|
c936105455 | ||
|
|
94fed02d72 | ||
|
|
d006c4147f | ||
|
|
ef455e5482 | ||
|
|
01b06b58e4 | ||
|
|
ea14ae1103 | ||
|
|
47d8c7bddc | ||
|
|
564652d9b4 | ||
|
|
2553b32cf4 | ||
|
|
d35a3338f6 | ||
|
|
a8c604b659 | ||
|
|
965dbdf00b | ||
|
|
c7a95dfbe8 | ||
|
|
027608b9d6 | ||
|
|
e39db2ee5e | ||
|
|
144218b4d7 | ||
|
|
3c73ba7f7f | ||
|
|
cad49a7a3f | ||
|
|
98b8af5332 | ||
|
|
4dedbcfc55 | ||
|
|
d65eba3036 | ||
|
|
c2f81db900 | ||
|
|
976c8482ce | ||
|
|
054f411458 | ||
|
|
98244608f1 | ||
|
|
400f8e288d | ||
|
|
017f66e59c | ||
|
|
f2e88b57f0 | ||
|
|
a15df65ef1 | ||
|
|
7825e1cd1f | ||
|
|
4172a97716 | ||
|
|
65d9d51040 | ||
|
|
2f3a352ae0 | ||
|
|
6f4ca098bf | ||
|
|
079af5b864 | ||
|
|
df1862d6bc | ||
|
|
1578ea9d67 | ||
|
|
7a4d344b99 | ||
|
|
1121f948d8 | ||
|
|
c89037293b | ||
|
|
62d75de88c | ||
|
|
4dbab51f04 | ||
|
|
295b2bccef | ||
|
|
2a04858b37 | ||
|
|
e7dfa206d1 | ||
|
|
f9e3d38140 | ||
|
|
c2a57a12f9 | ||
|
|
c8ae154689 | ||
|
|
0a5ea654c3 | ||
|
|
b75a5d902a | ||
|
|
210869a9fd | ||
|
|
b2cf31411c | ||
|
|
0de09e34d9 | ||
|
|
03bf3390de | ||
|
|
b410910a0d | ||
|
|
1e4011c93c | ||
|
|
3ae9e80058 | ||
|
|
eb2aeae8c3 | ||
|
|
6624b79f8f | ||
|
|
ac6a121d94 | ||
|
|
e43c11a44a | ||
|
|
b6559af1be | ||
|
|
41f56f66e7 | ||
|
|
3405aeb9b8 | ||
|
|
5d5172815a | ||
|
|
95d0af04f9 | ||
|
|
9b2497dd57 | ||
|
|
0f6841f9f5 | ||
|
|
875799a299 | ||
|
|
5ae7cacda6 | ||
|
|
29b1d8e0e5 | ||
|
|
52a58a8888 | ||
|
|
978e2d5212 | ||
|
|
5d4a4eefb4 | ||
|
|
e2b2cc5ed4 | ||
|
|
292dd88fb4 | ||
|
|
45fc84f23e | ||
|
|
cdcc80f178 | ||
|
|
91a9dc1b43 | ||
|
|
d7504748b3 | ||
|
|
844fd1f0a2 | ||
|
|
862d8f820f | ||
|
|
02433f85ad | ||
|
|
859f4b4a6a | ||
|
|
3fa622a9b7 | ||
|
|
ede83d3373 | ||
|
|
715f2c83f4 | ||
|
|
119c47dd46 | ||
|
|
5a0a6a6d60 | ||
|
|
6acbff04ea | ||
|
|
df9534cb72 | ||
|
|
41c9892d09 | ||
|
|
0bbaf6683f | ||
|
|
b22ee77134 | ||
|
|
51851f6277 | ||
|
|
06efef9d4b | ||
|
|
1794cd35f3 | ||
|
|
e6b8adf73e | ||
|
|
d721f39813 |
@@ -0,0 +1,133 @@
|
||||
---
|
||||
name: find-skills
|
||||
description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
|
||||
---
|
||||
|
||||
# Find Skills
|
||||
|
||||
This skill helps you discover and install skills from the open agent skills ecosystem.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use this skill when the user:
|
||||
|
||||
- Asks "how do I do X" where X might be a common task with an existing skill
|
||||
- Says "find a skill for X" or "is there a skill for X"
|
||||
- Asks "can you do X" where X is a specialized capability
|
||||
- Expresses interest in extending agent capabilities
|
||||
- Wants to search for tools, templates, or workflows
|
||||
- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.)
|
||||
|
||||
## What is the Skills CLI?
|
||||
|
||||
The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools.
|
||||
|
||||
**Key commands:**
|
||||
|
||||
- `npx skills find [query]` - Search for skills interactively or by keyword
|
||||
- `npx skills add <package>` - Install a skill from GitHub or other sources
|
||||
- `npx skills check` - Check for skill updates
|
||||
- `npx skills update` - Update all installed skills
|
||||
|
||||
**Browse skills at:** https://skills.sh/
|
||||
|
||||
## How to Help Users Find Skills
|
||||
|
||||
### Step 1: Understand What They Need
|
||||
|
||||
When a user asks for help with something, identify:
|
||||
|
||||
1. The domain (e.g., React, testing, design, deployment)
|
||||
2. The specific task (e.g., writing tests, creating animations, reviewing PRs)
|
||||
3. Whether this is a common enough task that a skill likely exists
|
||||
|
||||
### Step 2: Search for Skills
|
||||
|
||||
Run the find command with a relevant query:
|
||||
|
||||
```bash
|
||||
npx skills find [query]
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
- User asks "how do I make my React app faster?" → `npx skills find react performance`
|
||||
- User asks "can you help me with PR reviews?" → `npx skills find pr review`
|
||||
- User asks "I need to create a changelog" → `npx skills find changelog`
|
||||
|
||||
The command will return results like:
|
||||
|
||||
```
|
||||
Install with npx skills add <owner/repo@skill>
|
||||
|
||||
vercel-labs/agent-skills@vercel-react-best-practices
|
||||
└ https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices
|
||||
```
|
||||
|
||||
### Step 3: Present Options to the User
|
||||
|
||||
When you find relevant skills, present them to the user with:
|
||||
|
||||
1. The skill name and what it does
|
||||
2. The install command they can run
|
||||
3. A link to learn more at skills.sh
|
||||
|
||||
Example response:
|
||||
|
||||
```
|
||||
I found a skill that might help! The "vercel-react-best-practices" skill provides
|
||||
React and Next.js performance optimization guidelines from Vercel Engineering.
|
||||
|
||||
To install it:
|
||||
npx skills add vercel-labs/agent-skills@vercel-react-best-practices
|
||||
|
||||
Learn more: https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices
|
||||
```
|
||||
|
||||
### Step 4: Offer to Install
|
||||
|
||||
If the user wants to proceed, you can install the skill for them:
|
||||
|
||||
```bash
|
||||
npx skills add <owner/repo@skill> -g -y
|
||||
```
|
||||
|
||||
The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts.
|
||||
|
||||
## Common Skill Categories
|
||||
|
||||
When searching, consider these common categories:
|
||||
|
||||
| Category | Example Queries |
|
||||
| --------------- | ---------------------------------------- |
|
||||
| Web Development | react, nextjs, typescript, css, tailwind |
|
||||
| Testing | testing, jest, playwright, e2e |
|
||||
| DevOps | deploy, docker, kubernetes, ci-cd |
|
||||
| Documentation | docs, readme, changelog, api-docs |
|
||||
| Code Quality | review, lint, refactor, best-practices |
|
||||
| Design | ui, ux, design-system, accessibility |
|
||||
| Productivity | workflow, automation, git |
|
||||
|
||||
## Tips for Effective Searches
|
||||
|
||||
1. **Use specific keywords**: "react testing" is better than just "testing"
|
||||
2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd"
|
||||
3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills`
|
||||
|
||||
## When No Skills Are Found
|
||||
|
||||
If no relevant skills exist:
|
||||
|
||||
1. Acknowledge that no existing skill was found
|
||||
2. Offer to help with the task directly using your general capabilities
|
||||
3. Suggest the user could create their own skill with `npx skills init`
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
I searched for skills related to "xyz" but didn't find any matches.
|
||||
I can still help you with this task directly! Would you like me to proceed?
|
||||
|
||||
If this is something you do often, you could create your own skill:
|
||||
npx skills init my-xyz-skill
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,136 @@
|
||||
---
|
||||
name: vercel-react-best-practices
|
||||
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# Vercel React Best Practices
|
||||
|
||||
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 57 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
- Writing new React components or Next.js pages
|
||||
- Implementing data fetching (client or server-side)
|
||||
- Reviewing code for performance issues
|
||||
- Refactoring existing React/Next.js code
|
||||
- Optimizing bundle size or load times
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
|----------|----------|--------|--------|
|
||||
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
|
||||
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
|
||||
| 3 | Server-Side Performance | HIGH | `server-` |
|
||||
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
||||
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
|
||||
| 6 | Rendering Performance | MEDIUM | `rendering-` |
|
||||
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
||||
| 8 | Advanced Patterns | LOW | `advanced-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Eliminating Waterfalls (CRITICAL)
|
||||
|
||||
- `async-defer-await` - Move await into branches where actually used
|
||||
- `async-parallel` - Use Promise.all() for independent operations
|
||||
- `async-dependencies` - Use better-all for partial dependencies
|
||||
- `async-api-routes` - Start promises early, await late in API routes
|
||||
- `async-suspense-boundaries` - Use Suspense to stream content
|
||||
|
||||
### 2. Bundle Size Optimization (CRITICAL)
|
||||
|
||||
- `bundle-barrel-imports` - Import directly, avoid barrel files
|
||||
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
|
||||
- `bundle-defer-third-party` - Load analytics/logging after hydration
|
||||
- `bundle-conditional` - Load modules only when feature is activated
|
||||
- `bundle-preload` - Preload on hover/focus for perceived speed
|
||||
|
||||
### 3. Server-Side Performance (HIGH)
|
||||
|
||||
- `server-auth-actions` - Authenticate server actions like API routes
|
||||
- `server-cache-react` - Use React.cache() for per-request deduplication
|
||||
- `server-cache-lru` - Use LRU cache for cross-request caching
|
||||
- `server-dedup-props` - Avoid duplicate serialization in RSC props
|
||||
- `server-serialization` - Minimize data passed to client components
|
||||
- `server-parallel-fetching` - Restructure components to parallelize fetches
|
||||
- `server-after-nonblocking` - Use after() for non-blocking operations
|
||||
|
||||
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
|
||||
|
||||
- `client-swr-dedup` - Use SWR for automatic request deduplication
|
||||
- `client-event-listeners` - Deduplicate global event listeners
|
||||
- `client-passive-event-listeners` - Use passive listeners for scroll
|
||||
- `client-localstorage-schema` - Version and minimize localStorage data
|
||||
|
||||
### 5. Re-render Optimization (MEDIUM)
|
||||
|
||||
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
|
||||
- `rerender-memo` - Extract expensive work into memoized components
|
||||
- `rerender-memo-with-default-value` - Hoist default non-primitive props
|
||||
- `rerender-dependencies` - Use primitive dependencies in effects
|
||||
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
|
||||
- `rerender-derived-state-no-effect` - Derive state during render, not effects
|
||||
- `rerender-functional-setstate` - Use functional setState for stable callbacks
|
||||
- `rerender-lazy-state-init` - Pass function to useState for expensive values
|
||||
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
|
||||
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
|
||||
- `rerender-transitions` - Use startTransition for non-urgent updates
|
||||
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
|
||||
|
||||
### 6. Rendering Performance (MEDIUM)
|
||||
|
||||
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
|
||||
- `rendering-content-visibility` - Use content-visibility for long lists
|
||||
- `rendering-hoist-jsx` - Extract static JSX outside components
|
||||
- `rendering-svg-precision` - Reduce SVG coordinate precision
|
||||
- `rendering-hydration-no-flicker` - Use inline script for client-only data
|
||||
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
|
||||
- `rendering-activity` - Use Activity component for show/hide
|
||||
- `rendering-conditional-render` - Use ternary, not && for conditionals
|
||||
- `rendering-usetransition-loading` - Prefer useTransition for loading state
|
||||
|
||||
### 7. JavaScript Performance (LOW-MEDIUM)
|
||||
|
||||
- `js-batch-dom-css` - Group CSS changes via classes or cssText
|
||||
- `js-index-maps` - Build Map for repeated lookups
|
||||
- `js-cache-property-access` - Cache object properties in loops
|
||||
- `js-cache-function-results` - Cache function results in module-level Map
|
||||
- `js-cache-storage` - Cache localStorage/sessionStorage reads
|
||||
- `js-combine-iterations` - Combine multiple filter/map into one loop
|
||||
- `js-length-check-first` - Check array length before expensive comparison
|
||||
- `js-early-exit` - Return early from functions
|
||||
- `js-hoist-regexp` - Hoist RegExp creation outside loops
|
||||
- `js-min-max-loop` - Use loop for min/max instead of sort
|
||||
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
|
||||
- `js-tosorted-immutable` - Use toSorted() for immutability
|
||||
|
||||
### 8. Advanced Patterns (LOW)
|
||||
|
||||
- `advanced-event-handler-refs` - Store event handlers in refs
|
||||
- `advanced-init-once` - Initialize app once per app load
|
||||
- `advanced-use-latest` - useLatest for stable callback refs
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/async-parallel.md
|
||||
rules/bundle-barrel-imports.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: Store Event Handlers in Refs
|
||||
impact: LOW
|
||||
impactDescription: stable subscriptions
|
||||
tags: advanced, hooks, refs, event-handlers, optimization
|
||||
---
|
||||
|
||||
## Store Event Handlers in Refs
|
||||
|
||||
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||
|
||||
**Incorrect (re-subscribes on every render):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, handler)
|
||||
return () => window.removeEventListener(event, handler)
|
||||
}, [event, handler])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (stable subscription):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const handlerRef = useRef(handler)
|
||||
useEffect(() => {
|
||||
handlerRef.current = handler
|
||||
}, [handler])
|
||||
|
||||
useEffect(() => {
|
||||
const listener = (e) => handlerRef.current(e)
|
||||
window.addEventListener(event, listener)
|
||||
return () => window.removeEventListener(event, listener)
|
||||
}, [event])
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react'
|
||||
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const onEvent = useEffectEvent(handler)
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, onEvent)
|
||||
return () => window.removeEventListener(event, onEvent)
|
||||
}, [event])
|
||||
}
|
||||
```
|
||||
|
||||
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
title: Initialize App Once, Not Per Mount
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids duplicate init in development
|
||||
tags: initialization, useEffect, app-startup, side-effects
|
||||
---
|
||||
|
||||
## Initialize App Once, Not Per Mount
|
||||
|
||||
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
|
||||
|
||||
**Incorrect (runs twice in dev, re-runs on remount):**
|
||||
|
||||
```tsx
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
loadFromStorage()
|
||||
checkAuthToken()
|
||||
}, [])
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (once per app load):**
|
||||
|
||||
```tsx
|
||||
let didInit = false
|
||||
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
if (didInit) return
|
||||
didInit = true
|
||||
loadFromStorage()
|
||||
checkAuthToken()
|
||||
}, [])
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: useEffectEvent for Stable Callback Refs
|
||||
impact: LOW
|
||||
impactDescription: prevents effect re-runs
|
||||
tags: advanced, hooks, useEffectEvent, refs, optimization
|
||||
---
|
||||
|
||||
## useEffectEvent for Stable Callback Refs
|
||||
|
||||
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
||||
|
||||
**Incorrect (effect re-runs on every callback change):**
|
||||
|
||||
```tsx
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearch(query), 300)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [query, onSearch])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (using React's useEffectEvent):**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react';
|
||||
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
const onSearchEvent = useEffectEvent(onSearch)
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearchEvent(query), 300)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [query])
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: Prevent Waterfall Chains in API Routes
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: api-routes, server-actions, waterfalls, parallelization
|
||||
---
|
||||
|
||||
## Prevent Waterfall Chains in API Routes
|
||||
|
||||
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||||
|
||||
**Incorrect (config waits for auth, data waits for both):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const session = await auth()
|
||||
const config = await fetchConfig()
|
||||
const data = await fetchData(session.user.id)
|
||||
return Response.json({ data, config })
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (auth and config start immediately):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const sessionPromise = auth()
|
||||
const configPromise = fetchConfig()
|
||||
const session = await sessionPromise
|
||||
const [config, data] = await Promise.all([
|
||||
configPromise,
|
||||
fetchData(session.user.id)
|
||||
])
|
||||
return Response.json({ data, config })
|
||||
}
|
||||
```
|
||||
|
||||
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Defer Await Until Needed
|
||||
impact: HIGH
|
||||
impactDescription: avoids blocking unused code paths
|
||||
tags: async, await, conditional, optimization
|
||||
---
|
||||
|
||||
## Defer Await Until Needed
|
||||
|
||||
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
||||
|
||||
**Incorrect (blocks both branches):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
const userData = await fetchUserData(userId)
|
||||
|
||||
if (skipProcessing) {
|
||||
// Returns immediately but still waited for userData
|
||||
return { skipped: true }
|
||||
}
|
||||
|
||||
// Only this branch uses userData
|
||||
return processUserData(userData)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (only blocks when needed):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
if (skipProcessing) {
|
||||
// Returns immediately without waiting
|
||||
return { skipped: true }
|
||||
}
|
||||
|
||||
// Fetch only when needed
|
||||
const userData = await fetchUserData(userId)
|
||||
return processUserData(userData)
|
||||
}
|
||||
```
|
||||
|
||||
**Another example (early return optimization):**
|
||||
|
||||
```typescript
|
||||
// Incorrect: always fetches permissions
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const permissions = await fetchPermissions(userId)
|
||||
const resource = await getResource(resourceId)
|
||||
|
||||
if (!resource) {
|
||||
return { error: 'Not found' }
|
||||
}
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: 'Forbidden' }
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions)
|
||||
}
|
||||
|
||||
// Correct: fetches only when needed
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const resource = await getResource(resourceId)
|
||||
|
||||
if (!resource) {
|
||||
return { error: 'Not found' }
|
||||
}
|
||||
|
||||
const permissions = await fetchPermissions(userId)
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: 'Forbidden' }
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions)
|
||||
}
|
||||
```
|
||||
|
||||
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
title: Dependency-Based Parallelization
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, dependencies, better-all
|
||||
---
|
||||
|
||||
## Dependency-Based Parallelization
|
||||
|
||||
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
||||
|
||||
**Incorrect (profile waits for config unnecessarily):**
|
||||
|
||||
```typescript
|
||||
const [user, config] = await Promise.all([
|
||||
fetchUser(),
|
||||
fetchConfig()
|
||||
])
|
||||
const profile = await fetchProfile(user.id)
|
||||
```
|
||||
|
||||
**Correct (config and profile run in parallel):**
|
||||
|
||||
```typescript
|
||||
import { all } from 'better-all'
|
||||
|
||||
const { user, config, profile } = await all({
|
||||
async user() { return fetchUser() },
|
||||
async config() { return fetchConfig() },
|
||||
async profile() {
|
||||
return fetchProfile((await this.$.user).id)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Alternative without extra dependencies:**
|
||||
|
||||
We can also create all the promises first, and do `Promise.all()` at the end.
|
||||
|
||||
```typescript
|
||||
const userPromise = fetchUser()
|
||||
const profilePromise = userPromise.then(user => fetchProfile(user.id))
|
||||
|
||||
const [user, config, profile] = await Promise.all([
|
||||
userPromise,
|
||||
fetchConfig(),
|
||||
profilePromise
|
||||
])
|
||||
```
|
||||
|
||||
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Promise.all() for Independent Operations
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, promises, waterfalls
|
||||
---
|
||||
|
||||
## Promise.all() for Independent Operations
|
||||
|
||||
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
||||
|
||||
**Incorrect (sequential execution, 3 round trips):**
|
||||
|
||||
```typescript
|
||||
const user = await fetchUser()
|
||||
const posts = await fetchPosts()
|
||||
const comments = await fetchComments()
|
||||
```
|
||||
|
||||
**Correct (parallel execution, 1 round trip):**
|
||||
|
||||
```typescript
|
||||
const [user, posts, comments] = await Promise.all([
|
||||
fetchUser(),
|
||||
fetchPosts(),
|
||||
fetchComments()
|
||||
])
|
||||
```
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
title: Strategic Suspense Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: faster initial paint
|
||||
tags: async, suspense, streaming, layout-shift
|
||||
---
|
||||
|
||||
## Strategic Suspense Boundaries
|
||||
|
||||
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
||||
|
||||
**Incorrect (wrapper blocked by data fetching):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const data = await fetchData() // Blocks entire page
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<div>
|
||||
<DataDisplay data={data} />
|
||||
</div>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The entire layout waits for data even though only the middle section needs it.
|
||||
|
||||
**Correct (wrapper shows immediately, data streams in):**
|
||||
|
||||
```tsx
|
||||
function Page() {
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<div>
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<DataDisplay />
|
||||
</Suspense>
|
||||
</div>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function DataDisplay() {
|
||||
const data = await fetchData() // Only blocks this component
|
||||
return <div>{data.content}</div>
|
||||
}
|
||||
```
|
||||
|
||||
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
||||
|
||||
**Alternative (share promise across components):**
|
||||
|
||||
```tsx
|
||||
function Page() {
|
||||
// Start fetch immediately, but don't await
|
||||
const dataPromise = fetchData()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<DataDisplay dataPromise={dataPromise} />
|
||||
<DataSummary dataPromise={dataPromise} />
|
||||
</Suspense>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||
const data = use(dataPromise) // Unwraps the promise
|
||||
return <div>{data.content}</div>
|
||||
}
|
||||
|
||||
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||
const data = use(dataPromise) // Reuses the same promise
|
||||
return <div>{data.summary}</div>
|
||||
}
|
||||
```
|
||||
|
||||
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
|
||||
|
||||
**When NOT to use this pattern:**
|
||||
|
||||
- Critical data needed for layout decisions (affects positioning)
|
||||
- SEO-critical content above the fold
|
||||
- Small, fast queries where suspense overhead isn't worth it
|
||||
- When you want to avoid layout shift (loading → content jump)
|
||||
|
||||
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
title: Avoid Barrel File Imports
|
||||
impact: CRITICAL
|
||||
impactDescription: 200-800ms import cost, slow builds
|
||||
tags: bundle, imports, tree-shaking, barrel-files, performance
|
||||
---
|
||||
|
||||
## Avoid Barrel File Imports
|
||||
|
||||
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
|
||||
|
||||
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
|
||||
|
||||
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
|
||||
|
||||
**Incorrect (imports entire library):**
|
||||
|
||||
```tsx
|
||||
import { Check, X, Menu } from 'lucide-react'
|
||||
// Loads 1,583 modules, takes ~2.8s extra in dev
|
||||
// Runtime cost: 200-800ms on every cold start
|
||||
|
||||
import { Button, TextField } from '@mui/material'
|
||||
// Loads 2,225 modules, takes ~4.2s extra in dev
|
||||
```
|
||||
|
||||
**Correct (imports only what you need):**
|
||||
|
||||
```tsx
|
||||
import Check from 'lucide-react/dist/esm/icons/check'
|
||||
import X from 'lucide-react/dist/esm/icons/x'
|
||||
import Menu from 'lucide-react/dist/esm/icons/menu'
|
||||
// Loads only 3 modules (~2KB vs ~1MB)
|
||||
|
||||
import Button from '@mui/material/Button'
|
||||
import TextField from '@mui/material/TextField'
|
||||
// Loads only what you use
|
||||
```
|
||||
|
||||
**Alternative (Next.js 13.5+):**
|
||||
|
||||
```js
|
||||
// next.config.js - use optimizePackageImports
|
||||
module.exports = {
|
||||
experimental: {
|
||||
optimizePackageImports: ['lucide-react', '@mui/material']
|
||||
}
|
||||
}
|
||||
|
||||
// Then you can keep the ergonomic barrel imports:
|
||||
import { Check, X, Menu } from 'lucide-react'
|
||||
// Automatically transformed to direct imports at build time
|
||||
```
|
||||
|
||||
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
||||
|
||||
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
|
||||
|
||||
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
title: Conditional Module Loading
|
||||
impact: HIGH
|
||||
impactDescription: loads large data only when needed
|
||||
tags: bundle, conditional-loading, lazy-loading
|
||||
---
|
||||
|
||||
## Conditional Module Loading
|
||||
|
||||
Load large data or modules only when a feature is activated.
|
||||
|
||||
**Example (lazy-load animation frames):**
|
||||
|
||||
```tsx
|
||||
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
|
||||
const [frames, setFrames] = useState<Frame[] | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled && !frames && typeof window !== 'undefined') {
|
||||
import('./animation-frames.js')
|
||||
.then(mod => setFrames(mod.frames))
|
||||
.catch(() => setEnabled(false))
|
||||
}
|
||||
}, [enabled, frames, setEnabled])
|
||||
|
||||
if (!frames) return <Skeleton />
|
||||
return <Canvas frames={frames} />
|
||||
}
|
||||
```
|
||||
|
||||
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Defer Non-Critical Third-Party Libraries
|
||||
impact: MEDIUM
|
||||
impactDescription: loads after hydration
|
||||
tags: bundle, third-party, analytics, defer
|
||||
---
|
||||
|
||||
## Defer Non-Critical Third-Party Libraries
|
||||
|
||||
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
||||
|
||||
**Incorrect (blocks initial bundle):**
|
||||
|
||||
```tsx
|
||||
import { Analytics } from '@vercel/analytics/react'
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (loads after hydration):**
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const Analytics = dynamic(
|
||||
() => import('@vercel/analytics/react').then(m => m.Analytics),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Dynamic Imports for Heavy Components
|
||||
impact: CRITICAL
|
||||
impactDescription: directly affects TTI and LCP
|
||||
tags: bundle, dynamic-import, code-splitting, next-dynamic
|
||||
---
|
||||
|
||||
## Dynamic Imports for Heavy Components
|
||||
|
||||
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
||||
|
||||
**Incorrect (Monaco bundles with main chunk ~300KB):**
|
||||
|
||||
```tsx
|
||||
import { MonacoEditor } from './monaco-editor'
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <MonacoEditor value={code} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (Monaco loads on demand):**
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const MonacoEditor = dynamic(
|
||||
() => import('./monaco-editor').then(m => m.MonacoEditor),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <MonacoEditor value={code} />
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Preload Based on User Intent
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces perceived latency
|
||||
tags: bundle, preload, user-intent, hover
|
||||
---
|
||||
|
||||
## Preload Based on User Intent
|
||||
|
||||
Preload heavy bundles before they're needed to reduce perceived latency.
|
||||
|
||||
**Example (preload on hover/focus):**
|
||||
|
||||
```tsx
|
||||
function EditorButton({ onClick }: { onClick: () => void }) {
|
||||
const preload = () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
void import('./monaco-editor')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onMouseEnter={preload}
|
||||
onFocus={preload}
|
||||
onClick={onClick}
|
||||
>
|
||||
Open Editor
|
||||
</button>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Example (preload when feature flag is enabled):**
|
||||
|
||||
```tsx
|
||||
function FlagsProvider({ children, flags }: Props) {
|
||||
useEffect(() => {
|
||||
if (flags.editorEnabled && typeof window !== 'undefined') {
|
||||
void import('./monaco-editor').then(mod => mod.init())
|
||||
}
|
||||
}, [flags.editorEnabled])
|
||||
|
||||
return <FlagsContext.Provider value={flags}>
|
||||
{children}
|
||||
</FlagsContext.Provider>
|
||||
}
|
||||
```
|
||||
|
||||
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Deduplicate Global Event Listeners
|
||||
impact: LOW
|
||||
impactDescription: single listener for N components
|
||||
tags: client, swr, event-listeners, subscription
|
||||
---
|
||||
|
||||
## Deduplicate Global Event Listeners
|
||||
|
||||
Use `useSWRSubscription()` to share global event listeners across component instances.
|
||||
|
||||
**Incorrect (N instances = N listeners):**
|
||||
|
||||
```tsx
|
||||
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.metaKey && e.key === key) {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
}, [key, callback])
|
||||
}
|
||||
```
|
||||
|
||||
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
|
||||
|
||||
**Correct (N instances = 1 listener):**
|
||||
|
||||
```tsx
|
||||
import useSWRSubscription from 'swr/subscription'
|
||||
|
||||
// Module-level Map to track callbacks per key
|
||||
const keyCallbacks = new Map<string, Set<() => void>>()
|
||||
|
||||
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||
// Register this callback in the Map
|
||||
useEffect(() => {
|
||||
if (!keyCallbacks.has(key)) {
|
||||
keyCallbacks.set(key, new Set())
|
||||
}
|
||||
keyCallbacks.get(key)!.add(callback)
|
||||
|
||||
return () => {
|
||||
const set = keyCallbacks.get(key)
|
||||
if (set) {
|
||||
set.delete(callback)
|
||||
if (set.size === 0) {
|
||||
keyCallbacks.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [key, callback])
|
||||
|
||||
useSWRSubscription('global-keydown', () => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.metaKey && keyCallbacks.has(e.key)) {
|
||||
keyCallbacks.get(e.key)!.forEach(cb => cb())
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
})
|
||||
}
|
||||
|
||||
function Profile() {
|
||||
// Multiple shortcuts will share the same listener
|
||||
useKeyboardShortcut('p', () => { /* ... */ })
|
||||
useKeyboardShortcut('k', () => { /* ... */ })
|
||||
// ...
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
title: Version and Minimize localStorage Data
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents schema conflicts, reduces storage size
|
||||
tags: client, localStorage, storage, versioning, data-minimization
|
||||
---
|
||||
|
||||
## Version and Minimize localStorage Data
|
||||
|
||||
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
// No version, stores everything, no error handling
|
||||
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
|
||||
const data = localStorage.getItem('userConfig')
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
const VERSION = 'v2'
|
||||
|
||||
function saveConfig(config: { theme: string; language: string }) {
|
||||
try {
|
||||
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
|
||||
} catch {
|
||||
// Throws in incognito/private browsing, quota exceeded, or disabled
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig() {
|
||||
try {
|
||||
const data = localStorage.getItem(`userConfig:${VERSION}`)
|
||||
return data ? JSON.parse(data) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Migration from v1 to v2
|
||||
function migrate() {
|
||||
try {
|
||||
const v1 = localStorage.getItem('userConfig:v1')
|
||||
if (v1) {
|
||||
const old = JSON.parse(v1)
|
||||
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
|
||||
localStorage.removeItem('userConfig:v1')
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
```
|
||||
|
||||
**Store minimal fields from server responses:**
|
||||
|
||||
```typescript
|
||||
// User object has 20+ fields, only store what UI needs
|
||||
function cachePrefs(user: FullUser) {
|
||||
try {
|
||||
localStorage.setItem('prefs:v1', JSON.stringify({
|
||||
theme: user.preferences.theme,
|
||||
notifications: user.preferences.notifications
|
||||
}))
|
||||
} catch {}
|
||||
}
|
||||
```
|
||||
|
||||
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
|
||||
|
||||
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Use Passive Event Listeners for Scrolling Performance
|
||||
impact: MEDIUM
|
||||
impactDescription: eliminates scroll delay caused by event listeners
|
||||
tags: client, event-listeners, scrolling, performance, touch, wheel
|
||||
---
|
||||
|
||||
## Use Passive Event Listeners for Scrolling Performance
|
||||
|
||||
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||
|
||||
document.addEventListener('touchstart', handleTouch)
|
||||
document.addEventListener('wheel', handleWheel)
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('touchstart', handleTouch)
|
||||
document.removeEventListener('wheel', handleWheel)
|
||||
}
|
||||
}, [])
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||
|
||||
document.addEventListener('touchstart', handleTouch, { passive: true })
|
||||
document.addEventListener('wheel', handleWheel, { passive: true })
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('touchstart', handleTouch)
|
||||
document.removeEventListener('wheel', handleWheel)
|
||||
}
|
||||
}, [])
|
||||
```
|
||||
|
||||
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
|
||||
|
||||
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: Use SWR for Automatic Deduplication
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: automatic deduplication
|
||||
tags: client, swr, deduplication, data-fetching
|
||||
---
|
||||
|
||||
## Use SWR for Automatic Deduplication
|
||||
|
||||
SWR enables request deduplication, caching, and revalidation across component instances.
|
||||
|
||||
**Incorrect (no deduplication, each instance fetches):**
|
||||
|
||||
```tsx
|
||||
function UserList() {
|
||||
const [users, setUsers] = useState([])
|
||||
useEffect(() => {
|
||||
fetch('/api/users')
|
||||
.then(r => r.json())
|
||||
.then(setUsers)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (multiple instances share one request):**
|
||||
|
||||
```tsx
|
||||
import useSWR from 'swr'
|
||||
|
||||
function UserList() {
|
||||
const { data: users } = useSWR('/api/users', fetcher)
|
||||
}
|
||||
```
|
||||
|
||||
**For immutable data:**
|
||||
|
||||
```tsx
|
||||
import { useImmutableSWR } from '@/lib/swr'
|
||||
|
||||
function StaticContent() {
|
||||
const { data } = useImmutableSWR('/api/config', fetcher)
|
||||
}
|
||||
```
|
||||
|
||||
**For mutations:**
|
||||
|
||||
```tsx
|
||||
import { useSWRMutation } from 'swr/mutation'
|
||||
|
||||
function UpdateButton() {
|
||||
const { trigger } = useSWRMutation('/api/user', updateUser)
|
||||
return <button onClick={() => trigger()}>Update</button>
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
title: Avoid Layout Thrashing
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
|
||||
tags: javascript, dom, css, performance, reflow, layout-thrashing
|
||||
---
|
||||
|
||||
## Avoid Layout Thrashing
|
||||
|
||||
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
|
||||
|
||||
**This is OK (browser batches style changes):**
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
// Each line invalidates style, but browser batches the recalculation
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
element.style.backgroundColor = 'blue'
|
||||
element.style.border = '1px solid black'
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (interleaved reads and writes force reflows):**
|
||||
```typescript
|
||||
function layoutThrashing(element: HTMLElement) {
|
||||
element.style.width = '100px'
|
||||
const width = element.offsetWidth // Forces reflow
|
||||
element.style.height = '200px'
|
||||
const height = element.offsetHeight // Forces another reflow
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (batch writes, then read once):**
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
// Batch all writes together
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
element.style.backgroundColor = 'blue'
|
||||
element.style.border = '1px solid black'
|
||||
|
||||
// Read after all writes are done (single reflow)
|
||||
const { width, height } = element.getBoundingClientRect()
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (batch reads, then writes):**
|
||||
```typescript
|
||||
function avoidThrashing(element: HTMLElement) {
|
||||
// Read phase - all layout queries first
|
||||
const rect1 = element.getBoundingClientRect()
|
||||
const offsetWidth = element.offsetWidth
|
||||
const offsetHeight = element.offsetHeight
|
||||
|
||||
// Write phase - all style changes after
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
}
|
||||
```
|
||||
|
||||
**Better: use CSS classes**
|
||||
```css
|
||||
.highlighted-box {
|
||||
width: 100px;
|
||||
height: 200px;
|
||||
background-color: blue;
|
||||
border: 1px solid black;
|
||||
}
|
||||
```
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
element.classList.add('highlighted-box')
|
||||
|
||||
const { width, height } = element.getBoundingClientRect()
|
||||
}
|
||||
```
|
||||
|
||||
**React example:**
|
||||
```tsx
|
||||
// Incorrect: interleaving style changes with layout queries
|
||||
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (ref.current && isHighlighted) {
|
||||
ref.current.style.width = '100px'
|
||||
const width = ref.current.offsetWidth // Forces layout
|
||||
ref.current.style.height = '200px'
|
||||
}
|
||||
}, [isHighlighted])
|
||||
|
||||
return <div ref={ref}>Content</div>
|
||||
}
|
||||
|
||||
// Correct: toggle class
|
||||
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||
return (
|
||||
<div className={isHighlighted ? 'highlighted-box' : ''}>
|
||||
Content
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
|
||||
|
||||
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Cache Repeated Function Calls
|
||||
impact: MEDIUM
|
||||
impactDescription: avoid redundant computation
|
||||
tags: javascript, cache, memoization, performance
|
||||
---
|
||||
|
||||
## Cache Repeated Function Calls
|
||||
|
||||
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
|
||||
|
||||
**Incorrect (redundant computation):**
|
||||
|
||||
```typescript
|
||||
function ProjectList({ projects }: { projects: Project[] }) {
|
||||
return (
|
||||
<div>
|
||||
{projects.map(project => {
|
||||
// slugify() called 100+ times for same project names
|
||||
const slug = slugify(project.name)
|
||||
|
||||
return <ProjectCard key={project.id} slug={slug} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (cached results):**
|
||||
|
||||
```typescript
|
||||
// Module-level cache
|
||||
const slugifyCache = new Map<string, string>()
|
||||
|
||||
function cachedSlugify(text: string): string {
|
||||
if (slugifyCache.has(text)) {
|
||||
return slugifyCache.get(text)!
|
||||
}
|
||||
const result = slugify(text)
|
||||
slugifyCache.set(text, result)
|
||||
return result
|
||||
}
|
||||
|
||||
function ProjectList({ projects }: { projects: Project[] }) {
|
||||
return (
|
||||
<div>
|
||||
{projects.map(project => {
|
||||
// Computed only once per unique project name
|
||||
const slug = cachedSlugify(project.name)
|
||||
|
||||
return <ProjectCard key={project.id} slug={slug} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Simpler pattern for single-value functions:**
|
||||
|
||||
```typescript
|
||||
let isLoggedInCache: boolean | null = null
|
||||
|
||||
function isLoggedIn(): boolean {
|
||||
if (isLoggedInCache !== null) {
|
||||
return isLoggedInCache
|
||||
}
|
||||
|
||||
isLoggedInCache = document.cookie.includes('auth=')
|
||||
return isLoggedInCache
|
||||
}
|
||||
|
||||
// Clear cache when auth changes
|
||||
function onAuthChange() {
|
||||
isLoggedInCache = null
|
||||
}
|
||||
```
|
||||
|
||||
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||
|
||||
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Cache Property Access in Loops
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces lookups
|
||||
tags: javascript, loops, optimization, caching
|
||||
---
|
||||
|
||||
## Cache Property Access in Loops
|
||||
|
||||
Cache object property lookups in hot paths.
|
||||
|
||||
**Incorrect (3 lookups × N iterations):**
|
||||
|
||||
```typescript
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
process(obj.config.settings.value)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (1 lookup total):**
|
||||
|
||||
```typescript
|
||||
const value = obj.config.settings.value
|
||||
const len = arr.length
|
||||
for (let i = 0; i < len; i++) {
|
||||
process(value)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
title: Cache Storage API Calls
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces expensive I/O
|
||||
tags: javascript, localStorage, storage, caching, performance
|
||||
---
|
||||
|
||||
## Cache Storage API Calls
|
||||
|
||||
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
|
||||
|
||||
**Incorrect (reads storage on every call):**
|
||||
|
||||
```typescript
|
||||
function getTheme() {
|
||||
return localStorage.getItem('theme') ?? 'light'
|
||||
}
|
||||
// Called 10 times = 10 storage reads
|
||||
```
|
||||
|
||||
**Correct (Map cache):**
|
||||
|
||||
```typescript
|
||||
const storageCache = new Map<string, string | null>()
|
||||
|
||||
function getLocalStorage(key: string) {
|
||||
if (!storageCache.has(key)) {
|
||||
storageCache.set(key, localStorage.getItem(key))
|
||||
}
|
||||
return storageCache.get(key)
|
||||
}
|
||||
|
||||
function setLocalStorage(key: string, value: string) {
|
||||
localStorage.setItem(key, value)
|
||||
storageCache.set(key, value) // keep cache in sync
|
||||
}
|
||||
```
|
||||
|
||||
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||
|
||||
**Cookie caching:**
|
||||
|
||||
```typescript
|
||||
let cookieCache: Record<string, string> | null = null
|
||||
|
||||
function getCookie(name: string) {
|
||||
if (!cookieCache) {
|
||||
cookieCache = Object.fromEntries(
|
||||
document.cookie.split('; ').map(c => c.split('='))
|
||||
)
|
||||
}
|
||||
return cookieCache[name]
|
||||
}
|
||||
```
|
||||
|
||||
**Important (invalidate on external changes):**
|
||||
|
||||
If storage can change externally (another tab, server-set cookies), invalidate cache:
|
||||
|
||||
```typescript
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key) storageCache.delete(e.key)
|
||||
})
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
storageCache.clear()
|
||||
}
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Combine Multiple Array Iterations
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces iterations
|
||||
tags: javascript, arrays, loops, performance
|
||||
---
|
||||
|
||||
## Combine Multiple Array Iterations
|
||||
|
||||
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
||||
|
||||
**Incorrect (3 iterations):**
|
||||
|
||||
```typescript
|
||||
const admins = users.filter(u => u.isAdmin)
|
||||
const testers = users.filter(u => u.isTester)
|
||||
const inactive = users.filter(u => !u.isActive)
|
||||
```
|
||||
|
||||
**Correct (1 iteration):**
|
||||
|
||||
```typescript
|
||||
const admins: User[] = []
|
||||
const testers: User[] = []
|
||||
const inactive: User[] = []
|
||||
|
||||
for (const user of users) {
|
||||
if (user.isAdmin) admins.push(user)
|
||||
if (user.isTester) testers.push(user)
|
||||
if (!user.isActive) inactive.push(user)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Early Return from Functions
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids unnecessary computation
|
||||
tags: javascript, functions, optimization, early-return
|
||||
---
|
||||
|
||||
## Early Return from Functions
|
||||
|
||||
Return early when result is determined to skip unnecessary processing.
|
||||
|
||||
**Incorrect (processes all items even after finding answer):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
let hasError = false
|
||||
let errorMessage = ''
|
||||
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
hasError = true
|
||||
errorMessage = 'Email required'
|
||||
}
|
||||
if (!user.name) {
|
||||
hasError = true
|
||||
errorMessage = 'Name required'
|
||||
}
|
||||
// Continues checking all users even after error found
|
||||
}
|
||||
|
||||
return hasError ? { valid: false, error: errorMessage } : { valid: true }
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (returns immediately on first error):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
return { valid: false, error: 'Email required' }
|
||||
}
|
||||
if (!user.name) {
|
||||
return { valid: false, error: 'Name required' }
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true }
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Hoist RegExp Creation
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids recreation
|
||||
tags: javascript, regexp, optimization, memoization
|
||||
---
|
||||
|
||||
## Hoist RegExp Creation
|
||||
|
||||
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
||||
|
||||
**Incorrect (new RegExp every render):**
|
||||
|
||||
```tsx
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = new RegExp(`(${query})`, 'gi')
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (memoize or hoist):**
|
||||
|
||||
```tsx
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = useMemo(
|
||||
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
|
||||
[query]
|
||||
)
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Warning (global regex has mutable state):**
|
||||
|
||||
Global regex (`/g`) has mutable `lastIndex` state:
|
||||
|
||||
```typescript
|
||||
const regex = /foo/g
|
||||
regex.test('foo') // true, lastIndex = 3
|
||||
regex.test('foo') // false, lastIndex = 0
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Build Index Maps for Repeated Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: 1M ops to 2K ops
|
||||
tags: javascript, map, indexing, optimization, performance
|
||||
---
|
||||
|
||||
## Build Index Maps for Repeated Lookups
|
||||
|
||||
Multiple `.find()` calls by the same key should use a Map.
|
||||
|
||||
**Incorrect (O(n) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
return orders.map(order => ({
|
||||
...order,
|
||||
user: users.find(u => u.id === order.userId)
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (O(1) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
const userById = new Map(users.map(u => [u.id, u]))
|
||||
|
||||
return orders.map(order => ({
|
||||
...order,
|
||||
user: userById.get(order.userId)
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
Build map once (O(n)), then all lookups are O(1).
|
||||
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Early Length Check for Array Comparisons
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: avoids expensive operations when lengths differ
|
||||
tags: javascript, arrays, performance, optimization, comparison
|
||||
---
|
||||
|
||||
## Early Length Check for Array Comparisons
|
||||
|
||||
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
|
||||
|
||||
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
|
||||
|
||||
**Incorrect (always runs expensive comparison):**
|
||||
|
||||
```typescript
|
||||
function hasChanges(current: string[], original: string[]) {
|
||||
// Always sorts and joins, even when lengths differ
|
||||
return current.sort().join() !== original.sort().join()
|
||||
}
|
||||
```
|
||||
|
||||
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
|
||||
|
||||
**Correct (O(1) length check first):**
|
||||
|
||||
```typescript
|
||||
function hasChanges(current: string[], original: string[]) {
|
||||
// Early return if lengths differ
|
||||
if (current.length !== original.length) {
|
||||
return true
|
||||
}
|
||||
// Only sort when lengths match
|
||||
const currentSorted = current.toSorted()
|
||||
const originalSorted = original.toSorted()
|
||||
for (let i = 0; i < currentSorted.length; i++) {
|
||||
if (currentSorted[i] !== originalSorted[i]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
```
|
||||
|
||||
This new approach is more efficient because:
|
||||
- It avoids the overhead of sorting and joining the arrays when lengths differ
|
||||
- It avoids consuming memory for the joined strings (especially important for large arrays)
|
||||
- It avoids mutating the original arrays
|
||||
- It returns early when a difference is found
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Use Loop for Min/Max Instead of Sort
|
||||
impact: LOW
|
||||
impactDescription: O(n) instead of O(n log n)
|
||||
tags: javascript, arrays, performance, sorting, algorithms
|
||||
---
|
||||
|
||||
## Use Loop for Min/Max Instead of Sort
|
||||
|
||||
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
|
||||
|
||||
**Incorrect (O(n log n) - sort to find latest):**
|
||||
|
||||
```typescript
|
||||
interface Project {
|
||||
id: string
|
||||
name: string
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
function getLatestProject(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
return sorted[0]
|
||||
}
|
||||
```
|
||||
|
||||
Sorts the entire array just to find the maximum value.
|
||||
|
||||
**Incorrect (O(n log n) - sort for oldest and newest):**
|
||||
|
||||
```typescript
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
|
||||
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
|
||||
}
|
||||
```
|
||||
|
||||
Still sorts unnecessarily when only min/max are needed.
|
||||
|
||||
**Correct (O(n) - single loop):**
|
||||
|
||||
```typescript
|
||||
function getLatestProject(projects: Project[]) {
|
||||
if (projects.length === 0) return null
|
||||
|
||||
let latest = projects[0]
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt > latest.updatedAt) {
|
||||
latest = projects[i]
|
||||
}
|
||||
}
|
||||
|
||||
return latest
|
||||
}
|
||||
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
if (projects.length === 0) return { oldest: null, newest: null }
|
||||
|
||||
let oldest = projects[0]
|
||||
let newest = projects[0]
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
|
||||
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
|
||||
}
|
||||
|
||||
return { oldest, newest }
|
||||
}
|
||||
```
|
||||
|
||||
Single pass through the array, no copying, no sorting.
|
||||
|
||||
**Alternative (Math.min/Math.max for small arrays):**
|
||||
|
||||
```typescript
|
||||
const numbers = [5, 2, 8, 1, 9]
|
||||
const min = Math.min(...numbers)
|
||||
const max = Math.max(...numbers)
|
||||
```
|
||||
|
||||
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Use Set/Map for O(1) Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: O(n) to O(1)
|
||||
tags: javascript, set, map, data-structures, performance
|
||||
---
|
||||
|
||||
## Use Set/Map for O(1) Lookups
|
||||
|
||||
Convert arrays to Set/Map for repeated membership checks.
|
||||
|
||||
**Incorrect (O(n) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = ['a', 'b', 'c', ...]
|
||||
items.filter(item => allowedIds.includes(item.id))
|
||||
```
|
||||
|
||||
**Correct (O(1) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = new Set(['a', 'b', 'c', ...])
|
||||
items.filter(item => allowedIds.has(item.id))
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
title: Use toSorted() Instead of sort() for Immutability
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: prevents mutation bugs in React state
|
||||
tags: javascript, arrays, immutability, react, state, mutation
|
||||
---
|
||||
|
||||
## Use toSorted() Instead of sort() for Immutability
|
||||
|
||||
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
|
||||
|
||||
**Incorrect (mutates original array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Mutates the users prop array!
|
||||
const sorted = useMemo(
|
||||
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (creates new array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Creates new sorted array, original unchanged
|
||||
const sorted = useMemo(
|
||||
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Why this matters in React:**
|
||||
|
||||
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
|
||||
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
|
||||
|
||||
**Browser support (fallback for older browsers):**
|
||||
|
||||
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
|
||||
|
||||
```typescript
|
||||
// Fallback for older browsers
|
||||
const sorted = [...items].sort((a, b) => a.value - b.value)
|
||||
```
|
||||
|
||||
**Other immutable array methods:**
|
||||
|
||||
- `.toSorted()` - immutable sort
|
||||
- `.toReversed()` - immutable reverse
|
||||
- `.toSpliced()` - immutable splice
|
||||
- `.with()` - immutable element replacement
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Use Activity Component for Show/Hide
|
||||
impact: MEDIUM
|
||||
impactDescription: preserves state/DOM
|
||||
tags: rendering, activity, visibility, state-preservation
|
||||
---
|
||||
|
||||
## Use Activity Component for Show/Hide
|
||||
|
||||
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
import { Activity } from 'react'
|
||||
|
||||
function Dropdown({ isOpen }: Props) {
|
||||
return (
|
||||
<Activity mode={isOpen ? 'visible' : 'hidden'}>
|
||||
<ExpensiveMenu />
|
||||
</Activity>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Avoids expensive re-renders and state loss.
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Animate SVG Wrapper Instead of SVG Element
|
||||
impact: LOW
|
||||
impactDescription: enables hardware acceleration
|
||||
tags: rendering, svg, css, animation, performance
|
||||
---
|
||||
|
||||
## Animate SVG Wrapper Instead of SVG Element
|
||||
|
||||
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
|
||||
|
||||
**Incorrect (animating SVG directly - no hardware acceleration):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<svg
|
||||
className="animate-spin"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (animating wrapper div - hardware accelerated):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<div className="animate-spin">
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Use Explicit Conditional Rendering
|
||||
impact: LOW
|
||||
impactDescription: prevents rendering 0 or NaN
|
||||
tags: rendering, conditional, jsx, falsy-values
|
||||
---
|
||||
|
||||
## Use Explicit Conditional Rendering
|
||||
|
||||
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
|
||||
|
||||
**Incorrect (renders "0" when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return (
|
||||
<div>
|
||||
{count && <span className="badge">{count}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div>0</div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
|
||||
**Correct (renders nothing when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return (
|
||||
<div>
|
||||
{count > 0 ? <span className="badge">{count}</span> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div></div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: CSS content-visibility for Long Lists
|
||||
impact: HIGH
|
||||
impactDescription: faster initial render
|
||||
tags: rendering, css, content-visibility, long-lists
|
||||
---
|
||||
|
||||
## CSS content-visibility for Long Lists
|
||||
|
||||
Apply `content-visibility: auto` to defer off-screen rendering.
|
||||
|
||||
**CSS:**
|
||||
|
||||
```css
|
||||
.message-item {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: 0 80px;
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```tsx
|
||||
function MessageList({ messages }: { messages: Message[] }) {
|
||||
return (
|
||||
<div className="overflow-y-auto h-screen">
|
||||
{messages.map(msg => (
|
||||
<div key={msg.id} className="message-item">
|
||||
<Avatar user={msg.author} />
|
||||
<div>{msg.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
title: Hoist Static JSX Elements
|
||||
impact: LOW
|
||||
impactDescription: avoids re-creation
|
||||
tags: rendering, jsx, static, optimization
|
||||
---
|
||||
|
||||
## Hoist Static JSX Elements
|
||||
|
||||
Extract static JSX outside components to avoid re-creation.
|
||||
|
||||
**Incorrect (recreates element every render):**
|
||||
|
||||
```tsx
|
||||
function LoadingSkeleton() {
|
||||
return <div className="animate-pulse h-20 bg-gray-200" />
|
||||
}
|
||||
|
||||
function Container() {
|
||||
return (
|
||||
<div>
|
||||
{loading && <LoadingSkeleton />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (reuses same element):**
|
||||
|
||||
```tsx
|
||||
const loadingSkeleton = (
|
||||
<div className="animate-pulse h-20 bg-gray-200" />
|
||||
)
|
||||
|
||||
function Container() {
|
||||
return (
|
||||
<div>
|
||||
{loading && loadingSkeleton}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Prevent Hydration Mismatch Without Flickering
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids visual flicker and hydration errors
|
||||
tags: rendering, ssr, hydration, localStorage, flicker
|
||||
---
|
||||
|
||||
## Prevent Hydration Mismatch Without Flickering
|
||||
|
||||
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
|
||||
|
||||
**Incorrect (breaks SSR):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
// localStorage is not available on server - throws error
|
||||
const theme = localStorage.getItem('theme') || 'light'
|
||||
|
||||
return (
|
||||
<div className={theme}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Server-side rendering will fail because `localStorage` is undefined.
|
||||
|
||||
**Incorrect (visual flickering):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState('light')
|
||||
|
||||
useEffect(() => {
|
||||
// Runs after hydration - causes visible flash
|
||||
const stored = localStorage.getItem('theme')
|
||||
if (stored) {
|
||||
setTheme(stored)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className={theme}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
|
||||
|
||||
**Correct (no flicker, no hydration mismatch):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<div id="theme-wrapper">
|
||||
{children}
|
||||
</div>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
(function() {
|
||||
try {
|
||||
var theme = localStorage.getItem('theme') || 'light';
|
||||
var el = document.getElementById('theme-wrapper');
|
||||
if (el) el.className = theme;
|
||||
} catch (e) {}
|
||||
})();
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
|
||||
|
||||
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Suppress Expected Hydration Mismatches
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids noisy hydration warnings for known differences
|
||||
tags: rendering, hydration, ssr, nextjs
|
||||
---
|
||||
|
||||
## Suppress Expected Hydration Mismatches
|
||||
|
||||
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
|
||||
|
||||
**Incorrect (known mismatch warnings):**
|
||||
|
||||
```tsx
|
||||
function Timestamp() {
|
||||
return <span>{new Date().toLocaleString()}</span>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (suppress expected mismatch only):**
|
||||
|
||||
```tsx
|
||||
function Timestamp() {
|
||||
return (
|
||||
<span suppressHydrationWarning>
|
||||
{new Date().toLocaleString()}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Optimize SVG Precision
|
||||
impact: LOW
|
||||
impactDescription: reduces file size
|
||||
tags: rendering, svg, optimization, svgo
|
||||
---
|
||||
|
||||
## Optimize SVG Precision
|
||||
|
||||
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
|
||||
|
||||
**Incorrect (excessive precision):**
|
||||
|
||||
```svg
|
||||
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
|
||||
```
|
||||
|
||||
**Correct (1 decimal place):**
|
||||
|
||||
```svg
|
||||
<path d="M 10.3 20.8 L 30.9 40.2" />
|
||||
```
|
||||
|
||||
**Automate with SVGO:**
|
||||
|
||||
```bash
|
||||
npx svgo --precision=1 --multipass icon.svg
|
||||
```
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
title: Use useTransition Over Manual Loading States
|
||||
impact: LOW
|
||||
impactDescription: reduces re-renders and improves code clarity
|
||||
tags: rendering, transitions, useTransition, loading, state
|
||||
---
|
||||
|
||||
## Use useTransition Over Manual Loading States
|
||||
|
||||
Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
|
||||
|
||||
**Incorrect (manual loading state):**
|
||||
|
||||
```tsx
|
||||
function SearchResults() {
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleSearch = async (value: string) => {
|
||||
setIsLoading(true)
|
||||
setQuery(value)
|
||||
const data = await fetchResults(value)
|
||||
setResults(data)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<input onChange={(e) => handleSearch(e.target.value)} />
|
||||
{isLoading && <Spinner />}
|
||||
<ResultsList results={results} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (useTransition with built-in pending state):**
|
||||
|
||||
```tsx
|
||||
import { useTransition, useState } from 'react'
|
||||
|
||||
function SearchResults() {
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState([])
|
||||
const [isPending, startTransition] = useTransition()
|
||||
|
||||
const handleSearch = (value: string) => {
|
||||
setQuery(value) // Update input immediately
|
||||
|
||||
startTransition(async () => {
|
||||
// Fetch and update results
|
||||
const data = await fetchResults(value)
|
||||
setResults(data)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<input onChange={(e) => handleSearch(e.target.value)} />
|
||||
{isPending && <Spinner />}
|
||||
<ResultsList results={results} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
|
||||
- **Error resilience**: Pending state correctly resets even if the transition throws
|
||||
- **Better responsiveness**: Keeps the UI responsive during updates
|
||||
- **Interrupt handling**: New transitions automatically cancel pending ones
|
||||
|
||||
Reference: [useTransition](https://react.dev/reference/react/useTransition)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: Defer State Reads to Usage Point
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids unnecessary subscriptions
|
||||
tags: rerender, searchParams, localStorage, optimization
|
||||
---
|
||||
|
||||
## Defer State Reads to Usage Point
|
||||
|
||||
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
||||
|
||||
**Incorrect (subscribes to all searchParams changes):**
|
||||
|
||||
```tsx
|
||||
function ShareButton({ chatId }: { chatId: string }) {
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
const handleShare = () => {
|
||||
const ref = searchParams.get('ref')
|
||||
shareChat(chatId, { ref })
|
||||
}
|
||||
|
||||
return <button onClick={handleShare}>Share</button>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (reads on demand, no subscription):**
|
||||
|
||||
```tsx
|
||||
function ShareButton({ chatId }: { chatId: string }) {
|
||||
const handleShare = () => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const ref = params.get('ref')
|
||||
shareChat(chatId, { ref })
|
||||
}
|
||||
|
||||
return <button onClick={handleShare}>Share</button>
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Narrow Effect Dependencies
|
||||
impact: LOW
|
||||
impactDescription: minimizes effect re-runs
|
||||
tags: rerender, useEffect, dependencies, optimization
|
||||
---
|
||||
|
||||
## Narrow Effect Dependencies
|
||||
|
||||
Specify primitive dependencies instead of objects to minimize effect re-runs.
|
||||
|
||||
**Incorrect (re-runs on any user field change):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
console.log(user.id)
|
||||
}, [user])
|
||||
```
|
||||
|
||||
**Correct (re-runs only when id changes):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
console.log(user.id)
|
||||
}, [user.id])
|
||||
```
|
||||
|
||||
**For derived state, compute outside effect:**
|
||||
|
||||
```tsx
|
||||
// Incorrect: runs on width=767, 766, 765...
|
||||
useEffect(() => {
|
||||
if (width < 768) {
|
||||
enableMobileMode()
|
||||
}
|
||||
}, [width])
|
||||
|
||||
// Correct: runs only on boolean transition
|
||||
const isMobile = width < 768
|
||||
useEffect(() => {
|
||||
if (isMobile) {
|
||||
enableMobileMode()
|
||||
}
|
||||
}, [isMobile])
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Calculate Derived State During Rendering
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids redundant renders and state drift
|
||||
tags: rerender, derived-state, useEffect, state
|
||||
---
|
||||
|
||||
## Calculate Derived State During Rendering
|
||||
|
||||
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
|
||||
|
||||
**Incorrect (redundant state and effect):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [firstName, setFirstName] = useState('First')
|
||||
const [lastName, setLastName] = useState('Last')
|
||||
const [fullName, setFullName] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
setFullName(firstName + ' ' + lastName)
|
||||
}, [firstName, lastName])
|
||||
|
||||
return <p>{fullName}</p>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (derive during render):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [firstName, setFirstName] = useState('First')
|
||||
const [lastName, setLastName] = useState('Last')
|
||||
const fullName = firstName + ' ' + lastName
|
||||
|
||||
return <p>{fullName}</p>
|
||||
}
|
||||
```
|
||||
|
||||
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Subscribe to Derived State
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces re-render frequency
|
||||
tags: rerender, derived-state, media-query, optimization
|
||||
---
|
||||
|
||||
## Subscribe to Derived State
|
||||
|
||||
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
|
||||
|
||||
**Incorrect (re-renders on every pixel change):**
|
||||
|
||||
```tsx
|
||||
function Sidebar() {
|
||||
const width = useWindowWidth() // updates continuously
|
||||
const isMobile = width < 768
|
||||
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (re-renders only when boolean changes):**
|
||||
|
||||
```tsx
|
||||
function Sidebar() {
|
||||
const isMobile = useMediaQuery('(max-width: 767px)')
|
||||
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Use Functional setState Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents stale closures and unnecessary callback recreations
|
||||
tags: react, hooks, useState, useCallback, callbacks, closures
|
||||
---
|
||||
|
||||
## Use Functional setState Updates
|
||||
|
||||
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
|
||||
|
||||
**Incorrect (requires state as dependency):**
|
||||
|
||||
```tsx
|
||||
function TodoList() {
|
||||
const [items, setItems] = useState(initialItems)
|
||||
|
||||
// Callback must depend on items, recreated on every items change
|
||||
const addItems = useCallback((newItems: Item[]) => {
|
||||
setItems([...items, ...newItems])
|
||||
}, [items]) // ❌ items dependency causes recreations
|
||||
|
||||
// Risk of stale closure if dependency is forgotten
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems(items.filter(item => item.id !== id))
|
||||
}, []) // ❌ Missing items dependency - will use stale items!
|
||||
|
||||
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||
}
|
||||
```
|
||||
|
||||
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
|
||||
|
||||
**Correct (stable callbacks, no stale closures):**
|
||||
|
||||
```tsx
|
||||
function TodoList() {
|
||||
const [items, setItems] = useState(initialItems)
|
||||
|
||||
// Stable callback, never recreated
|
||||
const addItems = useCallback((newItems: Item[]) => {
|
||||
setItems(curr => [...curr, ...newItems])
|
||||
}, []) // ✅ No dependencies needed
|
||||
|
||||
// Always uses latest state, no stale closure risk
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems(curr => curr.filter(item => item.id !== id))
|
||||
}, []) // ✅ Safe and stable
|
||||
|
||||
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
|
||||
2. **No stale closures** - Always operates on the latest state value
|
||||
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
|
||||
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
|
||||
|
||||
**When to use functional updates:**
|
||||
|
||||
- Any setState that depends on the current state value
|
||||
- Inside useCallback/useMemo when state is needed
|
||||
- Event handlers that reference state
|
||||
- Async operations that update state
|
||||
|
||||
**When direct updates are fine:**
|
||||
|
||||
- Setting state to a static value: `setCount(0)`
|
||||
- Setting state from props/arguments only: `setName(newName)`
|
||||
- State doesn't depend on previous value
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: Use Lazy State Initialization
|
||||
impact: MEDIUM
|
||||
impactDescription: wasted computation on every render
|
||||
tags: react, hooks, useState, performance, initialization
|
||||
---
|
||||
|
||||
## Use Lazy State Initialization
|
||||
|
||||
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
|
||||
|
||||
**Incorrect (runs on every render):**
|
||||
|
||||
```tsx
|
||||
function FilteredList({ items }: { items: Item[] }) {
|
||||
// buildSearchIndex() runs on EVERY render, even after initialization
|
||||
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
// When query changes, buildSearchIndex runs again unnecessarily
|
||||
return <SearchResults index={searchIndex} query={query} />
|
||||
}
|
||||
|
||||
function UserProfile() {
|
||||
// JSON.parse runs on every render
|
||||
const [settings, setSettings] = useState(
|
||||
JSON.parse(localStorage.getItem('settings') || '{}')
|
||||
)
|
||||
|
||||
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (runs only once):**
|
||||
|
||||
```tsx
|
||||
function FilteredList({ items }: { items: Item[] }) {
|
||||
// buildSearchIndex() runs ONLY on initial render
|
||||
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
return <SearchResults index={searchIndex} query={query} />
|
||||
}
|
||||
|
||||
function UserProfile() {
|
||||
// JSON.parse runs only on initial render
|
||||
const [settings, setSettings] = useState(() => {
|
||||
const stored = localStorage.getItem('settings')
|
||||
return stored ? JSON.parse(stored) : {}
|
||||
})
|
||||
|
||||
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||
}
|
||||
```
|
||||
|
||||
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
||||
|
||||
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
|
||||
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
||||
impact: MEDIUM
|
||||
impactDescription: restores memoization by using a constant for default value
|
||||
tags: rerender, memo, optimization
|
||||
|
||||
---
|
||||
|
||||
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
||||
|
||||
When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
|
||||
|
||||
To address this issue, extract the default value into a constant.
|
||||
|
||||
**Incorrect (`onClick` has different values on every rerender):**
|
||||
|
||||
```tsx
|
||||
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
|
||||
// ...
|
||||
})
|
||||
|
||||
// Used without optional onClick
|
||||
<UserAvatar />
|
||||
```
|
||||
|
||||
**Correct (stable default value):**
|
||||
|
||||
```tsx
|
||||
const NOOP = () => {};
|
||||
|
||||
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
|
||||
// ...
|
||||
})
|
||||
|
||||
// Used without optional onClick
|
||||
<UserAvatar />
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
title: Extract to Memoized Components
|
||||
impact: MEDIUM
|
||||
impactDescription: enables early returns
|
||||
tags: rerender, memo, useMemo, optimization
|
||||
---
|
||||
|
||||
## Extract to Memoized Components
|
||||
|
||||
Extract expensive work into memoized components to enable early returns before computation.
|
||||
|
||||
**Incorrect (computes avatar even when loading):**
|
||||
|
||||
```tsx
|
||||
function Profile({ user, loading }: Props) {
|
||||
const avatar = useMemo(() => {
|
||||
const id = computeAvatarId(user)
|
||||
return <Avatar id={id} />
|
||||
}, [user])
|
||||
|
||||
if (loading) return <Skeleton />
|
||||
return <div>{avatar}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (skips computation when loading):**
|
||||
|
||||
```tsx
|
||||
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
||||
const id = useMemo(() => computeAvatarId(user), [user])
|
||||
return <Avatar id={id} />
|
||||
})
|
||||
|
||||
function Profile({ user, loading }: Props) {
|
||||
if (loading) return <Skeleton />
|
||||
return (
|
||||
<div>
|
||||
<UserAvatar user={user} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Put Interaction Logic in Event Handlers
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids effect re-runs and duplicate side effects
|
||||
tags: rerender, useEffect, events, side-effects, dependencies
|
||||
---
|
||||
|
||||
## Put Interaction Logic in Event Handlers
|
||||
|
||||
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
|
||||
|
||||
**Incorrect (event modeled as state + effect):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const theme = useContext(ThemeContext)
|
||||
|
||||
useEffect(() => {
|
||||
if (submitted) {
|
||||
post('/api/register')
|
||||
showToast('Registered', theme)
|
||||
}
|
||||
}, [submitted, theme])
|
||||
|
||||
return <button onClick={() => setSubmitted(true)}>Submit</button>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (do it in the handler):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const theme = useContext(ThemeContext)
|
||||
|
||||
function handleSubmit() {
|
||||
post('/api/register')
|
||||
showToast('Registered', theme)
|
||||
}
|
||||
|
||||
return <button onClick={handleSubmit}>Submit</button>
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Do not wrap a simple expression with a primitive result type in useMemo
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: wasted computation on every render
|
||||
tags: rerender, useMemo, optimization
|
||||
---
|
||||
|
||||
## Do not wrap a simple expression with a primitive result type in useMemo
|
||||
|
||||
When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
|
||||
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
function Header({ user, notifications }: Props) {
|
||||
const isLoading = useMemo(() => {
|
||||
return user.isLoading || notifications.isLoading
|
||||
}, [user.isLoading, notifications.isLoading])
|
||||
|
||||
if (isLoading) return <Skeleton />
|
||||
// return some markup
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
function Header({ user, notifications }: Props) {
|
||||
const isLoading = user.isLoading || notifications.isLoading
|
||||
|
||||
if (isLoading) return <Skeleton />
|
||||
// return some markup
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Use Transitions for Non-Urgent Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: maintains UI responsiveness
|
||||
tags: rerender, transitions, startTransition, performance
|
||||
---
|
||||
|
||||
## Use Transitions for Non-Urgent Updates
|
||||
|
||||
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
||||
|
||||
**Incorrect (blocks UI on every scroll):**
|
||||
|
||||
```tsx
|
||||
function ScrollTracker() {
|
||||
const [scrollY, setScrollY] = useState(0)
|
||||
useEffect(() => {
|
||||
const handler = () => setScrollY(window.scrollY)
|
||||
window.addEventListener('scroll', handler, { passive: true })
|
||||
return () => window.removeEventListener('scroll', handler)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking updates):**
|
||||
|
||||
```tsx
|
||||
import { startTransition } from 'react'
|
||||
|
||||
function ScrollTracker() {
|
||||
const [scrollY, setScrollY] = useState(0)
|
||||
useEffect(() => {
|
||||
const handler = () => {
|
||||
startTransition(() => setScrollY(window.scrollY))
|
||||
}
|
||||
window.addEventListener('scroll', handler, { passive: true })
|
||||
return () => window.removeEventListener('scroll', handler)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: Use useRef for Transient Values
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids unnecessary re-renders on frequent updates
|
||||
tags: rerender, useref, state, performance
|
||||
---
|
||||
|
||||
## Use useRef for Transient Values
|
||||
|
||||
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
|
||||
|
||||
**Incorrect (renders every update):**
|
||||
|
||||
```tsx
|
||||
function Tracker() {
|
||||
const [lastX, setLastX] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const onMove = (e: MouseEvent) => setLastX(e.clientX)
|
||||
window.addEventListener('mousemove', onMove)
|
||||
return () => window.removeEventListener('mousemove', onMove)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: lastX,
|
||||
width: 8,
|
||||
height: 8,
|
||||
background: 'black',
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (no re-render for tracking):**
|
||||
|
||||
```tsx
|
||||
function Tracker() {
|
||||
const lastXRef = useRef(0)
|
||||
const dotRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const onMove = (e: MouseEvent) => {
|
||||
lastXRef.current = e.clientX
|
||||
const node = dotRef.current
|
||||
if (node) {
|
||||
node.style.transform = `translateX(${e.clientX}px)`
|
||||
}
|
||||
}
|
||||
window.addEventListener('mousemove', onMove)
|
||||
return () => window.removeEventListener('mousemove', onMove)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={dotRef}
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: 8,
|
||||
height: 8,
|
||||
background: 'black',
|
||||
transform: 'translateX(0px)',
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: Use after() for Non-Blocking Operations
|
||||
impact: MEDIUM
|
||||
impactDescription: faster response times
|
||||
tags: server, async, logging, analytics, side-effects
|
||||
---
|
||||
|
||||
## Use after() for Non-Blocking Operations
|
||||
|
||||
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
|
||||
|
||||
**Incorrect (blocks response):**
|
||||
|
||||
```tsx
|
||||
import { logUserAction } from '@/app/utils'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Perform mutation
|
||||
await updateDatabase(request)
|
||||
|
||||
// Logging blocks the response
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown'
|
||||
await logUserAction({ userAgent })
|
||||
|
||||
return new Response(JSON.stringify({ status: 'success' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking):**
|
||||
|
||||
```tsx
|
||||
import { after } from 'next/server'
|
||||
import { headers, cookies } from 'next/headers'
|
||||
import { logUserAction } from '@/app/utils'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Perform mutation
|
||||
await updateDatabase(request)
|
||||
|
||||
// Log after response is sent
|
||||
after(async () => {
|
||||
const userAgent = (await headers()).get('user-agent') || 'unknown'
|
||||
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
|
||||
|
||||
logUserAction({ sessionCookie, userAgent })
|
||||
})
|
||||
|
||||
return new Response(JSON.stringify({ status: 'success' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
The response is sent immediately while logging happens in the background.
|
||||
|
||||
**Common use cases:**
|
||||
|
||||
- Analytics tracking
|
||||
- Audit logging
|
||||
- Sending notifications
|
||||
- Cache invalidation
|
||||
- Cleanup tasks
|
||||
|
||||
**Important notes:**
|
||||
|
||||
- `after()` runs even if the response fails or redirects
|
||||
- Works in Server Actions, Route Handlers, and Server Components
|
||||
|
||||
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: Authenticate Server Actions Like API Routes
|
||||
impact: CRITICAL
|
||||
impactDescription: prevents unauthorized access to server mutations
|
||||
tags: server, server-actions, authentication, security, authorization
|
||||
---
|
||||
|
||||
## Authenticate Server Actions Like API Routes
|
||||
|
||||
**Impact: CRITICAL (prevents unauthorized access to server mutations)**
|
||||
|
||||
Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
|
||||
|
||||
Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
|
||||
|
||||
**Incorrect (no authentication check):**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
export async function deleteUser(userId: string) {
|
||||
// Anyone can call this! No auth check
|
||||
await db.user.delete({ where: { id: userId } })
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (authentication inside the action):**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
import { verifySession } from '@/lib/auth'
|
||||
import { unauthorized } from '@/lib/errors'
|
||||
|
||||
export async function deleteUser(userId: string) {
|
||||
// Always check auth inside the action
|
||||
const session = await verifySession()
|
||||
|
||||
if (!session) {
|
||||
throw unauthorized('Must be logged in')
|
||||
}
|
||||
|
||||
// Check authorization too
|
||||
if (session.user.role !== 'admin' && session.user.id !== userId) {
|
||||
throw unauthorized('Cannot delete other users')
|
||||
}
|
||||
|
||||
await db.user.delete({ where: { id: userId } })
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
**With input validation:**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
import { verifySession } from '@/lib/auth'
|
||||
import { z } from 'zod'
|
||||
|
||||
const updateProfileSchema = z.object({
|
||||
userId: z.string().uuid(),
|
||||
name: z.string().min(1).max(100),
|
||||
email: z.string().email()
|
||||
})
|
||||
|
||||
export async function updateProfile(data: unknown) {
|
||||
// Validate input first
|
||||
const validated = updateProfileSchema.parse(data)
|
||||
|
||||
// Then authenticate
|
||||
const session = await verifySession()
|
||||
if (!session) {
|
||||
throw new Error('Unauthorized')
|
||||
}
|
||||
|
||||
// Then authorize
|
||||
if (session.user.id !== validated.userId) {
|
||||
throw new Error('Can only update own profile')
|
||||
}
|
||||
|
||||
// Finally perform the mutation
|
||||
await db.user.update({
|
||||
where: { id: validated.userId },
|
||||
data: {
|
||||
name: validated.name,
|
||||
email: validated.email
|
||||
}
|
||||
})
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
title: Cross-Request LRU Caching
|
||||
impact: HIGH
|
||||
impactDescription: caches across requests
|
||||
tags: server, cache, lru, cross-request
|
||||
---
|
||||
|
||||
## Cross-Request LRU Caching
|
||||
|
||||
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```typescript
|
||||
import { LRUCache } from 'lru-cache'
|
||||
|
||||
const cache = new LRUCache<string, any>({
|
||||
max: 1000,
|
||||
ttl: 5 * 60 * 1000 // 5 minutes
|
||||
})
|
||||
|
||||
export async function getUser(id: string) {
|
||||
const cached = cache.get(id)
|
||||
if (cached) return cached
|
||||
|
||||
const user = await db.user.findUnique({ where: { id } })
|
||||
cache.set(id, user)
|
||||
return user
|
||||
}
|
||||
|
||||
// Request 1: DB query, result cached
|
||||
// Request 2: cache hit, no DB query
|
||||
```
|
||||
|
||||
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
|
||||
|
||||
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
|
||||
|
||||
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
|
||||
|
||||
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: Per-Request Deduplication with React.cache()
|
||||
impact: MEDIUM
|
||||
impactDescription: deduplicates within request
|
||||
tags: server, cache, react-cache, deduplication
|
||||
---
|
||||
|
||||
## Per-Request Deduplication with React.cache()
|
||||
|
||||
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```typescript
|
||||
import { cache } from 'react'
|
||||
|
||||
export const getCurrentUser = cache(async () => {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return null
|
||||
return await db.user.findUnique({
|
||||
where: { id: session.user.id }
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
|
||||
|
||||
**Avoid inline objects as arguments:**
|
||||
|
||||
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
|
||||
|
||||
**Incorrect (always cache miss):**
|
||||
|
||||
```typescript
|
||||
const getUser = cache(async (params: { uid: number }) => {
|
||||
return await db.user.findUnique({ where: { id: params.uid } })
|
||||
})
|
||||
|
||||
// Each call creates new object, never hits cache
|
||||
getUser({ uid: 1 })
|
||||
getUser({ uid: 1 }) // Cache miss, runs query again
|
||||
```
|
||||
|
||||
**Correct (cache hit):**
|
||||
|
||||
```typescript
|
||||
const getUser = cache(async (uid: number) => {
|
||||
return await db.user.findUnique({ where: { id: uid } })
|
||||
})
|
||||
|
||||
// Primitive args use value equality
|
||||
getUser(1)
|
||||
getUser(1) // Cache hit, returns cached result
|
||||
```
|
||||
|
||||
If you must pass objects, pass the same reference:
|
||||
|
||||
```typescript
|
||||
const params = { uid: 1 }
|
||||
getUser(params) // Query runs
|
||||
getUser(params) // Cache hit (same reference)
|
||||
```
|
||||
|
||||
**Next.js-Specific Note:**
|
||||
|
||||
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
|
||||
|
||||
- Database queries (Prisma, Drizzle, etc.)
|
||||
- Heavy computations
|
||||
- Authentication checks
|
||||
- File system operations
|
||||
- Any non-fetch async work
|
||||
|
||||
Use `React.cache()` to deduplicate these operations across your component tree.
|
||||
|
||||
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
title: Avoid Duplicate Serialization in RSC Props
|
||||
impact: LOW
|
||||
impactDescription: reduces network payload by avoiding duplicate serialization
|
||||
tags: server, rsc, serialization, props, client-components
|
||||
---
|
||||
|
||||
## Avoid Duplicate Serialization in RSC Props
|
||||
|
||||
**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
|
||||
|
||||
RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
|
||||
|
||||
**Incorrect (duplicates array):**
|
||||
|
||||
```tsx
|
||||
// RSC: sends 6 strings (2 arrays × 3 items)
|
||||
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
|
||||
```
|
||||
|
||||
**Correct (sends 3 strings):**
|
||||
|
||||
```tsx
|
||||
// RSC: send once
|
||||
<ClientList usernames={usernames} />
|
||||
|
||||
// Client: transform there
|
||||
'use client'
|
||||
const sorted = useMemo(() => [...usernames].sort(), [usernames])
|
||||
```
|
||||
|
||||
**Nested deduplication behavior:**
|
||||
|
||||
Deduplication works recursively. Impact varies by data type:
|
||||
|
||||
- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
|
||||
- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
|
||||
|
||||
```tsx
|
||||
// string[] - duplicates everything
|
||||
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
|
||||
|
||||
// object[] - duplicates array structure only
|
||||
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
|
||||
```
|
||||
|
||||
**Operations breaking deduplication (create new references):**
|
||||
|
||||
- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
|
||||
- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
|
||||
|
||||
**More examples:**
|
||||
|
||||
```tsx
|
||||
// ❌ Bad
|
||||
<C users={users} active={users.filter(u => u.active)} />
|
||||
<C product={product} productName={product.name} />
|
||||
|
||||
// ✅ Good
|
||||
<C users={users} />
|
||||
<C product={product} />
|
||||
// Do filtering/destructuring in client
|
||||
```
|
||||
|
||||
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
title: Parallel Data Fetching with Component Composition
|
||||
impact: CRITICAL
|
||||
impactDescription: eliminates server-side waterfalls
|
||||
tags: server, rsc, parallel-fetching, composition
|
||||
---
|
||||
|
||||
## Parallel Data Fetching with Component Composition
|
||||
|
||||
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
|
||||
|
||||
**Incorrect (Sidebar waits for Page's fetch to complete):**
|
||||
|
||||
```tsx
|
||||
export default async function Page() {
|
||||
const header = await fetchHeader()
|
||||
return (
|
||||
<div>
|
||||
<div>{header}</div>
|
||||
<Sidebar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (both fetch simultaneously):**
|
||||
|
||||
```tsx
|
||||
async function Header() {
|
||||
const data = await fetchHeader()
|
||||
return <div>{data}</div>
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
<Sidebar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative with children prop:**
|
||||
|
||||
```tsx
|
||||
async function Header() {
|
||||
const data = await fetchHeader()
|
||||
return <div>{data}</div>
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
|
||||
function Layout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<Layout>
|
||||
<Sidebar />
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: Minimize Serialization at RSC Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: reduces data transfer size
|
||||
tags: server, rsc, serialization, props
|
||||
---
|
||||
|
||||
## Minimize Serialization at RSC Boundaries
|
||||
|
||||
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
|
||||
|
||||
**Incorrect (serializes all 50 fields):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const user = await fetchUser() // 50 fields
|
||||
return <Profile user={user} />
|
||||
}
|
||||
|
||||
'use client'
|
||||
function Profile({ user }: { user: User }) {
|
||||
return <div>{user.name}</div> // uses 1 field
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (serializes only 1 field):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const user = await fetchUser()
|
||||
return <Profile name={user.name} />
|
||||
}
|
||||
|
||||
'use client'
|
||||
function Profile({ name }: { name: string }) {
|
||||
return <div>{name}</div>
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
name: web-design-guidelines
|
||||
description: Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".
|
||||
metadata:
|
||||
author: vercel
|
||||
version: "1.0.0"
|
||||
argument-hint: <file-or-pattern>
|
||||
---
|
||||
|
||||
# Web Interface Guidelines
|
||||
|
||||
Review files for compliance with Web Interface Guidelines.
|
||||
|
||||
## How It Works
|
||||
|
||||
1. Fetch the latest guidelines from the source URL below
|
||||
2. Read the specified files (or prompt user for files/pattern)
|
||||
3. Check against all rules in the fetched guidelines
|
||||
4. Output findings in the terse `file:line` format
|
||||
|
||||
## Guidelines Source
|
||||
|
||||
Fetch fresh guidelines before each review:
|
||||
|
||||
```
|
||||
https://raw.githubusercontent.com/vercel-labs/web-interface-guidelines/main/command.md
|
||||
```
|
||||
|
||||
Use WebFetch to retrieve the latest rules. The fetched content contains all the rules and output format instructions.
|
||||
|
||||
## Usage
|
||||
|
||||
When a user provides a file or pattern argument:
|
||||
1. Fetch guidelines from the source URL above
|
||||
2. Read the specified files
|
||||
3. Apply all rules from the fetched guidelines
|
||||
4. Output findings using the format specified in the guidelines
|
||||
|
||||
If no files specified, ask the user which files to review.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/find-skills
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/gh-cli
|
||||
@@ -0,0 +1 @@
|
||||
../../.agents/skills/vercel-react-best-practices
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/web-design-guidelines
|
||||
+3
-2
@@ -60,5 +60,6 @@ lib/emails/marketing
|
||||
# trigger.dev
|
||||
.trigger
|
||||
|
||||
# changelog
|
||||
changelog
|
||||
# changelog and docs
|
||||
changelog
|
||||
.docs
|
||||
@@ -115,11 +115,13 @@ export default function EmailVerificationClient() {
|
||||
<div className="flex w-full justify-center bg-gray-50 md:w-1/2 lg:w-1/2">
|
||||
<div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">
|
||||
<div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">
|
||||
<img
|
||||
src="/_static/papermark-logo.svg"
|
||||
alt="Papermark Logo"
|
||||
className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
|
||||
/>
|
||||
<Link href="https://www.papermark.com" target="_blank">
|
||||
<img
|
||||
src="/_static/papermark-logo.svg"
|
||||
alt="Papermark Logo"
|
||||
className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
|
||||
/>
|
||||
</Link>
|
||||
<span className="text-balance text-3xl font-semibold text-gray-900">
|
||||
Code Expired
|
||||
</span>
|
||||
@@ -151,11 +153,13 @@ export default function EmailVerificationClient() {
|
||||
></div>
|
||||
<div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">
|
||||
<div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">
|
||||
<img
|
||||
src="/_static/papermark-logo.svg"
|
||||
alt="Papermark Logo"
|
||||
className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
|
||||
/>
|
||||
<Link href="https://www.papermark.com" target="_blank">
|
||||
<img
|
||||
src="/_static/papermark-logo.svg"
|
||||
alt="Papermark Logo"
|
||||
className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
|
||||
/>
|
||||
</Link>
|
||||
<Link href="/">
|
||||
<span className="text-balance text-3xl font-semibold text-gray-900">
|
||||
Check your email
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { signIn } from "next-auth/react";
|
||||
|
||||
/**
|
||||
* SAML Callback Page
|
||||
*
|
||||
* This page handles IdP-initiated SSO flow:
|
||||
* 1. User clicks the app tile in their IdP dashboard
|
||||
* 2. Jackson processes the SAML response and redirects here with a `code`
|
||||
* 3. We exchange the code via the `saml-idp` CredentialsProvider
|
||||
*
|
||||
* SP-initiated SSO (user clicks "Continue with SSO" on login page) is handled
|
||||
* entirely by NextAuth's OAuth flow via the `saml` provider — it never hits this page.
|
||||
*/
|
||||
export default function SAMLCallbackClient() {
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
const [status, setStatus] = useState<"loading" | "error">("loading");
|
||||
const [errorMessage, setErrorMessage] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
const code = searchParams?.get("code");
|
||||
if (code) {
|
||||
signIn("saml-idp", {
|
||||
code,
|
||||
redirect: false,
|
||||
}).then((result) => {
|
||||
if (result?.ok) {
|
||||
router.push("/dashboard");
|
||||
} else {
|
||||
setStatus("error");
|
||||
setErrorMessage(
|
||||
result?.error || "SSO authentication failed. Please try again.",
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
setStatus("error");
|
||||
setErrorMessage(
|
||||
"No authorization code received from your identity provider.",
|
||||
);
|
||||
}
|
||||
}, [searchParams, router]);
|
||||
|
||||
if (status === "error") {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="mx-auto max-w-md text-center">
|
||||
<h2 className="text-xl font-semibold text-gray-900">
|
||||
SSO Login Failed
|
||||
</h2>
|
||||
<p className="mt-2 text-sm text-gray-600">{errorMessage}</p>
|
||||
<button
|
||||
onClick={() => router.push("/login")}
|
||||
className="mt-4 rounded-md bg-gray-900 px-4 py-2 text-sm text-white hover:bg-gray-800"
|
||||
>
|
||||
Return to Login
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="mx-auto max-w-md text-center">
|
||||
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-2 border-gray-300 border-t-gray-900" />
|
||||
<p className="text-sm text-gray-600">Completing SSO login...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Metadata } from "next";
|
||||
|
||||
import SAMLCallbackClient from "./page-client";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "SSO Login | Papermark",
|
||||
description: "Completing SSO login",
|
||||
};
|
||||
|
||||
export default function SAMLCallbackPage() {
|
||||
return <SAMLCallbackClient />;
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { AlertCircle } from "lucide-react";
|
||||
|
||||
import { SSOLogin } from "@/ee/features/security/sso";
|
||||
import { signInWithPasskey } from "@teamhanko/passkeys-next-auth-provider/client";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { toast } from "sonner";
|
||||
@@ -24,6 +27,9 @@ import { Label } from "@/components/ui/label";
|
||||
export default function Login() {
|
||||
const { next } = useParams as { next?: string };
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const authError = searchParams?.get("error");
|
||||
const isSSORequired = authError === "require-saml-sso";
|
||||
|
||||
const [lastUsed, setLastUsed] = useLastUsed();
|
||||
const authMethods = ["google", "email", "linkedin", "passkey"] as const;
|
||||
@@ -55,11 +61,13 @@ export default function Login() {
|
||||
></div>
|
||||
<div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">
|
||||
<div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">
|
||||
<img
|
||||
src="/_static/papermark-logo.svg"
|
||||
alt="Papermark Logo"
|
||||
className="md:mb-48s -mt-8 mb-36 h-7 w-auto self-start sm:mb-32"
|
||||
/>
|
||||
<Link href="https://www.papermark.com" target="_blank">
|
||||
<img
|
||||
src="/_static/papermark-logo.svg"
|
||||
alt="Papermark Logo"
|
||||
className="md:mb-48s -mt-8 mb-36 h-7 w-auto self-start sm:mb-32"
|
||||
/>
|
||||
</Link>
|
||||
<Link href="/">
|
||||
<span className="text-balance text-3xl font-semibold text-gray-900">
|
||||
Welcome to Papermark
|
||||
@@ -69,6 +77,20 @@ export default function Login() {
|
||||
Share documents. Not attachments.
|
||||
</h3>
|
||||
</div>
|
||||
{isSSORequired && (
|
||||
<div className="mx-4 mb-2 flex items-start gap-3 rounded-lg border border-orange-200 bg-orange-50 px-4 py-3 sm:mx-12">
|
||||
<AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-orange-600" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-orange-900">
|
||||
Your organization requires SSO login
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-orange-700">
|
||||
Please use the <strong>SAML SSO</strong> option below to sign
|
||||
in with your company's identity provider.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="flex flex-col gap-4 px-4 pt-8 sm:px-12"
|
||||
onSubmit={(e) => {
|
||||
@@ -209,6 +231,9 @@ export default function Login() {
|
||||
{lastUsed === "passkey" && <LastUsed />}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<SSOLogin autoExpand={isSSORequired} />
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-10 w-full max-w-md px-4 text-xs text-muted-foreground sm:px-12">
|
||||
By clicking continue, you acknowledge that you have read and agree
|
||||
|
||||
@@ -35,7 +35,7 @@ export default function Register() {
|
||||
</div>
|
||||
<div className="z-10 mx-5 mt-[calc(20vh)] h-fit w-full max-w-md overflow-hidden rounded-lg border border-border bg-gray-50 dark:bg-gray-900 sm:mx-0 sm:shadow-xl">
|
||||
<div className="flex flex-col items-center justify-center space-y-3 px-4 py-6 pt-8 text-center sm:px-16">
|
||||
<Link href="/">
|
||||
<Link href="https://www.papermark.com" target="_blank">
|
||||
<Image
|
||||
src={PapermarkLogo}
|
||||
width={119}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { jackson } from "@/lib/jackson";
|
||||
import type { OAuthReq } from "@boxyhq/saml-jackson";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
try {
|
||||
const { oauthController } = await jackson();
|
||||
|
||||
const url = new URL(req.url);
|
||||
const requestParams = Object.fromEntries(
|
||||
url.searchParams.entries(),
|
||||
) as unknown as OAuthReq;
|
||||
|
||||
const { redirect_url, authorize_form } =
|
||||
await oauthController.authorize(requestParams);
|
||||
|
||||
if (redirect_url) {
|
||||
return NextResponse.redirect(redirect_url, { status: 302 });
|
||||
} else if (authorize_form) {
|
||||
return new Response(authorize_form, {
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "No redirect URL returned" },
|
||||
{ status: 400 },
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Authorize error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const { oauthController } = await jackson();
|
||||
|
||||
const contentType = req.headers.get("content-type") || "";
|
||||
|
||||
let body: Record<string, any>;
|
||||
|
||||
if (contentType.includes("application/x-www-form-urlencoded")) {
|
||||
const formData = await req.formData();
|
||||
body = Object.fromEntries(formData.entries());
|
||||
} else {
|
||||
body = await req.json();
|
||||
}
|
||||
|
||||
const { redirect_url, authorize_form } =
|
||||
await oauthController.authorize(body as unknown as OAuthReq);
|
||||
|
||||
if (redirect_url) {
|
||||
return NextResponse.redirect(redirect_url, { status: 302 });
|
||||
} else if (authorize_form) {
|
||||
return new Response(authorize_form, {
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "No redirect URL returned" },
|
||||
{ status: 400 },
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Authorize error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { jackson } from "@/lib/jackson";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const { oauthController } = await jackson();
|
||||
|
||||
const formData = await req.formData();
|
||||
const RelayState = (formData.get("RelayState") as string) || "";
|
||||
const SAMLResponse = (formData.get("SAMLResponse") as string) || "";
|
||||
|
||||
const { redirect_url } = await oauthController.samlResponse({
|
||||
RelayState,
|
||||
SAMLResponse,
|
||||
});
|
||||
|
||||
if (!redirect_url) {
|
||||
return NextResponse.json(
|
||||
{ error: "No redirect URL returned" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.redirect(redirect_url, { status: 302 });
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Callback error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { jackson } from "@/lib/jackson";
|
||||
// These imports fix crypto module bundling issues with Jackson in Next.js.
|
||||
// Without them, the serverless function bundle tree-shakes away jose's crypto
|
||||
// primitives, causing ERR_CRYPTO_INVALID_KEYLEN at runtime.
|
||||
// See: https://github.com/ory/polis/blob/main/pages/api/import-hack.ts
|
||||
import * as jose from "jose";
|
||||
import { NextResponse } from "next/server";
|
||||
import * as openidClient from "openid-client";
|
||||
|
||||
// Reference the imports so they aren't removed by tree-shaking
|
||||
const _dependencies = [jose, openidClient];
|
||||
void _dependencies;
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const { oauthController } = await jackson();
|
||||
|
||||
const formData = await req.formData();
|
||||
const body = Object.fromEntries(formData.entries());
|
||||
|
||||
const token = await oauthController.token(body as any);
|
||||
|
||||
return NextResponse.json(token);
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Token error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { jackson } from "@/lib/jackson";
|
||||
// Force-include crypto dependencies (same workaround as token route)
|
||||
import * as jose from "jose";
|
||||
import { NextResponse } from "next/server";
|
||||
import * as openidClient from "openid-client";
|
||||
|
||||
const _dependencies = [jose, openidClient];
|
||||
void _dependencies;
|
||||
|
||||
export async function GET(req: Request) {
|
||||
try {
|
||||
const { oauthController } = await jackson();
|
||||
|
||||
const authHeader = req.headers.get("Authorization");
|
||||
if (!authHeader) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// RFC 6750: token type is case-insensitive
|
||||
const token = authHeader.replace(/^bearer\s+/i, "");
|
||||
const userInfo = await oauthController.userInfo(token);
|
||||
|
||||
return NextResponse.json(userInfo);
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] UserInfo error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { jackson, jacksonProduct } from "@/lib/jackson";
|
||||
import prisma from "@/lib/prisma";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
* POST /api/auth/saml/verify
|
||||
* Verifies that a team has SSO configured.
|
||||
* Accepts either `slug` (preferred, user-friendly) or `teamId` (fallback).
|
||||
* Returns only the teamId — no team names, provider info, or other metadata.
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { slug, teamId } = body;
|
||||
|
||||
if (!slug && !teamId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Team slug or ID is required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Look up team by slug first, then by ID
|
||||
const team = slug
|
||||
? await prisma.team.findUnique({
|
||||
where: { slug },
|
||||
select: { id: true, ssoEnabled: true },
|
||||
})
|
||||
: await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { id: true, ssoEnabled: true },
|
||||
});
|
||||
|
||||
const ssoUnavailable = NextResponse.json(
|
||||
{ error: "SSO is not available for this team." },
|
||||
{ status: 404 },
|
||||
);
|
||||
|
||||
if (!team || !team.ssoEnabled) {
|
||||
return ssoUnavailable;
|
||||
}
|
||||
|
||||
// Check Jackson for actual SAML connections
|
||||
const { apiController } = await jackson();
|
||||
|
||||
const connections = await apiController.getConnections({
|
||||
tenant: team.id,
|
||||
product: jacksonProduct,
|
||||
});
|
||||
|
||||
if (!connections || connections.length === 0) {
|
||||
return ssoUnavailable;
|
||||
}
|
||||
|
||||
// Only return the team ID — no names, providers, or other metadata
|
||||
return NextResponse.json({ data: { teamId: team.id } });
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Verify error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Something went wrong" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import { jackson } from "@/lib/jackson";
|
||||
import prisma from "@/lib/prisma";
|
||||
import type { DirectorySyncEvent } from "@boxyhq/saml-jackson";
|
||||
import { createHash } from "crypto";
|
||||
import { headers } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
/** Return a truncated SHA-256 hex digest (first 12 chars) for log-safe pseudonymisation. */
|
||||
function hashEmail(email: string): string {
|
||||
return createHash("sha256").update(email).digest("hex").slice(0, 12);
|
||||
}
|
||||
|
||||
const handler = async (
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ directory: string[] }> },
|
||||
) => {
|
||||
try {
|
||||
const resolvedParams = await params;
|
||||
const headersList = await headers();
|
||||
const authHeader = headersList.get("Authorization");
|
||||
const apiSecret = authHeader ? authHeader.split(" ")[1] : null;
|
||||
|
||||
const url = new URL(req.url);
|
||||
const query = Object.fromEntries(url.searchParams.entries());
|
||||
|
||||
const [directoryId, path, resourceId] = resolvedParams.directory;
|
||||
|
||||
let body: any = {};
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
body = {};
|
||||
}
|
||||
|
||||
const { directorySyncController } = await jackson();
|
||||
|
||||
const request = {
|
||||
method: req.method as "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
|
||||
body,
|
||||
directoryId,
|
||||
resourceId,
|
||||
resourceType: (path === "Users" ? "users" : "groups") as
|
||||
| "users"
|
||||
| "groups",
|
||||
apiSecret,
|
||||
query: {
|
||||
count: query.count ? parseInt(query.count) : undefined,
|
||||
startIndex: query.startIndex ? parseInt(query.startIndex) : undefined,
|
||||
filter: query.filter as string,
|
||||
},
|
||||
};
|
||||
|
||||
const { status, data } = await directorySyncController.requests.handle(
|
||||
request,
|
||||
handleSCIMEvents,
|
||||
);
|
||||
|
||||
return NextResponse.json(data, { status });
|
||||
} catch (error: any) {
|
||||
console.error("[SCIM] Request error:", error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
|
||||
detail: "Internal server error",
|
||||
status: 500,
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export {
|
||||
handler as DELETE,
|
||||
handler as GET,
|
||||
handler as PATCH,
|
||||
handler as POST,
|
||||
handler as PUT,
|
||||
};
|
||||
|
||||
// ──────────────────────────────────────────────────────────
|
||||
// SCIM Event Handler — sync changes to the main app DB
|
||||
// ──────────────────────────────────────────────────────────
|
||||
async function handleSCIMEvents(event: DirectorySyncEvent) {
|
||||
const { event: eventType, data, tenant } = event;
|
||||
|
||||
// Verify the team exists and has SSO enabled
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: tenant },
|
||||
select: { id: true, plan: true, ssoEnabled: true },
|
||||
});
|
||||
|
||||
if (!team || !team.ssoEnabled) {
|
||||
console.warn(
|
||||
`[SCIM] Ignoring event for tenant ${tenant} — SSO not enabled`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Plan gate: only datarooms-premium or higher
|
||||
const allowedPlans = ["datarooms-premium", "datarooms-premium+old"];
|
||||
if (!allowedPlans.includes(team.plan)) {
|
||||
console.warn(
|
||||
`[SCIM] Ignoring event for tenant ${tenant} — plan ${team.plan} not eligible`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!("email" in data) || !data.email) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalize once so look-ups/upserts always use a consistent lowercase key
|
||||
const email = data.email.trim().toLowerCase();
|
||||
|
||||
try {
|
||||
switch (eventType) {
|
||||
case "user.created": {
|
||||
console.log(
|
||||
`[SCIM] User created: user_${hashEmail(email)} for tenant ${tenant}`,
|
||||
);
|
||||
|
||||
const user = await prisma.user.upsert({
|
||||
where: { email },
|
||||
create: {
|
||||
email,
|
||||
name: [data.first_name, data.last_name].filter(Boolean).join(" "),
|
||||
},
|
||||
update: {},
|
||||
});
|
||||
|
||||
await prisma.userTeam.upsert({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: user.id,
|
||||
teamId: tenant,
|
||||
},
|
||||
},
|
||||
update: {},
|
||||
create: {
|
||||
userId: user.id,
|
||||
teamId: tenant,
|
||||
role: "MEMBER",
|
||||
},
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "user.updated": {
|
||||
console.log(
|
||||
`[SCIM] User updated: user_${hashEmail(email)} for tenant ${tenant}`,
|
||||
);
|
||||
|
||||
// Handle Azure AD's active/inactive (can be boolean or string in any casing)
|
||||
const rawActive = (data as any).active;
|
||||
const normalizedActive =
|
||||
rawActive === undefined
|
||||
? undefined
|
||||
: typeof rawActive === "string"
|
||||
? rawActive.toLowerCase() === "true"
|
||||
: Boolean(rawActive);
|
||||
|
||||
const isActive = normalizedActive === true;
|
||||
const isInactive = normalizedActive === false;
|
||||
|
||||
if (isInactive) {
|
||||
// Deactivated — remove from team (same as user.deleted)
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
|
||||
if (user) {
|
||||
await prisma.userTeam
|
||||
.delete({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: user.id,
|
||||
teamId: tenant,
|
||||
},
|
||||
},
|
||||
})
|
||||
.catch(() => {
|
||||
console.warn(
|
||||
`[SCIM] Could not remove team membership for user_${hashEmail(email)}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
} else if (isActive) {
|
||||
// Reactivated — re-add to team
|
||||
const user = await prisma.user.upsert({
|
||||
where: { email },
|
||||
create: {
|
||||
email,
|
||||
name: [data.first_name, data.last_name]
|
||||
.filter(Boolean)
|
||||
.join(" "),
|
||||
},
|
||||
update: {
|
||||
name:
|
||||
[data.first_name, data.last_name].filter(Boolean).join(" ") ||
|
||||
undefined,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.userTeam.upsert({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: user.id,
|
||||
teamId: tenant,
|
||||
},
|
||||
},
|
||||
update: {},
|
||||
create: {
|
||||
userId: user.id,
|
||||
teamId: tenant,
|
||||
role: "MEMBER",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Just a name/attribute update
|
||||
await prisma.user
|
||||
.update({
|
||||
where: { email },
|
||||
data: {
|
||||
name:
|
||||
[data.first_name, data.last_name]
|
||||
.filter(Boolean)
|
||||
.join(" ") || undefined,
|
||||
},
|
||||
})
|
||||
.catch(() => {
|
||||
console.warn(
|
||||
`[SCIM] Could not update user user_${hashEmail(email)} — user not found`,
|
||||
);
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "user.deleted": {
|
||||
console.log(
|
||||
`[SCIM] User deleted: user_${hashEmail(email)} for tenant ${tenant}`,
|
||||
);
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
|
||||
if (user) {
|
||||
await prisma.userTeam
|
||||
.delete({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: user.id,
|
||||
teamId: tenant,
|
||||
},
|
||||
},
|
||||
})
|
||||
.catch(() => {
|
||||
console.warn(
|
||||
`[SCIM] Could not remove team membership for user_${hashEmail(email)}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "group.created":
|
||||
case "group.updated":
|
||||
case "group.deleted":
|
||||
case "group.user_added":
|
||||
case "group.user_removed": {
|
||||
console.log(`[SCIM] Group event ${eventType} for tenant ${tenant}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[SCIM] Error handling event ${eventType}:`, error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { jackson, jacksonProduct } from "@/lib/jackson";
|
||||
import prisma from "@/lib/prisma";
|
||||
import { CustomUser } from "@/lib/types";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]";
|
||||
|
||||
const SSO_ELIGIBLE_PLANS = ["datarooms-premium", "datarooms-premium+old"];
|
||||
|
||||
async function getAuthenticatedAdmin(teamId: string) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return null;
|
||||
|
||||
const userId = (session.user as CustomUser).id;
|
||||
|
||||
const teamAccess = await prisma.userTeam.findUnique({
|
||||
where: { userId_teamId: { userId, teamId } },
|
||||
select: { role: true },
|
||||
});
|
||||
|
||||
if (!teamAccess || teamAccess.role !== "ADMIN") return null;
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { id: true, plan: true, ssoEnabled: true },
|
||||
});
|
||||
|
||||
if (!team) return null;
|
||||
|
||||
return { userId, team };
|
||||
}
|
||||
|
||||
// GET /api/teams/:teamId/directory-sync — list SCIM directories
|
||||
export async function GET(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ teamId: string }> },
|
||||
) {
|
||||
const { teamId } = await params;
|
||||
const auth = await getAuthenticatedAdmin(teamId);
|
||||
if (!auth) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const { directorySyncController } = await jackson();
|
||||
|
||||
const { data, error } =
|
||||
await directorySyncController.directories.getByTenantAndProduct(
|
||||
teamId,
|
||||
jacksonProduct,
|
||||
);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 400 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ directories: data });
|
||||
} catch (error: any) {
|
||||
console.error("[SCIM] Get directories error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/teams/:teamId/directory-sync — create a SCIM directory connection
|
||||
export async function POST(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ teamId: string }> },
|
||||
) {
|
||||
const { teamId } = await params;
|
||||
const auth = await getAuthenticatedAdmin(teamId);
|
||||
if (!auth) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Plan gate
|
||||
if (!SSO_ELIGIBLE_PLANS.includes(auth.team.plan)) {
|
||||
return NextResponse.json(
|
||||
{ error: "SCIM Directory Sync requires a Datarooms Premium plan" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
// Feature flag gate
|
||||
if (!auth.team.ssoEnabled) {
|
||||
return NextResponse.json(
|
||||
{ error: "SSO is not enabled for this team" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const { directorySyncController } = await jackson();
|
||||
const body = await req.json();
|
||||
const { name, type, currentDirectoryId } = body;
|
||||
|
||||
// Create the new directory first; only delete the old one on success
|
||||
const result = await directorySyncController.directories.create({
|
||||
tenant: teamId,
|
||||
product: jacksonProduct,
|
||||
name: name || "Papermark SCIM Directory",
|
||||
type: type || "azure-scim-v2",
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
return NextResponse.json(
|
||||
{ error: result.error.message },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// If replacing an existing directory, delete the old one after successful create
|
||||
if (currentDirectoryId) {
|
||||
await directorySyncController.directories.delete(currentDirectoryId);
|
||||
}
|
||||
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
} catch (error: any) {
|
||||
console.error("[SCIM] Create directory error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/teams/:teamId/directory-sync — delete a SCIM directory
|
||||
export async function DELETE(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ teamId: string }> },
|
||||
) {
|
||||
const { teamId } = await params;
|
||||
const auth = await getAuthenticatedAdmin(teamId);
|
||||
if (!auth) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const { directorySyncController } = await jackson();
|
||||
const body = await req.json();
|
||||
const { directoryId } = body;
|
||||
|
||||
if (!directoryId) {
|
||||
return NextResponse.json(
|
||||
{ error: "directoryId is required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const { error } =
|
||||
await directorySyncController.directories.delete(directoryId);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 400 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error: any) {
|
||||
console.error("[SCIM] Delete directory error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
import { jackson, jacksonProduct, samlAudience } from "@/lib/jackson";
|
||||
import prisma from "@/lib/prisma";
|
||||
import { CustomUser } from "@/lib/types";
|
||||
import { isGenericDomain } from "@/lib/utils/email-domain";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]";
|
||||
|
||||
const SSO_ELIGIBLE_PLANS = ["datarooms-premium", "datarooms-premium+old"];
|
||||
|
||||
async function getAuthenticatedAdmin(teamId: string) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return null;
|
||||
|
||||
const userId = (session.user as CustomUser).id;
|
||||
|
||||
const teamAccess = await prisma.userTeam.findUnique({
|
||||
where: { userId_teamId: { userId, teamId } },
|
||||
select: { role: true },
|
||||
});
|
||||
|
||||
if (!teamAccess || teamAccess.role !== "ADMIN") return null;
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { id: true, plan: true, ssoEnabled: true, ssoEmailDomain: true, ssoEnforcedAt: true, slug: true },
|
||||
});
|
||||
|
||||
if (!team) return null;
|
||||
|
||||
return { userId, team, email: (session.user as CustomUser).email! };
|
||||
}
|
||||
|
||||
// GET /api/teams/:teamId/saml — list SAML connections + issuer/acs info
|
||||
export async function GET(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ teamId: string }> },
|
||||
) {
|
||||
const { teamId } = await params;
|
||||
const auth = await getAuthenticatedAdmin(teamId);
|
||||
if (!auth) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const { apiController } = await jackson();
|
||||
|
||||
const connections = await apiController.getConnections({
|
||||
tenant: teamId,
|
||||
product: jacksonProduct,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
connections,
|
||||
issuer: samlAudience,
|
||||
acs: `${process.env.NEXTAUTH_URL}/api/auth/saml/callback`,
|
||||
ssoEmailDomain: auth.team.ssoEmailDomain,
|
||||
ssoEnforcedAt: auth.team.ssoEnforcedAt,
|
||||
slug: auth.team.slug,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Get connections error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/teams/:teamId/saml — create a new SAML connection
|
||||
export async function POST(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ teamId: string }> },
|
||||
) {
|
||||
const { teamId } = await params;
|
||||
const auth = await getAuthenticatedAdmin(teamId);
|
||||
if (!auth) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Plan gate
|
||||
if (!SSO_ELIGIBLE_PLANS.includes(auth.team.plan)) {
|
||||
return NextResponse.json(
|
||||
{ error: "SSO requires a Datarooms Premium plan" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
// Feature flag gate
|
||||
if (!auth.team.ssoEnabled) {
|
||||
return NextResponse.json(
|
||||
{ error: "SSO is not enabled for this team" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const { apiController } = await jackson();
|
||||
const body = await req.json();
|
||||
const { rawMetadata, encodedRawMetadata, metadataUrl, domain } = body;
|
||||
|
||||
if (!rawMetadata && !metadataUrl && !encodedRawMetadata) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Either rawMetadata, encodedRawMetadata, or metadataUrl is required",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Normalize the explicit domain provided by the admin (if any)
|
||||
const explicitDomain = typeof domain === "string"
|
||||
? domain.trim().toLowerCase().replace(/^@/, "")
|
||||
: undefined;
|
||||
|
||||
// Validate explicit domain format if provided
|
||||
if (explicitDomain && !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(explicitDomain)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid domain format. Please provide a valid domain (e.g., example.com)." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Reject public / free email provider domains – SSO should only be
|
||||
// configured for organisation-owned domains.
|
||||
if (explicitDomain && isGenericDomain(explicitDomain)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Public email domains (e.g., gmail.com, outlook.com) cannot be used for SSO. Please provide your organization's domain.",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const connection = await apiController.createSAMLConnection({
|
||||
defaultRedirectUrl: `${process.env.NEXTAUTH_URL}/auth/saml`,
|
||||
redirectUrl: process.env.NEXTAUTH_URL as string,
|
||||
tenant: teamId,
|
||||
product: jacksonProduct,
|
||||
rawMetadata: rawMetadata || undefined,
|
||||
encodedRawMetadata: encodedRawMetadata || undefined,
|
||||
metadataUrl: metadataUrl || undefined,
|
||||
});
|
||||
|
||||
// Attempt to extract a domain hint from the IdP metadata returned by the
|
||||
// SAML connection. Standard IdP entity IDs / SSO URLs sometimes contain
|
||||
// the organisation's own domain (e.g. for self-hosted IdPs). We use this
|
||||
// as an additional validation signal – if the admin supplied a domain we
|
||||
// check it is consistent; if not, we fall back to the metadata hint only
|
||||
// when it looks like a real organisation domain (not a generic IdP host).
|
||||
let metadataDomain: string | undefined;
|
||||
try {
|
||||
const idpMeta = (connection as any)?.idpMetadata;
|
||||
const candidateUrls: string[] = [
|
||||
idpMeta?.entityID,
|
||||
idpMeta?.sso?.postUrl,
|
||||
idpMeta?.sso?.redirectUrl,
|
||||
].filter(Boolean);
|
||||
|
||||
const genericIdpHosts = new Set([
|
||||
"accounts.google.com",
|
||||
"login.microsoftonline.com",
|
||||
"sts.windows.net",
|
||||
"idp.ssocircle.com",
|
||||
"www.okta.com",
|
||||
"dev.okta.com",
|
||||
"auth0.com",
|
||||
"onelogin.com",
|
||||
"pingone.com",
|
||||
]);
|
||||
|
||||
for (const raw of candidateUrls) {
|
||||
try {
|
||||
const host = new URL(raw).hostname.toLowerCase();
|
||||
// Skip well-known generic IdP hosts and public email domains
|
||||
if (
|
||||
[...genericIdpHosts].some((g) => host === g || host.endsWith(`.${g}`)) ||
|
||||
isGenericDomain(host)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
// Must have at least two labels (e.g. "company.com")
|
||||
if (host.split(".").length >= 2) {
|
||||
metadataDomain = host;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// not a valid URL – skip
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// metadata extraction is best-effort
|
||||
}
|
||||
|
||||
// Determine the validated domain to persist:
|
||||
// 1. Prefer the explicitly admin-provided domain.
|
||||
// 2. Fall back to a domain extracted from metadata (if non-generic).
|
||||
// 3. If neither is available, do NOT store a domain.
|
||||
const validatedDomain = explicitDomain || metadataDomain || undefined;
|
||||
|
||||
// Only persist ssoEmailDomain when we have a validated value
|
||||
if (validatedDomain) {
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
ssoEmailDomain: validatedDomain,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(connection, { status: 201 });
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Create connection error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH /api/teams/:teamId/saml — update SSO enforcement settings
|
||||
export async function PATCH(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ teamId: string }> },
|
||||
) {
|
||||
const { teamId } = await params;
|
||||
const auth = await getAuthenticatedAdmin(teamId);
|
||||
if (!auth) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { enforced } = body;
|
||||
|
||||
if (typeof enforced !== "boolean") {
|
||||
return NextResponse.json(
|
||||
{ error: "'enforced' must be a boolean" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Can only enforce if there's an ssoEmailDomain set (which is set when SAML is configured)
|
||||
if (enforced && !auth.team.ssoEmailDomain) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Cannot enforce SSO without a configured email domain. Please configure SAML first.",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Verify there are active SAML connections before enforcing
|
||||
if (enforced) {
|
||||
const { apiController } = await jackson();
|
||||
const connections = await apiController.getConnections({
|
||||
tenant: teamId,
|
||||
product: jacksonProduct,
|
||||
});
|
||||
|
||||
if (!connections || connections.length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Cannot enforce SSO without an active SAML connection. Please configure SAML first.",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const now = enforced ? new Date() : null;
|
||||
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
ssoEnforcedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
enforced,
|
||||
ssoEnforcedAt: now?.toISOString() ?? null,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Update enforcement error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/teams/:teamId/saml — remove a SAML connection
|
||||
export async function DELETE(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ teamId: string }> },
|
||||
) {
|
||||
const { teamId } = await params;
|
||||
const auth = await getAuthenticatedAdmin(teamId);
|
||||
if (!auth) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const { apiController } = await jackson();
|
||||
const body = await req.json();
|
||||
const { clientID, clientSecret } = body;
|
||||
|
||||
if (!clientID || !clientSecret) {
|
||||
return NextResponse.json(
|
||||
{ error: "clientID and clientSecret are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Ownership check: verify the connection belongs to this team before deleting
|
||||
const existingConnections = await apiController.getConnections({
|
||||
clientID,
|
||||
});
|
||||
|
||||
const connection = Array.isArray(existingConnections)
|
||||
? existingConnections[0]
|
||||
: existingConnections;
|
||||
|
||||
if (!connection) {
|
||||
return NextResponse.json(
|
||||
{ error: "SAML connection not found" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
if (connection.tenant !== teamId) {
|
||||
return NextResponse.json(
|
||||
{ error: "You do not have permission to delete this connection" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
await apiController.deleteConnections({
|
||||
clientID,
|
||||
clientSecret,
|
||||
tenant: teamId,
|
||||
product: jacksonProduct,
|
||||
});
|
||||
|
||||
// Check if there are remaining connections
|
||||
const remaining = await apiController.getConnections({
|
||||
tenant: teamId,
|
||||
product: jacksonProduct,
|
||||
});
|
||||
|
||||
if (!remaining || (Array.isArray(remaining) && remaining.length === 0)) {
|
||||
// No more connections — clear SSO domain and enforcement
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
ssoEmailDomain: null,
|
||||
ssoEnforcedAt: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error: any) {
|
||||
console.error("[SAML] Delete connection error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
formatZodError,
|
||||
} from "@/ee/features/workflows/lib/validation";
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]";
|
||||
import { customAlphabet } from "nanoid";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -282,6 +283,11 @@ export async function DELETE(
|
||||
select: {
|
||||
id: true,
|
||||
entryLinkId: true,
|
||||
entryLink: {
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -292,6 +298,12 @@ export async function DELETE(
|
||||
);
|
||||
}
|
||||
|
||||
// Generate a random suffix for the deleted slug to free up the original slug
|
||||
const generateDeletedSuffix = customAlphabet(
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
||||
6,
|
||||
);
|
||||
|
||||
// Delete workflow and entry link in transaction
|
||||
// Note: Steps and executions will cascade delete via Prisma relations
|
||||
await prisma.$transaction([
|
||||
@@ -299,12 +311,15 @@ export async function DELETE(
|
||||
prisma.workflow.delete({
|
||||
where: { id: workflowId },
|
||||
}),
|
||||
// Delete entry link
|
||||
// Soft delete entry link and rename slug so it can be reused
|
||||
prisma.link.update({
|
||||
where: { id: workflow.entryLinkId },
|
||||
data: {
|
||||
deletedAt: new Date(),
|
||||
isArchived: true,
|
||||
...(workflow.entryLink?.slug && {
|
||||
slug: `${workflow.entryLink.slug}-DELETED-${generateDeletedSuffix()}`,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
@@ -216,7 +216,6 @@ export async function POST(request: NextRequest) {
|
||||
linkId,
|
||||
);
|
||||
|
||||
console.log("previewSession", previewSession);
|
||||
if (!previewSession) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
@@ -237,6 +236,7 @@ export async function POST(request: NextRequest) {
|
||||
link.dataroomId!,
|
||||
);
|
||||
|
||||
|
||||
// If we have a dataroom session, use its verified status
|
||||
if (dataroomSession) {
|
||||
isEmailVerified = dataroomSession.verified;
|
||||
@@ -669,7 +669,6 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
// ** DATAROOM_VIEW **
|
||||
if (viewType === "DATAROOM_VIEW") {
|
||||
console.log("viewType is DATAROOM_VIEW");
|
||||
try {
|
||||
let newDataroomView: { id: string } | null = null;
|
||||
if (!isPreview) {
|
||||
@@ -692,7 +691,7 @@ export async function POST(request: NextRequest) {
|
||||
clickId: newId("linkView"),
|
||||
viewId: newDataroomView.id,
|
||||
linkId,
|
||||
dataroomId,
|
||||
dataroomId: link.dataroomId!,
|
||||
teamId: link.teamId!,
|
||||
enableNotification: link.enableNotification,
|
||||
isPaused,
|
||||
@@ -705,7 +704,7 @@ export async function POST(request: NextRequest) {
|
||||
try {
|
||||
await notifyDataroomAccess({
|
||||
teamId: link.teamId!,
|
||||
dataroomId,
|
||||
dataroomId: link.dataroomId!,
|
||||
linkId,
|
||||
viewerEmail: verifiedEmail ?? email,
|
||||
viewerId: viewer?.id,
|
||||
@@ -743,7 +742,7 @@ export async function POST(request: NextRequest) {
|
||||
// Create a dataroom session token if a dataroom session doesn't exist yet
|
||||
if (!dataroomSession && !isPreview) {
|
||||
const newDataroomSession = await createDataroomSession(
|
||||
dataroomId,
|
||||
link.dataroomId!,
|
||||
linkId,
|
||||
newDataroomView?.id!,
|
||||
ipAddress(request) ?? LOCALHOST_IP,
|
||||
@@ -796,9 +795,6 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
// if dataroomSession is not present, create a dataroom view first
|
||||
if (!dataroomSession) {
|
||||
console.log(
|
||||
"no dataroom session present, creating new dataroom view",
|
||||
);
|
||||
dataroomView = await prisma.view.create({
|
||||
data: { ...viewFields, viewType: "DATAROOM_VIEW" },
|
||||
select: { id: true },
|
||||
@@ -811,7 +807,7 @@ export async function POST(request: NextRequest) {
|
||||
clickId: newId("linkView"),
|
||||
viewId: dataroomView.id,
|
||||
linkId,
|
||||
dataroomId,
|
||||
dataroomId: link.dataroomId!,
|
||||
teamId: link.teamId!,
|
||||
enableNotification: link.enableNotification,
|
||||
isPaused,
|
||||
@@ -839,7 +835,7 @@ export async function POST(request: NextRequest) {
|
||||
await notifyDocumentView({
|
||||
teamId: link.teamId!,
|
||||
documentId,
|
||||
dataroomId,
|
||||
dataroomId: link.dataroomId!,
|
||||
linkId,
|
||||
viewerEmail: verifiedEmail ?? email,
|
||||
viewerId: viewer?.id,
|
||||
@@ -955,12 +951,12 @@ export async function POST(request: NextRequest) {
|
||||
link.permissionGroupId) &&
|
||||
effectiveGroupId &&
|
||||
documentId &&
|
||||
dataroomId
|
||||
link.dataroomId
|
||||
) {
|
||||
const dataroomDocument = await prisma.dataroomDocument.findUnique({
|
||||
where: {
|
||||
dataroomId_documentId: {
|
||||
dataroomId: dataroomId,
|
||||
dataroomId: link.dataroomId,
|
||||
documentId: documentId,
|
||||
},
|
||||
},
|
||||
@@ -1060,7 +1056,7 @@ export async function POST(request: NextRequest) {
|
||||
// Create a dataroom session token if a dataroom session doesn't exist yet
|
||||
if (!dataroomSession && !isPreview) {
|
||||
const newDataroomSession = await createDataroomSession(
|
||||
dataroomId,
|
||||
link.dataroomId!,
|
||||
linkId,
|
||||
dataroomView?.id!,
|
||||
ipAddress(request) ?? LOCALHOST_IP,
|
||||
|
||||
@@ -1,68 +1,49 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { DownloadIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { DownloadProgressModal } from "@/components/datarooms/download-progress-modal";
|
||||
import { ResponsiveButton } from "@/components/ui/responsive-button";
|
||||
|
||||
export default function DownloadDataroomButton({
|
||||
teamId,
|
||||
dataroomId,
|
||||
dataroomName,
|
||||
}: {
|
||||
teamId: string;
|
||||
dataroomId: string;
|
||||
dataroomName?: string;
|
||||
}) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [showDownloadModal, setShowDownloadModal] = useState(false);
|
||||
|
||||
const downloadDataroom = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
toast.promise(
|
||||
fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/download/bulk`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
{
|
||||
loading: "Downloading dataroom...",
|
||||
success: async (response) => {
|
||||
const { downloadUrl } = await response.json();
|
||||
|
||||
const link = document.createElement("a");
|
||||
link.href = downloadUrl;
|
||||
link.rel = "noopener noreferrer";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(link);
|
||||
}, 100);
|
||||
|
||||
return "Dataroom downloaded successfully.";
|
||||
},
|
||||
error: (error) => {
|
||||
console.log(error);
|
||||
return (
|
||||
error.message || "An error occurred while downloading dataroom."
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
const openDownloadModal = () => {
|
||||
// Open the modal - it will show existing downloads and allow starting new ones
|
||||
setShowDownloadModal(true);
|
||||
};
|
||||
|
||||
const handleCloseDownloadModal = () => {
|
||||
setShowDownloadModal(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<ResponsiveButton
|
||||
icon={<DownloadIcon className="h-4 w-4" />}
|
||||
text="Download"
|
||||
onClick={downloadDataroom}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
loading={isLoading}
|
||||
/>
|
||||
<>
|
||||
<ResponsiveButton
|
||||
icon={<DownloadIcon className="h-4 w-4" />}
|
||||
text="Download"
|
||||
onClick={openDownloadModal}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
/>
|
||||
|
||||
{/* Download Progress Modal */}
|
||||
<DownloadProgressModal
|
||||
isOpen={showDownloadModal}
|
||||
onClose={handleCloseDownloadModal}
|
||||
jobId={null}
|
||||
dataroomName={dataroomName}
|
||||
teamId={teamId}
|
||||
dataroomId={dataroomId}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { TeamContextType } from "@/context/team-context";
|
||||
import {
|
||||
ArchiveXIcon,
|
||||
BetweenHorizontalStartIcon,
|
||||
FilePenIcon,
|
||||
FileSlidersIcon,
|
||||
FolderInputIcon,
|
||||
MoreVertical,
|
||||
@@ -39,6 +40,7 @@ import {
|
||||
import { AddToDataroomModal } from "../documents/add-document-to-dataroom-modal";
|
||||
import { DocumentPreviewButton } from "../documents/document-preview-button";
|
||||
import FileProcessStatusBar from "../documents/file-process-status-bar";
|
||||
import { EditDataroomDocumentModal } from "./edit-dataroom-document-modal";
|
||||
import { SetUnifiedPermissionsModal } from "./groups/set-unified-permissions-modal";
|
||||
import { MoveToDataroomFolderModal } from "./move-dataroom-folder-modal";
|
||||
|
||||
@@ -74,6 +76,7 @@ export default function DataroomDocumentCard({
|
||||
const [isFirstClick, setIsFirstClick] = useState<boolean>(false);
|
||||
const [menuOpen, setMenuOpen] = useState<boolean>(false);
|
||||
const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);
|
||||
const [renameOpen, setRenameOpen] = useState<boolean>(false);
|
||||
const dropdownRef = useRef<HTMLDivElement | null>(null);
|
||||
const [addDataRoomOpen, setAddDataRoomOpen] = useState<boolean>(false);
|
||||
|
||||
@@ -92,6 +95,14 @@ export default function DataroomDocumentCard({
|
||||
}
|
||||
}, [moveFolderOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!renameOpen) {
|
||||
setTimeout(() => {
|
||||
document.body.style.pointerEvents = "";
|
||||
});
|
||||
}
|
||||
}, [renameOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(event: { target: any }) {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
|
||||
@@ -287,6 +298,15 @@ export default function DataroomDocumentCard({
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" ref={dropdownRef}>
|
||||
<DropdownMenuLabel>Actions</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRenameOpen(true);
|
||||
}}
|
||||
>
|
||||
<FilePenIcon className="mr-2 h-4 w-4" />
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
@@ -353,6 +373,15 @@ export default function DataroomDocumentCard({
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{renameOpen ? (
|
||||
<EditDataroomDocumentModal
|
||||
open={renameOpen}
|
||||
setOpen={setRenameOpen}
|
||||
documentId={dataroomDocument.document.id}
|
||||
documentName={dataroomDocument.document.name}
|
||||
dataroomId={dataroomId}
|
||||
/>
|
||||
) : null}
|
||||
{addDataRoomOpen ? (
|
||||
<AddToDataroomModal
|
||||
open={addDataRoomOpen}
|
||||
|
||||
@@ -0,0 +1,663 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Download,
|
||||
FileArchive,
|
||||
Loader2,
|
||||
Plus,
|
||||
XCircle,
|
||||
} from "lucide-react";
|
||||
|
||||
import { DownloadJob } from "@/lib/redis-download-job-store";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
|
||||
export interface DownloadJobStatus {
|
||||
id: string;
|
||||
status: "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED";
|
||||
progress: number;
|
||||
totalFiles: number;
|
||||
processedFiles: number;
|
||||
downloadUrls?: string[];
|
||||
error?: string;
|
||||
isReady: boolean;
|
||||
dataroomName: string;
|
||||
createdAt: string;
|
||||
completedAt?: string;
|
||||
expiresAt?: string;
|
||||
}
|
||||
|
||||
interface DownloadProgressModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
jobId: string | null;
|
||||
dataroomName?: string;
|
||||
// For team member downloads (uses next-auth session)
|
||||
teamId: string;
|
||||
dataroomId: string;
|
||||
}
|
||||
|
||||
export function DownloadProgressModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
jobId,
|
||||
dataroomName,
|
||||
teamId,
|
||||
dataroomId,
|
||||
}: DownloadProgressModalProps) {
|
||||
const [status, setStatus] = useState<DownloadJobStatus | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isPolling, setIsPolling] = useState(false);
|
||||
const [existingDownloads, setExistingDownloads] = useState<DownloadJob[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showNewDownload, setShowNewDownload] = useState(false);
|
||||
const [isStartingDownload, setIsStartingDownload] = useState(false);
|
||||
const [expandedDownloadId, setExpandedDownloadId] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Cleanup interval on component unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (pollIntervalRef.current) {
|
||||
clearInterval(pollIntervalRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Fetch existing downloads when modal opens
|
||||
useEffect(() => {
|
||||
if (!isOpen || !teamId || !dataroomId) return;
|
||||
|
||||
const fetchExistingDownloads = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const endpoint = `/api/teams/${teamId}/datarooms/${dataroomId}/download/jobs`;
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const downloads = await response.json();
|
||||
setExistingDownloads(downloads);
|
||||
|
||||
// If we have a current jobId, show the new download view
|
||||
if (jobId) {
|
||||
setShowNewDownload(true);
|
||||
}
|
||||
} else {
|
||||
console.error("Failed to fetch existing downloads");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching existing downloads:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchExistingDownloads();
|
||||
}, [isOpen, dataroomId, teamId, jobId]);
|
||||
|
||||
const fetchStatus = useCallback(
|
||||
async (statusJobId: string) => {
|
||||
if (!statusJobId || !teamId || !dataroomId) return;
|
||||
|
||||
try {
|
||||
const url = `/api/teams/${teamId}/datarooms/${dataroomId}/download/${statusJobId}`;
|
||||
|
||||
const response = await fetch(url, {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || "Failed to fetch download status");
|
||||
}
|
||||
const data = await response.json();
|
||||
setStatus(data);
|
||||
setError(null);
|
||||
|
||||
// Stop polling when job is completed or failed
|
||||
if (data.status === "COMPLETED" || data.status === "FAILED") {
|
||||
setIsPolling(false);
|
||||
if (pollIntervalRef.current) {
|
||||
clearInterval(pollIntervalRef.current);
|
||||
pollIntervalRef.current = null;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "An error occurred");
|
||||
setIsPolling(false);
|
||||
}
|
||||
},
|
||||
[teamId, dataroomId],
|
||||
);
|
||||
|
||||
// Start polling when we have a jobId and showNewDownload is true
|
||||
useEffect(() => {
|
||||
if (isOpen && jobId && showNewDownload) {
|
||||
setIsPolling(true);
|
||||
setStatus(null);
|
||||
setError(null);
|
||||
fetchStatus(jobId);
|
||||
|
||||
// Start polling interval
|
||||
pollIntervalRef.current = setInterval(() => fetchStatus(jobId), 2000);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (pollIntervalRef.current) {
|
||||
clearInterval(pollIntervalRef.current);
|
||||
pollIntervalRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [isOpen, jobId, showNewDownload, fetchStatus]);
|
||||
|
||||
const startNewDownload = async () => {
|
||||
if (!teamId || !dataroomId) {
|
||||
setError("Missing required parameters to start download");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsStartingDownload(true);
|
||||
setShowNewDownload(true);
|
||||
|
||||
try {
|
||||
const endpoint = `/api/teams/${teamId}/datarooms/${dataroomId}/download/bulk`;
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || "Failed to start download");
|
||||
}
|
||||
|
||||
if (data.jobId) {
|
||||
// Start polling for this job
|
||||
setStatus({
|
||||
id: data.jobId,
|
||||
status: data.status || "PENDING",
|
||||
progress: 0,
|
||||
totalFiles: 0,
|
||||
processedFiles: 0,
|
||||
isReady: false,
|
||||
dataroomName: dataroomName || "",
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
setIsPolling(true);
|
||||
|
||||
const statusUrl = `/api/teams/${teamId}/datarooms/${dataroomId}/download/${data.jobId}`;
|
||||
|
||||
pollIntervalRef.current = setInterval(async () => {
|
||||
const statusResponse = await fetch(statusUrl, {
|
||||
credentials: "include",
|
||||
});
|
||||
if (statusResponse.ok) {
|
||||
const statusData = await statusResponse.json();
|
||||
setStatus(statusData);
|
||||
|
||||
if (
|
||||
statusData.status === "COMPLETED" ||
|
||||
statusData.status === "FAILED"
|
||||
) {
|
||||
setIsPolling(false);
|
||||
if (pollIntervalRef.current) {
|
||||
clearInterval(pollIntervalRef.current);
|
||||
pollIntervalRef.current = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "An error occurred");
|
||||
setShowNewDownload(false);
|
||||
} finally {
|
||||
setIsStartingDownload(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownload = (url: string) => {
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.rel = "noopener noreferrer";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(link);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
const handleDownloadAll = async (urls: string[]) => {
|
||||
// Download files sequentially with longer delays to avoid browser blocking
|
||||
// Browsers typically block rapid automatic downloads as a security measure
|
||||
console.log("Downloading all files:", urls);
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
handleDownload(urls[i]);
|
||||
// Wait 1.5 seconds between downloads to avoid browser blocking
|
||||
if (i < urls.length - 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
if (pollIntervalRef.current) {
|
||||
clearInterval(pollIntervalRef.current);
|
||||
pollIntervalRef.current = null;
|
||||
}
|
||||
setStatus(null);
|
||||
setError(null);
|
||||
setIsPolling(false);
|
||||
setShowNewDownload(false);
|
||||
setExistingDownloads([]);
|
||||
setExpandedDownloadId(null);
|
||||
setLoading(true);
|
||||
onClose();
|
||||
};
|
||||
|
||||
const getStatusIcon = (jobStatus?: string) => {
|
||||
switch (jobStatus) {
|
||||
case "PENDING":
|
||||
return (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
);
|
||||
case "PROCESSING":
|
||||
return <FileArchive className="h-4 w-4 animate-pulse text-primary" />;
|
||||
case "COMPLETED":
|
||||
return <CheckCircle2 className="h-4 w-4 text-green-500" />;
|
||||
case "FAILED":
|
||||
return <XCircle className="h-4 w-4 text-destructive" />;
|
||||
default:
|
||||
return (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusColor = (jobStatus: string) => {
|
||||
switch (jobStatus) {
|
||||
case "COMPLETED":
|
||||
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300";
|
||||
case "PROCESSING":
|
||||
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300";
|
||||
case "PENDING":
|
||||
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300";
|
||||
case "FAILED":
|
||||
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300";
|
||||
default:
|
||||
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300";
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleString();
|
||||
};
|
||||
|
||||
const formatExpirationTime = (expiresAt?: string) => {
|
||||
if (!expiresAt) return null;
|
||||
|
||||
const expires = new Date(expiresAt);
|
||||
const now = new Date();
|
||||
const diffMs = expires.getTime() - now.getTime();
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
|
||||
if (diffDays > 0) {
|
||||
return `${diffDays} day${diffDays > 1 ? "s" : ""}`;
|
||||
} else if (diffHours > 0) {
|
||||
return `${diffHours} hour${diffHours > 1 ? "s" : ""}`;
|
||||
}
|
||||
return "less than an hour";
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Download {dataroomName || status?.dataroomName || "Dataroom"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{showNewDownload
|
||||
? status?.status === "COMPLETED"
|
||||
? "Your files are ready to download."
|
||||
: "Please wait while we prepare your files..."
|
||||
: "View previous downloads or start a new one."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : showNewDownload ? (
|
||||
// Show download progress
|
||||
<div className="flex flex-col items-center space-y-4 py-6">
|
||||
{/* Status Icon */}
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted">
|
||||
{status?.status === "COMPLETED" ? (
|
||||
<CheckCircle2 className="h-8 w-8 text-green-500" />
|
||||
) : status?.status === "FAILED" ? (
|
||||
<XCircle className="h-8 w-8 text-destructive" />
|
||||
) : (
|
||||
<FileArchive className="h-8 w-8 animate-pulse text-primary" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Message */}
|
||||
<p
|
||||
className={cn(
|
||||
"text-center text-sm",
|
||||
status?.status === "FAILED"
|
||||
? "text-destructive"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{!status
|
||||
? "Starting download..."
|
||||
: status.status === "PENDING"
|
||||
? "Preparing your download..."
|
||||
: status.status === "PROCESSING"
|
||||
? `Processing ${status.processedFiles} of ${status.totalFiles} files...`
|
||||
: status.status === "COMPLETED"
|
||||
? status.downloadUrls && status.downloadUrls.length > 1
|
||||
? `Your download is ready! ${status.downloadUrls.length} ZIP files have been created.`
|
||||
: "Your download is ready!"
|
||||
: status.error || "Download failed. Please try again."}
|
||||
</p>
|
||||
|
||||
{/* Progress Bar */}
|
||||
{(status?.status === "PROCESSING" ||
|
||||
status?.status === "PENDING") && (
|
||||
<div className="w-full space-y-2">
|
||||
<Progress
|
||||
value={status?.progress || 0}
|
||||
text={`${status?.progress || 0}%`}
|
||||
className="h-4"
|
||||
/>
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
{status?.totalFiles
|
||||
? `${status.processedFiles || 0} / ${status.totalFiles} files`
|
||||
: "Calculating..."}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Download Links */}
|
||||
{status?.status === "COMPLETED" && status.downloadUrls && (
|
||||
<div className="w-full space-y-3">
|
||||
{status.downloadUrls.length === 1 ? (
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={() => handleDownload(status.downloadUrls![0])}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download ZIP
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
{status.downloadUrls.length <= 3 ? (
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={() => handleDownloadAll(status.downloadUrls!)}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download All ({status.downloadUrls.length} files)
|
||||
</Button>
|
||||
) : (
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
Your download has been split into{" "}
|
||||
{status.downloadUrls.length} parts. Download each part
|
||||
below:
|
||||
</p>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
{status.downloadUrls.length <= 3 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Or download individually:
|
||||
</p>
|
||||
)}
|
||||
<div className="max-h-48 space-y-1 overflow-y-auto">
|
||||
{status.downloadUrls.map((url, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
variant={
|
||||
status.downloadUrls!.length > 3
|
||||
? "default"
|
||||
: "outline"
|
||||
}
|
||||
size="sm"
|
||||
className="w-full justify-start"
|
||||
onClick={() => handleDownload(url)}
|
||||
>
|
||||
<FileArchive className="mr-2 h-3 w-3" />
|
||||
Part {index + 1} of {status.downloadUrls!.length}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Expiration Notice */}
|
||||
{status.expiresAt && (
|
||||
<div className="flex items-center justify-center gap-1 text-xs text-muted-foreground">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
<span>
|
||||
Download expires in{" "}
|
||||
{formatExpirationTime(status.expiresAt)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error State */}
|
||||
{status?.status === "FAILED" && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowNewDownload(false)}
|
||||
>
|
||||
Back to Downloads
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Back button for processing state */}
|
||||
{(status?.status === "PROCESSING" ||
|
||||
status?.status === "PENDING") && (
|
||||
<DialogFooter className="w-full sm:justify-center">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
You can close this dialog. We'll notify you when your
|
||||
download is ready.
|
||||
</p>
|
||||
</DialogFooter>
|
||||
)}
|
||||
|
||||
{/* Loading Error */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Show existing downloads and new download option
|
||||
<div className="space-y-4 py-2">
|
||||
{existingDownloads.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium">Recent Downloads</h4>
|
||||
<div className="max-h-64 space-y-2 overflow-y-auto">
|
||||
{existingDownloads.map((download) => (
|
||||
<div key={download.id} className="space-y-2">
|
||||
<div className="flex items-center justify-between rounded-md border p-3">
|
||||
<div className="flex-1 space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
{getStatusIcon(download.status)}
|
||||
<span
|
||||
className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${getStatusColor(download.status)}`}
|
||||
>
|
||||
{download.status}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{formatDate(download.createdAt)}
|
||||
</div>
|
||||
{download.totalFiles > 0 && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{download.totalFiles} files
|
||||
{download.downloadUrls &&
|
||||
download.downloadUrls.length > 1 &&
|
||||
` (${download.downloadUrls.length} ZIPs)`}
|
||||
</div>
|
||||
)}
|
||||
{download.expiresAt && (
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Expires in{" "}
|
||||
{formatExpirationTime(download.expiresAt)}
|
||||
</div>
|
||||
)}
|
||||
{download.error && (
|
||||
<p className="text-xs text-destructive">
|
||||
{download.error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{download.status === "COMPLETED" &&
|
||||
download.downloadUrls &&
|
||||
download.downloadUrls.length > 0 &&
|
||||
(download.downloadUrls.length === 1 ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
handleDownload(download.downloadUrls![0])
|
||||
}
|
||||
>
|
||||
<Download className="mr-1 h-3 w-3" />
|
||||
Download
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
setExpandedDownloadId(
|
||||
expandedDownloadId === download.id
|
||||
? null
|
||||
: download.id,
|
||||
)
|
||||
}
|
||||
>
|
||||
{expandedDownloadId === download.id ? (
|
||||
<>
|
||||
<ChevronUp className="mr-1 h-3 w-3" />
|
||||
Hide
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronDown className="mr-1 h-3 w-3" />
|
||||
Show Downloads
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
{(download.status === "PENDING" ||
|
||||
download.status === "PROCESSING") && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
{download.progress}%
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Expanded download parts */}
|
||||
{expandedDownloadId === download.id &&
|
||||
download.downloadUrls &&
|
||||
download.downloadUrls.length > 1 && (
|
||||
<div className="space-y-2 rounded-md border bg-muted/30 p-3">
|
||||
<Button
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() =>
|
||||
handleDownloadAll(download.downloadUrls!)
|
||||
}
|
||||
>
|
||||
<Download className="mr-2 h-3 w-3" />
|
||||
Download All ({download.downloadUrls.length}{" "}
|
||||
parts)
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Or download individually:
|
||||
</p>
|
||||
<div className="max-h-32 space-y-1 overflow-y-auto">
|
||||
{download.downloadUrls.map((url, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full justify-start"
|
||||
onClick={() => handleDownload(url)}
|
||||
>
|
||||
<FileArchive className="mr-2 h-3 w-3" />
|
||||
Part {index + 1} of{" "}
|
||||
{download.downloadUrls!.length}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-4 text-center text-sm text-muted-foreground">
|
||||
No previous downloads found
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border-t pt-4">
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={startNewDownload}
|
||||
disabled={isStartingDownload}
|
||||
>
|
||||
{isStartingDownload ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Start New Download
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { useTeam } from "@/context/team-context";
|
||||
import { toast } from "sonner";
|
||||
import { mutate } from "swr";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
export function EditDataroomDocumentModal({
|
||||
open,
|
||||
setOpen,
|
||||
documentId,
|
||||
documentName,
|
||||
dataroomId,
|
||||
}: {
|
||||
open: boolean;
|
||||
setOpen: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
documentId: string;
|
||||
documentName: string;
|
||||
dataroomId: string;
|
||||
}) {
|
||||
const [name, setName] = useState<string>(documentName);
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
|
||||
const teamInfo = useTeam();
|
||||
const router = useRouter();
|
||||
const currentFolderPath = router.query.name as string[] | undefined;
|
||||
|
||||
const editDocumentNameSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.min(1, {
|
||||
message: "Please provide a document name.",
|
||||
})
|
||||
.max(255, {
|
||||
message: "Document name is too long.",
|
||||
}),
|
||||
});
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const validation = editDocumentNameSchema.safeParse({ name });
|
||||
if (!validation.success) {
|
||||
return toast.error(validation.error.errors[0].message);
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/teams/${teamInfo?.currentTeam?.id}/documents/${documentId}/update-name`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: name.trim(),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const { error, message } = await response.json();
|
||||
setLoading(false);
|
||||
toast.error(error || message || "Failed to update document name");
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success("Document name updated successfully!");
|
||||
|
||||
// Revalidate the dataroom documents cache
|
||||
mutate(
|
||||
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,
|
||||
);
|
||||
// Revalidate folder documents if the document is in a folder
|
||||
if (currentFolderPath) {
|
||||
mutate(
|
||||
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents/${currentFolderPath.join("/")}`,
|
||||
);
|
||||
}
|
||||
// Revalidate the dataroom folders tree for sidebar
|
||||
mutate(
|
||||
`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders?tree=true`,
|
||||
);
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
toast.error("Error updating document name. Please try again.");
|
||||
return;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader className="text-start">
|
||||
<DialogTitle>Rename Document</DialogTitle>
|
||||
<DialogDescription>Enter a new document name.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Label htmlFor="document-name-update" className="opacity-80">
|
||||
Document Name
|
||||
</Label>
|
||||
<Input
|
||||
id="document-name-update"
|
||||
value={name}
|
||||
placeholder="document-name"
|
||||
className="mb-4 mt-1 w-full"
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button type="submit" className="h-9 w-full" loading={loading}>
|
||||
Update name
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,766 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { useTeam } from "@/context/team-context";
|
||||
import { BookOpenIcon, EyeIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { mutate } from "swr";
|
||||
|
||||
import { usePlan } from "@/lib/swr/use-billing";
|
||||
import { uploadImage } from "@/lib/utils";
|
||||
|
||||
import PlanBadge from "@/components/billing/plan-badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import LoadingSpinner from "@/components/ui/loading-spinner";
|
||||
import { RichTextEditor } from "@/components/ui/rich-text-editor";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
|
||||
interface IntroductionSettingsProps {
|
||||
dataroomId: string;
|
||||
}
|
||||
|
||||
interface FolderItem {
|
||||
id: string;
|
||||
name: string;
|
||||
documents?: { document: { name: string } }[];
|
||||
}
|
||||
|
||||
interface DocumentItem {
|
||||
document: { name: string };
|
||||
}
|
||||
|
||||
// Generate TipTap JSON content for introduction based on dataroom structure
|
||||
function generateIntroductionContent(
|
||||
dataroomName: string,
|
||||
folders: FolderItem[],
|
||||
rootDocuments: DocumentItem[],
|
||||
): any {
|
||||
const content: any[] = [];
|
||||
|
||||
// Overview paragraph (no "Welcome to" repetition)
|
||||
content.push({
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `This data room contains confidential documents and materials prepared for your review. Please take a moment to familiarize yourself with the structure below.`,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// What's Inside section
|
||||
content.push({
|
||||
type: "heading",
|
||||
attrs: { level: 2 },
|
||||
content: [{ type: "text", text: "What's Inside" }],
|
||||
});
|
||||
|
||||
// If there are folders, list them
|
||||
if (folders.length > 0) {
|
||||
const folderList = {
|
||||
type: "bulletList",
|
||||
content: folders.slice(0, 8).map((folder) => ({
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: folder.name,
|
||||
marks: [{ type: "bold" }],
|
||||
},
|
||||
...(folder.documents && folder.documents.length > 0
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: ` — ${folder.documents.length} document${folder.documents.length > 1 ? "s" : ""}`,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
],
|
||||
})),
|
||||
};
|
||||
content.push(folderList);
|
||||
|
||||
if (folders.length > 8) {
|
||||
content.push({
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `...and ${folders.length - 8} more sections.`,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Show placeholder sections if dataroom is empty
|
||||
const placeholderList = {
|
||||
type: "bulletList",
|
||||
content: [
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{ type: "text", text: "Section 1", marks: [{ type: "bold" }] },
|
||||
{ type: "text", text: " — Company Overview & Key Documents" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{ type: "text", text: "Section 2", marks: [{ type: "bold" }] },
|
||||
{ type: "text", text: " — Financial Information" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{ type: "text", text: "Section 3", marks: [{ type: "bold" }] },
|
||||
{ type: "text", text: " — Legal & Compliance" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{ type: "text", text: "Section 4", marks: [{ type: "bold" }] },
|
||||
{ type: "text", text: " — Additional Materials" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
content.push(placeholderList);
|
||||
}
|
||||
|
||||
// If there are root documents, mention them
|
||||
if (rootDocuments.length > 0) {
|
||||
content.push({
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `There ${rootDocuments.length === 1 ? "is" : "are"} also ${rootDocuments.length} document${rootDocuments.length > 1 ? "s" : ""} available at the root level for quick access.`,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
// How to Navigate section
|
||||
content.push({
|
||||
type: "heading",
|
||||
attrs: { level: 2 },
|
||||
content: [{ type: "text", text: "How to Navigate" }],
|
||||
});
|
||||
|
||||
content.push({
|
||||
type: "bulletList",
|
||||
content: [
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Use the sidebar on the left to browse sections and folders",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Click on any document to open and view it",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Use the search function to find specific documents quickly",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Placeholder for navigation screenshot
|
||||
|
||||
// Q&A and Conversations section
|
||||
content.push({
|
||||
type: "heading",
|
||||
attrs: { level: 2 },
|
||||
content: [{ type: "text", text: "Q&A and Conversations" }],
|
||||
});
|
||||
|
||||
content.push({
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Have questions about specific documents? You can start a conversation directly within the data room. Use the chat feature to ask questions and get answers from our team.",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
content.push({
|
||||
type: "bulletList",
|
||||
content: [
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Click the chat icon to start a new conversation",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Ask questions about any document or section",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "listItem",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Receive timely responses from our team",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Placeholder for conversations screenshot
|
||||
|
||||
// Need Help section
|
||||
content.push({
|
||||
type: "heading",
|
||||
attrs: { level: 2 },
|
||||
content: [{ type: "text", text: "Need Help?" }],
|
||||
});
|
||||
|
||||
content.push({
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "If you have any questions or need assistance, please reach out to your designated contact. We're here to help you navigate this data room effectively.",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
type: "doc",
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
// Helper to render inline text nodes with marks (bold, italic, etc.)
|
||||
function renderInlineContent(nodes: any[] | undefined): React.ReactNode {
|
||||
if (!nodes) return null;
|
||||
|
||||
return nodes.map((textNode: any, textIndex: number) => {
|
||||
if (textNode.type === "text") {
|
||||
let text: React.ReactNode = textNode.text;
|
||||
if (textNode.marks) {
|
||||
textNode.marks.forEach((mark: any) => {
|
||||
if (mark.type === "bold") {
|
||||
text = (
|
||||
<strong key={`bold-${textIndex}`} className="font-semibold">
|
||||
{text}
|
||||
</strong>
|
||||
);
|
||||
} else if (mark.type === "italic") {
|
||||
text = (
|
||||
<em key={`italic-${textIndex}`} className="italic">
|
||||
{text}
|
||||
</em>
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
return <React.Fragment key={textIndex}>{text}</React.Fragment>;
|
||||
} else if (textNode.type === "image") {
|
||||
return (
|
||||
<img
|
||||
key={textIndex}
|
||||
src={textNode.attrs?.src}
|
||||
alt={textNode.attrs?.alt || ""}
|
||||
className="my-2 h-auto max-w-full rounded-md"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
// Render TipTap JSON content for preview
|
||||
function renderContent(content: any): React.ReactNode {
|
||||
if (!content || !content.content) return null;
|
||||
|
||||
return content.content.map((node: any, index: number) => {
|
||||
if (node.type === "heading") {
|
||||
const level = node.attrs?.level || 1;
|
||||
const text = node.content?.[0]?.text || "";
|
||||
if (level === 1) {
|
||||
return (
|
||||
<h1
|
||||
key={index}
|
||||
className="mb-3 mt-4 text-xl font-bold text-gray-900 first:mt-0"
|
||||
>
|
||||
{text}
|
||||
</h1>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<h2
|
||||
key={index}
|
||||
className="mb-2 mt-4 text-base font-semibold text-gray-800 first:mt-0"
|
||||
>
|
||||
{text}
|
||||
</h2>
|
||||
);
|
||||
} else if (node.type === "paragraph") {
|
||||
return (
|
||||
<p key={index} className="mb-3 text-sm leading-relaxed text-gray-700">
|
||||
{renderInlineContent(node.content)}
|
||||
</p>
|
||||
);
|
||||
} else if (node.type === "bulletList") {
|
||||
return (
|
||||
<ul key={index} className="mb-3 list-disc pl-5 text-sm text-gray-700">
|
||||
{node.content?.map((item: any, itemIndex: number) => (
|
||||
<li key={itemIndex} className="mb-1">
|
||||
{renderInlineContent(item.content?.[0]?.content)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
} else if (node.type === "orderedList") {
|
||||
return (
|
||||
<ol
|
||||
key={index}
|
||||
className="mb-3 list-decimal pl-5 text-sm text-gray-700"
|
||||
>
|
||||
{node.content?.map((item: any, itemIndex: number) => (
|
||||
<li key={itemIndex} className="mb-1">
|
||||
{renderInlineContent(item.content?.[0]?.content)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
} else if (node.type === "blockquote") {
|
||||
return (
|
||||
<blockquote
|
||||
key={index}
|
||||
className="mb-3 border-l-4 border-gray-300 pl-4 italic text-gray-600"
|
||||
>
|
||||
{node.content?.map((p: any) =>
|
||||
p.content?.map((textNode: any) =>
|
||||
textNode.type === "text" ? textNode.text : null,
|
||||
),
|
||||
)}
|
||||
</blockquote>
|
||||
);
|
||||
} else if (node.type === "image") {
|
||||
return (
|
||||
<img
|
||||
key={index}
|
||||
src={node.attrs?.src}
|
||||
alt={node.attrs?.alt || ""}
|
||||
className="my-3 h-auto max-w-full rounded-md"
|
||||
/>
|
||||
);
|
||||
} else if (node.type === "youtube") {
|
||||
// Extract video ID from the src URL
|
||||
const src = node.attrs?.src || "";
|
||||
let videoId = "";
|
||||
|
||||
// Handle different YouTube URL formats
|
||||
const youtubeMatch = src.match(
|
||||
/(?:youtube(?:-nocookie)?\.com\/(?:embed\/|watch\?v=)|youtu\.be\/)([^?&]+)/,
|
||||
);
|
||||
if (youtubeMatch) {
|
||||
videoId = youtubeMatch[1];
|
||||
}
|
||||
|
||||
if (!videoId) return null;
|
||||
|
||||
return (
|
||||
<div key={index} className="my-4 aspect-video w-full">
|
||||
<iframe
|
||||
src={`https://www.youtube-nocookie.com/embed/${videoId}`}
|
||||
title="YouTube video"
|
||||
className="h-full w-full rounded-lg"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
export default function IntroductionSettings({
|
||||
dataroomId,
|
||||
}: IntroductionSettingsProps) {
|
||||
const teamInfo = useTeam();
|
||||
const teamId = teamInfo?.currentTeam?.id;
|
||||
const { isDataroomsPlus, isTrial } = usePlan();
|
||||
|
||||
const [isFetching, setIsFetching] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [introductionEnabled, setIntroductionEnabled] = useState(false);
|
||||
const [introductionContent, setIntroductionContent] = useState<any>({
|
||||
type: "doc",
|
||||
content: [],
|
||||
});
|
||||
const [showPreview, setShowPreview] = useState(false);
|
||||
const [dataroomName, setDataroomName] = useState<string>("Data Room");
|
||||
|
||||
const isFeatureAvailable = isDataroomsPlus || isTrial;
|
||||
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const hasInitialLoadRef = useRef(false);
|
||||
const skipNextAutosaveRef = useRef(false);
|
||||
|
||||
// Fetch current introduction settings from dataroom
|
||||
useEffect(() => {
|
||||
const fetchSettings = async () => {
|
||||
if (!teamId) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/teams/${teamId}/datarooms/${dataroomId}`,
|
||||
);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setIntroductionEnabled(data.introductionEnabled || false);
|
||||
setDataroomName(data.name || "Data Room");
|
||||
|
||||
const existingContent = data.introductionContent;
|
||||
const hasExistingContent =
|
||||
existingContent?.content && existingContent.content.length > 0;
|
||||
|
||||
if (hasExistingContent) {
|
||||
setIntroductionContent(existingContent);
|
||||
} else {
|
||||
// Auto-generate introduction if empty
|
||||
try {
|
||||
const foldersResponse = await fetch(
|
||||
`/api/teams/${teamId}/datarooms/${dataroomId}/folders?include_documents=true`,
|
||||
);
|
||||
|
||||
let folders: FolderItem[] = [];
|
||||
let rootDocuments: DocumentItem[] = [];
|
||||
|
||||
if (foldersResponse.ok) {
|
||||
const foldersData = await foldersResponse.json();
|
||||
folders = foldersData.filter(
|
||||
(item: any) => item.name && !item.document,
|
||||
);
|
||||
rootDocuments = foldersData.filter(
|
||||
(item: any) => item.document,
|
||||
);
|
||||
}
|
||||
|
||||
const generatedContent = generateIntroductionContent(
|
||||
data.name || "Data Room",
|
||||
folders,
|
||||
rootDocuments,
|
||||
);
|
||||
setIntroductionContent(generatedContent);
|
||||
} catch (genError) {
|
||||
console.error("Failed to auto-generate introduction:", genError);
|
||||
setIntroductionContent({ type: "doc", content: [] });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch introduction settings:", error);
|
||||
} finally {
|
||||
setIsFetching(false);
|
||||
hasInitialLoadRef.current = true;
|
||||
skipNextAutosaveRef.current = true;
|
||||
}
|
||||
};
|
||||
|
||||
fetchSettings();
|
||||
}, [teamId, dataroomId]);
|
||||
|
||||
// Auto-save function
|
||||
const saveSettings = useCallback(
|
||||
async (enabled: boolean, content: any) => {
|
||||
if (!teamId || !isFeatureAvailable) return;
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/teams/${teamId}/datarooms/${dataroomId}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
introductionEnabled: enabled,
|
||||
introductionContent: content,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
await mutate(`/api/teams/${teamId}/datarooms/${dataroomId}`);
|
||||
} else {
|
||||
toast.error("Failed to save introduction settings");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to save introduction settings:", error);
|
||||
toast.error("Failed to save introduction settings");
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
},
|
||||
[teamId, dataroomId, isFeatureAvailable],
|
||||
);
|
||||
|
||||
// Debounced auto-save on content change
|
||||
useEffect(() => {
|
||||
if (!hasInitialLoadRef.current) return;
|
||||
|
||||
// Skip the first auto-save pass after initial load
|
||||
if (skipNextAutosaveRef.current) {
|
||||
skipNextAutosaveRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (saveTimeoutRef.current) {
|
||||
clearTimeout(saveTimeoutRef.current);
|
||||
}
|
||||
|
||||
saveTimeoutRef.current = setTimeout(() => {
|
||||
saveSettings(introductionEnabled, introductionContent);
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
if (saveTimeoutRef.current) {
|
||||
clearTimeout(saveTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, [introductionContent, introductionEnabled, saveSettings]);
|
||||
|
||||
const handleImageUpload = async (file: File): Promise<string> => {
|
||||
try {
|
||||
const imageUrl = await uploadImage(file, "assets");
|
||||
return imageUrl;
|
||||
} catch (error) {
|
||||
console.error("Failed to upload image:", error);
|
||||
throw new Error("Failed to upload image");
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggle = (checked: boolean) => {
|
||||
if (!isFeatureAvailable) {
|
||||
toast.error("This feature is only available on Data Rooms Plus plan");
|
||||
return;
|
||||
}
|
||||
setIntroductionEnabled(checked);
|
||||
if (checked) {
|
||||
toast.success("Introduction page enabled");
|
||||
}
|
||||
};
|
||||
|
||||
const hasContent =
|
||||
introductionContent?.content && introductionContent.content.length > 0;
|
||||
|
||||
if (isFetching) {
|
||||
return (
|
||||
<Card className="bg-transparent">
|
||||
<CardContent className="flex items-center justify-center py-10">
|
||||
<LoadingSpinner className="h-6 w-6" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="bg-transparent">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
Introduction Page{" "}
|
||||
{!isFeatureAvailable && <PlanBadge plan="data rooms plus" />}
|
||||
{isSaving && (
|
||||
<span className="text-xs font-normal text-muted-foreground">
|
||||
Saving...
|
||||
</span>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Create an introduction page that will be shown to viewers when they
|
||||
first access your data room. Write your message based on the premade
|
||||
template below. You can edit, add and remove sections as you see fit.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Toggle and Preview */}
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="introduction-toggle"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<BookOpenIcon className="h-4 w-4" />
|
||||
Show introduction on first visit
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setShowPreview(true)}
|
||||
disabled={!hasContent}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
<EyeIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Preview introduction</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
<Switch
|
||||
id="introduction-toggle"
|
||||
checked={introductionEnabled}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={!isFeatureAvailable}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rich Text Editor */}
|
||||
<div className="space-y-2">
|
||||
<RichTextEditor
|
||||
content={introductionContent}
|
||||
onChange={setIntroductionContent}
|
||||
placeholder="Welcome to our data room! Here you'll find..."
|
||||
onImageUpload={handleImageUpload}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Preview Dialog */}
|
||||
<Dialog open={showPreview} onOpenChange={setShowPreview}>
|
||||
<DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden border-0 p-0 shadow-2xl sm:max-w-xl sm:rounded-2xl md:max-w-2xl">
|
||||
<DialogHeader className="border-b border-gray-100 bg-gray-50 px-4 py-6 dark:border-gray-800 dark:bg-gray-900 sm:px-6">
|
||||
<p className="mb-1 text-xs text-muted-foreground">
|
||||
This is a preview
|
||||
</p>
|
||||
<DialogTitle className="text-xl font-semibold">
|
||||
Welcome to {dataroomName}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[55vh] px-4 py-5 sm:px-6">
|
||||
<div className="prose prose-sm max-w-none dark:prose-invert">
|
||||
{renderContent(introductionContent)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="flex justify-end border-t border-gray-100 bg-gray-50 px-4 py-3 dark:border-gray-800 dark:bg-gray-900 sm:px-6 sm:py-4">
|
||||
<Button onClick={() => setShowPreview(false)}>
|
||||
Continue to Data Room
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</CardContent>
|
||||
<CardFooter className="flex items-center rounded-b-lg border-t bg-muted px-6 py-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This page will appear as a welcome popup when visitors first open the
|
||||
data room. Changes are saved automatically.
|
||||
</p>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { BellIcon, CogIcon, DownloadIcon, ShieldIcon } from "lucide-react";
|
||||
import {
|
||||
BellIcon,
|
||||
BookOpenIcon,
|
||||
CogIcon,
|
||||
DownloadIcon,
|
||||
ShieldIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@@ -27,6 +33,18 @@ export default function SettingsTabs({ dataroomId }: SettingsTabsProps) {
|
||||
<CogIcon className="h-4 w-4" />
|
||||
General
|
||||
</Link>
|
||||
<Link
|
||||
href={`/datarooms/${dataroomId}/settings/introduction`}
|
||||
className={cn(
|
||||
"flex items-center gap-x-2 rounded-md p-2 text-primary hover:bg-muted",
|
||||
{
|
||||
"bg-muted font-medium": router.pathname.includes("introduction"),
|
||||
},
|
||||
)}
|
||||
>
|
||||
<BookOpenIcon className="h-4 w-4" />
|
||||
Introduction
|
||||
</Link>
|
||||
<Link
|
||||
href={`/datarooms/${dataroomId}/settings/notifications`}
|
||||
className={cn(
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState, type ElementType } from "react";
|
||||
|
||||
import { useTeam } from "@/context/team-context";
|
||||
import { PlanEnum } from "@/ee/stripe/constants";
|
||||
import { LinkType } from "@prisma/client";
|
||||
import {
|
||||
AlertTriangleIcon,
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { z } from "zod";
|
||||
import { useDebounce } from "use-debounce";
|
||||
|
||||
import { useAnalytics } from "@/lib/analytics";
|
||||
import { validDomainRegex } from "@/lib/domains";
|
||||
import { usePlan } from "@/lib/swr/use-billing";
|
||||
import useLimits from "@/lib/swr/use-limits";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -22,10 +29,77 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import LoadingSpinner from "@/components/ui/loading-spinner";
|
||||
|
||||
import { UpgradePlanModal } from "../billing/upgrade-plan-modal";
|
||||
import { UpgradeButton } from "../ui/upgrade-button";
|
||||
|
||||
const sanitizeDomain = (value: string) =>
|
||||
value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "")
|
||||
.split("/")[0];
|
||||
|
||||
type DomainStatus =
|
||||
| "checking"
|
||||
| "conflict"
|
||||
| "has site"
|
||||
| "available"
|
||||
| "idle"
|
||||
| "invalid"
|
||||
| "error";
|
||||
|
||||
const STATUS_CONFIG: Record<
|
||||
DomainStatus,
|
||||
{
|
||||
prefix?: string;
|
||||
useStrong?: boolean;
|
||||
suffix?: string;
|
||||
icon?: ElementType;
|
||||
className?: string;
|
||||
message?: string;
|
||||
}
|
||||
> = {
|
||||
checking: {
|
||||
prefix: "Checking availability for",
|
||||
useStrong: true,
|
||||
suffix: "...",
|
||||
icon: LoadingSpinner,
|
||||
className: "bg-neutral-100 text-neutral-500",
|
||||
},
|
||||
conflict: {
|
||||
suffix: "is already in use.",
|
||||
icon: AlertTriangleIcon,
|
||||
className: "bg-rose-100 text-rose-600",
|
||||
},
|
||||
"has site": {
|
||||
suffix:
|
||||
"is currently pointing to an existing website. Only proceed if you're sure you want to use this domain for Papermark links.",
|
||||
icon: InfoIcon,
|
||||
className: "bg-blue-100 text-blue-800",
|
||||
},
|
||||
available: {
|
||||
suffix: "is ready to connect.",
|
||||
icon: CircleCheckIcon,
|
||||
className: "bg-emerald-100 text-emerald-600",
|
||||
},
|
||||
invalid: {
|
||||
message: "Enter a valid domain to check availability.",
|
||||
icon: AlertTriangleIcon,
|
||||
className: "bg-rose-100 text-rose-600",
|
||||
},
|
||||
idle: {
|
||||
message: "Enter a valid domain to check availability.",
|
||||
className: "bg-neutral-100 text-neutral-500",
|
||||
},
|
||||
error: {
|
||||
message: "We couldn't check this domain right now. Try again.",
|
||||
icon: AlertTriangleIcon,
|
||||
className: "bg-rose-100 text-rose-600",
|
||||
},
|
||||
};
|
||||
|
||||
export function AddDomainModal({
|
||||
open,
|
||||
setOpen,
|
||||
@@ -39,69 +113,154 @@ export function AddDomainModal({
|
||||
linkType?: Omit<LinkType, "WORKFLOW_LINK">;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
const [domain, setDomain] = useState<string>("");
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const [domainInput, setDomainInput] = useState<string>("");
|
||||
const [submitting, setSubmitting] = useState<boolean>(false);
|
||||
const [domainStatus, setDomainStatus] = useState<DomainStatus>("idle");
|
||||
const [statusMessageOverride, setStatusMessageOverride] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const teamInfo = useTeam();
|
||||
const teamId = teamInfo?.currentTeam?.id;
|
||||
const { isFree, isPro, isBusiness } = usePlan();
|
||||
const { limits } = useLimits();
|
||||
const analytics = useAnalytics();
|
||||
const addDomainSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.min(3, {
|
||||
message: "Please provide a domain name with at least 3 characters.",
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setDomainInput("");
|
||||
setSubmitting(false);
|
||||
setDomainStatus("idle");
|
||||
setStatusMessageOverride(null);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const sanitizedDomain = sanitizeDomain(domainInput);
|
||||
const [debouncedDomain] = useDebounce(sanitizedDomain, 500);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (!teamId) return;
|
||||
|
||||
if (!debouncedDomain) {
|
||||
setDomainStatus("idle");
|
||||
setStatusMessageOverride(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (debouncedDomain.includes("papermark")) {
|
||||
setDomainStatus("invalid");
|
||||
setStatusMessageOverride("Domain cannot contain 'papermark'.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validDomainRegex.test(debouncedDomain)) {
|
||||
setDomainStatus("idle");
|
||||
setStatusMessageOverride(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Abort any in-flight validation request before starting a new one
|
||||
abortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
|
||||
setDomainStatus("checking");
|
||||
setStatusMessageOverride(null);
|
||||
|
||||
fetch(
|
||||
`/api/teams/${teamId}/domains/${encodeURIComponent(
|
||||
debouncedDomain,
|
||||
)}/validate`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then(async (res) => res.json())
|
||||
.then((data) => {
|
||||
const nextStatus = data?.status as DomainStatus | undefined;
|
||||
if (
|
||||
nextStatus &&
|
||||
["invalid", "conflict", "has site", "available"].includes(nextStatus)
|
||||
) {
|
||||
setDomainStatus(nextStatus);
|
||||
} else {
|
||||
setDomainStatus("error");
|
||||
}
|
||||
})
|
||||
// Add validation for papermark
|
||||
.refine((name) => !name.toLowerCase().includes("papermark"), {
|
||||
message: "Domain cannot contain 'papermark'",
|
||||
}),
|
||||
});
|
||||
.catch((err) => {
|
||||
// Ignore aborted requests – they are expected when the user types again
|
||||
if ((err as DOMException).name === "AbortError") return;
|
||||
setDomainStatus("error");
|
||||
});
|
||||
|
||||
return () => {
|
||||
controller.abort();
|
||||
abortRef.current = null;
|
||||
};
|
||||
}, [debouncedDomain, open, teamId]);
|
||||
|
||||
const saveDisabled =
|
||||
!["available", "has site"].includes(domainStatus) || submitting;
|
||||
|
||||
const handleSubmit = async (event: any) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const validation = addDomainSchema.safeParse({ name: domain });
|
||||
if (!validation.success) {
|
||||
return toast.error(validation.error.errors[0].message);
|
||||
const normalizedDomain = sanitizeDomain(domainInput);
|
||||
if (!normalizedDomain || !validDomainRegex.test(normalizedDomain)) {
|
||||
return toast.error("Please enter a valid domain (e.g., example.com).");
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
const response = await fetch(
|
||||
`/api/teams/${teamInfo?.currentTeam?.id}/domains`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
if (normalizedDomain.includes("papermark")) {
|
||||
return toast.error("Domain cannot contain 'papermark'.");
|
||||
}
|
||||
|
||||
if (saveDisabled) {
|
||||
return toast.error(
|
||||
statusMessageOverride ??
|
||||
"Please enter a valid domain before adding.",
|
||||
);
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/teams/${teamId}/domains`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
domain: normalizedDomain,
|
||||
}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
domain: domain,
|
||||
}),
|
||||
},
|
||||
);
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const { message } = await response.json();
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
const newDomain = await response.json();
|
||||
|
||||
analytics.capture("Domain Added", { slug: normalizedDomain });
|
||||
toast.success("Domain added successfully! 🎉");
|
||||
|
||||
// Update local data with the new link
|
||||
onAddition && onAddition(newDomain);
|
||||
|
||||
if (!response.ok) {
|
||||
const { message } = await response.json();
|
||||
setLoading(false);
|
||||
setOpen(false);
|
||||
toast.error(message);
|
||||
return;
|
||||
|
||||
!onAddition && window.open("/settings/domains", "_blank");
|
||||
} catch (error: unknown) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "An unknown error occurred";
|
||||
toast.error(`Failed to add domain: ${message}`);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
const newDomain = await response.json();
|
||||
|
||||
analytics.capture("Domain Added", { slug: domain });
|
||||
toast.success("Domain added successfully! 🎉");
|
||||
|
||||
// Update local data with the new link
|
||||
onAddition && onAddition(newDomain);
|
||||
|
||||
setOpen(false);
|
||||
|
||||
setLoading(false);
|
||||
|
||||
!onAddition && window.open("/settings/domains", "_blank");
|
||||
};
|
||||
|
||||
// If the team is
|
||||
@@ -149,26 +308,89 @@ export function AddDomainModal({
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>{children}</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogContent className="sm:max-w-[520px]">
|
||||
<DialogHeader className="text-start">
|
||||
<DialogTitle>Add Domain</DialogTitle>
|
||||
<DialogDescription>
|
||||
You can easily add a custom domain.
|
||||
Add a custom domain and verify it with DNS.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Label htmlFor="domain" className="opacity-80">
|
||||
Domain
|
||||
Your domain
|
||||
</Label>
|
||||
<Input
|
||||
id="domain"
|
||||
placeholder="docs.yourdomain.com"
|
||||
className="mb-8 mt-1 w-full"
|
||||
onChange={(e) => setDomain(e.target.value)}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button type="submit" className="h-9 w-full">
|
||||
Add domain
|
||||
{(() => {
|
||||
const currentStatus = STATUS_CONFIG[domainStatus];
|
||||
const StatusIcon = currentStatus.icon;
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"-m-1 mt-2 rounded-[0.625rem] p-1",
|
||||
currentStatus.className || "bg-neutral-100 text-neutral-500",
|
||||
)}
|
||||
>
|
||||
<div className="flex rounded-md border border-neutral-300 bg-white">
|
||||
<Input
|
||||
id="domain"
|
||||
placeholder="docs.yourdomain.com"
|
||||
className="border-0 bg-transparent shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"
|
||||
value={domainInput}
|
||||
onBlur={() => {
|
||||
const normalized = sanitizeDomain(domainInput);
|
||||
if (normalized && normalized !== domainInput) {
|
||||
setDomainInput(normalized);
|
||||
}
|
||||
}}
|
||||
onChange={(e) => {
|
||||
// Cancel any in-flight validation so stale results
|
||||
// don't overwrite the reset status below
|
||||
abortRef.current?.abort();
|
||||
abortRef.current = null;
|
||||
setDomainStatus("idle");
|
||||
setStatusMessageOverride(null);
|
||||
setDomainInput(e.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-4 p-2 text-sm">
|
||||
<p>
|
||||
{["checking", "conflict", "has site", "available"].includes(
|
||||
domainStatus,
|
||||
) ? (
|
||||
<>
|
||||
{currentStatus.prefix || "The domain"}{" "}
|
||||
{currentStatus.useStrong ? (
|
||||
<strong className="font-semibold underline underline-offset-2">
|
||||
{sanitizedDomain || "this domain"}
|
||||
</strong>
|
||||
) : (
|
||||
<span className="font-semibold underline underline-offset-2">
|
||||
{sanitizedDomain || "this domain"}
|
||||
</span>
|
||||
)}{" "}
|
||||
{currentStatus.suffix}
|
||||
</>
|
||||
) : (
|
||||
statusMessageOverride ||
|
||||
currentStatus.message ||
|
||||
"Enter a valid domain to check availability."
|
||||
)}
|
||||
</p>
|
||||
{StatusIcon && (
|
||||
<StatusIcon className="h-5 w-5 shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
<DialogFooter className="mt-6">
|
||||
<Button
|
||||
type="submit"
|
||||
className="h-9 w-full"
|
||||
disabled={saveDisabled}
|
||||
>
|
||||
{submitting ? "Adding domain..." : "Add domain"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
|
||||
@@ -9,19 +9,27 @@ import {
|
||||
} from "@/lib/types";
|
||||
import { fetcher } from "@/lib/utils";
|
||||
|
||||
export function useDomainStatus({ domain }: { domain: string }) {
|
||||
export function useDomainStatus({
|
||||
domain,
|
||||
enabled = true,
|
||||
}: {
|
||||
domain: string;
|
||||
enabled?: boolean;
|
||||
}) {
|
||||
const teamInfo = useTeam();
|
||||
|
||||
const key =
|
||||
enabled && domain
|
||||
? `/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}/verify`
|
||||
: null;
|
||||
|
||||
const { data, isValidating, mutate } = useSWR<{
|
||||
status: DomainVerificationStatusProps;
|
||||
response: {
|
||||
domainJson: DomainResponse & { error: { code: string; message: string } };
|
||||
configJson: DomainConfigResponse;
|
||||
};
|
||||
}>(
|
||||
`/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}/verify`,
|
||||
fetcher,
|
||||
);
|
||||
}>(key, fetcher);
|
||||
|
||||
return {
|
||||
status: data?.status,
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import {
|
||||
Body,
|
||||
Button,
|
||||
Container,
|
||||
Head,
|
||||
Html,
|
||||
Preview,
|
||||
Section,
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
|
||||
import { Footer } from "./shared/footer";
|
||||
|
||||
function formatExpirationTime(expiresAt?: string): string {
|
||||
if (!expiresAt) return "3 days";
|
||||
|
||||
const expires = new Date(expiresAt);
|
||||
const now = new Date();
|
||||
const diffMs = expires.getTime() - now.getTime();
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
|
||||
if (diffDays > 0) {
|
||||
return `${diffDays} day${diffDays > 1 ? "s" : ""}`;
|
||||
} else if (diffHours > 0) {
|
||||
return `${diffHours} hour${diffHours > 1 ? "s" : ""}`;
|
||||
}
|
||||
return "less than an hour";
|
||||
}
|
||||
|
||||
export default function DownloadReady({
|
||||
dataroomName = "Dataroom",
|
||||
downloadUrl = "https://app.papermark.com",
|
||||
email = "email@example.com",
|
||||
expiresAt,
|
||||
isViewer = false,
|
||||
}: {
|
||||
dataroomName?: string;
|
||||
downloadUrl?: string;
|
||||
email: string;
|
||||
expiresAt?: string;
|
||||
isViewer?: boolean;
|
||||
}) {
|
||||
const expirationTime = formatExpirationTime(expiresAt);
|
||||
|
||||
return (
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>Your {dataroomName} download is ready</Preview>
|
||||
<Tailwind>
|
||||
<Body className="mx-auto my-auto bg-white font-sans">
|
||||
<Container className="mx-auto my-10 w-[465px] p-5">
|
||||
<Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">
|
||||
<span className="font-bold tracking-tighter">Papermark</span>
|
||||
</Text>
|
||||
<Text className="text-sm leading-6 text-black">
|
||||
Your download of <strong>{dataroomName}</strong> is ready!
|
||||
</Text>
|
||||
<Text className="text-sm leading-6 text-black">
|
||||
{isViewer
|
||||
? "Click the button below to open your downloads page and get your files."
|
||||
: "Click the button below to download your files. You'll need to be logged in to your Papermark account to access the download."}
|
||||
</Text>
|
||||
|
||||
<Section className="my-8 text-center">
|
||||
<Button
|
||||
className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
|
||||
href={downloadUrl}
|
||||
style={{ padding: "12px 20px" }}
|
||||
>
|
||||
Download Files
|
||||
</Button>
|
||||
</Section>
|
||||
|
||||
<Text className="text-sm leading-6 text-black">
|
||||
Download details:
|
||||
</Text>
|
||||
<ul className="break-all text-sm leading-6 text-black">
|
||||
<li className="text-sm leading-6 text-black">
|
||||
Dataroom: {dataroomName}
|
||||
</li>
|
||||
<li className="text-sm leading-6 text-black">
|
||||
Expires: in {expirationTime}
|
||||
</li>
|
||||
</ul>
|
||||
<Text className="text-sm leading-6 text-black">
|
||||
Best,
|
||||
<br />
|
||||
The Papermark Team
|
||||
</Text>
|
||||
<Footer
|
||||
footerText={
|
||||
<>
|
||||
This email was intended for{" "}
|
||||
<span className="text-black">{email}</span>. If you were not
|
||||
expecting this email, you can ignore this email. If you have
|
||||
any feedback or questions about this email, simply reply to
|
||||
it.
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Container>
|
||||
</Body>
|
||||
</Tailwind>
|
||||
</Html>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import Cookies from "js-cookie";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { AppBreadcrumb } from "@/components/layouts/breadcrumb";
|
||||
import TrialBanner from "@/components/layouts/trial-banner";
|
||||
@@ -12,16 +15,91 @@ import {
|
||||
SidebarTrigger,
|
||||
} from "@/components/ui/sidebar";
|
||||
|
||||
import { usePlan } from "@/lib/swr/use-billing";
|
||||
// import { usePlan } from "@/lib/swr/use-billing";
|
||||
// import YearlyUpgradeBanner from "@/components/billing/yearly-upgrade-banner";
|
||||
|
||||
import { BlockingModal } from "./blocking-modal";
|
||||
|
||||
const DATAROOM_SIDEBAR_COOKIE_NAME = "sidebar:dataroom-state";
|
||||
|
||||
// Helper to get initial sidebar state synchronously (avoids flash)
|
||||
function getInitialSidebarState(isDataroom: boolean): boolean {
|
||||
if (typeof window === "undefined") return false; // SSR: default closed to avoid flash
|
||||
|
||||
// For dataroom pages, check dataroom-specific cookie first
|
||||
if (isDataroom) {
|
||||
const dataroomCookie = Cookies.get(DATAROOM_SIDEBAR_COOKIE_NAME);
|
||||
if (dataroomCookie !== undefined) {
|
||||
return dataroomCookie === "true";
|
||||
}
|
||||
// No dataroom preference set yet - default to closed for datarooms
|
||||
return false;
|
||||
}
|
||||
|
||||
// For non-dataroom pages, use main cookie
|
||||
const mainCookie = Cookies.get(SIDEBAR_COOKIE_NAME);
|
||||
if (mainCookie !== undefined) {
|
||||
return mainCookie === "true";
|
||||
}
|
||||
|
||||
return true; // Default open for non-dataroom pages
|
||||
}
|
||||
|
||||
export default function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
// Default to open (true) if no cookie exists, otherwise use the stored preference
|
||||
const cookieValue = Cookies.get(SIDEBAR_COOKIE_NAME);
|
||||
const isSidebarOpen =
|
||||
cookieValue === undefined ? true : cookieValue === "true";
|
||||
const router = useRouter();
|
||||
const isDataroom = router.pathname.startsWith("/datarooms/[id]");
|
||||
|
||||
// Use lazy initializer to compute initial state synchronously (avoids flash)
|
||||
const [sidebarOpen, setSidebarOpen] = useState(() =>
|
||||
getInitialSidebarState(isDataroom),
|
||||
);
|
||||
|
||||
// Track previous dataroom state for transitions
|
||||
const prevIsDataroomRef = useRef<boolean>(isDataroom);
|
||||
const isFirstRenderRef = useRef(true);
|
||||
|
||||
// Handle initial mount and transitions between dataroom/non-dataroom
|
||||
useEffect(() => {
|
||||
if (isFirstRenderRef.current) {
|
||||
isFirstRenderRef.current = false;
|
||||
// Set cookie on initial mount if in dataroom and no preference exists
|
||||
if (
|
||||
isDataroom &&
|
||||
Cookies.get(DATAROOM_SIDEBAR_COOKIE_NAME) === undefined
|
||||
) {
|
||||
Cookies.set(DATAROOM_SIDEBAR_COOKIE_NAME, "false", { expires: 7 });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Transitioning from non-dataroom to dataroom
|
||||
if (!prevIsDataroomRef.current && isDataroom) {
|
||||
setSidebarOpen(false);
|
||||
Cookies.set(DATAROOM_SIDEBAR_COOKIE_NAME, "false", { expires: 7 });
|
||||
}
|
||||
|
||||
// Transitioning from dataroom to non-dataroom
|
||||
if (prevIsDataroomRef.current && !isDataroom) {
|
||||
Cookies.remove(DATAROOM_SIDEBAR_COOKIE_NAME);
|
||||
// Restore main sidebar state
|
||||
const mainCookie = Cookies.get(SIDEBAR_COOKIE_NAME);
|
||||
// setSidebarOpen(mainCookie === "true");
|
||||
setSidebarOpen(mainCookie !== undefined ? mainCookie === "true" : true);
|
||||
}
|
||||
|
||||
prevIsDataroomRef.current = isDataroom;
|
||||
}, [isDataroom]);
|
||||
|
||||
// Handle sidebar state changes - save to appropriate cookie
|
||||
const handleSidebarOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setSidebarOpen(open);
|
||||
if (isDataroom) {
|
||||
Cookies.set(DATAROOM_SIDEBAR_COOKIE_NAME, String(open), { expires: 7 });
|
||||
}
|
||||
},
|
||||
[isDataroom],
|
||||
);
|
||||
|
||||
// const { isAnnualPlan, isFree } = usePlan();
|
||||
// const [showYearlyBanner, setShowYearlyBanner] = useState<boolean | null>(null);
|
||||
@@ -43,7 +121,7 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
// }, [isFree, isAnnualPlan]);
|
||||
|
||||
return (
|
||||
<SidebarProvider defaultOpen={isSidebarOpen}>
|
||||
<SidebarProvider open={sidebarOpen} onOpenChange={handleSidebarOpenChange}>
|
||||
<div className="flex flex-1 flex-col gap-x-1 bg-gray-50 dark:bg-black md:flex-row">
|
||||
<AppSidebar />
|
||||
<SidebarInset className="ring-1 ring-gray-200 dark:ring-gray-800">
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { Dispatch, SetStateAction, useEffect, useState } from "react";
|
||||
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { useHotkeys } from "react-hotkeys-hook";
|
||||
|
||||
import { useTeam } from "@/context/team-context";
|
||||
import { PlanEnum } from "@/ee/stripe/constants";
|
||||
@@ -177,6 +179,7 @@ export default function LinkSheet({
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [isSaving, setIsSaving] = useState<boolean>(false);
|
||||
const [currentPreset, setCurrentPreset] = useState<LinkPreset | null>(null);
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
const isPresetsAllowed =
|
||||
isTrial ||
|
||||
@@ -200,6 +203,19 @@ export default function LinkSheet({
|
||||
setData(currentLink || DEFAULT_LINK_PROPS(linkType, groupId, !isDatarooms));
|
||||
}, [currentLink]);
|
||||
|
||||
// Handle Command+Enter (Mac) or Ctrl+Enter (Windows/Linux) to submit the form
|
||||
useHotkeys(
|
||||
"mod+enter",
|
||||
(e) => {
|
||||
e.preventDefault();
|
||||
if (!isSaving && formRef.current) {
|
||||
formRef.current.requestSubmit();
|
||||
}
|
||||
},
|
||||
{ enabled: isOpen, enableOnFormTags: true },
|
||||
[isSaving],
|
||||
);
|
||||
|
||||
const handlePreviewLink = async (link: LinkWithViews) => {
|
||||
if (link.domainId && isFree) {
|
||||
toast.error("You need to upgrade to preview this link");
|
||||
@@ -470,6 +486,7 @@ export default function LinkSheet({
|
||||
</SheetHeader>
|
||||
|
||||
<form
|
||||
ref={formRef}
|
||||
className="flex grow flex-col"
|
||||
onSubmit={(e) => handleSubmit(e, false)}
|
||||
>
|
||||
|
||||
+545
-351
@@ -1,6 +1,6 @@
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { useTeam } from "@/context/team-context";
|
||||
import { InviteViewersModal } from "@/ee/features/dataroom-invitations/components/invite-viewers-modal";
|
||||
@@ -10,15 +10,21 @@ import { DocumentVersion, LinkAudienceType } from "@prisma/client";
|
||||
import { isWithinInterval, subMinutes } from "date-fns";
|
||||
import {
|
||||
BoxesIcon,
|
||||
ChevronRightIcon,
|
||||
ClockFadingIcon,
|
||||
Code2Icon,
|
||||
CopyCheckIcon,
|
||||
CopyIcon,
|
||||
CopyPlusIcon,
|
||||
EyeIcon,
|
||||
EyeOffIcon,
|
||||
FileSlidersIcon,
|
||||
HourglassIcon,
|
||||
LinkIcon,
|
||||
SendIcon,
|
||||
Settings2Icon,
|
||||
Square,
|
||||
SquareArrowOutUpRightIcon,
|
||||
SquareDashedIcon,
|
||||
TimerOffIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
@@ -85,7 +91,6 @@ import { DataroomLinkSheet } from "./link-sheet/dataroom-link-sheet";
|
||||
import { PermissionsSheet } from "./link-sheet/permissions-sheet";
|
||||
import { TagColumn } from "./link-sheet/tags/tag-details";
|
||||
import LinksVisitors from "./links-visitors";
|
||||
import { PreviewButton } from "./preview-button";
|
||||
|
||||
const isDocumentProcessing = (version?: DocumentVersion) => {
|
||||
if (!version) return false;
|
||||
@@ -95,6 +100,151 @@ const isDocumentProcessing = (version?: DocumentVersion) => {
|
||||
);
|
||||
};
|
||||
|
||||
// Full URL helper
|
||||
const getFullUrl = (link: LinkWithViews) => {
|
||||
if (link.domainId) {
|
||||
return `https://${link.domainSlug}/${link.slug}`;
|
||||
}
|
||||
return `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`;
|
||||
};
|
||||
|
||||
// Display URL helper - shows the path portion that fits the cell
|
||||
const getDisplayUrl = (link: LinkWithViews) => {
|
||||
if (link.domainId) {
|
||||
return `${link.domainSlug}/${link.slug}`;
|
||||
}
|
||||
return `papermark.com/view/${link.id}`;
|
||||
};
|
||||
|
||||
// Link URL cell component - displays URL with click-to-copy hover overlay
|
||||
const LinkUrlCell = ({
|
||||
link,
|
||||
isFree,
|
||||
onCopy,
|
||||
isProcessing,
|
||||
primaryVersion,
|
||||
mutateDocument,
|
||||
isPopoverOpen,
|
||||
}: {
|
||||
link: LinkWithViews;
|
||||
isFree: boolean;
|
||||
onCopy: (url: string) => void;
|
||||
isProcessing: boolean;
|
||||
primaryVersion?: DocumentVersion;
|
||||
mutateDocument?: () => void;
|
||||
isPopoverOpen?: boolean;
|
||||
}) => {
|
||||
const fullUrl = getFullUrl(link);
|
||||
const displayUrl = getDisplayUrl(link);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group/url relative min-w-0 flex-1 cursor-pointer overflow-hidden rounded-md px-3 py-1.5 text-sm transition-all group-hover/row:ring-1 group-hover/row:ring-gray-400 group-hover/row:dark:ring-gray-100",
|
||||
link.domainId && isFree
|
||||
? "bg-destructive/10 text-destructive hover:bg-red-700 hover:dark:bg-red-200"
|
||||
: "bg-secondary text-secondary-foreground hover:bg-emerald-700 hover:dark:bg-emerald-200",
|
||||
isPopoverOpen && "ring-1 ring-gray-400 dark:ring-gray-100",
|
||||
)}
|
||||
onClick={() => onCopy(fullUrl)}
|
||||
>
|
||||
{/* Progress bar for document processing */}
|
||||
{isProcessing && primaryVersion && (
|
||||
<FileProcessStatusBar
|
||||
documentVersionId={primaryVersion.id}
|
||||
className="absolute bottom-0 left-0 right-0 top-0 z-20 flex h-full items-center gap-x-8"
|
||||
// @ts-ignore: mutateDocument is not present on datarooms but on document pages
|
||||
mutateDocument={mutateDocument}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* URL text - hidden on hover */}
|
||||
<span
|
||||
className="block overflow-hidden text-ellipsis whitespace-nowrap group-hover/url:opacity-0"
|
||||
style={{ direction: "rtl", textAlign: "left" }}
|
||||
>
|
||||
{displayUrl}
|
||||
</span>
|
||||
{/* Copy & Share overlay */}
|
||||
<span className="absolute inset-0 z-10 hidden items-center justify-center whitespace-nowrap text-center text-sm text-primary-foreground group-hover/url:flex">
|
||||
Copy & Share
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Link actions cell component - copy, preview, edit buttons
|
||||
const LinkActionsCell = ({
|
||||
link,
|
||||
onCopy,
|
||||
onPreview,
|
||||
isProcessing,
|
||||
}: {
|
||||
link: LinkWithViews;
|
||||
onCopy: (url: string) => void;
|
||||
onPreview: (link: LinkWithViews) => void;
|
||||
isProcessing: boolean;
|
||||
}) => {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const fullUrl = getFullUrl(link);
|
||||
|
||||
useEffect(() => {
|
||||
if (copied) {
|
||||
const timeout = setTimeout(() => setCopied(false), 2000);
|
||||
return () => clearTimeout(timeout);
|
||||
}
|
||||
}, [copied]);
|
||||
|
||||
const handleCopy = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
onCopy(fullUrl);
|
||||
setCopied(true);
|
||||
};
|
||||
|
||||
const handlePreview = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
onPreview(link);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<ButtonTooltip content={copied ? "Copied!" : "Copy link"}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 transition-colors hover:text-foreground group-hover/link:bg-emerald-500/10 group-hover/link:hover:bg-emerald-500/20"
|
||||
onClick={handleCopy}
|
||||
>
|
||||
{copied ? (
|
||||
<CopyCheckIcon className="h-4 w-4 text-emerald-500" />
|
||||
) : (
|
||||
<CopyIcon className="h-4 w-4 text-muted-foreground transition-colors hover:text-foreground group-hover/link:text-emerald-500" />
|
||||
)}
|
||||
</Button>
|
||||
</ButtonTooltip>
|
||||
<ButtonTooltip
|
||||
content={isProcessing ? "Preparing preview" : "Preview link"}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 hover:text-foreground"
|
||||
onClick={handlePreview}
|
||||
disabled={isProcessing}
|
||||
>
|
||||
{isProcessing ? (
|
||||
<SquareDashedIcon className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<SquareArrowOutUpRightIcon className="h-4 w-4 text-muted-foreground hover:text-foreground" />
|
||||
)}
|
||||
</Button>
|
||||
</ButtonTooltip>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default function LinksTable({
|
||||
targetType,
|
||||
links,
|
||||
@@ -616,169 +766,165 @@ export default function LinksTable({
|
||||
[processedLinks],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-full">
|
||||
<div className={cn(targetType === "DATAROOM" && "hidden")}>
|
||||
<h2 className="mb-2 md:mb-4">All links</h2>
|
||||
</div>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent">
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead className="w-[150px] sm:w-[200px] md:w-[250px]">
|
||||
Link
|
||||
</TableHead>
|
||||
{hasAnyTags ? (
|
||||
<TableHead className="w-[250px] 2xl:w-auto">Tags</TableHead>
|
||||
) : null}
|
||||
<TableHead className="w-[250px] sm:w-auto">Views</TableHead>
|
||||
<TableHead>Last Viewed</TableHead>
|
||||
<TableHead className="w-[80px]">Active</TableHead>
|
||||
<TableHead className="text-center sm:text-right"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{processedLinks && processedLinks.length > 0 ? (
|
||||
processedLinks.map((link) => (
|
||||
<Collapsible key={link.id} asChild>
|
||||
<>
|
||||
<TableRow
|
||||
key={link.id}
|
||||
className={cn(
|
||||
"group/row",
|
||||
popoverOpen === link.id && "bg-gray-100",
|
||||
link.isArchived &&
|
||||
"bg-gray-50 opacity-50 dark:bg-gray-700",
|
||||
)}
|
||||
>
|
||||
<TableCell className="w-[250px] truncate font-medium">
|
||||
<div className="flex items-center gap-x-2">
|
||||
{link.groupId ? (
|
||||
<ButtonTooltip content="Group Link">
|
||||
<BoxesIcon className="size-4" />
|
||||
</ButtonTooltip>
|
||||
) : null}
|
||||
// Collapsible state for "All Links" section (document pages only)
|
||||
const ALL_LINKS_COLLAPSED_KEY = "papermark-all-links-collapsed";
|
||||
const [isAllLinksOpen, setIsAllLinksOpen] = useState<boolean>(true);
|
||||
|
||||
// Load collapse state from localStorage on mount
|
||||
useEffect(() => {
|
||||
if (targetType !== "DOCUMENT") return;
|
||||
try {
|
||||
const stored = localStorage.getItem(ALL_LINKS_COLLAPSED_KEY);
|
||||
if (stored !== null) {
|
||||
// stored value is "true" if collapsed, so we invert for isOpen
|
||||
setIsAllLinksOpen(stored !== "true");
|
||||
}
|
||||
} catch (e) {
|
||||
// localStorage might be unavailable
|
||||
console.warn("Could not read from localStorage:", e);
|
||||
}
|
||||
}, [targetType]);
|
||||
|
||||
// Handle toggle and persist to localStorage
|
||||
const handleAllLinksToggle = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsAllLinksOpen(open);
|
||||
try {
|
||||
// Store "true" when collapsed, "false" when expanded
|
||||
localStorage.setItem(ALL_LINKS_COLLAPSED_KEY, String(!open));
|
||||
} catch (e) {
|
||||
console.warn("Could not write to localStorage:", e);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const isDataroom = targetType === "DATAROOM";
|
||||
|
||||
const linksTableContent = (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent">
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Link</TableHead>
|
||||
{hasAnyTags ? (
|
||||
<TableHead className="w-[250px] 2xl:w-auto">Tags</TableHead>
|
||||
) : null}
|
||||
<TableHead className="w-[250px] sm:w-auto">Views</TableHead>
|
||||
<TableHead>Last Viewed</TableHead>
|
||||
<TableHead className="w-[80px]">Active</TableHead>
|
||||
<TableHead className="text-center sm:text-right"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{processedLinks && processedLinks.length > 0 ? (
|
||||
processedLinks.map((link) => (
|
||||
<Collapsible key={link.id} asChild>
|
||||
<>
|
||||
<TableRow
|
||||
key={link.id}
|
||||
className={cn(
|
||||
"group/row",
|
||||
popoverOpen === link.id && "bg-gray-100",
|
||||
link.isArchived &&
|
||||
"bg-gray-50 opacity-50 dark:bg-gray-700",
|
||||
)}
|
||||
>
|
||||
<TableCell className="w-[200px] truncate font-medium md:w-[220px] lg:w-[250px] xl:w-[280px] 2xl:w-[350px]">
|
||||
<div className="flex items-center gap-x-2">
|
||||
{link.groupId ? (
|
||||
<ButtonTooltip content="Group Link">
|
||||
<BoxesIcon className="size-4 shrink-0" />
|
||||
</ButtonTooltip>
|
||||
) : null}
|
||||
<ButtonTooltip
|
||||
content={
|
||||
link.name || `Link #${link.id.slice(-5)}`
|
||||
}
|
||||
>
|
||||
<span className="max-w-[150px] truncate md:max-w-[170px] lg:max-w-[200px] xl:max-w-[230px] 2xl:max-w-[300px]">
|
||||
{link.name || `Link #${link.id.slice(-5)}`}
|
||||
{link.isNew && !link.isUpdated && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-emerald-600/80 text-emerald-600/80"
|
||||
>
|
||||
New
|
||||
</Badge>
|
||||
)}
|
||||
{link.isUpdated && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-blue-500/80 text-blue-500/80"
|
||||
>
|
||||
Updated
|
||||
</Badge>
|
||||
)}
|
||||
{link.expiresAt &&
|
||||
(new Date(link.expiresAt) < new Date() ? (
|
||||
<TimestampTooltip
|
||||
timestamp={link.expiresAt}
|
||||
side="right"
|
||||
rows={["local", "utc"]}
|
||||
title="Expired at"
|
||||
fullLabels
|
||||
>
|
||||
<span className="flex cursor-default items-center rounded-full bg-destructive/10 p-1 text-destructive ring-1 ring-destructive/20">
|
||||
<TimerOffIcon className="h-3 w-3" />
|
||||
</span>
|
||||
</TimestampTooltip>
|
||||
) : (
|
||||
<TimestampTooltip
|
||||
timestamp={link.expiresAt}
|
||||
side="right"
|
||||
rows={["local", "utc"]}
|
||||
title="Expires at"
|
||||
fullLabels
|
||||
>
|
||||
<span className="flex cursor-default items-center rounded-full bg-orange-100 p-1 text-orange-700 ring-1 ring-orange-200 dark:bg-orange-900/30 dark:text-orange-400 dark:ring-orange-800">
|
||||
<ClockFadingIcon className="h-3 w-3" />
|
||||
</span>
|
||||
</TimestampTooltip>
|
||||
))}
|
||||
{link.domainId && isFree ? (
|
||||
<span className="ml-2 rounded-full bg-destructive px-2.5 py-0.5 text-xs text-foreground ring-1 ring-destructive">
|
||||
Inactive
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="flex items-center gap-x-2 sm:min-w-[300px] md:min-w-[400px] lg:min-w-[450px]">
|
||||
<div
|
||||
className={cn(
|
||||
`group/cell relative flex w-full items-center gap-x-4 overflow-hidden truncate rounded-sm px-3 py-1.5 text-center text-secondary-foreground transition-all group-hover/row:ring-1 group-hover/row:ring-gray-400 group-hover/row:dark:ring-gray-100 md:py-1`,
|
||||
link.domainId && isFree
|
||||
? "bg-destructive hover:bg-red-700 hover:dark:bg-red-200"
|
||||
: "bg-secondary hover:bg-emerald-700 hover:dark:bg-emerald-200",
|
||||
popoverOpen === link.id &&
|
||||
"ring-1 ring-gray-400 dark:ring-gray-100",
|
||||
)}
|
||||
</span>
|
||||
</ButtonTooltip>
|
||||
{link.isNew && !link.isUpdated && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-emerald-600/80 text-emerald-600/80"
|
||||
>
|
||||
{/* Progress bar */}
|
||||
{isDocumentProcessing(primaryVersion) &&
|
||||
primaryVersion && (
|
||||
<FileProcessStatusBar
|
||||
documentVersionId={primaryVersion.id}
|
||||
className="absolute bottom-0 left-0 right-0 top-0 z-20 flex h-full items-center gap-x-8"
|
||||
// @ts-ignore: mutateDocument is not present on datarooms but on document pages
|
||||
mutateDocument={mutateDocument}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex w-full whitespace-nowrap text-sm group-hover/cell:opacity-0">
|
||||
{link.domainId
|
||||
? `https://${link.domainSlug}/${link.slug}`
|
||||
: `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`}
|
||||
</div>
|
||||
|
||||
{link.domainId && isFree ? (
|
||||
<button
|
||||
className="absolute bottom-0 left-0 right-0 top-0 z-10 hidden w-full whitespace-nowrap text-center text-sm group-hover/cell:block group-hover/cell:text-primary-foreground"
|
||||
onClick={() => router.push("/settings/billing")}
|
||||
title="Upgrade to activate link"
|
||||
>
|
||||
Upgrade to activate link
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="absolute bottom-0 left-0 right-0 top-0 z-10 hidden w-full whitespace-nowrap text-center text-xs group-hover/cell:block group-hover/cell:text-primary-foreground sm:text-sm"
|
||||
onClick={() =>
|
||||
handleCopyToClipboard(
|
||||
link.domainId
|
||||
? `https://${link.domainSlug}/${link.slug}`
|
||||
: `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`,
|
||||
)
|
||||
}
|
||||
title="Copy & Share"
|
||||
>
|
||||
Copy & Share
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<PreviewButton
|
||||
New
|
||||
</Badge>
|
||||
)}
|
||||
{link.isUpdated && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-blue-500/80 text-blue-500/80"
|
||||
>
|
||||
Updated
|
||||
</Badge>
|
||||
)}
|
||||
{link.expiresAt &&
|
||||
(new Date(link.expiresAt) < new Date() ? (
|
||||
<TimestampTooltip
|
||||
timestamp={link.expiresAt}
|
||||
side="right"
|
||||
rows={["local", "utc"]}
|
||||
title="Expired at"
|
||||
fullLabels
|
||||
>
|
||||
<span className="flex cursor-default items-center rounded-full bg-destructive/10 p-1 text-destructive ring-1 ring-destructive/20">
|
||||
<TimerOffIcon className="h-3 w-3" />
|
||||
</span>
|
||||
</TimestampTooltip>
|
||||
) : (
|
||||
<TimestampTooltip
|
||||
timestamp={link.expiresAt}
|
||||
side="right"
|
||||
rows={["local", "utc"]}
|
||||
title="Expires at"
|
||||
fullLabels
|
||||
>
|
||||
<span className="flex cursor-default items-center rounded-full bg-orange-100 p-1 text-orange-700 ring-1 ring-orange-200 dark:bg-orange-900/30 dark:text-orange-400 dark:ring-orange-800">
|
||||
<ClockFadingIcon className="h-3 w-3" />
|
||||
</span>
|
||||
</TimestampTooltip>
|
||||
))}
|
||||
{link.domainId && isFree ? (
|
||||
<span className="ml-2 rounded-full bg-destructive px-2.5 py-0.5 text-xs text-foreground ring-1 ring-destructive">
|
||||
Inactive
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</TableCell>
|
||||
{/* Link URL Cell */}
|
||||
<TableCell className="group/link max-w-[250px] pr-1 md:max-w-[300px] lg:max-w-[350px] xl:max-w-[400px] 2xl:max-w-[450px]">
|
||||
<div className="flex flex-row gap-x-1">
|
||||
<LinkUrlCell
|
||||
link={link}
|
||||
isFree={isFree}
|
||||
onCopy={handleCopyToClipboard}
|
||||
isProcessing={isDocumentProcessing(
|
||||
primaryVersion,
|
||||
)}
|
||||
primaryVersion={primaryVersion}
|
||||
mutateDocument={mutateDocument}
|
||||
isPopoverOpen={popoverOpen === link.id}
|
||||
/>
|
||||
<div className="flex shrink-0 items-center">
|
||||
<LinkActionsCell
|
||||
link={link}
|
||||
isProcessing={isDocumentProcessing(primaryVersion)}
|
||||
onCopy={handleCopyToClipboard}
|
||||
onPreview={handlePreviewLink}
|
||||
/>
|
||||
{targetType === "DATAROOM" &&
|
||||
link.permissionGroupId && (
|
||||
<ButtonTooltip content="Limited File Access">
|
||||
<FileSlidersIcon className="text-gray-400 group-hover:text-gray-500" />
|
||||
</ButtonTooltip>
|
||||
isProcessing={isDocumentProcessing(
|
||||
primaryVersion,
|
||||
)}
|
||||
/>
|
||||
{isMobile ? (
|
||||
<ButtonTooltip content="Edit link">
|
||||
<Button
|
||||
variant={"link"}
|
||||
size={"icon"}
|
||||
className="group h-7 w-8"
|
||||
variant="link"
|
||||
size="icon"
|
||||
className="group h-8 w-8"
|
||||
onClick={() => handleEditLink(link)}
|
||||
>
|
||||
<span className="sr-only">Edit link</span>
|
||||
@@ -794,7 +940,7 @@ export default function LinksTable({
|
||||
<Button
|
||||
variant="link"
|
||||
className={cn(
|
||||
"h-7 font-normal hover:no-underline focus-visible:ring-0 focus-visible:ring-offset-0",
|
||||
"h-8 w-8 font-normal hover:no-underline focus-visible:ring-0 focus-visible:ring-offset-0",
|
||||
popoverOpen === link.id
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
@@ -814,21 +960,13 @@ export default function LinksTable({
|
||||
onMouseLeave={() => {
|
||||
if (hoverTimeout.current)
|
||||
clearTimeout(hoverTimeout.current);
|
||||
|
||||
// Add delay before closing to prevent flickering
|
||||
hoverTimeout.current = setTimeout(
|
||||
() => setPopoverOpen(null),
|
||||
100,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Settings2Icon strokeWidth={1.75} />
|
||||
<span className="whitespace-nowrap">
|
||||
{countActiveSettings(link)}{" "}
|
||||
{countActiveSettings(link) === 1
|
||||
? "control"
|
||||
: "controls"}
|
||||
</span>
|
||||
<Settings2Icon />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
@@ -843,8 +981,6 @@ export default function LinksTable({
|
||||
onMouseLeave={() => {
|
||||
if (hoverTimeout.current)
|
||||
clearTimeout(hoverTimeout.current);
|
||||
|
||||
// Add delay before closing to prevent flickering
|
||||
hoverTimeout.current = setTimeout(
|
||||
() => setPopoverOpen(null),
|
||||
100,
|
||||
@@ -861,193 +997,251 @@ export default function LinksTable({
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
</TableCell>
|
||||
{hasAnyTags ? (
|
||||
<TableCell className="w-[250px] 2xl:w-auto">
|
||||
<TagColumn link={link} />
|
||||
</TableCell>
|
||||
) : null}
|
||||
<TableCell>
|
||||
<CollapsibleTrigger
|
||||
disabled={
|
||||
Number(nFormatter(link._count.views)) === 0 ||
|
||||
targetType === "DATAROOM"
|
||||
}
|
||||
>
|
||||
<div className="flex items-center space-x-1 [&[data-state=open]>svg.chevron]:rotate-180">
|
||||
<BarChart className="h-4 w-4 text-muted-foreground" />
|
||||
<p className="whitespace-nowrap text-sm text-muted-foreground">
|
||||
{nFormatter(link._count.views)}
|
||||
<span className="ml-1 hidden sm:inline-block">
|
||||
views
|
||||
</span>
|
||||
</p>
|
||||
{Number(nFormatter(link._count.views)) > 0 &&
|
||||
targetType !== "DATAROOM" ? (
|
||||
<ChevronDown className="chevron h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200" />
|
||||
) : null}
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">
|
||||
{link.views[0] ? (
|
||||
<TimestampTooltip
|
||||
timestamp={link.views[0].viewedAt}
|
||||
side="right"
|
||||
rows={["local", "utc", "unix"]}
|
||||
>
|
||||
<time
|
||||
className="select-none"
|
||||
dateTime={new Date(
|
||||
link.views[0].viewedAt,
|
||||
).toISOString()}
|
||||
>
|
||||
{timeAgo(link.views[0].viewedAt)}
|
||||
</time>
|
||||
</TimestampTooltip>
|
||||
) : (
|
||||
"-"
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<div className="flex items-center justify-center gap-x-1">
|
||||
<Switch
|
||||
className="data-[state=checked]:bg-primary/80 data-[state=checked]:hover:bg-primary data-[state=unchecked]:hover:bg-muted-foreground/80"
|
||||
id={`${link.id}-active-switch`}
|
||||
checked={!link.isArchived}
|
||||
onCheckedChange={(checked) =>
|
||||
handleArchiveLink(
|
||||
link.id,
|
||||
link.documentId ?? link.dataroomId ?? "",
|
||||
checked,
|
||||
)
|
||||
}
|
||||
disabled={loadingLinks.has(link.id)}
|
||||
/>
|
||||
<Label
|
||||
className="font-normal"
|
||||
htmlFor={`${link.id}-active-switch`}
|
||||
>
|
||||
{link.isArchived ? "No" : "Yes"}
|
||||
</Label>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-center sm:text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"
|
||||
>
|
||||
<span className="sr-only">Open menu</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel>Actions</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleEditLink(link)}
|
||||
>
|
||||
<Settings2Icon className="mr-2 h-4 w-4" />
|
||||
Edit Link
|
||||
</DropdownMenuItem>
|
||||
{targetType === "DATAROOM" &&
|
||||
link.audienceType !==
|
||||
LinkAudienceType.GROUP && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleEditPermissions(link)}
|
||||
disabled={isLoading}
|
||||
{/* File permissions icon (dataroom only) */}
|
||||
{isDataroom && (
|
||||
<div className="flex w-8 items-center justify-center">
|
||||
{link.permissionGroupId && (
|
||||
<ButtonTooltip content="Limited File Access">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 cursor-default"
|
||||
>
|
||||
<FileSlidersIcon className="mr-2 h-4 w-4" />
|
||||
Edit File Permissions
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => handlePreviewLink(link)}
|
||||
>
|
||||
<EyeIcon className="mr-2 h-4 w-4" />
|
||||
Preview Link
|
||||
</DropdownMenuItem>
|
||||
{targetType === "DATAROOM" &&
|
||||
isFeatureEnabled("dataroomInvitations") && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleSendInvitations(link)}
|
||||
>
|
||||
<SendIcon className="mr-2 h-4 w-4" />
|
||||
Send Invitations
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
disabled={!canAddLinks}
|
||||
onClick={() => handleDuplicateLink(link)}
|
||||
>
|
||||
<CopyPlusIcon className="mr-2 h-4 w-4" />
|
||||
Duplicate Link
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setSelectedEmbedLink({
|
||||
id: link.id,
|
||||
name:
|
||||
link.name || `Link #${link.id.slice(-5)}`,
|
||||
});
|
||||
setEmbedModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Code2Icon className="mr-2 h-4 w-4" />
|
||||
Get Embed Code
|
||||
</DropdownMenuItem>
|
||||
{!isFree && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setLinkToDelete(link);
|
||||
setShowDeleteLinkModal(true);
|
||||
}}
|
||||
className="text-destructive focus:bg-destructive focus:text-destructive-foreground"
|
||||
>
|
||||
<Trash2Icon className="mr-2 h-4 w-4" />
|
||||
Delete Link
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
<FileSlidersIcon className="h-4 w-4 text-muted-foreground hover:text-foreground" />
|
||||
</Button>
|
||||
</ButtonTooltip>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<CollapsibleContent asChild>
|
||||
<LinksVisitors
|
||||
linkName={link.name || "No link name"}
|
||||
linkId={link.id}
|
||||
/>
|
||||
</CollapsibleContent>
|
||||
</>
|
||||
</Collapsible>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={hasAnyTags ? 7 : 6}>
|
||||
<div className="flex w-full flex-col items-center justify-center gap-4 rounded-xl py-4">
|
||||
<div className="hidden rounded-full sm:block">
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-full border border-white bg-gradient-to-t from-gray-100 p-1 md:p-3",
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
<LinkIcon className="size-6" />
|
||||
</div>
|
||||
</div>
|
||||
<p>No links found for this {targetType.toLowerCase()}</p>
|
||||
<AddLinkButton />
|
||||
</TableCell>
|
||||
{hasAnyTags ? (
|
||||
<TableCell className="w-[250px] 2xl:w-auto">
|
||||
<TagColumn link={link} />
|
||||
</TableCell>
|
||||
) : null}
|
||||
<TableCell>
|
||||
<CollapsibleTrigger
|
||||
disabled={
|
||||
isDataroom ||
|
||||
link._count.views === 0
|
||||
}
|
||||
>
|
||||
<div className="flex items-center space-x-1 [&[data-state=open]>svg.chevron]:rotate-180">
|
||||
<BarChart className="h-4 w-4 text-muted-foreground" />
|
||||
<p className="whitespace-nowrap text-sm text-muted-foreground">
|
||||
{nFormatter(link._count.views)}
|
||||
<span className="ml-1 hidden sm:inline-block">
|
||||
views
|
||||
</span>
|
||||
</p>
|
||||
{!isDataroom &&
|
||||
link._count.views > 0 ? (
|
||||
<ChevronDown className="chevron h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200" />
|
||||
) : null}
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">
|
||||
{link.views[0] ? (
|
||||
<TimestampTooltip
|
||||
timestamp={link.views[0].viewedAt}
|
||||
side="right"
|
||||
rows={["local", "utc", "unix"]}
|
||||
>
|
||||
<time
|
||||
className="select-none"
|
||||
dateTime={new Date(
|
||||
link.views[0].viewedAt,
|
||||
).toISOString()}
|
||||
>
|
||||
{timeAgo(link.views[0].viewedAt)}
|
||||
</time>
|
||||
</TimestampTooltip>
|
||||
) : (
|
||||
"-"
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<div className="flex items-center justify-center gap-x-1">
|
||||
<Switch
|
||||
className="data-[state=checked]:bg-primary/80 data-[state=checked]:hover:bg-primary data-[state=unchecked]:hover:bg-muted-foreground/80"
|
||||
id={`${link.id}-active-switch`}
|
||||
checked={!link.isArchived}
|
||||
onCheckedChange={(checked) =>
|
||||
handleArchiveLink(
|
||||
link.id,
|
||||
link.documentId ?? link.dataroomId ?? "",
|
||||
checked,
|
||||
)
|
||||
}
|
||||
disabled={loadingLinks.has(link.id)}
|
||||
/>
|
||||
<Label
|
||||
className="font-normal"
|
||||
htmlFor={`${link.id}-active-switch`}
|
||||
>
|
||||
{link.isArchived ? "No" : "Yes"}
|
||||
</Label>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-center sm:text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"
|
||||
>
|
||||
<span className="sr-only">Open menu</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel>Actions</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleEditLink(link)}
|
||||
>
|
||||
<Settings2Icon className="mr-2 h-4 w-4" />
|
||||
Edit Link
|
||||
</DropdownMenuItem>
|
||||
{/* Dataroom-only: Edit File Permissions */}
|
||||
{isDataroom &&
|
||||
link.audienceType !==
|
||||
LinkAudienceType.GROUP && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleEditPermissions(link)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<FileSlidersIcon className="mr-2 h-4 w-4" />
|
||||
Edit File Permissions
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => handlePreviewLink(link)}
|
||||
>
|
||||
<EyeIcon className="mr-2 h-4 w-4" />
|
||||
Preview Link
|
||||
</DropdownMenuItem>
|
||||
{/* Dataroom-only: Send Invitations */}
|
||||
{isDataroom &&
|
||||
isFeatureEnabled("dataroomInvitations") && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleSendInvitations(link)}
|
||||
>
|
||||
<SendIcon className="mr-2 h-4 w-4" />
|
||||
Send Invitations
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
disabled={!canAddLinks}
|
||||
onClick={() => handleDuplicateLink(link)}
|
||||
>
|
||||
<CopyPlusIcon className="mr-2 h-4 w-4" />
|
||||
Duplicate Link
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setSelectedEmbedLink({
|
||||
id: link.id,
|
||||
name:
|
||||
link.name || `Link #${link.id.slice(-5)}`,
|
||||
});
|
||||
setEmbedModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Code2Icon className="mr-2 h-4 w-4" />
|
||||
Get Embed Code
|
||||
</DropdownMenuItem>
|
||||
{!isFree && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setLinkToDelete(link);
|
||||
setShowDeleteLinkModal(true);
|
||||
}}
|
||||
className="text-destructive focus:bg-destructive focus:text-destructive-foreground"
|
||||
>
|
||||
<Trash2Icon className="mr-2 h-4 w-4" />
|
||||
Delete Link
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<CollapsibleContent asChild>
|
||||
<LinksVisitors
|
||||
linkName={link.name || "No link name"}
|
||||
linkId={link.id}
|
||||
/>
|
||||
</CollapsibleContent>
|
||||
</>
|
||||
</Collapsible>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={hasAnyTags ? 7 : 6}>
|
||||
<div className="flex w-full flex-col items-center justify-center gap-4 rounded-xl py-4">
|
||||
<div className="hidden rounded-full sm:block">
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-full border border-white bg-gradient-to-t from-gray-100 p-1 md:p-3",
|
||||
)}
|
||||
>
|
||||
<LinkIcon className="size-6" />
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
<p>No links found for this {targetType.toLowerCase()}</p>
|
||||
<AddLinkButton />
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-full">
|
||||
{/* Collapsible wrapper for DOCUMENT type, plain div for DATAROOM */}
|
||||
{targetType === "DOCUMENT" ? (
|
||||
<Collapsible
|
||||
open={isAllLinksOpen}
|
||||
onOpenChange={handleAllLinksToggle}
|
||||
className="w-full"
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="mb-2 flex w-full cursor-pointer items-center gap-2 text-left md:mb-4"
|
||||
>
|
||||
<ChevronRightIcon
|
||||
className={cn(
|
||||
"h-5 w-5 text-muted-foreground transition-transform duration-200",
|
||||
isAllLinksOpen && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
<h2 className="m-0">All links</h2>
|
||||
{processedLinks && processedLinks.length > 0 && (
|
||||
<Badge variant="outline" className="text-muted-foreground">
|
||||
{processedLinks.length}
|
||||
</Badge>
|
||||
)}
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
|
||||
{linksTableContent}
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
) : (
|
||||
linksTableContent
|
||||
)}
|
||||
|
||||
{targetType === "DATAROOM" ? (
|
||||
<>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";
|
||||
import { useIsAdmin } from "@/lib/hooks/use-is-admin";
|
||||
|
||||
import { NavMenu } from "../navigation-menu";
|
||||
|
||||
export function SettingsHeader() {
|
||||
const { features } = useFeatureFlags();
|
||||
const { isAdmin } = useIsAdmin();
|
||||
|
||||
return (
|
||||
<header>
|
||||
@@ -78,10 +80,17 @@ export function SettingsHeader() {
|
||||
segment: "incoming-webhooks",
|
||||
disabled: !features?.incomingWebhooks,
|
||||
},
|
||||
{
|
||||
label: "Security",
|
||||
href: `/settings/security`,
|
||||
segment: "security",
|
||||
disabled: !isAdmin,
|
||||
},
|
||||
{
|
||||
label: "Billing",
|
||||
href: `/settings/billing`,
|
||||
segment: "billing",
|
||||
disabled: !isAdmin,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from "lucide-react";
|
||||
|
||||
import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";
|
||||
import { useIsAdmin } from "@/lib/hooks/use-is-admin";
|
||||
import { usePlan } from "@/lib/swr/use-billing";
|
||||
import useDataroomsSimple from "@/lib/swr/use-datarooms-simple";
|
||||
import useLimits from "@/lib/swr/use-limits";
|
||||
@@ -77,6 +78,9 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
// Check feature flags
|
||||
const { features } = useFeatureFlags();
|
||||
|
||||
// Check if current user is admin (for gating Security & Billing)
|
||||
const { isAdmin } = useIsAdmin();
|
||||
|
||||
// Fetch datarooms for the current team (simple mode - no filters or extra data)
|
||||
const { datarooms } = useDataroomsSimple();
|
||||
|
||||
@@ -201,11 +205,20 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
url: "/settings/slack",
|
||||
current: router.pathname.includes("settings/slack"),
|
||||
},
|
||||
{
|
||||
title: "Billing",
|
||||
url: "/settings/billing",
|
||||
current: router.pathname.includes("settings/billing"),
|
||||
},
|
||||
...(isAdmin
|
||||
? [
|
||||
{
|
||||
title: "Security",
|
||||
url: "/settings/security",
|
||||
current: router.pathname.includes("settings/security"),
|
||||
},
|
||||
{
|
||||
title: "Billing",
|
||||
url: "/settings/billing",
|
||||
current: router.pathname.includes("settings/billing"),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
// {
|
||||
@@ -251,7 +264,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
{isDataroomsPlus ? (
|
||||
{isDataroomsPlus && !isDataroomsPremium ? (
|
||||
<span className="relative ml-4 inline-flex items-center rounded-full bg-background px-2.5 py-1 text-xs tracking-normal text-foreground ring-1 ring-gray-800">
|
||||
Datarooms+
|
||||
{isPaused ? (
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import Image from "@tiptap/extension-image";
|
||||
import Placeholder from "@tiptap/extension-placeholder";
|
||||
import Youtube from "@tiptap/extension-youtube";
|
||||
import { EditorContent, useEditor } from "@tiptap/react";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import {
|
||||
Bold,
|
||||
Heading1,
|
||||
Heading2,
|
||||
ImageIcon,
|
||||
Italic,
|
||||
List,
|
||||
@@ -15,9 +18,78 @@ import {
|
||||
Quote,
|
||||
Redo,
|
||||
Undo,
|
||||
Youtube as YoutubeIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
/**
|
||||
* Validates if a given URL is a valid YouTube URL.
|
||||
* Supports:
|
||||
* - youtube.com/watch?v=VIDEO_ID
|
||||
* - youtu.be/VIDEO_ID
|
||||
* - youtube.com/embed/VIDEO_ID
|
||||
* - www.youtube.com variants
|
||||
* - youtube-nocookie.com variants
|
||||
*/
|
||||
function isValidYouTubeUrl(url: string): boolean {
|
||||
if (!url || typeof url !== "string") return false;
|
||||
|
||||
try {
|
||||
const parsedUrl = new URL(url.trim());
|
||||
const hostname = parsedUrl.hostname.toLowerCase();
|
||||
|
||||
// Check for valid YouTube hostnames
|
||||
const validHostnames = [
|
||||
"youtube.com",
|
||||
"www.youtube.com",
|
||||
"youtu.be",
|
||||
"www.youtu.be",
|
||||
"youtube-nocookie.com",
|
||||
"www.youtube-nocookie.com",
|
||||
];
|
||||
|
||||
if (!validHostnames.includes(hostname)) return false;
|
||||
|
||||
// For youtu.be short URLs, the video ID is in the pathname
|
||||
if (hostname === "youtu.be" || hostname === "www.youtu.be") {
|
||||
const videoId = parsedUrl.pathname.slice(1); // Remove leading slash
|
||||
return videoId.length > 0 && /^[\w-]+$/.test(videoId);
|
||||
}
|
||||
|
||||
// For youtube.com/watch URLs, check for 'v' parameter
|
||||
if (parsedUrl.pathname === "/watch") {
|
||||
const videoId = parsedUrl.searchParams.get("v");
|
||||
return videoId !== null && videoId.length > 0 && /^[\w-]+$/.test(videoId);
|
||||
}
|
||||
|
||||
// For youtube.com/embed/VIDEO_ID URLs
|
||||
if (parsedUrl.pathname.startsWith("/embed/")) {
|
||||
const videoId = parsedUrl.pathname.replace("/embed/", "").split("/")[0];
|
||||
return videoId.length > 0 && /^[\w-]+$/.test(videoId);
|
||||
}
|
||||
|
||||
// For youtube.com/v/VIDEO_ID URLs (legacy)
|
||||
if (parsedUrl.pathname.startsWith("/v/")) {
|
||||
const videoId = parsedUrl.pathname.replace("/v/", "").split("/")[0];
|
||||
return videoId.length > 0 && /^[\w-]+$/.test(videoId);
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch {
|
||||
// URL parsing failed
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
interface RichTextEditorProps {
|
||||
content?: any;
|
||||
@@ -32,6 +104,16 @@ export function RichTextEditor({
|
||||
placeholder = "Start typing...",
|
||||
onImageUpload,
|
||||
}: RichTextEditorProps) {
|
||||
const [youtubeDialogOpen, setYoutubeDialogOpen] = useState(false);
|
||||
const [youtubeUrl, setYoutubeUrl] = useState("");
|
||||
const [youtubeUrlError, setYoutubeUrlError] = useState<string | null>(null);
|
||||
|
||||
// Memoize URL validation to avoid recalculating on every render
|
||||
const isYoutubeUrlValid = useMemo(
|
||||
() => isValidYouTubeUrl(youtubeUrl),
|
||||
[youtubeUrl],
|
||||
);
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
@@ -42,6 +124,13 @@ export function RichTextEditor({
|
||||
class: "rounded-lg max-w-full h-auto",
|
||||
},
|
||||
}),
|
||||
Youtube.configure({
|
||||
controls: true,
|
||||
nocookie: true,
|
||||
HTMLAttributes: {
|
||||
class: "rounded-lg w-full aspect-video",
|
||||
},
|
||||
}),
|
||||
Placeholder.configure({
|
||||
placeholder,
|
||||
}),
|
||||
@@ -151,6 +240,37 @@ export function RichTextEditor({
|
||||
[editor, onImageUpload],
|
||||
);
|
||||
|
||||
const addYoutubeVideo = useCallback(() => {
|
||||
if (!editor || !youtubeUrl) return;
|
||||
|
||||
const trimmed = youtubeUrl.trim();
|
||||
|
||||
// Re-validate URL before inserting
|
||||
if (!isValidYouTubeUrl(trimmed)) {
|
||||
setYoutubeUrlError(
|
||||
"Please enter a valid YouTube URL (e.g., youtube.com/watch?v=..., youtu.be/...)",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
editor.commands.setYoutubeVideo({
|
||||
src: trimmed,
|
||||
});
|
||||
|
||||
setYoutubeUrl("");
|
||||
setYoutubeUrlError(null);
|
||||
setYoutubeDialogOpen(false);
|
||||
}, [editor, youtubeUrl]);
|
||||
|
||||
// Clear error and URL when dialog closes
|
||||
const handleYoutubeDialogChange = useCallback((open: boolean) => {
|
||||
setYoutubeDialogOpen(open);
|
||||
if (!open) {
|
||||
setYoutubeUrl("");
|
||||
setYoutubeUrlError(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
if (!editor) {
|
||||
return null;
|
||||
}
|
||||
@@ -159,6 +279,29 @@ export function RichTextEditor({
|
||||
<div className="rounded-md border border-input">
|
||||
{/* Toolbar */}
|
||||
<div className="flex flex-wrap gap-1 border-b border-input p-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
editor.chain().focus().toggleHeading({ level: 1 }).run()
|
||||
}
|
||||
className={editor.isActive("heading", { level: 1 }) ? "bg-muted" : ""}
|
||||
>
|
||||
<Heading1 className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
editor.chain().focus().toggleHeading({ level: 2 }).run()
|
||||
}
|
||||
className={editor.isActive("heading", { level: 2 }) ? "bg-muted" : ""}
|
||||
>
|
||||
<Heading2 className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="mx-1 h-6 w-px bg-border" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -213,6 +356,14 @@ export function RichTextEditor({
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={() => setYoutubeDialogOpen(true)}
|
||||
>
|
||||
<YoutubeIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="mx-1 h-6 w-px bg-border" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -241,6 +392,56 @@ export function RichTextEditor({
|
||||
className="prose prose-sm max-w-none focus:outline-none [&_.ProseMirror]:min-h-[150px] [&_.ProseMirror]:focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* YouTube Dialog */}
|
||||
<Dialog open={youtubeDialogOpen} onOpenChange={handleYoutubeDialogChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add YouTube Video</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="youtube-url">YouTube URL</Label>
|
||||
<Input
|
||||
id="youtube-url"
|
||||
placeholder="https://www.youtube.com/watch?v=..."
|
||||
value={youtubeUrl}
|
||||
onChange={(e) => {
|
||||
setYoutubeUrl(e.target.value);
|
||||
// Clear error when user starts typing
|
||||
if (youtubeUrlError) setYoutubeUrlError(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
addYoutubeVideo();
|
||||
}
|
||||
}}
|
||||
className={youtubeUrlError ? "border-destructive" : ""}
|
||||
/>
|
||||
{youtubeUrlError ? (
|
||||
<p className="text-xs text-destructive">{youtubeUrlError}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Paste a YouTube video URL (e.g., youtube.com/watch?v=...,
|
||||
youtu.be/...)
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleYoutubeDialogChange(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={addYoutubeVideo} disabled={!isYoutubeUrlValid}>
|
||||
Add Video
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import * as React from "react";
|
||||
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { VariantProps, cva } from "class-variance-authority";
|
||||
import { PanelLeft } from "lucide-react";
|
||||
|
||||
import { useIsMobile } from "@/lib/hooks/use-mobile";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -19,6 +18,53 @@ import {
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
|
||||
// Custom PanelLeft icon with filled state support
|
||||
const PanelLeftIcon = ({ filled = false }: { filled?: boolean }) => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
{filled ? (
|
||||
<>
|
||||
{/* Filled left panel background */}
|
||||
<path
|
||||
d="M10 3 H5 a2 2 0 0 0 -2 2 V19 a2 2 0 0 0 2 2 H10 Z"
|
||||
fill="currentColor"
|
||||
stroke="none"
|
||||
/>
|
||||
{/* Menu item lines (centered in sidebar panel) */}
|
||||
<path d="M5.25 8h2.5" className="stroke-background" strokeWidth="1.5" />
|
||||
<path
|
||||
d="M5.25 12h2.5"
|
||||
className="stroke-background"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M5.25 16h2.5"
|
||||
className="stroke-background"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* Menu item lines (centered in sidebar panel) */}
|
||||
<path d="M5.25 8h2.5" strokeWidth="1.5" />
|
||||
<path d="M5.25 12h2.5" strokeWidth="1.5" />
|
||||
<path d="M5.25 16h2.5" strokeWidth="1.5" />
|
||||
</>
|
||||
)}
|
||||
<rect width="18" height="18" x="3" y="3" rx="2" />
|
||||
<path d="M10 3v18" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const SIDEBAR_COOKIE_NAME = "sidebar:state";
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||
const SIDEBAR_WIDTH = "16rem";
|
||||
@@ -286,12 +332,13 @@ const SidebarTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof Button>,
|
||||
React.ComponentProps<typeof Button>
|
||||
>(({ className, onClick, ...props }, ref) => {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
const { toggleSidebar, open } = useSidebar();
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
data-sidebar="trigger"
|
||||
data-state={open ? "open" : "closed"}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("h-7 w-7", className)}
|
||||
@@ -301,7 +348,7 @@ const SidebarTrigger = React.forwardRef<
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeft />
|
||||
<PanelLeftIcon filled={open} />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -40,7 +40,12 @@ export type DEFAULT_DATAROOM_DOCUMENT_VIEW_TYPE = {
|
||||
file: string;
|
||||
pageNumber: string;
|
||||
embeddedLinks: string[];
|
||||
pageLinks: { href: string; coords: string }[];
|
||||
pageLinks: {
|
||||
href: string;
|
||||
coords: string;
|
||||
isInternal?: boolean;
|
||||
targetPage?: number;
|
||||
}[];
|
||||
metadata: { width: number; height: number; scaleFactor: number };
|
||||
}[]
|
||||
| null;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSlot,
|
||||
} from "@/components/ui/input-otp";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const REGEXP_ONLY_DIGITS = "^\\d+$";
|
||||
|
||||
export interface DownloadOtpVerificationProps {
|
||||
linkId: string;
|
||||
/** viewId is optional — when omitted the server resolves the view by email + linkId. */
|
||||
viewId?: string;
|
||||
email: string;
|
||||
onVerified: () => void;
|
||||
onCancel?: () => void;
|
||||
compact?: boolean;
|
||||
/** When true, send OTP email automatically on mount (e.g. when user just chose "Notify me" and clicked Start download). */
|
||||
sendOtpOnMount?: boolean;
|
||||
}
|
||||
|
||||
const RESEND_COOLDOWN_SECONDS = 60;
|
||||
|
||||
export function DownloadOtpVerification({
|
||||
linkId,
|
||||
viewId,
|
||||
email,
|
||||
onVerified,
|
||||
onCancel,
|
||||
compact = false,
|
||||
sendOtpOnMount = false,
|
||||
}: DownloadOtpVerificationProps) {
|
||||
const [code, setCode] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [resendCooldown, setResendCooldown] = useState(0);
|
||||
const hasSentOnMountRef = useRef(false);
|
||||
|
||||
const sendOtp = useCallback(async () => {
|
||||
setIsSending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const body: Record<string, string> = { linkId, email };
|
||||
if (viewId) body.viewId = viewId;
|
||||
const res = await fetch("/api/links/download/verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(data.error ?? "Failed to send code");
|
||||
return;
|
||||
}
|
||||
setResendCooldown(RESEND_COOLDOWN_SECONDS);
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
}, [linkId, viewId, email]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sendOtpOnMount || hasSentOnMountRef.current) return;
|
||||
hasSentOnMountRef.current = true;
|
||||
sendOtp();
|
||||
}, [sendOtpOnMount, sendOtp]);
|
||||
|
||||
const verifyOtp = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!code || code.length !== 6) return;
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const body: Record<string, string> = { linkId, email, code: code! };
|
||||
if (viewId) body.viewId = viewId;
|
||||
const res = await fetch("/api/links/download/verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(data.error ?? "Invalid code");
|
||||
return;
|
||||
}
|
||||
onVerified();
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (resendCooldown <= 0) return;
|
||||
const t = setInterval(
|
||||
() => setResendCooldown((s) => Math.max(0, s - 1)),
|
||||
1000,
|
||||
);
|
||||
return () => clearInterval(t);
|
||||
}, [resendCooldown]);
|
||||
|
||||
return (
|
||||
<form onSubmit={verifyOtp} className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
We sent a 6-digit code to <strong>{email}</strong>. Enter it below to
|
||||
verify and receive download notifications.
|
||||
</p>
|
||||
<InputOTP
|
||||
maxLength={6}
|
||||
pattern={REGEXP_ONLY_DIGITS}
|
||||
value={code ?? ""}
|
||||
onChange={(v) => {
|
||||
setError(null);
|
||||
setCode(v || null);
|
||||
}}
|
||||
containerClassName="my-4"
|
||||
accentColor="#e5e5e5"
|
||||
>
|
||||
<InputOTPGroup className="[&>div]:border-input [&>div]:text-foreground [&>div]:caret-foreground">
|
||||
{[0, 1, 2, 3, 4, 5].map((index) => (
|
||||
<InputOTPSlot key={index} index={index} />
|
||||
))}
|
||||
</InputOTPGroup>
|
||||
</InputOTP>
|
||||
{error ? (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
) : null}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!code || code.length !== 6 || isLoading}
|
||||
>
|
||||
{isLoading ? "Verifying..." : "Verify"}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Didn't receive the email?{" "}
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
className="h-auto p-0 text-sm font-normal text-muted-foreground underline"
|
||||
disabled={isSending || resendCooldown > 0}
|
||||
onClick={sendOtp}
|
||||
>
|
||||
{isSending
|
||||
? "Sending..."
|
||||
: resendCooldown > 0
|
||||
? `Resend code (${resendCooldown}s)`
|
||||
: "Resend code"}
|
||||
</Button>
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user