Skip to content

Commit

Permalink
fix: implement custom register fields in Account section
Browse files Browse the repository at this point in the history
  • Loading branch information
mirovladimitrovski committed Jun 7, 2023
1 parent ca54c2c commit 4aa35f5
Show file tree
Hide file tree
Showing 12 changed files with 108 additions and 45 deletions.
1 change: 1 addition & 0 deletions public/locales/en/user.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"firstname": "First name",
"hide_password": "Hide password",
"lastname": "Last name",
"other_registration_details": "Other registration details",
"password": "Password",
"save": "Save",
"security": "Security",
Expand Down
1 change: 0 additions & 1 deletion public/locales/en/video.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"current_episode": "Current episode",
"current_video": "Current video",
"episode": "episode",
"episode_not_found": "Episode not found",
"episodes": "Episodes",
"favorite": "Favorite",
"favorites_warning": "Maximum amount of favorite videos exceeded. You can only add up to {{maxCount}} favorite videos. Please delete one and repeat the operation.",
Expand Down
1 change: 1 addition & 0 deletions public/locales/es/user.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"firstname": "Nombre",
"hide_password": "Ocultar contraseña",
"lastname": "Apellido",
"other_registration_details": "Otros detalles de registro",
"password": "Contraseña",
"save": "Guardar",
"security": "Seguridad",
Expand Down
1 change: 0 additions & 1 deletion public/locales/es/video.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"current_episode": "Episodio actual",
"current_video": "Video actual",
"episode": "episodio",
"episode_not_found": "Episodio no encontrado",
"episodes": "Episodios",
"favorite": "Favorito",
"favorites_warning": "Se ha alcanzado el máximo de videos favoritos. Solo puedes agregar hasta {{maxCount}} videos favoritos. Por favor, elimina uno y repite la operación.",
Expand Down
6 changes: 6 additions & 0 deletions src/components/Account/Account.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,9 @@
flex-direction: column;
gap: 1rem;
}

.customFields {
display: flex;
flex-direction: column;
gap: 0.5em;
}
48 changes: 43 additions & 5 deletions src/components/Account/Account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useMutation } from 'react-query';
import styles from './Account.module.scss';

import type { FormSectionContentArgs, FormSectionProps } from '#components/Form/FormSection';
import type { ConsentFieldVariants } from '#src/services/inplayer.account.service';
import Alert from '#components/Alert/Alert';
import Visibility from '#src/icons/Visibility';
import VisibilityOff from '#src/icons/VisibilityOff';
Expand All @@ -17,8 +18,9 @@ import IconButton from '#components/IconButton/IconButton';
import TextField from '#components/TextField/TextField';
import Checkbox from '#components/Checkbox/Checkbox';
import HelperText from '#components/HelperText/HelperText';
import CustomRegisterField from '#components/CustomRegisterField/CustomRegisterField';
import useToggle from '#src/hooks/useToggle';
import { formatConsentsFromValues, formatConsentValues } from '#src/utils/collection';
import { formatConsentsFromValues, formatConsents, formatConsentValues } from '#src/utils/collection';
import { addQueryParam } from '#src/utils/location';
import { useAccountStore } from '#src/stores/AccountStore';
import { logDev } from '#src/utils/common';
Expand Down Expand Up @@ -64,15 +66,25 @@ const Account = ({ panelClassName, panelHeaderClassName, canUpdateEmail = true }
shallow,
);

const consentValues = useMemo(() => formatConsentValues(publisherConsents, customerConsents), [publisherConsents, customerConsents]);
const [termsConsents, nonTermsConsents] = useMemo(() => {
const terms = (publisherConsents || []).filter((consent) => consent.name === 'terms');
const nonTerms = publisherConsents?.filter((consent) => consent.name !== 'terms');

return [terms, nonTerms];
}, [publisherConsents]);

const consents = useMemo(() => formatConsents(publisherConsents, customerConsents), [publisherConsents, customerConsents]);

const consentsValues = useMemo(() => formatConsentValues(publisherConsents, customerConsents), [publisherConsents, customerConsents]);

