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

[horiz-layout] Add collapsible_container #1978

Merged
merged 9 commits into from Sep 11, 2020
24 changes: 24 additions & 0 deletions e2e/scripts/st_collapsible_container.py
@@ -0,0 +1,24 @@
# Copyright 2018-2020 Streamlit Inc.
#
# 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 streamlit as st

container = st.container()
container.write("I cannot collapse")

collapsible = st.collapsible_container("Collapse me!")
collapsible.write("I can collapse")

collapsed = st.collapsible_container("Expand me!", collapsed=True)
collapsed.write("I am already collapsed")
71 changes: 71 additions & 0 deletions e2e/specs/st_collapsible_container.spec.ts
@@ -0,0 +1,71 @@
/**
* @license
* Copyright 2018-2020 Streamlit Inc.
*
* 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.
*/

/// <reference types="cypress" />

const toggleIdentifier = "small[data-toggle]";

describe("st.collapsible_container", () => {
before(() => {
cy.visit("http://localhost:3000/");
});

it("displays collapsible + regular containers properly", () => {
cy.get(".stBlock")
.first()
.within(() => {
cy.get(toggleIdentifier).should("not.exist");
});
cy.get(".stBlock")
.eq(1)
.within(() => {
cy.get(toggleIdentifier).should("exist");
});
cy.get(".stBlock")
.eq(2)
.within(() => {
cy.get(toggleIdentifier).should("exist");
});
});

it("collapses + expands", () => {
// Starts expanded
cy.get(".stBlock")
.eq(1)
.within(() => {
let toggle = cy.get(toggleIdentifier);
toggle.should("exist");
toggle.should("have.text", "Hide");
toggle.click();

toggle = cy.get(toggleIdentifier);
toggle.should("have.text", "Show");
});
// Starts collapsed
cy.get(".stBlock")
.eq(2)
.within(() => {
let toggle = cy.get(toggleIdentifier);
toggle.should("exist");
toggle.should("have.text", "Show");
toggle.click();

toggle = cy.get(toggleIdentifier);
toggle.should("have.text", "Hide");
});
});
});
3 changes: 3 additions & 0 deletions frontend/src/assets/css/variables.scss
Expand Up @@ -67,6 +67,9 @@ $font-size-sm: 0.8rem;
$line-height-base: 1.6;
$line-height-tight: 1.25;

// Spacing
$spacer: 1rem;

// Overwrite other theme settings.
$border-radius: 0.25rem;
$border-radius-sm: 0.25rem;
Expand Down
27 changes: 22 additions & 5 deletions frontend/src/components/core/Block/Block.tsx
Expand Up @@ -22,7 +22,7 @@ import { dispatchOneOf } from "lib/immutableProto"
import { ReportRunState } from "lib/ReportRunState"
import { WidgetStateManager } from "lib/WidgetStateManager"
import { makeElementWithInfoText } from "lib/utils"
import { IForwardMsgMetadata } from "autogen/proto"
import { IForwardMsgMetadata, IBlock } from "autogen/proto"
import { ReportElement, BlockElement, SimpleElement } from "lib/DeltaParser"
import { FileUploadClient } from "lib/FileUploadClient"

Expand All @@ -42,6 +42,7 @@ import {
} from "components/widgets/CustomComponent/"

import Maybe from "components/core/Maybe/"
import withCollapsible from "hocs/withCollapsible"

// Lazy-load elements.
const Audio = React.lazy(() => import("components/elements/Audio/"))
Expand Down Expand Up @@ -94,21 +95,30 @@ interface Props {
uploadClient: FileUploadClient
widgetsDisabled: boolean
componentRegistry: ComponentRegistry
deltaBlock?: IBlock
}

