I wanted to set a wide layout for portrait and centered layout for landscape using Streamlit-JS-Eval.
I post below my solution with a little spinner, sleep and toast.
Implemented for my profile page.
from streamlit_js_eval import streamlit_js_eval
from time import sleep
sss = st.session_state
def check_layout():
'''With JS evaluation script, gets the width and height of the device.
Sleep a little to get the values from JS.
Then define a layout state depending on which is bigger.
'''
width = streamlit_js_eval(js_expressions='screen.width')
height = streamlit_js_eval(js_expressions='screen.height')
sleep(1)
if width is not None and height is not None:
sss['layout'] = "wide" if width < height else "centered"
def once_set_layout():
'''Search for the device layout and rerun once set.
'''
if 'layout' not in sss:
with st.spinner('Checking your device layout...'):
check_layout()
st.rerun()
def once_layout_toast():
if 'layout_toasted' not in sss:
st.toast(f"{'Narrow' if sss['layout'] == 'wide' else 'Wide'} layout detected.")
sss['layout_toasted'] = True
def __main__():
once_set_layout()
state = st.set_page_config(
layout=sss['layout'],
)
once_layout_toast()
st.info(f"The layout is set as {sss['layout']}")