Skip to content

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

Convert more utils to TypeScript (#1052)

Dhruv Bhanushali5d8985acfc68
diff --git a/src/components/VAllResultsGrid/VAllResultsGrid.vue b/src/components/VAllResultsGrid/VAllResultsGrid.vue
index 240b27e44..852faa315 100644
--- a/src/components/VAllResultsGrid/VAllResultsGrid.vue
+++ b/src/components/VAllResultsGrid/VAllResultsGrid.vue
@@ -53,7 +53,7 @@
<script>
import { computed, defineComponent, useContext } from '@nuxtjs/composition-api'
-import srand from '~/utils/srand'
+import { rand as prng, hash } from '~/utils/prng'
import VImageCellSquare from '~/components/VAllResultsGrid/VImageCellSquare.vue'
import VAudioCell from '~/components/VAllResultsGrid/VAudioCell.vue'
@@ -98,7 +98,11 @@ export default defineComponent({
// Seed the random number generator with the ID of
// the first and last search result, so the non-image
// distribution is the same on repeated searches
- const rand = srand(Object.keys(media[mediaKeys[0]])[0])
+ let seed = Object.keys(media[mediaKeys[0]])[0]
+ if (typeof seed === 'string') {
+ seed = hash(seed)
+ }
+ const rand = prng(seed)
const randomIntegerInRange = (min, max) =>
Math.floor(rand() * (max - min + 1)) + min
/**
diff --git a/src/components/VFilters/VSearchGridFilter.vue b/src/components/VFilters/VSearchGridFilter.vue
index 920595988..a1957236f 100644
--- a/src/components/VFilters/VSearchGridFilter.vue
+++ b/src/components/VFilters/VSearchGridFilter.vue
@@ -44,8 +44,7 @@
<script>
import { computed, useContext, useRouter } from '@nuxtjs/composition-api'
-
-import { kebabize } from '~/utils/format-strings'
+import { kebab } from 'case'
import {
CLEAR_FILTERS,
@@ -76,7 +75,7 @@ export default {
if (filterType === 'searchBy') {
return ''
}
- return i18n.t(`filters.${kebabize(filterType)}.title`)
+ return i18n.t(`filters.${kebab(filterType)}.title`)
}
const updateSearch = async () => {
diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.pot
index e31560b0e..88b37cbea 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-04T04:33:42+00:00\n"
+"POT-Creation-Date: 2022-03-04T12:13:48+00:00\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
@@ -735,7 +735,7 @@ msgid "Load more results"
msgstr ""
#. Do not translate words between ### ###.
-#: src/components/VAllResultsGrid/VAllResultsGrid.vue:147
+#: src/components/VAllResultsGrid/VAllResultsGrid.vue:151
msgctxt "browse-page.fetching-error"
msgid "Error fetching ###type###:"
msgstr ""
@@ -816,7 +816,7 @@ msgctxt "browse-page.search-form.image"
msgid "images"
msgstr ""
-#: src/components/VAllResultsGrid/VAllResultsGrid.vue:146
+#: src/components/VAllResultsGrid/VAllResultsGrid.vue:150
msgctxt "browse-page.search-form.audio"
msgid "audio"
msgstr ""
diff --git a/src/utils/format-strings.js b/src/utils/format-strings.js
deleted file mode 100644
index 210ac1438..000000000
--- a/src/utils/format-strings.js
+++ /dev/null
@@ -1,11 +0,0 @@
-export const capitalize = (str) => str[0].toUpperCase() + str.slice(1)
-export const kebabize = (str) => {
- return str
- .split('')
- .map((letter, idx) => {
- return letter.toUpperCase() === letter
- ? `${idx !== 0 ? '-' : ''}${letter.toLowerCase()}`
- : letter
- })
- .join('')
-}
diff --git a/src/utils/local.js b/src/utils/local.ts
similarity index 51%
rename from src/utils/local.js
rename to src/utils/local.ts
index a7725e31d..3dcec2488 100644
--- a/src/utils/local.js
+++ b/src/utils/local.ts
@@ -1,28 +1,24 @@
-// Small wrapper for localstorage to protect against SSR and permissions
+/*
+ * Small wrapper for localstorage to protect against SSR and permissions
+ */
+
import { warn } from '~/utils/console'
const localStorageExists = () => process.client && window.localStorage !== null
const local = {
- /**
- * @param {Parameters<typeof localStorage['getItem']>} args
- */
- get(...args) {
+ get(key: string) {
try {
- return localStorageExists() ? localStorage.getItem(...args) : null
+ return localStorageExists() ? localStorage.getItem(key) : null
} catch (e) {
// Probably a `SecurityError`
warn('`localStorage` access denied', e)
return null
}
},
- /**
- * @param {Parameters<typeof localStorage['setItem']>} args
- * @return {void}
- */
- set(...args) {
+ set(key: string, value: string) {
try {
- if (localStorageExists()) localStorage.setItem(...args)
+ if (localStorageExists()) localStorage.setItem(key, value)
} catch (e) {
// Probably a `SecurityError`
warn('`localStorage` access denied', e)
diff --git a/src/utils/math.js b/src/utils/math.js
deleted file mode 100644
index f09e0cb2b..000000000
--- a/src/utils/math.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Math utilities
- */
-
-/**
- * Perform linear interpolation to find a value that is fractionally between
- * the low and high limits of the given range.
- *
- * @param {number} low - the lower limit of the range
- * @param {number} high - the upper limit of the range
- * @param {number} frac - fraction controlling position of interpolated number
- * @returns {number} the interpolated number
- */
-export const lerp = (low, high, frac) => low + (high - low) * frac
-
-/**
- * Interpolate twice to solve the Bézier equation for three points P0, P1
- * and P2.
- *
- * @param {[number, number]} p0 - point #0
- * @param {[number, number]} p1 - point #1
- * @param {[number, number]} p2 - point #2
- * @param {number} frac - the fraction at which to solve the Bézier equation
- * @returns {[number,number]} a solution to the 3-point Bézier equation
- */
-export const doubleLerp = (p0, p1, p2, frac) => [
- lerp(lerp(p0[0], p1[0], frac), lerp(p1[0], p2[0], frac), frac),
- lerp(lerp(p0[1], p1[1], frac), lerp(p1[1], p2[1], frac), frac),
-]
-
-/**
- * Find the distance between two points P0 and P1.
- *
- * @param {[number, number]} p0 - point #0
- * @param {[number, number]} p1 - point #1
- * @returns {number} the distance between the two points
- */
-export const dist = (p0, p1) =>
- Math.sqrt(Math.pow(p0[0] - p1[0], 2) + Math.pow(p0[1] - p1[1], 2))
-
-/**
- * Get the required number of x-coordinates of Bézier points using 4 control
- * points.
- *
- * @param {[number, number][]} ctrlPts - the array of control points
- * @param {number} pointCount - the number of Bézier points to calculate
- * @return {[number]} the list of x-coordinates of Bézier points
- */
-export const bezier = (ctrlPts, pointCount) => {
- const bezierPoints = []
- for (let i = 0; i <= pointCount; i++) {
- const frac = i / pointCount
- const a = doubleLerp(ctrlPts[0], ctrlPts[1], ctrlPts[2], frac)
- const b = doubleLerp(ctrlPts[1], ctrlPts[2], ctrlPts[3], frac)
- const x = lerp(a[0], b[0], frac)
- bezierPoints.push(x)
- }
- return bezierPoints
-}
diff --git a/src/utils/math.ts b/src/utils/math.ts
new file mode 100644
index 000000000..2e9f0580e
--- /dev/null
+++ b/src/utils/math.ts
@@ -0,0 +1,67 @@
+/**
+ * Math utilities
+ */
+
+type Point = [number, number]
+
+/**
+ * Perform linear interpolation to find a value that is fractionally between
+ * the low and high limits of the given range.
+ *
+ * @param low - the lower limit of the range
+ * @param high - the upper limit of the range
+ * @param frac - fraction controlling position of interpolated number
+ * @returns the interpolated number
+ */
+export const lerp = (low: number, high: number, frac: number): number =>
+ low + (high - low) * frac
+
+/**
+ * Interpolate twice to solve the Bézier equation for three points P0, P1
+ * and P2.
+ *
+ * @param p0 - point #0
+ * @param p1 - point #1
+ * @param p2 - point #2
+ * @param frac - the fraction at which to solve the Bézier equation
+ * @returns a solution to the 3-point Bézier equation
+ */
+export const doubleLerp = (
+ p0: Point,
+ p1: Point,
+ p2: Point,
+ frac: number
+): Point => [
+ lerp(lerp(p0[0], p1[0], frac), lerp(p1[0], p2[0], frac), frac),
+ lerp(lerp(p0[1], p1[1], frac), lerp(p1[1], p2[1], frac), frac),
+]
+
+/**
+ * Find the distance between two points P0 and P1.
+ *
+ * @param p0 - point #0
+ * @param p1 - point #1
+ * @returns the distance between the two points
+ */
+export const dist = (p0: Point, p1: Point): number =>
+ Math.sqrt(Math.pow(p0[0] - p1[0], 2) + Math.pow(p0[1] - p1[1], 2))
+
+/**
+ * Get the required number of x-coordinates of Bézier points using 4 control
+ * points.
+ *
+ * @param ctrlPts - the array of control points
+ * @param pointCount - the number of Bézier points to calculate
+ * @returns the list of x-coordinates of Bézier points
+ */
+export const bezier = (ctrlPts: Point[], pointCount: number): number[] => {
+ const bezierPoints = []
+ for (let i = 0; i <= pointCount; i++) {
+ const frac = i / pointCount
+ const a = doubleLerp(ctrlPts[0], ctrlPts[1], ctrlPts[2], frac)
+ const b = doubleLerp(ctrlPts[1], ctrlPts[2], ctrlPts[3], frac)
+ const x = lerp(a[0], b[0], frac)
+ bezierPoints.push(x)
+ }
+ return bezierPoints
+}
diff --git a/src/utils/prng.js b/src/utils/prng.ts
similarity index 59%
rename from src/utils/prng.js
rename to src/utils/prng.ts
index b3bc9c036..b3d6a72eb 100644
--- a/src/utils/prng.js
+++ b/src/utils/prng.ts
@@ -7,18 +7,18 @@
* numbers as seeds.
* @see {@link https://github.com/bryc/code/blob/master/jshash/PRNGs.md#sfc32}
*
- * @param {number} a - first seed for SFC32
- * @param {number} b - second seed for SFC32
- * @param {number} c - third seed for SFC32
- * @param {number} d - fourth seed for SFC32
- * @return {() => number} the seeded PRNG
+ * @param a - first seed for SFC32
+ * @param b - second seed for SFC32
+ * @param c - third seed for SFC32
+ * @param d - fourth seed for SFC32
+ * @returns the seeded PRNG
*/
-const sfc32 = (a, b, c, d) => () => {
+const sfc32 = (a: number, b: number, c: number, d: number) => (): number => {
a |= 0
b |= 0
c |= 0
d |= 0
- let t = (((a + b) | 0) + d) | 0
+ const t = (((a + b) | 0) + d) | 0
d = (d + 1) | 0
a = b ^ (b >>> 9)
b = (c + (c << 3)) | 0
@@ -31,25 +31,25 @@ const sfc32 = (a, b, c, d) => () => {
* Get a seedable pseudo-random number generator based on SFC32 that accepts 1
* number as the seed. It uses three other arbitrary seeds.
*
- * @param {number} d - fourth seed for SFC32
- * @returns {() => number} the seeded PRNG
+ * @param d - fourth seed for SFC32
+ * @returns the seeded PRNG
*/
-export const rand = (d) => sfc32(0x9e3779b9, 0x243f6a88, 0xb7e15162, d)
+export const rand = (d: number) => sfc32(0x9e3779b9, 0x243f6a88, 0xb7e15162, d)
/**
* Hash a string into a 32-bit number that can be used as the seed for a
* pseudo-random number generator.
*
- * @param {string} str - the string to hash
- * @return {number} the number generated from hashing the string
+ * @param str - the string to hash
+ * @returns the number generated from hashing the string
*/
-export const hash = (str) => {
+export const hash = (str: string): number => {
let hash = 0
if (str.length === 0) {
return hash
}
for (let i = 0; i < str.length; i++) {
- let chr = str.charCodeAt(i)
+ const chr = str.charCodeAt(i)
hash = (hash << 5) - hash + chr
hash |= 0 // Convert to 32-bit integer
}
diff --git a/src/utils/send-message.js b/src/utils/send-message.js
deleted file mode 100644
index 1354ec130..000000000
--- a/src/utils/send-message.js
+++ /dev/null
@@ -1,18 +0,0 @@
-import { isProd } from '~/utils/node-env'
-
-// TODO: set correct targetOrigin of the parent window
-const TARGET_ORIGIN = '*'
-
-/**
- * Send message to the outer window. Can only be called on client-side
- * because it uses `window` object.
- * @param {Object} message
- * @param {boolean} [message.debug] - whether more verbose debug output should be used
- * @param {'resize'|'changeUrl'} message.type - event that triggers the message
- * @param {any} message.value - the value of event
- */
-export const sendWindowMessage = ({ debug = !isProd, ...message }) => {
- if (window.parent !== window) {
- window.parent.postMessage({ debug, ...message }, TARGET_ORIGIN)
- }
-}
diff --git a/src/utils/send-message.ts b/src/utils/send-message.ts
new file mode 100644
index 000000000..41d9b18c6
--- /dev/null
+++ b/src/utils/send-message.ts
@@ -0,0 +1,33 @@
+import { isProd } from '~/utils/node-env'
+
+// TODO: set correct targetOrigin of the parent window
+const TARGET_ORIGIN = '*'
+
+interface Message<T extends ResizeValue | UrlChangeValue> {
+ type: 'resize' | 'urlChange'
+ value: T
+}
+
+interface ResizeValue {
+ height: number
+}
+
+interface UrlChangeValue {
+ path: string
+ title: string
+}
+
+/**
+ * Send message to the outer window. Can only be called on client-side
+ * because it uses `window` object.
+ * @param debug - whether to log the messages from the parent
+ * @param message - the message to emit to the parent window
+ */
+export const sendWindowMessage = <T extends UrlChangeValue | ResizeValue>({
+ debug = !isProd,
+ ...message
+}: { debug?: boolean } & Message<T>) => {
+ if (window.parent !== window) {
+ window.parent.postMessage({ debug, ...message }, TARGET_ORIGIN)
+ }
+}
diff --git a/src/utils/srand.js b/src/utils/srand.js
deleted file mode 100644
index 8606eb948..000000000
--- a/src/utils/srand.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Seeded random number generator.
- * Taken from https://github.com/micro-js/srand/blob/master/lib/index.js
- */
-
-module.exports = srand
-
-/**
- * srand
- */
-function srand(seed) {
- let str
- // If we're passed a string, condense it down
- // into a number
- if (typeof seed === 'string') {
- str = seed
- seed = 0xff
- for (var i = 0; i < str.length; i++) {
- seed ^= str.charCodeAt(i)
- }
- }
-
- return function (max, min) {
- max = max || 1
- min = min || 0
- seed = (seed * 9301 + 49297) % 233280
-
- return min + (seed / 233280) * (max - min)
- }
-}
diff --git a/tsconfig.json b/tsconfig.json
index f701a25b8..e153c3331 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -50,8 +50,7 @@
"src/stores/nav.js",
"src/utils/decode-media-data.js",
"src/utils/deep-freeze.js",
- "src/utils/key-codes.js",
- "src/utils/local.js"
+ "src/utils/key-codes.js"
],
"exclude": ["node_modules"]
}