Search Urban Dictionary (urbandictionary.com)

Open urban-dictionary in Script Kit

// Name: Urban Dictionary
// Keyword: ud
import "@johnlindquist/kit"
import type { Choice } from "@johnlindquist/kit"
import { DateTime } from "luxon"
import { escapeHTML } from "../../.kit/core/utils"
await setInput("")
const debouncedOnInput = debounce(async (input) => {
if (!input) {
return
}
try {
const choices = await getResultsAsChoices(input)
await setChoices(choices)
} finally {
setHint("")
}
}, 500)
const link = await arg({
placeholder: "Search a word definition",
onInput: (input) => {
setHint("Searching...")
debouncedOnInput(input)
},
})
await clipboard.writeText(link)
notify({ title: "Urban Dictionary", message: "Definition URL copied to clipboard." })
await wait(200) // Somehow the notify function needs some time to complete...
type Definition = {
definition: string
permalink: string
thumbs_up: number
author: string
word: string
defid: number
current_vote: string
written_on: string
example: string
thumbs_down: number
}
async function getResultsAsChoices(query: string) {
const response = await get<{ list: Definition[] }>(
`https://api.urbandictionary.com/v0/define?term=${encodeURI(query)}`,
)
return response.data.list.map(
(e) =>
({
name: e.word,
description: e.definition.replaceAll(/[\[\]]/g, ""),
preview: formatMdDefinition(e),
value: e.permalink,
}) as Choice<string>,
)
}
function formatMdDefinition(def: Definition) {
const parts: string[] = []
parts.push(`# ${def.word}`)
parts.push(f(def.definition))
parts.push("<br><br>")
parts.push(`<i>${f(def.example)}</i>`)
parts.push("<br><br>")
const timestamp = DateTime.fromISO(def.written_on).toFormat("MMMM d, yyyy")
const author =
def.author && `by [${def.author}](https://www.urbandictionary.com/author.php?author=${encodeURI(def.author)})`
parts.push(`<b>${author ? `${author} ` : ""}${timestamp}</b>`)
parts.push("<br>")
parts.push(`👍 ${def.thumbs_up} | 👎 ${def.thumbs_down}`)
return md(parts.join("\n"))
}
function f(val: string) {
const result = val.replaceAll("\r\n", "\n")
return result.replaceAll(/\[(.*?)]/g, (substring: string, ...args: any[]) => {
const term = escapeHTML(args[0])
return `[${term}](https://www.urbandictionary.com/define.php?term=${encodeURI(term)})`
})
}