📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
feat: Feature flags
Blue Mouseb3bd3ff93de0
diff --git a/backend/apps/cloud/src/app.module.ts b/backend/apps/cloud/src/app.module.tsindex e3944eefc..d552d3af7 100644--- a/backend/apps/cloud/src/app.module.ts+++ b/backend/apps/cloud/src/app.module.ts@@ -21,6 +21,7 @@ import { PingModule } from './ping/ping.module'import { MarketplaceModule } from './marketplace/marketplace.module'import { AlertModule } from './alert/alert.module'import { GoalModule } from './goal/goal.module'+import { FeatureFlagModule } from './feature-flag/feature-flag.module'import { AiModule } from './ai/ai.module'import { getI18nConfig } from './configs'import { AuthModule } from './auth/auth.module'@@ -80,6 +81,7 @@ const modules = [MarketplaceModule,AlertModule,GoalModule,+ FeatureFlagModule,AiModule,AuthModule,CaptchaModule,diff --git a/backend/apps/cloud/src/feature-flag/dto/feature-flag.dto.ts b/backend/apps/cloud/src/feature-flag/dto/feature-flag.dto.tsnew file mode 100644index 000000000..d9695926b--- /dev/null+++ b/backend/apps/cloud/src/feature-flag/dto/feature-flag.dto.ts@@ -0,0 +1,224 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'+import {+ IsString,+ IsOptional,+ IsEnum,+ IsNumber,+ IsBoolean,+ IsArray,+ ValidateNested,+ Min,+ Max,+ MaxLength,+ Matches,+} from 'class-validator'+import { Type } from 'class-transformer'+import { FeatureFlagType, TargetingRule } from '../entity/feature-flag.entity'++export class TargetingRuleDto implements TargetingRule {+ @ApiProperty({+ description: 'Column/attribute to filter on (cc, dv, br, os, pg, etc.)',+ })+ @IsString()+ column: string++ @ApiProperty({ description: 'Value to match against' })+ @IsString()+ filter: string++ @ApiProperty({+ description: 'If true, excludes matches; if false, includes matches',+ })+ @IsBoolean()+ isExclusive: boolean+}++export class CreateFeatureFlagDto {+ @ApiProperty({ description: 'Project ID the flag belongs to' })+ @IsString()+ pid: string++ @ApiProperty({+ description: 'Unique key for the feature flag (kebab-case recommended)',+ })+ @IsString()+ @MaxLength(100)+ @Matches(/^[a-zA-Z0-9_-]+$/, {+ message:+ 'Key must contain only alphanumeric characters, underscores, and hyphens',+ })+ key: string++ @ApiPropertyOptional({+ description: 'Optional description of what this flag controls',+ })+ @IsOptional()+ @IsString()+ @MaxLength(500)+ description?: string++ @ApiPropertyOptional({+ enum: FeatureFlagType,+ description: 'Type of feature flag',+ default: FeatureFlagType.BOOLEAN,+ })+ @IsOptional()+ @IsEnum(FeatureFlagType)+ flagType?: FeatureFlagType++ @ApiPropertyOptional({+ description:+ 'Percentage of users to enable for (0-100), used when flagType is rollout',+ default: 100,+ })+ @IsOptional()+ @IsNumber()+ @Min(0)+ @Max(100)+ rolloutPercentage?: number++ @ApiPropertyOptional({+ type: [TargetingRuleDto],+ description:+ 'Array of targeting rules to filter which visitors see this flag',+ })+ @IsOptional()+ @IsArray()+ @ValidateNested({ each: true })+ @Type(() => TargetingRuleDto)+ targetingRules?: TargetingRuleDto[]++ @ApiPropertyOptional({+ description: 'Whether the flag is enabled',+ default: true,+ })+ @IsOptional()+ @IsBoolean()+ enabled?: boolean+}++export class UpdateFeatureFlagDto {+ @ApiPropertyOptional({ description: 'Unique key for the feature flag' })+ @IsOptional()+ @IsString()+ @MaxLength(100)+ @Matches(/^[a-zA-Z0-9_-]+$/, {+ message:+ 'Key must contain only alphanumeric characters, underscores, and hyphens',+ })+ key?: string++ @ApiPropertyOptional({+ description: 'Description of what this flag controls',+ })+ @IsOptional()+ @IsString()+ @MaxLength(500)+ description?: string | null++ @ApiPropertyOptional({+ enum: FeatureFlagType,+ description: 'Type of feature flag',+ })+ @IsOptional()+ @IsEnum(FeatureFlagType)+ flagType?: FeatureFlagType++ @ApiPropertyOptional({+ description: 'Percentage of users to enable for (0-100)',+ })+ @IsOptional()+ @IsNumber()+ @Min(0)+ @Max(100)+ rolloutPercentage?: number++ @ApiPropertyOptional({+ type: [TargetingRuleDto],+ description: 'Array of targeting rules',+ })+ @IsOptional()+ @IsArray()+ @ValidateNested({ each: true })+ @Type(() => TargetingRuleDto)+ targetingRules?: TargetingRuleDto[] | null++ @ApiPropertyOptional({ description: 'Whether the flag is enabled' })+ @IsOptional()+ @IsBoolean()+ enabled?: boolean+}++export class EvaluateFeatureFlagsDto {+ @ApiProperty({ description: 'Project ID to evaluate flags for' })+ @IsString()+ pid: string++ @ApiPropertyOptional({+ description: 'Visitor/user ID for consistent rollout',+ })+ @IsOptional()+ @IsString()+ visitorId?: string++ @ApiPropertyOptional({+ description: 'Visitor attributes for targeting (cc, dv, br, os, pg, etc.)',+ example: { cc: 'US', dv: 'desktop', br: 'Chrome', os: 'Windows' },+ })+ @IsOptional()+ attributes?: Record<string, string>+}++export class FeatureFlagDto {+ @ApiProperty()+ id: string++ @ApiProperty()+ key: string++ @ApiProperty()+ description: string | null++ @ApiProperty({ enum: FeatureFlagType })+ flagType: FeatureFlagType++ @ApiProperty()+ rolloutPercentage: number++ @ApiProperty({ type: [TargetingRuleDto] })+ targetingRules: TargetingRuleDto[] | null++ @ApiProperty()+ enabled: boolean++ @ApiProperty()+ pid: string++ @ApiProperty()+ created: Date+}++export class FeatureFlagStatsDto {+ @ApiProperty({ description: 'Total number of evaluations' })+ evaluations: number++ @ApiProperty({ description: 'Number of unique visitors' })+ uniqueVisitors: number++ @ApiProperty({ description: 'Number of times flag returned true' })+ trueCount: number++ @ApiProperty({ description: 'Number of times flag returned false' })+ falseCount: number++ @ApiProperty({ description: 'Percentage of true evaluations' })+ truePercentage: number+}++export class EvaluatedFlagsResponseDto {+ @ApiProperty({+ description: 'Map of flag keys to their evaluated boolean values',+ example: { 'new-checkout': true, 'dark-mode': false },+ })+ flags: Record<string, boolean>+}diff --git a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.tsnew file mode 100644index 000000000..3f434b308--- /dev/null+++ b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts@@ -0,0 +1,70 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ JoinColumn,+ ManyToOne,+ PrimaryGeneratedColumn,+ Unique,+} from 'typeorm'+import { ApiProperty } from '@nestjs/swagger'+import { Project } from '../../project/entity/project.entity'++export enum FeatureFlagType {+ BOOLEAN = 'boolean',+ ROLLOUT = 'rollout',+}++export interface TargetingRule {+ column: string // cc, dv, br, os, pg, etc.+ filter: string // value to match+ isExclusive: boolean // true = exclude, false = include+}++@Entity()+@Unique(['project', 'key'])+export class FeatureFlag {+ @ApiProperty()+ @PrimaryGeneratedColumn('uuid')+ id: string++ @ApiProperty()+ @Column('varchar', { length: 100 })+ key: string++ @ApiProperty()+ @Column('varchar', { length: 500, nullable: true })+ description: string | null++ @ApiProperty()+ @Column({+ type: 'enum',+ enum: FeatureFlagType,+ default: FeatureFlagType.BOOLEAN,+ })+ flagType: FeatureFlagType++ @ApiProperty()+ @Column('tinyint', { unsigned: true, default: 100 })+ rolloutPercentage: number++ @ApiProperty()+ @Column('json', { nullable: true })+ targetingRules: TargetingRule[] | null++ @ApiProperty()+ @Column({+ type: 'boolean',+ default: true,+ })+ enabled: boolean++ @ApiProperty({ type: () => Project })+ @ManyToOne(() => Project, project => project.featureFlags)+ @JoinColumn()+ project: Project++ @ApiProperty()+ @CreateDateColumn()+ created: Date+}diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.tsnew file mode 100644index 000000000..7ca5f5978--- /dev/null+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts@@ -0,0 +1,507 @@+import {+ Controller,+ Get,+ Put,+ Delete,+ Query,+ Param,+ Body,+ NotFoundException,+ Post,+ ForbiddenException,+ BadRequestException,+ HttpException,+ HttpStatus,+ ParseIntPipe,+} from '@nestjs/common'+import {+ ApiTags,+ ApiResponse,+ ApiBearerAuth,+ ApiOperation,+} from '@nestjs/swagger'+import _isEmpty from 'lodash/isEmpty'+import _map from 'lodash/map'+import _omit from 'lodash/omit'+import _pick from 'lodash/pick'+import _round from 'lodash/round'+import dayjs from 'dayjs'++import { UserService } from '../user/user.service'+import { ProjectService } from '../project/project.service'+import { AppLoggerService } from '../logger/logger.service'+import { PlanCode } from '../user/entities/user.entity'+import {+ AnalyticsService,+ getLowestPossibleTimeBucket,+} from '../analytics/analytics.service'+import { Auth } from '../auth/decorators'+import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'+import { FeatureFlag } from './entity/feature-flag.entity'+import {+ CreateFeatureFlagDto,+ UpdateFeatureFlagDto,+ EvaluateFeatureFlagsDto,+ FeatureFlagDto,+ FeatureFlagStatsDto,+ EvaluatedFlagsResponseDto,+} from './dto/feature-flag.dto'+import { FeatureFlagService } from './feature-flag.service'+import { clickhouse } from '../common/integrations/clickhouse'++const FEATURE_FLAGS_MAXIMUM = 100 // Maximum feature flags per project++const timeBucketConversion: Record<string, string> = {+ minute: 'toStartOfMinute',+ hour: 'toStartOfHour',+ day: 'toStartOfDay',+ month: 'toStartOfMonth',+ year: 'toStartOfYear',+}++@ApiTags('Feature Flag')+@Controller('feature-flag')+export class FeatureFlagController {+ constructor(+ private readonly featureFlagService: FeatureFlagService,+ private readonly projectService: ProjectService,+ private readonly logger: AppLoggerService,+ private readonly userService: UserService,+ private readonly analyticsService: AnalyticsService,+ ) {}++ // NOTE: More specific routes must come before generic parameter routes+ // e.g., /project/:projectId must be before /:flagId++ @ApiBearerAuth()+ @Get('/project/:projectId')+ @Auth()+ @ApiResponse({ status: 200, type: [FeatureFlagDto] })+ @ApiOperation({ summary: 'Get all feature flags for a project' })+ async getProjectFeatureFlags(+ @CurrentUserId() userId: string,+ @Param('projectId') projectId: string,+ @Query('take', new ParseIntPipe({ optional: true })) take?: number,+ @Query('skip', new ParseIntPipe({ optional: true })) skip?: number,+ ) {+ this.logger.log(+ { userId, projectId, take, skip },+ 'GET /feature-flag/project/:projectId',+ )++ const project = await this.projectService.getFullProject(projectId)++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToView(project, userId)++ const result = await this.featureFlagService.paginate(+ { take, skip },+ { project: { id: projectId } },+ ['project'],+ )++ // @ts-expect-error+ result.results = _map(result.results, flag => ({+ ..._omit(flag, ['project']),+ pid: flag.project.id,+ }))++ return result+ }++ @ApiBearerAuth()+ @Get('/:flagId')+ @Auth()+ @ApiResponse({ status: 200, type: FeatureFlagDto })+ @ApiOperation({ summary: 'Get a feature flag by ID' })+ async getFeatureFlag(+ @CurrentUserId() userId: string,+ @Param('flagId') flagId: string,+ ) {+ this.logger.log({ userId, flagId }, 'GET /feature-flag/:flagId')++ const flag = await this.featureFlagService.findOne({+ where: { id: flagId },+ relations: ['project'],+ })++ if (_isEmpty(flag)) {+ throw new NotFoundException('Feature flag not found')+ }++ const project = await this.projectService.getFullProject(flag.project.id)++ this.projectService.allowedToView(project, userId)++ return {+ ..._omit(flag, ['project']),+ pid: flag.project.id,+ }+ }++ @ApiBearerAuth()+ @Post('/')+ @Auth()+ @ApiResponse({ status: 201, type: FeatureFlagDto })+ @ApiOperation({ summary: 'Create a new feature flag' })+ async createFeatureFlag(+ @Body() flagDto: CreateFeatureFlagDto,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ uid, pid: flagDto.pid }, 'POST /feature-flag')++ const user = await this.userService.findOne({+ where: { id: uid },+ relations: ['projects'],+ })++ if (!user.isActive) {+ throw new ForbiddenException('Please, verify your email address first')+ }++ const project = await this.projectService.findOne({+ where: {+ id: flagDto.pid,+ },+ relations: ['featureFlags', 'admin'],+ })++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToManage(+ project,+ uid,+ 'You are not allowed to add feature flags to this project',+ )++ const flagsCount = await this.featureFlagService.count({+ where: { project: { id: flagDto.pid } },+ })++ if (user.planCode === PlanCode.none) {+ throw new HttpException(+ 'You cannot create new feature flags due to no active subscription. Please upgrade your account plan to continue.',+ HttpStatus.PAYMENT_REQUIRED,+ )+ }++ if (user.isAccountBillingSuspended) {+ throw new HttpException(+ 'The account that owns this site is currently suspended, this is because of a billing issue. Please resolve the issue to continue.',+ HttpStatus.PAYMENT_REQUIRED,+ )+ }++ if (flagsCount >= FEATURE_FLAGS_MAXIMUM) {+ throw new HttpException(+ `You cannot create more than ${FEATURE_FLAGS_MAXIMUM} feature flags per project.`,+ HttpStatus.PAYMENT_REQUIRED,+ )+ }++ // Check for duplicate key+ const existingFlag = await this.featureFlagService.findOne({+ where: { project: { id: flagDto.pid }, key: flagDto.key },+ })++ if (existingFlag) {+ throw new BadRequestException(+ `A feature flag with key "${flagDto.key}" already exists in this project`,+ )+ }++ try {+ const flag = new FeatureFlag()+ flag.key = flagDto.key+ flag.description = flagDto.description || null+ flag.flagType = flagDto.flagType || flag.flagType+ flag.rolloutPercentage = flagDto.rolloutPercentage ?? 100+ flag.targetingRules = flagDto.targetingRules || null+ flag.enabled = flagDto.enabled ?? true+ flag.project = project++ const newFlag = await this.featureFlagService.create(flag)++ return {+ ..._omit(newFlag, ['project']),+ pid: flagDto.pid,+ }+ } catch (reason) {+ this.logger.error({ reason }, 'Error while creating feature flag')+ throw new BadRequestException(+ 'Error occurred while creating feature flag',+ )+ }+ }++ @ApiBearerAuth()+ @Put('/:id')+ @Auth()+ @ApiResponse({ status: 200, type: FeatureFlagDto })+ @ApiOperation({ summary: 'Update a feature flag' })+ async updateFeatureFlag(+ @Param('id') id: string,+ @Body() flagDto: UpdateFeatureFlagDto,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ id, uid }, 'PUT /feature-flag/:id')++ const flag = await this.featureFlagService.findOneWithRelations(id)++ if (_isEmpty(flag)) {+ throw new NotFoundException()+ }++ this.projectService.allowedToManage(+ flag.project,+ uid,+ 'You are not allowed to manage this feature flag',+ )++ // Check for duplicate key if key is being changed+ if (flagDto.key && flagDto.key !== flag.key) {+ const existingFlag = await this.featureFlagService.findOne({+ where: { project: { id: flag.project.id }, key: flagDto.key },+ })++ if (existingFlag) {+ throw new BadRequestException(+ `A feature flag with key "${flagDto.key}" already exists in this project`,+ )+ }+ }++ const updatePayload: Partial<FeatureFlag> = {+ ..._pick(flagDto, [+ 'key',+ 'description',+ 'flagType',+ 'rolloutPercentage',+ 'targetingRules',+ 'enabled',+ ]),+ }++ await this.featureFlagService.update(id, updatePayload)++ const updatedFlag = await this.featureFlagService.findOne({ where: { id } })+ if (!updatedFlag) {+ throw new NotFoundException('Feature flag not found after update')+ }++ return {+ ..._omit(updatedFlag, ['project']),+ pid: flag.project.id,+ }+ }++ @ApiBearerAuth()+ @Delete('/:id')+ @Auth()+ @ApiResponse({ status: 204, description: 'Empty body' })+ @ApiOperation({ summary: 'Delete a feature flag' })+ async deleteFeatureFlag(+ @Param('id') id: string,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ id, uid }, 'DELETE /feature-flag/:id')++ const flag = await this.featureFlagService.findOneWithRelations(id)++ if (_isEmpty(flag)) {+ throw new NotFoundException()+ }++ this.projectService.allowedToManage(+ flag.project,+ uid,+ 'You are not allowed to manage this feature flag',+ )++ await this.featureFlagService.delete(id)+ }++ @Post('/evaluate')+ @ApiResponse({ status: 200, type: EvaluatedFlagsResponseDto })+ @ApiOperation({+ summary: 'Evaluate feature flags for a visitor (public endpoint)',+ description:+ 'Evaluates all enabled feature flags for a project based on visitor attributes. Does not require authentication.',+ })+ async evaluateFlags(@Body() evaluateDto: EvaluateFeatureFlagsDto) {+ this.logger.log({ pid: evaluateDto.pid }, 'POST /feature-flag/evaluate')++ const project = await this.projectService.findOne({+ where: { id: evaluateDto.pid },+ })++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ if (!project.active) {+ throw new BadRequestException('Project is not active')+ }++ const flags = await this.featureFlagService.findEnabledByProject(+ evaluateDto.pid,+ )++ const evaluatedFlags = this.featureFlagService.evaluateFlags(+ flags,+ evaluateDto.visitorId,+ evaluateDto.attributes,+ )++ // Track evaluations in ClickHouse (async, don't wait)+ this.trackEvaluations(+ evaluateDto.pid,+ flags,+ evaluatedFlags,+ evaluateDto.visitorId,+ ).catch(err => {+ this.logger.error({ err }, 'Failed to track flag evaluations')+ })++ return { flags: evaluatedFlags }+ }++ private async trackEvaluations(+ pid: string,+ flags: FeatureFlag[],+ evaluatedFlags: Record<string, boolean>,+ visitorId?: string,+ ) {+ if (flags.length === 0) return++ const now = new Date().toISOString().slice(0, 19).replace('T', ' ')+ const vid = visitorId || 'anonymous'++ const values = flags.map(flag => ({+ pid,+ flagId: flag.id,+ flagKey: flag.key,+ result: evaluatedFlags[flag.key] ? 1 : 0,+ visitorId: vid,+ created: now,+ }))++ try {+ await clickhouse.insert({+ table: 'feature_flag_evaluations',+ values,+ format: 'JSONEachRow',+ })+ } catch (err) {+ // Log error but don't fail the request+ this.logger.error({ err }, 'Failed to insert flag evaluations')+ }+ }++ @ApiBearerAuth()+ @Get('/:id/stats')+ @Auth()+ @ApiResponse({ status: 200, type: FeatureFlagStatsDto })+ @ApiOperation({ summary: 'Get statistics for a feature flag' })+ async getFeatureFlagStats(+ @CurrentUserId() userId: string,+ @Param('id') id: string,+ @Query('period') period: string,+ @Query('from') from?: string,+ @Query('to') to?: string,+ @Query('timezone') timezone?: string,+ ) {+ this.logger.log(+ { userId, id, period, from, to },+ 'GET /feature-flag/:id/stats',+ )++ const flag = await this.featureFlagService.findOneWithRelations(id)++ if (_isEmpty(flag)) {+ throw new NotFoundException('Feature flag not found')+ }++ const project = await this.projectService.getFullProject(flag.project.id)+ this.projectService.allowedToView(project, userId)++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const timeBucket = getLowestPossibleTimeBucket(period, from, to)++ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(+ from,+ to,+ timeBucket,+ period,+ safeTimezone,+ )++ const statsQuery = `+ SELECT+ count(*) as evaluations,+ uniqExact(visitorId) as uniqueVisitors,+ countIf(result = 1) as trueCount,+ countIf(result = 0) as falseCount+ FROM feature_flag_evaluations+ WHERE+ pid = {pid:FixedString(12)}+ AND flagId = {flagId:String}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ `++ const queryParams = {+ pid: flag.project.id,+ flagId: flag.id,+ groupFrom: groupFromUTC,+ groupTo: groupToUTC,+ }++ try {+ const { data } = await clickhouse+ .query({ query: statsQuery, query_params: queryParams })+ .then(resultSet =>+ resultSet.json<{+ evaluations: number+ uniqueVisitors: number+ trueCount: number+ falseCount: number+ }>(),+ )++ const stats = data[0] || {+ evaluations: 0,+ uniqueVisitors: 0,+ trueCount: 0,+ falseCount: 0,+ }++ const truePercentage =+ stats.evaluations > 0+ ? _round((stats.trueCount / stats.evaluations) * 100, 2)+ : 0++ return {+ evaluations: stats.evaluations,+ uniqueVisitors: stats.uniqueVisitors,+ trueCount: stats.trueCount,+ falseCount: stats.falseCount,+ truePercentage,+ }+ } catch (err) {+ // If table doesn't exist yet, return empty stats+ this.logger.warn({ err }, 'Failed to get flag stats')+ return {+ evaluations: 0,+ uniqueVisitors: 0,+ trueCount: 0,+ falseCount: 0,+ truePercentage: 0,+ }+ }+ }+}diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.module.ts b/backend/apps/cloud/src/feature-flag/feature-flag.module.tsnew file mode 100644index 000000000..7672d9801--- /dev/null+++ b/backend/apps/cloud/src/feature-flag/feature-flag.module.ts@@ -0,0 +1,24 @@+import { Module } from '@nestjs/common'+import { TypeOrmModule } from '@nestjs/typeorm'++import { ProjectModule } from '../project/project.module'+import { AppLoggerModule } from '../logger/logger.module'+import { UserModule } from '../user/user.module'+import { AnalyticsModule } from '../analytics/analytics.module'+import { FeatureFlagService } from './feature-flag.service'+import { FeatureFlag } from './entity/feature-flag.entity'+import { FeatureFlagController } from './feature-flag.controller'++@Module({+ imports: [+ TypeOrmModule.forFeature([FeatureFlag]),+ ProjectModule,+ AppLoggerModule,+ UserModule,+ AnalyticsModule,+ ],+ providers: [FeatureFlagService],+ exports: [FeatureFlagService],+ controllers: [FeatureFlagController],+})+export class FeatureFlagModule {}diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts b/backend/apps/cloud/src/feature-flag/feature-flag.service.tsnew file mode 100644index 000000000..1f4dc7331--- /dev/null+++ b/backend/apps/cloud/src/feature-flag/feature-flag.service.ts@@ -0,0 +1,228 @@+import { Injectable } from '@nestjs/common'+import { InjectRepository } from '@nestjs/typeorm'+import { FindManyOptions, FindOneOptions, Repository } from 'typeorm'+import * as crypto from 'crypto'+import { Pagination, PaginationOptionsInterface } from '../common/pagination'+import {+ FeatureFlag,+ FeatureFlagType,+ TargetingRule,+} from './entity/feature-flag.entity'++@Injectable()+export class FeatureFlagService {+ constructor(+ @InjectRepository(FeatureFlag)+ private featureFlagRepository: Repository<FeatureFlag>,+ ) {}++ async paginate(+ options: PaginationOptionsInterface,+ where: FindManyOptions<FeatureFlag>['where'],+ relations?: Array<string>,+ ): Promise<Pagination<FeatureFlag>> {+ const [results, total] = await this.featureFlagRepository.findAndCount({+ take: options.take || 100,+ skip: options.skip || 0,+ where,+ order: {+ key: 'ASC',+ },+ relations,+ })++ return new Pagination<FeatureFlag>({+ results,+ total,+ })+ }++ findOneWithRelations(id: string): Promise<FeatureFlag | null> {+ return this.featureFlagRepository.findOne({+ where: { id },+ relations: ['project', 'project.admin'],+ })+ }++ async count(options: FindManyOptions<FeatureFlag> = {}): Promise<number> {+ return this.featureFlagRepository.count(options)+ }++ findOne(options: FindOneOptions<FeatureFlag>): Promise<FeatureFlag | null> {+ return this.featureFlagRepository.findOne(options)+ }++ find(options: FindManyOptions<FeatureFlag>): Promise<FeatureFlag[]> {+ return this.featureFlagRepository.find(options)+ }++ findByProject(projectId: string): Promise<FeatureFlag[]> {+ return this.featureFlagRepository.find({+ where: { project: { id: projectId } },+ order: { key: 'ASC' },+ })+ }++ findEnabledByProject(projectId: string): Promise<FeatureFlag[]> {+ return this.featureFlagRepository.find({+ where: { project: { id: projectId }, enabled: true },+ order: { key: 'ASC' },+ })+ }++ async create(flagData: Partial<FeatureFlag>): Promise<FeatureFlag> {+ return this.featureFlagRepository.save(flagData)+ }++ async update(id: string, flagData: Partial<FeatureFlag>): Promise<any> {+ return this.featureFlagRepository.update(id, flagData)+ }++ async delete(id: string): Promise<any> {+ return this.featureFlagRepository.delete(id)+ }++ /**+ * Evaluates all feature flags for a project given visitor attributes+ */+ evaluateFlags(+ flags: FeatureFlag[],+ visitorId?: string,+ attributes?: Record<string, string>,+ ): Record<string, boolean> {+ const result: Record<string, boolean> = {}++ for (const flag of flags) {+ result[flag.key] = this.evaluateFlag(flag, visitorId, attributes)+ }++ return result+ }++ /**+ * Evaluates a single feature flag for a visitor+ */+ evaluateFlag(+ flag: FeatureFlag,+ visitorId?: string,+ attributes?: Record<string, string>,+ ): boolean {+ // If flag is disabled, always return false+ if (!flag.enabled) {+ return false+ }++ // Check targeting rules if any exist+ if (flag.targetingRules && flag.targetingRules.length > 0) {+ const matchesTargeting = this.matchesTargetingRules(+ flag.targetingRules,+ attributes,+ )+ if (!matchesTargeting) {+ return false+ }+ }++ // For boolean flags, return true if enabled and targeting matches+ if (flag.flagType === FeatureFlagType.BOOLEAN) {+ return true+ }++ // For rollout flags, use percentage-based rollout+ if (flag.flagType === FeatureFlagType.ROLLOUT) {+ return this.isInRolloutPercentage(+ flag.key,+ flag.rolloutPercentage,+ visitorId,+ )+ }++ return false+ }++ /**+ * Checks if visitor attributes match the targeting rules+ * Rules are evaluated as AND (all rules must match)+ */+ private matchesTargetingRules(+ rules: TargetingRule[],+ attributes?: Record<string, string>,+ ): boolean {+ if (!attributes) {+ // If no attributes provided, we can't match any rules+ // Return true to be permissive (flag will be shown)+ return true+ }++ for (const rule of rules) {+ const attributeValue = attributes[rule.column]++ // Check if we have the attribute+ if (attributeValue === undefined) {+ // If attribute not provided, skip this rule (be permissive)+ continue+ }++ const matches = this.matchesRule(attributeValue, rule.filter)++ // If isExclusive (exclude), we want the rule to NOT match+ // If not isExclusive (include), we want the rule to match+ if (rule.isExclusive) {+ // Exclude: if it matches, targeting fails+ if (matches) {+ return false+ }+ } else {+ // Include: if it doesn't match, targeting fails+ if (!matches) {+ return false+ }+ }+ }++ return true+ }++ /**+ * Checks if an attribute value matches a filter value+ * Supports case-insensitive matching+ */+ private matchesRule(attributeValue: string, filterValue: string): boolean {+ // Case-insensitive exact match+ return attributeValue.toLowerCase() === filterValue.toLowerCase()+ }++ /**+ * Determines if a visitor is within the rollout percentage+ * Uses consistent hashing based on flag key and visitor ID+ */+ private isInRolloutPercentage(+ flagKey: string,+ percentage: number,+ visitorId?: string,+ ): boolean {+ if (percentage >= 100) {+ return true+ }+ if (percentage <= 0) {+ return false+ }++ // Use visitor ID if provided, otherwise generate random+ const identifier = visitorId || crypto.randomUUID()++ // Create a consistent hash based on flag key and visitor ID+ const hash = crypto+ .createHash('md5')+ .update(`${flagKey}:${identifier}`)+ .digest('hex')++ // Convert first 8 hex characters to a number (0 to 2^32-1)+ const hashValue = parseInt(hash.substring(0, 8), 16)++ // Normalize to 0-100 range+ const normalizedValue = (hashValue / 0xffffffff) * 100++ return normalizedValue < percentage+ }+}diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.tsindex 24d3c2751..b617c6c49 100644--- a/backend/apps/cloud/src/project/entity/project.entity.ts+++ b/backend/apps/cloud/src/project/entity/project.entity.ts@@ -9,6 +9,7 @@ import {import { ApiProperty } from '@nestjs/swagger'import { Alert } from '../../alert/entity/alert.entity'+import { FeatureFlag } from '../../feature-flag/entity/feature-flag.entity'import { Goal } from '../../goal/entity/goal.entity'import { User } from '../../user/entities/user.entity'import { ProjectShare } from './project-share.entity'@@ -128,6 +129,10 @@ export class Project {@OneToMany(() => Goal, goal => goal.project)goals: Goal[]+ @ApiProperty({ type: () => FeatureFlag })+ @OneToMany(() => FeatureFlag, featureFlag => featureFlag.project)+ featureFlags: FeatureFlag[]+@Column('varchar', {default: null,length: 60,diff --git a/backend/migrations/clickhouse/2025_12_08_feature_flags.js b/backend/migrations/clickhouse/2025_12_08_feature_flags.jsnew file mode 100644index 000000000..3cc80748c--- /dev/null+++ b/backend/migrations/clickhouse/2025_12_08_feature_flags.js@@ -0,0 +1,20 @@+const { queriesRunner, dbName } = require('./setup')++const queries = [+ // Create feature_flag_evaluations table for tracking flag evaluations+ `CREATE TABLE IF NOT EXISTS ${dbName}.feature_flag_evaluations+ (+ pid FixedString(12),+ flagId String,+ flagKey String,+ result UInt8,+ visitorId String,+ created DateTime('UTC')+ )+ ENGINE = MergeTree()+ PARTITION BY toYYYYMM(created)+ ORDER BY (pid, flagId, created)+ TTL created + INTERVAL 1 YEAR;`,+]++queriesRunner(queries)diff --git a/backend/migrations/mysql/2025_12_08_feature_flags.sql b/backend/migrations/mysql/2025_12_08_feature_flags.sqlnew file mode 100644index 000000000..581a3c79d--- /dev/null+++ b/backend/migrations/mysql/2025_12_08_feature_flags.sql@@ -0,0 +1,15 @@+-- Feature flags table migration+CREATE TABLE IF NOT EXISTS `feature_flag` (+ `id` varchar(36) NOT NULL,+ `key` varchar(100) NOT NULL,+ `description` varchar(500) DEFAULT NULL,+ `flagType` enum('boolean', 'rollout') NOT NULL DEFAULT 'boolean',+ `rolloutPercentage` tinyint UNSIGNED NOT NULL DEFAULT 100,+ `targetingRules` json DEFAULT NULL,+ `enabled` tinyint(1) NOT NULL DEFAULT 1,+ `created` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ `projectId` varchar(12) DEFAULT NULL,+ PRIMARY KEY (`id`),+ UNIQUE KEY `unique_key_per_project` (`projectId`, `key`),+ FOREIGN KEY (`projectId`) REFERENCES `project` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 8de3d95f7..e09d51da0 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -1246,6 +1246,108 @@ export const getGoalChart = (throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})+// Feature Flags API+export interface TargetingRule {+ column: string+ filter: string+ isExclusive: boolean+}++export interface ProjectFeatureFlag {+ id: string+ key: string+ description: string | null+ flagType: 'boolean' | 'rollout'+ rolloutPercentage: number+ targetingRules: TargetingRule[] | null+ enabled: boolean+ pid: string+ created: string+}++export interface FeatureFlagStats {+ evaluations: number+ uniqueVisitors: number+ trueCount: number+ falseCount: number+ truePercentage: number+}++export type CreateFeatureFlag = {+ pid: string+ key: string+ description?: string+ flagType?: 'boolean' | 'rollout'+ rolloutPercentage?: number+ targetingRules?: TargetingRule[]+ enabled?: boolean+}++export const DEFAULT_FEATURE_FLAGS_TAKE = 20++export const getProjectFeatureFlags = (projectId: string, take: number = DEFAULT_FEATURE_FLAGS_TAKE, skip = 0) =>+ api+ .get(`/feature-flag/project/${projectId}?take=${take}&skip=${skip}`)+ .then(+ (+ response,+ ): {+ results: ProjectFeatureFlag[]+ total: number+ } => response.data,+ )+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const getFeatureFlag = (flagId: string) =>+ api+ .get(`/feature-flag/${flagId}`)+ .then((response): ProjectFeatureFlag => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const createFeatureFlag = (data: CreateFeatureFlag) =>+ api+ .post('feature-flag', data)+ .then((response): ProjectFeatureFlag => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const updateFeatureFlag = (id: string, data: Partial<ProjectFeatureFlag>) =>+ api+ .put(`feature-flag/${id}`, data)+ .then((response): ProjectFeatureFlag => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const deleteFeatureFlag = (id: string) =>+ api+ .delete(`feature-flag/${id}`)+ .then((response) => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const getFeatureFlagStats = (+ flagId: string,+ period: string,+ from: string = '',+ to: string = '',+ timezone?: string,+) =>+ api+ .get(`/feature-flag/${flagId}/stats`, {+ params: { period, from, to, timezone },+ })+ .then((response): FeatureFlagStats => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })+export const reGenerateCaptchaSecretKey = (pid: string) =>api.post(`project/secret-gen/${pid}`)diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.tsindex 3399135e3..590589e83 100644--- a/web/app/lib/constants/index.ts+++ b/web/app/lib/constants/index.ts@@ -405,6 +405,7 @@ const SELFHOSTED_PROJECT_TABS = {sessions: 'sessions',errors: 'errors',goals: 'goals',+ featureFlags: 'featureFlags',} as constconst PRODUCTION_PROJECT_TABS = {@@ -415,6 +416,7 @@ const PRODUCTION_PROJECT_TABS = {sessions: 'sessions',errors: 'errors',goals: 'goals',+ featureFlags: 'featureFlags',alerts: 'alerts',captcha: 'captcha',ai: 'ai',diff --git a/web/app/pages/Project/FeatureFlags/View/FeatureFlagSettingsModal.tsx b/web/app/pages/Project/FeatureFlags/View/FeatureFlagSettingsModal.tsxnew file mode 100644index 000000000..29f9e1710--- /dev/null+++ b/web/app/pages/Project/FeatureFlags/View/FeatureFlagSettingsModal.tsx@@ -0,0 +1,686 @@+import {+ Dialog,+ DialogBackdrop,+ DialogPanel,+ DialogTitle,+ Listbox,+ ListboxButton,+ ListboxOption,+ ListboxOptions,+ Transition,+} from '@headlessui/react'+import { XMarkIcon, ClipboardIcon, CheckIcon as HeroCheckIcon } from '@heroicons/react/24/outline'+import cx from 'clsx'+import _map from 'lodash/map'+import { Trash2Icon, PlusIcon, CodeIcon, ChevronDownIcon, ChevronsUpDownIcon, CheckIcon } from 'lucide-react'+import { useState, useEffect, useCallback, Fragment } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'++import {+ getFeatureFlag,+ createFeatureFlag,+ updateFeatureFlag,+ getFilters,+ type CreateFeatureFlag,+ type TargetingRule,+} from '~/api'+import { useTheme } from '~/providers/ThemeProvider'+import Button from '~/ui/Button'+import Checkbox from '~/ui/Checkbox'+import FilterValueInput, { filterCategoryIcons } from '~/ui/FilterValueInput'+import Input from '~/ui/Input'+import Loader from '~/ui/Loader'+import Select from '~/ui/Select'+import { Text } from '~/ui/Text'++const FLAG_TYPES = [+ { value: 'boolean', label: 'Boolean (On/Off)' },+ { value: 'rollout', label: 'Rollout (Percentage)' },+]++const TARGETING_COLUMNS = [+ { value: 'cc', label: 'Country' },+ { value: 'rg', label: 'Region' },+ { value: 'ct', label: 'City' },+ { value: 'dv', label: 'Device' },+ { value: 'br', label: 'Browser' },+ { value: 'os', label: 'OS' },+ { value: 'lc', label: 'Locale' },+ { value: 'ref', label: 'Referrer' },+ { value: 'pg', label: 'Page' },+]++interface FeatureFlagSettingsModalProps {+ isOpen: boolean+ onClose: () => void+ onSuccess: () => void+ projectId: string+ flagId?: string | null+}++const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagId }: FeatureFlagSettingsModalProps) => {+ const {+ t,+ i18n: { language },+ } = useTranslation()+ const { theme } = useTheme()+ const isNew = !flagId++ const [isLoading, setIsLoading] = useState(false)+ const [isSaving, setIsSaving] = useState(false)+ const [showImplementation, setShowImplementation] = useState(false)+ const [copiedCode, setCopiedCode] = useState<string | null>(null)++ // Filter values cache for targeting rules+ const [filterValuesCache, setFilterValuesCache] = useState<Record<string, string[]>>({})+ const [loadingColumns, setLoadingColumns] = useState<Set<string>>(new Set())++ // Form state+ const [key, setKey] = useState('')+ const [description, setDescription] = useState('')+ const [flagType, setFlagType] = useState<'boolean' | 'rollout'>('boolean')+ const [rolloutPercentage, setRolloutPercentage] = useState(100)+ const [targetingRules, setTargetingRules] = useState<TargetingRule[]>([])+ const [enabled, setEnabled] = useState(true)++ const resetForm = () => {+ setKey('')+ setDescription('')+ setFlagType('boolean')+ setRolloutPercentage(100)+ setTargetingRules([])+ setEnabled(true)+ setShowImplementation(false)+ }++ const fetchFilterValues = useCallback(+ async (column: string) => {+ if (filterValuesCache[column] || loadingColumns.has(column)) return++ setLoadingColumns((prev) => new Set(prev).add(column))+ try {+ const result = await getFilters(projectId, column)+ setFilterValuesCache((prev) => ({ ...prev, [column]: result }))+ } catch (error) {+ console.error('Failed to fetch filter values:', error)+ setFilterValuesCache((prev) => ({ ...prev, [column]: [] }))+ } finally {+ setLoadingColumns((prev) => {+ const newSet = new Set(prev)+ newSet.delete(column)+ return newSet+ })+ }+ },+ [projectId, filterValuesCache, loadingColumns],+ )++ // Pre-fetch filter values when modal opens+ useEffect(() => {+ if (isOpen) {+ // Pre-fetch values for all targeting columns+ TARGETING_COLUMNS.forEach(({ value: column }) => {+ if (!filterValuesCache[column] && !loadingColumns.has(column)) {+ fetchFilterValues(column)+ }+ })+ }+ }, [isOpen, fetchFilterValues, filterValuesCache, loadingColumns])++ const loadFlag = async () => {+ if (!flagId) return+ setIsLoading(true)+ try {+ const flag = await getFeatureFlag(flagId)+ setKey(flag.key)+ setDescription(flag.description || '')+ setFlagType(flag.flagType)+ setRolloutPercentage(flag.rolloutPercentage)+ setTargetingRules(flag.targetingRules || [])+ setEnabled(flag.enabled)+ } catch (err: any) {+ toast.error(err?.message || 'Failed to load feature flag')+ onClose()+ } finally {+ setIsLoading(false)+ }+ }++ useEffect(() => {+ if (isOpen) {+ if (flagId) {+ loadFlag()+ } else {+ resetForm()+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isOpen, flagId])++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault()+ setIsSaving(true)++ try {+ if (isNew) {+ const data: CreateFeatureFlag = {+ pid: projectId,+ key,+ description: description || undefined,+ flagType,+ rolloutPercentage: flagType === 'rollout' ? rolloutPercentage : 100,+ targetingRules: targetingRules.length > 0 ? targetingRules : undefined,+ enabled,+ }+ await createFeatureFlag(data)+ toast.success(t('featureFlags.created'))+ } else if (flagId) {+ await updateFeatureFlag(flagId, {+ key,+ description: description || null,+ flagType,+ rolloutPercentage: flagType === 'rollout' ? rolloutPercentage : 100,+ targetingRules: targetingRules.length > 0 ? targetingRules : null,+ enabled,+ })+ toast.success(t('featureFlags.updated'))+ }+ onSuccess()+ onClose()+ } catch (err: any) {+ toast.error(err?.message || t('apiNotifications.somethingWentWrong'))+ } finally {+ setIsSaving(false)+ }+ }++ const addTargetingRule = () => {+ setTargetingRules([...targetingRules, { column: 'cc', filter: '', isExclusive: false }])+ }++ const updateTargetingRule = (index: number, field: keyof TargetingRule, value: string | boolean) => {+ const updated = [...targetingRules]+ if (field === 'column') {+ // Reset filter value when column changes+ updated[index] = { ...updated[index], column: value as string, filter: '' }+ // Fetch filter values for the new column if not already cached+ if (value && !filterValuesCache[value as string] && !loadingColumns.has(value as string)) {+ fetchFilterValues(value as string)+ }+ } else {+ // @ts-expect-error - TypeScript doesn't like dynamic field assignment+ updated[index][field] = value+ }+ setTargetingRules(updated)+ }++ const removeTargetingRule = (index: number) => {+ setTargetingRules(targetingRules.filter((_, i) => i !== index))+ }++ const handleKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ // Convert to kebab-case+ const value = e.target.value+ .toLowerCase()+ .replace(/\s+/g, '-')+ .replace(/[^a-z0-9_-]/g, '')+ setKey(value)+ }++ const copyToClipboard = async (code: string, id: string) => {+ try {+ await navigator.clipboard.writeText(code)+ setCopiedCode(id)+ setTimeout(() => setCopiedCode(null), 2000)+ } catch {+ toast.error('Failed to copy to clipboard')+ }+ }++ const jsCode = `// Check if feature is enabled+const isEnabled = await swetrix.isFeatureEnabled('${key || 'my-feature'}', {+ userId: 'user-123', // Optional: for consistent rollout+})++if (isEnabled) {+ // Show new feature+} else {+ // Show default experience+}`++ const jsCodeWithAttributes = `// Check with custom attributes+const isEnabled = await swetrix.isFeatureEnabled('${key || 'my-feature'}', {+ userId: 'user-123',+ attributes: {+ cc: 'US', // Country code+ dv: 'desktop', // Device type+ br: 'Chrome', // Browser+ }+})`++ const fetchCode = `// Using fetch API directly+const response = await fetch('https://api.swetrix.com/feature-flag/evaluate', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ pid: '${projectId}',+ visitorId: 'user-123',+ attributes: { cc: 'US', dv: 'desktop' }+ })+})+const { flags } = await response.json()+// flags = { '${key || 'my-feature'}': true/false, ... }`++ return (+ <Dialog className='relative z-40' open={isOpen} onClose={onClose}>+ <DialogBackdrop+ transition+ className='fixed inset-0 bg-gray-500/75 transition-opacity data-closed:opacity-0 data-enter:ease-out data-leave:duration-200 data-leave:ease-in'+ />++ <div className='fixed inset-0 z-10 w-screen overflow-y-auto'>+ <div className='flex min-h-full items-center justify-center p-4'>+ <DialogPanel+ transition+ className='w-full max-w-2xl transform rounded-xl bg-white transition-all data-closed:translate-y-4 data-closed:opacity-0 data-enter:ease-out data-leave:duration-200 data-leave:ease-in dark:bg-slate-900'+ >+ {isLoading ? (+ <div className='flex min-h-[300px] items-center justify-center'>+ <Loader />+ </div>+ ) : (+ <form onSubmit={handleSubmit}>+ <div className='max-h-[70vh] overflow-y-auto px-6 pt-5 pb-4'>+ <div className='flex items-center justify-between'>+ <DialogTitle className='text-lg font-semibold text-gray-900 dark:text-gray-50'>+ {isNew ? t('featureFlags.createTitle') : t('featureFlags.editTitle')}+ </DialogTitle>+ <button+ type='button'+ onClick={onClose}+ className='rounded-md p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:hover:bg-slate-800 dark:hover:text-gray-300'+ >+ <XMarkIcon className='h-5 w-5' />+ </button>+ </div>++ <div className='mt-4 space-y-4'>+ <Input+ label={t('featureFlags.key')}+ value={key}+ onChange={handleKeyChange}+ placeholder='my-feature-flag'+ hint={t('featureFlags.keyHint')}+ required+ />++ <div>+ <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>+ {t('featureFlags.descriptionLabel')}+ </label>+ <textarea+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ placeholder={t('featureFlags.descriptionPlaceholder')}+ rows={2}+ className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder-gray-500 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-none dark:border-slate-700 dark:bg-slate-800 dark:text-gray-100 dark:placeholder-gray-400'+ />+ </div>++ <div>+ <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>+ {t('featureFlags.flagType')}+ </label>+ <Select+ items={FLAG_TYPES}+ onSelect={(item) => setFlagType(item.value as 'boolean' | 'rollout')}+ title={FLAG_TYPES.find((t) => t.value === flagType)?.label || ''}+ labelExtractor={(item) => item.label}+ keyExtractor={(item) => item.value}+ selectedItem={FLAG_TYPES.find((t) => t.value === flagType)}+ capitalise+ />+ </div>++ {flagType === 'rollout' ? (+ <div>+ <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>+ {t('featureFlags.rolloutPercentage')} ({rolloutPercentage}%)+ </label>+ <input+ type='range'+ min='0'+ max='100'+ value={rolloutPercentage}+ onChange={(e) => setRolloutPercentage(Number(e.target.value))}+ className='w-full'+ />+ <div className='mt-1 flex justify-between text-xs text-gray-500'>+ <span>0%</span>+ <span>50%</span>+ <span>100%</span>+ </div>+ </div>+ ) : null}++ {/* Targeting Rules */}+ <div>+ <div className='mb-2 flex items-center justify-between'>+ <label className='block text-sm font-medium text-gray-700 dark:text-gray-300'>+ {t('featureFlags.targetingRules')}+ </label>+ <button+ type='button'+ onClick={addTargetingRule}+ className='flex items-center gap-1 text-sm text-indigo-600 hover:text-indigo-500 dark:text-indigo-400'+ >+ <PlusIcon className='h-4 w-4' />+ {t('featureFlags.addRule')}+ </button>+ </div>+ {targetingRules.length > 0 ? (+ <div className='space-y-3'>+ {_map(targetingRules, (rule, index) => (+ <div key={index} className='flex items-center gap-2'>+ {/* Column Select */}+ <Listbox+ value={rule.column}+ onChange={(value) => updateTargetingRule(index, 'column', value)}+ >+ {({ open }) => (+ <div className='relative w-36'>+ <ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'>+ <span className='flex items-center gap-2 truncate'>+ {rule.column ? filterCategoryIcons[rule.column] : null}+ {TARGETING_COLUMNS.find((c) => c.value === rule.column)?.label ||+ t('common.select')}+ </span>+ <span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>+ <ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />+ </span>+ </ListboxButton>+ <Transition+ show={open}+ as={Fragment}+ enter='transition ease-in duration-100'+ enterFrom='opacity-0'+ enterTo='opacity-100'+ leave='transition ease-in duration-100'+ leaveFrom='opacity-100'+ leaveTo='opacity-0'+ >+ <ListboxOptions+ static+ className='absolute z-50 mt-1 max-h-60 w-full min-w-[160px] overflow-auto rounded-md bg-white py-1 text-sm ring-1 ring-black/10 focus:outline-hidden dark:bg-slate-800'+ >+ {TARGETING_COLUMNS.map((col) => (+ <ListboxOption+ key={col.value}+ value={col.value}+ className={({ focus }) =>+ cx('relative cursor-pointer py-2 pr-4 pl-3 select-none', {+ 'bg-gray-100 dark:bg-slate-700': focus,+ 'text-gray-700 dark:text-gray-50': !focus,+ })+ }+ >+ {({ selected }) => (+ <span+ className={cx('flex items-center gap-2', { 'font-medium': selected })}+ >+ <span className='shrink-0 text-gray-500 dark:text-gray-400'>+ {filterCategoryIcons[col.value]}+ </span>+ <span className='truncate'>{col.label}</span>+ {selected ? (+ <CheckIcon className='ml-auto h-4 w-4 shrink-0 text-indigo-600 dark:text-indigo-400' />+ ) : null}+ </span>+ )}+ </ListboxOption>+ ))}+ </ListboxOptions>+ </Transition>+ </div>+ )}+ </Listbox>++ {/* Operator Select */}+ <Listbox+ value={rule.isExclusive ? 'exclude' : 'include'}+ onChange={(value) => updateTargetingRule(index, 'isExclusive', value === 'exclude')}+ >+ {({ open }) => (+ <div className='relative w-24'>+ <ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'>+ <span className='block truncate'>+ {rule.isExclusive ? t('featureFlags.isNot') : t('featureFlags.is')}+ </span>+ <span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>+ <ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />+ </span>+ </ListboxButton>+ <Transition+ show={open}+ as={Fragment}+ enter='transition ease-in duration-100'+ enterFrom='opacity-0'+ enterTo='opacity-100'+ leave='transition ease-in duration-100'+ leaveFrom='opacity-100'+ leaveTo='opacity-0'+ >+ <ListboxOptions+ static+ className='absolute z-50 mt-1 w-full overflow-auto rounded-md bg-white py-1 text-sm ring-1 ring-black/10 focus:outline-hidden dark:bg-slate-800'+ >+ <ListboxOption+ value='include'+ className={({ focus }) =>+ cx('relative cursor-pointer py-2 pr-4 pl-8 select-none', {+ 'bg-gray-100 dark:bg-slate-700': focus,+ 'text-gray-700 dark:text-gray-50': !focus,+ })+ }+ >+ {({ selected }) => (+ <>+ <span className={cx('block truncate', { 'font-medium': selected })}>+ {t('featureFlags.is')}+ </span>+ {selected ? (+ <span className='absolute inset-y-0 left-0 flex items-center pl-2 text-indigo-600 dark:text-indigo-400'>+ <CheckIcon className='h-4 w-4' />+ </span>+ ) : null}+ </>+ )}+ </ListboxOption>+ <ListboxOption+ value='exclude'+ className={({ focus }) =>+ cx('relative cursor-pointer py-2 pr-4 pl-8 select-none', {+ 'bg-gray-100 dark:bg-slate-700': focus,+ 'text-gray-700 dark:text-gray-50': !focus,+ })+ }+ >+ {({ selected }) => (+ <>+ <span className={cx('block truncate', { 'font-medium': selected })}>+ {t('featureFlags.isNot')}+ </span>+ {selected ? (+ <span className='absolute inset-y-0 left-0 flex items-center pl-2 text-indigo-600 dark:text-indigo-400'>+ <CheckIcon className='h-4 w-4' />+ </span>+ ) : null}+ </>+ )}+ </ListboxOption>+ </ListboxOptions>+ </Transition>+ </div>+ )}+ </Listbox>++ {/* Value Input with Autocomplete */}+ <FilterValueInput+ items={filterValuesCache[rule.column] || []}+ value={rule.filter}+ onChange={(value) => updateTargetingRule(index, 'filter', value)}+ placeholder={t('featureFlags.valuePlaceholder')}+ column={rule.column}+ language={language}+ isLoading={loadingColumns.has(rule.column)}+ theme={theme}+ />++ {/* Delete Button */}+ <button+ type='button'+ onClick={() => removeTargetingRule(index)}+ className='rounded-md p-2 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-700 dark:hover:text-gray-300'+ >+ <Trash2Icon className='h-4 w-4' />+ </button>+ </div>+ ))}+ </div>+ ) : (+ <Text as='p' size='sm' colour='muted'>+ {t('featureFlags.noTargetingRules')}+ </Text>+ )}+ </div>++ {/* Enable checkbox */}+ <Checkbox+ checked={enabled}+ onChange={setEnabled}+ label={t('featureFlags.enableFlag')}+ hint={t('featureFlags.enableFlagHint')}+ />++ {/* How to implement section */}+ <div className='border-t border-gray-200 pt-4 dark:border-slate-700'>+ <button+ type='button'+ onClick={() => setShowImplementation(!showImplementation)}+ className='flex w-full items-center justify-between text-left'+ >+ <div className='flex items-center gap-2'>+ <CodeIcon className='size-5 text-gray-500' />+ <Text as='span' weight='medium'>+ {t('featureFlags.howToImplement')}+ </Text>+ </div>+ <ChevronDownIcon+ className={cx('size-5 text-gray-500 transition-transform', {+ 'rotate-180': showImplementation,+ })}+ />+ </button>++ {showImplementation ? (+ <div className='mt-4 space-y-4'>+ <Text as='p' size='sm' colour='secondary'>+ {t('featureFlags.implementationDescription')}+ </Text>++ {/* JavaScript SDK */}+ <div>+ <div className='mb-2 flex items-center justify-between'>+ <Text as='span' size='sm' weight='medium'>+ JavaScript SDK+ </Text>+ <button+ type='button'+ onClick={() => copyToClipboard(jsCode, 'js')}+ className='flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700'+ >+ {copiedCode === 'js' ? (+ <HeroCheckIcon className='size-4 text-green-500' />+ ) : (+ <ClipboardIcon className='size-4' />+ )}+ {copiedCode === 'js' ? 'Copied!' : 'Copy'}+ </button>+ </div>+ <pre className='overflow-x-auto rounded-lg bg-gray-900 p-3 text-xs text-gray-100'>+ <code>{jsCode}</code>+ </pre>+ </div>++ {/* With attributes */}+ <div>+ <div className='mb-2 flex items-center justify-between'>+ <Text as='span' size='sm' weight='medium'>+ With custom attributes+ </Text>+ <button+ type='button'+ onClick={() => copyToClipboard(jsCodeWithAttributes, 'js-attr')}+ className='flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700'+ >+ {copiedCode === 'js-attr' ? (+ <HeroCheckIcon className='size-4 text-green-500' />+ ) : (+ <ClipboardIcon className='size-4' />+ )}+ {copiedCode === 'js-attr' ? 'Copied!' : 'Copy'}+ </button>+ </div>+ <pre className='overflow-x-auto rounded-lg bg-gray-900 p-3 text-xs text-gray-100'>+ <code>{jsCodeWithAttributes}</code>+ </pre>+ </div>++ {/* Fetch API */}+ <div>+ <div className='mb-2 flex items-center justify-between'>+ <Text as='span' size='sm' weight='medium'>+ REST API (Fetch)+ </Text>+ <button+ type='button'+ onClick={() => copyToClipboard(fetchCode, 'fetch')}+ className='flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700'+ >+ {copiedCode === 'fetch' ? (+ <HeroCheckIcon className='size-4 text-green-500' />+ ) : (+ <ClipboardIcon className='size-4' />+ )}+ {copiedCode === 'fetch' ? 'Copied!' : 'Copy'}+ </button>+ </div>+ <pre className='overflow-x-auto rounded-lg bg-gray-900 p-3 text-xs text-gray-100'>+ <code>{fetchCode}</code>+ </pre>+ </div>+ </div>+ ) : null}+ </div>+ </div>+ </div>++ <div className='flex justify-end gap-3 border-t border-gray-200 px-6 py-4 dark:border-slate-700'>+ <Button type='button' onClick={onClose} secondary regular>+ {t('common.cancel')}+ </Button>+ <Button type='submit' primary regular loading={isSaving}>+ {isNew ? t('featureFlags.create') : t('featureFlags.save')}+ </Button>+ </div>+ </form>+ )}+ </DialogPanel>+ </div>+ </div>+ </Dialog>+ )+}++export default FeatureFlagSettingsModaldiff --git a/web/app/pages/Project/FeatureFlags/View/FeatureFlagsView.tsx b/web/app/pages/Project/FeatureFlags/View/FeatureFlagsView.tsxnew file mode 100644index 000000000..095028da7--- /dev/null+++ b/web/app/pages/Project/FeatureFlags/View/FeatureFlagsView.tsx@@ -0,0 +1,521 @@+import { XCircleIcon } from '@heroicons/react/24/outline'+import cx from 'clsx'+import _isEmpty from 'lodash/isEmpty'+import _map from 'lodash/map'+import _size from 'lodash/size'+import {+ FlagIcon,+ Trash2Icon,+ PencilIcon,+ PlusIcon,+ SearchIcon,+ ToggleLeftIcon,+ ToggleRightIcon,+ PercentIcon,+ UsersIcon,+ ActivityIcon,+} from 'lucide-react'+import { useState, useEffect, useMemo, useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { Link } from 'react-router'+import { toast } from 'sonner'++import {+ deleteFeatureFlag as deleteFeatureFlagApi,+ getProjectFeatureFlags,+ getFeatureFlagStats,+ DEFAULT_FEATURE_FLAGS_TAKE,+ type ProjectFeatureFlag,+ type FeatureFlagStats,+} from '~/api'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'+import { useCurrentProject } from '~/providers/CurrentProjectProvider'+import Button from '~/ui/Button'+import Spin from '~/ui/icons/Spin'+import Loader from '~/ui/Loader'+import LoadingBar from '~/ui/LoadingBar'+import Modal from '~/ui/Modal'+import Pagination from '~/ui/Pagination'+import { Text } from '~/ui/Text'+import { nFormatter } from '~/utils/generic'+import routes from '~/utils/routes'++import FeatureFlagSettingsModal from './FeatureFlagSettingsModal'++interface FeatureFlagRowProps {+ flag: ProjectFeatureFlag+ stats: FeatureFlagStats | null+ statsLoading: boolean+ onDelete: (id: string) => void+ onEdit: (id: string) => void+ onToggle: (id: string, enabled: boolean) => void+}++const FeatureFlagRow = ({+ flag,+ stats,+ statsLoading,+ onDelete,+ onEdit,+ onToggle,+}: FeatureFlagRowProps) => {+ const { t } = useTranslation()+ const [showDeleteModal, setShowDeleteModal] = useState(false)++ const targetingRulesCount = flag.targetingRules?.length || 0++ return (+ <>+ <li className='relative mb-3 overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors dark:border-slate-800/25 dark:bg-slate-800/70'>+ <div className='flex justify-between gap-x-6 px-4 py-4 sm:px-6'>+ <div className='flex min-w-0 gap-x-4'>+ <div className='min-w-0 flex-auto'>+ <div className='flex items-center gap-x-2'>+ <Text as='p' weight='semibold' truncate className='flex items-center gap-x-1.5'>+ <FlagIcon className='size-4 text-indigo-500' strokeWidth={1.5} />+ <span>{flag.key}</span>+ </Text>+ {/* Status badge */}+ <span+ className={cx(+ 'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',+ flag.enabled+ ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'+ : 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400',+ )}+ >+ {flag.enabled ? t('featureFlags.enabled') : t('featureFlags.disabled')}+ </span>+ {/* Flag type badge */}+ <span className='inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900/30 dark:text-blue-400'>+ {flag.flagType === 'rollout' ? (+ <>+ <PercentIcon className='size-3' />+ {flag.rolloutPercentage}%+ </>+ ) : (+ <>+ <ToggleRightIcon className='size-3' />+ {t('featureFlags.boolean')}+ </>+ )}+ </span>+ </div>+ {flag.description ? (+ <Text className='mt-1' as='p' size='sm' colour='secondary'>+ {flag.description}+ </Text>+ ) : null}+ {targetingRulesCount > 0 ? (+ <Text className='mt-1' as='p' size='xs' colour='muted'>+ {t('featureFlags.targetingRulesCount', { count: targetingRulesCount })}+ </Text>+ ) : null}+ {/* Mobile stats */}+ <div className='mt-2 flex h-9 items-center gap-x-3 text-xs leading-5 text-gray-500 sm:hidden dark:text-gray-300'>+ {statsLoading ? (+ <div className='flex size-9 items-center justify-center'>+ <Spin className='m-0 size-5' />+ </div>+ ) : stats ? (+ <>+ <span className='flex items-center gap-1'>+ <ActivityIcon className='size-3' />+ {nFormatter(stats.evaluations, 1)} {t('featureFlags.evaluations').toLowerCase()}+ </span>+ <span className='flex items-center gap-1'>+ <UsersIcon className='size-3' />+ {nFormatter(stats.uniqueVisitors, 1)}+ </span>+ </>+ ) : (+ <Text as='p' size='xs' colour='muted'>+ {t('featureFlags.noStats')}+ </Text>+ )}+ </div>+ </div>+ </div>+ <div className='flex shrink-0 items-center gap-x-4'>+ {/* Desktop stats */}+ <div className='hidden h-11 sm:flex sm:items-center sm:gap-x-4'>+ {statsLoading ? (+ <div className='flex size-11 items-center justify-center'>+ <Spin className='m-0 size-5' />+ </div>+ ) : stats ? (+ <>+ <div className='text-right'>+ <Text as='p' size='sm' weight='semibold'>+ {nFormatter(stats.evaluations, 1)}+ </Text>+ <Text as='p' size='xs' colour='muted'>+ {t('featureFlags.evaluations')}+ </Text>+ </div>+ <div className='text-right'>+ <Text as='p' size='sm' weight='semibold'>+ {nFormatter(stats.uniqueVisitors, 1)}+ </Text>+ <Text as='p' size='xs' colour='muted'>+ {t('featureFlags.visitors')}+ </Text>+ </div>+ <div className='text-right'>+ <Text as='p' size='sm' weight='semibold' className='text-green-600 dark:text-green-400'>+ {stats.truePercentage}%+ </Text>+ <Text as='p' size='xs' colour='muted'>+ {t('featureFlags.trueRate')}+ </Text>+ </div>+ </>+ ) : (+ <Text as='p' size='sm' colour='muted'>+ {t('featureFlags.noStats')}+ </Text>+ )}+ </div>+ {/* Action buttons */}+ <div className='flex items-center gap-1'>+ <button+ type='button'+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ onToggle(flag.id, !flag.enabled)+ }}+ aria-label={flag.enabled ? t('featureFlags.disable') : t('featureFlags.enable')}+ className={cx(+ 'rounded-md border border-transparent p-1.5 transition-colors',+ flag.enabled+ ? 'text-green-600 hover:border-green-300 hover:bg-green-50 dark:text-green-400 hover:dark:border-green-700/80 dark:hover:bg-green-900/30'+ : 'text-gray-400 hover:border-gray-300 hover:bg-gray-50 dark:text-gray-500 hover:dark:border-slate-700/80 dark:hover:bg-slate-800',+ )}+ >+ {flag.enabled ? (+ <ToggleRightIcon className='size-5' strokeWidth={1.5} />+ ) : (+ <ToggleLeftIcon className='size-5' strokeWidth={1.5} />+ )}+ </button>+ <button+ type='button'+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ onEdit(flag.id)+ }}+ aria-label={t('common.edit')}+ className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-slate-300'+ >+ <PencilIcon className='size-4' strokeWidth={1.5} />+ </button>+ <button+ type='button'+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ setShowDeleteModal(true)+ }}+ aria-label={t('common.delete')}+ className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-slate-300'+ >+ <Trash2Icon className='size-4' strokeWidth={1.5} />+ </button>+ </div>+ </div>+ </div>+ </li>+ <Modal+ onClose={() => setShowDeleteModal(false)}+ onSubmit={() => {+ onDelete(flag.id)+ setShowDeleteModal(false)+ }}+ submitText={t('featureFlags.delete')}+ closeText={t('common.close')}+ title={t('featureFlags.deleteConfirmTitle')}+ message={t('featureFlags.deleteConfirmMessage')}+ submitType='danger'+ type='error'+ isOpened={showDeleteModal}+ />+ </>+ )+}++interface FeatureFlagsViewProps {+ period: string+ from?: string+ to?: string+ timezone?: string+}++const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlagsViewProps) => {+ const { id } = useCurrentProject()+ const { t } = useTranslation()++ const [isLoading, setIsLoading] = useState<boolean | null>(null)+ const isLoadingRef = useRef(false)+ const isMountedRef = useRef(true)+ const [total, setTotal] = useState(0)+ const [flags, setFlags] = useState<ProjectFeatureFlag[]>([])+ const [flagStats, setFlagStats] = useState<Record<string, FeatureFlagStats | null>>({})+ const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})+ const [page, setPage] = useState(1)+ const [error, setError] = useState<string | null>(null)+ const [filterQuery, setFilterQuery] = useState('')++ // Modal state+ const [isModalOpen, setIsModalOpen] = useState(false)+ const [editingFlagId, setEditingFlagId] = useState<string | null>(null)++ // Cleanup on unmount+ useEffect(() => {+ isMountedRef.current = true+ return () => {+ isMountedRef.current = false+ }+ }, [])++ const pageAmount = Math.ceil(total / DEFAULT_FEATURE_FLAGS_TAKE)++ const filteredFlags = useMemo(() => {+ if (!filterQuery.trim()) return flags+ const query = filterQuery.toLowerCase()+ return flags.filter(+ (flag) =>+ flag.key.toLowerCase().includes(query) ||+ (flag.description && flag.description.toLowerCase().includes(query)),+ )+ }, [flags, filterQuery])++ const loadFlags = async (take: number, skip: number) => {+ if (isLoadingRef.current) {+ return+ }+ isLoadingRef.current = true+ setIsLoading(true)++ try {+ const result = await getProjectFeatureFlags(id, take, skip)+ if (isMountedRef.current) {+ setFlags(result.results)+ setTotal(result.total)+ }+ } catch (reason: any) {+ if (isMountedRef.current) {+ setError(reason?.message || reason?.toString() || 'Unknown error')+ }+ } finally {+ isLoadingRef.current = false+ if (isMountedRef.current) {+ setIsLoading(false)+ }+ }+ }++ const loadFlagStats = async (flagId: string) => {+ setStatsLoading((prev) => ({ ...prev, [flagId]: true }))+ try {+ const stats = await getFeatureFlagStats(flagId, period, from, to, timezone)+ if (isMountedRef.current) {+ setFlagStats((prev) => ({ ...prev, [flagId]: stats }))+ }+ } catch (err) {+ console.error('Failed to load flag stats:', err)+ if (isMountedRef.current) {+ setFlagStats((prev) => ({ ...prev, [flagId]: null }))+ }+ } finally {+ if (isMountedRef.current) {+ setStatsLoading((prev) => ({ ...prev, [flagId]: false }))+ }+ }+ }++ useEffect(() => {+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [page])++ useEffect(() => {+ // Load stats for all flags when flags change or date range changes+ flags.forEach((flag) => {+ loadFlagStats(flag.id)+ })+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [flags, period, from, to, timezone])++ const handleNewFlag = () => {+ setEditingFlagId(null)+ setIsModalOpen(true)+ }++ const handleEditFlag = (flagId: string) => {+ setEditingFlagId(flagId)+ setIsModalOpen(true)+ }++ const handleCloseModal = () => {+ setIsModalOpen(false)+ setEditingFlagId(null)+ }++ const handleModalSuccess = () => {+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE)+ }++ const handleDeleteFlag = async (flagId: string) => {+ try {+ await deleteFeatureFlagApi(flagId)+ toast.success(t('featureFlags.deleted'))+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE)+ } catch (reason: any) {+ toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))+ }+ }++ const handleToggleFlag = async (flagId: string, enabled: boolean) => {+ try {+ const { updateFeatureFlag } = await import('~/api')+ await updateFeatureFlag(flagId, { enabled })+ toast.success(enabled ? t('featureFlags.flagEnabled') : t('featureFlags.flagDisabled'))+ // Update local state+ setFlags((prev) => prev.map((f) => (f.id === flagId ? { ...f, enabled } : f)))+ } catch (reason: any) {+ toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))+ }+ }++ if (error && isLoading === false) {+ return (+ <div className='bg-gray-50 px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8 dark:bg-slate-900'>+ <div className='mx-auto max-w-max'>+ <main className='sm:flex'>+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />+ <div className='sm:ml-6'>+ <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>+ <h1 className='text-4xl font-extrabold text-gray-900 sm:text-5xl dark:text-gray-50'>+ {t('apiNotifications.somethingWentWrong')}+ </h1>+ <p className='mt-4 text-2xl font-medium text-gray-700 dark:text-gray-200'>+ {t('apiNotifications.errorCode', { error })}+ </p>+ </div>+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>+ <button+ type='button'+ onClick={() => window.location.reload()}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden'+ >+ {t('dashboard.reloadPage')}+ </button>+ <Link+ to={routes.contact}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'+ >+ {t('notFoundPage.support')}+ </Link>+ </div>+ </div>+ </main>+ </div>+ </div>+ )+ }++ // Show Loader only on initial load (no existing data)+ if ((isLoading || isLoading === null) && _isEmpty(flags)) {+ return (+ <div className='mt-4'>+ <Loader />+ </div>+ )+ }++ return (+ <div className='mt-4'>+ {isLoading && !_isEmpty(flags) ? <LoadingBar /> : null}+ {_isEmpty(flags) ? (+ <div className='mt-5 rounded-xl bg-gray-700 p-5'>+ <div className='flex items-center text-gray-50'>+ <FlagIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />+ <p className='text-3xl font-bold'>{t('featureFlags.title')}</p>+ </div>+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('featureFlags.description')}</p>+ <Button+ onClick={handleNewFlag}+ className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-indigo-50 md:px-4'+ secondary+ large+ >+ {t('featureFlags.add')}+ </Button>+ </div>+ ) : (+ <>+ {/* Header with filter and add button */}+ <div className='mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between'>+ <div className='relative'>+ <SearchIcon className='absolute top-1/2 left-3 size-4 -translate-y-1/2 text-gray-400' strokeWidth={1.5} />+ <input+ type='text'+ placeholder={t('featureFlags.filterFlags')}+ value={filterQuery}+ onChange={(e) => setFilterQuery(e.target.value)}+ className='w-full rounded-lg border border-gray-300 bg-white py-2 pr-4 pl-9 text-sm text-gray-900 placeholder-gray-500 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-none sm:w-64 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-100 dark:placeholder-gray-400 dark:focus:border-indigo-400 dark:focus:ring-indigo-400'+ />+ </div>+ <Button onClick={handleNewFlag} primary regular>+ <PlusIcon className='mr-1.5 size-4' strokeWidth={2} />+ {t('featureFlags.addFlag')}+ </Button>+ </div>++ {/* Flags list */}+ <ul className='mt-4'>+ {_map(filteredFlags, (flag) => (+ <FeatureFlagRow+ key={flag.id}+ flag={flag}+ stats={flagStats[flag.id] || null}+ statsLoading={statsLoading[flag.id] || false}+ onDelete={handleDeleteFlag}+ onEdit={handleEditFlag}+ onToggle={handleToggleFlag}+ />+ ))}+ </ul>++ {filteredFlags.length === 0 && filterQuery ? (+ <p className='py-8 text-center text-sm text-gray-500 dark:text-gray-400'>+ {t('featureFlags.noFlagsMatchFilter')}+ </p>+ ) : null}+ </>+ )}+ {pageAmount > 1 && !filterQuery ? (+ <Pagination+ className='mt-4'+ page={page}+ pageAmount={pageAmount}+ setPage={setPage}+ total={total}+ pageSize={DEFAULT_FEATURE_FLAGS_TAKE}+ />+ ) : null}++ <FeatureFlagSettingsModal+ isOpen={isModalOpen}+ onClose={handleCloseModal}+ onSuccess={handleModalSuccess}+ projectId={id}+ flagId={editingFlagId}+ />+ </div>+ )+}++export default FeatureFlagsViewdiff --git a/web/app/pages/Project/FeatureFlags/View/index.tsx b/web/app/pages/Project/FeatureFlags/View/index.tsxnew file mode 100644index 000000000..5bc2e331f--- /dev/null+++ b/web/app/pages/Project/FeatureFlags/View/index.tsx@@ -0,0 +1 @@+export { default } from './FeatureFlagsView'diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex 660b5cea5..3065dbbfa 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -41,6 +41,7 @@ import {TargetIcon,PuzzleIcon,SparklesIcon,+ FlagIcon,} from 'lucide-react'import React, {useState,@@ -169,6 +170,7 @@ import routes from '~/utils/routes'import { useCurrentProject, useProjectPassword } from '../../../providers/CurrentProjectProvider'import ProjectAlertsView from '../Alerts/View'import AskAIView from '../AskAI'+import FeatureFlagsView from '../FeatureFlags/View'import GoalsView from '../Goals/View'import AddAViewModal from './components/AddAViewModal'@@ -1507,6 +1509,11 @@ const ViewProjectContent = () => {label: t('dashboard.goals'),icon: TargetIcon,},+ {+ id: PROJECT_TABS.featureFlags,+ label: t('dashboard.featureFlags'),+ icon: FlagIcon,+ },]const adminTabs = allowedToManage@@ -4317,6 +4324,14 @@ const ViewProjectContent = () => {timezone={timezone}/>) : null}+ {activeTab === PROJECT_TABS.featureFlags ? (+ <FeatureFlagsView+ period={period}+ from={dateRange ? getFormatDate(dateRange[0]) : ''}+ to={dateRange ? getFormatDate(dateRange[1]) : ''}+ timezone={timezone}+ />+ ) : null}{activeTab === PROJECT_TABS.ai ? <AskAIView projectId={id} /> : null}{activeTab === PROJECT_TABS.captcha ? <CaptchaView projectId={id} /> : null}{analyticsLoading &&diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsxindex fae54efb4..a35e16517 100644--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx@@ -185,6 +185,7 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({PROJECT_TABS.funnels,PROJECT_TABS.errors,PROJECT_TABS.goals,+ PROJECT_TABS.featureFlags,].includes(tab.id as any),)if (productAnalyticsTabs.length > 0) {diff --git a/web/app/pages/Project/View/components/SearchFilters.tsx b/web/app/pages/Project/View/components/SearchFilters.tsxindex d6ca3a870..3828e2ad9 100644--- a/web/app/pages/Project/View/components/SearchFilters.tsx+++ b/web/app/pages/Project/View/components/SearchFilters.tsx@@ -1,89 +1,22 @@import { Listbox, Transition, ListboxButton, ListboxOptions, ListboxOption } from '@headlessui/react'-import { useVirtualizer } from '@tanstack/react-virtual'import cx from 'clsx'-import _includes from 'lodash/includes'import _isEmpty from 'lodash/isEmpty'-import _toLower from 'lodash/toLower'-import {- BuildingIcon,- CheckIcon,- ChevronsUpDownIcon,- CircleQuestionMark,- CompassIcon,- CpuIcon,- FileIcon,- FileTextIcon,- Gamepad2Icon,- GlobeIcon,- LanguagesIcon,- LinkIcon,- LogInIcon,- LogOutIcon,- MapIcon,- MapPinIcon,- MegaphoneIcon,- MonitorCogIcon,- MonitorIcon,- PlusIcon,- RadioIcon,- ServerIcon,- ShareIcon,- SlidersHorizontalIcon,- SmartphoneIcon,- TabletIcon,- TabletSmartphoneIcon,- TagIcon,- Trash2Icon,- TvIcon,- WatchIcon,-} from 'lucide-react'-import { useState, useEffect, useCallback, useRef, useMemo, Fragment, ReactNode } from 'react'+import { CheckIcon, ChevronsUpDownIcon, PlusIcon, SlidersHorizontalIcon, Trash2Icon } from 'lucide-react'+import { useState, useEffect, useCallback, Fragment } from 'react'import { useTranslation } from 'react-i18next'import { useNavigate, useSearchParams } from 'react-router'import { getFilters, getErrorsFilters, getVersionFilters } from '~/api'-import {- FILTERS_PANELS_ORDER,- ERRORS_FILTERS_PANELS_ORDER,- BROWSER_LOGO_MAP,- OS_LOGO_MAP,- OS_LOGO_MAP_DARK,-} from '~/lib/constants'+import { FILTERS_PANELS_ORDER, ERRORS_FILTERS_PANELS_ORDER } from '~/lib/constants'import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'import { useTheme } from '~/providers/ThemeProvider'-import Flag from '~/ui/Flag'-import Spin from '~/ui/icons/Spin'+import FilterValueInput, { filterCategoryIcons, createVersionValue, parseVersionValue } from '~/ui/FilterValueInput'import Modal from '~/ui/Modal'import countries from '~/utils/isoCountries'import { Filter as FilterType } from '../interfaces/traffic'import { isFilterValid } from '../utils/filters'-// Icon mapping for filter categories-const filterCategoryIcons: Record<string, ReactNode> = {- cc: <MapPinIcon className='size-4' strokeWidth={1.5} />,- rg: <MapIcon className='size-4' strokeWidth={1.5} />,- ct: <BuildingIcon className='size-4' strokeWidth={1.5} />,- pg: <FileTextIcon className='size-4' strokeWidth={1.5} />,- entryPage: <LogInIcon className='size-4' strokeWidth={1.5} />,- exitPage: <LogOutIcon className='size-4' strokeWidth={1.5} />,- host: <ServerIcon className='size-4' strokeWidth={1.5} />,- br: <CompassIcon className='size-4' strokeWidth={1.5} />,- brv: <CompassIcon className='size-4' strokeWidth={1.5} />,- os: <MonitorCogIcon className='size-4' strokeWidth={1.5} />,- osv: <MonitorCogIcon className='size-4' strokeWidth={1.5} />,- ref: <LinkIcon className='size-4' strokeWidth={1.5} />,- so: <ShareIcon className='size-4' strokeWidth={1.5} />,- me: <RadioIcon className='size-4' strokeWidth={1.5} />,- ca: <MegaphoneIcon className='size-4' strokeWidth={1.5} />,- te: <TagIcon className='size-4' strokeWidth={1.5} />,- co: <FileIcon className='size-4' strokeWidth={1.5} />,- lc: <LanguagesIcon className='size-4' strokeWidth={1.5} />,- dv: <TabletSmartphoneIcon className='size-4' strokeWidth={1.5} />,-}--const ITEM_HEIGHT = 36-export const getFiltersUrlParams = (filters: FilterType[],newFilters: FilterType[],@@ -165,340 +98,6 @@ const operatorToFilter = (operator: FilterOperator): { isExclusive: boolean; isC}}-// Device icon mapping-const deviceIconMapping: Record<string, ReactNode> = {- desktop: <MonitorIcon className='size-4' strokeWidth={1.5} />,- mobile: <SmartphoneIcon className='size-4' strokeWidth={1.5} />,- tablet: <TabletIcon className='size-4' strokeWidth={1.5} />,- smarttv: <TvIcon className='size-4' strokeWidth={1.5} />,- console: <Gamepad2Icon className='size-4' strokeWidth={1.5} />,- wearable: <WatchIcon className='size-4' strokeWidth={1.5} />,- embedded: <CpuIcon className='size-4' strokeWidth={1.5} />,-}--interface ValueInputProps {- items: string[]- value: string- onChange: (value: string) => void- placeholder: string- column: string- language: string- disabled?: boolean- isLoading?: boolean- theme: string-}--const ValueInput = ({- items,- value,- onChange,- placeholder,- column,- language,- disabled,- isLoading,- theme,-}: ValueInputProps) => {- const { t } = useTranslation('common')- const [inputValue, setInputValue] = useState('')- const [isOpen, setIsOpen] = useState(false)- const listRef = useRef<HTMLDivElement>(null)- const inputRef = useRef<HTMLInputElement>(null)- const containerRef = useRef<HTMLDivElement>(null)-- // Close dropdown when clicking outside- useEffect(() => {- const handleClickOutside = (event: MouseEvent) => {- if (containerRef.current && !containerRef.current.contains(event.target as Node)) {- setIsOpen(false)- }- }- document.addEventListener('mousedown', handleClickOutside)- return () => document.removeEventListener('mousedown', handleClickOutside)- }, [])-- const getLabelForItem = useCallback(- (item: string) => {- if (column === 'cc') {- return countries.getName(item, language) || item- }- // Handle combined version values (e.g., "Chrome|||120.5" -> "Chrome 120.5")- if (column === 'brv' || column === 'osv') {- const parsed = parseVersionValue(item)- if (parsed) {- return `${parsed.parent} ${parsed.version}`- }- }- return item || t('common.notSet')- },- [column, language, t],- )-- const getIconForItem = useCallback(- (item: string): ReactNode => {- if (column === 'cc') {- return <Flag className='shrink-0 rounded-xs' country={item} size={16} alt='' aria-hidden='true' />- }-- if (column === 'br') {- // @ts-expect-error - dynamic key access- const logoUrl = BROWSER_LOGO_MAP[item]- if (logoUrl) {- return <img src={logoUrl} className='size-4 shrink-0' alt='' />- }- return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />- }-- // For browser versions, show browser icon- if (column === 'brv') {- const parsed = parseVersionValue(item)- if (parsed) {- // @ts-expect-error - dynamic key access- const logoUrl = BROWSER_LOGO_MAP[parsed.parent]- if (logoUrl) {- return <img src={logoUrl} className='size-4 shrink-0' alt='' />- }- }- return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />- }-- if (column === 'os') {- // @ts-expect-error - dynamic key access- const logoPathLight = OS_LOGO_MAP[item]- // @ts-expect-error - dynamic key access- const logoPathDark = OS_LOGO_MAP_DARK[item]- let logoPath = theme === 'dark' ? logoPathDark : logoPathLight- logoPath ||= logoPathLight-- if (logoPath) {- return <img src={`/${logoPath}`} className='size-4 shrink-0 dark:fill-gray-50' alt='' />- }- return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />- }-- // For OS versions, show OS icon- if (column === 'osv') {- const parsed = parseVersionValue(item)- if (parsed) {- // @ts-expect-error - dynamic key access- const logoPathLight = OS_LOGO_MAP[parsed.parent]- // @ts-expect-error - dynamic key access- const logoPathDark = OS_LOGO_MAP_DARK[parsed.parent]- let logoPath = theme === 'dark' ? logoPathDark : logoPathLight- logoPath ||= logoPathLight-- if (logoPath) {- return <img src={`/${logoPath}`} className='size-4 shrink-0 dark:fill-gray-50' alt='' />- }- }- return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />- }-- if (column === 'dv') {- const icon = deviceIconMapping[item]- if (icon) {- return <span className='shrink-0'>{icon}</span>- }- return <CircleQuestionMark className='size-4 shrink-0' strokeWidth={1.5} />- }-- return null- },- [column, theme],- )-- // Get icon for the currently selected value (for display in input)- const selectedIcon = value ? getIconForItem(value) : null- const displayValue = value ? getLabelForItem(value) : ''-- const filteredItems = useMemo(() => {- // When dropdown is closed or input is empty, show all items- if (!isOpen || _isEmpty(inputValue)) return items- return items.filter((item) => {- const labelValue = getLabelForItem(item)- return _includes(_toLower(labelValue), _toLower(inputValue))- })- }, [items, inputValue, isOpen, getLabelForItem])-- const virtualizer = useVirtualizer({- count: filteredItems.length,- getScrollElement: () => listRef.current,- estimateSize: () => ITEM_HEIGHT,- overscan: 15,- })-- const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {- const newValue = e.target.value- setInputValue(newValue)- }-- const handleSelectItem = (item: string) => {- setInputValue('')- onChange(item)- setIsOpen(false)- }-- const handleFocus = () => {- // When focusing, initialize input with the display value so user can edit it- if (value) {- setInputValue(displayValue)- }- setIsOpen(true)- }-- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {- if (e.key === 'Enter') {- e.preventDefault()- if (inputValue.trim()) {- // For country codes, try to find the alpha2 code- if (column === 'cc') {- const alpha2 = countries.getAlpha2Code(inputValue, language)- if (alpha2) {- onChange(alpha2)- } else {- // Check if it's already a valid alpha2 code- const validCode = items.find((item) => _toLower(item) === _toLower(inputValue))- onChange(validCode || inputValue.trim())- }- } else {- // Check if input matches an existing item (case insensitive)- const matchingItem = items.find((item) => _toLower(getLabelForItem(item)) === _toLower(inputValue.trim()))- onChange(matchingItem || inputValue.trim())- }- setInputValue('')- setIsOpen(false)- }- } else if (e.key === 'Escape') {- setInputValue('')- setIsOpen(false)- }- }-- // Determine if we should show the icon in the input (when closed and value is selected)- const showIconInInput = !isOpen && value && selectedIcon-- return (- <div ref={containerRef} className='relative flex-1'>- <div className='relative'>- {showIconInInput ? (- <span className='pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2.5'>{selectedIcon}</span>- ) : null}- <input- ref={inputRef}- type='text'- className={cx(- 'w-full rounded-md border border-gray-300 bg-white py-2 pr-8 text-sm transition-colors placeholder:text-gray-400 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:placeholder:text-gray-500',- {- 'cursor-not-allowed opacity-60': disabled,- 'pl-8': showIconInInput,- 'pl-3': !showIconInInput,- },- )}- placeholder={placeholder}- value={isOpen ? inputValue : displayValue}- onChange={handleInputChange}- onFocus={handleFocus}- onKeyDown={handleKeyDown}- disabled={disabled}- />- <span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>- {isLoading ? <Spin className='size-4' /> : <ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />}- </span>- </div>-- {isOpen && !disabled ? (- <div className='absolute z-50 mt-1 w-full min-w-[200px] rounded-md bg-white text-sm shadow-lg ring-1 ring-black/10 dark:bg-slate-800'>- {isLoading ? (- <div className='flex items-center justify-center gap-2 px-4 py-3 text-gray-500 dark:text-gray-400'>- <Spin className='size-4' />- {t('common.loading')}- </div>- ) : _isEmpty(filteredItems) ? (- <div className='px-4 py-3'>- {inputValue.trim() ? (- <button- type='button'- onClick={() => {- if (column === 'cc') {- const alpha2 = countries.getAlpha2Code(inputValue, language)- onChange(alpha2 || inputValue.trim())- } else {- onChange(inputValue.trim())- }- setIsOpen(false)- }}- className='flex w-full items-center justify-center gap-1.5 rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-indigo-700'- >- <PlusIcon className='h-4 w-4' />- {t('project.filterUseValue', { value: inputValue.trim() })}- </button>- ) : (- <span className='text-gray-500 dark:text-gray-400'>{t('common.nothingFound')}</span>- )}- </div>- ) : (- <div ref={listRef} className='max-h-48 overflow-auto py-1'>- <div- style={{- height: `${virtualizer.getTotalSize()}px`,- width: '100%',- position: 'relative',- }}- >- {virtualizer.getVirtualItems().map((virtualItem) => {- const item = filteredItems[virtualItem.index]- const labelValue = getLabelForItem(item)- const selected = item === value- const icon = getIconForItem(item)-- return (- <button- key={item}- type='button'- onClick={() => handleSelectItem(item)}- className={cx(- 'absolute right-0 left-0 mx-1 flex cursor-pointer items-center gap-2 rounded-md py-2 pr-4 pl-2 text-left transition-colors select-none hover:bg-gray-100 dark:hover:bg-slate-700',- {- 'bg-indigo-50 dark:bg-indigo-900/30': selected,- 'text-gray-700 dark:text-gray-50': !selected,- },- )}- style={{- top: 0,- transform: `translateY(${virtualItem.start}px)`,- height: `${virtualItem.size}px`,- }}- >- {icon}- <span className={cx('block truncate', { 'font-medium': selected })}>{labelValue}</span>- {selected ? (- <CheckIcon className='ml-auto h-4 w-4 shrink-0 text-indigo-600 dark:text-indigo-400' />- ) : null}- </button>- )- })}- </div>- </div>- )}- </div>- ) : null}- </div>- )-}--// Special separator for combined version values (e.g., "Chrome|||120.5")-const VERSION_SEPARATOR = '|||'--// Helper to create combined version value-const createVersionValue = (parent: string, version: string) => `${parent}${VERSION_SEPARATOR}${version}`--// Helper to parse combined version value-const parseVersionValue = (value: string): { parent: string; version: string } | null => {- if (!value.includes(VERSION_SEPARATOR)) return null- const [parent, version] = value.split(VERSION_SEPARATOR)- return { parent, version }-}-interface SearchFiltersProps {showModal: booleansetShowModal: (show: boolean) => void@@ -854,7 +453,7 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se</Listbox>{/* Freeform Value Input with Suggestions */}- <ValueInput+ <FilterValueInputitems={filterValuesCache[row.column] || []}value={row.value}onChange={(value) => updateFilterRow(row.id, 'value', value)}diff --git a/web/app/ui/FilterValueInput.tsx b/web/app/ui/FilterValueInput.tsxnew file mode 100644index 000000000..3371e253a--- /dev/null+++ b/web/app/ui/FilterValueInput.tsx@@ -0,0 +1,406 @@+import { useVirtualizer } from '@tanstack/react-virtual'+import cx from 'clsx'+import _includes from 'lodash/includes'+import _isEmpty from 'lodash/isEmpty'+import _toLower from 'lodash/toLower'+import {+ BuildingIcon,+ CheckIcon,+ ChevronsUpDownIcon,+ CircleQuestionMark,+ CompassIcon,+ CpuIcon,+ FileIcon,+ FileTextIcon,+ Gamepad2Icon,+ GlobeIcon,+ LanguagesIcon,+ LinkIcon,+ LogInIcon,+ LogOutIcon,+ MapIcon,+ MapPinIcon,+ MegaphoneIcon,+ MonitorCogIcon,+ MonitorIcon,+ PlusIcon,+ RadioIcon,+ ServerIcon,+ ShareIcon,+ SmartphoneIcon,+ TabletIcon,+ TabletSmartphoneIcon,+ TagIcon,+ TvIcon,+ WatchIcon,+} from 'lucide-react'+import { useState, useEffect, useCallback, useRef, useMemo, ReactNode } from 'react'+import { useTranslation } from 'react-i18next'++import { BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'+import Flag from '~/ui/Flag'+import Spin from '~/ui/icons/Spin'+import countries from '~/utils/isoCountries'++const ITEM_HEIGHT = 36++// Icon mapping for filter categories+export const filterCategoryIcons: Record<string, ReactNode> = {+ cc: <MapPinIcon className='size-4' strokeWidth={1.5} />,+ rg: <MapIcon className='size-4' strokeWidth={1.5} />,+ ct: <BuildingIcon className='size-4' strokeWidth={1.5} />,+ pg: <FileTextIcon className='size-4' strokeWidth={1.5} />,+ entryPage: <LogInIcon className='size-4' strokeWidth={1.5} />,+ exitPage: <LogOutIcon className='size-4' strokeWidth={1.5} />,+ host: <ServerIcon className='size-4' strokeWidth={1.5} />,+ br: <CompassIcon className='size-4' strokeWidth={1.5} />,+ brv: <CompassIcon className='size-4' strokeWidth={1.5} />,+ os: <MonitorCogIcon className='size-4' strokeWidth={1.5} />,+ osv: <MonitorCogIcon className='size-4' strokeWidth={1.5} />,+ ref: <LinkIcon className='size-4' strokeWidth={1.5} />,+ so: <ShareIcon className='size-4' strokeWidth={1.5} />,+ me: <RadioIcon className='size-4' strokeWidth={1.5} />,+ ca: <MegaphoneIcon className='size-4' strokeWidth={1.5} />,+ te: <TagIcon className='size-4' strokeWidth={1.5} />,+ co: <FileIcon className='size-4' strokeWidth={1.5} />,+ lc: <LanguagesIcon className='size-4' strokeWidth={1.5} />,+ dv: <TabletSmartphoneIcon className='size-4' strokeWidth={1.5} />,+}++// Device icon mapping+export const deviceIconMapping: Record<string, ReactNode> = {+ desktop: <MonitorIcon className='size-4' strokeWidth={1.5} />,+ mobile: <SmartphoneIcon className='size-4' strokeWidth={1.5} />,+ tablet: <TabletIcon className='size-4' strokeWidth={1.5} />,+ smarttv: <TvIcon className='size-4' strokeWidth={1.5} />,+ console: <Gamepad2Icon className='size-4' strokeWidth={1.5} />,+ wearable: <WatchIcon className='size-4' strokeWidth={1.5} />,+ embedded: <CpuIcon className='size-4' strokeWidth={1.5} />,+}++// Special separator for combined version values (e.g., "Chrome|||120.5")+export const VERSION_SEPARATOR = '|||'++// Helper to create combined version value+export const createVersionValue = (parent: string, version: string) => `${parent}${VERSION_SEPARATOR}${version}`++// Helper to parse combined version value+export const parseVersionValue = (value: string): { parent: string; version: string } | null => {+ if (!value.includes(VERSION_SEPARATOR)) return null+ const [parent, version] = value.split(VERSION_SEPARATOR)+ return { parent, version }+}++export interface FilterValueInputProps {+ items: string[]+ value: string+ onChange: (value: string) => void+ placeholder: string+ column: string+ language: string+ disabled?: boolean+ isLoading?: boolean+ theme: string+ className?: string+}++const FilterValueInput = ({+ items,+ value,+ onChange,+ placeholder,+ column,+ language,+ disabled,+ isLoading,+ theme,+ className,+}: FilterValueInputProps) => {+ const { t } = useTranslation('common')+ const [inputValue, setInputValue] = useState('')+ const [isOpen, setIsOpen] = useState(false)+ const listRef = useRef<HTMLDivElement>(null)+ const inputRef = useRef<HTMLInputElement>(null)+ const containerRef = useRef<HTMLDivElement>(null)++ // Close dropdown when clicking outside+ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ if (containerRef.current && !containerRef.current.contains(event.target as Node)) {+ setIsOpen(false)+ }+ }+ document.addEventListener('mousedown', handleClickOutside)+ return () => document.removeEventListener('mousedown', handleClickOutside)+ }, [])++ const getLabelForItem = useCallback(+ (item: string) => {+ if (column === 'cc') {+ return countries.getName(item, language) || item+ }+ // Handle combined version values (e.g., "Chrome|||120.5" -> "Chrome 120.5")+ if (column === 'brv' || column === 'osv') {+ const parsed = parseVersionValue(item)+ if (parsed) {+ return `${parsed.parent} ${parsed.version}`+ }+ }+ return item || t('common.notSet')+ },+ [column, language, t],+ )++ const getIconForItem = useCallback(+ (item: string): ReactNode => {+ if (column === 'cc') {+ return <Flag className='shrink-0 rounded-xs' country={item} size={16} alt='' aria-hidden='true' />+ }++ if (column === 'br') {+ // @ts-expect-error - dynamic key access+ const logoUrl = BROWSER_LOGO_MAP[item]+ if (logoUrl) {+ return <img src={logoUrl} className='size-4 shrink-0' alt='' />+ }+ return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />+ }++ // For browser versions, show browser icon+ if (column === 'brv') {+ const parsed = parseVersionValue(item)+ if (parsed) {+ // @ts-expect-error - dynamic key access+ const logoUrl = BROWSER_LOGO_MAP[parsed.parent]+ if (logoUrl) {+ return <img src={logoUrl} className='size-4 shrink-0' alt='' />+ }+ }+ return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />+ }++ if (column === 'os') {+ // @ts-expect-error - dynamic key access+ const logoPathLight = OS_LOGO_MAP[item]+ // @ts-expect-error - dynamic key access+ const logoPathDark = OS_LOGO_MAP_DARK[item]+ let logoPath = theme === 'dark' ? logoPathDark : logoPathLight+ logoPath ||= logoPathLight++ if (logoPath) {+ return <img src={`/${logoPath}`} className='size-4 shrink-0 dark:fill-gray-50' alt='' />+ }+ return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />+ }++ // For OS versions, show OS icon+ if (column === 'osv') {+ const parsed = parseVersionValue(item)+ if (parsed) {+ // @ts-expect-error - dynamic key access+ const logoPathLight = OS_LOGO_MAP[parsed.parent]+ // @ts-expect-error - dynamic key access+ const logoPathDark = OS_LOGO_MAP_DARK[parsed.parent]+ let logoPath = theme === 'dark' ? logoPathDark : logoPathLight+ logoPath ||= logoPathLight++ if (logoPath) {+ return <img src={`/${logoPath}`} className='size-4 shrink-0 dark:fill-gray-50' alt='' />+ }+ }+ return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />+ }++ if (column === 'dv') {+ const icon = deviceIconMapping[item]+ if (icon) {+ return <span className='shrink-0'>{icon}</span>+ }+ return <CircleQuestionMark className='size-4 shrink-0' strokeWidth={1.5} />+ }++ return null+ },+ [column, theme],+ )++ // Get icon for the currently selected value (for display in input)+ const selectedIcon = value ? getIconForItem(value) : null+ const displayValue = value ? getLabelForItem(value) : ''++ const filteredItems = useMemo(() => {+ // When dropdown is closed or input is empty, show all items+ if (!isOpen || _isEmpty(inputValue)) return items+ return items.filter((item) => {+ const labelValue = getLabelForItem(item)+ return _includes(_toLower(labelValue), _toLower(inputValue))+ })+ }, [items, inputValue, isOpen, getLabelForItem])++ const virtualizer = useVirtualizer({+ count: filteredItems.length,+ getScrollElement: () => listRef.current,+ estimateSize: () => ITEM_HEIGHT,+ overscan: 15,+ })++ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ const newValue = e.target.value+ setInputValue(newValue)+ }++ const handleSelectItem = (item: string) => {+ setInputValue('')+ onChange(item)+ setIsOpen(false)+ }++ const handleFocus = () => {+ // When focusing, initialize input with the display value so user can edit it+ if (value) {+ setInputValue(displayValue)+ }+ setIsOpen(true)+ }++ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === 'Enter') {+ e.preventDefault()+ if (inputValue.trim()) {+ // For country codes, try to find the alpha2 code+ if (column === 'cc') {+ const alpha2 = countries.getAlpha2Code(inputValue, language)+ if (alpha2) {+ onChange(alpha2)+ } else {+ // Check if it's already a valid alpha2 code+ const validCode = items.find((item) => _toLower(item) === _toLower(inputValue))+ onChange(validCode || inputValue.trim())+ }+ } else {+ // Check if input matches an existing item (case insensitive)+ const matchingItem = items.find((item) => _toLower(getLabelForItem(item)) === _toLower(inputValue.trim()))+ onChange(matchingItem || inputValue.trim())+ }+ setInputValue('')+ setIsOpen(false)+ }+ } else if (e.key === 'Escape') {+ setInputValue('')+ setIsOpen(false)+ }+ }++ // Determine if we should show the icon in the input (when closed and value is selected)+ const showIconInInput = !isOpen && value && selectedIcon++ return (+ <div ref={containerRef} className={cx('relative flex-1', className)}>+ <div className='relative'>+ {showIconInInput ? (+ <span className='pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2.5'>{selectedIcon}</span>+ ) : null}+ <input+ ref={inputRef}+ type='text'+ className={cx(+ 'w-full rounded-md border border-gray-300 bg-white py-2 pr-8 text-sm transition-colors placeholder:text-gray-400 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:placeholder:text-gray-500',+ {+ 'cursor-not-allowed opacity-60': disabled,+ 'pl-8': showIconInInput,+ 'pl-3': !showIconInInput,+ },+ )}+ placeholder={placeholder}+ value={isOpen ? inputValue : displayValue}+ onChange={handleInputChange}+ onFocus={handleFocus}+ onKeyDown={handleKeyDown}+ disabled={disabled}+ />+ <span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>+ {isLoading ? <Spin className='size-4' /> : <ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />}+ </span>+ </div>++ {isOpen && !disabled ? (+ <div className='absolute z-50 mt-1 w-full min-w-[200px] rounded-md bg-white text-sm shadow-lg ring-1 ring-black/10 dark:bg-slate-800'>+ {isLoading ? (+ <div className='flex items-center justify-center gap-2 px-4 py-3 text-gray-500 dark:text-gray-400'>+ <Spin className='size-4' />+ {t('common.loading')}+ </div>+ ) : _isEmpty(filteredItems) ? (+ <div className='px-4 py-3'>+ {inputValue.trim() ? (+ <button+ type='button'+ onClick={() => {+ if (column === 'cc') {+ const alpha2 = countries.getAlpha2Code(inputValue, language)+ onChange(alpha2 || inputValue.trim())+ } else {+ onChange(inputValue.trim())+ }+ setIsOpen(false)+ }}+ className='flex w-full items-center justify-center gap-1.5 rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-indigo-700'+ >+ <PlusIcon className='h-4 w-4' />+ {t('project.filterUseValue', { value: inputValue.trim() })}+ </button>+ ) : (+ <span className='text-gray-500 dark:text-gray-400'>{t('common.nothingFound')}</span>+ )}+ </div>+ ) : (+ <div ref={listRef} className='max-h-48 overflow-auto py-1'>+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ width: '100%',+ position: 'relative',+ }}+ >+ {virtualizer.getVirtualItems().map((virtualItem) => {+ const item = filteredItems[virtualItem.index]+ const labelValue = getLabelForItem(item)+ const selected = item === value+ const icon = getIconForItem(item)++ return (+ <button+ key={item}+ type='button'+ onClick={() => handleSelectItem(item)}+ className={cx(+ 'absolute right-0 left-0 mx-1 flex cursor-pointer items-center gap-2 rounded-md py-2 pr-4 pl-2 text-left transition-colors select-none hover:bg-gray-100 dark:hover:bg-slate-700',+ {+ 'bg-indigo-50 dark:bg-indigo-900/30': selected,+ 'text-gray-700 dark:text-gray-50': !selected,+ },+ )}+ style={{+ top: 0,+ transform: `translateY(${virtualItem.start}px)`,+ height: `${virtualItem.size}px`,+ }}+ >+ {icon}+ <span className={cx('block truncate', { 'font-medium': selected })}>{labelValue}</span>+ {selected ? (+ <CheckIcon className='ml-auto h-4 w-4 shrink-0 text-indigo-600 dark:text-indigo-400' />+ ) : null}+ </button>+ )+ })}+ </div>+ </div>+ )}+ </div>+ ) : null}+ </div>+ )+}++export default FilterValueInputdiff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex aa5b7f4b0..261f02e78 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -884,6 +884,8 @@"alertsDesc": "Automated alerts is a powerful tool that notifies you when some events occur on your website.\nWe can automatically monitor your project for traffic spikes and notify you via Telegram, Slack or Discord.","goals": "Goals","goalsDesc": "Conversion goals help you track important user actions on your website.\nDefine pageview goals or custom event goals to measure how many visitors complete specific actions.",+ "featureFlags": "Feature Flags",+ "featureFlagsDesc": "Feature flags allow you to toggle features for cohorts or individuals.\nTest the impact before rolling out to everyone.","askAi": "Ask AI","webAnalytics": "Web analytics","productAnalytics": "Product analytics",@@ -999,6 +1001,53 @@"noData": "No conversion data yet","noChartData": "No chart data available for the selected period"},+ "featureFlags": {+ "title": "Feature Flags",+ "description": "Feature flags allow you to toggle features for cohorts or individuals.\nTest the impact of new features before rolling out to everyone.",+ "add": "Add feature flag",+ "addFlag": "Add Flag",+ "filterFlags": "Filter flags",+ "noFlagsMatchFilter": "No flags match your filter",+ "create": "Create flag",+ "save": "Save",+ "delete": "Delete flag",+ "deleted": "Feature flag has been deleted",+ "created": "Feature flag has been created",+ "updated": "Feature flag has been updated",+ "createTitle": "Create new feature flag",+ "editTitle": "Edit feature flag",+ "deleteConfirmTitle": "Delete this feature flag?",+ "deleteConfirmMessage": "This action is irreversible. The feature flag and all its data will be permanently deleted.",+ "key": "Flag key",+ "keyHint": "Use kebab-case (e.g., my-new-feature)",+ "descriptionLabel": "Description",+ "descriptionPlaceholder": "What does this feature flag control?",+ "flagType": "Flag type",+ "boolean": "Boolean",+ "rollout": "Rollout",+ "rolloutPercentage": "Rollout percentage",+ "targetingRules": "Targeting rules",+ "addRule": "Add rule",+ "noTargetingRules": "No targeting rules. Flag will be served to all visitors.",+ "is": "is",+ "isNot": "is not",+ "valuePlaceholder": "Value",+ "enableFlag": "Enable feature flag",+ "enableFlagHint": "When disabled, the flag will always return false.",+ "enabled": "Enabled",+ "disabled": "Disabled",+ "enable": "Enable",+ "disable": "Disable",+ "flagEnabled": "Feature flag enabled",+ "flagDisabled": "Feature flag disabled",+ "evaluations": "Evaluations",+ "visitors": "Visitors",+ "trueRate": "True rate",+ "noStats": "No data yet",+ "targetingRulesCount": "{{count}} targeting rule(s)",+ "howToImplement": "How to implement",+ "implementationDescription": "Use the code snippets below to check feature flags in your application."+ },"error": {"status": {"active": "Active",