/* * Copyright (C) 2022 Kristóf Marussy * * This file is part of Sophie. * * Sophie is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * * SPDX-License-Identifier: AGPL-3.0-only */ import FilledInput from '@mui/material/FilledInput'; import { styled } from '@mui/material/styles'; import { autorun } from 'mobx'; import { observer } from 'mobx-react-lite'; import React, { useCallback, useEffect, useState } from 'react'; import Service from '../../stores/Service'; import GoAdornment from './GoAdornment'; import LocationOverlayInput from './LocationOverlayInput'; import UrlAdornment from './UrlAdornment'; import UrlOverlay from './UrlOverlay'; import splitUrl from './splitUrl'; const LocationTextFieldRoot = styled(FilledInput, { name: 'LocationTextField', slot: 'Root', })(({ theme }) => ({ paddingLeft: 12, paddingRight: 12, borderRadius: 20, '&.Mui-focused': { outline: `2px solid ${theme.palette.primary.main}`, }, })); function LocationTextField({ service, }: { service: Service | undefined; }): JSX.Element { const [inputFocused, setInputFocused] = useState(false); const [changed, setChanged] = useState(false); const [value, setValue] = useState(''); const resetValue = useCallback(() => { setValue(service?.currentUrl ?? ''); setChanged(false); }, [service, setChanged, setValue]); useEffect( () => autorun(() => { resetValue(); }), [resetValue], ); const inputRefCallback = useCallback( (input: HTMLInputElement) => { setInputFocused( document.activeElement !== null && document.activeElement === input, ); }, [setInputFocused], ); const splitResult = splitUrl(service?.currentUrl); return ( , }} inputRef={inputRefCallback} onFocus={() => setInputFocused(true)} onBlur={() => setInputFocused(false)} onChange={({ target: { value: newValue } }) => { setValue(newValue); setChanged(true); }} onKeyUp={(event) => { switch (event.key) { case 'Escape': resetValue(); event.preventDefault(); break; case 'Enter': service?.go(value); event.preventDefault(); break; default: // Nothing to do, let the key event through. break; } }} size="small" fullWidth hiddenLabel disableUnderline startAdornment={ } endAdornment={ changed ? service?.go(value)} /> : undefined } value={value} /> ); } export default observer(LocationTextField);