forked from ahzf/CsQuery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptManager.cs
More file actions
365 lines (285 loc) · 11.5 KB
/
Copy pathScriptManager.cs
File metadata and controls
365 lines (285 loc) · 11.5 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.IO;
namespace CsQuery.Mvc.ClientScript
{
/// <summary>
/// A class to manage JavaScript dependencies. Comments at the top of the file in the form
/// //using somelibrary
///
/// will be resolved into "~/somelibrary.js", and themselves searched for other dependencies. All
/// dependencies found will be bundled, and the bundle URL inserted as a new script.
/// </summary>
public class ScriptManager
{
#region constructor
/// <summary>
/// Default constructor; creates this ScriptManager for the active HttpContext.MapPath
/// </summary>
public ScriptManager()
{
Initialize(null, null,null);
}
static ScriptManager()
{
//BundleTable.EnableOptimizations = false;
}
/// <summary>
/// Creates a ScriptManager for the ScriptEnvironment data passed
/// </summary>
///
/// <param name="env">
/// The environment.
/// </param>
public ScriptManager(ScriptEnvironment env)
{
ScriptEnvironment = env;
}
/// <summary>
/// Default constructor; creates this ScriptManager for the specified library path & MapPath
/// function.
/// </summary>
///
/// <exception cref="ArgumentException">
/// Thrown when one or more arguments have unsupported or illegal values.
/// </exception>
///
/// <param name="libraryPath">
/// The paths in the library search path.
/// </param>
/// <param name="mapPathFunc">
/// The map path function.
/// </param>
/// <param name="resolveUrlFunc">
/// A function to resolve relative URLs
/// </param>
public ScriptManager(PathList libraryPath, Func<string,string> mapPathFunc, Func<string,string> resolveUrlFunc)
{
if (mapPathFunc == null)
{
throw new ArgumentException("The MapPath function cannot be null.");
}
if (libraryPath == null)
{
throw new ArgumentException("The LibraryPath cannot be null.");
}
Initialize(libraryPath, mapPathFunc, resolveUrlFunc);
}
/// <summary>
/// Creates this ScriptManager with an empty LibraryPath.
/// </summary>
///
/// <exception cref="ArgumentException">
/// Thrown when one or more arguments have unsupported or illegal values.
/// </exception>
///
/// <param name="mapPathFunc">
/// The map path function.
/// </param>
/// <param name="resolveUrlFunc">
/// A function to resolve relative URLs.
/// </param>
public ScriptManager(Func<string, string> mapPathFunc, Func<string, string> resolveUrlFunc)
{
if (mapPathFunc == null)
{
throw new ArgumentException("The mapPath function cannot be null.");
}
if (resolveUrlFunc == null)
{
throw new ArgumentException("The resolveUrlFunc function cannot be null.");
}
Initialize(null, mapPathFunc, resolveUrlFunc);
}
private void Initialize(PathList libraryPath, Func<string, string> mapPathFunc, Func<string, string> resolveUrlFunc)
{
ScriptEnvironment = new ScriptEnvironment
{
MapPath = mapPathFunc,
LibraryPath = libraryPath,
ResolveUrl = resolveUrlFunc
};
}
/// <summary>
/// Identifier used to generate unique IDs for the generated script bundles
/// </summary>
static int ScriptID;
/// <summary>
/// Cache of bundles. If a ScriptCollection is built for a page that matches one built previously,
/// we will reuse the bundle rather than recreating the dependency table.
/// </summary>
static ConcurrentDictionary<ScriptCollection, string> Bundles = new ConcurrentDictionary<ScriptCollection, string>();
#endregion
#region private properties
private ScriptEnvironment ScriptEnvironment;
#endregion
#region public properties
/// <summary>
/// Gets or sets options that control the operation of the ScriptManager.
/// </summary>
public ViewEngineOptions Options { get; set; }
#endregion
/// <summary>
/// Resolve all script dependencies in the bound CQ document. Scripts that cotain a "data-
/// location='head'" attribute will be moved to the head.
/// </summary>
///
/// <param name="doc">
/// The document to resolve.
/// </param>
public void ResolveScriptDependencies(CQ doc)
{
string scriptSelector = "script[src][type='text/javascript'], script[src]:not([type]), link[type='text/css']";
CQ scripts = doc[scriptSelector];
if (scripts.Length == 0)
{
return;
}
// move scripts first
// TODO: Optimize using a query caching mechanism so
foreach (var item in scripts.Filter("[data-moveto]"))
{
var target = doc.Select(item["data-moveto"]);
if (target.Length>0) {
target.First().Append(item);
item.RemoveAttribute("data-moveto");
}
}
// resolve dependencies
ScriptCollection coll = new ScriptCollection(ScriptEnvironment);
coll.Options= Options;
// identify the insertion point for the script bundle. AddFromCq returns the first script with dependencies,
// so scripts should be added right before that one. Otherwise they should be added
// at the end of head.
var firstScriptEl = coll.AddFromCq(scripts);
CQ firstScript=null;
if (firstScriptEl != null)
{
firstScript = firstScriptEl.Cq();
}
string bundleUrl;
List<ScriptRef> dependencies = coll.GetDependencies()
.Where(item=>!coll.Contains(item))
.ToList();
// Now add scripts directly for dependencies marked as NoCombine.
var inlineScripts = Options.HasFlag(ViewEngineOptions.NoBundle) ?
dependencies :
dependencies.Where(item => item.NoCombine);
foreach (var item in inlineScripts)
{
var script = GetScriptHtml(item.Path, item.ScriptHash);
if (firstScript != null)
{
firstScript.Before(script);
}
else
{
firstScript = script;
doc["body"].Append(script);
}
}
// Before creating the bundle, remove any duplicates of the same script on the page
if (!Options.HasFlag(ViewEngineOptions.NoBundle))
{
bool hasBundle = Bundles.TryGetValue(coll, out bundleUrl);
if (hasBundle)
{
// when nocache is set, we will regenerate the bundle, but not change the script ID. The v=
// flag will be changed by BundleTable.
if (Options.HasFlag(ViewEngineOptions.NoCache))
{
string removeUrl = "~" + bundleUrl.Before("?");
BundleTable.Bundles.Remove(BundleTable.Bundles.GetBundleFor(removeUrl));
hasBundle = false;
ScriptID++;
// this code attempts to un-cache the bundle, it doesn't work.
// leaving it here until some permanent solution is found as a reminder
//
// http://stackoverflow.com/questions/12317391/how-to-force-bundlecollection-to-flush-cached-script-bundles-in-mvc4
//
//var bundleList = BundleTable.Bundles.ToList();
//BundleTable.Bundles.Clear();
//BundleTable.Bundles.ResetAll();
//BundleTable.EnableOptimizations = false;
//foreach (var oldBundle in bundleList)
//{
// BundleTable.Bundles.Add(oldBundle);
//}
}
}
else
{
ScriptID++;
}
if (!hasBundle)
{
var activeDependencies = dependencies.Where(item => !item.NoCombine).ToList();
if (activeDependencies.Count > 0)
{
string bundleAlias = "~/cqbundle" + ScriptID;
var bundle = GetScriptBundle(bundleAlias);
foreach (var item in activeDependencies)
{
bundle.Include(item.Path);
}
BundleTable.Bundles.Add(bundle);
if (HttpContext.Current != null)
{
bundleUrl = BundleTable.Bundles.ResolveBundleUrl(bundleAlias, true);
}
else
{
bundleUrl = bundleAlias + "_no_http_context";
}
Bundles[coll] = bundleUrl;
}
}
var scriptPlaceholder = scripts.First();
// add bundle after all noncombined scripts
if (!String.IsNullOrEmpty(bundleUrl))
{
firstScript.Before(GetScriptHtml(bundleUrl));
}
}
}
private CQ GetScriptHtml(string url, string hash=null)
{
string template;
if (url.EndsWith(".css"))
{
template = "<link rel=\"stylesheet\" type=\"text/css\" class=\"csquery-generated\" href=\"{0}\" />";
}
else
{
template = "<script type=\"text/javascript\" class=\"csquery-generated\" src=\"{0}\"></script>";
}
if (!String.IsNullOrEmpty(hash))
{
url = url + "?v=" + hash;
}
return CQ.CreateFragment(String.Format(template, ScriptEnvironment.ResolveUrl(url)));
}
private ScriptBundle GetScriptBundle(string bundleAlias)
{
var bundle = new ScriptBundle(bundleAlias);
if (Options.HasFlag(ViewEngineOptions.NoMinifyScripts))
{
bundle.Transforms.Clear();
}
else
{
if (!bundle.Transforms.Any(item => item is JsMinify))
{
bundle.Transforms.Add(new JsMinify());
}
}
return bundle;
}
}
}