Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Vendor in case functions (#3233)

Olga Bulat1eb9f976d122
diff --git a/frontend/package.json b/frontend/package.json
index 13c76f0bb..e73dd86e6 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -71,7 +71,6 @@
"async-mutex": "^0.3.2",
"axios": "^0.27.0",
"axios-mock-adapter": "^1.20.0",
- "case": "^1.6.3",
"clipboard": "^2.0.11",
"cookie-universal-nuxt": "^2.1.5",
"core-js": "^3.27.2",
diff --git a/frontend/src/components/VLicense/VLicense.vue b/frontend/src/components/VLicense/VLicense.vue
index 6592536ec..c0883177b 100644
--- a/frontend/src/components/VLicense/VLicense.vue
+++ b/frontend/src/components/VLicense/VLicense.vue
@@ -17,11 +17,11 @@
</template>
<script lang="ts">
-import { camel } from "case"
import { computed, defineComponent, PropType } from "vue"
import type { License } from "~/constants/license"
import { getFullLicenseName, getElements } from "~/utils/license"
+import { camelCase } from "~/utils/case"
import { useI18n } from "~/composables/use-i18n"
import VIcon from "~/components/VIcon/VIcon.vue"
@@ -63,7 +63,7 @@ export default defineComponent({
const iconNames = computed(() => getElements(props.license))
const licenseName = computed(() => {
const licenseKey =
- props.license === "sampling+" ? props.license : camel(props.license)
+ props.license === "sampling+" ? props.license : camelCase(props.license)
return {
readable: i18n.t(`licenseReadableNames.${licenseKey}`).toString(),
full: getFullLicenseName(props.license, "", i18n),
diff --git a/frontend/src/components/VLicense/VLicenseElements.vue b/frontend/src/components/VLicense/VLicenseElements.vue
index 7edef234b..27864f9bc 100644
--- a/frontend/src/components/VLicense/VLicenseElements.vue
+++ b/frontend/src/components/VLicense/VLicenseElements.vue
@@ -22,11 +22,11 @@
<script lang="ts">
import { computed, defineComponent, PropType } from "vue"
-import { camel } from "case"
import type { License } from "~/constants/license"
import { useI18n } from "~/composables/use-i18n"
import { useUiStore } from "~/stores/ui"
+import { camelCase } from "~/utils/case"
import { getElements } from "~/utils/license"
import VIcon from "~/components/VIcon/VIcon.vue"
@@ -62,7 +62,7 @@ export default defineComponent({
const isMobile = computed(() => !uiStore.isDesktopLayout)
const getLicenseDescription = (element: string) => {
- return i18n.t(`browsePage.licenseDescription.${camel(element)}`)
+ return i18n.t(`browsePage.licenseDescription.${camelCase(element)}`)
}
return {
diff --git a/frontend/src/components/VSafetyWall/VSafetyWall.vue b/frontend/src/components/VSafetyWall/VSafetyWall.vue
index aa25271dc..df2419c59 100644
--- a/frontend/src/components/VSafetyWall/VSafetyWall.vue
+++ b/frontend/src/components/VSafetyWall/VSafetyWall.vue
@@ -12,7 +12,7 @@
</p>
<p v-for="reason in media.sensitivity" :key="reason">
{{
- $t(`sensitiveContent.reasons.${camel(reason)}`, {
+ $t(`sensitiveContent.reasons.${camelCase(reason)}`, {
openverse: "Openverse",
})
}}
@@ -57,10 +57,10 @@
<script lang="ts">
import { PropType, computed, defineComponent } from "@nuxtjs/composition-api"
-import { camel } from "case"
import { useSearchStore } from "~/stores/search"
import { useAnalytics } from "~/composables/use-analytics"
+import { camelCase } from "~/utils/case"
import type { AudioDetail, ImageDetail } from "~/types/media"
import VLink from "~/components/VLink.vue"
@@ -99,7 +99,7 @@ export default defineComponent({
backToSearchPath,
handleBack,
handleShow,
- camel,
+ camelCase,
}
},
})
diff --git a/frontend/src/components/meta/VButton.stories.mdx b/frontend/src/components/meta/VButton.stories.mdx
index 5a7f24870..b55126dc3 100644
--- a/frontend/src/components/meta/VButton.stories.mdx
+++ b/frontend/src/components/meta/VButton.stories.mdx
@@ -6,9 +6,9 @@ import {
Story,
} from "@storybook/addon-docs"
import { buttonForms, buttonSizes, buttonVariants } from "~/types/button"
+import { capitalCase } from "~/utils/case"
import VButton from "~/components/VButton.vue"
import VIcon from "~/components/VIcon/VIcon.vue"
-import { capital } from "case"
<Meta title="Components/VButton" components={VButton} />
@@ -101,7 +101,7 @@ export const VariantsTemplate = (args) => ({
components: { VButton },
methods: {
capitalize(str) {
- return capital(str)
+ return capitalCase(str)
},
},
setup() {
diff --git a/frontend/src/locales/scripts/utils.js b/frontend/src/locales/scripts/utils.js
index 737f1c28b..94bbafdd6 100644
--- a/frontend/src/locales/scripts/utils.js
+++ b/frontend/src/locales/scripts/utils.js
@@ -1,7 +1,18 @@
const { writeFile } = require("fs/promises")
const os = require("os")
-const { camel } = require("case")
+/**
+ * Convert a kebab-case string (`image-title`) to camel case (`imageTitle`).
+ */
+function kebabToCamel(input) {
+ const split = input.split("-")
+ if (split.length === 1) return input
+
+ for (let i = 1; i < split.length; i++) {
+ split[i] = split[i][0].toUpperCase() + split[i].slice(1)
+ }
+ return split.join("")
+}
/**
* Mutates an object at the path with the value. If the path
@@ -34,7 +45,7 @@ function replacer(_, match) {
if (match.includes("-")) {
console.warn("Found kebab-cased key in translation strings:", match)
}
- return `{${camel(match)}}`
+ return `{${kebabToCamel(match)}}`
}
/**
diff --git a/frontend/src/stores/provider.ts b/frontend/src/stores/provider.ts
index 1f50b66c3..520f25c52 100644
--- a/frontend/src/stores/provider.ts
+++ b/frontend/src/stores/provider.ts
@@ -1,7 +1,7 @@
-import { capital } from "case"
import { defineStore } from "pinia"
import { ssrRef } from "@nuxtjs/composition-api"
+import { capitalCase } from "~/utils/case"
import { env } from "~/utils/env"
import { parseFetchingError } from "~/utils/errors"
import {
@@ -102,7 +102,7 @@ export const useProviderStore = defineStore("provider", {
*/
getProviderName(providerCode: string, mediaType: SupportedMediaType) {
const provider = this._getProvider(providerCode, mediaType)
- return provider?.display_name || capital(providerCode)
+ return provider?.display_name || capitalCase(providerCode)
},
/**
diff --git a/frontend/src/utils/case.ts b/frontend/src/utils/case.ts
new file mode 100644
index 000000000..084202324
--- /dev/null
+++ b/frontend/src/utils/case.ts
@@ -0,0 +1,71 @@
+// Copied from https://github.com/blakeembrey/change-case
+// Case-related utility functions are vendored in because `case` package
+// cannot be used in Nuxt 3 which requires ESM compatibility.
+
+// Regexps involved with splitting words in various case formats.
+const SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu
+const SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu
+
+// Regexp involved with stripping non-word characters from the result.
+const DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu
+
+// The replacement value for splits.
+const SPLIT_REPLACE_VALUE = "$1\0$2"
+
+/**
+ * Split any cased input strings into an array of words.
+ */
+function split(input: string) {
+ let result = input.trim()
+
+ result = result
+ .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)
+ .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE)
+ .replace(DEFAULT_STRIP_REGEXP, "\0")
+
+ let start = 0
+ let end = result.length
+
+ // Trim the delimiter from around the output string.
+ while (result.charAt(start) === "\0") start++
+ if (start === end) return []
+ while (result.charAt(end - 1) === "\0") end--
+
+ return result.slice(start, end).split(/\0/g)
+}
+
+function pascalCaseTransformFactory() {
+ return (word: string, index: number) => {
+ const char0 = word[0]
+ const initial =
+ index > 0 && char0 >= "0" && char0 <= "9"
+ ? "_" + char0
+ : char0.toUpperCase()
+ return initial + word.slice(1).toLowerCase()
+ }
+}
+
+function capitalCaseTransformFactory() {
+ return (word: string) =>
+ `${word[0].toUpperCase()}${word.slice(1).toLowerCase()}`
+}
+
+/**
+ * Convert a string to camel case (`fooBar`).
+ */
+export function camelCase(input: string) {
+ const transform = pascalCaseTransformFactory()
+ return split(input)
+ .map((word, index) => {
+ if (index === 0) return word.toLowerCase()
+ return transform(word, index)
+ })
+ .join("")
+}
+
+/**
+ * Convert a string to capital case (`Foo Bar`).
+ */
+export function capitalCase(input: string) {
+ return split(input).map(capitalCaseTransformFactory()).join(" ")
+}
diff --git a/frontend/src/utils/decode-media-data.ts b/frontend/src/utils/decode-media-data.ts
index 55482d5fd..6dec35088 100644
--- a/frontend/src/utils/decode-media-data.ts
+++ b/frontend/src/utils/decode-media-data.ts
@@ -1,11 +1,10 @@
-import { title as titleCase } from "case"
-
import { decodeData as decodeString } from "~/utils/decode-data"
import type { ApiMedia, Media, Tag } from "~/types/media"
import { SENSITIVITY_RESPONSE_PARAM } from "~/constants/content-safety"
import type { MediaType } from "~/constants/media"
import { AUDIO, IMAGE, MODEL_3D, VIDEO } from "~/constants/media"
import { useFeatureFlagStore } from "~/stores/feature-flag"
+import { capitalCase } from "~/utils/case"
import { getFakeSensitivities } from "~/utils/content-safety"
const mediaTypeExtensions: Record<MediaType, string[]> = {
@@ -68,7 +67,7 @@ const mediaTitle = (
media: ApiMedia,
mediaType: MediaType
): { title: string; originalTitle: string } => {
- const originalTitle = decodeString(media.title) || titleCase(mediaType)
+ const originalTitle = decodeString(media.title) || capitalCase(mediaType)
return {
originalTitle,
title: stripExtension(originalTitle, mediaType, media),
diff --git a/frontend/src/utils/license.ts b/frontend/src/utils/license.ts
index b5e3b393b..0b64fe441 100644
--- a/frontend/src/utils/license.ts
+++ b/frontend/src/utils/license.ts
@@ -3,7 +3,6 @@
* For any changes made here, please make the corresponding changes in the
* backend, or open an issue to track it.
*/
-import { camel } from "case"
import type {
License,
@@ -15,6 +14,7 @@ import {
DEPRECATED_CC_LICENSES,
PUBLIC_DOMAIN_MARKS,
} from "~/constants/license"
+import { camelCase } from "~/utils/case"
import type VueI18n from "vue-i18n"
@@ -36,7 +36,9 @@ export const getFullLicenseName = (
// PDM has no abbreviation
if (license === "pdm" && i18n) {
- licenseName = i18n.t(`licenseReadableNames.${camel(license)}`).toString()
+ licenseName = i18n
+ .t(`licenseReadableNames.${camelCase(license)}`)
+ .toString()
} else {
licenseName = license.toUpperCase().replace("SAMPLING", "Sampling")
}
diff --git a/frontend/src/utils/metadata.ts b/frontend/src/utils/metadata.ts
index a67ff902e..70466eab1 100644
--- a/frontend/src/utils/metadata.ts
+++ b/frontend/src/utils/metadata.ts
@@ -1,5 +1,4 @@
-import { title } from "case"
-
+import { capitalCase } from "~/utils/case"
import type { AudioDetail, ImageDetail, Metadata } from "~/types/media"
import { AUDIO, IMAGE } from "~/constants/media"
@@ -95,7 +94,7 @@ export const getMediaMetadata = (
if (media.genres && media.genres.length > 0) {
metadata.push({
label: "audioDetails.table.genre",
- value: media.genres.map((genre) => title(genre)).join(", "),
+ value: media.genres.map((genre) => capitalCase(genre)).join(", "),
})
}
diff --git a/frontend/test/unit/specs/utils/case.spec.js b/frontend/test/unit/specs/utils/case.spec.js
new file mode 100644
index 000000000..7d2fd0d5f
--- /dev/null
+++ b/frontend/test/unit/specs/utils/case.spec.js
@@ -0,0 +1,29 @@
+import { camelCase, capitalCase } from "~/utils/case"
+
+describe("camelCase", () => {
+ it.each`
+ input | output
+ ${"media"} | ${"media"}
+ ${"mediaTitle"} | ${"mediaTitle"}
+ ${"Media Title"} | ${"mediaTitle"}
+ ${"media title"} | ${"mediaTitle"}
+ ${"media-title"} | ${"mediaTitle"}
+ ${"media_title"} | ${"mediaTitle"}
+ `("returns $output for $input", ({ input, output }) => {
+ expect(camelCase(input)).toBe(output)
+ })
+})
+
+describe("capitalCase", () => {
+ it.each`
+ input | output
+ ${"media"} | ${"Media"}
+ ${"mediaTitle"} | ${"Media Title"}
+ ${"Media Title"} | ${"Media Title"}
+ ${"media title"} | ${"Media Title"}
+ ${"media-title"} | ${"Media Title"}
+ ${"media_title"} | ${"Media Title"}
+ `("returns $output for $input", ({ input, output }) => {
+ expect(capitalCase(input)).toBe(output)
+ })
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 568f8f9b0..8d8caf35f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -80,7 +80,6 @@ importers:
babel-core: ^7.0.0-bridge.0
babel-jest: ^26.6.3
babel-loader: 8.2.5
- case: ^1.6.3
chokidar: ^3.5.3
clipboard: ^2.0.11
comment-json: ^4.2.3
@@ -142,7 +141,6 @@ importers:
async-mutex: 0.3.2
axios: 0.27.2
axios-mock-adapter: [email protected]
- case: 1.6.3
clipboard: 2.0.11
cookie-universal-nuxt: 2.1.5
core-js: 3.27.2
@@ -8675,11 +8673,6 @@ packages:
engines: {node: '>=4'}
dev: true
- /case/1.6.3:
- resolution: {integrity: sha512-mzDSXIPaFwVDvZAHqZ9VlbyF4yyXRuX6IvB06WvPYkqJVO24kX1PPhv9bfpKNFZyxYFmmgo03HUiD8iklmJYRQ==}
- engines: {node: '>= 0.8.0'}
- dev: false
-
/ccount/1.1.0:
resolution: {integrity: sha512-vlNK021QdI7PNeiUh/lKkC/mNHHfV0m/Ad5JoI0TYtlBnJAslM/JIkm/tGC88bkLIwO6OQ5uV6ztS6kVAtCDlg==}
dev: true