// Dependencies
import { measurements, isDegreeMeasurement, control as controlConfig } from '@freesewing/config'
import {
cloudflareImageUrl,
capitalize,
formatMm,
horFlexClasses,
linkClasses,
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 } from '@freesewing/react/components/Link'
import {
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 { ToggleInput } from '@freesewing/react/components/Input'
import { DisplayRow } from './shared.mjs'
import Markdown from 'react-markdown'
import { ModalWrapper } from '@freesewing/react/components/Modal'
//import { measurements as designMeasurements } from 'shared/prebuild/data/design-measurements.mjs'
//import { freeSewingConfig as conf, controlLevels } from 'shared/config/freesewing.config.mjs'
//import { isDegreeMeasurement } from 'config/measurements.mjs'
//import {
// shortDate,
// cloudflareImageUrl,
// formatMm,
// hasRequiredMeasurements,
// capitalize,
// horFlexClasses,
//} from 'shared/utils.mjs'
//// Hooks
//import { useState, useEffect, useContext } from 'react'
//import { useTranslation } from 'next-i18next'
//import { useAccount } from 'shared/hooks/use-account.mjs'
//import { useBackend } from 'shared/hooks/use-backend.mjs'
//import { useRouter } from 'next/router'
//// Context
//import { LoadingStatusContext } from 'shared/context/loading-status-context.mjs'
//import { ModalContext } from 'shared/context/modal-context.mjs'
//// Components
//import { Popout } from 'shared/components/popout/index.mjs'
//import { BackToAccountButton } from './shared.mjs'
//import { AnchorLink, PageLink, Link } from 'shared/components/link.mjs'
//import { Json } from 'shared/components/json.mjs'
//import { Yaml } from 'shared/components/yaml.mjs'
//import { ModalWrapper } from 'shared/components/wrappers/modal.mjs'
//import { Mdx } from 'shared/components/mdx/dynamic.mjs'
//import Timeago from 'react-timeago'
//import {
// StringInput,
// ToggleInput,
// PassiveImageInput,
// ListInput,
// MarkdownInput,
// MeasieInput,
// DesignDropdown,
// ns as inputNs,
//} from 'shared/components/inputs.mjs'
//import { BookmarkButton } from 'shared/components/bookmarks.mjs'
//import { DynamicMdx } from 'shared/components/mdx/dynamic.mjs'
/*
* 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 = () => {
if (!filter) return measurements.map((m) => `measurements:${m}` + `|${m}`).sort()
else return designMeasurements[filter].map((m) => `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, '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.data.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 === 200 && body.result === 'success') {
setMset(body.data.set)
setEdit(false)
setLoadingStatus([true, 'Nailed it', true, true])
} else setLoadingStatus([true, 'We failed to create this measurements set', true, false])
}
const heading = (
<>
{account.control > 2 && mset.public && mset.userId !== account.id ? (
) : (
)}
{account.control > 3 && mset.userId === account.id ? (
setModal(
)
}
>
JSON
setModal(
)
}
>
YAML
) : (
)}
{account.id && account.control > 2 && mset.public && mset.userId !== account.id ? (
{t('account:importSet')}
) : null}
{account.control > 2 ? (
) : null}
setModal(
)
}
className={`daisy-btn daisy-btn-secondary btn-outline ${horFlexClasses}`}
>
Show Image
{!publicOnly && (
<>
{account.control > 2 ? (
{
setSuggest(!suggest)
setEdit(false)
}}
className={`daisy-btn ${
suggest ? 'daisy-btn-neutral' : 'daisy-btn-primary'
} daisy-btn-outline ${horFlexClasses}`}
>
{suggest ? : }
{suggest ? 'Cancel' : 'Suggest for curation'}
) : null}
{edit ? (
<>
{
setEdit(false)
setSuggest(false)
}}
className={`daisy-btn daisy-btn-neutral daisy-btn-outline ${horFlexClasses}`}
>
Cancel
Save measurements set
>
) : (
{
setEdit(true)
setSuggest(false)
}}
className={`daisy-btn daisy-btn-primary ${horFlexClasses}`}
>
Edit measurements set
)}
>
)}
{account.control > 2 && mset.userId === account.id ? (
Clone measurements set
) : 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 ? (
) : (
)}
Make {mset.public ? 'Private' : '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}
{['measies', 'data'].map((s) => (
{s}
))}
Name
{account.control >= conf.account.sets.img ? (
Image
) : null}
{['public', 'units', 'notes'].map((id) =>
account.control >= conf.account.sets[id] ? (
{id}
) : null
)}
{t('measies')}
Clear filter}
/>
{filterMeasurements().map((mplus) => {
const [translated, m] = mplus.split('|')
return (
)
})}
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 ? (
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 >= conf.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}
/>
{t('unitsMustSave')}
>
) : null}
{/* notes: Control level determines whether or not to show this */}
{account.control >= conf.account.sets.notes ? (
) : null}
Save Measurements Set
)
}
/**
* 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}°
) : (
)
/*
export const NewSet = () => {
// Hooks
const { setLoadingStatus } = useContext(LoadingStatusContext)
const backend = useBackend()
const { t } = useTranslation(ns)
const router = useRouter()
const { account } = useAccount()
// 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, 'processingUpdate'])
const result = await backend.createSet({ name, imperial })
if (result.success) {
setLoadingStatus([true, t('nailedIt'), true, true])
router.push(`/account/set?id=${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'}
/>
{t('newSet')}
)
}
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 (
{inner}
)
// 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) => (
))}
)}
>
)
}
const SuggestCset = ({ mset, backend, setLoadingStatus, t }) => {
// State
const [height, setHeight] = useState('')
const [img, setImg] = useState('')
const [name, setName] = useState('')
const [notes, setNotes] = useState('')
const [submission, setSubmission] = useState(false)
// Method to submit the form
const suggestSet = async () => {
setLoadingStatus([true, 'status:contactingBackend'])
const result = await backend.suggestCset({ set: mset.id, height, img, name, notes })
if (result.success && result.data.submission) {
setSubmission(result.data.submission)
setLoadingStatus([true, 'status:nailedIt', true, true])
} else setLoadingStatus([true, 'backendError', 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 (
<>
{t('account:thankYouVeryMuch')}
{t('account:csetSuggestedMsg')}
{t('account:itIsAvailableAt')}:
>
)
}
return (
<>
{t('account:suggestCset')}
{missing.length > 0 ? : }
{t('account:measurements')}
{missing.length > 0 ? (
<>
{t('account:csetAllMeasies')}
{t('account:csetMissing')}:
{missing.map((m) => (
{t(`measurements:${m}`)}
))}
>
) : (
{t('account:allMeasiesAvailable')}
)}
{name.length > 1 ? : }
{t('account:name')}
{t('account:csetNameMsg')}
val.length > 1}
/>
{height.length > 1 ? : }
{t('measurements:height')}
{t('account:csetHeightMsg1')}
val.length > 1}
/>
{img.length > 0 ? : }
{t('account:img')}
{t('account:csetImgMsg')}:{' '}
{t('account:docs')}
val.length > 1}
/>
{t('account:notes')}
{t('account:csetNotesMsg')}
{t('account:mdSupport')}
true}
/>
1 && img.length > 0)}
onClick={suggestSet}
>
{t('account:suggestForCuration')}
>
)
}
*/