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
use pagetop::prelude::*;

new_handle!(MODULE_JQUERY);

static_locales!(LOCALES_JQUERY);

static_files!(jquery);

// Library version.
const VERSION_JQUERY: &str = "3.6.0";

// Context parameter.
const PARAM_JQUERY: &str = "jquery.lib";

/// Implements [`ModuleTrait`](pagetop::core::module::ModuleTrait) and specific module API.
pub struct JQuery;

impl ModuleTrait for JQuery {
    fn handle(&self) -> Handle {
        MODULE_JQUERY
    }

    fn name(&self) -> L10n {
        L10n::t("module_name", &LOCALES_JQUERY)
    }

    fn description(&self) -> L10n {
        L10n::t("module_description", &LOCALES_JQUERY)
    }

    fn actions(&self) -> Vec<Action> {
        vec![action!(ActionAfterPrepareBody => after_prepare_body)]
    }

    fn configure_service(&self, scfg: &mut service::web::ServiceConfig) {
        static_files_service!(scfg, "/jquery", jquery);
    }
}

impl JQuery {
    pub fn enable_jquery(&self, cx: &mut Context) -> &Self {
        cx.set_param::<bool>(PARAM_JQUERY, true);
        self
    }

    pub fn disable_jquery(&self, cx: &mut Context) -> &Self {
        cx.set_param::<bool>(PARAM_JQUERY, false);
        self
    }
}

fn after_prepare_body(page: &mut Page) {
    if let Some(true) = page.context().get_param::<bool>(PARAM_JQUERY) {
        page.context().alter(ContextOp::AddJavaScript(
            JavaScript::at("/jquery/jquery.min.js")
                .with_version(VERSION_JQUERY)
                .with_weight(-99)
                .with_mode(ModeJS::Normal),
        ));
    }
}