1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.myfaces.shared.renderkit.html;
20
21
22
23
24
25
26 public class JavascriptContext
27 {
28 private static final String LINE_SEPARATOR = System.getProperty(
29 "line.separator", "\r\n");
30 private static final char TABULATOR = '\t';
31
32 private long currentIndentationLevel;
33 private StringBuilder buffer = new StringBuilder();
34 private boolean prettyPrint = false;
35
36
37
38
39
40
41 private boolean automaticFormatting = true;
42
43 public JavascriptContext()
44 {
45
46 }
47
48 public JavascriptContext(boolean prettyPrint)
49 {
50 this.prettyPrint = prettyPrint;
51 }
52
53 public JavascriptContext(StringBuilder buf, boolean prettyPrint)
54 {
55 this.prettyPrint = prettyPrint;
56 this.buffer = buf;
57 }
58
59 public void increaseIndent()
60 {
61 currentIndentationLevel++;
62 }
63
64 public void decreaseIndent()
65 {
66 currentIndentationLevel--;
67
68 if (currentIndentationLevel < 0)
69 {
70 currentIndentationLevel = 0;
71 }
72 }
73
74 public void prettyLine()
75 {
76 if (prettyPrint)
77 {
78 append(LINE_SEPARATOR);
79
80 for (int i = 0; i < getCurrentIndentationLevel(); i++)
81 {
82 append(TABULATOR);
83 }
84 }
85 }
86
87 public void prettyLineIncreaseIndent()
88 {
89 increaseIndent();
90 prettyLine();
91 }
92
93 public void prettyLineDecreaseIndent()
94 {
95 decreaseIndent();
96 prettyLine();
97 }
98
99 public long getCurrentIndentationLevel()
100 {
101 return currentIndentationLevel;
102 }
103
104 public void setCurrentIndentationLevel(long currentIndentationLevel)
105 {
106 this.currentIndentationLevel = currentIndentationLevel;
107 }
108
109 public JavascriptContext append(String str)
110 {
111
112 if (automaticFormatting && str.length() == 1)
113 {
114 boolean openBlock = str.equals("{");
115 boolean closeBlock = str.equals("}");
116
117 if (openBlock)
118 {
119 prettyLine();
120 }
121 else if (closeBlock)
122 {
123 prettyLineDecreaseIndent();
124 }
125
126 buffer.append(str);
127
128 if (openBlock)
129 {
130 prettyLineIncreaseIndent();
131 }
132 else if (closeBlock)
133 {
134 prettyLine();
135 }
136 }
137 else
138 {
139 buffer.append(str);
140 }
141 return this;
142 }
143
144 public JavascriptContext append(char c)
145 {
146 buffer.append(c);
147 return this;
148 }
149
150 public JavascriptContext append(int i)
151 {
152 buffer.append(i);
153 return this;
154 }
155
156 public String toString()
157 {
158 return buffer.toString();
159 }
160 }