// Dependencies import { useState, useEffect, useContext } from 'react' import { useTranslation } from 'next-i18next' import { measurements } from 'config/measurements.mjs' import { measurements as designMeasurements } from 'shared/prebuild/data/design-measurements.mjs' import { freeSewingConfig as conf, controlLevels } from 'shared/config/freesewing.config.mjs' import { siteConfig } from 'site/site.config.mjs' import { shortDate, cloudflareImageUrl, formatMm, hasRequiredMeasurements, capitalize, horFlexClasses, } from 'shared/utils.mjs' import orderBy from 'lodash.orderby' // Hooks import { useAccount } from 'shared/hooks/use-account.mjs' import { useBackend } from 'shared/hooks/use-backend.mjs' import { useRouter } from 'next/router' import { useLoadingStatus } from 'shared/hooks/use-loading-status.mjs' // Context import { ModalContext } from 'shared/context/modal-context.mjs' // Components import { Popout } from 'shared/components/popout/index.mjs' import { Tag } from 'shared/components/tag.mjs' import { BackToAccountButton } from './shared.mjs' import { AnchorLink, PageLink, Link } from 'shared/components/link.mjs' import { V3Wip } from 'shared/components/v3-wip.mjs' import { OkIcon, NoIcon, TrashIcon, EditIcon, UploadIcon, ResetIcon, PlusIcon, WarningIcon, FilterIcon, CameraIcon, } from 'shared/components/icons.mjs' import { ModalWrapper } from 'shared/components/wrappers/modal.mjs' import Markdown from 'react-markdown' import Timeago from 'react-timeago' import { DisplayRow } from './shared.mjs' import { isDegreeMeasurement } from 'config/measurements.mjs' import { DynamicOrgDocs } from 'shared/components/dynamic-docs/org.mjs' import { StringInput, PassiveImageInput, ListInput, MarkdownInput, MeasieInput, DesignDropdown, ns as inputNs, } from 'shared/components/inputs.mjs' export const ns = [inputNs, 'account', 'patterns', 'status', 'measurements', 'sets'] export const NewSet = () => { // Hooks const { setLoadingStatus, LoadingStatus } = useLoadingStatus() const backend = useBackend() const { t } = useTranslation(ns) const router = useRouter() // State const [name, setName] = useState('') // Helper method to create a new set const createSet = async () => { setLoadingStatus([true, 'processingUpdate']) const result = await backend.createSet({ name }) if (result.success) { setLoadingStatus([true, t('nailedIt'), true, true]) router.push(`/account/sets/${result.data.set.id}`) } else setLoadingStatus([true, 'backendError', true, false]) } return (
{t('name')}

{t('setNameDesc')}

