// 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'
// 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 { BackToAccountButton } from './shared.mjs'
import { AnchorLink, PageLink, Link } from 'shared/components/link.mjs'
import {
OkIcon,
NoIcon,
TrashIcon,
EditIcon,
UploadIcon,
ResetIcon,
MeasieIcon,
CalendarIcon,
PlusIcon,
} 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 { shortDate, cloudflareImageUrl, formatMm } from 'shared/utils.mjs'
import { isDegreeMeasurement } from 'config/measurements.mjs'
import { TextOnBg } from 'shared/components/text-on-bg.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']
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'}
/>
{t('newSet')}
)
}
export const MeasieVal = ({ val, m, imperial }) =>
isDegreeMeasurement(m) ? {val}° : {formatMm(val, imperial)}
export const MsetBanner = ({ set, control, onClick = false, href = false }) => {
const { t, i18n } = useTranslation(ns)
const info = []
if (control > 1)
info.push([
,
{shortDate(i18n.language, set.createdAt, false)} ,
])
info.push([
,
{(set.measies ? Object.keys(set.measies).length : 0) + ' ' + t('measies')} ,
])
if (control > 2)
info.push([
set.public ? (
) : (
),
{t(set.public ? 'publicSet' : 'privateSet')} ,
])
const inner = (
<>
{set.name}
{info.map((item) => (
{item[0]}
{item[1]}
))}
>
)
const props = {
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') props.style.backgroundPosition = 'bottom right'
return onClick ? (
{inner}
) : (
{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 = (
setModal(
)
}
/>
{account.control > 3 && mset.public ? (
) : (
)}
{!publicOnly && (
<>
{edit ? (
setEdit(false)}
className="btn btn-primary btn-outline flex flex-row items-center gap-4"
>
{t('cancel')}
{t('saveThing', { thing: t('account:set') })}
) : (
setEdit(true)} className="btn btn-primary">
{t('editThing', { thing: t('account:set') })}
)}
>
)}
)
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}
{t('saveThing', { thing: t('account:set') })}
)
}
// 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 ? (
{selCount} {t('sets')}
) : null}
)
}