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

Improve swap lang button for language and text swapping #482

Draft
wants to merge 6 commits into
base: master
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
15 changes: 2 additions & 13 deletions src/components/translator/LanguageSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export type Props = {
tgtLang: string;
setTgtLang: (code: string) => void;
recentTgtLangs: Array<string>;
swapLangs?: () => void;

detectLangEnabled: boolean;
detectedLang: string | null;
Expand All @@ -37,7 +38,6 @@ export type Props = {
type SharedProps = Props & {
srcLangs: NamedLangs;
tgtLangs: NamedLangs;
swapLangs?: () => void;
detectingLang: boolean;
setDetectingLang: (detecting: boolean) => void;
onDetectLang: () => void;
Expand Down Expand Up @@ -423,18 +423,7 @@ const DesktopLanguageSelector = ({
};

const LanguageSelector = (props: Props): React.ReactElement => {
const { pairs, srcLang, setSrcLang, recentSrcLangs, setRecentSrcLangs, tgtLang, setTgtLang, setDetectedLang } = props;

const swapLangs = React.useMemo(
() =>
isPair(pairs, tgtLang, srcLang)
? () => {
setSrcLang(tgtLang);
setTgtLang(srcLang);
}
: undefined,
[pairs, setSrcLang, setTgtLang, srcLang, tgtLang],
);
const { pairs, srcLang, setSrcLang, recentSrcLangs, setRecentSrcLangs, setDetectedLang, swapLangs } = props;

const [detectingLang, setDetectingLang] = React.useState(false);

Expand Down
21 changes: 11 additions & 10 deletions src/components/translator/TextTranslationForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ import { useHistory } from 'react-router-dom';
import { useMatomo } from '@datapunt/matomo-tracker-react';

import { DetectCompleteEvent, DetectEvent, PairPrefValues, TranslateEvent, baseUrlParams } from '.';
import { MaxURLLength, buildNewSearch, getUrlParam } from '../../util/url';
import { MaxURLLength, buildNewSearch } from '../../util/url';
import { APyContext } from '../../context';
import { buildUrl as buildWebpageTranslationUrl } from './WebpageTranslationForm';
import { langDirection } from '../../util/languages';
import useLocalStorage from '../../util/useLocalStorage';
import { textUrlParam } from './Translator';
import { useLocalization } from '../../util/localization';

const textUrlParam = 'q';

const instantTranslationPunctuationDelay = 1000,
instantTranslationDelay = 3000;

Expand All @@ -36,6 +34,10 @@ export type Props = {
markUnknown: boolean;
pairPrefs: PairPrefValues;
setLoading: (loading: boolean) => void;
srcText: string;
tgtText: string;
setSrcText: (text: string) => void;
setTgtText: (text: string) => void;
};

const TextTranslationForm = ({
Expand All @@ -45,6 +47,10 @@ const TextTranslationForm = ({
instantTranslation,
pairPrefs,
setLoading,
srcText,
tgtText,
setSrcText,
setTgtText,
}: Props): React.ReactElement => {
const { t } = useLocalization();
const history = useHistory();
Expand All @@ -54,11 +60,6 @@ const TextTranslationForm = ({
const srcTextareaRef = React.useRef<HTMLTextAreaElement>(null);
const tgtTextareaRef = React.useRef<HTMLTextAreaElement>(null);

const [srcText, setSrcText] = useLocalStorage('srcText', '', {
overrideValue: getUrlParam(history.location.search, textUrlParam),
});
const [tgtText, setTgtText] = React.useState('');

React.useEffect(() => {
const baseParams = baseUrlParams({ srcLang, tgtLang });
let search = buildNewSearch({ ...baseParams, [textUrlParam]: srcText });
Expand Down Expand Up @@ -130,7 +131,7 @@ const TextTranslationForm = ({
}
})();
},
[apyFetch, markUnknown, prefs, setLoading, srcLang, srcText, tgtLang, trackEvent],
[apyFetch, markUnknown, prefs, setLoading, setTgtText, srcLang, srcText, tgtLang, trackEvent],
);

const translationTimer = React.useRef<number | null>(null);
Expand Down
47 changes: 42 additions & 5 deletions src/components/translator/Translator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import useLocalStorage from '../../util/useLocalStorage';
import { useLocalization } from '../../util/localization';

const recentLangsCount = 3;
const textUrlParam = 'q';

const defaultSrcLang = (pairs: Pairs): string => {
const browserLangs = window.navigator.languages;
Expand Down Expand Up @@ -150,18 +151,25 @@ type WithTgtLangsProps = {
setRecentTgtLangs: (langs: Array<string>) => void;
pairPrefs: PairPrefValues;
setPairPrefs: (prefs: PairPrefValues) => void;
swapLangs?: () => void;
};

const WithTgtLang = ({
pairs,
srcLang,
tgtText,
setSrcText,
setSrcLang,
urlTgtLang,
selectedPrefs,
setSelectedPrefs,
children,
}: {
pairs: Pairs;
srcLang: string;
tgtText: string;
setSrcText: (text: string) => void;
setSrcLang: (lang: string) => void;
urlTgtLang: string | null;
selectedPrefs: Record<string, PairPrefValues>;
setSelectedPrefs: (prefs: Record<string, PairPrefValues>) => void;
Expand Down Expand Up @@ -236,8 +244,18 @@ const WithTgtLang = ({
},
[pair, selectedPrefs, setSelectedPrefs],
);

return children({ tgtLang, setTgtLang, recentTgtLangs, setRecentTgtLangs, pairPrefs, setPairPrefs });
const swapLangs = React.useMemo(
Copy link
Member

Choose a reason for hiding this comment

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

This should be React.useCallback?

() =>
isPair(pairs, tgtLang, srcLang)
? () => {
setSrcLang(tgtLang);
setTgtLang(srcLang);
setSrcText(tgtText);
}
: undefined,
[pairs, setSrcLang, setTgtLang, setSrcText, srcLang, tgtLang, tgtText],
);
return children({ tgtLang, setTgtLang, recentTgtLangs, setRecentTgtLangs, pairPrefs, setPairPrefs, swapLangs });
};

const Translator = ({ mode: initialMode }: { mode?: Mode }): React.ReactElement => {
Expand All @@ -248,6 +266,10 @@ const Translator = ({ mode: initialMode }: { mode?: Mode }): React.ReactElement
const config = React.useContext(ConfigContext);

const [loading, setLoading] = React.useState(false);
const [srcText, setSrcText] = useLocalStorage('srcText', '', {
overrideValue: getUrlParam(history.location.search, textUrlParam),
});
const [tgtText, setTgtText] = React.useState('');

const [markUnknown, setMarkUnknown] = useLocalStorage('markUnknown', false);
const [instantTranslation, setInstantTranslation] = useLocalStorage('instantTranslation', true);
Expand Down Expand Up @@ -289,8 +311,10 @@ const Translator = ({ mode: initialMode }: { mode?: Mode }): React.ReactElement
detectedLang,
setDetectedLang,
}: WithSrcLangsProps) => (
<WithTgtLang {...{ pairs, srcLang, urlTgtLang, selectedPrefs, setSelectedPrefs }}>
{({ tgtLang, setTgtLang, recentTgtLangs, pairPrefs, setPairPrefs }: WithTgtLangsProps) => (
<WithTgtLang
{...{ pairs, srcLang, tgtText, setSrcText, setSrcLang, urlTgtLang, selectedPrefs, setSelectedPrefs }}
>
{({ tgtLang, setTgtLang, recentTgtLangs, pairPrefs, setPairPrefs, swapLangs }: WithTgtLangsProps) => (
<>
<LanguageSelector
detectLangEnabled={mode === Mode.Text}
Expand All @@ -307,12 +331,24 @@ const Translator = ({ mode: initialMode }: { mode?: Mode }): React.ReactElement
tgtLang,
detectedLang,
loading,
swapLangs,
}}
/>
{(mode === Mode.Text || !mode) && (
<>
<TextTranslationForm
{...{ instantTranslation, markUnknown, setLoading, srcLang, tgtLang, pairPrefs }}
{...{
instantTranslation,
markUnknown,
setLoading,
srcLang,
tgtLang,
pairPrefs,
srcText,
tgtText,
setSrcText,
setTgtText,
}}
/>
<Row className="mt-2 mb-3">
<Col className="d-flex d-sm-block flex-wrap translation-modes" md="6" xs="12">
Expand Down Expand Up @@ -377,4 +413,5 @@ const Translator = ({ mode: initialMode }: { mode?: Mode }): React.ReactElement
);
};

export { textUrlParam };
export default Translator;
8 changes: 4 additions & 4 deletions src/components/translator/__tests__/LanguageSelector.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const renderLanguageSelector = (props_: Partial<Props> = {}): Props => {
detectLangEnabled: true,
detectedLang: null,
setDetectedLang: jest.fn(),
swapLangs: jest.fn(),
...props_,
};

Expand Down Expand Up @@ -84,20 +85,19 @@ it('switches between mobile and desktop', () => {

describe('swapping', () => {
it('does not allow swapping when swapped pair invalid', () => {
renderLanguageSelector();
renderLanguageSelector({ swapLangs: undefined });
Copy link
Member

Choose a reason for hiding this comment

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

I don't think this is testing what the test description describes anymore?


expect((screen.getByTestId('swap-langs-button') as HTMLButtonElement).disabled).toBeTruthy();
});

it('allow swapping when swapped pair valid', () => {
const { srcLang, tgtLang, setSrcLang, setTgtLang } = renderLanguageSelector({
const { swapLangs } = renderLanguageSelector({
tgtLang: 'spa',
});

userEvent.click(screen.getByTestId('swap-langs-button'));

expect(setSrcLang).toHaveBeenCalledWith(tgtLang);
expect(setTgtLang).toHaveBeenCalledWith(srcLang);
expect(swapLangs).toHaveBeenCalled();
});
});

Expand Down
43 changes: 41 additions & 2 deletions src/components/translator/__tests__/TextTranslationForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import userEvent from '@testing-library/user-event';

import { DetectCompleteEvent, DetectEvent, TranslateEvent } from '..';
import TextTranslationForm, { Props } from '../TextTranslationForm';
import { getUrlParam } from '../../../util/url';
import { textUrlParam } from '../Translator';
import useLocalStorage from '../../../util/useLocalStorage';

const renderTextTranslationForm = (
props_: Partial<Props> = {},
Expand All @@ -20,13 +23,34 @@ const renderTextTranslationForm = (
srcLang: 'eng',
tgtLang: 'spa',
pairPrefs: {},
srcText: '',
tgtText: '',
setSrcText: jest.fn(),
setTgtText: jest.fn(),
setLoading: jest.fn(),
...props_,
};

const Wrapper = () => {
const [srcText, setSrcText] = useLocalStorage('srcText', '', {
overrideValue: getUrlParam(history.location.search, textUrlParam),
});
Copy link
Member

Choose a reason for hiding this comment

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

Why do we need to duplicate this code in a test...?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

To be honest, I'm currently stuck here, and I'm not entirely sure why I went with this approach. It seems to be the only way the tests are passing, and I need your help on how to improve this setup. The functionality of TextTranslationForm is closely tied to state variables passed as props from its parent.

Copy link
Member

Choose a reason for hiding this comment

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

The problem is that the tests need to be relocated now. Moving the logic that pulls srcText from local storage from TextTranslationForm to Translator means that the tests which verify that functionality need to be moved to Translator.test.tsx.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I realized that my knowledge of React testing might be a bit lacking. I plan to learn jest, and then I'll resume working on the pull request at a later point in time. I'll focus on other issues for now i.e. #405

const [tgtText, setTgtText] = React.useState('');

return (
<TextTranslationForm
{...props}
setSrcText={setSrcText}
setTgtText={setTgtText}
srcText={srcText}
tgtText={tgtText}
/>
);
};

render(
<Router history={history}>
<TextTranslationForm {...props} />
<Wrapper />
</Router>,
);

Expand Down Expand Up @@ -149,16 +173,31 @@ describe('translation', () => {
srcLang: 'eng',
tgtLang: 'spa',
pairPrefs: {},
srcText: '',
tgtText: '',
setSrcText: jest.fn(),
setTgtText: jest.fn(),
setLoading: jest.fn(),
};

const Container = () => {
const [srcLang, setSrcLang] = React.useState('eng');
const [srcText, setSrcText] = useLocalStorage('srcText', '', {
overrideValue: getUrlParam(history.location.search, textUrlParam),
});
const [tgtText, setTgtText] = React.useState('');
Copy link
Member

Choose a reason for hiding this comment

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

Same question here as above.

return (
<>
<button onClick={() => setSrcLang('cat')}>ChangeSrcLang</button>
<Router history={history}>
<TextTranslationForm {...props} srcLang={srcLang} />
<TextTranslationForm
{...props}
setSrcText={setSrcText}
setTgtText={setTgtText}
srcLang={srcLang}
srcText={srcText}
tgtText={tgtText}
/>
</Router>
</>
);
Expand Down
Loading