1
0
Fork 0
freesewing/sites/shared/components/account/sets.mjs

1024 lines
31 KiB
JavaScript
Raw Normal View History

2023-04-22 16:41:13 +02:00
// Dependencies
2023-08-24 18:39:12 +02:00
import { useState, useEffect, useContext } from 'react'
2023-04-22 16:41:13 +02:00
import { useTranslation } from 'next-i18next'
import { measurements } from 'config/measurements.mjs'
import { measurements as designMeasurements } from 'shared/prebuild/data/design-measurements.mjs'
2023-08-23 17:41:34 +02:00
import { freeSewingConfig as conf, controlLevels } from 'shared/config/freesewing.config.mjs'
import { siteConfig } from 'site/site.config.mjs'
import {
shortDate,
cloudflareImageUrl,
formatMm,
hasRequiredMeasurements,
capitalize,
scrollTo,
horFlexClasses,
} from 'shared/utils.mjs'
import orderBy from 'lodash.orderby'
2023-04-22 16:41:13 +02:00
// Hooks
import { useAccount } from 'shared/hooks/use-account.mjs'
import { useBackend } from 'shared/hooks/use-backend.mjs'
import { useRouter } from 'next/router'
2023-08-23 12:18:20 +02:00
import { useLoadingStatus } from 'shared/hooks/use-loading-status.mjs'
// Context
import { ModalContext } from 'shared/context/modal-context.mjs'
2023-04-22 16:41:13 +02:00
// Components
import { Popout } from 'shared/components/popout/index.mjs'
import { Tag } from 'shared/components/tag.mjs'
2023-08-24 18:39:12 +02:00
import { BackToAccountButton } from './shared.mjs'
import { AnchorLink, PageLink, Link, linkClasses } from 'shared/components/link.mjs'
import { V3Wip } from 'shared/components/v3-wip.mjs'
2023-04-23 18:00:52 +02:00
import {
OkIcon,
NoIcon,
TrashIcon,
EditIcon,
2023-08-23 12:18:20 +02:00
UploadIcon,
ResetIcon,
PlusIcon,
WarningIcon,
FilterIcon,
CameraIcon,
2023-04-23 18:00:52 +02:00
} from 'shared/components/icons.mjs'
2023-04-22 16:41:13 +02:00
import { ModalWrapper } from 'shared/components/wrappers/modal.mjs'
import Markdown from 'react-markdown'
2023-04-23 18:00:52 +02:00
import Timeago from 'react-timeago'
import { DisplayRow } from './shared.mjs'
2023-08-23 12:18:20 +02:00
import { isDegreeMeasurement } from 'config/measurements.mjs'
import { DynamicOrgDocs } from 'shared/components/dynamic-docs/org.mjs'
2023-04-22 16:41:13 +02:00
2023-08-23 12:18:20 +02:00
import {
StringInput,
PassiveImageInput,
ListInput,
MarkdownInput,
MeasieInput,
2023-08-23 17:41:34 +02:00
DesignDropdown,
ns as inputNs,
2023-08-23 12:18:20 +02:00
} from 'shared/components/inputs.mjs'
2023-04-30 20:31:28 +02:00
export const ns = [inputNs, 'account', 'patterns', 'status', 'measurements', 'sets']
2023-08-23 12:18:20 +02:00
export const NewSet = () => {
// Hooks
2023-08-23 12:18:20 +02:00
const { setLoadingStatus, LoadingStatus } = useLoadingStatus()
const backend = useBackend()
const { t } = useTranslation(ns)
2023-04-22 16:41:13 +02:00
const router = useRouter()
// State
2023-04-22 16:41:13 +02:00
const [name, setName] = useState('')
// Helper method to create a new set
2023-04-22 16:41:13 +02:00
const createSet = async () => {
2023-08-23 12:18:20 +02:00
setLoadingStatus([true, 'processingUpdate'])
const result = await backend.createSet({ name })
2023-04-22 16:41:13 +02:00
if (result.success) {
2023-08-23 12:18:20 +02:00
setLoadingStatus([true, t('nailedIt'), true, true])
router.push(`/account/sets/${result.data.set.id}`)
} else setLoadingStatus([true, 'backendError', true, false])
2023-04-22 16:41:13 +02:00
}
return (
2023-08-23 12:18:20 +02:00
<div className="max-w-xl">
2023-08-24 18:39:12 +02:00
<LoadingStatus />
<h5>{t('name')}</h5>
2023-04-22 16:41:13 +02:00
<p>{t('setNameDesc')}</p>
<input
2023-04-23 18:00:52 +02:00
autoFocus
2023-04-22 16:41:13 +02:00
value={name}
onChange={(evt) => setName(evt.target.value)}
className="input w-full input-bordered flex flex-row"
type="text"
placeholder={'Georg Cantor'}
/>
<div className="flex flex-row gap-2 items-center w-full mt-8 mb-2">
2023-04-22 16:41:13 +02:00
<button
className="btn btn-primary grow capitalize"
disabled={name.length < 1}
onClick={createSet}
>
{t('newSet')}
</button>
</div>
</div>
)
}
2023-08-23 12:18:20 +02:00
export const MeasieVal = ({ val, m, imperial }) =>
isDegreeMeasurement(m) ? <span>{val}°</span> : <span>{formatMm(val, imperial)}</span>
2023-04-23 18:00:52 +02:00
export const MsetCard = ({
set,
onClick = false,
href = false,
useA = false,
design = false,
language = false,
}) => {
2023-08-27 17:01:58 +02:00
const { t } = useTranslation(ns)
const wrapperProps = {
className:
'bg-base-300 aspect-square max-h-96 max-w-96 mb-2 mx-auto flex flex-col items-start text-center justify-between rounded-none md:rounded shadow',
style: {
backgroundImage: `url(${cloudflareImageUrl({ type: 'w1000', id: set.img })})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: '50%',
},
}
if (!set.img || set.img === 'default-avatar')
wrapperProps.style.backgroundPosition = 'bottom right'
let note = <span></span>
if (design) {
2023-08-27 17:01:58 +02:00
const [hasMeasies] = hasRequiredMeasurements(designMeasurements[design], set.measies, true)
const noteClasses =
'bg-opacity-90 w-full text-center py-2 font-bold px-2 rounded rounded-b-none leading-4 text-sm'
note = hasMeasies ? (
<div className={`${noteClasses} bg-success text-success-content`}>
{t('setHasMeasiesForDesign', { design: t(`designs:${design}.t`) })}
</div>
) : (
<div className={`${noteClasses} bg-warning text-warning-content`}>
{t('setLacksMeasiesForDesign', { design: t(`designs:${design}.t`) })}
</div>
)
}
const inner = (
<>
{note}
<h5 className="bg-neutral text-neutral-content px-4 w-full bg-opacity-50 py-2 rounded rounded-t-none">
{language ? set[`name${capitalize(language)}`] : set.name}
</h5>
2023-08-23 17:41:34 +02:00
</>
)
// Is it a button with an onClick handler?
if (onClick)
return (
<button {...wrapperProps} onClick={() => onClick(set)}>
{inner}
</button>
)
// Returns a link to an internal page
if (href && !useA)
return (
<Link {...wrapperProps} href={href}>
{inner}
</Link>
)
// Returns a link to an external page
if (href && useA)
return (
<a {...wrapperProps} href={href}>
{inner}
</a>
)
// Returns a div
return <div {...wrapperProps}>{inner}</div>
2023-08-23 17:41:34 +02:00
}
2023-08-23 12:18:20 +02:00
export const Mset = ({ id, publicOnly = false }) => {
// Hooks
2023-08-23 17:41:34 +02:00
const { account, control } = useAccount()
2023-08-23 12:18:20 +02:00
const { setLoadingStatus, LoadingStatus } = useLoadingStatus()
const backend = useBackend()
2023-08-24 19:01:48 +02:00
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] = <DynamicOrgDocs language={i18n.language} path={`site/sets/${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] = <DynamicOrgDocs language={i18n.language} path={`measurements/${m}`} />
}
2023-04-23 18:00:52 +02:00
2023-08-23 12:18:20 +02:00
// 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])
}
2023-08-23 12:18:20 +02:00
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])
2023-04-23 18:00:52 +02:00
}
2023-08-23 12:18:20 +02:00
if (id) {
if (publicOnly) getPublicSet()
else getSet()
2023-04-23 18:00:52 +02:00
}
2023-08-23 12:18:20 +02:00
}, [id, publicOnly])
2023-04-23 18:00:52 +02:00
2023-08-23 12:18:20 +02:00
const filterMeasurements = () => {
if (!filter) return measurements.map((m) => t(`measurements:${m}`) + `|${m}`).sort()
else return designMeasurements[filter].map((m) => t(`measurements:${m}`) + `|${m}`).sort()
2023-04-23 18:00:52 +02:00
}
2023-08-23 12:18:20 +02:00
if (!id || !mset) return null
2023-04-23 18:00:52 +02:00
2023-08-23 12:18:20 +02:00
const updateMeasies = (m, val) => {
const newMeasies = { ...measies }
newMeasies[m] = val
setMeasies(newMeasies)
2023-04-23 18:00:52 +02:00
}
const save = async () => {
2023-08-23 12:18:20 +02:00
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]
2023-04-23 18:00:52 +02:00
}
2023-08-23 12:18:20 +02:00
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])
2023-04-23 18:00:52 +02:00
}
2023-08-23 12:18:20 +02:00
const heading = (
<>
2023-08-23 12:18:20 +02:00
<LoadingStatus />
<div className="flex flex-wrap md:flex-nowrap flex-row gap-2 w-full">
<div className="w-full md:w-96 shrink-0">
<MsetCard set={mset} control={control} />
</div>
<div className="flex flex-col justify-end gap-2 mb-2 grow">
{account.control > 3 && mset.public ? (
<div className="flex flex-row gap-2 items-center">
<a
className="badge badge-secondary font-bold badge-lg"
href={`${conf.backend}/sets/${mset.id}.json`}
2023-08-23 12:18:20 +02:00
>
JSON
</a>
<a
className="badge badge-success font-bold badge-lg"
href={`${conf.backend}/sets/${mset.id}.yaml`}
>
YAML
</a>
2023-08-23 12:18:20 +02:00
</div>
) : (
<span></span>
2023-08-23 12:18:20 +02:00
)}
<button
onClick={() =>
setModal(
<ModalWrapper flex="col" justify="top lg:justify-center" slideFrom="right">
<img src={cloudflareImageUrl({ type: 'public', id: mset.img })} />
</ModalWrapper>
)
}
className={`btn btn-secondary btn-outline ${horFlexClasses}`}
>
<CameraIcon />
{t('showImage')}
</button>
{!publicOnly && (
<>
{edit ? (
<>
<button
onClick={() => setEdit(false)}
className={`btn btn-neutral btn-outline ${horFlexClasses}`}
>
<ResetIcon />
{t('cancel')}
</button>
<button onClick={save} className={`btn btn-primary ${horFlexClasses}`}>
<UploadIcon />
{t('saveThing', { thing: t('account:set') })}
</button>
</>
) : (
<button
onClick={() => setEdit(true)}
className={`btn btn-primary ${horFlexClasses}`}
>
<EditIcon /> {t('editThing', { thing: t('account:set') })}
</button>
)}
</>
)}
</div>
</div>
<div className="flex flex-row flex-wrap gap-4 text-sm items-center justify-between mb-2"></div>
</>
2023-08-23 12:18:20 +02:00
)
2023-08-23 12:18:20 +02:00
if (!edit)
return (
<div className="max-w-2xl">
{heading}
{Object.keys(mset.measies).length > 0 && (
<>
<h2>{t('measies')}</h2>
{Object.entries(mset.measies).map(([m, val]) =>
val > 0 ? (
<DisplayRow title={<MeasieVal m={m} val={val} />} key={m}>
<span className="font-medium">{t(m)}</span>
</DisplayRow>
) : null
)}
2023-08-23 12:18:20 +02:00
</>
)}
2023-08-23 12:18:20 +02:00
<h2>{t('data')}</h2>
<DisplayRow title={t('name')}>{mset.name}</DisplayRow>
<DisplayRow title={t('units')}>
{mset.imperial ? t('imerialUnits') : t('metricUnits')}
</DisplayRow>
2023-08-23 17:41:34 +02:00
{control >= controlLevels.sets.notes && (
<DisplayRow title={t('notes')}>
2023-08-23 17:41:34 +02:00
<Markdown>{mset.notes}</Markdown>
</DisplayRow>
2023-08-23 12:18:20 +02:00
)}
2023-08-23 17:41:34 +02:00
{control >= controlLevels.sets.public && (
<>
<DisplayRow title={t('public')}>
2023-08-23 17:41:34 +02:00
{mset.public ? (
<OkIcon className="w-6 h-6 text-success" stroke={4} />
) : (
<NoIcon className="w-6 h-6 text-error" stroke={3} />
)}
</DisplayRow>
2023-08-23 17:41:34 +02:00
{mset.public && (
<DisplayRow title={t('permalink')}>
2023-08-23 17:41:34 +02:00
<PageLink href={`/sets/${mset.id}`} txt={`/sets/${mset.id}`} />
</DisplayRow>
2023-08-23 17:41:34 +02:00
)}
</>
)}
{control >= controlLevels.sets.createdAt && (
<DisplayRow title={t('created')}>
2023-08-23 17:41:34 +02:00
<Timeago date={mset.createdAt} />
<span className="px-2 opacity-50">|</span>
2023-08-24 19:01:48 +02:00
{shortDate(i18n.language, mset.createdAt, false)}
</DisplayRow>
2023-08-23 17:41:34 +02:00
)}
{control >= controlLevels.sets.createdAt && (
<DisplayRow title={t('updated')}>
2023-08-23 17:41:34 +02:00
<Timeago date={mset.updatedAt} />
<span className="px-2 opacity-50">|</span>
2023-08-24 19:01:48 +02:00
{shortDate(i18n.language, mset.createdAt, false)}
</DisplayRow>
2023-08-23 17:41:34 +02:00
)}
{control >= controlLevels.sets.id && <DisplayRow title={t('id')}>{mset.id}</DisplayRow>}
2023-08-23 12:18:20 +02:00
</div>
)
2023-08-23 12:18:20 +02:00
return (
<div className="max-w-2xl">
{heading}
<ul className="list list-disc list-inside ml-4">
{['measies', 'data'].map((s) => (
<li key={s}>
<AnchorLink id={s} txt={t(s)} />
</li>
))}
<ul className="list list-disc list-inside ml-4">
2023-08-23 17:41:34 +02:00
<li>
<AnchorLink id="name" txt={t('name')} />
</li>
{account.control >= conf.account.sets.img ? (
2023-08-23 12:18:20 +02:00
<li>
2023-08-23 17:41:34 +02:00
<AnchorLink id="image" txt={t('image')} />
2023-08-23 12:18:20 +02:00
</li>
2023-08-23 17:41:34 +02:00
) : null}
{['public', 'units', 'notes'].map((id) =>
account.control >= conf.account.sets[id] ? (
2023-08-24 18:39:12 +02:00
<li key={id}>
2023-08-23 17:41:34 +02:00
<AnchorLink id="units" txt={t(id)} />
</li>
) : null
)}
2023-08-23 12:18:20 +02:00
</ul>
</ul>
<h2 id="measies">{t('measies')}</h2>
2023-08-23 17:41:34 +02:00
<div className="bg-secondary px-4 pt-1 pb-4 rounded-lg shadow bg-opacity-10">
<DesignDropdown
update={setFilter}
label={t('filterByDesign')}
current={filter}
firstOption={<option value="">{t('noFilter')}</option>}
docs={
<div className="max-w-prose">
<h2>
{t('measies')}: {t('filterByDesign')}
</h2>
<p>
If you have a specific design in mind, you can <b>filter by design</b> to only list
those measurements that are required for this design.
</p>
</div>
}
2023-08-23 17:41:34 +02:00
/>
2023-04-23 18:00:52 +02:00
</div>
2023-08-23 12:18:20 +02:00
{filterMeasurements().map((mplus) => {
const [translated, m] = mplus.split('|')
return (
<MeasieInput
2023-08-26 09:27:27 +02:00
id={`measie-${m}`}
2023-08-23 12:18:20 +02:00
key={m}
m={m}
docs={measieDocs[m]}
imperial={mset.imperial}
label={translated}
current={mset.measies[m]}
original={mset.measies[m]}
update={updateMeasies}
/>
)
})}
2023-04-23 18:00:52 +02:00
2023-08-23 12:18:20 +02:00
<h2 id="data">{t('data')}</h2>
2023-08-23 12:18:20 +02:00
{/* Name is always shown */}
<span id="name"></span>
<StringInput
2023-08-26 09:27:27 +02:00
id="set-name"
2023-08-23 12:18:20 +02:00
label={t('name')}
update={setName}
current={name}
original={mset.name}
docs={docs.name}
placeholder="Georg Cantor"
valid={(val) => val && val.length > 0}
/>
2023-04-22 16:41:13 +02:00
2023-08-23 12:18:20 +02:00
{/* img: Control level determines whether or not to show this */}
<span id="image"></span>
{account.control >= conf.account.sets.img ? (
<PassiveImageInput
2023-08-26 09:27:27 +02:00
id="set-img"
2023-08-23 12:18:20 +02:00
label={t('image')}
update={setImage}
current={image}
docs={docs.image}
valid={(val) => val.length > 0}
/>
) : null}
2023-04-22 16:41:13 +02:00
2023-08-23 12:18:20 +02:00
{/* public: Control level determines whether or not to show this */}
<span id="public"></span>
{account.control >= conf.account.sets.public ? (
<ListInput
2023-08-26 09:27:27 +02:00
id="set-public"
2023-08-23 12:18:20 +02:00
label={t('public')}
update={setIsPublic}
docs={docs.public}
list={[
{
val: true,
label: (
<div className="flex flex-row items-center flex-wrap justify-between w-full">
<span>{t('publicSet')}</span>
<OkIcon
className="w-8 h-8 text-success bg-base-100 rounded-full p-1"
stroke={4}
/>
</div>
),
desc: t('publicSetDesc'),
},
{
val: false,
label: (
<div className="flex flex-row items-center flex-wrap justify-between w-full">
<span>{t('privateSet')}</span>
<NoIcon className="w-8 h-8 text-error bg-base-100 rounded-full p-1" stroke={3} />
</div>
),
desc: t('privateSetDesc'),
},
]}
current={isPublic}
/>
) : null}
{/* units: Control level determines whether or not to show this */}
<span id="units"></span>
{account.control >= conf.account.sets.units ? (
<ListInput
2023-08-26 09:27:27 +02:00
id="set-units"
2023-08-23 12:18:20 +02:00
label={t('units')}
docs={docs.units}
update={setImperial}
list={[
{
val: false,
label: (
<div className="flex flex-row items-center flex-wrap justify-between w-full">
<span>{t('metricUnits')}</span>
<span className="text-inherit text-2xl pr-2">cm</span>
</div>
),
desc: t('metricUnitsd'),
},
{
val: true,
label: (
<div className="flex flex-row items-center flex-wrap justify-between w-full">
<span>{t('imperialUnits')}</span>
<span className="text-inherit text-4xl pr-2"></span>
</div>
),
desc: t('imperialUnitsd'),
},
]}
current={imperial}
/>
) : null}
{/* notes: Control level determines whether or not to show this */}
<span id="notes"></span>
{account.control >= conf.account.sets.notes ? (
<MarkdownInput
2023-08-26 09:27:27 +02:00
id="set-notes"
2023-08-23 12:18:20 +02:00
label={t('notes')}
update={setNotes}
docs={docs.notes}
current={notes}
placeholder={t('mdSupport')}
/>
) : null}
<button
onClick={save}
className="btn btn-primary btn-lg flex flex-row items-center gap-4 mx-auto mt-8"
>
<UploadIcon />
{t('saveThing', { thing: t('account:set') })}
</button>
</div>
2023-04-22 16:41:13 +02:00
)
}
// Component for the account/sets page
2023-08-25 10:44:05 +02:00
export const Sets = () => {
// Hooks
2023-08-23 17:41:34 +02:00
const { control } = useAccount()
2023-08-20 18:48:40 +02:00
const backend = useBackend()
2023-08-24 19:01:48 +02:00
const { t } = useTranslation(ns)
2023-08-23 12:18:20 +02:00
const { setLoadingStatus, LoadingStatus, LoadingProgress } = useLoadingStatus()
2023-04-22 16:41:13 +02:00
// State
2023-04-22 16:41:13 +02:00
const [sets, setSets] = useState([])
2023-08-23 12:18:20 +02:00
const [selected, setSelected] = useState({})
const [refresh, setRefresh] = useState(0)
2023-04-22 16:41:13 +02:00
// Effects
2023-04-22 16:41:13 +02:00
useEffect(() => {
const getSets = async () => {
const result = await backend.getSets()
if (result.success) setSets(result.data.sets)
}
getSets()
2023-08-23 12:18:20 +02:00
}, [refresh])
// Helper var to see how many are selected
const selCount = Object.keys(selected).length
2023-04-22 16:41:13 +02:00
2023-08-23 12:18:20 +02:00
// 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)
2023-08-25 10:44:05 +02:00
setLoadingStatus([
true,
<LoadingProgress val={i} max={selCount} msg={t('removingSets')} key="linter" />,
])
2023-08-23 12:18:20 +02:00
}
setSelected({})
setRefresh(refresh + 1)
setLoadingStatus([true, 'nailedIt', true, true])
}
2023-04-22 16:41:13 +02:00
return (
<div className="max-w-7xl xl:pl-4">
2023-08-23 12:18:20 +02:00
<LoadingStatus />
2023-08-23 17:41:34 +02:00
<p className="text-center md:text-right">
<Link
className="btn btn-primary capitalize w-full md:w-auto"
bottom
primary
href="/new/set"
>
<PlusIcon />
2023-08-23 12:18:20 +02:00
{t('newSet')}
</Link>
</p>
<div className="flex flex-row gap-2 border-b-2 mb-4 pb-4 mt-8 h-14 items-center">
<input
type="checkbox"
className="checkbox checkbox-secondary"
onClick={toggleSelectAll}
checked={sets.length === selCount}
/>
{selCount ? (
<button className="btn btn-error" onClick={removeSelectedSets}>
<TrashIcon /> {selCount} {t('sets')}
</button>
) : null}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-2">
{sets.map((set, i) => (
<div
key={i}
className={`flex flex-row items-start gap-1 border-2
${
selected[set.id] ? 'border-solid border-secondary' : 'border-dotted border-base-300'
} rounded-lg p-2`}
>
<label className="w-8 h-full shrink-0">
2023-08-23 12:18:20 +02:00
<input
type="checkbox"
checked={selected[set.id] ? true : false}
2023-08-23 12:18:20 +02:00
className="checkbox checkbox-secondary"
onClick={() => toggleSelect(set.id)}
2023-08-23 12:18:20 +02:00
/>
</label>
<div className="w-full">
<MsetCard control={control} href={`/account/sets/${set.id}`} set={set} />
</div>
</div>
))}
</div>
2023-05-26 10:41:36 +02:00
<BackToAccountButton />
2023-04-22 16:41:13 +02:00
</div>
)
}
export const SetCard = ({
set,
requiredMeasies = [],
href = false,
onClick = false,
useA = false,
}) => {
// Hooks
const { t } = useTranslation(['sets'])
2023-08-27 17:01:58 +02:00
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 : (
<div className="flex flex-row gap-2 items-center">
<WarningIcon className="w-6 h-6 shrink-0 text-error" />
2023-08-27 17:01:58 +02:00
<span>{t('setLacksMeasiesForDesign')}</span>
</div>
)
// Is it a button with an onClick handler?
if (onClick)
return (
<button {...wrapperProps} onClick={onClick}>
{inner}
</button>
)
// Returns a link to an internal page
if (href && !useA)
return (
<Link {...wrapperProps} href={href}>
{inner}
</Link>
)
// Returns a link to an external page
if (href && useA)
return (
<a {...wrapperProps} href={href}>
{inner}
</a>
)
// Returns a div
return <div {...wrapperProps}>{inner}</div>
}
export const MsetButton = (props) => <MsetCard {...props} href={false} />
export const MsetLink = (props) => <MsetCard {...props} onClick={false} useA={false} />
export const MsetA = (props) => <MsetCard {...props} onClick={false} useA={true} />
export const UserSetPicker = ({ design, t, href, clickHandler }) => {
// 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) {
2023-08-27 17:01:58 +02:00
const [hasMeasies] = hasRequiredMeasurements(
designMeasurements[design],
sets[setId].measies,
true
)
if (hasMeasies) okSets.push(sets[setId])
else lackingSets.push(sets[setId])
}
}
if (!hasSets)
return (
<div className="w-full max-w-3xl mx-auto">
<Popout tip>
<h5>{t('account:noOwnSets')}</h5>
<p className="text-lg">{t('account:pleaseMtm')}</p>
<p className="text-lg">{t('account:noOwnSetsMsg')}</p>
<p className="text-center md:text-right">
<Link
className="btn btn-primary capitalize w-full md:w-auto"
bottom
primary
href="/new/set"
>
<PlusIcon />
{t('account:newSet')}
</Link>
</p>
</Popout>
</div>
)
return (
<>
<ul className="list list-inside list-disc ml-4">
<li>
<button className={linkClasses} onClick={() => scrollTo('ownsets')}>
{t('account:ownSets')}
</button>
</li>
<li>
<button className={linkClasses} onClick={() => scrollTo('bookmarkedsets')}>
{t('account:bookmarkedSets')}
</button>
</li>
<li>
<button className={linkClasses} onClick={() => scrollTo('curatedsets')}>
{t('account:curatedSets')}
</button>
</li>
</ul>
<h3 id="ownsets">{t('yourSets')}</h3>
{okSets.length > 0 && (
<>
<h4>{t('account:theseSetsReady')}</h4>
<div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-2">
2023-08-27 17:01:58 +02:00
{okSets.map((set) => (
<MsetButton
{...{ set, control, design }}
onClick={clickHandler}
2023-08-27 17:06:01 +02:00
href={href}
requiredMeasies={measurements[design]}
key={set.id}
/>
))}
</div>
</>
)}
{lackingSets.length > 0 && (
<div className="my-4">
<h4>{t('account:someSetsLacking')}</h4>
<div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-2">
2023-08-27 17:01:58 +02:00
{lackingSets.map((set) => (
<MsetLink
{...{ set, control, design }}
onClick={clickHandler}
requiredMeasies={measurements[design]}
key={set.id}
/>
))}
</div>
</div>
)}
</>
)
}
export const CuratedSetPicker = ({ design, language, href, clickHandler }) => {
// 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 (
<>
<h3 id="curatedsets">{t('account:curatedSets')}</h3>
<V3Wip />
{tags.map((tag) => (
<Tag onClick={() => addFilter(tag)} tag={tag} key={tag}>
{tag}
</Tag>
))}
<div className="my-2 p-2 px-4 border rounded-lg bg-secondary bg-opacity-10 max-w-xl">
<div className="flex flex-row items-center justify-between gap-2">
<FilterIcon className="w-6 h-6 text-secondary" />
<span>
{list.length} / {curatedSets.length}
</span>
<button onClick={() => setFilter([])} className="btn btn-secondary btn-sm">
clear
</button>
</div>
{filter.map((tag) => (
<Tag onClick={() => removeFilter(tag)} color="success" hoverColor="error" key={tag}>
{tag}
</Tag>
))}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-2">
{orderBy(list, ['name'], ['asc']).map((set) => (
<MsetButton
key={set.id}
{...{ set, control, design }}
2023-08-27 17:01:58 +02:00
href={href}
onClick={clickHandler}
requiredMeasies={measurements[design]}
language={i18n.language}
/>
))}
</div>
</>
)
}
2023-08-27 17:01:58 +02:00
export const BookmarkedSetPicker = () => <V3Wip />
export const SetPicker = ({ design, href = false, clickHandler = false }) => {
const { t, i18n } = useTranslation('sets')
const { language } = i18n
const pickerProps = { design, t, language, href, clickHandler }
return (
<>
<h2>{t('chooseSet')}</h2>
<UserSetPicker {...pickerProps} />
<BookmarkedSetPicker {...pickerProps} />
<CuratedSetPicker {...pickerProps} />
</>
)
}