1 | (function (doc, define) {
|
2 |
|
3 | define(['./util/beget'], function (beget) {
|
4 | "use strict";
|
5 |
|
6 | var absoluteUrlRE, urlEncodedBraceOpenRE, urlEncodedBraceCloseRE;
|
7 |
|
8 | absoluteUrlRE = /^https?:\/\//i;
|
9 | urlEncodedBraceOpenRE = /%7b/i;
|
10 | urlEncodedBraceCloseRE = /%7d/i;
|
11 |
|
12 | |
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | function buildUrl(template, params) {
|
23 |
|
24 | var url, name, queryStringParams, re;
|
25 |
|
26 | url = template;
|
27 | queryStringParams = {};
|
28 |
|
29 | if (params) {
|
30 | for (name in params) {
|
31 | re = new RegExp("\\{" + name + "\\}");
|
32 | if (re.test(url)) {
|
33 | url = url.replace(re, encodeURIComponent(params[name]), "g");
|
34 | }
|
35 | else {
|
36 | queryStringParams[name] = params[name];
|
37 | }
|
38 | }
|
39 | for (name in queryStringParams) {
|
40 | url += url.indexOf("?") === -1 ? "?" : "&";
|
41 | url += encodeURIComponent(name);
|
42 | if (queryStringParams[name] !== null && queryStringParams[name] !== undefined) {
|
43 | url += "=";
|
44 | url += encodeURIComponent(queryStringParams[name]);
|
45 | }
|
46 | }
|
47 | }
|
48 | return url;
|
49 | }
|
50 |
|
51 | |
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | function UrlBuilder(template, params) {
|
59 | if (template instanceof UrlBuilder) {
|
60 | this._template = template.template;
|
61 | this._params = beget(this._params, params);
|
62 | }
|
63 | else {
|
64 | this._template = (template || '').toString();
|
65 | this._params = params;
|
66 | }
|
67 | }
|
68 |
|
69 | UrlBuilder.prototype = {
|
70 |
|
71 | |
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | append: function (template, params) {
|
80 |
|
81 | return new UrlBuilder(this._template + template, beget(this._params, params));
|
82 | },
|
83 |
|
84 | |
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 | absolute: function () {
|
95 | if (!doc || absoluteUrlRE.test(this._template)) { return this; }
|
96 |
|
97 | var a, template;
|
98 |
|
99 | a = doc.createElement('a');
|
100 | a.href = this._template;
|
101 | template = a.href.replace(urlEncodedBraceOpenRE, '{').replace(urlEncodedBraceCloseRE, '}');
|
102 |
|
103 | return new UrlBuilder(template, this._params);
|
104 | },
|
105 |
|
106 | |
107 |
|
108 |
|
109 |
|
110 |
|
111 |
|
112 | build: function (params) {
|
113 | return buildUrl(this._template, beget(this._params, params));
|
114 | },
|
115 |
|
116 | |
117 |
|
118 |
|
119 | toString: function () {
|
120 | return this.build();
|
121 | }
|
122 | };
|
123 |
|
124 | return UrlBuilder;
|
125 | });
|
126 |
|
127 | }(
|
128 | this.document,
|
129 | typeof define === 'function' ? define : function (deps, factory) {
|
130 | module.exports = factory.apply(this, deps.map(require));
|
131 | }
|
132 |
|
133 | ));
|