ItemLayout.tsx 17.2 KB
Newer Older
Stefan Probst's avatar
Stefan Probst committed
1
2
3
import { Menu } from '@headlessui/react'
import cx from 'clsx'
import dynamic from 'next/dynamic'
Stefan Probst's avatar
Stefan Probst committed
4
import Link from 'next/link'
Stefan Probst's avatar
Stefan Probst committed
5
import type { PropsWithChildren } from 'react'
Stefan Probst's avatar
Stefan Probst committed
6
7
import { Fragment, useMemo, useState } from 'react'

Stefan Probst's avatar
Stefan Probst committed
8
9
import { useGetItemCategories } from '@/api/sshoc'
import type {
Stefan Probst's avatar
Stefan Probst committed
10
  Item as GenericItem,
Stefan Probst's avatar
Stefan Probst committed
11
12
13
  ItemCategory as ItemCategoryWithStep,
  ItemSearchQuery,
} from '@/api/sshoc/types'
Stefan Probst's avatar
Stefan Probst committed
14
import ProtectedView from '@/modules/auth/ProtectedView'
Stefan Probst's avatar
Stefan Probst committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import RelatedItems from '@/modules/item/RelatedItems'
import GridLayout from '@/modules/layout/GridLayout'
import HStack from '@/modules/layout/HStack'
import VStack from '@/modules/layout/VStack'
import Metadata from '@/modules/metadata/Metadata'
import { Anchor } from '@/modules/ui/Anchor'
import Breadcrumbs from '@/modules/ui/Breadcrumbs'
import Header from '@/modules/ui/Header'
import { ItemCategoryIcon } from '@/modules/ui/ItemCategoryIcon'
import Triangle from '@/modules/ui/Triangle'
import { SectionTitle } from '@/modules/ui/typography/SectionTitle'
import { SubSectionTitle } from '@/modules/ui/typography/SubSectionTitle'
import { Title } from '@/modules/ui/typography/Title'
import styles from '@/screens/item/ItemLayout.module.css'
import { formatDate } from '@/utils/formatDate'
import { getSingularItemCategoryLabel } from '@/utils/getSingularItemCategoryLabel'
import type { RequiredFields } from '@/utils/ts/object'
import { Svg as UrlIcon } from '@@/assets/icons/url.svg'

/** lazy load markdown processor */
const Markdown = dynamic(() => import('@/modules/markdown/Markdown'))

type ItemCategory = Exclude<ItemCategoryWithStep, 'step'>
type ItemProperties = Exclude<Item['properties'], undefined>
type ItemProperty = ItemProperties[number]
40
type ItemContributors = Exclude<Item['contributors'], undefined>
Stefan Probst's avatar
Stefan Probst committed
41
type RelatedItems = Exclude<Item['relatedItems'], undefined>
42
type Item = GenericItem & { dateCreated?: string; dateLastUpdated?: string }
Stefan Probst's avatar
Stefan Probst committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

/**
 * Shared item details screen.
 */
