forked from javelit/javelit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeExample.java
More file actions
288 lines (248 loc) · 12.5 KB
/
Copy pathCodeExample.java
File metadata and controls
288 lines (248 loc) · 12.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
/// usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS io.javelit:javelit:0.76.0
import io.javelit.core.Jt;
public class CodeExample {
public static void main(String[] args) {
Jt.title("# Code Component Showcase").use();
Jt.markdown("This demo showcases all the capabilities of the `st.code` component in Javelit.").use();
// Language highlighting examples
Jt.title("## Language Highlighting").use();
Jt.markdown("### Java Code (Default Language)").use();
Jt.code("""
public class HelloWorld {
private static final String GREETING = "Hello, World!";
public static void main(String[] args) {
System.out.println(GREETING);
// Create a simple list
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream()
.map(name -> "Hello, " + name + "!")
.forEach(System.out::println);
}
}
""").use();
Jt.markdown("### Python Code").use();
Jt.code("""
def fibonacci(n):
\"\"\"Generate Fibonacci sequence up to n terms\"\"\"
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[i-1] + sequence[i-2])
return sequence
# Generate first 10 Fibonacci numbers
fib_numbers = fibonacci(10)
print(f"First 10 Fibonacci numbers: {fib_numbers}")
# List comprehension example
squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f"Squares of even numbers: {squares}")
""").language("python").use();
Jt.markdown("### Plain Text (No Highlighting)").use();
Jt.code("""
This is plain text without any syntax highlighting.
No keywords, strings, or comments will be colored.
function example() {
// This looks like JavaScript but won't be highlighted
return "plain text";
}
SELECT * FROM users WHERE active = true;
-- This looks like SQL but won't be highlighted either
""").language(null).use();
// Line numbers and wrap lines combinations
Jt.title("## Line Numbers & Wrap Lines Combinations").use();
Jt.markdown("### Default: No Line Numbers, No Wrapping").use();
Jt.code("""
// Short lines that don't need wrapping
public void shortMethod() {
String name = "Alice";
int age = 25;
System.out.println("Name: " + name + ", Age: " + age);
}
""").use();
Jt.markdown("### Line Numbers Only").use();
Jt.code("""
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
public double divide(int a, int b) {
if (b == 0) throw new IllegalArgumentException("Division by zero");
return (double) a / b;
}
}
""").lineNumbers(true).use();
Jt.markdown("### Wrap Lines Only (Long Lines)").use();
Jt.code("""
// This is a very long comment that demonstrates how line wrapping works when enabled. It will wrap to multiple lines instead of creating a horizontal scroll bar.
public void processUserData(String firstName, String lastName, String email, String phoneNumber, String address, String city, String country) {
String fullName = firstName + " " + lastName;
System.out.println("Processing user: " + fullName + " with email: " + email + " and phone: " + phoneNumber + " living at: " + address + ", " + city + ", " + country);
// Another long line that will wrap when wrap lines is enabled, showing how code remains readable even with very long statements or expressions
boolean isValidUser = !firstName.isEmpty() && !lastName.isEmpty() && email.contains("@") && phoneNumber.matches("\\\\d{10}") && !address.isEmpty() && !city.isEmpty() && !country.isEmpty();
}
""").wrapLines(true).use();
Jt.markdown("### Both Line Numbers and Wrap Lines").use();
Jt.code("""
/**
* This method demonstrates both line numbers and line wrapping functionality together, which is particularly useful for long code blocks with extended lines
*/
public class DataProcessor {
public void processComplexData(Map<String, List<UserProfile>> userGroups, Set<String> activeRegions, List<String> supportedLanguages) {
// This long line will wrap and show line numbers, making it easy to reference specific parts of the code during code reviews or debugging sessions
userGroups.entrySet().stream()
.filter(entry -> activeRegions.contains(entry.getKey()))
.flatMap(entry -> entry.getValue().stream())
.filter(user -> supportedLanguages.contains(user.getPreferredLanguage()) && user.isActive() && user.hasValidSubscription())
.collect(Collectors.groupingBy(UserProfile::getRegion, Collectors.mapping(UserProfile::getEmail, Collectors.toList())))
.forEach((region, emails) -> sendNotificationToUsers(region, emails, "Welcome to our premium service!"));
}
}
""").lineNumbers(true).wrapLines(true).use();
// Width and height examples
Jt.title("## Width and Height Control").use();
Jt.markdown("### Default Dimensions (Stretch Width, Content Height)").use();
Jt.code("""
// This code block uses default dimensions
public void defaultSize() {
System.out.println("Default width stretches to container");
System.out.println("Height adjusts to content");
}
""").use();
Jt.markdown("### Fixed Pixel Dimensions").use();
Jt.code("""
// This code block has fixed width and height
public void fixedDimensions() {
String[] languages = {"Java", "Python", "JavaScript", "Go", "Rust"};
for (String lang : languages) {
System.out.println("Language: " + lang);
}
// More content to show scrolling behavior
System.out.println("This content might require scrolling");
System.out.println("if the fixed height is smaller");
System.out.println("than the content height.");
}
""").width(600).height(150).lineNumbers(true).use();
Jt.markdown("### Content Width (Fits Code Width)").use();
Jt.code("short code").width("content").lineNumbers(true).use();
Jt.markdown("### Stretch Height (Fills Available Space)").use();
final var cs = Jt.container().height(500).use();
Jt.code("""
// This code block stretches to available height
public class StretchExample {
public void method1() {
System.out.println("Method 1");
}
public void method2() {
System.out.println("Method 2");
}
}
""").height("stretch").lineNumbers(true).use(cs);
// Language variety showcase
Jt.title("## Different Programming Languages").use();
Jt.markdown("### JavaScript").use();
Jt.code("""
const fetchUserData = async (userId) => {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const userData = await response.json();
return userData;
} catch (error) {
console.error('Failed to fetch user data:', error);
throw error;
}
};
// Usage with arrow function and destructuring
fetchUserData(123).then(({name, email, profile}) => {
console.log(`User: ${name} (${email})`);
console.log(`Profile: ${JSON.stringify(profile, null, 2)}`);
});
""").language("javascript").lineNumbers(true).use();
Jt.code("""
const fetchUserData = async (userId) => {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const userData = await response.json();
return userData;
ile: ${JSON.stringify(profile, null, 2)}`);
});
""").language("javascript").lineNumbers(true).use();
Jt.markdown("### CSS").use();
Jt.code("""
/* Modern CSS with custom properties and grid */
:root {
--primary-color: #3498db;
--secondary-color: #2c3e50;
--border-radius: 8px;
--spacing: 1rem;
}
.card {
background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
border-radius: var(--border-radius);
padding: var(--spacing);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.2s ease-in-out;
}
.card:hover {
transform: translateY(-2px);
}
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: var(--spacing);
}
""").language("css").lineNumbers(true).wrapLines(true).use();
Jt.markdown("### JSON Configuration").use();
Jt.code("""
{
"name": "javelit-demo",
"version": "1.0.0",
"description": "A comprehensive demo of code component capabilities",
"dependencies": {
"spring-boot": "3.2.0",
"jackson": "2.15.2",
"junit": "5.9.3"
},
"configuration": {
"server": {
"port": 8080,
"ssl": {
"enabled": false,
"key-store": "/path/to/keystore.p12"
}
},
"logging": {
"level": {
"io.javelit": "DEBUG",
"org.springframework": "INFO"
}
}
},
"features": [
"syntax-highlighting",
"line-numbers",
"code-wrapping",
"responsive-design"
]
}
""").language("json").lineNumbers(true).use();
Jt.markdown("---").use();
Jt
.markdown(
"**Demo Complete!** This showcase demonstrates all the key features of the CodeComponent including syntax highlighting for multiple languages, line numbers, line wrapping, and flexible width/height controls.")
.use();
}
}