// __SDEFILE__ - This file is a dependency for the stand-alone environment
// Dependencies
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 { 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 {
OkIcon,
NoIcon,
TrashIcon,
EditIcon,
UploadIcon,
ResetIcon,
PlusIcon,
WarningIcon,
CameraIcon,
CsetIcon,
BoolYesIcon,
BoolNoIcon,
CloneIcon,
} from 'shared/components/icons.mjs'
import { ModalWrapper } from 'shared/components/wrappers/modal.mjs'
import { Mdx } from 'shared/components/mdx/dynamic.mjs'
import Timeago from 'react-timeago'
import { DisplayRow } from './shared.mjs'
import {
StringInput,
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'
export const ns = [inputNs, 'account', 'patterns', 'status', 'measurements', 'sets']
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 MeasieVal = ({ val, m, imperial }) =>
isDegreeMeasurement(m) ? (
{val}°
) : (
)
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 { t } = useTranslation(ns)
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 =
let missingMeasies = ''
let linebreak = ''
const maxLength = 75
if (design) {
const [hasMeasies, missing] = hasRequiredMeasurements(
designMeasurements[design],
set.measies,
true
)
const iconClasses = 'w-8 h-8 p-1 rounded-full -mt-2 -ml-2 shadow'
icon = hasMeasies ? (
) : (
)
if (missing.length > 0) {
const translated = missing.map((m) => {
return t(m)
})
let missingString = t('missing') + ': ' + translated.join(', ')
if (missingString.length > maxLength) {
const lastSpace = missingString.lastIndexOf(', ', maxLength)
missingString = missingString.substring(0, lastSpace) + ', ' + t('andMore') + '...'
}
const measieClasses = 'font-normal text-xs'
missingMeasies = {missingString}
linebreak =
}
}
const inner = (
<>
{icon}
{language ? set[`name${capitalize(language)}`] : set.name}
{linebreak}
{missingMeasies}
>
)
// Is it a button with an onClick handler?
if (onClick)
return (
onClick(set)}>
{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 Mset = ({ id, publicOnly = false }) => {
// Hooks
const { account, control } = useAccount()
const { setLoadingStatus } = useContext(LoadingStatusContext)
const backend = useBackend()
const { t, i18n } = useTranslation(ns)
// 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({})
// 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 importSet = async () => {
setLoadingStatus([true, t('account.importing')])
// Compile data
const data = {
...mset,
userId: account.id,
measies: { ...mset.measies },
}
delete data.img
const result = await backend.createSet(data)
if (result.success) {
setMset(result.data.set)
setEdit(false)
setLoadingStatus([true, 'nailedIt', true, true])
} else setLoadingStatus([true, 'backendError', true, false])
}
const docs = {}
for (const option of ['name', 'units', 'public', 'notes', 'image']) {
docs[option] =
}
const heading = (
<>
{account.control > 3 && mset.public && mset.userId !== account.id ? (
) : (
)}
{account.control > 3 && mset.userId === account.id ? (
setModal(
)
}
>
JSON
setModal(
)
}
>
YAML
) : (
)}
{account.control > 2 && mset.public && mset.userId !== account.id ? (
{t('account:importSet')}
) : null}
{account.control > 2 ? (
) : null}
setModal(
)
}
className={`btn btn-secondary btn-outline ${horFlexClasses}`}
>
{t('showImage')}
{!publicOnly && (
<>
{account.control > 2 ? (
{
setSuggest(!suggest)
setEdit(false)
}}
className={`btn ${
suggest ? 'btn-neutral' : 'btn-primary'
} btn-outline ${horFlexClasses}`}
>
{suggest ? : }
{t(suggest ? 'account:cancel' : 'account:suggestForCuration')}
) : null}
{edit ? (
<>
{
setEdit(false)
setSuggest(false)
}}
className={`btn btn-neutral btn-outline ${horFlexClasses}`}
>
{t('cancel')}
{t('saveThing', { thing: t('account:set') })}
>
) : (
{
setEdit(true)
setSuggest(false)
}}
className={`btn btn-primary ${horFlexClasses}`}
>
{t('editThing', { thing: t('account:set') })}
)}
>
)}
{account.control > 2 && mset.userId === account.id ? (
{t('account:cloneSet')}
) : null}
>
)
if (suggest)
return (
{heading}
)
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('imperialUnits') : t('metricUnits')}
{control >= controlLevels.sets.notes && (
)}
{control >= controlLevels.sets.public && (
<>
{mset.public ? (
) : (
)}
{mset.public && (
)}
>
)}
{control >= controlLevels.sets.createdAt && (
|
{shortDate(i18n.language, mset.createdAt, false)}
)}
{control >= controlLevels.sets.updatedAt && (
|
{shortDate(i18n.language, mset.updatedAt, 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')}}
/>
{filterMeasurements().map((mplus) => {
const [translated, m] = mplus.split('|')
return (
}
/>
)
})}
{t('data')}
{/* Name is always shown */}
val && val.length > 0}
docs={docs.name}
/>
{/* img: Control level determines whether or not to show this */}
{account.control >= conf.account.sets.img ? (
val.length > 0}
docs={docs.image}
/>
) : 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}
docs={docs.public}
/>
) : 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}
docs={docs.units}
/>
{t('unitsMustSave')}
>
) : 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, LoadingProgress } = useContext(LoadingStatusContext)
// 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 (
{sets.length > 0 ? (
<>
{t('account:importSets')}
{t('newSet')}
{selCount} {t('sets')}
>
) : (
{t('newSet')}
)}
{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 (
{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')}
>
)
}