-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathInfiniteScroll.java
81 lines (68 loc) · 2.54 KB
/
InfiniteScroll.java
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
package com.devhow.htmxdemo.demo;
import org.intellij.lang.annotations.Language;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.List;
/**
* This demonstration uses HTML generated here (in the controller!) instead of just the HTML coming from Thymeleaf
* templates.
* <p>
* This is really intended to be a very primitive transitional demonstration, showing the basics of how HTMX could
* serve as the starting point for a more component-oriented approach, or perhaps even used in combination with
* WebSockets and Server-Side Events.
* https://htmx.org/docs/#websockets-and-sse
* <p>
* Put another way - this is a pretty messy, hacky mess... but it's also the kernel for starting what could be a
* different approach.
*/
@Controller
@RequestMapping("/infinite-scroll")
public class InfiniteScroll {
@GetMapping
public String start(Model model) {
model.addAttribute("now", new Date().toInstant());
return "infinite-scroll";
}
@Language("html")
String contactHtml = """
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>
""";
@Language("html")
String loadHtml = """
<tr hx-get="/infinite-scroll/page/%d"
hx-trigger="revealed"
hx-swap="afterend"
<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>
""";
@GetMapping(value = "/page/{id}", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
public String nextPage(@PathVariable Integer id) {
StringBuilder result = new StringBuilder();
List<Contact> demoContacts = Contact.randomContacts(9);
for (Contact c : demoContacts) {
result.append("<tr>");
result.append(contactHtml.formatted(c.getFirstName(), c.getLastName(), c.getEmail()));
}
Contact last = Contact.randomContacts(1).get(0);
result.append(loadHtml.formatted(id + 1, last.getFirstName(), last.getLastName(), last.getEmail()));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return result.toString();
}
}