setName(evt.target.value)} className="input w-full input-bordered flex flex-row" type="text" placeholder={'Georg Cantor'} />
) } export const MeasieVal = ({ val, m, imperial }) => isDegreeMeasurement(m) ? {val}° : {formatMm(val, imperial)} export const MsetCard = ({ set, onClick = false, href = false, useA = false, design = false, language = false, size = 'lg', }) => { const sizes = { lg: 96, md: 52, sm: 36, } const s = sizes[size] const wrapperProps = { className: `bg-base-300 aspect-square h-${s} w-${s} mb-2 mx-auto flex flex-col items-start text-center justify-between rounded-none md:rounded shadow`, style: { backgroundImage: `url(${cloudflareImageUrl({ type: 'w500', id: set.img })})`, backgroundSize: 'cover', backgroundRepeat: 'no-repeat', backgroundPosition: '50%', }, } if (!set.img || set.img === 'default-avatar') wrapperProps.style.backgroundPosition = 'bottom right' let icon = if (design) { const [hasMeasies] = hasRequiredMeasurements(designMeasurements[design], set.measies, true) const iconClasses = 'w-8 h-8 p-1 rounded-full -mt-2 -ml-2 shadow' icon = hasMeasies ? ( ) : ( ) } const inner = ( <> {icon} {language ? set[`name${capitalize(language)}`] : set.name} ) // Is it a button with an onClick handler? if (onClick) return ( ) // Returns a link to an internal page if (href && !useA) return ( {inner} ) // Returns a link to an external page if (href && useA) return ( {inner} ) // Returns a div return
{inner}
} export const Mset = ({ id, publicOnly = false }) => { // Hooks const { account, control } = useAccount() const { setLoadingStatus, LoadingStatus } = useLoadingStatus() const backend = useBackend() const { t, i18n } = useTranslation(ns) // FIXME: implement a solution for loading docs dynamically the is simple and work as expected const docs = {} for (const option of ['name', 'units', 'public', 'notes', 'image']) { docs[option] = } // FIXME: implement a solution for loading docs dynamically the is simple and work as expected const measieDocs = {} for (const m of measurements) { measieDocs[m] = } // Context const { setModal } = useContext(ModalContext) const [filter, setFilter] = useState(false) const [edit, setEdit] = useState(false) const [mset, setMset] = useState() // Set fields for editing const [name, setName] = useState(mset?.name) const [image, setImage] = useState(mset?.image) const [isPublic, setIsPublic] = useState(mset?.public ? true : false) const [imperial, setImperial] = useState(mset?.imperial ? true : false) const [notes, setNotes] = useState(mset?.notes || '') const [measies, setMeasies] = useState({}) // Effect useEffect(() => { const getSet = async () => { setLoadingStatus([true, t('backendLoadingStarted')]) const result = await backend.getSet(id) if (result.success) { setMset(result.data.set) setName(result.data.set.name) setImage(result.data.set.image) setIsPublic(result.data.set.public ? true : false) setImperial(result.data.set.imperial ? true : false) setNotes(result.data.set.notes) setMeasies(result.data.set.measies) setLoadingStatus([true, 'backendLoadingCompleted', true, true]) } else setLoadingStatus([true, 'backendError', true, false]) } const getPublicSet = async () => { setLoadingStatus([true, t('backendLoadingStarted')]) const result = await backend.getPublicSet(id) if (result.success) { setMset({ ...result.data, public: true, measies: result.data.measurements, }) setName(result.data.name) setImage(result.data.image) setIsPublic(result.data.public ? true : false) setImperial(result.data.imperial ? true : false) setNotes(result.data.notes) setMeasies(result.data.measurements) setLoadingStatus([true, 'backendLoadingCompleted', true, true]) } else setLoadingStatus([true, 'backendError', true, false]) } if (id) { if (publicOnly) getPublicSet() else getSet() } }, [id, publicOnly]) const filterMeasurements = () => { if (!filter) return measurements.map((m) => t(`measurements:${m}`) + `|${m}`).sort() else return designMeasurements[filter].map((m) => t(`measurements:${m}`) + `|${m}`).sort() } if (!id || !mset) return null const updateMeasies = (m, val) => { const newMeasies = { ...measies } newMeasies[m] = val setMeasies(newMeasies) } const save = async () => { setLoadingStatus([true, 'gatheringInfo']) // Compile data const data = { measies: {} } if (name || name !== mset.name) data.name = name if (image || image !== mset.image) data.img = image if ([true, false].includes(isPublic) && isPublic !== mset.public) data.public = isPublic if ([true, false].includes(imperial) && imperial !== mset.imperial) data.imperial = imperial if (notes || notes !== mset.notes) data.notes = notes // Add measurements for (const m of measurements) { if (measies[m] || measies[m] !== mset.measies[m]) data.measies[m] = measies[m] } setLoadingStatus([true, 'savingSet']) const result = await backend.updateSet(mset.id, data) if (result.success) { setMset(result.data.set) setEdit(false) setLoadingStatus([true, 'nailedIt', true, true]) } else setLoadingStatus([true, 'backendError', true, false]) } const heading = ( <>
{account.control > 3 && mset.public ? ( ) : ( )} {!publicOnly && ( <> {edit ? ( <> ) : ( )} )}
) if (!edit) return (
{heading} {Object.keys(mset.measies).length > 0 && ( <>

{t('measies')}

{Object.entries(mset.measies).map(([m, val]) => val > 0 ? ( } key={m}> {t(m)} ) : null )} )}

