Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Convert license utils and constants to TS (#1134)
Dhruv Bhanushali64976f21166b
diff --git a/src/components/License/VLicense.vue b/src/components/License/VLicense.vueindex 6f7e14507..cb420eb11 100644--- a/src/components/License/VLicense.vue+++ b/src/components/License/VLicense.vue@@ -1,13 +1,6 @@<template><div class="license flex flex-row items-center gap-2"><div class="flex gap-1">- <VIcon- v-if="isCC"- :class="['icon', bgFilled ? 'bg-filled text-black' : '']"- view-box="0 0 30 30"- :icon-path="ccLogo"- :size="4"- /><VIconv-for="(name, index) in icons":key="index"@@ -26,12 +19,9 @@<script>import { computed, useContext } from '@nuxtjs/composition-api'-import {- ALL_LICENSES,- CC_LICENSES,- DEPRECATED_LICENSES,- LICENSE_ICON_MAPPING,-} from '~/constants/license'+import { ALL_LICENSES } from '~/constants/license'++import { isCc, getFullLicenseName } from '~/utils/license'import VIcon from '~/components/VIcon/VIcon.vue'@@ -42,6 +32,7 @@ import nc from '~/assets/licenses/nc.svg'import nd from '~/assets/licenses/nd.svg'import pdm from '~/assets/licenses/pdm.svg'import sa from '~/assets/licenses/sa.svg'+import samplingPlus from '~/assets/licenses/sampling-plus.svg'/*** Displays the icons for the license along with a readable display name for the@@ -77,47 +68,37 @@ export default {},setup(props) {const { i18n } = useContext()- const isDeprecated = computed(() =>- DEPRECATED_LICENSES.includes(props.license)- )++ const isCcLicense = computed(() => isCc(props.license))+const icons = computed(() => {- if (isDeprecated.value) {- return []- }- return props.license- .split(/[-\s]/)- .map((term) => LICENSE_ICON_MAPPING[term])+ let iconList = props.license.split(/[-\s]/)+ if (isCcLicense.value) iconList = ['ccLogo', ...iconList]+ return iconList})- const isCC = computed(- () => CC_LICENSES.includes(props.license) || props.license === 'cc0'- )- /**- * @type {import('@nuxtjs/composition-api').ComputedRef<{ readable: string, full: string }>}- */+const licenseName = computed(() => {- if (isDeprecated.value) {- return { readable: props.license, full: props.license }- } else {- return {- readable: i18n.t(`license-readable-names.${props.license}`),- full: i18n.t(`license-names.${props.license}`),- }+ return {+ readable: i18n.t(`license-readable-names.${props.license}`),+ full: getFullLicenseName(props.license, '', i18n),}})return {ccLogo,svgs: {+ ccLogo,by,cc0,nc,nd,pdm,sa,+ 'sampling+': samplingPlus,},icons,- isCC,+ isCcLicense,licenseName,}},diff --git a/src/components/License/meta/VLicense.stories.mdx b/src/components/License/meta/VLicense.stories.mdxindex 98d588bf0..efa61eaa7 100644--- a/src/components/License/meta/VLicense.stories.mdx+++ b/src/components/License/meta/VLicense.stories.mdx@@ -10,10 +10,12 @@ import VLicense from '~/components/License/VLicense.vue'<Meta title="Components/VLicense" component={VLicense} />-export const Template = (args, { argTypes }) => ({- template: `<VLicense v-bind="$props" />`,+export const Template = (args) => ({+ template: `<VLicense v-bind="args" />`,components: { VLicense },- props: Object.keys(argTypes),+ setup() {+ return { args }+ },})# VLicense@@ -24,18 +26,18 @@ export const Template = (args, { argTypes }) => ({It can display CC licenses.-| License name | Code | Slug |-| --------------------------------------- | -------- | ---------- |-| Attribution | BY | `by` |-| Attribution-ShareAlike | BY-SA | `by-sa` |-| Attribution-NoDerivatives | BY-ND | `by-nd` |-| Attribution-NonCommercial | BY-NC | `by-nc` |-| Attribution-NonCommercial-ShareAlike | BY-NC-SA | `by-nc-sa` |-| Attribution-NonCommercial-NoDerivatives | BY-NC-ND | `by-nc-nd` |+| License name | Abbreviation | Slug |+| --------------------------------------- | ------------ | ---------- |+| Attribution | CC BY | `by` |+| Attribution-ShareAlike | CC BY-SA | `by-sa` |+| Attribution-NoDerivatives | CC BY-ND | `by-nd` |+| Attribution-NonCommercial | CC BY-NC | `by-nc` |+| Attribution-NonCommercial-ShareAlike | CC BY-NC-SA | `by-nc-sa` |+| Attribution-NonCommercial-NoDerivatives | CC BY-NC-ND | `by-nc-nd` |<Canvas><Story- name="BY"+ name="CC BY"args={{license: 'by',}}@@ -43,7 +45,7 @@ It can display CC licenses.{Template.bind({})}</Story><Story- name="BY-SA"+ name="CC BY-SA"args={{license: 'by-sa',}}@@ -51,7 +53,7 @@ It can display CC licenses.{Template.bind({})}</Story><Story- name="BY-ND"+ name="CC BY-ND"args={{license: 'by-nd',}}@@ -59,7 +61,7 @@ It can display CC licenses.{Template.bind({})}</Story><Story- name="BY-NC"+ name="CC BY-NC"args={{license: 'by-nc',}}@@ -67,7 +69,7 @@ It can display CC licenses.{Template.bind({})}</Story><Story- name="BY-NC-SA"+ name="CC BY-NC-SA"args={{license: 'by-nc-sa',}}@@ -75,7 +77,7 @@ It can display CC licenses.{Template.bind({})}</Story><Story- name="BY-NC-ND"+ name="CC BY-NC-ND"args={{license: 'by-nc-nd',}}@@ -86,10 +88,10 @@ It can display CC licenses.It can also display some public domain licenses.-| License name | Code | Slug |-| ------------------ | ---- | ----- |-| CC Zero | CC0 | `cc0` |-| Public domain mark | PDM | `pdm` |+| License name | Abbreviation | Slug |+| ------------------ | ------------ | ----- |+| CC Zero | CC0 | `cc0` |+| Public Domain Mark | - | `pdm` |<Canvas><Story@@ -110,6 +112,32 @@ It can also display some public domain licenses.</Story></Canvas>+It can also display some deprecated CC licenses.++| License name | Abbreviation | Slug |+| --------------------------- | --------------- | -------------- |+| Sampling Plus | CC Sampling+ | `sampling+` |+| NonCommercial Sampling Plus | CC NC-Sampling+ | `nc-sampling+` |++<Canvas>+ <Story+ name="CC Sampling+"+ args={{+ license: 'sampling+',+ }}+ >+ {Template.bind({})}+ </Story>+ <Story+ name="CC NC-Sampling+"+ args={{+ license: 'nc-sampling+',+ }}+ >+ {Template.bind({})}+ </Story>+</Canvas>+It can also show only the license icons.<Canvas>diff --git a/src/components/VFilters/VLicenseExplanation.vue b/src/components/VFilters/VLicenseExplanation.vueindex a8ab70266..8f04d71ae 100644--- a/src/components/VFilters/VLicenseExplanation.vue+++ b/src/components/VFilters/VLicenseExplanation.vue@@ -36,9 +36,7 @@</template><script>-import { isLicense } from '~/utils/license'--import { DEPRECATED_LICENSES } from '~/constants/license'+import { isLicense, isDeprecated } from '~/utils/license'import VLicenseElements from '~/components/VLicenseElements.vue'import VLink from '~/components/VLink.vue'@@ -78,7 +76,7 @@ export default {fragment = 'publicdomain/zero/1.0'} else if (licenseTerm === 'pdm') {fragment = 'publicdomain/mark/1.0'- } else if (DEPRECATED_LICENSES.includes(licenseTerm)) {+ } else if (isDeprecated(licenseTerm)) {fragment = `licenses/${licenseTerm}/1.0`} else {fragment = `licenses/${licenseTerm}/4.0`diff --git a/src/components/VMediaInfo/VMediaReuse.vue b/src/components/VMediaInfo/VMediaReuse.vueindex 8e9a12794..17e16e4ca 100644--- a/src/components/VMediaInfo/VMediaReuse.vue+++ b/src/components/VMediaInfo/VMediaReuse.vue@@ -15,7 +15,7 @@</template><script>-import { computed, defineComponent } from '@nuxtjs/composition-api'+import { computed, defineComponent, useContext } from '@nuxtjs/composition-api'import { getFullLicenseName } from '~/utils/license'@@ -32,8 +32,10 @@ const VMediaReuse = defineComponent({},},setup(props) {+ const { i18n } = useContext()+const fullLicenseName = computed(() =>- getFullLicenseName(props.media.license, props.media.license_version)+ getFullLicenseName(props.media.license, props.media.license_version, i18n))return { fullLicenseName }diff --git a/src/constants/filters.ts b/src/constants/filters.tsindex 99ad5baad..33914337c 100644--- a/src/constants/filters.ts+++ b/src/constants/filters.ts@@ -59,7 +59,7 @@ export const mediaUniqueFilterKeys = deepFreeze<})const filterCodesPerCategory = deepFreeze<Record<FilterCategory, string[]>>({- licenses: ACTIVE_LICENSES,+ licenses: [...ACTIVE_LICENSES],licenseTypes: ['commercial', 'modification'],audioCategories: ['music', 'sound', 'podcast'],imageCategories: ['photograph', 'illustration', 'digitized_artwork'],diff --git a/src/constants/license.js b/src/constants/license.jsdeleted file mode 100644index f5cc5591f..000000000--- a/src/constants/license.js+++ /dev/null@@ -1,29 +0,0 @@-export const CC_LICENSES = [- 'by',- 'by-sa',- 'by-nd',- 'by-nc',- 'by-nc-sa',- 'by-nc-nd',-]--export const NON_CC_LICENSES = ['cc0', 'pdm']--export const DEPRECATED_LICENSES = ['nc-sampling+', 'sampling+']--export const ACTIVE_LICENSES = [...NON_CC_LICENSES, ...CC_LICENSES]--export const ALL_LICENSES = [- ...CC_LICENSES,- ...NON_CC_LICENSES,- ...DEPRECATED_LICENSES,-]--export const LICENSE_ICON_MAPPING = {- by: 'by',- nc: 'nc',- nd: 'nd',- sa: 'sa',- cc0: 'cc0',- pdm: 'pdm',-}diff --git a/src/constants/license.ts b/src/constants/license.tsnew file mode 100644index 000000000..7f193fe02--- /dev/null+++ b/src/constants/license.ts@@ -0,0 +1,25 @@+export const CC_LICENSES = [+ 'by',+ 'by-sa',+ 'by-nd',+ 'by-nc',+ 'by-nc-sa',+ 'by-nc-nd',+] as const++export const DEPRECATED_CC_LICENSES = ['nc-sampling+', 'sampling+'] as const++export const PUBLIC_DOMAIN_MARKS = ['pdm', 'cc0'] as const++export const ACTIVE_LICENSES = [...PUBLIC_DOMAIN_MARKS, ...CC_LICENSES] as const++export const ALL_LICENSES = [+ ...ACTIVE_LICENSES,+ ...DEPRECATED_CC_LICENSES,+] as const++export type License = typeof ALL_LICENSES[number]++export const LICENSE_VERSIONS = ['', '1.0', '2.0', '2.5', '3.0', '4.0'] as const++export type LicenseVersion = typeof LICENSE_VERSIONS[number]diff --git a/src/layouts/default.vue b/src/layouts/default.vueindex 43e59c965..eeec414ca 100644--- a/src/layouts/default.vue+++ b/src/layouts/default.vue@@ -110,7 +110,7 @@ export default embeddedPage.main {height: 100%;display: grid;- grid-template-columns: 1fr 316px;+ grid-template-columns: 1fr 336px;}// Make the main content area span both grid columns// when the sidebar is closed...diff --git a/src/locales/en.json b/src/locales/en.jsonindex 83c8329c0..8d70debd3 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -575,16 +575,6 @@"podcast": "Podcast","pronunciation": "Pronunciation"},- "license-names": {- "cc0": "CC0",- "pdm": "Public Domain Mark",- "by": "BY",- "by-sa": "BY-SA",- "by-nc": "BY-NC",- "by-nd": "BY-ND",- "by-nc-sa": "BY-NC-SA",- "by-nc-nd": "BY-NC-ND"- },"license-readable-names": {"cc0": "Zero","pdm": "Public Domain Mark",@@ -593,7 +583,9 @@"by-nc": "Attribution-NonCommercial","by-nd": "Attribution-NoDerivatives","by-nc-sa": "Attribution-NonCommercial-Share-Alike",- "by-nc-nd": "Attribution-NonCommercial-NoDerivatives"+ "by-nc-nd": "Attribution-NonCommercial-NoDerivatives",+ "sampling+": "Sampling Plus",+ "nc-sampling+": "NonCommercial Sampling Plus"},"dropdown-button": {"aria": {diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.potindex 121fc777d..66414816e 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-03-21T10:40:55+00:00\n"+"POT-Creation-Date: 2022-03-21T12:21:26+00:00\n""MIME-Version: 1.0\n""Content-Type: text/plain; charset=UTF-8\n""Content-Transfer-Encoding: 8bit\n"@@ -155,36 +155,12 @@ msgctxt "license-readable-names.by-nc-nd"msgid "Attribution-NonCommercial-NoDerivatives"msgstr ""-msgctxt "license-names.cc0"-msgid "CC0"-msgstr ""--msgctxt "license-names.pdm"-msgid "Public Domain Mark"-msgstr ""--msgctxt "license-names.by"-msgid "BY"-msgstr ""--msgctxt "license-names.by-sa"-msgid "BY-SA"+msgctxt "license-readable-names.sampling+"+msgid "Sampling Plus"msgstr ""-msgctxt "license-names.by-nc"-msgid "BY-NC"-msgstr ""--msgctxt "license-names.by-nd"-msgid "BY-ND"-msgstr ""--msgctxt "license-names.by-nc-sa"-msgid "BY-NC-SA"-msgstr ""--msgctxt "license-names.by-nc-nd"-msgid "BY-NC-ND"+msgctxt "license-readable-names.nc-sampling+"+msgid "NonCommercial Sampling Plus"msgstr ""msgctxt "audio-categories.title"@@ -1108,7 +1084,7 @@ msgid "Couldn't find image with id ###id###"msgstr ""#. Do not translate words between ### ###.-#: src/pages/audio/_id.vue:78+#: src/pages/audio/_id.vue:82msgctxt "error.media-not-found"msgid "Couldn't find ###mediaType### with id ###id###"msgstr ""diff --git a/src/pages/audio/_id.vue b/src/pages/audio/_id.vueindex 4c4ccf8c9..faa25dcf0 100644--- a/src/pages/audio/_id.vue+++ b/src/pages/audio/_id.vue@@ -52,7 +52,11 @@ const AudioDetailPage = {computed: {...mapState(MEDIA, ['audio']),fullLicenseName() {- return getFullLicenseName(this.audio.license, this.audio.license_version)+ return getFullLicenseName(+ this.audio.license,+ this.audio.license_version,+ this.$i18n+ )},licenseUrl() {return `${this.audio.license_url}?ref=openverse`diff --git a/src/utils/filters.js b/src/utils/filters.jsdeleted file mode 100644index e69de29bb..000000000diff --git a/src/utils/license.js b/src/utils/license.jsdeleted file mode 100644index 9e3557cc1..000000000--- a/src/utils/license.js+++ /dev/null@@ -1,48 +0,0 @@-// There are six CC licenses and two Public Domain tools (PDM and CC0,-// which are not licenses in the legal sense.-// FAQ on CC and PDM: https://wiki.creativecommons.org/wiki/CC0_FAQ#What_is_CC0.3F-// Information on CC licenses: https://creativecommons.org/about/cclicenses/-// In code, for conciseness, we call all of them 'License'-/** @typedef {'cc0'|'pdm'|'by'|'by-sa'|'by-nc'|'by-nd'|'by-nc-nd'|'by-nc-sa'} License */--/** @typedef {'CC0'|'PDM'|'CC BY'|'CC BY-SA'|'CC BY-NC'|'CC BY-ND'|'CC BY-NC-ND'|'CC BY-NC-SA'} LicenseName */--// There are several versions of the licenses, and PDM has no version-// https://wiki.creativecommons.org/wiki/License_Versions-/** @typedef {'1.0'|'2.0'|'2.5'|'3.0'|'4.0'|''} LicenseVersion */--/**- * Capitalized full license name from license slug and version:- * ('by-sa', '4.0') -> 'CC BY-SA 4.0'- * @param {License} license- * @param {LicenseVersion} license_version- * @return {string}- */-export const getFullLicenseName = (license, license_version) => {- if (!license) {- return ''- }- const licenseUpper = license.toUpperCase()- return licenseUpper === 'CC0'- ? `${licenseUpper} ${license_version}`- : `CC ${licenseUpper} ${license_version}`-}--/**- * CC licenses have different legal status from the public domain marks- * such as CC0 and PDM, and need different wording.- * @param {License|LicenseName|''} licenseOrMark- * @return {asserts licenseOrMark is Exclude<'pdm' | 'cc0', License | LicenseName | ''>} false if licenseOrMark is CC0 or PDM, true otherwise- */-export const isLicense = (licenseOrMark = '') => {- return !['pdm', 'cc0'].includes(licenseOrMark.toLowerCase())-}--/**- * Returns true if argument is PDM or CC0- * @param {License|LicenseName|''} licenseOrMark- * @return {boolean}- */-export const isPublicDomain = (licenseOrMark = '') => {- return ['pdm', 'cc0'].includes(licenseOrMark.toLowerCase())-}diff --git a/src/utils/license.ts b/src/utils/license.tsnew file mode 100644index 000000000..1181767fc--- /dev/null+++ b/src/utils/license.ts@@ -0,0 +1,88 @@+import type { License, LicenseVersion } from '~/constants/license'+import {+ CC_LICENSES,+ DEPRECATED_CC_LICENSES,+ PUBLIC_DOMAIN_MARKS,+} from '~/constants/license'++import type { IVueI18n } from 'vue-i18n'++/**+ * Get the full name of the license in a displayable format from the license+ * slug and version.+ *+ * @param license - the slug of the license+ * @param licenseVersion - the version number of the license+ * @param i18n - the i18n instance to access translations+ * @returns the full name of the license+ */+export const getFullLicenseName = (+ license: License,+ licenseVersion: LicenseVersion = '', // unknown version+ i18n: IVueI18n | null = null+): string => {+ let licenseName++ // PDM has no abbreviation+ if (license === 'pdm' && i18n) {+ licenseName = i18n.t(`license-readable-names.${license}`).toString()+ } else {+ licenseName = license.toUpperCase().replace('SAMPLING', 'Sampling')+ }++ // If version is known, append version to the name+ if (licenseVersion) {+ licenseName = `${licenseName} ${licenseVersion}`+ }++ // For licenses other than public-domain marks, prepend 'CC' to the name+ if (!(PUBLIC_DOMAIN_MARKS as ReadonlyArray<License>).includes(license)) {+ licenseName = `CC ${licenseName}`+ }+ return licenseName.trim()+}++/**+ * CC licenses have different legal status from the public domain marks+ * such as CC0 and PDM, and need different wording. Check if the given name+ * belongs to a license and is not a public-domain mark.+ *+ * @param license - the license slug to check+ * @returns `false` if `license` is 'cc0' or 'pdm', `true` otherwise+ */+export const isLicense = (license: License): boolean =>+ !(PUBLIC_DOMAIN_MARKS as ReadonlyArray<License>).includes(license)++/**+ * CC licenses have different legal status from the public domain marks+ * such as CC0 and PDM, and need different wording. Check if the given name+ * belongs to a public-domain mark and is not a license.+ *+ * @param license - the license slug to check+ * @returns `true` if `license` is 'cc0' or 'pdm', `false` otherwise+ */+export const isPublicDomain = (license: License): boolean => !isLicense(license)++/**+ * Check if the given name belongs to a deprecated CC license. The full list of+ * deprecated licenses can be found on the+ * [Retired Legal Tools page](https://creativecommons.org/retiredlicenses/) on+ * the CC.org site.+ *+ * @param license - the license slug to check+ * @returns `true` if the license is a deprecated CC license, `false` otherwise+ */+export const isDeprecated = (license: License): boolean =>+ (DEPRECATED_CC_LICENSES as ReadonlyArray<License>).includes(license)++/**+ * Check if the given name belongs to a CC license, active or deprecated. This+ * includes CC0, which although not technically a license, is offered by CC.+ *+ * @param license - the license slug to check+ * @returns `true` if the license is a deprecated CC license, `false` otherwise+ */+export const isCc = (license: License): boolean =>+ license == 'cc0' ||+ (CC_LICENSES as ReadonlyArray<License>).includes(license) ||+ (DEPRECATED_CC_LICENSES as ReadonlyArray<License>).includes(license)diff --git a/test/unit/specs/store/filter-store.spec.js b/test/unit/specs/store/filter-store.spec.jsindex 0909f5b25..581445f96 100644--- a/test/unit/specs/store/filter-store.spec.js+++ b/test/unit/specs/store/filter-store.spec.js@@ -148,7 +148,7 @@ describe('Filter Store', () => {it.each`filterType | code | idx- ${'licenses'} | ${'cc0'} | ${0}+ ${'licenses'} | ${'cc0'} | ${1}${'licenseTypes'} | ${'modification'} | ${1}${'imageExtensions'} | ${'svg'} | ${3}${'imageCategories'} | ${'photograph'} | ${0}diff --git a/test/unit/specs/utils/license.spec.ts b/test/unit/specs/utils/license.spec.tsnew file mode 100644index 000000000..8a38c1ba1--- /dev/null+++ b/test/unit/specs/utils/license.spec.ts@@ -0,0 +1,41 @@+import Vuei18n from 'vue-i18n'++import { getFullLicenseName } from '~/utils/license'+import type { License, LicenseVersion } from '~/constants/license'+import enMessages from '~/locales/en.json'++const i18n = new Vuei18n({+ locale: 'en',+ fallbackLocale: 'en',+ messages: { en: enMessages },+})++describe('getFullLicenseName', () => {+ it.each`+ license | licenseVersion | sendI18n | fullName+ ${'by'} | ${''} | ${false} | ${'CC BY'}+ ${'by-nc-nd'} | ${'4.0'} | ${false} | ${'CC BY-NC-ND 4.0'}+ ${'cc0'} | ${''} | ${false} | ${'CC0'}+ ${'sampling+'} | ${''} | ${false} | ${'CC Sampling+'}+ ${'nc-sampling+'} | ${''} | ${false} | ${'CC NC-Sampling+'}+ ${'pdm'} | ${''} | ${false} | ${'PDM'}+ ${'pdm'} | ${''} | ${true} | ${'Public Domain Mark'}+ `(+ 'returns license name for license $license and version $licenseVersion',+ ({+ license,+ licenseVersion,+ sendI18n,+ fullName,+ }: {+ license: License+ licenseVersion: LicenseVersion+ sendI18n: boolean+ fullName: string+ }) => {+ expect(+ getFullLicenseName(license, licenseVersion, sendI18n ? i18n : null)+ ).toBe(fullName)+ }+ )+})