18 Commits

Author SHA1 Message Date
Bas
be24beeaa5 Merge pull request #16 from xtr-dev/dev
v0.0.20: Remove debug logging, clean up custom ListView
2025-10-03 21:18:02 +02:00
05952e3e72 v0.0.20: Remove debug logging, clean up custom ListView
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 21:16:19 +02:00
Bas
e6f56535ca Merge pull request #15 from xtr-dev/dev
Dev
2025-10-03 20:58:55 +02:00
eefe9bdaf3 v0.0.19: Add debug logging 2025-10-03 20:10:10 +02:00
49c10c7091 Add debug logging to diagnose ListView props
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 20:10:10 +02:00
Bas
fe3da4fe52 Merge pull request #14 from xtr-dev/dev
Dev
2025-10-03 20:06:39 +02:00
e82bf9c6d4 v0.0.18: Fix enableCustomListView to use proper ListView pattern 2025-10-03 20:04:38 +02:00
460d627d92 Update custom list view to use proper Payload ListView pattern
- Changed from AdminViewServerProps to ListViewServerProps
- Updated component to use collectionConfig instead of collection
- Simplified view structure to work directly with Payload's List View
- Added ListViewClientProps import to client component

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 20:04:26 +02:00
Bas
14a5acd222 Merge pull request #13 from xtr-dev/dev
Dev
2025-10-03 19:57:05 +02:00
d3b8a8446e . 2025-10-03 19:56:55 +02:00
7dc17bc80a v0.0.17: Add enableCustomListView option 2025-10-03 19:53:01 +02:00
b642b653d0 Add enableCustomListView option
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 19:52:57 +02:00
Bas
1db434e701 Merge pull request #12 from xtr-dev/dev
Dev
2025-10-03 19:20:09 +02:00
7fd6194712 v0.0.16: Rebuild to sync dist with source 2025-10-03 19:19:41 +02:00
259599ddcc v0.0.15: Fix SSR warning in client components
Removes misleading warning that appeared during Next.js SSR:
- Client components are initially rendered on server where window is undefined
- This is expected behavior and doesn't require a warning
- Now silently falls back to relative URLs during SSR
- Properly uses window.location.origin once hydrated on client

The hooks now work seamlessly in:
- Pure client-side apps
- Next.js with SSR/SSG
- Server components (with explicit serverURL)
- Client components (auto-detects after hydration)

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 18:48:46 +02:00
Bas
7f54d9a79f Merge pull request #11 from xtr-dev/dev
Fix: Client hooks webpack error - remove @payloadcms/ui dependency
2025-10-03 18:35:32 +02:00
9bb5f4ecc8 v0.0.14: Improve SSR support and fix race condition
Addresses critical issues identified in code review:

1. Server-Side Environment Handling:
   - Add warning when serverURL is not provided in SSR/SSG environments
   - Falls back to relative URLs with console warning
   - Prevents silent failures in server-side rendering

2. Race Condition Fix:
   - Use useRef for initialFlags to prevent re-creating fetchFlags on every render
   - Removes initialFlags from useCallback dependencies
   - Prevents excessive re-renders and potential infinite loops

These improvements ensure better stability and reliability in both
client-side and server-side environments.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 18:30:58 +02:00
4f802c8cc9 v0.0.13: Remove useConfig dependency from client hooks
Makes client hooks work outside of Payload Admin UI context by:
- Adding FeatureFlagOptions parameter to all hooks for configuration
- Using window.location.origin as default serverURL when in browser
- Removing @payloadcms/ui dependency from client hooks
- Allowing custom serverURL, apiPath, and collectionSlug configuration

This fixes the webpack error "_payloadcms_ui__WEBPACK_IMPORTED_MODULE_1__.b() is undefined"
when using the hooks in frontend applications.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 18:25:32 +02:00
7 changed files with 161 additions and 145 deletions

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "payload-feature-flags",
"version": "1.0.0",
"version": "0.0.19",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "payload-feature-flags",
"version": "1.0.0",
"version": "0.0.19",
"license": "MIT",
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@xtr-dev/payload-feature-flags",
"version": "0.0.12",
"version": "0.0.20",
"description": "Feature flags plugin for Payload CMS - manage feature toggles, A/B tests, and gradual rollouts",
"license": "MIT",
"type": "module",

