aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/lib/extract_callback.js
blob: fbd8090d99f6f68c98ef2ec0bf6e523850ff9bfb (plain)
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
81
export default function extractCallback(cmd, payload, root = window) {
    var command = cmd,
        last_chunk = null,
        callback = root,
        previous = null;

    // Try to decode URI component in case it is encoded
    try {
        command = window.decodeURIComponent(command);
    } catch {
        // No action necessary
    }

    // Try to parse value as JSON (value might be {func: 'foo', payload: {}})
    try {
        command = JSON.parse(command);
    } catch {
        command = { func: command };
    }

    // Check for invalid call
    if (command.func === undefined) {
        throw 'Dialog: Invalid value for X-Dialog-Execute';
    }

    // Populate payload if not set
    if (command.payload === undefined) {
        command.payload = payload;
    }

    // Find callback
    command.func.trim().split(/\./).forEach(chunk => {
        // Check if last chunk was unfinished
        if (last_chunk !== null) {
            chunk = last_chunk + '.' + chunk;
            last_chunk = null;
        }

        // Check for not finished/closed chunk
        if (chunk.match(/\([^)]*$/)) {
            last_chunk = chunk;
            return;
        }

        previous = callback;

        var match = chunk.match(/\((.*)\);?$/),
            parameters = null;

        if (match !== null) {
            chunk = chunk.replace(match[0], '');
            try {
                parameters = JSON.parse('[' + match[1].replace(/'/g, '"') + ']');
            } catch {
                console.log('error parsing json', match);
            }
        }

        if (callback === null || callback[chunk] === undefined) {
            console.log('Error: Undefined callback ' + cmd);
            return;
        }

        if (typeof callback[chunk] === 'function' && parameters !== null) {
            callback = callback[chunk].apply(callback, parameters);
        } else {
            callback = callback[chunk];
        }
    });

    // Check callback
    if (typeof callback !== 'function') {
        return function() {
            return callback;
        };
    }

    return function(p) {
        return callback.apply(previous, [p || command.payload]);
    };
}