Compare commits
73
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
../../.agents/skills/vercel-react-best-practices
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/web-design-guidelines
|
||||
@@ -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
|
||||
|
||||
@@ -55,11 +55,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
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -692,7 +692,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 +705,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 +743,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,
|
||||
@@ -811,7 +811,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 +839,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 +955,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 +1060,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}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,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(
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
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,
|
||||
}: {
|
||||
dataroomName?: string;
|
||||
downloadUrl?: string;
|
||||
email: string;
|
||||
expiresAt?: string;
|
||||
}) {
|
||||
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">
|
||||
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)}
|
||||
>
|
||||
|
||||
+282
-158
@@ -1,6 +1,6 @@
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { useTeam } from "@/context/team-context";
|
||||
import { InviteViewersModal } from "@/ee/features/dataroom-invitations/components/invite-viewers-modal";
|
||||
@@ -12,13 +12,18 @@ import {
|
||||
BoxesIcon,
|
||||
ClockFadingIcon,
|
||||
Code2Icon,
|
||||
CopyCheckIcon,
|
||||
CopyIcon,
|
||||
CopyPlusIcon,
|
||||
EyeIcon,
|
||||
EyeOffIcon,
|
||||
FileSlidersIcon,
|
||||
HourglassIcon,
|
||||
LinkIcon,
|
||||
SendIcon,
|
||||
Settings2Icon,
|
||||
Square,
|
||||
SquareArrowOutUpRightIcon,
|
||||
SquareDashedIcon,
|
||||
TimerOffIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
@@ -85,7 +90,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 +99,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,
|
||||
@@ -627,9 +776,8 @@ export default function LinksTable({
|
||||
<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>
|
||||
<TableHead>Link</TableHead>
|
||||
{/* <TableHead className="w-fit !pl-1"></TableHead> */}
|
||||
{hasAnyTags ? (
|
||||
<TableHead className="w-[250px] 2xl:w-auto">Tags</TableHead>
|
||||
) : null}
|
||||
@@ -653,14 +801,22 @@ export default function LinksTable({
|
||||
"bg-gray-50 opacity-50 dark:bg-gray-700",
|
||||
)}
|
||||
>
|
||||
<TableCell className="w-[250px] truncate font-medium">
|
||||
<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" />
|
||||
<BoxesIcon className="size-4 shrink-0" />
|
||||
</ButtonTooltip>
|
||||
) : null}
|
||||
{link.name || `Link #${link.id.slice(-5)}`}
|
||||
<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)}`}
|
||||
</span>
|
||||
</ButtonTooltip>
|
||||
{link.isNew && !link.isUpdated && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
@@ -710,157 +866,125 @@ export default function LinksTable({
|
||||
) : 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",
|
||||
)}
|
||||
>
|
||||
{/* 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}
|
||||
/>
|
||||
{/* 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,
|
||||
)}
|
||||
|
||||
<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
|
||||
link={link}
|
||||
isProcessing={isDocumentProcessing(primaryVersion)}
|
||||
onPreview={handlePreviewLink}
|
||||
/>
|
||||
{targetType === "DATAROOM" &&
|
||||
link.permissionGroupId && (
|
||||
<ButtonTooltip content="Limited File Access">
|
||||
<FileSlidersIcon className="text-gray-400 group-hover:text-gray-500" />
|
||||
</ButtonTooltip>
|
||||
)}
|
||||
{isMobile ? (
|
||||
<ButtonTooltip content="Edit link">
|
||||
<Button
|
||||
variant={"link"}
|
||||
size={"icon"}
|
||||
className="group h-7 w-8"
|
||||
onClick={() => handleEditLink(link)}
|
||||
>
|
||||
<span className="sr-only">Edit link</span>
|
||||
<Settings2Icon className="text-gray-400 group-hover:text-gray-500" />
|
||||
</Button>
|
||||
</ButtonTooltip>
|
||||
) : (
|
||||
<Popover
|
||||
open={popoverOpen === link.id}
|
||||
onOpenChange={() => {}}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="link"
|
||||
className={cn(
|
||||
"h-7 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",
|
||||
)}
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleEditLink(link);
|
||||
}}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onMouseEnter={() => {
|
||||
hoverTimeout.current = setTimeout(
|
||||
() => setPopoverOpen(link.id),
|
||||
250,
|
||||
);
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
if (hoverTimeout.current)
|
||||
clearTimeout(hoverTimeout.current);
|
||||
|
||||
// Add delay before closing to prevent flickering
|
||||
hoverTimeout.current = setTimeout(
|
||||
() => setPopoverOpen(null),
|
||||
100,
|
||||
);
|
||||
}}
|
||||
primaryVersion={primaryVersion}
|
||||
mutateDocument={mutateDocument}
|
||||
isPopoverOpen={popoverOpen === link.id}
|
||||
/>
|
||||
<div className="flex shrink-0 items-center">
|
||||
<LinkActionsCell
|
||||
link={link}
|
||||
onCopy={handleCopyToClipboard}
|
||||
onPreview={handlePreviewLink}
|
||||
isProcessing={isDocumentProcessing(
|
||||
primaryVersion,
|
||||
)}
|
||||
/>
|
||||
{isMobile ? (
|
||||
<ButtonTooltip content="Edit link">
|
||||
<Button
|
||||
variant="link"
|
||||
size="icon"
|
||||
className="group h-8 w-8"
|
||||
onClick={() => handleEditLink(link)}
|
||||
>
|
||||
<span className="sr-only">Edit link</span>
|
||||
<Settings2Icon className="text-gray-400 group-hover:text-gray-500" />
|
||||
</Button>
|
||||
</ButtonTooltip>
|
||||
) : (
|
||||
<Popover
|
||||
open={popoverOpen === link.id}
|
||||
onOpenChange={() => {}}
|
||||
>
|
||||
<Settings2Icon strokeWidth={1.75} />
|
||||
<span className="whitespace-nowrap">
|
||||
{countActiveSettings(link)}{" "}
|
||||
{countActiveSettings(link) === 1
|
||||
? "control"
|
||||
: "controls"}
|
||||
</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
side="top"
|
||||
align="start"
|
||||
className="w-56 p-0"
|
||||
onMouseEnter={() => {
|
||||
if (hoverTimeout.current)
|
||||
clearTimeout(hoverTimeout.current);
|
||||
setPopoverOpen(link.id);
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
if (hoverTimeout.current)
|
||||
clearTimeout(hoverTimeout.current);
|
||||
|
||||
// Add delay before closing to prevent flickering
|
||||
hoverTimeout.current = setTimeout(
|
||||
() => setPopoverOpen(null),
|
||||
100,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<LinkActiveControls
|
||||
link={link}
|
||||
onEditClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleEditLink(link);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="link"
|
||||
className={cn(
|
||||
"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",
|
||||
)}
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleEditLink(link);
|
||||
}}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onMouseEnter={() => {
|
||||
hoverTimeout.current = setTimeout(
|
||||
() => setPopoverOpen(link.id),
|
||||
250,
|
||||
);
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
if (hoverTimeout.current)
|
||||
clearTimeout(hoverTimeout.current);
|
||||
hoverTimeout.current = setTimeout(
|
||||
() => setPopoverOpen(null),
|
||||
100,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Settings2Icon />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
side="top"
|
||||
align="start"
|
||||
className="w-56 p-0"
|
||||
onMouseEnter={() => {
|
||||
if (hoverTimeout.current)
|
||||
clearTimeout(hoverTimeout.current);
|
||||
setPopoverOpen(link.id);
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
if (hoverTimeout.current)
|
||||
clearTimeout(hoverTimeout.current);
|
||||
hoverTimeout.current = setTimeout(
|
||||
() => setPopoverOpen(null),
|
||||
100,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<LinkActiveControls
|
||||
link={link}
|
||||
onEditClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleEditLink(link);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
{/* Reserve space for file permissions icon in dataroom */}
|
||||
{targetType === "DATAROOM" && (
|
||||
<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="h-4 w-4 text-muted-foreground hover:text-foreground" />
|
||||
</Button>
|
||||
</ButtonTooltip>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
{hasAnyTags ? (
|
||||
<TableCell className="w-[250px] 2xl:w-auto">
|
||||
|
||||
@@ -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,327 @@
|
||||
"use client";
|
||||
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
useCallback,
|
||||
} from "react";
|
||||
|
||||
import { InfoIcon } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
|
||||
interface IntroductionModalProps {
|
||||
dataroom: {
|
||||
id?: string;
|
||||
name?: string;
|
||||
introductionEnabled?: boolean;
|
||||
introductionContent?: any;
|
||||
};
|
||||
viewerId?: string;
|
||||
}
|
||||
|
||||
// Context to share modal state
|
||||
interface IntroductionContextType {
|
||||
openIntroduction: () => void;
|
||||
hasIntroduction: boolean;
|
||||
hasSeen: boolean;
|
||||
}
|
||||
|
||||
const IntroductionContext = createContext<IntroductionContextType>({
|
||||
openIntroduction: () => {},
|
||||
hasIntroduction: false,
|
||||
hasSeen: false,
|
||||
});
|
||||
|
||||
export const useIntroduction = () => useContext(IntroductionContext);
|
||||
|
||||
// Info button component to be placed inline (e.g., next to dataroom name)
|
||||
export function IntroductionInfoButton() {
|
||||
const { openIntroduction, hasIntroduction, hasSeen } = useIntroduction();
|
||||
|
||||
if (!hasIntroduction) return null;
|
||||
|
||||
return (
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
onClick={openIntroduction}
|
||||
className={`inline-flex items-center justify-center rounded-full p-1.5 transition-colors ${
|
||||
hasSeen
|
||||
? "text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
: "border-2 border-gray-900 text-gray-900 hover:bg-gray-100 dark:border-white dark:text-white dark:hover:bg-gray-800"
|
||||
}`}
|
||||
aria-label="View introduction"
|
||||
>
|
||||
<InfoIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="left">
|
||||
<p>View introduction</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// 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
|
||||
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 dark:text-gray-100"
|
||||
>
|
||||
{text}
|
||||
</h1>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<h2
|
||||
key={index}
|
||||
className="mb-2 mt-4 text-base font-semibold text-gray-800 first:mt-0 dark:text-gray-200"
|
||||
>
|
||||
{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, pIndex: number) =>
|
||||
p.content?.map((textNode: any, textIndex: number) =>
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
interface IntroductionProviderProps extends IntroductionModalProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function IntroductionProvider({
|
||||
dataroom,
|
||||
viewerId,
|
||||
children,
|
||||
}: IntroductionProviderProps) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [hasSeen, setHasSeen] = useState(true); // Default to true, will be updated on mount
|
||||
|
||||
const storageKey = `dataroom-intro-seen-${dataroom.id}${viewerId ? `-${viewerId}` : ""}`;
|
||||
|
||||
const content = dataroom.introductionContent as any;
|
||||
const hasContent =
|
||||
dataroom.introductionEnabled &&
|
||||
content?.content &&
|
||||
content.content.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
// Check if introduction is enabled and has content
|
||||
if (!hasContent) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if user has already seen the introduction
|
||||
const seen = localStorage.getItem(storageKey);
|
||||
setHasSeen(!!seen);
|
||||
|
||||
// Show modal only first time
|
||||
if (!seen) {
|
||||
setIsOpen(true);
|
||||
}
|
||||
}, [hasContent, storageKey]);
|
||||
|
||||
const handleClose = () => {
|
||||
setIsOpen(false);
|
||||
localStorage.setItem(storageKey, "true");
|
||||
setHasSeen(true);
|
||||
};
|
||||
|
||||
const openIntroduction = useCallback(() => {
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<IntroductionContext.Provider
|
||||
value={{ openIntroduction, hasIntroduction: hasContent, hasSeen }}
|
||||
>
|
||||
{children}
|
||||
|
||||
{/* Introduction Modal */}
|
||||
{hasContent && (
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
handleClose();
|
||||
} else {
|
||||
setIsOpen(true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<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-6 py-6 dark:border-gray-800 dark:bg-gray-900">
|
||||
<DialogTitle className="text-xl font-semibold">
|
||||
Welcome to {dataroom.name || "Data Room"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[60vh] px-6 py-5">
|
||||
<div className="prose prose-sm max-w-none dark:prose-invert">
|
||||
{renderContent(content)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="flex justify-end border-t border-gray-100 bg-gray-50 px-6 py-4 dark:border-gray-800 dark:bg-gray-900">
|
||||
<Button onClick={handleClose} size="lg">
|
||||
Continue to Data Room
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</IntroductionContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// Backwards compatible export
|
||||
export function IntroductionModal({
|
||||
dataroom,
|
||||
viewerId,
|
||||
}: IntroductionModalProps) {
|
||||
return (
|
||||
<IntroductionProvider dataroom={dataroom} viewerId={viewerId}>
|
||||
{null}
|
||||
</IntroductionProvider>
|
||||
);
|
||||
}
|
||||
@@ -35,7 +35,12 @@ export type DEFAULT_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;
|
||||
|
||||
@@ -48,6 +48,10 @@ import DocumentCard from "../dataroom/document-card";
|
||||
import { DocumentUploadModal } from "../dataroom/document-upload-modal";
|
||||
import FolderCard from "../dataroom/folder-card";
|
||||
import IndexFileDialog from "../dataroom/index-file-dialog";
|
||||
import {
|
||||
IntroductionInfoButton,
|
||||
IntroductionProvider,
|
||||
} from "../dataroom/introduction-modal";
|
||||
import DataroomNav from "../dataroom/nav-dataroom";
|
||||
|
||||
const ViewerBreadcrumbItem = ({
|
||||
@@ -384,16 +388,17 @@ export default function DataroomViewer({
|
||||
}));
|
||||
|
||||
return (
|
||||
<ViewerChatProvider
|
||||
enabled={viewData.agentsEnabled}
|
||||
dataroomId={dataroom?.id}
|
||||
dataroomName={viewData.dataroomName}
|
||||
linkId={linkId}
|
||||
viewId={viewId}
|
||||
viewerId={viewerId}
|
||||
documents={documentsForChat}
|
||||
folders={folders}
|
||||
>
|
||||
<IntroductionProvider dataroom={dataroom} viewerId={viewerId}>
|
||||
<ViewerChatProvider
|
||||
enabled={viewData.agentsEnabled}
|
||||
dataroomId={dataroom?.id}
|
||||
dataroomName={viewData.dataroomName}
|
||||
linkId={linkId}
|
||||
viewId={viewId}
|
||||
viewerId={viewerId}
|
||||
documents={documentsForChat}
|
||||
folders={folders}
|
||||
>
|
||||
<DataroomNav
|
||||
brand={brand}
|
||||
linkId={linkId}
|
||||
@@ -499,6 +504,7 @@ export default function DataroomViewer({
|
||||
</Breadcrumb>
|
||||
|
||||
<div className="flex items-center gap-x-2">
|
||||
<IntroductionInfoButton />
|
||||
<SearchBoxPersisted inputClassName="h-9" />
|
||||
{enableIndexFile && viewId && viewerId && (
|
||||
<IndexFileDialog
|
||||
@@ -561,6 +567,7 @@ export default function DataroomViewer({
|
||||
{/* AI Chat Components */}
|
||||
<ViewerChatPanel />
|
||||
<ViewerChatToggle />
|
||||
</ViewerChatProvider>
|
||||
</ViewerChatProvider>
|
||||
</IntroductionProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,10 +11,7 @@ import { getTrackingOptions } from "@/lib/tracking/tracking-config";
|
||||
import { WatermarkConfig } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import {
|
||||
ResizablePanel,
|
||||
ResizablePanelGroup,
|
||||
} from "@/components/ui/resizable";
|
||||
import { ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
|
||||
|
||||
import { ScreenProtector } from "../ScreenProtection";
|
||||
import Nav, { TNavData } from "../nav";
|
||||
@@ -48,7 +45,12 @@ export default function PagesHorizontalViewer({
|
||||
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 };
|
||||
}[];
|
||||
feedbackEnabled: boolean;
|
||||
@@ -901,7 +903,6 @@ export default function PagesHorizontalViewer({
|
||||
/>
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -11,10 +11,7 @@ import { WatermarkConfig } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useMediaQuery } from "@/lib/utils/use-media-query";
|
||||
|
||||
import {
|
||||
ResizablePanel,
|
||||
ResizablePanelGroup,
|
||||
} from "@/components/ui/resizable";
|
||||
import { ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
|
||||
|
||||
import { ScreenProtector } from "../ScreenProtection";
|
||||
import Nav, { TNavData } from "../nav";
|
||||
@@ -27,6 +24,7 @@ import { AwayPoster } from "./away-poster";
|
||||
import "@/styles/custom-viewer-styles.css";
|
||||
|
||||
const DEFAULT_PRELOADED_IMAGES_NUM = 5;
|
||||
const JUMP_WINDOW_SIZE = 3; // Number of pages to load before and after target when jumping
|
||||
|
||||
const calculateOptimalWidth = (
|
||||
containerWidth: number,
|
||||
@@ -73,7 +71,12 @@ export default function PagesVerticalViewer({
|
||||
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 };
|
||||
}[];
|
||||
feedbackEnabled: boolean;
|
||||
@@ -621,12 +624,17 @@ export default function PagesVerticalViewer({
|
||||
isPreview,
|
||||
});
|
||||
|
||||
// Preload target page and 2 pages on either side
|
||||
const startPage = Math.max(0, targetPage - 2 - 1);
|
||||
const endPage = Math.min(numPages - 1, targetPage + 2 - 1);
|
||||
// Only load a bounded window around the target page to avoid unbounded downloads
|
||||
// Unloaded pages will render as placeholders with correct height from metadata
|
||||
const startPage = Math.max(0, targetPage - 1 - JUMP_WINDOW_SIZE);
|
||||
const endPage = Math.min(
|
||||
numPages - 1,
|
||||
targetPage - 1 + JUMP_WINDOW_SIZE,
|
||||
);
|
||||
|
||||
setLoadedImages((prev) => {
|
||||
const newLoadedImages = [...prev];
|
||||
// Only load pages within the window around targetPage
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
newLoadedImages[i] = true;
|
||||
}
|
||||
@@ -635,16 +643,49 @@ export default function PagesVerticalViewer({
|
||||
|
||||
setPageNumber(targetPage);
|
||||
pageNumberRef.current = targetPage;
|
||||
if (containerRef.current) {
|
||||
scrollActionRef.current = true;
|
||||
const newScrollPosition =
|
||||
((targetPage - 1) * containerRef.current.scrollHeight) /
|
||||
numPagesWithAccountCreation;
|
||||
containerRef.current.scrollTo({
|
||||
top: newScrollPosition,
|
||||
behavior: "smooth",
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for images to load before scrolling
|
||||
const waitForImageAndScroll = () => {
|
||||
const targetImg = imageRefs.current[targetPage - 1];
|
||||
|
||||
// Check if target image exists and is loaded
|
||||
if (targetImg && targetImg.complete && targetImg.naturalHeight > 0) {
|
||||
scrollActionRef.current = true;
|
||||
targetImg.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
return;
|
||||
}
|
||||
|
||||
// If image element exists but not loaded, wait for it
|
||||
if (targetImg) {
|
||||
const handleLoad = () => {
|
||||
scrollActionRef.current = true;
|
||||
targetImg.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
targetImg.removeEventListener("load", handleLoad);
|
||||
};
|
||||
targetImg.addEventListener("load", handleLoad);
|
||||
|
||||
// Timeout fallback in case image is already cached but complete wasn't set
|
||||
setTimeout(() => {
|
||||
targetImg.removeEventListener("load", handleLoad);
|
||||
if (targetImg) {
|
||||
scrollActionRef.current = true;
|
||||
targetImg.scrollIntoView({
|
||||
behavior: "smooth",
|
||||
block: "start",
|
||||
});
|
||||
}
|
||||
}, 500);
|
||||
return;
|
||||
}
|
||||
|
||||
// Image ref not available yet, wait for React to render
|
||||
requestAnimationFrame(waitForImageAndScroll);
|
||||
};
|
||||
|
||||
// Start checking after React processes the state update
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(waitForImageAndScroll);
|
||||
});
|
||||
|
||||
// Reset the start time for the new page
|
||||
startTimeRef.current = Date.now();
|
||||
@@ -816,15 +857,49 @@ export default function PagesVerticalViewer({
|
||||
e.stopPropagation();
|
||||
}}
|
||||
>
|
||||
{pages.map((page, index) =>
|
||||
loadedImages[index] ? (
|
||||
{pages.map((page, index) => {
|
||||
const optimalWidth = containerWidth
|
||||
? calculateOptimalWidth(
|
||||
containerWidth,
|
||||
page.metadata,
|
||||
isMobile,
|
||||
isTablet,
|
||||
)
|
||||
: 800;
|
||||
|
||||
// Calculate placeholder height from metadata aspect ratio
|
||||
const placeholderHeight =
|
||||
page.metadata && page.metadata.width > 0
|
||||
? (optimalWidth * page.metadata.height) /
|
||||
page.metadata.width
|
||||
: 600; // fallback height
|
||||
|
||||
if (!loadedImages[index]) {
|
||||
// Render a placeholder div with correct dimensions to preserve scroll height
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className="relative w-full px-4 md:px-8"
|
||||
style={{
|
||||
width: `${optimalWidth}px`,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="viewer-container relative border-b border-t border-gray-100 bg-gray-50"
|
||||
style={{
|
||||
height: `${placeholderHeight}px`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className="relative w-full px-4 md:px-8"
|
||||
style={{
|
||||
width: containerWidth
|
||||
? `${calculateOptimalWidth(containerWidth, page.metadata, isMobile, isTablet)}px`
|
||||
: undefined,
|
||||
width: `${optimalWidth}px`,
|
||||
}}
|
||||
>
|
||||
<div className="viewer-container relative border-b border-t border-gray-100">
|
||||
@@ -880,11 +955,7 @@ export default function PagesVerticalViewer({
|
||||
}
|
||||
}}
|
||||
useMap={`#page-map-${index + 1}`}
|
||||
src={
|
||||
loadedImages[index]
|
||||
? page.file
|
||||
: "https://www.papermark.com/_static/blank.gif"
|
||||
}
|
||||
src={page.file}
|
||||
alt={`Page ${index + 1}`}
|
||||
/>
|
||||
|
||||
@@ -979,8 +1050,8 @@ export default function PagesVerticalViewer({
|
||||
})
|
||||
: null}
|
||||
</div>
|
||||
) : null,
|
||||
)}
|
||||
);
|
||||
})}
|
||||
|
||||
{enableQuestion &&
|
||||
feedback &&
|
||||
@@ -1060,7 +1131,6 @@ export default function PagesVerticalViewer({
|
||||
{/* </div> */}
|
||||
{/* </div> */}
|
||||
</ResizablePanel>
|
||||
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -422,8 +422,8 @@ export function InviteViewersModal({
|
||||
<br />
|
||||
<span className="break-all text-foreground">
|
||||
{selectedLink
|
||||
? `https://papermark.io/view/${selectedLink.slug ?? selectedLink.id}`
|
||||
: "https://papermark.io/view/..."}
|
||||
? `https://papermark.com/view/${selectedLink.slug ?? selectedLink.id}`
|
||||
: "https://papermark.com/view/..."}
|
||||
</span>
|
||||
</p>
|
||||
<Separator className="my-2" />
|
||||
|
||||
@@ -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 {
|
||||
@@ -113,6 +115,7 @@ export function DataroomLinkSheet({
|
||||
const [currentPreset, setCurrentPreset] = useState<LinkPreset | null>(null);
|
||||
const [showPermissionsSheet, setShowPermissionsSheet] =
|
||||
useState<boolean>(false);
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const [pendingLinkData, setPendingLinkData] =
|
||||
useState<DEFAULT_LINK_TYPE | null>(null);
|
||||
const [showSuccessSheet, setShowSuccessSheet] = useState<boolean>(false);
|
||||
@@ -140,6 +143,19 @@ export function DataroomLinkSheet({
|
||||
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");
|
||||
@@ -695,6 +711,7 @@ export function DataroomLinkSheet({
|
||||
</SheetHeader>
|
||||
|
||||
<form
|
||||
ref={formRef}
|
||||
className="flex grow flex-col"
|
||||
onSubmit={(e) => handleSubmit(e, false)}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { toast } from "sonner";
|
||||
import { z } from "zod";
|
||||
@@ -327,7 +327,7 @@ export function StepFormDialog({
|
||||
)}
|
||||
{!link.domainSlug && link.slug && (
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
papermark.io/{link.slug}
|
||||
papermark.com/{link.slug}
|
||||
</span>
|
||||
)}
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Link from "next/link";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
import { timeAgo } from "@/lib/utils";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
interface Workflow {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -28,7 +30,7 @@ export function WorkflowList({ workflows }: WorkflowListProps) {
|
||||
if (workflow.entryLink.domainSlug && workflow.entryLink.slug) {
|
||||
return `https://${workflow.entryLink.domainSlug}/${workflow.entryLink.slug}`;
|
||||
}
|
||||
return `${process.env.NEXT_PUBLIC_MARKETING_URL || "https://www.papermark.io"}/view/${workflow.entryLink.id}`;
|
||||
return `${process.env.NEXT_PUBLIC_MARKETING_URL || "https://www.papermark.com"}/view/${workflow.entryLink.id}`;
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -72,4 +74,3 @@ export function WorkflowList({ workflows }: WorkflowListProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
import { useTeam } from "@/context/team-context";
|
||||
import { toast } from "sonner";
|
||||
import useSWR from "swr";
|
||||
import { z } from "zod";
|
||||
|
||||
import { fetcher } from "@/lib/utils";
|
||||
|
||||
@@ -87,7 +87,9 @@ export default function WorkflowDetailPage() {
|
||||
error,
|
||||
mutate,
|
||||
} = useSWR<Workflow>(
|
||||
validWorkflowId && validTeamId ? `/api/workflows/${validWorkflowId}?teamId=${validTeamId}` : null,
|
||||
validWorkflowId && validTeamId
|
||||
? `/api/workflows/${validWorkflowId}?teamId=${validTeamId}`
|
||||
: null,
|
||||
fetcher,
|
||||
);
|
||||
|
||||
@@ -101,7 +103,7 @@ export default function WorkflowDetailPage() {
|
||||
if (workflow.entryLink.domainSlug && workflow.entryLink.slug) {
|
||||
return `https://${workflow.entryLink.domainSlug}/${workflow.entryLink.slug}`;
|
||||
}
|
||||
return `${process.env.NEXT_PUBLIC_MARKETING_URL || "https://www.papermark.io"}/view/${workflow.entryLink.id}`;
|
||||
return `${process.env.NEXT_PUBLIC_MARKETING_URL || "https://www.papermark.com"}/view/${workflow.entryLink.id}`;
|
||||
};
|
||||
|
||||
const handleDeleteStep = async (stepId: string) => {
|
||||
@@ -110,7 +112,11 @@ export default function WorkflowDetailPage() {
|
||||
const stepIdValidation = z.string().cuid().safeParse(stepId);
|
||||
const teamIdValidation = z.string().cuid().safeParse(teamId);
|
||||
|
||||
if (!workflowIdValidation.success || !stepIdValidation.success || !teamIdValidation.success) {
|
||||
if (
|
||||
!workflowIdValidation.success ||
|
||||
!stepIdValidation.success ||
|
||||
!teamIdValidation.success
|
||||
) {
|
||||
toast.error("Invalid workflow, step, or team ID");
|
||||
return;
|
||||
}
|
||||
|
||||
+373
-16
@@ -1,12 +1,102 @@
|
||||
import {
|
||||
Brand,
|
||||
DataroomBrand,
|
||||
ItemType,
|
||||
LinkAudienceType,
|
||||
LinkType,
|
||||
PermissionGroupAccessControls,
|
||||
Prisma,
|
||||
ViewerGroupAccessControls,
|
||||
} from "@prisma/client";
|
||||
|
||||
import prisma from "@/lib/prisma";
|
||||
import { sortItemsByIndexAndName } from "@/lib/utils/sort-items-by-index-name";
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type LinkFetchStatus = "ok" | "not_found" | "archived" | "deleted" | "free";
|
||||
|
||||
export type LinkFetchResult =
|
||||
| {
|
||||
status: "ok";
|
||||
linkType: LinkType;
|
||||
link: any;
|
||||
brand: Partial<Brand> | Partial<DataroomBrand> | null;
|
||||
linkId?: string;
|
||||
}
|
||||
| {
|
||||
status: Exclude<LinkFetchStatus, "ok">;
|
||||
};
|
||||
|
||||
// Common select object for link queries
|
||||
const linkSelect = {
|
||||
id: true,
|
||||
expiresAt: true,
|
||||
emailProtected: true,
|
||||
emailAuthenticated: true,
|
||||
allowDownload: true,
|
||||
enableFeedback: true,
|
||||
enableScreenshotProtection: true,
|
||||
password: true,
|
||||
isArchived: true,
|
||||
deletedAt: true,
|
||||
enableIndexFile: true,
|
||||
enableCustomMetatag: true,
|
||||
metaTitle: true,
|
||||
metaDescription: true,
|
||||
metaImage: true,
|
||||
metaFavicon: true,
|
||||
welcomeMessage: true,
|
||||
enableQuestion: true,
|
||||
linkType: true,
|
||||
feedback: {
|
||||
select: {
|
||||
id: true,
|
||||
data: true,
|
||||
},
|
||||
},
|
||||
enableAgreement: true,
|
||||
agreement: true,
|
||||
showBanner: true,
|
||||
enableWatermark: true,
|
||||
watermarkConfig: true,
|
||||
groupId: true,
|
||||
permissionGroupId: true,
|
||||
audienceType: true,
|
||||
dataroomId: true,
|
||||
teamId: true,
|
||||
team: {
|
||||
select: {
|
||||
plan: true,
|
||||
globalBlockList: true,
|
||||
},
|
||||
},
|
||||
customFields: {
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
identifier: true,
|
||||
label: true,
|
||||
placeholder: true,
|
||||
required: true,
|
||||
disabled: true,
|
||||
orderIndex: true,
|
||||
},
|
||||
orderBy: {
|
||||
orderIndex: "asc" as const,
|
||||
},
|
||||
},
|
||||
} satisfies Prisma.LinkSelect;
|
||||
|
||||
// Type for the link record returned by the common select query
|
||||
type LinkRecord = Prisma.LinkGetPayload<{ select: typeof linkSelect }>;
|
||||
|
||||
// ============================================================================
|
||||
// Internal Helpers
|
||||
// ============================================================================
|
||||
|
||||
// Helper function to get all parent folder IDs for given folder IDs
|
||||
async function getAllParentFolderIds(
|
||||
folderIds: string[],
|
||||
@@ -31,7 +121,6 @@ async function getAllParentFolderIds(
|
||||
// For each accessible folder, traverse up to find all parent folders
|
||||
for (const folderId of folderIds) {
|
||||
let currentId: string | null = folderId;
|
||||
|
||||
while (currentId) {
|
||||
allRequiredFolderIds.add(currentId);
|
||||
currentId = folderMap.get(currentId) || null;
|
||||
@@ -41,6 +130,10 @@ async function getAllParentFolderIds(
|
||||
return Array.from(allRequiredFolderIds);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Data Fetchers (used by both API routes and getStaticProps)
|
||||
// ============================================================================
|
||||
|
||||
export async function fetchDataroomLinkData({
|
||||
linkId,
|
||||
dataroomId,
|
||||
@@ -113,6 +206,8 @@ export async function fetchDataroomLinkData({
|
||||
teamId: true,
|
||||
allowBulkDownload: true,
|
||||
showLastUpdated: true,
|
||||
introductionEnabled: true,
|
||||
introductionContent: true,
|
||||
createdAt: true,
|
||||
documents: {
|
||||
where:
|
||||
@@ -197,9 +292,7 @@ export async function fetchDataroomLinkData({
|
||||
);
|
||||
|
||||
const dataroomBrand = await prisma.dataroomBrand.findFirst({
|
||||
where: {
|
||||
dataroomId: linkData.dataroom.id,
|
||||
},
|
||||
where: { dataroomId: linkData.dataroom.id },
|
||||
select: {
|
||||
logo: true,
|
||||
banner: true,
|
||||
@@ -210,9 +303,7 @@ export async function fetchDataroomLinkData({
|
||||
});
|
||||
|
||||
const teamBrand = await prisma.brand.findFirst({
|
||||
where: {
|
||||
teamId: linkData.dataroom.teamId,
|
||||
},
|
||||
where: { teamId: linkData.dataroom.teamId },
|
||||
select: {
|
||||
logo: true,
|
||||
banner: true,
|
||||
@@ -341,9 +432,7 @@ export async function fetchDataroomDocumentLinkData({
|
||||
}
|
||||
|
||||
const dataroomBrand = await prisma.dataroomBrand.findFirst({
|
||||
where: {
|
||||
dataroomId: linkData.dataroom.id,
|
||||
},
|
||||
where: { dataroomId: linkData.dataroom.id },
|
||||
select: {
|
||||
logo: true,
|
||||
banner: true,
|
||||
@@ -354,9 +443,7 @@ export async function fetchDataroomDocumentLinkData({
|
||||
});
|
||||
|
||||
const teamBrand = await prisma.brand.findFirst({
|
||||
where: {
|
||||
teamId: linkData.dataroom.teamId,
|
||||
},
|
||||
where: { teamId: linkData.dataroom.teamId },
|
||||
select: {
|
||||
logo: true,
|
||||
banner: true,
|
||||
@@ -420,9 +507,7 @@ export async function fetchDocumentLinkData({
|
||||
}
|
||||
|
||||
const brand = await prisma.brand.findFirst({
|
||||
where: {
|
||||
teamId: linkData.document.teamId,
|
||||
},
|
||||
where: { teamId: linkData.document.teamId },
|
||||
select: {
|
||||
logo: true,
|
||||
brandColor: true,
|
||||
@@ -433,3 +518,275 @@ export async function fetchDocumentLinkData({
|
||||
|
||||
return { linkData, brand };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Unified Link Data Fetcher for getStaticProps
|
||||
// Avoids internal HTTP fetch which can be blocked by Vercel edge (403 errors)
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Core function to process link data after fetching the link record.
|
||||
* Handles all link types: DOCUMENT_LINK, DATAROOM_LINK, WORKFLOW_LINK
|
||||
*/
|
||||
async function processLinkData(
|
||||
link: LinkRecord,
|
||||
options: {
|
||||
dataroomDocumentId?: string;
|
||||
isCustomDomain?: boolean;
|
||||
} = {},
|
||||
): Promise<LinkFetchResult> {
|
||||
const { dataroomDocumentId, isCustomDomain } = options;
|
||||
const teamPlan = link.team?.plan || "free";
|
||||
const linkType = link.linkType;
|
||||
|
||||
// For custom domains, free plan is not allowed
|
||||
if (isCustomDomain && teamPlan.includes("free")) {
|
||||
return { status: "free" };
|
||||
}
|
||||
|
||||
// Handle WORKFLOW_LINK
|
||||
if (linkType === "WORKFLOW_LINK") {
|
||||
let brand: Partial<Brand> | null = null;
|
||||
if (link.teamId) {
|
||||
const teamBrand = await prisma.brand.findUnique({
|
||||
where: { teamId: link.teamId },
|
||||
select: {
|
||||
logo: true,
|
||||
brandColor: true,
|
||||
accentColor: true,
|
||||
},
|
||||
});
|
||||
brand = teamBrand;
|
||||
}
|
||||
|
||||
// For workflow links, return the link with minimal processing
|
||||
// Remove team object (contains plan, globalBlockList) but keep teamId for feature flags
|
||||
const sanitizedLink = {
|
||||
...link,
|
||||
team: undefined,
|
||||
deletedAt: undefined,
|
||||
};
|
||||
|
||||
// Serialize to convert Date objects to strings (required for Next.js getStaticProps)
|
||||
const serializedLink = JSON.parse(JSON.stringify(sanitizedLink));
|
||||
const serializedBrand = brand ? JSON.parse(JSON.stringify(brand)) : null;
|
||||
|
||||
return {
|
||||
status: "ok",
|
||||
linkType,
|
||||
brand: serializedBrand,
|
||||
linkId: link.id,
|
||||
link: serializedLink,
|
||||
};
|
||||
}
|
||||
|
||||
let brand: Partial<Brand> | Partial<DataroomBrand> | null = null;
|
||||
let linkData: any;
|
||||
|
||||
// Handle DOCUMENT_LINK
|
||||
if (linkType === "DOCUMENT_LINK") {
|
||||
// Guard: teamId is required for document links
|
||||
if (!link.teamId) {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await fetchDocumentLinkData({
|
||||
linkId: link.id,
|
||||
teamId: link.teamId,
|
||||
});
|
||||
linkData = data.linkData;
|
||||
brand = data.brand;
|
||||
} catch {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
}
|
||||
// Handle DATAROOM_LINK
|
||||
else if (linkType === "DATAROOM_LINK") {
|
||||
// Guard: teamId is required for dataroom links
|
||||
if (!link.teamId) {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
|
||||
if (dataroomDocumentId) {
|
||||
// Fetching specific document within dataroom
|
||||
try {
|
||||
const data = await fetchDataroomDocumentLinkData({
|
||||
linkId: link.id,
|
||||
teamId: link.teamId,
|
||||
dataroomDocumentId: dataroomDocumentId,
|
||||
permissionGroupId: link.permissionGroupId || undefined,
|
||||
...(link.audienceType === LinkAudienceType.GROUP &&
|
||||
link.groupId && {
|
||||
groupId: link.groupId,
|
||||
}),
|
||||
});
|
||||
linkData = data.linkData;
|
||||
brand = data.brand;
|
||||
} catch {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
} else {
|
||||
// Fetching full dataroom
|
||||
try {
|
||||
const data = await fetchDataroomLinkData({
|
||||
linkId: link.id,
|
||||
dataroomId: link.dataroomId,
|
||||
teamId: link.teamId,
|
||||
permissionGroupId: link.permissionGroupId || undefined,
|
||||
...(link.audienceType === LinkAudienceType.GROUP &&
|
||||
link.groupId && {
|
||||
groupId: link.groupId,
|
||||
}),
|
||||
});
|
||||
linkData = data.linkData;
|
||||
brand = data.brand;
|
||||
linkData.accessControls = data.accessControls;
|
||||
} catch {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only include agreement if enabled (no need to expose it otherwise)
|
||||
const sanitizedAgreement =
|
||||
link.enableAgreement && link.agreement
|
||||
? {
|
||||
id: link.agreement.id,
|
||||
name: link.agreement.name,
|
||||
content: link.agreement.content,
|
||||
contentType: link.agreement.contentType,
|
||||
requireName: link.agreement.requireName,
|
||||
}
|
||||
: null;
|
||||
|
||||
// Sanitize document - keep fields needed by getStaticProps
|
||||
// Note: team/teamId are used server-side for feature flags and are stripped before client props
|
||||
const sanitizedDocument = linkData?.document
|
||||
? {
|
||||
id: linkData.document.id,
|
||||
name: linkData.document.name,
|
||||
teamId: linkData.document.teamId,
|
||||
team: linkData.document.team, // Used server-side for plan check, stripped before client
|
||||
downloadOnly: linkData.document.downloadOnly,
|
||||
advancedExcelEnabled: linkData.document.advancedExcelEnabled,
|
||||
versions: linkData.document.versions,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
// Sanitize link for return - remove sensitive/internal data
|
||||
const sanitizedLink = {
|
||||
...link,
|
||||
// Remove team object (contains plan, globalBlockList) but keep teamId for feature flags
|
||||
team: undefined,
|
||||
// Remove internal fields
|
||||
deletedAt: undefined,
|
||||
document: undefined,
|
||||
dataroom: undefined,
|
||||
// Use sanitized agreement
|
||||
agreement: sanitizedAgreement,
|
||||
...(teamPlan === "free" && {
|
||||
customFields: [],
|
||||
enableAgreement: false,
|
||||
enableWatermark: false,
|
||||
permissionGroupId: null,
|
||||
}),
|
||||
};
|
||||
|
||||
const returnLink = {
|
||||
...sanitizedLink,
|
||||
...linkData,
|
||||
// Override with sanitized document
|
||||
document: sanitizedDocument,
|
||||
// Keep dataroomId for DATAROOM_LINK types (needed for session verification and API calls)
|
||||
// For DOCUMENT_LINK types, set to undefined
|
||||
dataroomId:
|
||||
linkType === "DATAROOM_LINK"
|
||||
? link.dataroomId || linkData?.dataroom?.id
|
||||
: undefined,
|
||||
dataroomDocument: linkData?.dataroom?.documents?.[0] || undefined,
|
||||
};
|
||||
|
||||
// Serialize to convert Date objects to strings (required for Next.js getStaticProps)
|
||||
const serializedLink = JSON.parse(JSON.stringify(returnLink));
|
||||
const serializedBrand = brand ? JSON.parse(JSON.stringify(brand)) : null;
|
||||
|
||||
return {
|
||||
status: "ok",
|
||||
linkType,
|
||||
link: serializedLink,
|
||||
brand: serializedBrand,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch link data by linkId (for /view/[linkId] routes)
|
||||
*/
|
||||
export async function fetchLinkDataById({
|
||||
linkId,
|
||||
dataroomDocumentId,
|
||||
}: {
|
||||
linkId: string;
|
||||
dataroomDocumentId?: string;
|
||||
}): Promise<LinkFetchResult> {
|
||||
const link = await prisma.link.findUnique({
|
||||
where: { id: linkId },
|
||||
select: linkSelect,
|
||||
});
|
||||
|
||||
if (!link) {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
|
||||
if (link.deletedAt) {
|
||||
return { status: "deleted" };
|
||||
}
|
||||
|
||||
if (link.isArchived) {
|
||||
return { status: "archived" };
|
||||
}
|
||||
|
||||
return processLinkData(link, { dataroomDocumentId, isCustomDomain: false });
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch link data by domain and slug (for /view/domains/[domain]/[slug] routes)
|
||||
* Includes free plan check since custom domains require paid plan
|
||||
*/
|
||||
export async function fetchLinkDataByDomainSlug({
|
||||
domain,
|
||||
slug,
|
||||
dataroomDocumentId,
|
||||
}: {
|
||||
domain: string;
|
||||
slug: string;
|
||||
dataroomDocumentId?: string;
|
||||
}): Promise<LinkFetchResult> {
|
||||
const link = await prisma.link.findUnique({
|
||||
where: {
|
||||
domainSlug_slug: {
|
||||
slug: slug,
|
||||
domainSlug: domain,
|
||||
},
|
||||
},
|
||||
select: linkSelect,
|
||||
});
|
||||
|
||||
if (!link) {
|
||||
return { status: "not_found" };
|
||||
}
|
||||
|
||||
if (link.deletedAt) {
|
||||
return { status: "deleted" };
|
||||
}
|
||||
|
||||
if (link.isArchived) {
|
||||
return { status: "archived" };
|
||||
}
|
||||
|
||||
return processLinkData(link, { dataroomDocumentId, isCustomDomain: true });
|
||||
}
|
||||
|
||||
// Legacy export aliases for backward compatibility
|
||||
export const fetchCustomDomainLinkData = fetchLinkDataByDomainSlug;
|
||||
export type CustomDomainLinkResult = LinkFetchResult;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { sendEmail } from "@/lib/resend";
|
||||
|
||||
import DownloadReady from "@/components/emails/download-ready";
|
||||
|
||||
export const sendDownloadReadyEmail = async ({
|
||||
to,
|
||||
dataroomName,
|
||||
downloadUrl,
|
||||
expiresAt,
|
||||
}: {
|
||||
to: string;
|
||||
dataroomName: string;
|
||||
downloadUrl: string;
|
||||
expiresAt?: string;
|
||||
}) => {
|
||||
const emailTemplate = DownloadReady({
|
||||
dataroomName,
|
||||
downloadUrl,
|
||||
email: to,
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
try {
|
||||
await sendEmail({
|
||||
to,
|
||||
subject: `Your ${dataroomName} download is ready`,
|
||||
react: emailTemplate,
|
||||
test: process.env.NODE_ENV === "development",
|
||||
system: true,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Error sending download ready email:", e);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
@@ -12,28 +12,71 @@ export class SlackEventManager {
|
||||
this.client = new SlackClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the viewer's email domain is in the team's ignored domains list
|
||||
*/
|
||||
private isViewerDomainIgnored(
|
||||
viewerEmail: string | undefined,
|
||||
ignoredDomains: string[] | null,
|
||||
): boolean {
|
||||
if (!viewerEmail || !ignoredDomains || ignoredDomains.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const viewerDomain = viewerEmail.split("@").pop();
|
||||
if (!viewerDomain) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Normalize ignored domains (remove @ prefix if present)
|
||||
const normalizedIgnoredDomains = ignoredDomains.map((d) =>
|
||||
d.startsWith("@") ? d.substring(1) : d,
|
||||
);
|
||||
|
||||
return normalizedIgnoredDomains.includes(viewerDomain);
|
||||
}
|
||||
|
||||
async processEvent(eventData: SlackEventData): Promise<void> {
|
||||
try {
|
||||
const env = getSlackEnv();
|
||||
|
||||
const integration = await prisma.installedIntegration.findUnique({
|
||||
where: {
|
||||
teamId_integrationId: {
|
||||
teamId: eventData.teamId,
|
||||
integrationId: env.SLACK_INTEGRATION_ID,
|
||||
// Fetch integration and team's ignored domains in parallel
|
||||
const [integration, team] = await Promise.all([
|
||||
prisma.installedIntegration.findUnique({
|
||||
where: {
|
||||
teamId_integrationId: {
|
||||
teamId: eventData.teamId,
|
||||
integrationId: env.SLACK_INTEGRATION_ID,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
enabled: true,
|
||||
credentials: true,
|
||||
configuration: true,
|
||||
},
|
||||
});
|
||||
select: {
|
||||
enabled: true,
|
||||
credentials: true,
|
||||
configuration: true,
|
||||
},
|
||||
}),
|
||||
prisma.team.findUnique({
|
||||
where: { id: eventData.teamId },
|
||||
select: { ignoredDomains: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!integration || !integration.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the viewer's email domain is in the ignored domains list
|
||||
if (
|
||||
this.isViewerDomainIgnored(eventData.viewerEmail, team?.ignoredDomains ?? null)
|
||||
) {
|
||||
// Log only the domain to avoid persisting PII
|
||||
const redactedDomain = eventData.viewerEmail?.split("@").pop() ?? "unknown-domain";
|
||||
console.log(
|
||||
`Slack notification skipped for ignored domain: ${redactedDomain}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.sendSlackNotification(
|
||||
eventData,
|
||||
integration as SlackIntegrationServer,
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { nanoid } from "@/lib/utils";
|
||||
|
||||
import { redis } from "./redis";
|
||||
|
||||
export type DownloadJobStatus =
|
||||
| "PENDING"
|
||||
| "PROCESSING"
|
||||
| "COMPLETED"
|
||||
| "FAILED";
|
||||
|
||||
export interface DownloadJob {
|
||||
id: string;
|
||||
type: "bulk" | "folder";
|
||||
status: DownloadJobStatus;
|
||||
dataroomId: string;
|
||||
dataroomName: string;
|
||||
totalFiles: number;
|
||||
processedFiles: number;
|
||||
progress: number; // 0-100
|
||||
downloadUrls?: string[]; // Multiple ZIPs if large (S3 presigned URLs auto-expire)
|
||||
error?: string;
|
||||
teamId: string;
|
||||
userId: string;
|
||||
triggerRunId?: string; // Trigger.dev run ID for cancellation
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
completedAt?: string;
|
||||
expiresAt?: string; // When download links expire
|
||||
emailNotification?: boolean;
|
||||
emailAddress?: string;
|
||||
}
|
||||
|
||||
const JOB_PREFIX = "download_job:";
|
||||
const TEAM_JOBS_PREFIX = "team_download_jobs:";
|
||||
const JOB_TTL = 60 * 60 * 24 * 3; // 3 days - Redis handles cleanup via TTL
|
||||
|
||||
export class RedisDownloadJobStore {
|
||||
private getJobKey(jobId: string): string {
|
||||
return `${JOB_PREFIX}${jobId}`;
|
||||
}
|
||||
|
||||
private getTeamJobsKey(teamId: string): string {
|
||||
return `${TEAM_JOBS_PREFIX}${teamId}`;
|
||||
}
|
||||
|
||||
async createJob(
|
||||
jobData: Omit<DownloadJob, "id" | "createdAt" | "updatedAt">,
|
||||
): Promise<DownloadJob> {
|
||||
const jobId = nanoid();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const job: DownloadJob = {
|
||||
...jobData,
|
||||
id: jobId,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const jobKey = this.getJobKey(jobId);
|
||||
const teamJobsKey = this.getTeamJobsKey(jobData.teamId);
|
||||
|
||||
// Store job data with TTL (Redis handles cleanup)
|
||||
await redis.setex(jobKey, JOB_TTL, JSON.stringify(job));
|
||||
|
||||
// Add to team's job list (sorted by creation time)
|
||||
await redis.zadd(teamJobsKey, { score: Date.now(), member: jobId });
|
||||
await redis.expire(teamJobsKey, JOB_TTL);
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
async getJob(jobId: string): Promise<DownloadJob | null> {
|
||||
const jobKey = this.getJobKey(jobId);
|
||||
const jobData = await redis.get(jobKey);
|
||||
|
||||
if (!jobData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if data is already an object (Redis client auto-parsed)
|
||||
if (typeof jobData === "object") {
|
||||
return jobData as DownloadJob;
|
||||
}
|
||||
// Otherwise parse the JSON string
|
||||
return JSON.parse(jobData as string);
|
||||
} catch (error) {
|
||||
console.error("Error parsing download job data:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async updateJob(
|
||||
jobId: string,
|
||||
updates: Partial<DownloadJob>,
|
||||
): Promise<DownloadJob | null> {
|
||||
const job = await this.getJob(jobId);
|
||||
if (!job) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const updatedJob: DownloadJob = {
|
||||
...job,
|
||||
...updates,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const jobKey = this.getJobKey(jobId);
|
||||
await redis.setex(jobKey, JOB_TTL, JSON.stringify(updatedJob));
|
||||
|
||||
return updatedJob;
|
||||
}
|
||||
|
||||
private async getTeamJobs(
|
||||
teamId: string,
|
||||
limit: number = 20,
|
||||
): Promise<DownloadJob[]> {
|
||||
const teamJobsKey = this.getTeamJobsKey(teamId);
|
||||
|
||||
// Get job IDs sorted by creation time (newest first)
|
||||
const jobIds = await redis.zrange(teamJobsKey, 0, limit - 1, { rev: true });
|
||||
|
||||
if (!jobIds.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Get all job data
|
||||
const jobs = await Promise.all(
|
||||
(jobIds as string[]).map((jobId: string) => this.getJob(jobId)),
|
||||
);
|
||||
|
||||
// Filter out null values (expired jobs)
|
||||
return jobs.filter(
|
||||
(job: DownloadJob | null): job is DownloadJob => job !== null,
|
||||
);
|
||||
}
|
||||
|
||||
async getDataroomJobs(
|
||||
dataroomId: string,
|
||||
teamId: string,
|
||||
limit: number = 10,
|
||||
): Promise<DownloadJob[]> {
|
||||
const teamJobs = await this.getTeamJobs(teamId, limit * 2); // Get more to filter
|
||||
|
||||
// Filter jobs by dataroom
|
||||
return teamJobs
|
||||
.filter((job) => {
|
||||
const matchesDataroom = job.dataroomId === dataroomId;
|
||||
const matchStatus = job.status !== "FAILED";
|
||||
return matchesDataroom && matchStatus;
|
||||
})
|
||||
.slice(0, limit);
|
||||
}
|
||||
}
|
||||
|
||||
export const downloadJobStore = new RedisDownloadJobStore();
|
||||
+1
-1
@@ -55,7 +55,7 @@ export const sendEmail = async ({
|
||||
? "Papermark <system@verify.papermark.com>"
|
||||
: !!scheduledAt
|
||||
? "Marc Seitz <marc@papermark.com>"
|
||||
: "Marc from Papermark <marc@papermark.io>");
|
||||
: "Marc from Papermark <marc@papermark.com>");
|
||||
|
||||
try {
|
||||
const { data, error } = await resend.emails.send({
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
import { logger, task } from "@trigger.dev/sdk/v3";
|
||||
|
||||
import { sendDownloadReadyEmail } from "@/lib/emails/send-download-ready-email";
|
||||
import { downloadJobStore } from "@/lib/redis-download-job-store";
|
||||
|
||||
// Maximum files per batch (Lambda payload limit)
|
||||
const MAX_FILES_PER_BATCH = 500;
|
||||
// Maximum size for a single ZIP file (500MB to stay within Vercel's 5min timeout)
|
||||
// Lambda needs time to: read from S3 + create ZIP + upload to S3
|
||||
// Conservative estimate: ~500MB can be processed in ~2-3 minutes
|
||||
const MAX_ZIP_SIZE_BYTES = 500 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Generate a UTC timestamp in the format: "20260202T131428Z"
|
||||
* @returns Formatted UTC timestamp
|
||||
*/
|
||||
function generateTimestamp(): string {
|
||||
return new Date()
|
||||
.toISOString()
|
||||
.replace(/[-:]/g, "")
|
||||
.replace(/\.\d{3}/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a zip filename in the format: "Dataroom Name-20260202T131428Z"
|
||||
* @param dataroomName - The name of the dataroom
|
||||
* @param timestamp - The UTC timestamp (shared across all parts)
|
||||
* @param partNumber - The part number (1-indexed) (optional)
|
||||
* @returns Formatted zip filename without extension
|
||||
*/
|
||||
function generateZipFileName(
|
||||
dataroomName: string,
|
||||
timestamp: string,
|
||||
partNumber?: number,
|
||||
): string {
|
||||
// Zero-pad part number to 3 digits
|
||||
const paddedPart = partNumber?.toString().padStart(3, "0") ?? "";
|
||||
|
||||
return `${dataroomName}-${timestamp}${paddedPart ? `-${paddedPart}` : ""}`;
|
||||
}
|
||||
|
||||
export type BulkDownloadPayload = {
|
||||
jobId: string;
|
||||
dataroomId: string;
|
||||
dataroomName: string;
|
||||
teamId: string;
|
||||
folderStructure: {
|
||||
[key: string]: {
|
||||
name: string;
|
||||
path: string;
|
||||
files: {
|
||||
name: string;
|
||||
key: string;
|
||||
type?: string;
|
||||
numPages?: number;
|
||||
needsWatermark?: boolean;
|
||||
size?: number; // File size in bytes
|
||||
}[];
|
||||
};
|
||||
};
|
||||
fileKeys: string[];
|
||||
sourceBucket: string;
|
||||
watermarkConfig?: {
|
||||
enabled: boolean;
|
||||
config?: any;
|
||||
viewerData?: {
|
||||
email?: string | null;
|
||||
date?: string;
|
||||
time?: string;
|
||||
link?: string | null;
|
||||
ipAddress?: string;
|
||||
};
|
||||
};
|
||||
viewId?: string;
|
||||
viewerId?: string;
|
||||
viewerEmail?: string;
|
||||
linkId?: string;
|
||||
userId?: string;
|
||||
emailNotification?: boolean;
|
||||
emailAddress?: string;
|
||||
};
|
||||
|
||||
export const bulkDownloadTask = task({
|
||||
id: "bulk-download",
|
||||
retry: { maxAttempts: 2 },
|
||||
machine: { preset: "large-1x" }, // 4 vCPU, 8GB RAM for orchestration
|
||||
run: async (payload: BulkDownloadPayload) => {
|
||||
const {
|
||||
jobId,
|
||||
dataroomId,
|
||||
dataroomName,
|
||||
teamId,
|
||||
folderStructure,
|
||||
fileKeys,
|
||||
sourceBucket,
|
||||
watermarkConfig,
|
||||
viewId,
|
||||
viewerEmail,
|
||||
emailNotification,
|
||||
emailAddress,
|
||||
} = payload;
|
||||
|
||||
logger.info("Starting bulk download task", {
|
||||
jobId,
|
||||
dataroomId,
|
||||
dataroomName,
|
||||
totalFiles: fileKeys.length,
|
||||
});
|
||||
|
||||
// Generate timestamp once for all parts of this download
|
||||
const downloadTimestamp = generateTimestamp();
|
||||
|
||||
try {
|
||||
// Update job status to processing
|
||||
await downloadJobStore.updateJob(jobId, {
|
||||
status: "PROCESSING",
|
||||
processedFiles: 0,
|
||||
progress: 0,
|
||||
});
|
||||
|
||||
// For small datarooms, process in a single batch
|
||||
if (fileKeys.length <= MAX_FILES_PER_BATCH) {
|
||||
logger.info("Processing as single batch", {
|
||||
jobId,
|
||||
fileCount: fileKeys.length,
|
||||
});
|
||||
|
||||
const downloadUrl = await processDownloadBatch({
|
||||
teamId,
|
||||
folderStructure,
|
||||
fileKeys,
|
||||
sourceBucket,
|
||||
watermarkConfig,
|
||||
dataroomName,
|
||||
zipPartNumber: 1,
|
||||
totalParts: 1,
|
||||
zipFileName: generateZipFileName(dataroomName, downloadTimestamp),
|
||||
});
|
||||
|
||||
// Update job with completed status
|
||||
const completedJob = await downloadJobStore.updateJob(jobId, {
|
||||
status: "COMPLETED",
|
||||
processedFiles: fileKeys.length,
|
||||
progress: 100,
|
||||
downloadUrls: [downloadUrl],
|
||||
completedAt: new Date().toISOString(),
|
||||
expiresAt: new Date(
|
||||
Date.now() + 3 * 24 * 60 * 60 * 1000,
|
||||
).toISOString(), // 3 days
|
||||
});
|
||||
|
||||
// Send email notification if requested
|
||||
if (emailNotification && emailAddress && completedJob) {
|
||||
await sendEmailNotification({
|
||||
emailAddress,
|
||||
dataroomName,
|
||||
jobId,
|
||||
teamId,
|
||||
dataroomId,
|
||||
expiresAt: completedJob.expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
logger.info("Bulk download task completed successfully", {
|
||||
jobId,
|
||||
downloadUrls: [downloadUrl],
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
jobId,
|
||||
downloadUrls: [downloadUrl],
|
||||
};
|
||||
}
|
||||
|
||||
// For large datarooms, split into batches
|
||||
logger.info("Processing as multiple batches", {
|
||||
jobId,
|
||||
fileCount: fileKeys.length,
|
||||
maxFilesPerBatch: MAX_FILES_PER_BATCH,
|
||||
maxSizePerBatch: `${MAX_ZIP_SIZE_BYTES / (1024 * 1024)}MB`,
|
||||
});
|
||||
|
||||
// Split files into batches
|
||||
const batches = splitFilesIntoBatches(folderStructure, fileKeys);
|
||||
const totalBatches = batches.length;
|
||||
const downloadUrls: string[] = [];
|
||||
|
||||
logger.info("Created file batches", {
|
||||
jobId,
|
||||
totalBatches,
|
||||
batchDetails: batches.map((b, i) => ({
|
||||
batch: i + 1,
|
||||
files: b.fileKeys.length,
|
||||
sizeBytes: b.totalSize,
|
||||
sizeMB: Math.round(b.totalSize / (1024 * 1024)),
|
||||
})),
|
||||
});
|
||||
|
||||
// Process each batch sequentially (to avoid Lambda concurrency issues)
|
||||
for (let i = 0; i < batches.length; i++) {
|
||||
const batch = batches[i];
|
||||
const batchNumber = i + 1;
|
||||
|
||||
logger.info(`Processing batch ${batchNumber}/${totalBatches}`, {
|
||||
jobId,
|
||||
batchNumber,
|
||||
fileCount: batch.fileKeys.length,
|
||||
});
|
||||
|
||||
try {
|
||||
const downloadUrl = await processDownloadBatch({
|
||||
teamId,
|
||||
folderStructure: batch.folderStructure,
|
||||
fileKeys: batch.fileKeys,
|
||||
sourceBucket,
|
||||
watermarkConfig,
|
||||
dataroomName,
|
||||
zipPartNumber: batchNumber,
|
||||
totalParts: totalBatches,
|
||||
zipFileName: generateZipFileName(
|
||||
dataroomName,
|
||||
downloadTimestamp,
|
||||
batchNumber,
|
||||
),
|
||||
});
|
||||
|
||||
downloadUrls.push(downloadUrl);
|
||||
|
||||
// Calculate progress
|
||||
const processedFiles = batches
|
||||
.slice(0, batchNumber)
|
||||
.reduce((sum, b) => sum + b.fileKeys.length, 0);
|
||||
const progress = Math.round((batchNumber / totalBatches) * 100);
|
||||
|
||||
// Update job progress
|
||||
await downloadJobStore.updateJob(jobId, {
|
||||
processedFiles,
|
||||
progress,
|
||||
});
|
||||
|
||||
logger.info(`Batch ${batchNumber} completed`, {
|
||||
jobId,
|
||||
batchNumber,
|
||||
downloadUrl,
|
||||
progress,
|
||||
});
|
||||
} catch (batchError) {
|
||||
logger.error(`Batch ${batchNumber} failed`, {
|
||||
jobId,
|
||||
batchNumber,
|
||||
error:
|
||||
batchError instanceof Error
|
||||
? batchError.message
|
||||
: String(batchError),
|
||||
});
|
||||
throw batchError;
|
||||
}
|
||||
}
|
||||
|
||||
// Update job with completed status
|
||||
const completedJob = await downloadJobStore.updateJob(jobId, {
|
||||
status: "COMPLETED",
|
||||
processedFiles: fileKeys.length,
|
||||
progress: 100,
|
||||
downloadUrls,
|
||||
completedAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString(), // 3 days
|
||||
});
|
||||
|
||||
// Send email notification if requested
|
||||
if (emailNotification && emailAddress && completedJob) {
|
||||
await sendEmailNotification({
|
||||
emailAddress,
|
||||
dataroomName,
|
||||
jobId,
|
||||
teamId,
|
||||
dataroomId,
|
||||
expiresAt: completedJob.expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
logger.info("Bulk download task completed successfully", {
|
||||
jobId,
|
||||
totalBatches,
|
||||
downloadUrls,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
jobId,
|
||||
downloadUrls,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error("Bulk download task failed", {
|
||||
jobId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
|
||||
// Update job status to failed
|
||||
await downloadJobStore.updateJob(jobId, {
|
||||
status: "FAILED",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
interface ProcessDownloadBatchParams {
|
||||
teamId: string;
|
||||
folderStructure: BulkDownloadPayload["folderStructure"];
|
||||
fileKeys: string[];
|
||||
sourceBucket: string;
|
||||
watermarkConfig?: BulkDownloadPayload["watermarkConfig"];
|
||||
dataroomName: string;
|
||||
zipPartNumber: number;
|
||||
totalParts: number;
|
||||
zipFileName: string;
|
||||
expirationHours?: number;
|
||||
}
|
||||
|
||||
async function processDownloadBatch({
|
||||
teamId,
|
||||
folderStructure,
|
||||
fileKeys,
|
||||
sourceBucket,
|
||||
watermarkConfig,
|
||||
dataroomName,
|
||||
zipPartNumber,
|
||||
totalParts,
|
||||
zipFileName,
|
||||
expirationHours = 72,
|
||||
}: ProcessDownloadBatchParams): Promise<string> {
|
||||
const baseUrl = process.env.NEXTAUTH_URL || "https://app.papermark.com";
|
||||
const internalApiKey = process.env.INTERNAL_API_KEY;
|
||||
|
||||
if (!internalApiKey) {
|
||||
throw new Error("INTERNAL_API_KEY is not configured");
|
||||
}
|
||||
|
||||
const response = await fetch(`${baseUrl}/api/jobs/process-download-batch`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${internalApiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
teamId,
|
||||
sourceBucket,
|
||||
fileKeys,
|
||||
folderStructure,
|
||||
watermarkConfig: watermarkConfig || { enabled: false },
|
||||
zipPartNumber,
|
||||
totalParts,
|
||||
dataroomName,
|
||||
zipFileName,
|
||||
expirationHours,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(`API error: ${errorData.error || response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.downloadUrl;
|
||||
}
|
||||
|
||||
interface FileBatch {
|
||||
folderStructure: BulkDownloadPayload["folderStructure"];
|
||||
fileKeys: string[];
|
||||
totalSize: number;
|
||||
}
|
||||
|
||||
interface FileInfo {
|
||||
key: string;
|
||||
folderPath: string;
|
||||
size: number;
|
||||
file: BulkDownloadPayload["folderStructure"][string]["files"][number];
|
||||
}
|
||||
|
||||
function splitFilesIntoBatches(
|
||||
folderStructure: BulkDownloadPayload["folderStructure"],
|
||||
fileKeys: string[],
|
||||
): FileBatch[] {
|
||||
const batches: FileBatch[] = [];
|
||||
|
||||
// Build a list of files with their info
|
||||
const filesWithInfo: FileInfo[] = [];
|
||||
for (const [path, folder] of Object.entries(folderStructure)) {
|
||||
for (const file of folder.files) {
|
||||
if (file.key && fileKeys.includes(file.key)) {
|
||||
filesWithInfo.push({
|
||||
key: file.key,
|
||||
folderPath: path,
|
||||
size: file.size || 0, // Default to 0 if size unknown
|
||||
file,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we have size information for most files
|
||||
const filesWithSize = filesWithInfo.filter((f) => f.size > 0);
|
||||
const hasSizeInfo = filesWithSize.length > filesWithInfo.length * 0.5; // At least 50% have size
|
||||
|
||||
if (hasSizeInfo) {
|
||||
// Size-based batching
|
||||
let currentBatch: FileInfo[] = [];
|
||||
let currentBatchSize = 0;
|
||||
|
||||
for (const fileInfo of filesWithInfo) {
|
||||
const fileSize = fileInfo.size || 10 * 1024 * 1024; // Estimate 10MB for unknown sizes
|
||||
|
||||
// If adding this file would exceed limit, start a new batch
|
||||
// Also enforce max file count per batch to avoid Lambda payload limits
|
||||
if (
|
||||
currentBatch.length > 0 &&
|
||||
(currentBatchSize + fileSize > MAX_ZIP_SIZE_BYTES ||
|
||||
currentBatch.length >= MAX_FILES_PER_BATCH)
|
||||
) {
|
||||
batches.push(buildBatchFromFiles(currentBatch, folderStructure));
|
||||
currentBatch = [];
|
||||
currentBatchSize = 0;
|
||||
}
|
||||
|
||||
currentBatch.push(fileInfo);
|
||||
currentBatchSize += fileSize;
|
||||
}
|
||||
|
||||
// Don't forget the last batch
|
||||
if (currentBatch.length > 0) {
|
||||
batches.push(buildBatchFromFiles(currentBatch, folderStructure));
|
||||
}
|
||||
} else {
|
||||
// Fallback to count-based batching if no size info
|
||||
for (let i = 0; i < filesWithInfo.length; i += MAX_FILES_PER_BATCH) {
|
||||
const batchFiles = filesWithInfo.slice(i, i + MAX_FILES_PER_BATCH);
|
||||
batches.push(buildBatchFromFiles(batchFiles, folderStructure));
|
||||
}
|
||||
}
|
||||
|
||||
return batches;
|
||||
}
|
||||
|
||||
function buildBatchFromFiles(
|
||||
files: FileInfo[],
|
||||
folderStructure: BulkDownloadPayload["folderStructure"],
|
||||
): FileBatch {
|
||||
const batchFolderStructure: BulkDownloadPayload["folderStructure"] = {};
|
||||
const batchFileKeys: string[] = [];
|
||||
let totalSize = 0;
|
||||
|
||||
for (const fileInfo of files) {
|
||||
batchFileKeys.push(fileInfo.key);
|
||||
totalSize += fileInfo.size || 0;
|
||||
|
||||
// Initialize folder if not exists in batch
|
||||
if (!batchFolderStructure[fileInfo.folderPath]) {
|
||||
batchFolderStructure[fileInfo.folderPath] = {
|
||||
name: folderStructure[fileInfo.folderPath].name,
|
||||
path: folderStructure[fileInfo.folderPath].path,
|
||||
files: [],
|
||||
};
|
||||
}
|
||||
|
||||
batchFolderStructure[fileInfo.folderPath].files.push(fileInfo.file);
|
||||
}
|
||||
|
||||
// Ensure all parent folders are included
|
||||
for (const path of Object.keys(batchFolderStructure)) {
|
||||
const pathParts = path.split("/").filter(Boolean);
|
||||
let currentPath = "";
|
||||
|
||||
for (const part of pathParts) {
|
||||
currentPath += "/" + part;
|
||||
if (!batchFolderStructure[currentPath] && folderStructure[currentPath]) {
|
||||
batchFolderStructure[currentPath] = {
|
||||
name: folderStructure[currentPath].name,
|
||||
path: folderStructure[currentPath].path,
|
||||
files: [], // Empty files array for intermediate folders
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
folderStructure: batchFolderStructure,
|
||||
fileKeys: batchFileKeys,
|
||||
totalSize,
|
||||
};
|
||||
}
|
||||
|
||||
async function sendEmailNotification({
|
||||
emailAddress,
|
||||
dataroomName,
|
||||
jobId,
|
||||
teamId,
|
||||
dataroomId,
|
||||
expiresAt,
|
||||
}: {
|
||||
emailAddress: string;
|
||||
dataroomName: string;
|
||||
jobId: string;
|
||||
teamId: string;
|
||||
dataroomId: string;
|
||||
expiresAt?: string;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
// Link to the dataroom documents page where user can see and download their files
|
||||
const baseUrl = process.env.NEXTAUTH_URL || "https://app.papermark.com";
|
||||
const downloadUrl = `${baseUrl}/datarooms/${dataroomId}/documents`;
|
||||
|
||||
await sendDownloadReadyEmail({
|
||||
to: emailAddress,
|
||||
dataroomName,
|
||||
downloadUrl,
|
||||
expiresAt,
|
||||
});
|
||||
logger.info("Download ready email sent", {
|
||||
jobId,
|
||||
emailAddress,
|
||||
downloadUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error("Failed to send download ready email", {
|
||||
jobId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,10 @@ export const convertPdfToImageRoute = task({
|
||||
if (!documentVersion) {
|
||||
logger.error("File not found", { payload });
|
||||
updateStatus({ progress: 0, text: "Document not found" });
|
||||
return;
|
||||
return {
|
||||
success: false,
|
||||
message: "Document version not found",
|
||||
};
|
||||
}
|
||||
|
||||
logger.info("Document version", { documentVersion });
|
||||
@@ -51,7 +54,10 @@ export const convertPdfToImageRoute = task({
|
||||
if (!signedUrl) {
|
||||
logger.error("Failed to get signed url", { payload });
|
||||
updateStatus({ progress: 0, text: "Failed to retrieve document" });
|
||||
return;
|
||||
return {
|
||||
success: false,
|
||||
message: "Failed to get signed URL for document",
|
||||
};
|
||||
}
|
||||
|
||||
let numPages = documentVersion.numPages;
|
||||
@@ -61,39 +67,67 @@ export const convertPdfToImageRoute = task({
|
||||
// 3. send file to api/convert endpoint in a task and get back number of pages
|
||||
logger.info("Sending file to api/get-pages endpoint");
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_BASE_URL}/api/mupdf/get-pages`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ url: signedUrl }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_BASE_URL}/api/mupdf/get-pages`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ url: signedUrl }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error("Failed to get number of pages", {
|
||||
signedUrl,
|
||||
response,
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
logger.error("Failed to get number of pages", {
|
||||
signedUrl,
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
payload,
|
||||
});
|
||||
updateStatus({ progress: 0, text: "Failed to get number of pages" });
|
||||
return {
|
||||
success: false,
|
||||
message: "Failed to get number of pages",
|
||||
};
|
||||
}
|
||||
|
||||
const { numPages: numPagesResult } = (await response.json()) as {
|
||||
numPages: number;
|
||||
};
|
||||
|
||||
logger.info("Received number of pages", { numPagesResult });
|
||||
|
||||
if (numPagesResult < 1) {
|
||||
logger.error("Failed to get number of pages", { payload });
|
||||
updateStatus({ progress: 0, text: "Failed to get number of pages" });
|
||||
return {
|
||||
success: false,
|
||||
message: "Failed to get number of pages - invalid page count",
|
||||
};
|
||||
}
|
||||
|
||||
numPages = numPagesResult;
|
||||
} catch (error: unknown) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
const errorCause =
|
||||
error instanceof Error && error.cause ? error.cause : undefined;
|
||||
|
||||
logger.error("Failed to fetch page count", {
|
||||
error: errorMessage,
|
||||
cause: errorCause,
|
||||
payload,
|
||||
});
|
||||
throw new Error("Failed to get number of pages");
|
||||
updateStatus({ progress: 0, text: "Failed to retrieve page count" });
|
||||
return {
|
||||
success: false,
|
||||
message: `Failed to fetch page count: ${errorMessage}`,
|
||||
};
|
||||
}
|
||||
|
||||
const { numPages: numPagesResult } = (await response.json()) as {
|
||||
numPages: number;
|
||||
};
|
||||
|
||||
logger.info("Received number of pages", { numPagesResult });
|
||||
|
||||
if (numPagesResult < 1) {
|
||||
logger.error("Failed to get number of pages", { payload });
|
||||
updateStatus({ progress: 0, text: "Failed to get number of pages" });
|
||||
return;
|
||||
}
|
||||
|
||||
numPages = numPagesResult;
|
||||
}
|
||||
|
||||
updateStatus({ progress: 20, text: "Converting document..." });
|
||||
@@ -165,11 +199,17 @@ export const convertPdfToImageRoute = task({
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
conversionWithoutError = false;
|
||||
if (error instanceof Error) {
|
||||
logger.error("Failed to convert page", {
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
const errorCause =
|
||||
error instanceof Error && error.cause ? error.cause : undefined;
|
||||
|
||||
logger.error("Failed to convert page", {
|
||||
pageNumber: currentPage,
|
||||
error: errorMessage,
|
||||
cause: errorCause,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
updateStatus({
|
||||
@@ -184,7 +224,12 @@ export const convertPdfToImageRoute = task({
|
||||
progress: (currentPage / numPages) * 100,
|
||||
text: `Error processing page ${currentPage} of ${numPages}`,
|
||||
});
|
||||
return;
|
||||
return {
|
||||
success: false,
|
||||
message: `Failed to process page ${currentPage} of ${numPages}`,
|
||||
totalPages: numPages,
|
||||
failedAtPage: currentPage,
|
||||
};
|
||||
}
|
||||
|
||||
// 5. after all pages are uploaded, update document version to hasPages = true
|
||||
|
||||
@@ -9,7 +9,12 @@ export interface DocumentPreviewData {
|
||||
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 };
|
||||
}[];
|
||||
file?: string;
|
||||
|
||||
+47
-36
@@ -85,6 +85,30 @@ export const logStore = async ({ object }: { object: any }) => {
|
||||
}
|
||||
};
|
||||
|
||||
const LOG_TIMEOUT_MS = 2500;
|
||||
|
||||
const postJsonWithTimeout = async (
|
||||
url: string,
|
||||
body: unknown,
|
||||
timeoutMs: number,
|
||||
) => {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
||||
timeoutId.unref?.();
|
||||
try {
|
||||
return await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
|
||||
export const log = async ({
|
||||
message,
|
||||
type,
|
||||
@@ -105,45 +129,32 @@ export const log = async ({
|
||||
|
||||
/* Log a message to channel */
|
||||
try {
|
||||
if (type === "trial" && process.env.PPMK_TRIAL_SLACK_WEBHOOK_URL) {
|
||||
return await fetch(`${process.env.PPMK_TRIAL_SLACK_WEBHOOK_URL}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
const payload = {
|
||||
blocks: [
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
// prettier-ignore
|
||||
text: `${mention ? "<@U05BTDUKPLZ> " : ""}${type === "error" ? ":rotating_light: " : ""}${message}`,
|
||||
},
|
||||
},
|
||||
body: JSON.stringify({
|
||||
blocks: [
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
// prettier-ignore
|
||||
text: `${mention ? "<@U05BTDUKPLZ> " : ""}${message}`,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
],
|
||||
};
|
||||
|
||||
if (type === "trial" && process.env.PPMK_TRIAL_SLACK_WEBHOOK_URL) {
|
||||
return await postJsonWithTimeout(
|
||||
process.env.PPMK_TRIAL_SLACK_WEBHOOK_URL,
|
||||
payload,
|
||||
LOG_TIMEOUT_MS,
|
||||
);
|
||||
}
|
||||
|
||||
return await fetch(`${process.env.PPMK_SLACK_WEBHOOK_URL}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
blocks: [
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
// prettier-ignore
|
||||
text: `${mention ? "<@U05BTDUKPLZ> " : ""}${type === "error" ? ":rotating_light: " : ""}${message}`,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
return await postJsonWithTimeout(
|
||||
`${process.env.PPMK_SLACK_WEBHOOK_URL}`,
|
||||
payload,
|
||||
LOG_TIMEOUT_MS,
|
||||
);
|
||||
} catch (e) {}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,40 +1,17 @@
|
||||
import { pdfjs } from "react-pdf";
|
||||
import { PDF, SecurityError } from "@libpdf/core";
|
||||
import * as XLSX from "xlsx";
|
||||
|
||||
// Default to CDN worker URL
|
||||
const cdnWorkerUrl = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = cdnWorkerUrl;
|
||||
|
||||
export const getPagesCount = async (arrayBuffer: ArrayBuffer) => {
|
||||
try {
|
||||
// Only in browser context
|
||||
if (typeof window !== "undefined") {
|
||||
try {
|
||||
// First attempt with the current worker configuration
|
||||
const pdf = await pdfjs.getDocument({ data: arrayBuffer }).promise;
|
||||
return pdf.numPages;
|
||||
} catch (workerError) {
|
||||
console.warn("PDF worker error, trying fallback:", workerError);
|
||||
|
||||
// Fall back to local worker
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = `/pdf.worker.min.js`;
|
||||
|
||||
try {
|
||||
// Try again with local worker
|
||||
const pdf = await pdfjs.getDocument({ data: arrayBuffer }).promise;
|
||||
return pdf.numPages;
|
||||
} catch (fallbackError) {
|
||||
console.warn("Both CDN and local worker failed:", fallbackError);
|
||||
return 1; // Default to 1 page if both attempts fail
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Server-side rendering case
|
||||
const pdf = await pdfjs.getDocument(arrayBuffer).promise;
|
||||
return pdf.numPages;
|
||||
}
|
||||
const bytes = new Uint8Array(arrayBuffer);
|
||||
const pdf = await PDF.load(bytes);
|
||||
return pdf.getPageCount();
|
||||
} catch (error) {
|
||||
console.error("Error getting PDF page count:", error);
|
||||
if (error instanceof SecurityError) {
|
||||
console.warn("PDF is password-protected, cannot determine page count");
|
||||
} else {
|
||||
console.error("Error getting PDF page count:", error);
|
||||
}
|
||||
return 1; // Assuming at least one page if we can't determine
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { render } from "@react-email/components";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
import YearInReviewEmail from "@/components/emails/year-in-review-papermark";
|
||||
|
||||
import prisma from "@/lib/prisma";
|
||||
import { resend } from "@/lib/resend";
|
||||
import { log } from "@/lib/utils";
|
||||
import { generateUnsubscribeUrl } from "@/lib/utils/unsubscribe";
|
||||
|
||||
import YearInReviewEmail from "@/components/emails/year-in-review-papermark";
|
||||
|
||||
const BATCH_SIZE = 100; // Maximum number of emails Resend supports in one batch
|
||||
const MAX_ATTEMPTS = 3;
|
||||
const RATE_LIMIT_DELAY = 10000; // 10 seconds
|
||||
@@ -145,7 +145,7 @@ export async function processEmailQueue() {
|
||||
|
||||
return {
|
||||
email: {
|
||||
from: "Papermark <system@papermark.io>",
|
||||
from: "Papermark <system@papermark.com>",
|
||||
to: userTeam.user.email || "delivered@resend.dev",
|
||||
subject: "2024 in Review: Your Year with Papermark",
|
||||
react,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user