View File

@@ -7,4 +7,5 @@ export {
useRolloutCheck,
withFeatureFlag,
type FeatureFlag,
type FeatureFlagOptions,
} from '../hooks/client.js'

View File

@@ -1,6 +1,5 @@
'use client'
import React, { useCallback, useEffect, useState } from 'react'
import { useConfig } from '@payloadcms/ui'
import React, { useCallback, useEffect, useState, useRef } from 'react'
export interface FeatureFlag {
name: string
@@ -14,34 +13,78 @@ export interface FeatureFlag {
metadata?: any
}
export interface FeatureFlagOptions {
serverURL?: string
apiPath?: string
collectionSlug?: string
}
// Helper to get config from options or defaults
function getConfig(options?: FeatureFlagOptions) {
// Check if serverURL is explicitly provided
if (options?.serverURL) {
return {
serverURL: options.serverURL,
apiPath: options.apiPath || '/api',
collectionSlug: options.collectionSlug || 'feature-flags'
}
}
// In browser environment, use window.location.origin
if (typeof window !== 'undefined') {
return {
serverURL: window.location.origin,
apiPath: options?.apiPath || '/api',
collectionSlug: options?.collectionSlug || 'feature-flags'
}
}
// During SSR or in non-browser environments, use relative URL
// This will work for same-origin requests
return {
serverURL: '',
apiPath: options?.apiPath || '/api',
collectionSlug: options?.collectionSlug || 'feature-flags'
}
}
/**
* Hook to fetch all active feature flags from the API
*/
export function useFeatureFlags(
initialFlags: Partial<FeatureFlag>[]
initialFlags: Partial<FeatureFlag>[],
options?: FeatureFlagOptions
): {
flags: Partial<FeatureFlag>[]
loading: boolean
error: string | null
refetch: () => Promise<void>
} {
const { config } = useConfig()
const { serverURL, apiPath, collectionSlug } = getConfig(options)
const [flags, setFlags] = useState<Partial<FeatureFlag>[]>(initialFlags)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
// Use ref to store initialFlags to avoid re-creating fetchFlags on every render
const initialFlagsRef = useRef(initialFlags)
// Update ref when initialFlags changes (but won't trigger re-fetch)
useEffect(() => {
initialFlagsRef.current = initialFlags
}, [initialFlags])
const fetchFlags = useCallback(async () => {
try {
setLoading(true)
setError(null)
// Use Payload's native collection API
const names = initialFlags.map(f => f.name).filter(Boolean)
const names = initialFlagsRef.current.map(f => f.name).filter(Boolean)
const query = names.length > 0
? `?where[name][in]=${names.join(',')}&limit=1000`
: '?limit=1000'
const response = await fetch(`${config.serverURL}${config.routes.api}/feature-flags${query}`)
const response = await fetch(`${serverURL}${apiPath}/${collectionSlug}${query}`)
if (!response.ok) {
throw new Error(`Failed to fetch feature flags: ${response.statusText}`)
@@ -64,7 +107,7 @@ export function useFeatureFlags(
}
// Sort flags based on the order of names in initialFlags
const sortedFlags = initialFlags.map(initialFlag => {
const sortedFlags = initialFlagsRef.current.map(initialFlag => {
const fetchedFlag = fetchedFlagsMap.get(initialFlag.name!)
// Use fetched flag if available, otherwise keep the initial flag
return fetchedFlag || initialFlag
@@ -77,7 +120,7 @@ export function useFeatureFlags(
} finally {
setLoading(false)
}
}, [config.serverURL, config.routes.api, initialFlags])
}, [serverURL, apiPath, collectionSlug]) // Remove initialFlags from dependencies
useEffect(() => {
void fetchFlags()
@@ -89,13 +132,16 @@ export function useFeatureFlags(
/**
* Hook to check if a specific feature flag is enabled
*/
export function useFeatureFlag(flagName: string): {
export function useFeatureFlag(
flagName: string,
options?: FeatureFlagOptions
): {
isEnabled: boolean
flag: Partial<FeatureFlag> | null
loading: boolean
error: string | null
} {
const { flags, loading, error } = useFeatureFlags([{ name: flagName }])
const { flags, loading, error } = useFeatureFlags([{ name: flagName }], options)
const flag = flags.find(f => f.name === flagName) || null
const isEnabled = flag?.enabled || false
@@ -106,13 +152,16 @@ export function useFeatureFlag(flagName: string): {
/**
* Hook to fetch a specific feature flag from the API
*/
export function useSpecificFeatureFlag(flagName: string): {
export function useSpecificFeatureFlag(
flagName: string,
options?: FeatureFlagOptions
): {
flag: FeatureFlag | null
loading: boolean
error: string | null
refetch: () => Promise<void>
} {
const { config } = useConfig()
const { serverURL, apiPath, collectionSlug } = getConfig(options)
const [flag, setFlag] = useState<FeatureFlag | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@@ -124,7 +173,7 @@ export function useSpecificFeatureFlag(flagName: string): {
// Use Payload's native collection API with query filter
const response = await fetch(
`${config.serverURL}${config.routes.api}/feature-flags?where[name][equals]=${flagName}&limit=1`
`${serverURL}${apiPath}/${collectionSlug}?where[name][equals]=${flagName}&limit=1`
)
if (!response.ok) {
@@ -153,7 +202,7 @@ export function useSpecificFeatureFlag(flagName: string): {
} finally {
setLoading(false)
}
}, [config.serverURL, config.routes.api, flagName])
}, [serverURL, apiPath, collectionSlug, flagName])
useEffect(() => {
void fetchFlag()
@@ -167,14 +216,15 @@ export function useSpecificFeatureFlag(flagName: string): {
*/
export function useVariantSelection(
flagName: string,
userId: string
userId: string,
options?: FeatureFlagOptions
): {
variant: string | null
flag: FeatureFlag | null
loading: boolean
error: string | null
} {
const { flag, loading, error } = useSpecificFeatureFlag(flagName)
const { flag, loading, error } = useSpecificFeatureFlag(flagName, options)
const variant = flag?.enabled && flag.variants
? selectVariantForUser(userId, flag.variants)
@@ -188,14 +238,15 @@ export function useVariantSelection(
*/
export function useRolloutCheck(
flagName: string,
userId: string
userId: string,
options?: FeatureFlagOptions
): {
isInRollout: boolean
flag: FeatureFlag | null
loading: boolean
error: string | null
} {
const { flag, loading, error } = useSpecificFeatureFlag(flagName)
const { flag, loading, error } = useSpecificFeatureFlag(flagName, options)
const isInRollout = flag?.enabled
? checkUserInRollout(userId, flag.rolloutPercentage || 100)
@@ -253,13 +304,14 @@ function checkUserInRollout(userId: string, percentage: number): boolean {
*/
export function withFeatureFlag<P extends Record<string, any>>(
flagName: string,
FallbackComponent?: React.ComponentType<P>
FallbackComponent?: React.ComponentType<P>,
options?: FeatureFlagOptions
) {
return function FeatureFlagWrapper(
WrappedComponent: React.ComponentType<P>
): React.ComponentType<P> {
return function WithFeatureFlagComponent(props: P): React.ReactElement | null {
const { isEnabled, loading } = useFeatureFlag(flagName)
const { isEnabled, loading } = useFeatureFlag(flagName, options)
if (loading) {
return null // or a loading spinner

View File

@@ -34,6 +34,11 @@ export type PayloadFeatureFlagsConfig = {
* Override collection configuration
*/
collectionOverrides?: CollectionOverrides
/**
* Enable custom list view for feature flags
* @default false
*/
enableCustomListView?: boolean
}
export const payloadFeatureFlags =
@@ -44,6 +49,7 @@ export const payloadFeatureFlags =
defaultValue = false,
enableRollouts = true,
enableVariants = true,
enableCustomListView = false,
collectionOverrides,
} = pluginOptions
@@ -163,6 +169,15 @@ export const payloadFeatureFlags =
useAsTitle: 'name',
group: 'Configuration',
description: 'Manage feature flags for your application',
components: enableCustomListView ? {
...collectionOverrides?.admin?.components,
views: {
...collectionOverrides?.admin?.components?.views,
list: {
Component: '@xtr-dev/payload-feature-flags/views#FeatureFlagsView'
}
}
} : collectionOverrides?.admin?.components || {},
...(collectionOverrides?.admin || {}),
},
fields,

View File

@@ -1,4 +1,6 @@
'use client'
import React from 'react'
import type { ListViewClientProps } from 'payload'
import { useState, useEffect, useCallback, useMemo, memo } from 'react'
import {
useConfig,
@@ -236,7 +238,7 @@ const FeatureFlagsClientComponent = ({
color: styles.text,
margin: '0 0 0.5rem 0'
}}>
Feature Flags Dashboard
Feature Flags
</h1>
<p style={{
color: styles.textMuted,
@@ -664,4 +666,4 @@ const FeatureFlagsClientComponent = ({
}
export const FeatureFlagsClient = memo(FeatureFlagsClientComponent)
export default FeatureFlagsClient
export default FeatureFlagsClient

View File

@@ -1,19 +1,13 @@
import type { AdminViewServerProps } from 'payload'
import { DefaultTemplate } from '@payloadcms/next/templates'
import { Gutter } from '@payloadcms/ui'
import React from 'react'
import type { ListViewServerProps } from 'payload'
import FeatureFlagsClient from './FeatureFlagsClient.js'
import type { FeatureFlag } from '../types/index.js'
async function fetchInitialFlags(payload: any, searchParams?: Record<string, any>): Promise<FeatureFlag[]> {
async function fetchInitialFlags(payload: any, collectionSlug: string): Promise<FeatureFlag[]> {
try {
const limit = Math.min(1000, parseInt(searchParams?.limit as string) || 100)
const page = Math.max(1, parseInt(searchParams?.page as string) || 1)
const collectionSlug = searchParams?.collectionSlug as string || 'feature-flags'
const result = await payload.find({
collection: collectionSlug,
limit,
page,
limit: 1000,
sort: 'name',
})
@@ -24,131 +18,83 @@ async function fetchInitialFlags(payload: any, searchParams?: Record<string, any
}
}
export default async function FeatureFlagsView({
initPageResult,
params,
searchParams,
}: AdminViewServerProps) {
const {
req: { user },
permissions,
} = initPageResult
export default async function FeatureFlagsView(props: ListViewServerProps) {
const { collectionConfig, user, permissions, payload } = props
// Security check: User must be logged in
if (!user) {
return (
<DefaultTemplate
i18n={initPageResult.req.i18n}
locale={initPageResult.locale}
params={params}
payload={initPageResult.req.payload}
permissions={initPageResult.permissions}
searchParams={searchParams}
user={undefined}
visibleEntities={initPageResult.visibleEntities}
>
<Gutter>
<div style={{
padding: '2rem',
textAlign: 'center',
color: 'var(--theme-error-500)',
backgroundColor: 'var(--theme-error-50)',
border: '1px solid var(--theme-error-200)',
borderRadius: '0.5rem',
margin: '2rem 0'
}}>
<h2 style={{ marginBottom: '1rem', color: 'var(--theme-error-600)' }}>
Authentication Required
</h2>
<p style={{ marginBottom: '1rem' }}>
You must be logged in to view the Feature Flags Dashboard.
</p>
<a
href="/admin/login"
style={{
display: 'inline-block',
padding: '0.75rem 1.5rem',
backgroundColor: 'var(--theme-error-500)',
color: 'white',
textDecoration: 'none',
borderRadius: '0.375rem',
fontWeight: '500'
}}
>
Go to Login
</a>
</div>
</Gutter>
</DefaultTemplate>
<div style={{
padding: '2rem',
textAlign: 'center',
color: 'var(--theme-error-500)',
backgroundColor: 'var(--theme-error-50)',
border: '1px solid var(--theme-error-200)',
borderRadius: '0.5rem',
margin: '2rem 0'
}}>
<h2 style={{ marginBottom: '1rem', color: 'var(--theme-error-600)' }}>
Authentication Required
</h2>
<p style={{ marginBottom: '1rem' }}>
You must be logged in to view the Feature Flags Dashboard.
</p>
<a
href="/admin/login"
style={{
display: 'inline-block',
padding: '0.75rem 1.5rem',
backgroundColor: 'var(--theme-error-500)',
color: 'white',
textDecoration: 'none',
borderRadius: '0.375rem',
fontWeight: '500'
}}
>
Go to Login
</a>
</div>
)
}
// Security check: User must have permissions to access feature-flags collection
const collectionSlug = searchParams?.collectionSlug as string || 'feature-flags'
const canReadFeatureFlags = permissions?.collections?.[collectionSlug]?.read
// Security check: User must have permissions to access the collection
const canReadFeatureFlags = permissions?.collections?.[collectionConfig.slug]?.read
if (!canReadFeatureFlags) {
return (
<DefaultTemplate
i18n={initPageResult.req.i18n}
locale={initPageResult.locale}
params={params}
payload={initPageResult.req.payload}
permissions={initPageResult.permissions}
searchParams={searchParams}
user={initPageResult.req.user || undefined}
visibleEntities={initPageResult.visibleEntities}
>
<Gutter>
<div style={{
padding: '2rem',
textAlign: 'center',
color: 'var(--theme-warning-600)',
backgroundColor: 'var(--theme-warning-50)',
border: '1px solid var(--theme-warning-200)',
borderRadius: '0.5rem',
margin: '2rem 0'
}}>
<h2 style={{ marginBottom: '1rem', color: 'var(--theme-warning-700)' }}>
Access Denied
</h2>
<p style={{ marginBottom: '1rem' }}>
You don't have permission to access the Feature Flags Dashboard.
</p>
<p style={{ fontSize: '0.875rem', color: 'var(--theme-warning-600)' }}>
Contact your administrator to request access to the feature-flags collection.
</p>
</div>
</Gutter>
</DefaultTemplate>
<div style={{
padding: '2rem',
textAlign: 'center',
color: 'var(--theme-warning-600)',
backgroundColor: 'var(--theme-warning-50)',
border: '1px solid var(--theme-warning-200)',
borderRadius: '0.5rem',
margin: '2rem 0'
}}>
<h2 style={{ marginBottom: '1rem', color: 'var(--theme-warning-700)' }}>
Access Denied
</h2>
<p style={{ marginBottom: '1rem' }}>
You don't have permission to access the Feature Flags Dashboard.
</p>
<p style={{ fontSize: '0.875rem', color: 'var(--theme-warning-600)' }}>
Contact your administrator to request access to the {collectionConfig.slug} collection.
</p>
</div>
)
}
// Fetch initial data server-side (only if user has access)
const initialFlags = await fetchInitialFlags(initPageResult.req.payload, searchParams)
const initialFlags = await fetchInitialFlags(payload, collectionConfig.slug)
// Check if user can update feature flags (use already defined collection slug)
const canUpdateFeatureFlags = permissions?.collections?.[collectionSlug]?.update || false
// Check if user can update feature flags
const canUpdateFeatureFlags = permissions?.collections?.[collectionConfig.slug]?.update || false
// Use DefaultTemplate with proper props structure from initPageResult
return (
<DefaultTemplate
i18n={initPageResult.req.i18n}
locale={initPageResult.locale}
params={params}
payload={initPageResult.req.payload}
permissions={initPageResult.permissions}
searchParams={searchParams}
user={initPageResult.req.user || undefined}
visibleEntities={initPageResult.visibleEntities}
>
<Gutter>
<FeatureFlagsClient
initialFlags={initialFlags}
canUpdate={canUpdateFeatureFlags}
maxFlags={parseInt(searchParams?.maxFlags as string) || 100}
collectionSlug={collectionSlug}
/>
</Gutter>
</DefaultTemplate>
<FeatureFlagsClient
initialFlags={initialFlags}
canUpdate={canUpdateFeatureFlags}
maxFlags={100}
collectionSlug={collectionConfig.slug}
/>
)
}