Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/lib/sugar-web/graphics/icon.js
blob: f2c07915a1ca50844f361713a5bd4be4f3d30489 (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
define(function () {
    var icon = {};

    function changeColors(iconData, fillColor, strokeColor) {
        var re;

        if (fillColor) {
            re = /(<!ENTITY fill_color ")(.*)(">)/;
            iconData = iconData.replace(re, "$1" + fillColor + "$3");
        }

        if (strokeColor) {
            re = /(<!ENTITY stroke_color ")(.*)(">)/;
            iconData = iconData.replace(re, "$1" + strokeColor + "$3");
        }

        return iconData;
    }

    icon.load = function (iconInfo, callback) {
        var source;
        var dataHeader = "data:image/svg+xml,";

        if ("uri" in iconInfo) {
            source = iconInfo.uri;
        } else if ("name" in iconInfo) {
            source = "lib/graphics/icons/" + iconInfo.name + ".svg";
        }

        var fillColor = iconInfo.fillColor;
        var strokeColor = iconInfo.strokeColor;

        // If source is already a data uri, read it instead of doing
        // the XMLHttpRequest
        if (source.substring(0, 4) == 'data') {
            var iconData = unescape(source.slice(dataHeader.length));
            var newData = changeColors(iconData, fillColor, strokeColor);
            callback(dataHeader + escape(newData));
            return;
        }

        var client = new XMLHttpRequest();

        client.onload = function () {
            var iconData = this.responseText;
            var newData = changeColors(iconData, fillColor, strokeColor);
            callback(dataHeader + escape(newData));
        };

        client.open("GET", source);
        client.send();
    };

    function getBackgroundURL(elem) {
        var style = elem.currentStyle || window.getComputedStyle(elem, '');
        // Remove prefix 'url(' and suffix ')' before return
        return style.backgroundImage.slice(4, -1);
    }

    function setBackgroundURL(elem, url) {
        elem.style.backgroundImage = "url('" + url + "')";
    }

    icon.colorize = function (elem, colors, callback) {
        var iconInfo = {
            "uri": getBackgroundURL(elem),
            "strokeColor": colors.stroke,
            "fillColor": colors.fill
        };

        icon.load(iconInfo, function (url) {
            setBackgroundURL(elem, url);
            if (callback) {
                callback();
            }
        });

    };

    return icon;
});