Initial commit

This commit is contained in:
2023-04-30 19:10:59 +02:00
commit 9ce11fe589
22 changed files with 562 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
import { reactive } from 'vue'
const DEFAULT_BASE = 'https://official-joke-api.appspot.com'
const DEFAULT_URL = `${DEFAULT_BASE}/jokes/programming/random`
const DEFAULT_CHAR_DELAY = 20
const DEFAULT_PUNCHLINE_DELAY = 2000
export class Joke {
error : string | null = null
setup : string | null = null
punchline : string = ""
reset() {
this.error = null
this.setup = null
this.punchline = ""
}
}
export function useJokeAPI(
url: string = DEFAULT_URL,
charDelay: int = DEFAULT_CHAR_DELAY,
punchlineDelay: int = DEFAULT_PUNCHLINE_DELAY
) {
let joke = reactive(new Joke())
let working = false
async function loadJoke(): bool {
if (working) return false
working = true
// Load joke
joke.reset()
try {
let res = await fetch(url)
var [{ setup, punchline }] = await res.json()
} catch (e) {
console.error(e)
}
// Animate joke appearance
if (setup && punchline) {
for (let i = 0; i <= setup.length; i++) {
joke.setup = setup.substr(0, i)
await sleep(charDelay)
}
await sleep(punchlineDelay)
for (let i = 0; i <= punchline.length; i++) {
joke.punchline = punchline.substr(0, i)
await sleep(charDelay)
}
} else {
joke.error = "Loading joke failed"
}
working = false
}
return { joke, loadJoke }
}
async function sleep(ms: number) {
await new Promise((res, rej) => setTimeout(res, ms))
}