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

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

    // Try to parse value as JSON (value might be {func: 'foo', payload: {}})
    try {
        command = $.parseJSON(command);
    } catch (e) {
        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
    chunks = command.func.trim().split(/\./);
    $.each(chunks, function(index, 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 = $.parseJSON('[' + match[1].replace(/'/g, '"') + ']');
            } catch (e) {
                console.log('error parsing json', match);
            }
        }

        if (callback[chunk] === undefined) {
            throw 'Error: Undefined callback ' + cmd;
        }

        if ($.isFunction(callback[chunk]) && parameters !== null) {
            callback = callback[chunk].apply(callback, parameters);
        } else {
            callback = callback[chunk];
        }
    });

    // Check callback
    if (!$.isFunction(callback)) {
        return function() {
            return callback;
        };
    }

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