// Dependencies import { measurements, isDegreeMeasurement, control as controlConfig, urls, } from '@freesewing/config' import { measurements as measurementTranslations } from '@freesewing/i18n' import { measurements as designMeasurements } from '@freesewing/collection' import { cloudflareImageUrl, capitalize, formatMm, horFlexClasses, linkClasses, notEmpty, roundDistance, shortDate, timeAgo, } from '@freesewing/utils' // Context import { LoadingStatusContext } from '@freesewing/react/context/LoadingStatus' import { ModalContext } from '@freesewing/react/context/Modal' // Hooks import React, { useState, useEffect, Fragment, useContext } from 'react' import { useAccount } from '@freesewing/react/hooks/useAccount' import { useBackend } from '@freesewing/react/hooks/useBackend' // Components import { Link as WebLink, AnchorLink } from '@freesewing/react/components/Link' import { BoolNoIcon, BoolYesIcon, CloneIcon, CuratedMeasurementsSetIcon, EditIcon, ShowcaseIcon, NewMeasurementsSetIcon, NoIcon, OkIcon, PlusIcon, ResetIcon, TrashIcon, UploadIcon, // WarningIcon, // BoolYesIcon, // BoolNoIcon, } from '@freesewing/react/components/Icon' import { BookmarkButton, MsetCard } from '@freesewing/react/components/Account' import { DesignInput, MarkdownInput, ListInput, MeasieInput, PassiveImageInput, StringInput, ToggleInput, } from '@freesewing/react/components/Input' import { DisplayRow } from './shared.mjs' import Markdown from 'react-markdown' import { ModalWrapper } from '@freesewing/react/components/Modal' import { Json } from '@freesewing/react/components/Json' import { Yaml } from '@freesewing/react/components/Yaml' import { Popout } from '@freesewing/react/components/Popout' const t = (input) => { console.log('t called', input) return input } /* * Component to show an individual measurements set * * @param {object} props - All React props * @param {number} id - The ID of the measurements set to load * @param {bool} publicOnly - FIXME * @param {function} Link - An optional framework-specific Link component to use for client-side routing */ export const Set = ({ id, publicOnly = false, Link = false }) => { if (!Link) Link = WebLink // Hooks const { account, control } = useAccount() const { setLoadingStatus } = useContext(LoadingStatusContext) const backend = useBackend() // Context const { setModal } = useContext(ModalContext) const [filter, setFilter] = useState(false) const [edit, setEdit] = useState(false) const [suggest, setSuggest] = 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({}) const [displayAsMetric, setDisplayAsMetric] = useState(mset?.imperial ? false : true) // Effect useEffect(() => { const getSet = async () => { setLoadingStatus([true, 'Contacting the backend']) const [status, body] = await backend.getSet(id) if (status === 200 && body.result === 'success') { setMset(body.set) setName(body.set.name) setImage(body.set.image) setIsPublic(body.set.public ? true : false) setImperial(body.set.imperial ? true : false) setNotes(body.set.notes) setMeasies(body.set.measies) setLoadingStatus([true, 'Measurements set loaded', true, true]) } else setLoadingStatus([true, 'An error occured while contacting the backend', true, false]) } const getPublicSet = async () => { setLoadingStatus([true, 'Contacting the backend']) const [status, body] = await backend.getPublicSet(id) if (status === 200 && body.result === 'success') { setMset({ ...body.data, public: true, measies: body.data.measurements, }) setName(body.data.name) setImage(body.data.image) setIsPublic(body.data.public ? true : false) setImperial(body.data.imperial ? true : false) setNotes(body.data.notes) setMeasies(body.data.measurements) setLoadingStatus([true, 'Measurements set loaded', true, true]) } else setLoadingStatus([ true, 'An error occured while loading this measurements set', true, false, ]) } if (id) { if (publicOnly) getPublicSet() else getSet() } }, [id, publicOnly]) const filterMeasurements = () => filter ? designMeasurements[filter].sort() : measurements.sort() if (!id || !mset) return null const updateMeasies = (m, val) => { const newMeasies = { ...measies } newMeasies[m] = val setMeasies(newMeasies) } const save = async () => { setLoadingStatus([true, 'Gathering info']) // 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, 'Saving measurements set']) const [status, body] = await backend.updateSet(mset.id, data) if (status === 200 && body.result === 'success') { setMset(body.set) setEdit(false) setLoadingStatus([true, 'Nailed it', true, true]) } else setLoadingStatus([true, 'That did not go as planned. Saving the set failed.', true, false]) } const togglePublic = async () => { setLoadingStatus([true, 'Getting ready']) const [status, body] = await backend.updateSet(mset.id, { public: !mset.public }) if (status === 200 && body.result === 'success') { setMset(body.set) setLoadingStatus([true, 'Alright, done!', true, true]) } else setLoadingStatus([true, 'Backend says no :(', true, false]) } const importSet = async () => { setLoadingStatus([true, 'Importing data']) // Compile data const data = { ...mset, userId: account.id, measies: { ...mset.measies }, } delete data.img const [status, body] = await backend.createSet(data) if (status === 201 && body.result === 'created') { setLoadingStatus([true, 'Loading newly created set', true, true]) window.location = `/account/data/sets/set?id=${body.set.id}` } else setLoadingStatus([true, 'We failed to create this measurements set', true, false]) } const heading = ( <>
{account.control > 2 && mset.public && mset.userId !== account.id ? (
JSON YAML
) : ( )} {account.control > 3 && mset.userId === account.id ? (
) : ( )} {account.id && account.control > 2 && mset.public && mset.userId !== account.id ? ( ) : null} {account.control > 2 ? ( ) : null} {!publicOnly && ( <> {account.control > 2 ? ( ) : null} {edit ? ( <> ) : ( )} )} {account.control > 2 && mset.userId === account.id ? ( ) : null}
) if (suggest) return (
{heading}
) if (!edit) return (
{heading}

Data

{mset.name} {mset.imperial ? 'Imperial' : 'Metric'} {control >= controlConfig.account.sets.notes && ( {mset.notes} )} {control >= controlConfig.account.sets.public && ( <> {mset.userId === account.id && (
{mset.public ? ( ) : ( )}
)} {mset.public && ( {`/set?id=${mset.id}`} )} )} {control >= controlConfig.account.sets.createdAt && ( {timeAgo(mset.createdAt, false)} ({shortDate(mset.createdAt, false)}) )} {control >= controlConfig.account.sets.updatedAt && ( {timeAgo(mset.updatedAt, false)} ({shortDate(mset.updatedAt, false)}) )} {control >= controlConfig.account.sets.id && {mset.id}} {Object.keys(mset.measies).length > 0 && ( <>

Measurements

setDisplayAsMetric(!displayAsMetric)} current={displayAsMetric} /> {Object.entries(mset.measies).map(([m, val]) => val > 0 ? ( } key={m} > {m} ) : null )} )}
) return (
{heading}

Measurements

Clear filter} />
{filterMeasurements().map((m) => ( ))}