export default function ItemLayout({
  item: _item,
  children,
}: PropsWithChildren<{
  item: Item
}>): JSX.Element {
  const { data: itemCategories = {} } = useGetItemCategories()
  /** we can assume these fields to be present */
  const item = _item as RequiredFields<
    typeof _item,
    'id' | 'label' | 'category' | 'accessibleAt'
  >
  const query: ItemSearchQuery = {
    categories: [item.category],
    order: ['label'],
  }

Stefan Probst's avatar
Stefan Probst committed
64
  const relatedItems = item.relatedItems as RelatedItems
65

Stefan Probst's avatar
Stefan Probst committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  return (
    <Fragment>
      <Metadata
        title={item.label}
        description={item.description}
        openGraph={{ title: item.label, description: item.description }}
      />
      <GridLayout>
        <Header image={'/assets/images/browse-item/clouds@2x.png'}>
          <Breadcrumbs
            links={[
              { pathname: '/', label: 'Home' },
              {
                pathname: '/search',
                query,
                label: itemCategories[item.category],
              },
              {
84
                pathname: `/${item.category}/${item.persistentId}`,
Stefan Probst's avatar
Stefan Probst committed
85
86
87
88
89
90
                label: item.label,
              },
            ]}
          />
        </Header>
        <VStack className={cx('space-y-12 px-6 py-6', styles.mainColumn)}>
Stefan Probst's avatar
Stefan Probst committed
91
92
93
94
95
96
97
98
99
          <HStack className="items-start justify-between space-x-4">
            <div className="flex items-center justify-between space-x-4">
              <ItemThumbnail
                category={item.category as ItemCategory}
                properties={item.properties as ItemProperties}
              />
              <Title>{item.label}</Title>
            </div>
            <ProtectedView>
100
              <div className="flex flex-col space-y-2 xl:flex-row xl:space-y-0 xl:space-x-4">
101
102
103
104
105
106
107
108
109
110
111
                {item.status === 'approved' ? (
                  <Link
                    href={{
                      pathname: `/${item.category}/${item.persistentId}/edit`,
                    }}
                  >
                    <a className="w-32 px-6 py-3 text-lg text-center text-white transition rounded lg:text-xl lg:w-48 lg:px-10 lg:py-4 bg-primary-750 hover:bg-secondary-600">
                      Edit
                    </a>
                  </Link>
                ) : null}
112
113
114
115
116
117
118
119
120
121
                <Link
                  href={{
                    pathname: `/${item.category}/${item.persistentId}/history`,
                  }}
                >
                  <a className="w-32 px-6 py-3 text-lg text-center text-white transition rounded lg:text-xl lg:w-48 lg:px-10 lg:py-4 bg-primary-750 hover:bg-secondary-600">
                    History
                  </a>
                </Link>
              </div>
Stefan Probst's avatar
Stefan Probst committed
122
            </ProtectedView>
Stefan Probst's avatar
Stefan Probst committed
123
124
125
126
127
128
129
130
          </HStack>
          <ItemDescription description={item.description} />
        </VStack>
        <div className={cx(styles.mainColumn, 'px-6 py-6')}>
          <ItemMedia properties={item.properties as ItemProperties} />
        </div>
        {children}
        <div className={cx(styles.mainColumn, 'px-6 py-6')}>
131
          <RelatedItems items={relatedItems} />
Stefan Probst's avatar
Stefan Probst committed
132
133
134
135
136
137
138
139
140
        </div>
        <SideColumn>
          <VStack className="px-6 pt-6 pb-12 space-y-16">
            <AccessibleAtLinks
              accessibleAt={item.accessibleAt}
              category={item.category as ItemCategory}
            />
            <ItemPropertiesList
              properties={item.properties as ItemProperties}
141
              contributors={item.contributors as ItemContributors}
142
143
              licenses={item.licenses}
              source={item.source}
Stefan Probst's avatar
Stefan Probst committed
144
              sourceItemId={item.sourceItemId}
145
146
              dateCreated={item.dateCreated}
              dateLastUpdated={item.dateLastUpdated}
Stefan Probst's avatar
Stefan Probst committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
            />
          </VStack>
        </SideColumn>
      </GridLayout>
    </Fragment>
  )
}

function SideColumn({ children }: PropsWithChildren<unknown>) {
  return <section className={styles.sideColumn}>{children}</section>
}

/**
 * Thumbail or category icon
 */
function ItemThumbnail({
  category,
  properties,
}: {
  category: ItemCategory
  properties: ItemProperties
}) {
  if (properties === undefined) return null
  const thumbnail = properties.find(
    (property) => property.type?.code === 'thumbnail',
  )
  if (thumbnail !== undefined) {
    return (
Stefan Probst's avatar
Stefan Probst committed
175
      <img src={thumbnail.value} alt="" className="object-contain w-24 h-24" />
Stefan Probst's avatar
Stefan Probst committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    )
  }
  return (
    <ItemCategoryIcon
      category={category}
      width="6em"
      className="flex-shrink-0"
    />
  )
}

