import React, { useState, useReducer } from 'react'; import { FormState, UseFormRegister, UseFormSetValue } from 'react-hook-form'; import { FieldValues } from 'react-hook-form/dist/types/fields'; import { User } from '../../models/user'; import { SocialNetwork } from '../../models/social-network'; import Icons from '../../../../images/social-icons.svg'; import { FormInput } from '../form/form-input'; import { Trash } from 'phosphor-react'; import { useTranslation } from 'react-i18next'; interface EditSocialsProps { register: UseFormRegister, setValue: UseFormSetValue, networks: SocialNetwork[], formState: FormState, disabled: boolean|((id: string) => boolean), } /** * Allow a user to edit its personnal social networks */ export const EditSocials = ({ register, setValue, networks, formState, disabled }: EditSocialsProps) => { const { t } = useTranslation('shared'); // regular expression to validate the the input fields const urlRegex = /^(https?:\/\/)([^.]+)\.(.{2,30})(\/.*)*\/?$/; const initSelectedNetworks = networks.filter(el => !['', null, undefined].includes(el.url)); const [selectedNetworks, setSelectedNetworks] = useState(initSelectedNetworks); /** * Callback triggered when the user adds a network, from the list of available networks, to the editable networks. */ const selectNetwork = (network) => { setSelectedNetworks([...selectedNetworks, network]); }; /** * Return a derivated state of the selected networks list, depending on the given action. */ const reducer = (state, action) => { switch (action.type) { case 'delete': setSelectedNetworks(selectedNetworks.filter(el => el !== action.payload.network)); setValue(action.payload.field, ''); return state.map(el => el === action.payload.network ? { ...el, url: '' } : el); case 'update': return state.map(el => el === action.payload ? { ...el, url: action.payload.url } : el); default: return state; } }; const [userNetworks, dispatch] = useReducer(reducer, networks); return ( <>
{userNetworks.map((network, index) => !selectedNetworks.includes(network) && selectNetwork(network)} viewBox="0 0 24 24" > )}
{selectNetwork.length &&
{userNetworks.map((network, index) => selectedNetworks.includes(network) && } addOn={} addOnAction={() => dispatch({ type: 'delete', payload: { network, field: `profile_attributes.${network.name}` } })} /> )}
} ); };