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

feat(ui): rework theme switching and make navbar responsive #1898

Draft
wants to merge 16 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 36 additions & 42 deletions src/components/navbar/StartStopJoinButton.tsx
Original file line number Diff line number Diff line change
@@ -1,86 +1,80 @@
import React, { RefObject, useState } from 'react';
import Button from '../button';
import cx from 'classnames';
import useComponentVisible from '../../hooks/useComponentVisible';
import React, { useState } from 'react';

import { Device } from '../../types';
import { useTranslation } from 'react-i18next';
import { toHHMMSS } from '../../utils';
import { BridgeApi } from '../../actions/BridgeApi';
import { GlobalState } from '../../store';

import Dropdown from 'react-bootstrap/Dropdown';
import Button from 'react-bootstrap/Button';
import ButtonGroup from 'react-bootstrap/ButtonGroup';

export type StartStopJoinButtonProps = Pick<BridgeApi, 'setPermitJoin'> & Pick<GlobalState, 'bridgeInfo' | 'devices'>;

export function StartStopJoinButton({ devices, setPermitJoin, bridgeInfo }: StartStopJoinButtonProps) {
const { t } = useTranslation(['navbar']);
const { ref, isComponentVisible, setIsComponentVisible } = useComponentVisible(false);
const [selectedRouter, setSelectedRouter] = useState<Device>({} as Device);
const { permit_join: permitJoin, permit_join_timeout: permitJoinTimeout } = bridgeInfo;

const selectAndHide = (device: Device) => {
setSelectedRouter(device);
setIsComponentVisible(false);
const select = (device?: Device) => {
setSelectedRouter(device ? device : {} as Device);
};
const sortByName = (a: Device, b: Device) => a.friendly_name.localeCompare(b.friendly_name);
const prioritizeCoordinator = (a: Device, b: Device) =>
a.type === 'Coordinator' ? -1 : b.type === 'Coordinator' ? 1 : 0;
const routers = Object.values(devices)
.filter((d) => d.type === 'Router' || d.type === 'Coordinator')
.filter((d) => d.type === 'Router')
.sort(sortByName)
.sort(prioritizeCoordinator)
.map((device) => (
<li key={device.friendly_name}>
<Button<Device> item={device} className="dropdown-item" onClick={selectAndHide}>
{device.friendly_name}
</Button>
</li>
<Dropdown.Item key={device.friendly_name} active={selectedRouter?.ieee_address === device.ieee_address ? true : false} onClick={() => { select(device) }}>
{device.friendly_name}
</Dropdown.Item>
));
const coordinator = Object.values(devices)
.filter((d) => d.type === 'Coordinator')
.map((device) => (
<Dropdown.Item key={device.friendly_name} active={selectedRouter?.ieee_address === device.ieee_address ? true : false} onClick={() => { select(device) }}>
{t('zigbee:coordinator')}
</Dropdown.Item>
));

const onBtnClick = () => {
setPermitJoin(!permitJoin, selectedRouter);
};
const permitJoinTimer = (
<>
{permitJoinTimeout ? (
<div className="d-inline-block mx-1" style={{ width: '30px', maxWidth: '30px' }}>
{permitJoin ? (
<div className={'d-inline-block ms-1'}>
{toHHMMSS(permitJoinTimeout)}
</div>
) : null}
</>
);
const buttonLabel = (
<>
{permitJoin ? t('disable_join') : t('permit_join')} ({selectedRouter?.friendly_name ?? t('all')})
{permitJoin ? t('disable_join') : t('permit_join')}
{permitJoinTimer}
</>
);
return (
<div className="btn-group text-nowrap me-1">
<button onClick={onBtnClick} type="button" className="btn btn-outline-secondary">
<Dropdown as={ButtonGroup}>
<Button onClick={onBtnClick} type={'button'} variant={'outline-secondary'}
className={'text-nowrap text-truncate overflow-hidden'} style={{ maxWidth: '300px' }}>
{buttonLabel}
</button>
</Button>
{routers.length ? (
<>
<Button<boolean>
type="button"
className="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split"
onClick={setIsComponentVisible}
item={!isComponentVisible}
>
<span className="visually-hidden">{t('toggle_dropdown')}</span>
</Button>
<ul
ref={ref as RefObject<HTMLUListElement>}
className={cx('dropdown-menu', { show: isComponentVisible })}
>
<li key="all">
<Button className="dropdown-item" onClick={selectAndHide}>
{t('all')}
</Button>
</li>
<Dropdown.Toggle split={true} variant={'outline-secondary'} data-bs-reference={'parent'}>
<span className={'visually-hidden'}>{t('toggle_dropdown')}</span>
</Dropdown.Toggle>
<Dropdown.Menu align="end" className={'my-1'}>
<Dropdown.Item key={'all'} onClick={() => { select(undefined) }} active={selectedRouter?.friendly_name ? false : true}>
{t('all')}
</Dropdown.Item>
{coordinator}
{routers}
</ul>
</Dropdown.Menu>
</>
) : null}
</div>
</Dropdown>
);
}
45 changes: 26 additions & 19 deletions src/components/navbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import { BridgeApi } from '../../actions/BridgeApi';
import { ThemeSwitcher } from '../theme-switcher';
import { WithTranslation, withTranslation } from 'react-i18next';
import LocalePicker from '../../i18n/LocalePicker';
import { isIframe } from '../../utils';
import { StartStopJoinButton } from './StartStopJoinButton';
import { SettingsDropdown } from './SettingsDropdown';

import NavbarBrand from 'react-bootstrap/esm/NavbarBrand';

const urls = [
{
href: '/',
Expand Down Expand Up @@ -54,19 +55,23 @@ const urls = [
type PropsFromStore = Pick<GlobalState, 'devices' | 'bridgeInfo'>;

const NavBar: FunctionComponent<PropsFromStore & ThemeActions & WithTranslation<'navbar'> & BridgeApi> = (props) => {
const { devices, setPermitJoin, bridgeInfo, restartBridge, setTheme, t } = props;
const { devices, setPermitJoin, bridgeInfo, restartBridge, t } = props;
const ref = useRef<HTMLDivElement>();
const [navbarIsVisible, setNavbarIsVisible] = useState<boolean>(false);
useOnClickOutside(ref, () => {
setNavbarIsVisible(false);
});
return (
<nav className="navbar navbar-expand-md navbar-light">
<div ref={ref as React.MutableRefObject<HTMLDivElement>} className="container-fluid">
<Link onClick={() => setNavbarIsVisible(false)} to="/">
{isIframe() ? `Z2M@${document.location.hostname}` : 'Zigbee2MQTT'}
</Link>

<nav className={'navbar navbar-expand-lg'}>
<div ref={ref as React.MutableRefObject<HTMLDivElement>} className="container-fluid align-items-baseline">
<NavbarBrand href="/#/">
<img alt={'Zigbee2MQTT'} src={'/images/logo.png'} width={'30'} height={'30'}
className={'d-inline-block align-top'}
/>{' '}
<Link onClick={() => setNavbarIsVisible(false)} to={'/'}>
{'Zigbee2MQTT'}
</Link>
</NavbarBrand>
<button
onClick={() => {
setNavbarIsVisible(!navbarIsVisible);
Expand All @@ -76,32 +81,34 @@ const NavBar: FunctionComponent<PropsFromStore & ThemeActions & WithTranslation<
>
<span className="navbar-toggler-icon" />
</button>
<div className={cx('navbar-collapse collapse', { show: navbarIsVisible })}>
<ul className="navbar-nav">
<div className={cx('navbar-collapse collapse d-flex flex-wrap', { 'd-none': !navbarIsVisible })}>
<ul className="navbar-nav flex-wrap flex-grow-1">
{urls.map((url) => (
<li key={url.href} className="nav-item">
<NavLink
onClick={() => setNavbarIsVisible(false)}
exact={url.exact}
className="nav-link"
to={url.href}
activeClassName="active"
onClick={() => setNavbarIsVisible(false)}
>
{t(url.key)}
</NavLink>
</li>
))}
</ul>
<div className="d-flex align-self-start align-items-center flex-wrap justify-content-end gap-1 py-2">
<StartStopJoinButton devices={devices} setPermitJoin={setPermitJoin} bridgeInfo={bridgeInfo} />
<SettingsDropdown />
<LocalePicker />
</ul>
<StartStopJoinButton devices={devices} setPermitJoin={setPermitJoin} bridgeInfo={bridgeInfo} />
<ThemeSwitcher saveCurrentTheme={setTheme} />
<ThemeSwitcher />
{bridgeInfo.restart_required ? (
<Button onClick={restartBridge} prompt className="btn btn-danger">
{t('restart')}
</Button>
) : null}
</div>
</div>
{bridgeInfo.restart_required ? (
<Button onClick={restartBridge} prompt className="btn btn-danger me-1">
{t('restart')}
</Button>
) : null}
</div>
</nav>
);
Expand Down
90 changes: 70 additions & 20 deletions src/components/theme-switcher.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,79 @@
import * as React from 'react';
import { useTranslation } from 'react-i18next';

import { useThemeSwitcher } from 'react-css-theme-switcher';
import Button from './button';
import Dropdown from 'react-bootstrap/Dropdown';
import Button from 'react-bootstrap/Button';
import ButtonGroup from 'react-bootstrap/ButtonGroup';

export type Theme = 'light' | 'dark';
export const ThemeSwitcher = (): JSX.Element => {
const { t } = useTranslation(['navbar']);
const getStoredTheme = () => localStorage.getItem('z2m-theme')
const setStoredTheme = theme => localStorage.setItem('z2m-theme', theme)

type ThemeSwitcherProps = {
saveCurrentTheme(theme: Theme): void;
};
export const ThemeSwitcher = (props: ThemeSwitcherProps): JSX.Element => {
const { saveCurrentTheme } = props;
const { switcher, themes, status, currentTheme } = useThemeSwitcher();
const isDarkMode = currentTheme === 'dark';
const getPreferredTheme = () => {
const storedTheme = getStoredTheme()
if (storedTheme) {
return storedTheme
}
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}

const setTheme = theme => {
if (theme === 'auto') {
document.documentElement.setAttribute('data-bs-theme', window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
} else {
document.documentElement.setAttribute('data-bs-theme', theme)
}
}

if (status === 'loading') {
return <div>Loading styles...</div>;
setTheme(getPreferredTheme())
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
const storedTheme = getStoredTheme()
if (storedTheme !== 'light' && storedTheme !== 'dark') {
setTheme(getPreferredTheme())
}
})

const updateTheme = (theme: string) => {
setStoredTheme(theme)
setTheme(getPreferredTheme())
const icon = document.getElementById('theme-dropdown-icon')
icon!.className = getCurrentThemeClass()
}

const getCurrentThemeClass = () => {
const theme = getStoredTheme()
let icon = 'fa-solid'
switch (theme) {
case 'light': { icon += ' fa-sun'; break }
case 'dark': { icon += ' fa-moon'; break }
default: { icon += ' fa-circle-half-stroke'; break }
}
return icon
}
const toggleDarkMode = (light: boolean) => {
const theme = light ? themes.light : themes.dark;
saveCurrentTheme(theme as Theme);
switcher({ theme });
};

return (
<Button<boolean> item={isDarkMode} className="btn btn-info" onClick={toggleDarkMode}>
{isDarkMode ? '🌑' : `🌞`}
</Button>
<Dropdown as={ButtonGroup}>
<Button variant={'outline-secondary'} className={'d-flex align-items-center'}>
<i id={'theme-dropdown-icon'} className={getCurrentThemeClass()} style={{ margin: '0 1px', width: '16px' }}></i>
</Button>
<Dropdown.Toggle split={true} variant={'outline-secondary'} data-bs-reference={'parent'}>
<span className={'visually-hidden'}>{t('toggle_dropdown')}</span>
</Dropdown.Toggle>
<Dropdown.Menu className={'my-1'}>
<Dropdown.Item onClick={(e) => { updateTheme('light') }}>
<i className={'fa-solid fa-sun me-2'} style={{ width: '16px' }}></i>
<span>{t('themes:light')}</span>
</Dropdown.Item>
<Dropdown.Item onClick={(e) => { updateTheme('dark') }}>
<i className={'fa-solid fa-moon me-2'} style={{ width: '16px' }}></i>
<span>{t('themes:dark')}</span>
</Dropdown.Item>
<Dropdown.Item onClick={(e) => { updateTheme('auto') }}>
<i className={'fa-solid fa-circle-half-stroke me-2'} style={{ width: '16px' }}></i>
<span>{t('themes:auto')}</span>
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
);
};
Loading
Loading