Skip to content

Commit

Permalink
Reuse style element for theme injection into custom components (strea…
Browse files Browse the repository at this point in the history
…mlit#7914)

* Reuse style element for theme injection into custom components

* Test for reuse of style element for theme injection into custom components

* Run precommit

---------

Co-authored-by: Vincent Donato <vincent@streamlit.io>
  • Loading branch information
2 people authored and zyxue committed Apr 16, 2024
1 parent cfd0ee6 commit ecb04d5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
17 changes: 17 additions & 0 deletions component-lib/src/streamlit.test.ts
Expand Up @@ -249,6 +249,23 @@ describe("Streamlit", () => {
"--text-color"
)
).toEqual(theme.textColor);

expect(
document.getElementById(Streamlit.INJECTED_STYLE_ELEMENT_ID)
).toBeInstanceOf(HTMLStyleElement)
expect(
document.querySelectorAll(`style#${Streamlit.INJECTED_STYLE_ELEMENT_ID}`)
).toHaveLength(1);

window.postMessage(
{ type: "streamlit:render", args: {}, theme: theme },
"*"
);
await tick();

expect(
document.querySelectorAll(`style#${Streamlit.INJECTED_STYLE_ELEMENT_ID}`)
).toHaveLength(1);
});

test("The parent frame can sent plain arguments", async () => {
Expand Down
10 changes: 8 additions & 2 deletions component-lib/src/streamlit.ts
Expand Up @@ -69,6 +69,8 @@ export class Streamlit {

public static readonly RENDER_EVENT = "streamlit:render";

public static readonly INJECTED_STYLE_ELEMENT_ID = "__streamlit_injected_styles";

/** Dispatches events received from Streamlit. */
public static readonly events = new EventTarget();

Expand Down Expand Up @@ -228,8 +230,12 @@ export class Streamlit {
}

const _injectTheme = (theme: Theme) => {
const style = document.createElement("style");
document.head.appendChild(style);
let style = document.getElementById(Streamlit.INJECTED_STYLE_ELEMENT_ID);
if (!style) {
style = document.createElement("style");
style.id = Streamlit.INJECTED_STYLE_ELEMENT_ID;
document.head.appendChild(style);
}
style.innerHTML = `
:root {
--primary-color: ${theme.primaryColor};
Expand Down

0 comments on commit ecb04d5

Please sign in to comment.