Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reuse style element for theme injection into custom components #7914

Merged
merged 3 commits into from Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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