{t('data')}

{mset.name} {mset.imperial ? t('imerialUnits') : t('metricUnits')} {control >= controlLevels.sets.notes && ( {mset.notes} )} {control >= controlLevels.sets.public && ( <> {mset.public ? ( ) : ( )} {mset.public && ( )} )} {control >= controlLevels.sets.createdAt && ( | {shortDate(i18n.language, mset.createdAt, false)} )} {control >= controlLevels.sets.createdAt && ( | {shortDate(i18n.language, mset.createdAt, false)} )} {control >= controlLevels.sets.id && {mset.id}}
) return (
{heading}
    {['measies', 'data'].map((s) => (
  • ))}
    • {account.control >= conf.account.sets.img ? (
    • ) : null} {['public', 'units', 'notes'].map((id) => account.control >= conf.account.sets[id] ? (
    • ) : null )}

{t('measies')}

{t('noFilter')}} docs={

{t('measies')}: {t('filterByDesign')}

If you have a specific design in mind, you can filter by design to only list those measurements that are required for this design.

} />
{filterMeasurements().map((mplus) => { const [translated, m] = mplus.split('|') return ( ) })}

{t('data')}

{/* Name is always shown */} val && val.length > 0} /> {/* img: Control level determines whether or not to show this */} {account.control >= conf.account.sets.img ? ( val.length > 0} /> ) : null} {/* public: Control level determines whether or not to show this */} {account.control >= conf.account.sets.public ? ( {t('publicSet')}
), desc: t('publicSetDesc'), }, { val: false, label: (
{t('privateSet')}
), desc: t('privateSetDesc'), }, ]} current={isPublic} /> ) : null} {/* units: Control level determines whether or not to show this */} {account.control >= conf.account.sets.units ? ( {t('metricUnits')} cm ), desc: t('metricUnitsd'), }, { val: true, label: (
{t('imperialUnits')}
), desc: t('imperialUnitsd'), }, ]} current={imperial} /> ) : null} {/* notes: Control level determines whether or not to show this */} {account.control >= conf.account.sets.notes ? ( ) : null} ) } // Component for the account/sets page export const Sets = () => { // Hooks const { control } = useAccount() const backend = useBackend() const { t } = useTranslation(ns) const { setLoadingStatus, LoadingStatus, LoadingProgress } = useLoadingStatus() // State const [sets, setSets] = useState([]) const [selected, setSelected] = useState({}) const [refresh, setRefresh] = useState(0) // Effects useEffect(() => { const getSets = async () => { const result = await backend.getSets() if (result.success) setSets(result.data.sets) } getSets() }, [refresh]) // Helper var to see how many are selected const selCount = Object.keys(selected).length // Helper method to toggle single selection const toggleSelect = (id) => { const newSelected = { ...selected } if (newSelected[id]) delete newSelected[id] else newSelected[id] = 1 setSelected(newSelected) } // Helper method to toggle select all const toggleSelectAll = () => { if (selCount === sets.length) setSelected({}) else { const newSelected = {} for (const set of sets) newSelected[set.id] = 1 setSelected(newSelected) } } // Helper to delete one or more measurements sets const removeSelectedSets = async () => { let i = 0 for (const id in selected) { i++ await backend.removeSet(id) setLoadingStatus([ true, , ]) } setSelected({}) setRefresh(refresh + 1) setLoadingStatus([true, 'nailedIt', true, true]) } return (

{t('newSet')}