Data

{/* Name is always shown */} val && val.length > 0} /> {/* img: Control level determines whether or not to show this */} {account.control >= controlConfig.account.sets.img ? ( val.length > 0} /> ) : null} {/* public: Control level determines whether or not to show this */} {account.control >= controlConfig.account.sets.public ? ( Public measurements set
), desc: 'Others are allowed to use these measurements to generate or test patterns', }, { val: false, label: (
Private measurements set
), desc: 'These measurements cannot be used by other users or visitors', }, ]} current={isPublic} /> ) : null} {/* units: Control level determines whether or not to show this */} {account.control >= controlConfig.account.sets.units ? ( <> Metric units (cm) cm ), desc: 'Pick this if you prefer cm over inches', }, { val: true, label: (
Imperial units (inch)
), desc: 'Pick this if you prefer inches over cm', }, ]} current={imperial} /> Note: You must save after changing Units to have the change take effect on this page. ) : null} {/* notes: Control level determines whether or not to show this */} {account.control >= controlConfig.account.sets.notes ? ( ) : null} ) } /** * A (helper) component to display a measurements value * * @param {object} props - All React props * @param {string} val - The value * @param {string} m - The measurement name * @param {bool} imperial - True for imperial measurements, or metric by default */ export const MeasurementValue = ({ val, m, imperial = false }) => isDegreeMeasurement(m) ? ( {val}° ) : ( ) /** * React component to suggest a measurements set for curation * * @param {object} props - All React props * @param {string} mset - The measurements set */ export const SuggestCset = ({ mset, Link }) => { // State const [height, setHeight] = useState('') const [img, setImg] = useState('') const [name, setName] = useState('') const [notes, setNotes] = useState('') const [submission, setSubmission] = useState(false) console.log(mset) // Hooks const backend = useBackend() // Method to submit the form const suggestSet = async () => { setLoadingStatus([true, 'Contacting backend']) const result = await backend.suggestCset({ set: mset.id, height, img, name, notes }) if (result.success && result.data.submission) { setSubmission(result.data.submission) setLoadingStatus([true, 'Nailed it', true, true]) } else setLoadingStatus([true, 'An unexpected error occured. Please report this.', true, false]) } const missing = [] for (const m of measurements) { if (typeof mset.measies[m] === 'undefined') missing.push(m) } if (submission) { const url = `/curate/sets/suggested/${submission.id}` return ( <>

Thank you

Your submission has been registered and will be processed by one of our curators.

It is available at: {url}

) } return ( <>

Suggest a measurements set for curation

{missing.length > 0 ? : } Measurements

{missing.length > 0 ? ( <>

To ensure curated measurements sets work for all designs, you need to provide a full set of measurements.

Your measurements set is missing the following measurements:

) : (

All measurements are available.

)}

{name.length > 1 ? : } Name

Each curated set has a name. You can suggest your own name or a pseudonym.

val.length > 1} />

