Skip to content

Commit

Permalink
Feature: st.logo (#8554)
Browse files Browse the repository at this point in the history
Add a new command `st.logo` to display a logo in the top left of main page & sidebar
  • Loading branch information
mayagbarnes committed May 7, 2024
1 parent 1a3a1c0 commit 3fa988a
Show file tree
Hide file tree
Showing 88 changed files with 663 additions and 94 deletions.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added e2e_playwright/multipage_apps/full-streamlit.png
24 changes: 24 additions & 0 deletions e2e_playwright/multipage_apps/mpa_basics_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,3 +243,27 @@ def test_removes_non_embed_query_params_when_swapping_pages(page: Page, app_port
expect(page).to_have_url(
f"http://localhost:{app_port}/page3?embed=true&embed_options=show_toolbar&embed_options=show_colored_line"
)


def test_renders_logos(app: Page, assert_snapshot: ImageCompareFunction):
"""Test that logos display properly in sidebar and main sections"""

# Go to logo page & wait short moment for logo to appear
app.get_by_test_id("stSidebarNav").locator("a").nth(8).click()
wait_for_app_loaded(app)

# Sidebar logo
expect(app.get_by_test_id("stSidebarHeader").locator("a")).to_have_attribute(
"href", "https://www.example.com"
)
assert_snapshot(app.get_by_test_id("stSidebar"), name="sidebar-logo")

# Collapse the sidebar
app.get_by_test_id("stSidebarCollapseButton").locator("button").click()
app.wait_for_timeout(500)

# Collapsed logo
expect(app.get_by_test_id("collapsedControl").locator("a")).to_have_attribute(
"href", "https://www.example.com"
)
assert_snapshot(app.get_by_test_id("collapsedControl"), name="collapsed-logo")
11 changes: 11 additions & 0 deletions e2e_playwright/multipage_apps/mpa_configure_sidebar.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib

from PIL import Image

import streamlit as st

small_logo = Image.open(str(pathlib.Path(__file__).parent / "small-streamlit.png"))

logo = Image.open(str(pathlib.Path(__file__).parent / "full-streamlit.png"))

st.header("App with no sidebar")

st.subheader("Page Navigation:")

st.logo(logo, link="https://www.example.com", icon_image=small_logo)


colA, colB = st.columns(2)

with colA:
Expand Down
11 changes: 11 additions & 0 deletions e2e_playwright/multipage_apps/mpa_configure_sidebar_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,14 @@ def test_page_link_href(
expect(page_links.nth(1)).to_have_attribute("href", "page2")
expect(page_links.nth(2)).to_have_attribute("href", "page3")
expect(page_links.nth(3)).to_have_attribute("href", "page_with_duplicate_name")


def test_logo_no_sidebar(
app: Page, configure_show_sidebar_nav, assert_snapshot: ImageCompareFunction
):
"""Test that logo renders properly with no sidebar."""
expect(app.get_by_test_id("stSidebar")).not_to_be_attached()
expect(app.get_by_test_id("collapsedControl").locator("a")).to_have_attribute(
"href", "https://www.example.com"
)
assert_snapshot(app.get_by_test_id("collapsedControl"), name="logo-no-sidebar")
31 changes: 31 additions & 0 deletions e2e_playwright/multipage_apps/pages/09_logo_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib

from PIL import Image

import streamlit as st

small_logo = Image.open(
str(pathlib.Path(__file__).parent.parent / "small-streamlit.png")
)

logo = Image.open(str(pathlib.Path(__file__).parent.parent / "full-streamlit.png"))

st.header("Logo page")
st.logo(logo, link="https://www.example.com", icon_image=small_logo)

with st.sidebar:
st.radio("Example Sidebar Content", ["Home", "About", "Contact"])
Binary file added e2e_playwright/multipage_apps/small-streamlit.png
6 changes: 6 additions & 0 deletions frontend/app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import {
IAppPage,
IGitInfo,
Initialize,
Logo,
NewSession,
PageConfig,
PageInfo,
Expand Down Expand Up @@ -150,6 +151,7 @@ interface State {
formsData: FormsData
hideTopBar: boolean
hideSidebarNav: boolean
appLogo: Logo | null
appPages: IAppPage[]
currentPageScriptHash: string
latestRunTime: number
Expand Down Expand Up @@ -257,6 +259,7 @@ export class App extends PureComponent<Props, State> {
themeHash: this.createThemeHash(),
gitInfo: null,
formsData: createFormsData(),
appLogo: null,
appPages: [],
currentPageScriptHash: "",
// We set hideTopBar to true by default because this information isn't
Expand Down Expand Up @@ -636,6 +639,7 @@ export class App extends PureComponent<Props, State> {
this.uploadClient.onFileURLsResponse(fileURLsResponse),
parentMessage: (parentMessage: ParentMessage) =>
this.handleCustomParentMessage(parentMessage),
logo: (logo: Logo) => this.setState({ appLogo: logo }),
})
} catch (e) {
const err = ensureError(e)
Expand Down Expand Up @@ -1323,6 +1327,7 @@ export class App extends PureComponent<Props, State> {
}

onPageChange = (pageScriptHash: string): void => {
this.setState({ appLogo: null })
this.sendRerunBackMsg(undefined, undefined, pageScriptHash)
}

Expand Down Expand Up @@ -1834,6 +1839,7 @@ export class App extends PureComponent<Props, State> {
uploadClient={this.uploadClient}
componentRegistry={this.componentRegistry}
formsData={this.state.formsData}
appLogo={this.state.appLogo}
appPages={this.state.appPages}
onPageChange={this.onPageChange}
currentPageScriptHash={currentPageScriptHash}
Expand Down
75 changes: 70 additions & 5 deletions frontend/app/src/components/AppView/AppView.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import React from "react"
import "@testing-library/jest-dom"
import { screen } from "@testing-library/react"
import { screen, within } from "@testing-library/react"
import {
AppContext,
Props as AppContextProps,
Expand All @@ -38,6 +38,7 @@ import {
mockSessionInfo,
render,
Block as BlockProto,
Logo as LogoProto,
} from "@streamlit/lib"
import AppView, { AppViewProps } from "./AppView"

Expand Down Expand Up @@ -66,14 +67,15 @@ function getContextOutput(context: Partial<AppContextProps>): AppContextProps {
}
}

const mockEndpointProp = mockEndpoints()

function getProps(props: Partial<AppViewProps> = {}): AppViewProps {
const formsData = createFormsData()

const sessionInfo = mockSessionInfo()
const endpoints = mockEndpoints()

return {
endpoints: endpoints,
endpoints: mockEndpointProp,
elements: AppRoot.empty(true),
sendMessageToHost: jest.fn(),
sessionInfo: sessionInfo,
Expand All @@ -85,13 +87,14 @@ function getProps(props: Partial<AppViewProps> = {}): AppViewProps {
}),
uploadClient: new FileUploadClient({
sessionInfo: sessionInfo,
endpoints: endpoints,
endpoints: mockEndpointProp,
formsWithPendingRequestsChanged: () => {},
requestFileURLs: jest.fn(),
}),
widgetsDisabled: true,
componentRegistry: new ComponentRegistry(endpoints),
componentRegistry: new ComponentRegistry(mockEndpointProp),
formsData,
appLogo: null,
appPages: [{ pageName: "streamlit_app", pageScriptHash: "page_hash" }],
onPageChange: jest.fn(),
currentPageScriptHash: "main_page_script_hash",
Expand Down Expand Up @@ -252,6 +255,68 @@ describe("AppView element", () => {
expect(style.maxWidth).toEqual("initial")
})

describe("handles logo rendering with no sidebar", () => {
const imageOnly = LogoProto.create({
image:
"https://global.discourse-cdn.com/business7/uploads/streamlit/original/2X/8/8cb5b6c0e1fe4e4ebfd30b769204c0d30c332fec.png",
})

const imageWithLink = LogoProto.create({
image:
"https://global.discourse-cdn.com/business7/uploads/streamlit/original/2X/8/8cb5b6c0e1fe4e4ebfd30b769204c0d30c332fec.png",
link: "www.example.com",
})

const fullAppLogo = LogoProto.create({
image:
"https://global.discourse-cdn.com/business7/uploads/streamlit/original/2X/8/8cb5b6c0e1fe4e4ebfd30b769204c0d30c332fec.png",
link: "www.example.com",
iconImage: "https://docs.streamlit.io/logo.svg",
})

it("doesn't render if no logo provided", () => {
render(<AppView {...getProps()} />)
expect(screen.queryByTestId("stLogo")).not.toBeInTheDocument()
})

it("uses iconImage if provided", () => {
const sourceSpy = jest.spyOn(mockEndpointProp, "buildMediaURL")
render(<AppView {...getProps({ appLogo: fullAppLogo })} />)
const openSidebarContainer = screen.getByTestId("collapsedControl")
expect(openSidebarContainer).toBeInTheDocument()
const collapsedLogo = within(openSidebarContainer).getByTestId("stLogo")
expect(collapsedLogo).toBeInTheDocument()
expect(sourceSpy).toHaveBeenCalledWith(
"https://docs.streamlit.io/logo.svg"
)
})

it("defaults to image if no iconImage", () => {
const sourceSpy = jest.spyOn(mockEndpointProp, "buildMediaURL")
render(<AppView {...getProps({ appLogo: imageOnly })} />)
const openSidebarContainer = screen.getByTestId("collapsedControl")
expect(openSidebarContainer).toBeInTheDocument()
const collapsedLogo = within(openSidebarContainer).getByTestId("stLogo")
expect(collapsedLogo).toBeInTheDocument()
expect(sourceSpy).toHaveBeenCalledWith(
"https://global.discourse-cdn.com/business7/uploads/streamlit/original/2X/8/8cb5b6c0e1fe4e4ebfd30b769204c0d30c332fec.png"
)
})

it("default no link with image", () => {
render(<AppView {...getProps({ appLogo: imageOnly })} />)
expect(screen.queryByTestId("stLogoLink")).not.toBeInTheDocument()
})

it("link with image if provided", () => {
render(<AppView {...getProps({ appLogo: imageWithLink })} />)
expect(screen.getByTestId("stLogoLink")).toHaveAttribute(
"href",
"www.example.com"
)
})
})

describe("when window.location.hash changes", () => {
let originalLocation: Location
beforeEach(() => (originalLocation = window.location))
Expand Down
39 changes: 39 additions & 0 deletions frontend/app/src/components/AppView/AppView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,16 @@ import {
IGuestToHostMessage,
StreamlitEndpoints,
LibContext,
Logo,
} from "@streamlit/lib"

import { ThemedSidebar } from "@streamlit/app/src/components/Sidebar"
import EventContainer from "@streamlit/app/src/components/EventContainer"
import {
StyledSidebarOpenContainer,
StyledLogo,
StyledLogoLink,
} from "@streamlit/app/src/components/Sidebar/styled-components"

import { AppContext } from "@streamlit/app/src/components/AppContext"

Expand Down Expand Up @@ -76,6 +82,8 @@ export interface AppViewProps {

formsData: FormsData

appLogo: Logo | null

appPages: IAppPage[]

onPageChange: (pageName: string) => void
Expand All @@ -99,6 +107,7 @@ function AppView(props: AppViewProps): ReactElement {
uploadClient,
componentRegistry,
formsData,
appLogo,
appPages,
onPageChange,
currentPageScriptHash,
Expand Down Expand Up @@ -126,6 +135,7 @@ function AppView(props: AppViewProps): ReactElement {
disableScrolling,
showToolbar,
showColoredLine,
sidebarChevronDownshift,
} = React.useContext(AppContext)

const { addScriptFinishedHandler, removeScriptFinishedHandler, libConfig } =
Expand Down Expand Up @@ -167,6 +177,25 @@ function AppView(props: AppViewProps): ReactElement {
removeScriptFinishedHandler,
])

const renderLogo = (appLogo: Logo): ReactElement => {
const displayImage = appLogo.iconImage ? appLogo.iconImage : appLogo.image
const source = endpoints.buildMediaURL(displayImage)

if (appLogo.link) {
return (
<StyledLogoLink
href={appLogo.link}
target="_blank"
rel="noreferrer"
data-testid="stLogoLink"
>
<StyledLogo src={source} alt="Logo" data-testid="stLogo" />
</StyledLogoLink>
)
}
return <StyledLogo src={source} alt="Logo" data-testid="stLogo" />
}

// Activate scroll to bottom whenever there are bottom elements:
const Component = hasBottomElements
? ScrollToBottomContainer
Expand Down Expand Up @@ -198,6 +227,7 @@ function AppView(props: AppViewProps): ReactElement {
<ThemedSidebar
endpoints={endpoints}
initialSidebarState={initialSidebarState}
appLogo={appLogo}
appPages={appPages}
hasElements={hasSidebarElements}
onPageChange={onPageChange}
Expand All @@ -209,6 +239,15 @@ function AppView(props: AppViewProps): ReactElement {
</StyledSidebarBlockContainer>
</ThemedSidebar>
)}
{!showSidebar && appLogo && (
<StyledSidebarOpenContainer
chevronDownshift={sidebarChevronDownshift}
isCollapsed={true}
data-testid="collapsedControl"
>
{renderLogo(appLogo)}
</StyledSidebarOpenContainer>
)}
<Component
tabIndex={0}
isEmbedded={embedded}
Expand Down
4 changes: 2 additions & 2 deletions frontend/app/src/components/Header/styled-components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ export const StyledHeaderDecoration = styled.div(({ theme }) => ({

export const StyledHeaderToolbar = styled.div(({ theme }) => ({
position: "absolute",
top: theme.spacing.sm,
right: theme.spacing.twoXS,
top: theme.spacing.xl,
right: theme.spacing.xl,
display: "flex",
flexDirection: "row",
alignItems: "center",
Expand Down

0 comments on commit 3fa988a

Please sign in to comment.