Skip to content

Instantly share code, notes, and snippets.

@masenf
Last active September 24, 2023 08:05
Show Gist options
  • Save masenf/611157fcee00e12afa928f83ca4bb6e1 to your computer and use it in GitHub Desktop.
Save masenf/611157fcee00e12afa928f83ca4bb6e1 to your computer and use it in GitHub Desktop.
Rendering a tweet with Reflex web framework
from typing import Any
import httpx
import reflex as rx
class HtmlDangerous(rx.Component):
"""Render the html via createRange().createContextualFragment.
Allows for execution of scripts in the given HTML without restriction.
"""
tag = "DangerouslySetHtmlContent"
# The HTML to render.
html: Any
def _get_custom_code(self) -> str | None:
"""Include DangerouslySetHtmlContent component.
Copyright 2023 christo-pr (https://github.com/christo-pr)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Returns:
The code to render the DangerouslySetHtmlContent component.
"""
return """
// Copyright 2023 christo-pr (https://github.com/christo-pr)
function DangerouslySetHtmlContent({ html, dangerouslySetInnerHTML, ...rest }) {
const divRef = useRef(null)
useEffect(() => {
if (!html || !divRef.current) throw new Error("html prop can't be null")
const slotHtml = document.createRange().createContextualFragment(html)
divRef.current.innerHTML = ''
divRef.current.appendChild(slotHtml)
}, [html, divRef])
return <div {...rest} ref={divRef} />
}"""
INTERESTING_TWEETS = [
"https://twitter.com/pwang_szn/status/1617567945059872770",
"https://twitter.com/elonmusk/status/1519480761749016577",
"https://twitter.com/GretaThunberg/status/1608056944501178368",
"https://twitter.com/BTS_twt/status/1353536893787357184",
"https://twitter.com/IncredibleCulk/status/1298730289737293824",
]
class State(rx.State):
tweet_url: str = ""
_tweet_ix: int = 0 # dummy variable to "change" the load script every time the url changes
def set_tweet_url(self, url: str):
self.tweet_url = url
self._tweet_ix += 1
@rx.cached_var
def tweet_html(self) -> str:
if self.tweet_url:
resp = httpx.get(
f'https://publish.twitter.com/oembed?url={self.tweet_url}&hide_media=true&hide_thread=true&align=center&omit_script=true',
)
return resp.json()['html']
@rx.cached_var
def twttr_load(self) -> str:
"""Return a "reloader" script that re-renders the tweet after loading new content."""
return (
f"<script>// load {self._tweet_ix}\n"
"if (typeof window !== 'undefined') {window.twttr.widgets.load()}</script>"
) if self._tweet_ix > 0 else ""
def post() -> rx.Component:
return rx.center(
# load twitter.js https://developer.twitter.com/en/docs/twitter-for-websites/javascript-api/guides/set-up-twitter-for-websites
rx.script("""window.twttr = (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], t = window.twttr || {}; if (d.getElementById(id)) return t; js = d.createElement(s); js.id = id; js.src = "https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); t._e = []; t.ready = function(f) { t._e.push(f); }; return t; }(document, "script", "twitter-wjs"));"""),
rx.html(State.tweet_html),
# Here's a hack to re-render the tweet after loading new content.
rx.cond(
State.twttr_load != "",
HtmlDangerous.create(html=State.twttr_load),
),
)
def index() -> rx.Component:
return rx.vstack(
rx.heading("A Tweet For You..."),
rx.select(
rx.option("Select a tweet to embed", value=""),
*[rx.option(tweet, value=tweet) for tweet in INTERESTING_TWEETS],
value=State.tweet_url,
on_change=State.set_tweet_url,
),
post(),
)
# Add state and page to the app.
app = rx.App()
app.add_page(index)
app.compile()
@masenf
Copy link
Author

masenf commented Sep 24, 2023

I kinda hate it ... but it works?

HtmlDangerous should be available in reflex-0.2.9 (reflex-dev/reflex#1850); but maybe this exposes a more general requirement for an event handler to be able to yield arbitrary javascript to execute against the page (reflex-dev/reflex#1357). Currently we have rx.client_side, but since this is a BaseVar and not a real EventHandler, it really can only be used as a trigger; there's no way to fire it from the backend.

@masenf
Copy link
Author

masenf commented Sep 24, 2023

Screen.Recording.2023-09-24.at.1.01.00.AM.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment