Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
More TS-ification and refactoring (#1210)
Dhruv Bhanushali55e53f3ce901
diff --git a/src/assets/licenses/cc-logo.svg b/src/assets/licenses/cc.svgsimilarity index 100%rename from src/assets/licenses/cc-logo.svgrename to src/assets/licenses/cc.svgdiff --git a/src/assets/licenses/pdm.svg b/src/assets/licenses/pd.svgsimilarity index 100%rename from src/assets/licenses/pdm.svgrename to src/assets/licenses/pd.svgdiff --git a/src/assets/licenses/sampling-plus.svg b/src/assets/licenses/sampling.plus.svgsimilarity index 100%rename from src/assets/licenses/sampling-plus.svgrename to src/assets/licenses/sampling.plus.svgdiff --git a/src/assets/licenses/cc0.svg b/src/assets/licenses/zero.svgsimilarity index 100%rename from src/assets/licenses/cc0.svgrename to src/assets/licenses/zero.svgdiff --git a/src/components/VErrorSection/VErrorImage.vue b/src/components/VErrorSection/VErrorImage.vueindex 64cfbee58..11ed84540 100644--- a/src/components/VErrorSection/VErrorImage.vue+++ b/src/components/VErrorSection/VErrorImage.vue@@ -11,7 +11,7 @@import { computed } from '@nuxtjs/composition-api'import { errorCodes } from '~/constants/errors'-import { getAttributionMarkup } from '~/utils/attribution-html'+import { getAttribution } from '~/utils/attribution-html'import imageInfo from '~/assets/error_images/image_info.json'@@ -35,7 +35,7 @@ export default {...image,src: require(`~/assets/error_images/${image.file}.jpg`),alt: `error-images.${image.id}`,- attribution: getAttributionMarkup(image),+ attribution: getAttribution(image),}return [errorItem.error, image]})diff --git a/src/components/VFilters/VLicenseExplanation.vue b/src/components/VFilters/VLicenseExplanation.vueindex 8f04d71ae..9ed48d9b0 100644--- a/src/components/VFilters/VLicenseExplanation.vue+++ b/src/components/VFilters/VLicenseExplanation.vue@@ -38,7 +38,7 @@<script>import { isLicense, isDeprecated } from '~/utils/license'-import VLicenseElements from '~/components/VLicenseElements.vue'+import VLicenseElements from '~/components/VLicense/VLicenseElements.vue'import VLink from '~/components/VLink.vue'/**diff --git a/src/components/VLicense/VLicense.vue b/src/components/VLicense/VLicense.vueindex 47c3b4b9e..eafefebef 100644--- a/src/components/VLicense/VLicense.vue+++ b/src/components/VLicense/VLicense.vue@@ -2,11 +2,11 @@<div class="license flex flex-row items-center gap-2"><div class="flex gap-1"><VIcon- v-for="(name, index) in icons"+ v-for="(name, index) in iconNames":key="index":class="['icon', bgFilled ? 'bg-filled text-black' : '']"view-box="0 0 30 30"- :icon-path="svgs[name]"+ :icon-path="icons[name]":size="4"/></div>@@ -24,14 +24,12 @@ import {useContext,} from '@nuxtjs/composition-api'-import { ALL_LICENSES, License, licenseIcons } from '~/constants/license'+import { ALL_LICENSES, License, LICENSE_ICONS } from '~/constants/license'-import { isCc, getFullLicenseName, licenseToElements } from '~/utils/license'+import { getFullLicenseName, getElements } from '~/utils/license'import VIcon from '~/components/VIcon/VIcon.vue'-import ccLogo from '~/assets/licenses/cc-logo.svg'-/*** Displays the icons for the license along with a readable display name for the* license.@@ -47,7 +45,7 @@ export default defineComponent({license: {type: String as PropType<License>,required: true,- validator: (val: string) => ALL_LICENSES.includes(val as License),+ validator: (val: License) => ALL_LICENSES.includes(val as License),},/*** Whether to display icons filled with a white background or leave them transparent.@@ -67,16 +65,7 @@ export default defineComponent({setup(props) {const { i18n } = useContext()- const isCcLicense = computed(() => isCc(props.license))-- const icons = computed(() => {- if (isCcLicense.value) {- return ['ccLogo', ...licenseToElements(props.license)] as const- } else {- return [...licenseToElements(props.license)] as const- }- })-+ const iconNames = computed(() => getElements(props.license))const licenseName = computed(() => {return {readable: i18n.t(`license-readable-names.${props.license}`).toString(),@@ -85,11 +74,8 @@ export default defineComponent({})return {- ccLogo,- svgs: { ...licenseIcons, ccLogo },-- icons,- isCcLicense,+ icons: LICENSE_ICONS,+ iconNames,licenseName,}},diff --git a/src/components/VLicenseElements.vue b/src/components/VLicense/VLicenseElements.vuesimilarity index 61%rename from src/components/VLicenseElements.vuerename to src/components/VLicense/VLicenseElements.vueindex 5bb0e682b..7773701f7 100644--- a/src/components/VLicenseElements.vue+++ b/src/components/VLicense/VLicenseElements.vue@@ -1,7 +1,7 @@<template><ul><li- v-for="element in elements"+ v-for="element in elementNames":key="element"class="flex items-center gap-3 mb-2 text-sm md:text-base">@@ -10,7 +10,7 @@:size="isSmall ? 5 : 6":icon-path="icons[element]"/>- <span v-if="elements.length > 1" class="sr-only">{{+ <span v-if="elementNames.length > 1" class="sr-only">{{element.toUpperCase()}}</span><p :class="{ 'text-sm': isSmall }">@@ -24,8 +24,9 @@import { computed, defineComponent, PropType } from '@nuxtjs/composition-api'import type { License } from '~/constants/license'-import { licenseIcons } from '~/constants/license'-import { licenseToElements } from '~/utils/license'+import { ALL_LICENSES, LICENSE_ICONS } from '~/constants/license'++import { getElements } from '~/utils/license'import VIcon from '~/components/VIcon/VIcon.vue'@@ -33,24 +34,34 @@ export default defineComponent({name: 'VLicenseElements',components: { VIcon },props: {+ /**+ * the slug of the license+ * @values ALL_LICENSES+ */license: {type: String as PropType<License>,required: true,+ validator: (val: License) => ALL_LICENSES.includes(val),},+ /**+ * the size of the icons and text+ */size: {type: String as PropType<'big' | 'small'>,default: 'big',- validator: (val: string) => ['big', 'small'].includes(val),+ validator: (val: 'big' | 'small') => ['big', 'small'].includes(val),},},setup(props) {- const elements = computed(() => licenseToElements(props.license))+ const elementNames = computed(() =>+ getElements(props.license).filter((icon) => icon !== 'cc')+ )const isSmall = computed(() => props.size === 'small')return {- icons: licenseIcons,- elements,+ icons: LICENSE_ICONS,+ elementNames,isSmall,}},diff --git a/src/components/VLicense/meta/VLicenseElements.stories.mdx b/src/components/VLicense/meta/VLicenseElements.stories.mdxnew file mode 100644index 000000000..e24a45eaa--- /dev/null+++ b/src/components/VLicense/meta/VLicenseElements.stories.mdx@@ -0,0 +1,70 @@+import {+ ArgsTable,+ Canvas,+ Description,+ Meta,+ Story,+} from '@storybook/addon-docs'++import VLicenseElements from '~/components/VLicense/VLicenseElements.vue'+import { ALL_LICENSES } from '~/constants/license'++<Meta+ title="Components/VLicenseElements"+ component={VLicenseElements}+ argTypes={{+ license: {+ default: 'by',+ options: ALL_LICENSES,+ control: 'select',+ },+ size: {+ default: 'big',+ options: ['big', 'small'],+ control: 'select',+ },+ }}+/>++export const Template = (args) => ({+ template: `<VLicenseElements v-bind="args" />`,+ components: { VLicenseElements },+ setup() {+ return { args }+ },+})++# VLicense++<Description of={VLicenseElements} />++<ArgsTable of={VLicenseElements} />++## Sizes++### Big++<Canvas>+ <Story+ name="Big"+ args={{+ license: 'by-nc-nd',+ }}+ >+ {Template.bind({})}+ </Story>+</Canvas>++### Small++<Canvas>+ <Story+ name="Small"+ args={{+ license: 'by-nc-nd',+ size: 'small',+ }}+ >+ {Template.bind({})}+ </Story>+</Canvas>diff --git a/src/components/VLink.vue b/src/components/VLink.vueindex 9b5977d15..c4ae68132 100644--- a/src/components/VLink.vue+++ b/src/components/VLink.vue@@ -27,7 +27,7 @@ export default defineComponent({href: {type: String,required: false,- validator: (v: unknown) =>+ validator: (v: string | undefined) =>(typeof v === 'string' && v.length > 0) || typeof v === 'undefined',},},diff --git a/src/components/VMediaInfo/VCopyLicense.vue b/src/components/VMediaInfo/VCopyLicense.vueindex 50eaa610e..2f4df8ccb 100644--- a/src/components/VMediaInfo/VCopyLicense.vue+++ b/src/components/VMediaInfo/VCopyLicense.vue@@ -34,91 +34,27 @@:class="{ hidden: activeTab !== tab }"><div class="overflow-y-scroll">- <i18n+ <!-- Disable reason: We control the attribution HTML generation so this is safe and will not lead to XSS attacks -->+ <!-- eslint-disable vue/no-v-html -->+ <divv-if="tab === 'rich'"id="attribution-rich"- path="media-details.reuse.credit.text"- tag="p"- >- <template #title- ><VLink :href="media.foreign_landing_url">{{- media.title- }}</VLink></template- >- <template #creator>- <i18n- v-if="media.creator"- path="media-details.reuse.credit.creator-text"- tag="span"- >- <template #creator-name>- <VLink v-if="media.creator_url" :href="media.creator_url">{{- media.creator- }}</VLink>- <span v-else>{{ media.creator }}</span>- </template>- </i18n>- </template>- <template #marked-licensed>- {{- isPDM- ? $t('media-details.reuse.credit.marked')- : $t('media-details.reuse.credit.licensed')- }}- </template>- <template #license>- <VLink class="uppercase" :href="licenseUrl">{{- fullLicenseName- }}</VLink- >{{ period }}- </template>- </i18n>+ v-html="getAttributionMarkup({ includeIcons: false })"+ />+ <!-- eslint-enable vue/no-v-html -->+<pv-if="tab === 'html'"id="attribution-html"class="font-mono break-all"dir="ltr">- {{ attributionHtml }}+ {{ getAttributionMarkup() }}</p>- <i18n- v-if="tab === 'plain'"- id="attribution-plain"- path="media-details.reuse.credit.text"- tag="p"- >- <template #title>{{ media.title }}</template>- <template #creator>- <i18n- v-if="media.creator"- path="media-details.reuse.credit.creator-text"- >- <template #creator-name>{{ media.creator }}</template>- </i18n>- </template>- <template #marked-licensed>- {{- isPDM- ? $t('media-details.reuse.credit.marked')- : $t('media-details.reuse.credit.licensed')- }}- </template>- <template #license> {{ fullLicenseName }}</template>- <template #view-legal>- <i18n path="media-details.reuse.credit.view-legal-text">- <template #terms-copy>- {{- isPDM- ? $t('media-details.reuse.credit.terms-text')- : $t('media-details.reuse.credit.copy-text')- }}- </template>- <template v-if="licenseUrl" #URL>- {{ licenseUrl }}- </template>- </i18n>- </template>- </i18n>++ <div v-if="tab === 'plain'" id="attribution-plain">+ {{ getAttributionMarkup({ isPlaintext: true }) }}+ </div></div><VCopyButton@@ -131,52 +67,37 @@</template><script>-import { computed, defineComponent, ref } from '@nuxtjs/composition-api'+import { defineComponent, ref, useContext } from '@nuxtjs/composition-api'-import getAttributionHtml from '~/utils/attribution-html'-import { isPublicDomain } from '~/utils/license'+import { getAttribution } from '~/utils/attribution-html'-import VLink from '~/components/VLink.vue'import VCopyButton from '~/components/VCopyButton.vue'const VCopyLicense = defineComponent({name: 'VCopyLicense',- components: { VCopyButton, VLink },+ components: { VCopyButton },props: {media: {type: Object,},- fullLicenseName: {- type: String,- },},setup(props) {+ const { i18n } = useContext()+const activeTab = ref('rich')const tabs = ['rich', 'html', 'plain']const setActiveTab = (tabIdx) => (activeTab.value = tabIdx)- const licenseUrl = computed(- () => `${props.media.license_url}?ref=openverse`- )-- const isPDM = () => isPublicDomain(props.fullLicenseName)-- const attributionHtml = computed(() => {- const licenseUrl = `${props.media.license_url}&atype=html`- return getAttributionHtml(props.media, licenseUrl, props.fullLicenseName)- })-- const period = '.'+ const getAttributionMarkup = (options) =>+ getAttribution(props.media, i18n, options)return {activeTab,- attributionHtml,- isPDM,- licenseUrl,tabs,setActiveTab,- period,++ getAttributionMarkup,}},})diff --git a/src/components/VMediaInfo/VMediaLicense.vue b/src/components/VMediaInfo/VMediaLicense.vueindex 721e4034b..6172d5e1f 100644--- a/src/components/VMediaInfo/VMediaLicense.vue+++ b/src/components/VMediaInfo/VMediaLicense.vue@@ -41,7 +41,7 @@<script>import { isLicense } from '~/utils/license'-import VLicenseElements from '~/components/VLicenseElements.vue'+import VLicenseElements from '~/components/VLicense/VLicenseElements.vue'import VLink from '~/components/VLink.vue'export default {diff --git a/src/components/VMediaInfo/VMediaReuse.vue b/src/components/VMediaInfo/VMediaReuse.vueindex 17e16e4ca..331e2baf9 100644--- a/src/components/VMediaInfo/VMediaReuse.vue+++ b/src/components/VMediaInfo/VMediaReuse.vue@@ -9,7 +9,7 @@:license-url="media.license_url":full-license-name="fullLicenseName"/>- <VCopyLicense :media="media" :full-license-name="fullLicenseName" />+ <VCopyLicense :media="media" /></div></section></template>diff --git a/src/constants/license.ts b/src/constants/license.tsindex da1710fac..0d020f3ec 100644--- a/src/constants/license.ts+++ b/src/constants/license.ts@@ -1,12 +1,12 @@+import cc from '~/assets/licenses/cc.svg'import by from '~/assets/licenses/by.svg'import nc from '~/assets/licenses/nc.svg'import nd from '~/assets/licenses/nd.svg'import sa from '~/assets/licenses/sa.svg'-import cc0 from '~/assets/licenses/cc0.svg'-import pdm from '~/assets/licenses/pdm.svg'+import zero from '~/assets/licenses/zero.svg'+import pd from '~/assets/licenses/pd.svg'import sampling from '~/assets/licenses/sampling.svg'-import samplingPlus from '~/assets/licenses/sampling-plus.svg'-import ccLogo from '~/assets/licenses/cc-logo.svg'+import samplingPlus from '~/assets/licenses/sampling.plus.svg'export const CC_LICENSES = ['by',@@ -34,15 +34,25 @@ export const LICENSE_VERSIONS = ['', '1.0', '2.0', '2.5', '3.0', '4.0'] as constexport type LicenseVersion = typeof LICENSE_VERSIONS[number]-export const licenseIcons = {- ccLogo,+/**+ * Each key of this mapping can be constructed into an SVG in Creative Commons'+ * press-kit assets using the following URL.+ * ```+ * https://mirrors.creativecommons.org/presskit/icons/{licenseElement}.svg+ * ```+ */+export const LICENSE_ICONS = Object.freeze({+ cc,by,nc,nd,sa,- cc0,- pdm,+ pd,+ zero,sampling,- 'sampling+': samplingPlus,-}-export type LicenseElement = keyof typeof licenseIcons+ 'sampling-plus': samplingPlus,+ remix: undefined,+ share: undefined,+} as const)++export type LicenseElement = keyof typeof LICENSE_ICONSdiff --git a/src/locales/en.json b/src/locales/en.jsonindex b638484d5..1c275048c 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -388,9 +388,9 @@"nc": "Noncommercial uses only.","nd": "No derivatives or adaptations permitted.","sa": "Share adaptations under the same terms.",- "cc0": "This work has been marked as dedicated to the public domain.",- "pdm": "This work is marked as being in the public domain.",- "sampling+": "Samples, mash-ups, creative transformations permitted."+ "zero": "This work has been marked as dedicated to the public domain.",+ "pd": "This work is marked as being in the public domain.",+ "sampling-plus": "Samples, mash-ups, creative transformations permitted."},"aria": {"close": "close",@@ -417,11 +417,11 @@"link": "here"},"credit": {- "text": "\"{title}\"{creator}{marked-licensed}{license}{view-legal}",+ "text": "\"{title}\"{creator}{marked-licensed}{license}. {view-legal}","creator-text": " by {creator-name}",- "marked": "is marked with",- "licensed": "is licensed under",- "view-legal-text": ". To view {terms-copy}visit {URL}",+ "marked": " is marked with ",+ "licensed": " is licensed under ",+ "view-legal-text": "To view {terms-copy} visit {URL}.","terms-text": "the terms,","copy-text": "a copy of this license,"},diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.potindex 4da23f69d..ffc3af3f6 100644--- a/src/locales/po-files/openverse.pot+++ b/src/locales/po-files/openverse.pot@@ -4,7 +4,7 @@ msgid ""msgstr """Project-Id-Version: Openverse \n""Report-Msgid-Bugs-To: https://github.com/wordpress/openverse/issues \n"-"POT-Creation-Date: 2022-04-05T13:27:38+00:00\n"+"POT-Creation-Date: 2022-04-06T10:05:03+00:00\n""MIME-Version: 1.0\n""Content-Type: text/plain; charset=UTF-8\n""Content-Transfer-Encoding: 8bit\n"@@ -614,39 +614,32 @@ msgid "Copied!"msgstr ""#. Do not translate words between ### ###.-#: src/components/VMediaInfo/VCopyLicense.vue:37msgctxt "media-details.reuse.credit.text"-msgid "\"###title###\"###creator######marked-licensed######license######view-legal###"+msgid "\"###title###\"###creator######marked-licensed######license###. ###view-legal###"msgstr ""#. Do not translate words between ### ###.-#: src/components/VMediaInfo/VCopyLicense.vue:49msgctxt "media-details.reuse.credit.creator-text"msgid " by ###creator-name###"msgstr ""-#: src/components/VMediaInfo/VCopyLicense.vue:65msgctxt "media-details.reuse.credit.marked"-msgid "is marked with"+msgid " is marked with "msgstr ""-#: src/components/VMediaInfo/VCopyLicense.vue:66msgctxt "media-details.reuse.credit.licensed"-msgid "is licensed under"+msgid " is licensed under "msgstr ""#. Do not translate words between ### ###.-#: src/components/VMediaInfo/VCopyLicense.vue:108msgctxt "media-details.reuse.credit.view-legal-text"-msgid ". To view ###terms-copy###visit ###URL###"+msgid "To view ###terms-copy### visit ###URL###."msgstr ""-#: src/components/VMediaInfo/VCopyLicense.vue:112msgctxt "media-details.reuse.credit.terms-text"msgid "the terms,"msgstr ""-#: src/components/VMediaInfo/VCopyLicense.vue:113msgctxt "media-details.reuse.credit.copy-text"msgid "a copy of this license,"msgstr ""@@ -745,15 +738,15 @@ msgctxt "browse-page.license-description.sa"msgid "Share adaptations under the same terms."msgstr ""-msgctxt "browse-page.license-description.cc0"+msgctxt "browse-page.license-description.zero"msgid "This work has been marked as dedicated to the public domain."msgstr ""-msgctxt "browse-page.license-description.pdm"+msgctxt "browse-page.license-description.pd"msgid "This work is marked as being in the public domain."msgstr ""-msgctxt "browse-page.license-description.sampling+"+msgctxt "browse-page.license-description.sampling-plus"msgid "Samples, mash-ups, creative transformations permitted."msgstr ""@@ -1091,7 +1084,7 @@ msgid "Couldn't find image with id ###id###"msgstr ""#. Do not translate words between ### ###.-#: src/pages/audio/_id.vue:87+#: src/pages/audio/_id.vue:67msgctxt "error.media-not-found"msgid "Couldn't find ###mediaType### with id ###id###"msgstr ""diff --git a/src/models/media.ts b/src/models/media.tsindex e75015ebe..e56d0961a 100644--- a/src/models/media.ts+++ b/src/models/media.ts@@ -1,4 +1,5 @@import type { SupportedMediaType } from '~/constants/media'+import type { License, LicenseVersion } from '~/constants/license'export interface Tag {name: string@@ -18,8 +19,8 @@ export interface Media {url: stringforeign_landing_url: string- license: string- license_version: string+ license: License+ license_version: LicenseVersionlicense_url: stringattribution: stringdiff --git a/src/pages/audio/_id.vue b/src/pages/audio/_id.vueindex abfbe1b37..8baf30d13 100644--- a/src/pages/audio/_id.vue+++ b/src/pages/audio/_id.vue@@ -7,13 +7,7 @@<divclass="mt-10 lg:mt-16 flex flex-col gap-10 lg:gap-16 px-4 lg:px-0 lg:max-w-5xl mx-auto">- <VMediaReuse- data-testid="audio-attribution"- :media="audio"- :license-url="licenseUrl"- :full-license-name="fullLicenseName"- :attribution-html="attributionHtml()"- />+ <VMediaReuse data-testid="audio-attribution" :media="audio" /><VAudioDetails data-testid="audio-info" :audio="audio" /><VRelatedAudio v-if="audio.id" :audio-id="audio.id" /></div>@@ -24,8 +18,6 @@import { computed } from '@nuxtjs/composition-api'import { AUDIO } from '~/constants/media'-import getAttributionHtml from '~/utils/attribution-html'-import { getFullLicenseName } from '~/utils/license'import { useMediaStore } from '~/stores/media'import VAudioDetails from '~/components/VAudioDetails/VAudioDetails.vue'@@ -54,18 +46,6 @@ const AudioDetailPage = {return { audio }},- computed: {- fullLicenseName() {- return getFullLicenseName(- this.audio.license,- this.audio.license_version,- this.$i18n- )- },- licenseUrl() {- return `${this.audio.license_url}?ref=openverse`- },- },watch: {audio(newAudio) {this.id = newAudio.id@@ -101,12 +81,6 @@ const AudioDetailPage = {}})},- methods: {- attributionHtml() {- const licenseUrl = `${this.licenseUrl}&atype=html`- return getAttributionHtml(this.audio, licenseUrl, this.fullLicenseName)- },- },head() {const title = this.audio.titlereturn {diff --git a/src/utils/attribution-html.ts b/src/utils/attribution-html.tsindex c6b2d5244..1f7126579 100644--- a/src/utils/attribution-html.ts+++ b/src/utils/attribution-html.ts@@ -1,70 +1,197 @@import type { Media } from '~/models/media'+import {+ getElements,+ getFullLicenseName,+ isPublicDomain,+} from '~/utils/license'+import type { LicenseElement } from '~/constants/license'-const linkProperties = 'target="_blank" rel="noopener noreferrer"'+import type VueI18n from 'vue-i18n'-function getAttributionHtml(- media: Media,- licenseUrl: string,- fullLicenseName: string-) {- if (!media) {- return ''- }- const baseAssetsPath = 'https://search.openverse.engineering/static/img'- const imgLink = `<a href="${media.foreign_landing_url}" ${linkProperties}>"${media.title}"</a>`- let creator = ''- let mediaTag = ''- if (media.url && media.title) {- mediaTag = `<img style="display: block;" src="${media.url}" alt="${media.title}">`- }- if (media.creator && media.creator_url) {- creator = `<span> by <a href="${media.creator_url}" ${linkProperties}>${media.creator}</a></span>`- } else if (media.creator && !media.creator_url) {- creator = `<span> by <span>${media.creator}</span></span>`- }- const licenseLink = ` is licensed under <a href="${licenseUrl}" style="margin-right: 5px;" ${linkProperties}>${fullLicenseName.toUpperCase()}</a>`-- let licenseIcons = `<img style="height: inherit;margin-right: 3px;display: inline-block;" src="${baseAssetsPath}/cc_icon.svg?media_id=${media.id}" />`- if (media.license) {- licenseIcons += media.license- .split('-')- .map(- (license) =>- `<img style="height: inherit;margin-right: 3px;display: inline-block;" src="${baseAssetsPath}/cc-${license.toLowerCase()}_icon.svg" />`- )- .join('')- }+/* Helper functions */++/**+ * Create an HTML tag with the given name, attributes and children.+ *+ * @param name - the tag name+ * @param attrs - the attributes associated with the tag+ * @param children - the tags children+ * @returns the HTML markup of the tag+ */+const h = (+ name: string,+ attrs: Record<string, string>,+ children: string[] | null = null+): string => {+ const map = Object.entries(attrs)+ .map(([key, value]) => `${key}="${value}"`)+ .join(' ')+ const opening = map ? `<${name} ${map}>` : `<${name}>`+ const closing = `</${name}>`+ return `${opening}${(children ?? []).join('\n')}${closing}`+}++/**+ * Get an `<img>` tag corresponding to a license element.+ *+ * @param licenseElement - the license element for which to get the `<img>` tag+ * @returns the HTML markup of the `<img>` tag+ */+const licenseElementImg = (licenseElement: LicenseElement): string => {+ const filename = licenseElement.replace('-', '.')+ const src = `https://mirrors.creativecommons.org/presskit/icons/${filename}.svg`+ return h('img', {+ src,+ style: 'height: 1em; margin-right: 0.125em; display: inline;',+ })+}++/**+ * Get an HTML `<a>` tag set up with the `target` and `rel` attributes.+ *+ * @param href - the link that the anchor tag should point to+ * @param text - the textual content of the anchor tag+ * @returns the HTML markup of the `<a>` tag+ */+const extLink = (href: string, text: string) =>+ h('a', { target: '_blank', rel: 'noopener noreferrer', href }, [text])++/* Interfaces */++/**+ * This interface describes a subset of media that contains fields necessary+ * for generating a proper attribution.+ */+export type AttributableMedia = Pick<+ Media,+ | 'title'+ | 'foreign_landing_url'+ | 'creator'+ | 'creator_url'+ | 'license'+ | 'license_version'+ | 'license_url'+>- const licenseImgLink = `<a href="${licenseUrl}" ${linkProperties} style="display: inline-block;white-space: none;margin-top: 2px;margin-left: 3px;height: 22px !important;">${licenseIcons}</a>`- return `<p style="font-size: 0.9rem;font-style: italic;">${mediaTag}${imgLink}${creator}${licenseLink}${licenseImgLink}</p>`+/**+ * This interface describes the options that the `getAttribution` function can+ * take to customise its output.+ */+interface AttributionOptions {+ includeIcons?: boolean+ isPlaintext?: boolean}+/* Actual util */+/**- * Get the HTML markup for attributing the given media item.+ * Get the HTML markup for properly attributing the given media item.*- * @param mediaItem - the media item, image or audio from the API, to attribute+ * @param mediaItem - the media item being attributed+ * @param i18n - the i18n instance to access translations+ * @param includePreview - whether to include the preview markup in the HTML* @returns the HTML markup of the attribution*/-export const getAttributionMarkup = (mediaItem: Media) => {+export const getAttribution = (+ mediaItem: AttributableMedia,+ i18n: VueI18n | null = null,+ { includeIcons, isPlaintext }: AttributionOptions = {+ isPlaintext: false,+ includeIcons: true,+ }+): string => {if (!mediaItem) return ''- const extLink = (href: string, text: string) =>- `<a rel="noopener noreferrer" target="_blank" href="${href}">${text}</a>`+ /* Title */- let title = `"${mediaItem.title}"`- if (mediaItem.foreign_landing_url) {- title = extLink(mediaItem.foreign_landing_url, title)+ let titleLink = mediaItem.title || ''+ if (!isPlaintext && mediaItem.foreign_landing_url)+ titleLink = extLink(mediaItem.foreign_landing_url, titleLink)++ /* Creator */++ let creatorLink = mediaItem.creator || ''+ if (!isPlaintext && mediaItem.creator_url)+ creatorLink = extLink(mediaItem.creator_url, creatorLink)++ /* License */++ const fullLicenseName = getFullLicenseName(+ mediaItem.license,+ mediaItem.license_version,+ i18n+ )+ let licenseIcons = ''+ if (includeIcons && mediaItem.license) {+ const elements = getElements(mediaItem.license)+ const icons = elements.map((element) => licenseElementImg(element))+ // Icons are only rendered if present for every element+ if (!icons.includes('')) {+ licenseIcons = icons.join('')+ }}- let creator = mediaItem.creator- if (mediaItem.creator_url) {- creator = extLink(mediaItem.creator_url, creator)+ let licenseLink = `${fullLicenseName} ${licenseIcons}`.trim()+ if (!isPlaintext && mediaItem.license_url) {+ licenseLink = extLink(`${mediaItem.license_url}?ref=openverse`, licenseLink)}- let license = `${mediaItem.license} ${mediaItem.license_version}`- license = extLink(mediaItem.license_url, license.toUpperCase())+ /* Attribution */- return `${title} by ${creator} is licensed under ${license}.`-}+ const i18nBase = 'media-details.reuse.credit'+ const isPd = isPublicDomain(mediaItem.license)++ let attribution: string+ if (i18n) {+ let fillers: Record<string, string> = {+ title: titleLink,+ creator: i18n+ .t(`${i18nBase}.creator-text`, {+ 'creator-name': creatorLink,+ })+ .toString(),+ 'marked-licensed': i18n+ .t(`${i18nBase}.${isPd ? 'marked' : 'licensed'}`)+ .toString(),+ license: licenseLink,+ }+ if (isPlaintext) {+ fillers = {+ ...fillers,+ 'view-legal': i18n+ .t(`${i18nBase}.view-legal-text`, {+ 'terms-copy': i18n.t(+ `${i18nBase}.${isPd ? 'terms-text' : 'copy-text'}`+ ),+ URL: `${mediaItem.license_url}?ref=openverse`,+ })+ .toString(),+ }+ }+ attribution = i18n.t(`${i18nBase}.text`, fillers).toString()+ } else {+ let attributionParts = [+ `"${titleLink}"`,+ ' by ',+ creatorLink,+ isPd ? ' is marked with ' : ' is licensed under ',+ licenseLink,+ '.',+ ]+ if (isPlaintext) {+ attributionParts = [+ ...attributionParts,+ ' To view ',+ isPd ? 'the terms,' : 'a copy of this license,',+ ' visit',+ mediaItem.license_url,+ '.',+ ]+ }-export default getAttributionHtml+ attribution = attributionParts.join('')+ }+ return isPlaintext+ ? attribution+ : h('p', { class: 'attribution' }, [attribution])+}diff --git a/src/utils/license.ts b/src/utils/license.tsindex c503e1e89..b9516f3d8 100644--- a/src/utils/license.ts+++ b/src/utils/license.ts@@ -1,8 +1,11 @@-import type { License, LicenseVersion } from '~/constants/license'+import type {+ License,+ LicenseVersion,+ LicenseElement,+} from '~/constants/license'import {CC_LICENSES,DEPRECATED_CC_LICENSES,- LicenseElement,PUBLIC_DOMAIN_MARKS,} from '~/constants/license'@@ -89,8 +92,30 @@ export const isCc = (license: License): boolean =>(DEPRECATED_CC_LICENSES as ReadonlyArray<License>).includes(license)/**- * Splits license slug by `-` and returns an array of license elements- * @param license - the license slug+ * Get the list of elements that comprise the given license or mark.+ *+ * @param license - the license for which to get the elements*/-export const licenseToElements = (license: License) =>- (license as string).split(/[-\s]/) as LicenseElement[]+export const getElements = (license: License): LicenseElement[] => {+ if (license === 'pdm') {+ return ['pd']+ }++ const icons: LicenseElement[] = ['cc']+ if (license === 'cc0') {+ icons.push('zero')+ } else {+ const replacements: Record<string, LicenseElement> = {+ 'sampling+': 'sampling-plus',+ }+ const elements = license+ .split('-')+ .map((element) =>+ element in replacements+ ? replacements[element]+ : (element as LicenseElement)+ )+ icons.push(...elements)+ }+ return icons+}diff --git a/test/playwright/e2e/attribution.spec.ts b/test/playwright/e2e/attribution.spec.tsnew file mode 100644index 000000000..f317128f9--- /dev/null+++ b/test/playwright/e2e/attribution.spec.ts@@ -0,0 +1,44 @@+import { test, expect } from '@playwright/test'++test.beforeEach(async ({ context }) => {+ await context.grantPermissions(['clipboard-read', 'clipboard-write'])+})++test('can copy rich text attribution', async ({ page }) => {+ await page.goto('image/e9d97a98-621b-4ec2-bf70-f47a74380452')+ await page.click('[aria-controls="tab-rich"]')+ await page.click('[id="copyattr-rich"]')+ const clippedText = await page.evaluate(async () => {+ return navigator.clipboard.readText()+ })+ // The Clipboard API returns a plain-text-ified version of the rich text.+ expect(clippedText).toContain('"bubbles in honey" by mutednarayan')+})++test('can copy HTML attribution', async ({ page }) => {+ await page.goto('image/e9d97a98-621b-4ec2-bf70-f47a74380452')+ await page.click('[aria-controls="tab-html"]')+ await page.click('[id="copyattr-html"]')+ const clippedText = await page.evaluate(async () => {+ return navigator.clipboard.readText()+ })+ const snippets = [+ '<p class="attribution">',+ '>bubbles in honey</a>',+ '>mutednarayan</a>',+ ]+ snippets.forEach((snippet) => {+ expect(clippedText).toContain(snippet)+ })+})++test('can copy plain text attribution', async ({ page }) => {+ await page.goto('image/e9d97a98-621b-4ec2-bf70-f47a74380452')+ await page.click('[aria-controls="tab-plain"]')+ await page.click('[id="copyattr-plain"]')+ const clippedText = await page.evaluate(async () => {+ return navigator.clipboard.readText()+ })+ // Only the plain-text license contains the "To view" bit.+ expect(clippedText).toContain('To view a copy of this license')+})diff --git a/test/unit/specs/utils/attribution-html.spec.ts b/test/unit/specs/utils/attribution-html.spec.tsnew file mode 100644index 000000000..12e1d03a4--- /dev/null+++ b/test/unit/specs/utils/attribution-html.spec.ts@@ -0,0 +1,70 @@+import Vuei18n from 'vue-i18n'++import type { AttributableMedia } from '~/utils/attribution-html'+import { getAttribution } from '~/utils/attribution-html'+import enMessages from '~/locales/en.json'++const i18n = new Vuei18n({+ locale: 'en',+ fallbackLocale: 'en',+ messages: { en: enMessages },+})++const mediaItem: AttributableMedia = {+ title: 'Title',+ foreign_landing_url: 'https://foreign.landing/url',+ creator: 'Creator',+ creator_url: 'https://creator/url',+ license: 'pdm',+ license_version: '1.0',+ license_url: 'https://license/url',+}++describe('getAttribution', () => {+ it.each`+ sendI18n | attributionText+ ${true} | ${'"Title" by Creator is marked with Public Domain Mark 1.0 .'}+ ${false} | ${'"Title" by Creator is marked with PDM 1.0 .'}+ `(+ 'returns attribution for media with i18n $sendI18n',+ ({+ sendI18n,+ attributionText,+ }: {+ sendI18n: boolean+ attributionText: boolean+ }) => {+ document.body.innerHTML = getAttribution(+ mediaItem,+ sendI18n ? i18n : null+ )+ const attributionP = document.getElementsByClassName('attribution')[0]+ expect(attributionP.textContent?.trim()).toEqual(attributionText)+ }+ )++ it('does not use anchors in plain-text mode', () => {+ document.body.innerHTML = getAttribution(mediaItem, i18n)+ expect(document.getElementsByTagName('a').length !== 0)+ document.body.innerHTML = getAttribution(mediaItem, i18n, {+ isPlaintext: true,+ })+ expect(document.getElementsByTagName('a').length === 0)+ })++ it('renders the correct text in plain-text mode', () => {+ const attrText = getAttribution(mediaItem, i18n, { isPlaintext: true })+ const expectation =+ '"Title" by Creator is marked with Public Domain Mark 1.0. To view the terms, visit https://license/url?ref=openverse.'+ expect(attrText).toEqual(expectation)+ })++ it('does not add license element icons in no-icons mode', () => {+ document.body.innerHTML = getAttribution(mediaItem, i18n)+ expect(document.getElementsByTagName('img').length !== 0)+ document.body.innerHTML = getAttribution(mediaItem, i18n, {+ includeIcons: false,+ })+ expect(document.getElementsByTagName('img').length === 0)+ })+})diff --git a/test/unit/specs/utils/license.spec.ts b/test/unit/specs/utils/license.spec.tsindex 8a38c1ba1..c23f8ed22 100644--- a/test/unit/specs/utils/license.spec.ts+++ b/test/unit/specs/utils/license.spec.ts@@ -1,6 +1,6 @@import Vuei18n from 'vue-i18n'-import { getFullLicenseName } from '~/utils/license'+import { getFullLicenseName, getElements } from '~/utils/license'import type { License, LicenseVersion } from '~/constants/license'import enMessages from '~/locales/en.json'@@ -39,3 +39,24 @@ describe('getFullLicenseName', () => {})})++describe('getElements', () => {+ it.each`+ license | icons+ ${'by'} | ${['cc', 'by']}+ ${'by-sa'} | ${['cc', 'by', 'sa']}+ ${'by-nd'} | ${['cc', 'by', 'nd']}+ ${'by-nc'} | ${['cc', 'by', 'nc']}+ ${'by-nc-sa'} | ${['cc', 'by', 'nc', 'sa']}+ ${'by-nc-nd'} | ${['cc', 'by', 'nc', 'nd']}+ ${'nc-sampling+'} | ${['cc', 'nc', 'sampling-plus']}+ ${'sampling+'} | ${['cc', 'sampling-plus']}+ ${'pdm'} | ${['pd']}+ ${'cc0'} | ${['cc', 'zero']}+ `(+ 'returns $icons for $license',+ ({ license, icons }: { license: License; icons: string[] }) => {+ expect(getElements(license)).toEqual(icons)+ }+ )+})