/**
 * Description
 */
function ItemDescription({
  description,
}: {
  description: Item['description']
}) {
  if (description === undefined) return null
  return (
    <div className="leading-8">
      <Markdown text={description} />
    </div>
  )
}

/**
 * Upstream link(s) to item.
 */
function AccessibleAtLinks({
  accessibleAt,
  category,
}: {
  accessibleAt: Array<string>
  category: ItemCategory
}) {
  if (accessibleAt === undefined || accessibleAt.length === 0) return null
  /** we only get plural labels from the backend in GET items-categories */
  const label = getSingularItemCategoryLabel(category)
  const buttonClassNames =
    'w-full text-xl rounded py-4 px-4 bg-primary-800 text-white hover:bg-primary-700 transition-colors duration-150 inline-flex items-center'

  /** when more than one upstream link is provided render a menu button */
  if (accessibleAt.length > 1) {
    return (
      <Menu>
        {({ open }) => (
          <div className="relative inline-block w-full">
            <Menu.Button
              className={cx(buttonClassNames, 'inline-flex justify-between')}
            >
              <span className="px-4">Go to {label}</span>
              <span className="pl-3 pr-1 border-l border-primary-500">
                <Triangle />
              </span>
            </Menu.Button>
            <Menu.Items className="absolute z-10 w-full mt-1 overflow-hidden bg-white border rounded shadow-md">
              {accessibleAt.map((href) => (
                <Menu.Item key={href} as={Fragment}>
                  <a
                    href={href}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="block px-8 py-6 truncate transition-colors duration-150 text-primary-500 hover:bg-gray-50"
                  >
                    {href}
                  </a>
                </Menu.Item>
              ))}
            </Menu.Items>
          </div>
        )}
      </Menu>
    )
  }

  return (
    <a
      className={buttonClassNames}
      href={accessibleAt[0]}
      rel="noopener noreferrer"
      target="_blank"
    >
      <span className="inline-flex items-start justify-center w-full px-4 space-x-2">
        <span>Go to {label}</span> <UrlIcon width="0.75em" className="pt-1" />
      </span>
    </a>
  )
}

/**
 * Item media.
 */
function ItemMedia({ properties }: { properties: ItemProperties }) {
  const [index, setIndex] = useState(0)

Stefan Probst's avatar
Stefan Probst committed
273
  const media = properties.filter((property) => property.type?.code === 'media')
Stefan Probst's avatar
Stefan Probst committed
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293

  if (media === undefined || media.length === 0) return null

  const current = media[index]

  return (
    <section>
      <SectionTitle className="sr-only">Media</SectionTitle>
      <div className="relative w-full h-64 border border-b-0 border-gray-200">
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <img
            src={current.value}
            alt=""
            loading="lazy"
            className="object-contain w-full h-full"
          />
        </div>
      </div>
      <div className="flex justify-center border border-gray-200">
        <button
294
          aria-label="Previous image"
Stefan Probst's avatar
Stefan Probst committed
295
296
297
298
299
300
301
302
303
304
305
          className={cx(
            'inline-flex items-center justify-center px-6',
            media.length === 1
              ? 'text-gray-500 pointer-events-none'
              : 'text-primary-800',
          )}
          disabled={media.length === 1}
          onClick={() => {
            setIndex((index) => (index > 0 ? index - 1 : media.length - 1))
          }}
        >
306
307
308
309
310
311
          <svg
            aria-hidden
            viewBox="0 0 7.599 14.043"
            fill={'currentColor'}
            height="0.8em"
          >
Stefan Probst's avatar
Stefan Probst committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
            <g transform="translate(7.599) rotate(90)">
              <path
                className="a"
                d="M14.043,0H0L6.931,7.6Z"
                transform="translate(0 0)"
              />
            </g>
          </svg>
        </button>
        <ul className="flex justify-center flex-1 px-6 space-x-1 border-l border-r border-gray-200">
          {media.map((m) => (
            <li key={m.id}>
              <img src={m.value} alt="" className="h-24 py-2" />
            </li>
          ))}
        </ul>
        <button
329
          aria-label="Next image"
Stefan Probst's avatar
Stefan Probst committed
330
331
332
333
334
335
336
337
338
339
340
          className={cx(
            'inline-flex items-center justify-center px-6',
            media.length === 1
              ? 'text-gray-500 pointer-events-none'
              : 'text-primary-800',
          )}
          disabled={media.length === 1}
          onClick={() => {
            setIndex((index) => (index >= media.length - 1 ? 0 : index + 1))
          }}
        >
341
342
343
344
345
346
          <svg
            aria-hidden
            viewBox="0 0 7.599 14.043"
            fill={'currentColor'}
            height="0.8em"
          >
Stefan Probst's avatar
Stefan Probst committed
347
348
349
350
351
352
353
354
355
356
            <g transform="translate(0 14.043) rotate(-90)">
              <path d="M14.043,0H0L6.931,7.6Z" transform="translate(0 0)" />
            </g>
          </svg>
        </button>
      </div>
    </section>
  )
}

