Архивирование с быстрым подключением и серверный рендеринг для веб-клиента #15
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
-module(calendar_html_renderer).
|
||||
-include("records.hrl").
|
||||
|
||||
-export([render_month/3, init_cache/0]).
|
||||
|
||||
init_cache() ->
|
||||
case ets:info(archive_html_cache) of
|
||||
undefined ->
|
||||
ets:new(archive_html_cache, [set, public, named_table, {keypos, 1}]);
|
||||
_ -> ok
|
||||
end.
|
||||
|
||||
render_month(Year, Month, Events) ->
|
||||
Key = {Year, Month},
|
||||
try ets:lookup(archive_html_cache, Key) of
|
||||
[{Key, Html}] -> Html;
|
||||
[] ->
|
||||
Html = generate_html(Year, Month, Events),
|
||||
ets:insert(archive_html_cache, {Key, Html}),
|
||||
Html
|
||||
catch
|
||||
_:_ ->
|
||||
generate_html(Year, Month, Events)
|
||||
end.
|
||||
|
||||
generate_html(Year, Month, Events) ->
|
||||
DaysInMonth = calendar:last_day_of_the_month(Year, Month),
|
||||
EventsByDay = group_events_by_day(Events),
|
||||
DayList = lists:seq(1, DaysInMonth),
|
||||
DayCells = lists:map(fun(D) ->
|
||||
DayEvents = maps:get(D, EventsByDay, []),
|
||||
["<td>", integer_to_list(D), format_events(DayEvents), "</td>"]
|
||||
end, DayList),
|
||||
["<html><body><table>",
|
||||
"<tr>", DayCells, "</tr>",
|
||||
"</table></body></html>"].
|
||||
|
||||
group_events_by_day(Events) ->
|
||||
lists:foldl(fun(Evt, Acc) ->
|
||||
case Evt of
|
||||
#event{start_time = {{_, _, Day}, {_, _, _}}} ->
|
||||
maps:update_with(Day, fun(List) -> [Evt | List] end, [Evt], Acc);
|
||||
_ -> Acc
|
||||
end
|
||||
end, #{}, Events).
|
||||
|
||||
format_events(Events) ->
|
||||
case Events of
|
||||
[] -> [];
|
||||
_ ->
|
||||
["<ul>",
|
||||
lists:map(fun(#event{title = Title, start_time = {{_, _, _}, {H, M, _}}}) ->
|
||||
["<li>", Title, " (", integer_to_list(H), ":",
|
||||
io_lib:format("~2..0B", [M]), ")</li>"]
|
||||
end, Events),
|
||||
"</ul>"]
|
||||
end.
|
||||
Reference in New Issue
Block a user