Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions frontend/src/lib/logic/featureFlagLogic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,45 @@ import posthog from 'posthog-js'

type FeatureFlagsSet = { [flag: string]: boolean }

const eventsNotified: Record<string, boolean> = {}
function notifyFlagIfNeeded(flag: string, flagState: boolean): void {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why aren't we just using the native posthog.isFeatureEnabled instead of featureFlagLogic?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we put this inside a react render component, then in my tests, the action and navigation feature flags were checked 6 times per render and hundreds of times when browsing around. That's too many events.

if (!eventsNotified[flag]) {
posthog.capture('$feature_flag_called', {
$feature_flag: flag,
$feature_flag_response: flagState,
})
eventsNotified[flag] = true
}
}

function spyOnFeatureFlags(featureFlags: FeatureFlagsSet): FeatureFlagsSet {
if (typeof window.Proxy !== 'undefined') {
return new Proxy(
{},
{
get(_, flag) {
const flagString = flag.toString()
const flagState = !!featureFlags[flagString]
notifyFlagIfNeeded(flagString, flagState)
return flagState
},
}
)
} else {
// Fallback for IE11. Won't track "false" results. ¯\_(ツ)_/¯
const flags: FeatureFlagsSet = {}
for (const flag of Object.keys(featureFlags)) {
Object.defineProperty(flags, flag, {
get: function () {
notifyFlagIfNeeded(flag, true)
return true
},
})
}
return flags
}
}

export const featureFlagLogic = kea<featureFlagLogicType<PostHog, FeatureFlagsSet>>({
actions: {
setFeatureFlags: (featureFlags: string[]) => ({ featureFlags }),
Expand All @@ -19,12 +58,12 @@ export const featureFlagLogic = kea<featureFlagLogicType<PostHog, FeatureFlagsSe
featureFlags: [
{} as FeatureFlagsSet,
{
setFeatureFlags: (_: FeatureFlagsSet, { featureFlags }: { featureFlags: string[] }) => {
setFeatureFlags: (_, { featureFlags }) => {
const flags: FeatureFlagsSet = {}
for (const flag of featureFlags) {
flags[flag] = true
}
return flags
return spyOnFeatureFlags(flags)
},
},
],
Expand Down