{selCount ? ( ) : null}
{sets.map((set, i) => (
))}
) } export const SetCard = ({ set, requiredMeasies = [], href = false, onClick = false, useA = false, }) => { // Hooks const { t } = useTranslation(['sets']) const [hasMeasies] = hasRequiredMeasurements(requiredMeasies, set.measies, true) const wrapperProps = { className: 'bg-base-300 w-full mb-2 mx-auto flex flex-col items-start text-center justify-center rounded shadow py-4', style: { backgroundImage: `url(${cloudflareImageUrl({ type: 'w1000', id: set.img })})`, backgroundSize: 'cover', backgroundRepeat: 'no-repeat', backgroundPosition: '50%', }, } if (set.img === 'default-avatar') wrapperProps.style.backgroundPosition = 'bottom right' const inner = hasMeasies ? null : (
{t('setLacksMeasiesForDesign')}
) // Is it a button with an onClick handler? if (onClick) return ( ) // Returns a link to an internal page if (href && !useA) return ( {inner} ) // Returns a link to an external page if (href && useA) return ( {inner} ) // Returns a div return
{inner}
} export const MsetButton = (props) => export const MsetLink = (props) => export const MsetA = (props) => export const UserSetPicker = ({ design, t, href, clickHandler, size = 'lg' }) => { // Hooks const backend = useBackend() const { control } = useAccount() // State const [sets, setSets] = useState({}) // Effects useEffect(() => { const getSets = async () => { const result = await backend.getSets() if (result.success) { const all = {} for (const set of result.data.sets) all[set.id] = set setSets(all) } } getSets() }, [backend]) let hasSets = false const okSets = [] const lackingSets = [] if (Object.keys(sets).length > 0) { hasSets = true for (const setId in sets) { const [hasMeasies] = hasRequiredMeasurements( designMeasurements[design], sets[setId].measies, true ) if (hasMeasies) okSets.push(sets[setId]) else lackingSets.push(sets[setId]) } } if (!hasSets) return (
{t('account:noOwnSets')}

{t('account:pleaseMtm')}

{t('account:noOwnSetsMsg')}

{t('account:newSet')}

) return ( <> {okSets.length > 0 && (
{okSets.map((set) => ( ))}
)} {lackingSets.length > 0 && (
{t('account:someSetsLacking')}
{lackingSets.map((set) => ( ))}
)} ) } export const CuratedSetPicker = ({ design, language, href, clickHandler, size }) => { // Hooks const backend = useBackend() const { t, i18n } = useTranslation('sets') const { control } = useAccount() // State const [curatedSets, setCuratedSets] = useState([]) const [filter, setFilter] = useState([]) const [tags, setTags] = useState([]) // Effects useEffect(() => { const getCuratedSets = async () => { const result = await backend.getCuratedSets() if (result.success) { const all = [] const allTags = new Set() for (const set of result.data.curatedSets) { all.push(set) for (const tag of set[`tags${capitalize(language)}`]) allTags.add(tag) } setCuratedSets(all) setTags([...allTags]) } } getCuratedSets() }, [backend, language]) const addFilter = (tag) => { const newFilter = [...filter, tag] setFilter(newFilter) } const removeFilter = (tag) => { const newFilter = filter.filter((t) => t !== tag) setFilter(newFilter) } const applyFilter = () => { const newList = new Set() for (const set of curatedSets) { const setTags = [] for (const lang of siteConfig.languages) { const key = `tags${capitalize(lang)}` if (set[key]) setTags.push(...set[key]) } let match = 0 for (const tag of filter) { if (setTags.includes(tag)) match++ } if (match === filter.length) newList.add(set) } return [...newList] } const list = applyFilter() // Need to sort designs by their translated title const translated = {} for (const d of list) translated[t(`${d}.t`)] = d return ( <>

{t('account:curatedSets')}

{tags.map((tag) => ( addFilter(tag)} tag={tag} key={tag}> {tag} ))}
{list.length} / {curatedSets.length}
{filter.map((tag) => ( removeFilter(tag)} color="success" hoverColor="error" key={tag}> {tag} ))}
{orderBy(list, ['name'], ['asc']).map((set) => ( ))}
) } export const BookmarkedSetPicker = () => export const SetPicker = ({ design, href = false, clickHandler = false, size = 'lg' }) => { const { t, i18n } = useTranslation('sets') const { language } = i18n const pickerProps = { design, t, language, href, clickHandler, size } return ( <> ) }