-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsse.py
More file actions
199 lines (169 loc) · 6.25 KB
/
sse.py
File metadata and controls
199 lines (169 loc) · 6.25 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
from __future__ import annotations
import json
from collections.abc import AsyncIterable, Iterable, Mapping
from itertools import chain
from typing import Literal, Protocol, TypeAlias, overload, runtime_checkable
import datastar_py.consts as consts
from datastar_py.attributes import _escape, SignalValue
SSE_HEADERS: dict[str, str] = {
"Cache-Control": "no-cache",
"Content-Type": "text/event-stream",
"X-Accel-Buffering": "no",
}
@runtime_checkable
class _HtmlProvider(Protocol):
"""A type that produces text ready to be placed in an HTML document.
This is a convention used by html producing/consuming libraries. This lets
e.g. fasthtml fasttags, or htpy elements, be passed straight in to
merge_fragments.
"""
def __html__(self) -> str: ...
class DatastarEvent(str):
pass
# 0..N datastar events
DatastarEvents: TypeAlias = (
DatastarEvent | Iterable[DatastarEvent] | AsyncIterable[DatastarEvent] | None
)
class ServerSentEventGenerator:
__slots__ = ()
@classmethod
def _send(
cls,
event_type: consts.EventType,
data_lines: list[str],
event_id: str | None = None,
retry_duration: int | None = None,
) -> DatastarEvent:
prefix = [f"event: {event_type}"]
if event_id:
prefix.append(f"id: {event_id}")
if retry_duration and retry_duration != consts.DEFAULT_SSE_RETRY_DURATION:
prefix.append(f"retry: {retry_duration}")
data_lines = [f"data: {line}" for line in data_lines]
return DatastarEvent("\n".join(chain(prefix, data_lines)) + "\n\n")
@overload
@classmethod
def patch_elements(
cls,
*,
selector: str,
mode: Literal[consts.ElementPatchMode.REMOVE],
use_view_transition: bool | None = None,
event_id: str | None = None,
retry_duration: int | None = None,
) -> DatastarEvent: ...
@overload
@classmethod
def patch_elements(
cls,
elements: str | _HtmlProvider,
selector: str | None = None,
mode: consts.ElementPatchMode | None = None,
use_view_transition: bool | None = None,
event_id: str | None = None,
retry_duration: int | None = None,
) -> DatastarEvent: ...
@classmethod
def patch_elements(
cls,
elements: str | _HtmlProvider | None = None,
selector: str | None = None,
mode: consts.ElementPatchMode | None = None,
use_view_transition: bool | None = None,
namespace: consts.ElementPatchNamespace | None = None,
event_id: str | None = None,
retry_duration: int | None = None,
) -> DatastarEvent:
if isinstance(elements, _HtmlProvider):
elements = elements.__html__()
data_lines = []
if mode and mode != consts.ElementPatchMode.OUTER:
data_lines.append(f"{consts.MODE_DATALINE_LITERAL} {mode}")
if selector:
data_lines.append(f"{consts.SELECTOR_DATALINE_LITERAL} {selector}")
if (
use_view_transition is not None
and use_view_transition != consts.DEFAULT_ELEMENTS_USE_VIEW_TRANSITIONS
):
data_lines.append(
f"{consts.USE_VIEW_TRANSITION_DATALINE_LITERAL} {_js_bool(use_view_transition)}"
)
if namespace and namespace != consts.ElementPatchNamespace.HTML:
data_lines.append(f"{consts.NAMESPACE_DATALINE_LITERAL} {namespace}")
if elements:
data_lines.extend(
f"{consts.ELEMENTS_DATALINE_LITERAL} {x}" for x in elements.splitlines()
)
return ServerSentEventGenerator._send(
consts.EventType.PATCH_ELEMENTS,
data_lines,
event_id,
retry_duration,
)
@classmethod
def remove_elements(
cls, selector: str, event_id: str | None = None, retry_duration: int | None = None
) -> DatastarEvent:
return ServerSentEventGenerator.patch_elements(
selector=selector,
mode=consts.ElementPatchMode.REMOVE,
event_id=event_id,
retry_duration=retry_duration,
)
@classmethod
def patch_signals(
cls,
signals: dict[str, SignalValue] | str,
event_id: str | None = None,
only_if_missing: bool | None = None,
retry_duration: int | None = None,
) -> DatastarEvent:
data_lines = []
if (
only_if_missing is not None
and only_if_missing != consts.DEFAULT_PATCH_SIGNALS_ONLY_IF_MISSING
):
data_lines.append(
f"{consts.ONLY_IF_MISSING_DATALINE_LITERAL} {_js_bool(only_if_missing)}"
)
signals_str = (
signals if isinstance(signals, str) else json.dumps(signals, separators=(",", ":"))
)
data_lines.extend(
f"{consts.SIGNALS_DATALINE_LITERAL} {line}" for line in signals_str.splitlines()
)
return ServerSentEventGenerator._send(
consts.EventType.PATCH_SIGNALS, data_lines, event_id, retry_duration
)
@classmethod
def execute_script(
cls,
script: str,
auto_remove: bool = True,
attributes: Mapping[str, str] | list[str] | None = None,
event_id: str | None = None,
retry_duration: int | None = None,
) -> DatastarEvent:
attribute_string = ""
if auto_remove:
attribute_string += ' data-effect="el.remove()"'
if attributes:
if isinstance(attributes, Mapping):
attribute_string += " " + " ".join(
f'{_escape(k)}="{_escape(v)}"' for k, v in attributes.items()
)
else:
attribute_string += " " + " ".join(attributes)
script_tag = f"<script{attribute_string}>{script}</script>"
return ServerSentEventGenerator.patch_elements(
script_tag,
mode=consts.ElementPatchMode.APPEND,
selector="body",
event_id=event_id,
retry_duration=retry_duration,
)
@classmethod
def redirect(cls, location: str) -> DatastarEvent:
return cls.execute_script(f"setTimeout(() => window.location = '{location}')")
def _js_bool(b: bool) -> str:
return "true" if b else "false"