<script>
import Icon from '@iconify/svelte'
import orcidSvg from './assets/orcid.svg'
import rorSvg from './assets/ror.svg'
import { _ } from '@sveltia/i18n'
import { Button } from '$lib/components/ui/button/index.js'
import { renderContent, formatDate, typeLabel, languageLabel, subjectLabel, getCCIcons, formatCount, decodeEntities, countLabel, preferredPdf, RELATION_TYPE_ORDER, entityPath } from '$lib/bib-utils.js'
import { SEARCH_ALL, searchHrefFor } from '$lib/search-url.js'
let {
entry,
meta,
index,
bibLocale,
copiedCiteId,
addedId,
isSaved = false,
savedFull = false,
hideVersionLink = false,
largeTitle = false,
dragId,
dropPosition,
ondragstart,
ondragover,
ondragleave,
ondrop,
ondragend,
oncopy,
ondelete,
onadd,
dragHandleActive = $bindable(false),
} = $props()
// Every internal link goes through entityPath so it opens the entity page
// rather than resolving to the publisher.
const rorPath = entityPath
const orcidPath = entityPath
/// Every work narrowed to one facet value: what this card's own year,
/// language, type or subject reads as in the search.
const workSearchHref = filters =>
searchHrefFor({ q: SEARCH_ALL, kind: 'works', filters })
</script>
<li
draggable={dragHandleActive}
onpointerdown={() => { dragHandleActive = false }}
ondragstart={e => { if (!dragHandleActive) { e.preventDefault(); return } ondragstart?.(e) }}
ondragover={ondragover}
ondragleave={ondragleave}
ondrop={ondrop}
ondragend={() => { dragHandleActive = false; ondragend?.() }}
class="flex items-start gap-3 px-5 py-4 bg-background transition-opacity
{dragId === entry.id ? 'opacity-30' : ''}
{dropPosition?.id === entry.id && dropPosition.before ? 'border-t-2 border-primary' : ''}
{dropPosition?.id === entry.id && !dropPosition.before ? 'border-b-2 border-primary' : ''}"
>
{#if index !== undefined && index !== null}
<!-- The list runs over the whole of a large entity's works, so an ordinal
reaches into the thousands: the column grows past its minimum rather
than clipping, and reads in the page's locale like every other count. -->
<span class="text-xs text-muted-foreground min-w-5 shrink-0 pt-0.5 text-right tabular-nums">{formatCount(index + 1, bibLocale)}.</span>
{/if}
<!-- Structured metadata -->
<div class="flex-1 min-w-0 space-y-0.5">
{#if meta}
{@const doiPath = meta.id?.startsWith('https://doi.org/') ? entityPath(meta.id) : null}
{#if meta.title}
<!-- A work taken back or doubted is marked where the title is, and
named in words: a reader who takes only the title away from the
card has to take that with it. The whole line carries the colour,
so it is visible at a glance down a list of twenty.
Red for a retraction or a withdrawal, amber for an expression of
concern — and red wins where a work carries both, since the
louder notice is the one that has to be read first.
The colour is the band and the badge, with no rule down the left
edge: the badge already starts the line, and a second, darker
mark beside it only crowded it. -->
{@const marks = meta.marks ?? []}
{@const tone = marks.some(m => m.tone === 'alarm') ? 'alarm' : marks.length > 0 ? 'caution' : ''}
{@const band = tone === 'alarm'
? ' rounded bg-destructive/15 px-2 py-1'
: tone === 'caution'
? ' rounded bg-caution/20 px-2 py-1'
: ''}
<p class="{largeTitle ? 'text-lg' : 'text-base'} font-semibold leading-snug{band}">
{#each marks as mark}<span
class="mr-1.5 inline-flex items-center rounded px-1.5 py-0.5 align-middle text-xs font-bold uppercase tracking-wide {mark.tone === 'alarm' ? 'bg-destructive text-destructive-foreground' : 'bg-caution text-caution-foreground'}"
>{_(mark.label)}</span>{/each}{#if meta.id}<a href={doiPath ?? meta.id} {...(doiPath ? {} : { target: '_blank', rel: 'noreferrer' })} class="hover:underline">{@html renderContent(meta.title)}</a>{:else}{@html renderContent(meta.title)}{/if}
</p>
{/if}
{@const formattedDate = formatDate(meta.datePublished, bibLocale)}
{@const typeLbl = typeLabel(meta.type, bibLocale)}
{@const langLbl = languageLabel(meta.language, bibLocale)}
<!-- What the facets are keyed on, which is not what the card shows: the
index keeps the four-digit year of a full date, and a language's
primary subtag — `en`, not `en-US`. -->
{@const facetYear = /^\d{4}$/.test((meta.datePublished ?? '').trim().slice(0, 4)) ? (meta.datePublished ?? '').trim().slice(0, 4) : ''}
{@const facetLang = (meta.language ?? '').trim().split('-')[0].toLowerCase()}
{@const line2start = typeLbl}
{@const line2date = formattedDate ? `${_('bibliography.published')} ${formattedDate}` : ''}
{@const ivDoi = meta.isVersionOf?.startsWith('https://doi.org/') ? meta.isVersionOf.replace('https://doi.org/', '') : null}
{@const ivHref = ivDoi ? entityPath(ivDoi) : (meta.isVersionOf || null)}
{#if line2start || meta.version || line2date || meta.containerTitle || langLbl}
<p class="text-sm text-muted-foreground">{#if line2start}{#if meta.type}<a href={workSearchHref({ type: [meta.type] })} class="hover:underline">{line2start}</a>{:else}{line2start}{/if}{/if}{line2start && (meta.version || line2date || meta.containerTitle || langLbl) ? ' ' : ''}{#if meta.version}{_('bibliography.version')} {#if ivHref && !hideVersionLink}<a href={ivHref} class="hover:underline">{meta.version}</a>{:else}{meta.version}{/if}{/if}{(line2start || meta.version) && line2date ? ' ' : ''}{#if line2date}{_('bibliography.published')} {#if facetYear}<a href={workSearchHref({ year: [facetYear] })} class="hover:underline">{formattedDate}</a>{:else}{formattedDate}{/if}{/if}{(line2start || meta.version || line2date) && meta.containerTitle ? ' ' : ''}{#if meta.containerTitle}{_('bibliography.in')} {#if meta.containerPagePath}<a href={meta.containerPagePath} class="hover:underline"><em>{meta.containerTitle}</em></a>{:else}<em>{meta.containerTitle}</em>{/if}{/if}{meta.containerTitle && langLbl ? ' ' : ''}{#if langLbl}({#if facetLang}<a href={workSearchHref({ lang: [facetLang] })} class="hover:underline">{langLbl}</a>{:else}{langLbl}{/if}){/if}</p>
{/if}
{#if meta.authorList.length > 0}
<p class="text-sm text-muted-foreground leading-relaxed">
{#each meta.authorList as author, ai}
{#if ai > 0}, {/if}{#if author.isEllipsis}<span class="select-none">…</span>{:else}<span class="inline-flex items-baseline gap-px">{#if author.orcid}<a href={orcidPath(author.orcid)} class="hover:underline">{author.name}</a>{:else}{author.name}{/if}{#if author.affIndices.length > 0}<sup class="text-[0.65em] leading-none ml-px">{author.affIndices.join(',')}</sup>{/if}{#if author.orcid}<img src={orcidSvg} width="14" height="14" alt="ORCID" class="ml-0.5 inline-block align-middle opacity-70 shrink-0" />{/if}</span>{/if}
{/each}
</p>
{#if meta.affiliations.length > 0}
<p class="text-sm text-muted-foreground/60">
{#each meta.affiliations as aff, i}
{#if i > 0} · {/if}<sup class="text-[0.65em] leading-none">{i + 1}</sup> {#if aff.ror}<a href={rorPath(aff.ror)} class="hover:underline">{aff.name}</a><img src={rorSvg} width="14" height="14" alt="ROR" class="ml-0.5 inline-block align-middle opacity-70 shrink-0" />{:else}{aff.name}{/if}
{/each}
</p>
{/if}
{/if}
{#if meta.funders.length > 0}
<p class="text-sm text-muted-foreground/60">
{_('bibliography.funded_by')}
{#each meta.funders as f, i}{#if i > 0}, {/if}{@const funderName = decodeEntities(f.funder_name || f.funder_id)}{#if f.funder_id?.startsWith('https://ror.org/')}<a href={rorPath(f.funder_id)} class="hover:underline inline-flex items-center gap-0.5">{funderName}<img src={rorSvg} width="14" height="14" alt="ROR" class="inline-block align-middle opacity-70 shrink-0" /></a>{:else if f.funder_id?.startsWith('http')}{funderName}{:else}{funderName}{/if}{#if f.award_title || f.award_number}{@const awardLabel = f.award_title ? (f.award_number ? `${decodeEntities(f.award_title)} (${f.award_number})` : decodeEntities(f.award_title)) : f.award_number}: {#if f.award_id?.startsWith('http')}<a href={f.award_id} target="_blank" rel="noreferrer" class="hover:underline">{awardLabel}</a>{:else}{awardLabel}{/if}{/if}{/each}
</p>
{/if}
{#if meta.description}
<p class="text-sm text-muted-foreground line-clamp-3 mt-3 mb-3">{@html renderContent(meta.description)}</p>
{/if}
{#if meta.referenceCount > 0 || Object.entries(meta.relationCounts ?? {}).some(([t, c]) => c > 0 && (t === 'IsReferencedBy' || !t.startsWith('Is')))}
{@const rc = meta.relationCounts ?? {}}
{@const otherOrdered = RELATION_TYPE_ORDER.filter(t => t !== 'IsReferencedBy' && t !== 'References' && !t.startsWith('Is') && rc[t] > 0)}
{@const otherExtra = Object.keys(rc).filter(t => rc[t] > 0 && t !== 'IsReferencedBy' && t !== 'References' && !t.startsWith('Is') && !RELATION_TYPE_ORDER.includes(t)).sort()}
{@const parts = [
...[...otherOrdered, ...otherExtra].map(t => `${formatCount(rc[t], bibLocale)} ${countLabel(t, rc[t])}`),
meta.referenceCount > 0 ? `${formatCount(meta.referenceCount, bibLocale)} ${meta.referenceCount === 1 ? _('bibliography.reference') : _('bibliography.references')}` : '',
rc['IsReferencedBy'] > 0 ? `${formatCount(rc['IsReferencedBy'], bibLocale)} ${rc['IsReferencedBy'] === 1 ? _('bibliography.citation') : _('bibliography.citations')}` : '',
].filter(Boolean)}
{@const joined = parts.length < 2 ? (parts[0] ?? '') : `${parts.slice(0, -1).join(', ')} ${_('bibliography.and')} ${parts[parts.length - 1]}`}
<p class="text-sm text-muted-foreground/60">{joined}</p>
{/if}
{#if meta.licenseTitle || meta.licenseId}
{@const ccIcons = getCCIcons(meta.licenseId)}
<!-- Text, not a row of boxes. As a flex container every piece of this
— the bracket, the identifier, the closing bracket, the full stop —
was an item of its own, so each could wrap to a line of its own and
each carried the gap: "International (" broke before the id and left
a space before the ")". The icons keep their own flex, which is all
that ever needed it. -->
<p class="text-sm text-muted-foreground/60">
<!-- The identifier leads to the other works under the same license,
since that is what the index counts them by; the icons lead out
to the license itself. Each goes where the thing under the
pointer stands for. -->
{_('bibliography.license')} {meta.licenseTitle}{#if meta.licenseId}{meta.licenseTitle ? ' ' : ''}<span class="whitespace-nowrap">(<a href={workSearchHref({ license: [meta.licenseId] })} class="hover:underline">{meta.licenseId}</a>)</span>{/if}.{#if ccIcons.length > 0} {#if meta.licenseUrl}<a href={meta.licenseUrl} target="_blank" rel="noreferrer" aria-label={meta.licenseTitle || meta.licenseId} class="inline-flex items-center gap-0.5 align-text-bottom hover:opacity-70 transition-opacity">{#each ccIcons as icon}<Icon {icon} width="16" height="16" />{/each}</a>{:else}{#each ccIcons as icon}<Icon {icon} width="16" height="16" />{/each}{/if}{/if}
</p>
{/if}
{#if meta.subjects.length > 0}
<div class="flex flex-wrap gap-1 my-1">
{#each meta.subjects.slice(0, 5) as subject}
{#if subject.code}
<!-- A classified subject is named as the facet it leads to names
it: the vocabulary's wording for the field or subfield, in
the page's language, not the record's — a record may word a
subfield's subject any way it likes, and in one language.
A topic is narrower than the value it leads to, so it keeps
its own words, as an unclassified subject does. -->
<a href={workSearchHref({ subject: [subject.code] })} class="inline-flex items-center rounded-full border border-border px-2.5 py-0.5 text-xs font-medium text-muted-foreground hover:underline">{subject.topic ? subject.label : subjectLabel(subject.code, bibLocale)}</a>
{:else}
<span class="inline-flex items-center rounded-full border border-border px-2.5 py-0.5 text-xs font-medium text-muted-foreground">{subject.label}</span>
{/if}
{/each}
</div>
{/if}
<!-- What the record points at: one PDF, the copy that opens. A record
lists several — the same URL once per content version, and a mining
endpoint beside the reader's copy — and `preferredPdf` holds the
choice and the reason for it.
One link, named for what it opens and with no heading over it: a
section called "Content" holding a single row said less than the row
does. Only the PDFs for now — the other media types a record carries,
xml, plain text, html, need a name a reader recognises before they
are worth a row of their own. -->
{@const pdf = preferredPdf(meta.files)}
{#if pdf}
<a href={pdf.url} rel="noreferrer"
class="text-sm text-primary hover:underline flex items-center gap-1.5 mt-3 mb-2 [&>svg]:shrink-0"
><Icon icon="catppuccin:pdf" width="16" height="16" />{_('bibliography.full_text_pdf')}</a>
{/if}
<!-- The other identifiers a work is known by, each linked where it is
described: an identical work's DOI to its page here, a PubMed or
PubMed Central id to NCBI, an OpenAlex work id to OpenAlex. -->
{@const alsoKnownAs = [
...(meta.identicalIds ?? []).map(id => {
const doiSuffix = id.startsWith('https://doi.org/') ? id.replace('https://doi.org/', '') : null
return { href: doiSuffix ? entityPath(doiSuffix) : id, label: doiSuffix ?? id, external: !doiSuffix }
}),
...(meta.pmid ? [{ href: `https://pubmed.ncbi.nlm.nih.gov/${meta.pmid}/`, label: `PMID ${meta.pmid}`, external: true }] : []),
...(meta.pmcid ? [{ href: `https://pmc.ncbi.nlm.nih.gov/articles/${meta.pmcid}/`, label: `PMCID ${meta.pmcid}`, external: true }] : []),
...(meta.openalex ? [{ href: `https://openalex.org/${meta.openalex}`, label: `OpenAlex ${meta.openalex}`, external: true }] : []),
]}
{#if alsoKnownAs.length > 0}
<div class="text-sm mt-3 mb-2">
<p class="font-semibold text-foreground">{_('bibliography.also_known_as')}</p>
<div class="text-muted-foreground space-y-0.5">
{#each alsoKnownAs as item}
<div class="leading-5"><a href={item.href} {...(item.external ? { target: '_blank', rel: 'noreferrer' } : {})} class="text-primary hover:underline">{item.label}</a></div>
{/each}
</div>
</div>
{/if}
{#if meta.id}
<a href={meta.id} target="_blank" rel="noreferrer"
class="text-sm text-primary hover:underline flex items-center gap-1.5 pt-0.5 wrap-anywhere max-w-full [&>svg]:shrink-0"
>{#if meta.id.startsWith('https://doi.org/')}<Icon icon="academicons:doi" width="16" height="16" color="#fab608" />{/if}{meta.id}</a>
{/if}
{/if}
</div>
<!-- Per-entry icon buttons -->
<div class="flex flex-col gap-0.5 shrink-0">
{#if onadd && (!isSaved || addedId === meta?.id)}
<Button type="button" variant="ghost" size="icon"
disabled={savedFull && !isSaved}
onclick={() => onadd(meta?.id ?? '', entry.data)}
aria-label="Add to saved"
class="h-7 w-7 text-muted-foreground hover:text-foreground"
>
{#if addedId === meta?.id}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
<path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
</svg>
{/if}
</Button>
{/if}
<Button type="button" variant="ghost" size="icon"
onclick={oncopy}
aria-label={_('bibliography.copy_citation')}
class="h-7 w-7 text-muted-foreground hover:text-foreground"
>
{#if copiedCiteId === entry.id}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
<path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184" />
</svg>
{/if}
</Button>
{#if ondelete}
<Button type="button" variant="ghost" size="icon"
onclick={ondelete}
aria-label={_('bibliography.delete_entry')}
class="h-7 w-7 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
<path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
</svg>
</Button>
{/if}
</div>
</li>