class Block extends PureComponent<Props> {
private WithCollapsibleBlock = withCollapsible(Block)

/** Recursively transform this BLockElement and all children to React Nodes. */
private renderElements = (width: number): ReactNode[] => {
const elementsToRender = this.props.elements

// Transform Streamlit elements into ReactNodes.
return elementsToRender
.toArray()
.map((reportElement: ReportElement, index: number): ReactNode | null => {
const element = reportElement.get("element")

if (element instanceof List) {
return this.renderBlock(element as BlockElement, index, width)
return this.renderBlock(
element as BlockElement,
index,
width,
reportElement.get("deltaBlock").toJS()
)
}
// Base case AKA a single element AKA leaf node in the render tree
return this.renderElementWithErrorBoundary(reportElement, index, width)
})
.filter((node: ReactNode | null): ReactNode => node != null)
Expand All @@ -129,11 +139,16 @@ class Block extends PureComponent<Props> {
private renderBlock(
element: BlockElement,
index: number,
width: number
width: number,
deltaBlock: IBlock
): ReactNode {
const BlockType = deltaBlock.collapsible
? this.WithCollapsibleBlock
: Block
const optionalProps = deltaBlock.collapsible ? deltaBlock.collapsible : {}
return (
<div key={index} className="stBlock" style={{ width }}>
<Block
<BlockType
elements={element}
reportId={this.props.reportId}
reportRunState={this.props.reportRunState}
Expand All @@ -142,6 +157,8 @@ class Block extends PureComponent<Props> {
uploadClient={this.props.uploadClient}
widgetsDisabled={this.props.widgetsDisabled}
componentRegistry={this.props.componentRegistry}
deltaBlock={deltaBlock}
{...optionalProps}
/>
</div>
)
Expand Down
18 changes: 18 additions & 0 deletions frontend/src/hocs/withCollapsible/index.tsx
@@ -0,0 +1,18 @@
/**
* @license
* Copyright 2018-2020 Streamlit Inc.
*
* 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.
*/

export { default } from "./withCollapsible"
62 changes: 62 additions & 0 deletions frontend/src/hocs/withCollapsible/withCollapsible.test.tsx
@@ -0,0 +1,62 @@
/**
* @license
* Copyright 2018-2020 Streamlit Inc.
*
* 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 React, { ComponentType } from "react"
import { shallow } from "enzyme"
import withCollapsible, { Props, StyledToggle } from "./withCollapsible"

const testComponent: ComponentType = () => <div>test</div>

const getProps = (props: Partial<ReportElementProps> = {}): Props => ({
label: "hi",
collapsible: true,
...props,
})

describe("withCollapsible HOC", () => {
it("renders without crashing", () => {
const props = getProps()
const WithHoc = withCollapsible(testComponent)
// @ts-ignore
const wrapper = shallow(<WithHoc {...props} />)

expect(wrapper.html()).not.toBeNull()
})

it("should render a expanded component", () => {
const props = getProps()
const WithHoc = withCollapsible(testComponent)
// @ts-ignore
const wrapper = shallow(<WithHoc {...props} />)
const toggleHeader = wrapper.find(StyledToggle)

expect(toggleHeader.exists()).toBeTruthy()
expect(toggleHeader.text()).toEqual("Hide")
})

it("should render a collapsed component", () => {
const props = getProps({
collapsed: true,
})
const WithHoc = withCollapsible(testComponent)
// @ts-ignore
const wrapper = shallow(<WithHoc {...props} />)
const toggleHeader = wrapper.find(StyledToggle)

expect(toggleHeader.text()).toEqual("Show")
})
})
92 changes: 92 additions & 0 deletions frontend/src/hocs/withCollapsible/withCollapsible.tsx
@@ -0,0 +1,92 @@
/**
* @license
* Copyright 2018-2020 Streamlit Inc.
*
* 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 React, { ComponentType, ReactElement, useEffect, useState } from "react"
import { styled } from "styletron-react"
import { colors, variables } from "lib/widgetTheme"

export interface Props {
collapsible: boolean
label: string
collapsed: boolean
}

type ComponentProps = {
collapsed: boolean
}

export const AnimatedComponentWrapper = styled(
akrolsmir marked this conversation as resolved.
Show resolved Hide resolved
"div",
({ collapsed }: ComponentProps) => ({
maxHeight: collapsed ? 0 : "100vh",
overflow: "hidden",
transitionProperty: "max-height",
transitionDuration: "0.5s",
transitionTimingFunction: "ease-in-out",
})
)

export const StyledHeader = styled("div", ({ collapsed }: ComponentProps) => ({
display: "flex",
justifyContent: "space-between",
cursor: "pointer",
borderWidth: 0,
borderBottomWidth: collapsed ? 0 : "1px",
borderStyle: "solid",
borderColor: colors.grayLighter,
marginBottom: variables.spacer,
transitionProperty: "border-bottom-width",
transitionDuration: "0.5s",
transitionTimingFunction: "ease-in-out",
}))

export const StyledToggle = styled("small", {
color: colors.gray,
})

function withCollapsible(
WrappedComponent: ComponentType<any>
): ComponentType<any> {
const CollapsibleComponent = (props: Props): ReactElement => {
const { label, collapsed: initialCollapsed, ...componentProps } = props

const [collapsed, toggleCollapse] = useState<boolean>(initialCollapsed)
useEffect(() => {
karriebear marked this conversation as resolved.
Show resolved Hide resolved
toggleCollapse(initialCollapsed)
}, [initialCollapsed])

const toggle = (): void => toggleCollapse(!collapsed)

return (
<>
<StyledHeader collapsed={collapsed}>
<div>{label}</div>
<StyledToggle onClick={toggle} role="button" data-toggle>
{collapsed ? "Show" : "Hide"}
</StyledToggle>
</StyledHeader>
<AnimatedComponentWrapper collapsed={collapsed}>
<WrappedComponent {...componentProps} />
</AnimatedComponentWrapper>
</>
)
}

return CollapsibleComponent
}

export default withCollapsible