357
358
359
/** thumbnail and media are already shown, no need to list them in the metadata panel */
const HIDDEN_PROPERTIES = ['thumbnail', 'media']

Stefan Probst's avatar
Stefan Probst committed
360
361
362
/**
 * Properties.
 */
363
364
365
function ItemPropertiesList({
  properties,
  contributors,
366
367
  licenses,
  source,
Stefan Probst's avatar
Stefan Probst committed
368
  sourceItemId,
369
370
  dateCreated,
  dateLastUpdated,
371
372
373
}: {
  properties: ItemProperties
  contributors: ItemContributors
374
375
  licenses?: Item['licenses']
  source?: Item['source']
Stefan Probst's avatar
Stefan Probst committed
376
  sourceItemId?: Item['sourceItemId']
377
378
  dateCreated?: string
  dateLastUpdated?: string
379
}) {
Stefan Probst's avatar
Stefan Probst committed
380
  const groupedProperties = useMemo(() => {
381
    if (properties === undefined || properties.length === 0) return {}
Stefan Probst's avatar
Stefan Probst committed
382
383
384

    const grouped: Record<string, Array<ItemProperty>> = {}
    properties.forEach((property) => {
385
386
      if (HIDDEN_PROPERTIES.includes(property.type?.code as string)) return

Stefan Probst's avatar
Stefan Probst committed
387
388
389
390
391
392
393
394
395
396
397
      const label = property.type?.label as string
      if (!Array.isArray(grouped[label])) {
        grouped[label] = []
      }
      grouped[label].push(property)
    })
    return grouped
  }, [properties])

  const sortedLabels = Object.keys(groupedProperties).sort()

398
399
400
401
402
403
404
405
406
407
408
  if (
    sortedLabels.length === 0 &&
    (contributors == null || contributors.length === 0) &&
    dateCreated == null &&
    dateLastUpdated == null &&
    (licenses == null || licenses.length === 0) &&
    source == null
  ) {
    return null
  }

Stefan Probst's avatar
Stefan Probst committed
409
410
411
412
  return (
    <VStack className="space-y-4">
      <SubSectionTitle as="h2">Details</SubSectionTitle>
      <VStack as="dl" className="space-y-2 text-sm leading-7">
413
        {/* contributors are a top-level field, not a property */}
414
        {contributors != null && contributors.length > 0 ? (
415
416
417
418
419
420
421
422
423
424
425
          <div>
            <dt className="inline mr-2 text-gray-500">Contributors:</dt>
            <dd className="inline">
              {contributors.map((contributor, index) => {
                if (contributor == null || contributor.actor == null)
                  return null
                return (
                  <Fragment
                    key={`${contributor.actor.id}${contributor.role?.code}`}
                  >
                    {index !== 0 ? <span>, </span> : null}
Stefan Probst's avatar
Stefan Probst committed
426
                    {contributor.actor.website != null ? (
427
428
429
430
431
432
433
434
435
436
437
438
                      <a href={contributor.actor.website}>
                        {contributor.actor.name}
                      </a>
                    ) : (
                      contributor.actor.name
                    )}
                  </Fragment>
                )
              })}
            </dd>
          </div>
        ) : null}
439

440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
        {/* dateCreated and dateLastUpdated are top-level fields, not properties */}
        {dateCreated != null ? (
          <div>
            <dt className="inline mr-2 text-gray-500">Created:</dt>
            <dd className="inline">
              <time dateTime={dateCreated}>{formatDate(dateCreated)}</time>
            </dd>
          </div>
        ) : null}
        {dateLastUpdated != null ? (
          <div>
            <dt className="inline mr-2 text-gray-500">Last updated:</dt>
            <dd className="inline">
              <time dateTime={dateLastUpdated}>
                {formatDate(dateLastUpdated)}
              </time>
            </dd>
          </div>
        ) : null}

460
        {/* properties */}
Stefan Probst's avatar
Stefan Probst committed
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
        {sortedLabels.map((label) => {
          const properties = groupedProperties[label]
          return (
            <div key={label}>
              <dt className="inline mr-2 text-gray-500">{label}:</dt>
              <dd className="inline">
                {properties.map((property, index) => {
                  return (
                    <Fragment key={property.id}>
                      {index !== 0 ? <span>, </span> : null}
                      <ItemPropertyValue property={property} />
                    </Fragment>
                  )
                })}
              </dd>
            </div>
          )
        })}
479
480

        {/* licenses are a top-level field, not a property */}
481
        {licenses != null && licenses.length > 0 ? (
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
          <div>
            <dt className="inline mr-2 text-gray-500">Licenses:</dt>
            <dd className="inline">
              {licenses.map((license, index) => {
                return (
                  <Fragment key={license.code}>
                    {index !== 0 ? <span>, </span> : null}
                    {license.accessibleAt != null ? (
                      <a href={license.accessibleAt}>{license.label}</a>
                    ) : (
                      license.label
                    )}
                  </Fragment>
                )
              })}
            </dd>
          </div>
        ) : null}
Stefan Probst's avatar
Stefan Probst committed
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522

        {/* source is a top-level field, not a property */}
        {source != null ? (
          <div>
            <dt className="inline mr-2 text-gray-500">Source:</dt>
            <dd className="inline">
              <Fragment key={source.id}>
                {source.urlTemplate != null && sourceItemId != null ? (
                  <a
                    href={source.urlTemplate.replace(
                      '{source-item-id}',
                      sourceItemId,
                    )}
                  >
                    {source.label}
                  </a>
                ) : (
                  source.label
                )}
              </Fragment>
            </dd>
          </div>
        ) : null}
Stefan Probst's avatar
Stefan Probst committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
      </VStack>
    </VStack>
  )
}

function ItemPropertyValue({ property }: { property: ItemProperty }) {
  switch (property.type?.type) {
    case 'concept':
      return <a href={property.concept?.uri}>{property.concept?.label}</a>
    case 'string':
      return <span>{property.value}</span>
    case 'url':
      return <Anchor href={property.value}>{property.value}</Anchor>
    case 'int':
    case 'float':
      return <span>{property.value}</span>
    case 'date':
      return property.value === undefined ? null : (
        <time dateTime={property.value}>{formatDate(property.value)}</time>
      )
    default:
      return null
  }
}