|
| 1 | +import { useTranslation } from "next-i18next"; |
| 2 | + |
| 3 | +import Container from "components/services/widget/container"; |
| 4 | +import Block from "components/services/widget/block"; |
| 5 | +import useWidgetAPI from "utils/proxy/use-widget-api"; |
| 6 | + |
| 7 | +export default function Component({ service }) { |
| 8 | + const { t } = useTranslation(); |
| 9 | + const { widget } = service; |
| 10 | + |
| 11 | + // eslint-disable-next-line prefer-const |
| 12 | + let { data: spoolData, error: spoolError } = useWidgetAPI(widget, "spools"); |
| 13 | + |
| 14 | + if (spoolError) { |
| 15 | + return <Container service={service} error={spoolError} />; |
| 16 | + } |
| 17 | + |
| 18 | + if (!spoolData) { |
| 19 | + const nBlocksGuess = widget.spoolIds?.length ?? 4; |
| 20 | + return ( |
| 21 | + <Container service={service}> |
| 22 | + {[...Array(nBlocksGuess)].map((_, i) => ( |
| 23 | + // eslint-disable-next-line react/no-array-index-key |
| 24 | + <Block key={i} label="spoolman.loading" /> |
| 25 | + ))} |
| 26 | + </Container> |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + if (spoolData.error || spoolData.message) { |
| 31 | + return <Container service={service} error={spoolData?.error ?? spoolData} />; |
| 32 | + } |
| 33 | + |
| 34 | + if (spoolData.length === 0) { |
| 35 | + return ( |
| 36 | + <Container service={service}> |
| 37 | + <Block label="spoolman.noSpools" /> |
| 38 | + </Container> |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + if (widget.spoolIds?.length) { |
| 43 | + spoolData = spoolData.filter((spool) => widget.spoolIds.includes(spool.id)); |
| 44 | + } |
| 45 | + |
| 46 | + if (spoolData.length > 4) { |
| 47 | + spoolData = spoolData.slice(0, 4); |
| 48 | + } |
| 49 | + |
| 50 | + return ( |
| 51 | + <Container service={service}> |
| 52 | + {spoolData.map((spool) => ( |
| 53 | + <Block |
| 54 | + key={spool.id} |
| 55 | + label={spool.filament.name} |
| 56 | + value={t("common.percent", { |
| 57 | + value: (spool.remaining_weight / spool.initial_weight) * 100, |
| 58 | + })} |
| 59 | + /> |
| 60 | + ))} |
| 61 | + </Container> |
| 62 | + ); |
| 63 | +} |
0 commit comments