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

Feature: st.logo #8554

Merged
merged 25 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
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
mayagbarnes marked this conversation as resolved.
Show resolved Hide resolved
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.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: it might be a good idea to add a print-test where there is a logo (with sidebar opened and closed).

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.
mayagbarnes marked this conversation as resolved.
Show resolved Hide resolved
mayagbarnes marked this conversation as resolved.
Show resolved Hide resolved
mayagbarnes marked this conversation as resolved.
Show resolved Hide resolved
mayagbarnes marked this conversation as resolved.
Show resolved Hide resolved
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
2 changes: 1 addition & 1 deletion e2e_playwright/st_graphviz_chart_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def test_first_graph_fullscreen(app: Page, assert_snapshot: ImageCompareFunction

def check_dimensions():
svg_dimensions = first_graph_svg.bounding_box()
return svg_dimensions["width"] == 1256 and svg_dimensions["height"] == 662
return svg_dimensions["width"] == 1256 and svg_dimensions["height"] == 648

wait_until(app, check_dimensions)

Expand Down
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 @@ -1324,6 +1328,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 @@ -1835,6 +1840,7 @@ export class App extends PureComponent<Props, State> {
uploadClient={this.uploadClient}
componentRegistry={this.componentRegistry}
formsData={this.state.formsData}
appLogo={this.state.appLogo}
mayagbarnes marked this conversation as resolved.
Show resolved Hide resolved
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"
mayagbarnes marked this conversation as resolved.
Show resolved Hide resolved

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
mayagbarnes marked this conversation as resolved.
Show resolved Hide resolved
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