const initialValues = useMemo(
() => ({
...customer,
consents: consentValues,
consents,
consentsValues,
confirmationPassword: '',
}),
[customer, consentValues],
[customer, consents, consentsValues],
);

const formatConsentLabel = (label: string): string | JSX.Element => {
Expand Down Expand Up @@ -250,7 +262,7 @@ const Account = ({ panelClassName, panelHeaderClassName, canUpdateEmail = true }
onSubmit: (values) => updateConsents(formatConsentsFromValues(publisherConsents, values)),
content: (section) => (
<>
{publisherConsents?.map((consent, index) => (
{termsConsents?.map((consent, index) => (
<Checkbox
key={index}
name={`consents.${consent.name}`}
Expand All @@ -264,6 +276,32 @@ const Account = ({ panelClassName, panelHeaderClassName, canUpdateEmail = true }
</>
),
}),
...(nonTermsConsents
? [
formSection({
label: t('account.other_registration_details'),
saveButton: t('account.update_consents'),
onSubmit: (values) => updateConsents(formatConsentsFromValues(nonTermsConsents, values.consentsValues)),
content: (section) => (
<div className={styles.customFields}>
{nonTermsConsents.map((consent) => (
<CustomRegisterField
key={consent.name}
type={consent.type as ConsentFieldVariants}
name={`consentsValues.${consent.name}`}
options={consent.options}
label={formatConsentLabel(consent.label)}
placeholder={consent.placeholder}
value={`${section.values.consentsValues[consent.name] || ''}`}
disabled={consent.required || section.isBusy}
onChange={section.onChange}
/>
))}
</div>
),
}),
]
: []),
...(canExportAccountData
? [
formSection({
Expand Down
38 changes: 19 additions & 19 deletions src/components/Account/__snapshots__/Account.test.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -138,29 +138,29 @@ exports[`<Account> > renders and matches snapshot 1`] = `
account.terms_and_tracking
</h3>
</div>
<div
class="_flexBox_1c1c63"
/>
<div
class="_controls_1c1c63"
/>
</div>
<div
class="panel-class"
>
<div
class="header-class"
>
<h3>
account.other_registration_details
</h3>
</div>
<div
class="_flexBox_1c1c63"
>
<div
class="_checkbox_531f07"
>
<div
class="_row_531f07"
>
<input
id="check-box_1235_consents.marketing"
name="consents.marketing"
type="checkbox"
value=""
/>
<label
for="check-box_1235_consents.marketing"
>
Receive Marketing Emails
</label>
</div>
</div>
class="_customFields_c968f7"
/>
</div>
<div
class="_controls_1c1c63"
Expand Down
17 changes: 3 additions & 14 deletions src/components/CustomRegisterField/CustomRegisterField.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type FC, type ChangeEventHandler, type ReactNode, useMemo, useCallback } from 'react';
import { type FC, type ChangeEventHandler, type ReactNode, useMemo } from 'react';
import type { GetRegisterFieldOption } from '@inplayer-org/inplayer.js';

import Checkbox from '#components/Checkbox/Checkbox';
Expand All @@ -12,7 +12,7 @@ type Props = {
type: ConsentFieldVariants;
name: string;
value: string;
onChange: (name: string, value: string) => void;
onChange: ChangeEventHandler<HTMLInputElement>;
} & Partial<{
label: ReactNode;
placeholder: string;
Expand All @@ -26,17 +26,6 @@ type Props = {
export type CustomRegisterFieldCommonProps = Props;

export const CustomRegisterField: FC<Props> = ({ type, name, value = '', onChange, ...props }) => {
const changeHandler: ChangeEventHandler<HTMLInputElement> = useCallback(
(e) => {
if (type === ConsentFieldVariants.CHECKBOX) {
onChange(name, `${e.target.checked}`);
} else {
onChange(name, e.target.value);
}
},
[type, name, onChange],
);

const optionsList = useMemo(() => {
const optionsObject = (() => {
switch (type) {
Expand All @@ -56,7 +45,7 @@ export const CustomRegisterField: FC<Props> = ({ type, name, value = '', onChang
return Object.entries(optionsObject).map(([value, label]) => ({ value, label }));
}, [type, props.options]);

const commonProps = { ...props, name, onChange: changeHandler };
const commonProps = { ...props, name, onChange };

switch (type) {
case ConsentFieldVariants.CHECKBOX:
Expand Down
2 changes: 1 addition & 1 deletion src/components/Form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function Form<TData extends GenericFormValues>({ isLoading, initialValues, onRes
}}
>
{children?.map((props, i) => (
<FormSection key={i} {...props} />
<FormSection<TData> key={i} {...props} />
))}
</FormContext.Provider>
);
Expand Down
2 changes: 1 addition & 1 deletion src/components/Form/FormSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function FormSection<TData extends GenericFormValues>({
if (!currentTarget) return;

const { name, type } = currentTarget;
const value = type === 'checkbox' ? (currentTarget as HTMLInputElement).checked : currentTarget.value;
const value = type === 'checkbox' ? `${(currentTarget as HTMLInputElement).checked}` : currentTarget.value;

if (!isEditing) {
onCancel();
Expand Down
13 changes: 11 additions & 2 deletions src/components/RegistrationForm/RegistrationForm.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { type ChangeEventHandler } from 'react';
import { useLocation } from 'react-router';
import { useTranslation } from 'react-i18next';
import DOMPurify from 'dompurify';
Expand Down Expand Up @@ -68,6 +68,15 @@ const RegistrationForm: React.FC<Props> = ({
return label;
};

const changeHandler: ChangeEventHandler<HTMLInputElement> = ({ currentTarget }) => {
if (!currentTarget) return;

const { name, type } = currentTarget;
const value = type === 'checkbox' ? `${(currentTarget as HTMLInputElement).checked}` : currentTarget.value;

onConsentChange(name, value);
};

if (loading) {
return (
<div style={{ height: 400 }}>
Expand Down Expand Up @@ -127,7 +136,7 @@ const RegistrationForm: React.FC<Props> = ({
required={consent.required}
error={consentErrors?.includes(consent.name)}
helperText={consentErrors?.includes(consent.name) ? t('registration.consent_required') : undefined}
onChange={onConsentChange}
onChange={changeHandler}
/>
))}
</div>
Expand Down
23 changes: 22 additions & 1 deletion src/utils/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,24 @@ const formatConsentValues = (publisherConsents: Consent[] | null = [], customerC
if (!publisherConsents || !customerConsents) {
return {};
}

const values: Record<string, string> = {};

publisherConsents?.forEach((publisherConsent) => {
const consent = customerConsents?.find((customerConsent) => customerConsent.name === publisherConsent.name);

if (consent) {
values[publisherConsent.name] = consent.value ?? '';
}
});

return values;
};

const formatConsents = (publisherConsents: Consent[] | null = [], customerConsents: CustomerConsent[] | null = []) => {
if (!publisherConsents || !customerConsents) {
return {};
}
const values: Record<string, boolean> = {};
publisherConsents?.forEach((publisherConsent) => {
if (customerConsents?.find((customerConsent) => customerConsent.name === publisherConsent.name && customerConsent.state === 'accepted')) {
Expand Down Expand Up @@ -102,7 +120,8 @@ const formatConsentsFromValues = (publisherConsents: Consent[] | null, values?:
consents.push({
name: consent.name,
version: consent.version,
state: values.consents[consent.name] ? 'accepted' : 'declined',
state: values[consent.name] ? 'accepted' : 'declined',
value: `${values[consent.name] ?? ''}`,
});
});

Expand All @@ -124,6 +143,7 @@ const checkConsentsFromValues = (publisherConsents: Consent[], consents: Record<
name: consent.name,
version: consent.version,
state: consents[consent.name] ? 'accepted' : 'declined',
value: `${consents[consent.name] ?? ''}`,
});
});

Expand Down Expand Up @@ -158,6 +178,7 @@ export {
findPlaylistImageForWidth,
generatePlaylistPlaceholder,
formatConsentValues,
formatConsents,
formatConsentsFromValues,
extractConsentValues,
checkConsentsFromValues,
Expand Down

0 comments on commit 4aa35f5

Please sign in to comment.