-
Notifications
You must be signed in to change notification settings - Fork 7
/
JsTranslatorTransform.cs
73 lines (55 loc) · 2.31 KB
/
JsTranslatorTransform.cs
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
using System.Collections.Generic;
using System.Text;
using Karambolo.AspNetCore.Bundling;
using Karambolo.Common;
using Microsoft.Extensions.Localization;
namespace JsTranslation.Infrastructure.Bundling
{
// this is a crude implementation for replacing js strings with localized texts looked up through an IStringLocalizer
// it includes basic support for escaping but tries to localize every js string indiscriminately
public class JsTranslatorTransform : BundleItemTransform
{
static int FindNextString(string content, ref int endIndex)
{
var quote = '"';
var startIndex = content.IndexOf(quote, endIndex + 1);
if (startIndex < 0)
{
quote = '\'';
startIndex = content.IndexOf(quote, endIndex + 1);
}
if (startIndex < 0)
return -1;
endIndex = content.IndexOfEscaped('\\', quote, startIndex + 1);
if (endIndex < 0)
return -1;
return startIndex;
}
readonly IStringLocalizer _stringLocalizer;
public JsTranslatorTransform(IStringLocalizer stringLocalizer)
{
_stringLocalizer = stringLocalizer;
}
public override void Transform(IBundleItemTransformContext context)
{
int startIndex, endIndex = -1;
var stringLocations = new List<(int startIndex, int count)>();
while ((startIndex = FindNextString(context.Content, ref endIndex)) >= 0)
stringLocations.Add((startIndex + 1, endIndex - startIndex - 1));
if (stringLocations.Count == 0)
return;
var sb = new StringBuilder(context.Content);
for (var i = stringLocations.Count - 1; i >= 0; i--)
{
var stringLocation = stringLocations[i];
sb.Remove(stringLocation.startIndex, stringLocation.count);
var value = context.Content
.Substring(stringLocation.startIndex, stringLocation.count)
.Unescape('\\', '\'', '"');
value = _stringLocalizer[value].Value.Escape('\\', '\'', '"');
sb.Insert(stringLocation.startIndex, value);
}
context.Content = sb.ToString();
}
}
}