1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use gpui::{AppContext, Subscription, ViewContext};

#[derive(Default)]
struct FeatureFlags {
    flags: Vec<String>,
    staff: bool,
}

impl FeatureFlags {
    fn has_flag(&self, flag: &str) -> bool {
        self.staff || self.flags.iter().find(|f| f.as_str() == flag).is_some()
    }
}

pub trait FeatureFlag {
    const NAME: &'static str;
}

pub enum ChannelsAlpha {}

impl FeatureFlag for ChannelsAlpha {
    const NAME: &'static str = "channels_alpha";
}

pub trait FeatureFlagViewExt<V: 'static> {
    fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
    where
        F: Fn(bool, &mut V, &mut ViewContext<V>) + Send + Sync + 'static;
}

impl<V> FeatureFlagViewExt<V> for ViewContext<'_, V>
where
    V: 'static + Send + Sync,
{
    fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
    where
        F: Fn(bool, &mut V, &mut ViewContext<V>) + Send + Sync + 'static,
    {
        self.observe_global::<FeatureFlags>(move |v, cx| {
            let feature_flags = cx.global::<FeatureFlags>();
            callback(feature_flags.has_flag(<T as FeatureFlag>::NAME), v, cx);
        })
    }
}

pub trait FeatureFlagAppExt {
    fn update_flags(&mut self, staff: bool, flags: Vec<String>);
    fn set_staff(&mut self, staff: bool);
    fn has_flag<T: FeatureFlag>(&self) -> bool;
    fn is_staff(&self) -> bool;
}

impl FeatureFlagAppExt for AppContext {
    fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
        let feature_flags = self.default_global::<FeatureFlags>();
        feature_flags.staff = staff;
        feature_flags.flags = flags;
    }

    fn set_staff(&mut self, staff: bool) {
        let feature_flags = self.default_global::<FeatureFlags>();
        feature_flags.staff = staff;
    }

    fn has_flag<T: FeatureFlag>(&self) -> bool {
        if self.has_global::<FeatureFlags>() {
            self.global::<FeatureFlags>().has_flag(T::NAME)
        } else {
            false
        }
    }

    fn is_staff(&self) -> bool {
        if self.has_global::<FeatureFlags>() {
            return self.global::<FeatureFlags>().staff;
        } else {
            false
        }
    }
}