{height.length > 1 ? : } Height

To allow organizing and presenting our curated sets in a structured way, we organize them by height.

val.length > 1} />

{img.length > 0 ? : } Image

Finally, we need a picture. Please refer to the documentation to see what makes a good picture for a curated measurements set. Documentation

val.length > 1} />

Notes

If you would like to add any notes, you can do so here.

This field supports markdown true} /> ) } export const NewSet = () => { // Hooks const backend = useBackend() const { account } = useAccount() const { setLoadingStatus, LoadingProgress } = useContext(LoadingStatusContext) // State const [name, setName] = useState('') // Use account setting for imperial const imperial = account.imperial // Helper method to create a new set const createSet = async () => { setLoadingStatus([true, 'Storing new measurements set']) const [status, body] = await backend.createSet({ name, imperial }) if (status === 201 && body.result === 'created') { setLoadingStatus([true, 'Nailed it', true, true]) window.location = `/account/set?id=${body.set.id}` } else setLoadingStatus([ true, 'Failed to save the measurments set. Please report this.', true, false, ]) } return (
Name

Give this set of measurements a name. That will help tell them apart.

val && val.length > 0} placeholder={'Georg Cantor'} />
) } /* 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, missingClickHandler, 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 BookmarkedSetPicker = ({ design, clickHandler, t, size, href }) => { // Hooks const { control } = useAccount() const backend = useBackend() // State const [sets, setSets] = useState({}) // Effects useEffect(() => { const getBookmarks = async () => { const result = await backend.getBookmarks() const loadedSets = {} if (result.success) { for (const bookmark of result.data.bookmarks.filter( (bookmark) => bookmark.type === 'set' )) { let set try { set = await backend.getSet(bookmark.url.slice(6)) if (set.success) { const [hasMeasies] = hasRequiredMeasurements( designMeasurements[design], set.data.set.measies, true ) loadedSets[set.data.set.id] = { ...set.data.set, hasMeasies } } } catch (err) { console.log(err) } } } setSets(loadedSets) } getBookmarks() }, []) const okSets = Object.values(sets).filter((set) => set.hasMeasies) const lackingSets = Object.values(sets).filter((set) => !set.hasMeasies) return ( <> {okSets.length > 0 && (
{okSets.map((set) => ( ))}
)} {lackingSets.length > 0 && (
{t('account:someSetsLacking')}
{lackingSets.map((set) => ( ))}
)} ) } */