file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
src/App.vue | Vue | <script setup lang="ts">
import { onBeforeMount, onMounted } from "vue"
import { supabase } from "./plugins/supabase"
import { store } from "@/store"
onBeforeMount(() => {
let session = supabase.auth.session()
if (session) store.user = session?.user
})
supabase.auth.onAuthStateChange((event, session) => {
console.log({ event, session })
if (event == "SIGNED_IN") {
store.user = session?.user
} else if (event == "SIGNED_OUT") {
store.user = null
}
})
</script>
<template>
<div class="bg-dark-500 flex h-full h-screen min-h-screen justify-center p-3 md:p-6 overflow-y-auto">
<div class="max-w-screen-xl w-full h-full flex flex-col relative">
<div>
<router-link class="flex w-max !font-bold text-3xl md:text-5xl link" to="/">
<h1>SupaDB</h1>
</router-link>
</div>
<div class="flex">
<aside class="p-3 h-min text-2xl flex -top-2 right-22 md:flex-col md:space-y-4 w-20 absolute md:sticky">
<router-link
to="/"
class="hidden md:flex items-center justify-center p-3 bg-transparent hover:bg-dark-200 rounded-xl transition"
:class="{ 'bg-dark-200': $route.name == 'index' }"
>
<i-heroicons-outline:home></i-heroicons-outline:home>
</router-link>
<router-link
:to="store.user ? '/settings' : '/login'"
class="flex items-center justify-center p-3 bg-transparent hover:bg-dark-200 rounded-xl transition"
:class="{ 'bg-dark-200': $route.name == 'settings' || $route.name == 'login' }"
>
<i-heroicons-outline:user-circle></i-heroicons-outline:user-circle>
</router-link>
<div class="px-4 hidden md:block">
<div class="h-1 rounded-full bg-gray-100 w-full"></div>
</div>
<router-link
to="/imdb"
class="flex items-center justify-center p-3 bg-transparent hover:bg-dark-200 rounded-xl transition"
:class="{ 'bg-dark-200': $route.name == 'imdb' }"
>
<i-simple-icons:imdb></i-simple-icons:imdb>
</router-link>
<router-link
to="/steam"
class="flex items-center justify-center p-3 bg-transparent hover:bg-dark-200 rounded-xl transition"
:class="{ 'bg-dark-200': $route.name == 'steam' }"
>
<i-simple-icons:steam></i-simple-icons:steam>
</router-link>
</aside>
<div class="p-3 w-full md:w-[calc(100%-5rem)]">
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</div>
</div>
<div class="flex flex-col md:flex-row md:items-center mt-auto pt-12 pb-3">
<router-link class="small-link" to="/terms-and-conditions"> Terms & Conditions </router-link>
<span class="hidden md:block">|</span>
<p class="flex items-center w-max px-4 font-semibold">
Coded with 💛 by <a class="small-link" target="_blank" href="https://twitter.com/zernonia">Zernonia</a>
</p>
<span class="hidden md:block">|</span>
<a class="small-link" target="_blank" href="https://github.com/zernonia/supadb">⭐️ GitHub</a>
</div>
</div>
</div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/assets/main.css | CSS | html {
font-family: "Inter", sans-serif;
@apply text-light-900;
}
pre {
@apply p-6 rounded-2xl md:text-lg !bg-dark-300 overflow-y-auto;
}
pre span {
font-family: "Roboto Mono", monospace;
}
label {
@apply font-font-font-medium text-lg;
}
input {
@apply px-6 py-3 rounded-xl mt-1 mb-3 disabled:bg-dark-300 disabled:text-light-900 disabled:text-opacity-75;
}
strong {
@apply text-yellow-300;
}
.link {
@apply flex w-max px-6 py-3 font-semibold bg-transparent hover:bg-dark-300 transition rounded-2xl;
}
.small-link {
@apply flex w-max mx-1 px-3 py-1 font-semibold bg-transparent hover:bg-dark-300 transition rounded-lg;
}
.fade-enter-active,
.fade-leave-active {
transition: all 0.2s ease-in-out;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/components/BasePage.vue | Vue | <script setup lang="ts">
import CodeInit from "@/components/CodeInit.vue"
import { ref } from "vue"
import CodeGraphql from "./CodeGraphql.vue"
import LazyImage from "./LazyImage.vue"
const props = defineProps({
dictionary: Object,
banner: String,
title: String,
})
const isLoading = ref(true)
</script>
<template>
<div class="md:pr-6">
<LazyImage
class="min-h-48 md:h-76 object-cover w-full rounded-2xl md:rounded-3xl lg:rounded-4xl"
alt="Steam banner"
:src="banner"
></LazyImage>
<p class="mt-4 text-xl md:text-2xl font-medium">
<slot name="description"></slot>
</p>
<section class="mt-6">
<CodeInit :title="title"></CodeInit>
<div class="flex flex-col md:flex-row items-center justify-center">
<div
class="md:w-1/2 items-center justify-center h-full text-2xl md:text-4xl md:text-center md:leading-12 font-semibold opacity-50"
>
Or...
<br class="hidden md:block" />
with Graphql
</div>
<CodeGraphql class="md:min-w-96 w-full md:w-1/2 md:ml-6" :title="title"></CodeGraphql>
</div>
<div class="mt-6">
<h4 class="text-yellow-300 text-2xl md:text-3xl font-semibold">Dictionary</h4>
<div class="mt-3">
<div class="px-6 py-3 flex w-full opacity-50">
<div class="w-1/3 flex-shrink-0">name</div>
<div class="w-1/5 flex-shrink-0 mx-3">type</div>
<div class="w-full">value</div>
</div>
<ul class="p-3 rounded-2xl bg-dark-300">
<li
class="px-3 py-2 flex bg-transparent hover:bg-dark-100 transition rounded-xl"
v-for="item in dictionary"
>
<div class="w-1/3 flex-shrink-0">{{ item.name }}</div>
<div class="w-1/5 flex-shrink-0 mx-3">{{ item.type }}</div>
<div class="w-full truncate">{{ item.value }}</div>
</li>
</ul>
</div>
</div>
</section>
</div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/components/CodeGraphql.vue | Vue | <script setup lang="ts">
import { ref } from "vue"
import { highlighter } from "@/plugins/shiki"
const props = defineProps({
title: String,
})
let code = ref(`query ${props.title}Query {
${props.title}Collection {
edges {
node {
id
title
link
image
...
}
}
}
}`)
code.value = highlighter.codeToHtml(code.value, "graphql")
</script>
<template>
<div v-html="code"></div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/components/CodeInit.vue | Vue | <script setup lang="ts">
import { ref, watch } from "vue"
import { highlighter } from "@/plugins/shiki"
const props = defineProps({
title: String,
})
const code = ref("")
code.value = highlighter.codeToHtml(code.value, "ts")
const tab = ref("supabase_client")
const tabs = [
{ name: "Supabase Client", value: "supabase_client" },
{ name: "Fetch", value: "fetch" },
]
watch(
tab,
(n) => {
if (n == "supabase_client") {
code.value = highlighter.codeToHtml(
`const supabase = createClient(...) // Login to get receive credential
const { data, error } = await supabase.from("${props.title}").select("*")
`,
"ts"
)
} else if (n == "fetch") {
code.value = highlighter.codeToHtml(
`fetch('${import.meta.env.VITE_SUPABASE_URL}/rest/v1/${props.title}?select=*', {
headers: {
apikey: ..., // Login to get receive credential
Authorization: 'Bearer ...'
}
})`,
"ts"
)
}
},
{ immediate: true }
)
</script>
<template>
<div>
<Tabs v-model="tab" :tabs="tabs"></Tabs>
<div v-html="code"></div>
</div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/components/LazyImage.vue | Vue | <script setup lang="ts">
import { ref } from "vue"
const props = defineProps({
src: String,
})
const isLoading = ref(true)
const image = new URL(`../assets/images/${props.src}`, import.meta.url).href
const imageBlur = new URL(`../assets/images/${props.src?.replace(/(\.[\w\d_-]+)$/i, "_blur$1")}`, import.meta.url).href
const imageLoaded = () => {
isLoading.value = false
}
</script>
<template>
<img
v-bind="$attrs"
decoding="async"
:src="isLoading ? imageBlur : image"
@load="imageLoaded"
:class="[isLoading ? 'grayscale blur-xl' : 'grayscale-0 blur-0']"
class="duration-300 ease-in-out filter"
/>
<img :src="image" class="hidden" v-if="isLoading" />
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/components/Tabs.vue | Vue | <script setup lang="ts">
import { PropType } from "vue"
interface Tab {
name: string
value: string
}
const props = defineProps({
modelValue: String,
tabs: Object as PropType<Tab[]>,
})
const emit = defineEmits<{
(e: "update:modelValue", value: string): void
}>()
</script>
<template>
<div class="flex">
<button
v-for="tab in tabs"
@click="emit('update:modelValue', tab.value)"
class="link border-b-3 border-transparent !rounded-b-none text-true-gray-400"
:class="{ 'border-yellow-300 !text-light-900 ': modelValue == tab.value }"
>
{{ tab.name }}
</button>
</div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/env.d.ts | TypeScript | /// <reference types="vite/client" />
/// <reference types="vite-plugin-pages/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue"
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>
export default component
}
interface ImportMetaEnv {
readonly VITE_SUPABASE_URL: string
readonly VITE_SUPABASE_ANON: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/main.ts | TypeScript | import { createApp } from "vue"
import App from "./App.vue"
import "virtual:windi.css"
import "./assets/main.css"
import { initHighlighter } from "./plugins/shiki"
import { router } from "./plugins/router"
initHighlighter().then(() => {
createApp(App).use(router).mount("#app")
})
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/pages/imdb.vue | Vue | <script setup lang="ts">
const dictionary = [
{ name: "id", type: "string", value: "tt0050051" },
{
name: "image",
type: "string",
value: "https://m.media-amazon.com/images/M/MV5BZjEzYmZk...",
},
{ name: "link", type: "string", value: "https://www.imdb.com/title/tt0050051/?ref_=adv_li_i" },
{ name: "title", type: "string", value: "Perry Mason" },
{ name: "year", type: "string", value: "1957–1966" },
{ name: "certificate", type: "string", value: "TV-PG" },
{ name: "duration", type: "number", value: 60 },
{ name: "genre", type: "string[]", value: ["Crime", "Drama", "Mystery"] },
{ name: "rating", type: "number", value: 8.4 },
{ name: "metascore", type: "number", value: 20 },
{
name: "description",
type: "string",
value: "The cases of a master criminal defens...",
},
{ name: "vote", type: "number", value: "8645" },
]
</script>
<template>
<BasePage :dictionary="dictionary" title="imdb" banner="imdb_banner.jpeg">
<template #description>
IMDb is so popular for begineer tutorial, how can I not turn it into <strong>Supabase Database</strong>?
</template>
</BasePage>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/pages/index.vue | Vue | <script setup lang="ts">
import imgImdb from "@/assets/images/imdb.jpeg"
import imgSteam from "@/assets/images/steam.jpeg"
</script>
<template>
<div>
<div class="flex flex-col items-center">
<h1 class="mt-16 md:mt-32 text-4xl md:text-6xl xl:text-7xl font-bold text-center leading-tight">
Pre-Built <strong>Supabase DB</strong><br />
for you to connect
</h1>
<p class="mt-4 text-center text-lg md:text-2xl opacity-50">
Connect and play with Supabase REST API / Graphql easily
</p>
<div class="mt-16 lg:mt-32 grid lg:grid-cols-2 gap-8 lg:px-24">
<div class="max-w-108 max-h-108 overflow-hidden rounded-3xl">
<router-link to="/imdb">
<img class="w-full h-full transform hover:scale-110 transition" :src="imgImdb" alt="" />
</router-link>
</div>
<div class="max-w-108 max-h-108 overflow-hidden rounded-3xl">
<router-link to="/steam">
<img class="w-full h-full transform hover:scale-110 transition" :src="imgSteam" alt="" />
</router-link>
</div>
</div>
</div>
</div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/pages/login.vue | Vue | <script setup lang="ts">
import { supabase } from "@/plugins/supabase"
const login = () => {
supabase.auth.signIn({
provider: "github",
})
}
</script>
<template>
<div class="mt-12 flex flex-col items-center">
<h2 class="text-yellow-300 text-4xl text-center font-semibold">
Login with <br class="block md:hidden" />
GitHub
</h2>
<button
class="mt-6 flex items-center text-lg text-dark-700 bg-light-900 transition hover:bg-light-400 font-semibold px-6 py-3 rounded-xl"
@click="login"
>
Login <i-simple-icons:github class="ml-2"></i-simple-icons:github>
</button>
<p class="px-6 my-20 text-sm opacity-50 text-center">
By login, you agree to the
<router-link class="underline underline-offset-2" to="/terms-and-conditions">terms & conditions</router-link>
</p>
</div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/pages/settings.vue | Vue | <script setup lang="ts">
import { store } from "@/store"
import { computed, ref, watch } from "vue"
import { useClipboard } from "@vueuse/core"
import { highlighter } from "@/plugins/shiki"
const config = ref({
url: import.meta.env.VITE_SUPABASE_URL,
anon: import.meta.env.VITE_SUPABASE_ANON,
auth: "",
})
const getAnonKey = () => {
fetch("./api/user/generate", {
method: "POST",
body: JSON.stringify({
id: store.user?.id,
}),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((res) => (config.value.auth = res.key))
}
getAnonKey()
const code = ref("")
const tab = ref("supabase_client")
const tabs = [
{ name: "Supabase Client", value: "supabase_client" },
{ name: "Fetch", value: "fetch" },
]
const applyShiki = () => {
if (tab.value == "supabase_client") {
code.value = highlighter.codeToHtml(
`const supabase = createClient("${config.value.url}",
"${config.value.anon}", {
headers: {
Authorization: "Bearer ${config.value.auth}"
}
})`,
"ts"
)
} else if (tab.value == "fetch") {
code.value = highlighter.codeToHtml(
`fetch("${config.value.url}/rest/v1/<table>?select=*", {
headers: {
apikey: "${config.value.anon}"
Authorization: "Bearer ${config.value.auth}"
}
})`,
"ts"
)
}
}
watch([tab, config], () => applyShiki(), { immediate: true, deep: true })
const { copy, copied } = useClipboard({ source: code.value })
</script>
<template>
<div>
<h2 class="text-yellow-300 text-2xl md:text-4xl font-semibold">Settings</h2>
<div class="mt-6 flex flex-col">
<label for="url">Supabase URL</label>
<input id="url" type="text" disabled :value="config.url" />
<label for="url">Supabase Anon Key</label>
<input type="text" disabled :value="config.anon" />
<label for="url">Authorization Key</label>
<input type="text" disabled :value="config.auth" />
</div>
<h2 class="text-yellow-300 mt-12 text-2xl md:text-4xl font-semibold">Initiate Supabase Client</h2>
<div class="flex items-center justify-between">
<p class="md:text-lg">Simply copy and paste the snippet below to initiate Supabase Client</p>
<button
@click="copy()"
class="w-10 h-10 flex-shrink-0 p-2 rounded-xl bg-transparent hover:bg-dark-300 transition"
>
<i-heroicons-outline:clipboard-copy class="inline h-full w-full"></i-heroicons-outline:clipboard-copy>
</button>
</div>
<Tabs v-model="tab" :tabs="tabs"></Tabs>
<div class="truncate" v-html="code" :class="{ 'animate-head-shake': copied }"></div>
</div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/pages/steam.vue | Vue | <script setup lang="ts">
const dictionary = [
{ name: "id", type: "number", value: "915810" },
{
name: "link",
type: "string",
value: "https://store.steampowered.com/app/915810/Midnight_Ghost_Hunt/?snr=1_241_4_action_103",
},
{
name: "image",
type: "string",
value: "https://cdn.akamai.steamstatic.com/steam/apps/915810/capsule_184x69.jpg?t=1649315580",
},
{ name: "title", type: "string", value: "Midnight Ghost Hunt" },
{ name: "price", type: "number", value: 19.99 },
{ name: "tags", type: "string[]", value: ["Early Access", "Combat", "Multiplayer", "Team-Based"] },
{ name: "platforms", type: "string[]", value: ["Windows"] },
{ name: "genre", type: "string", value: "action" },
]
</script>
<template>
<BasePage :dictionary="dictionary" title="steam" banner="steam_banner.jpeg">
<template #description>
STEAM is included into <strong>Supabase Database</strong> because I can't find any STEAM marketplace API.
</template>
</BasePage>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/pages/terms-and-conditions.vue | Vue | <template>
<div>
<h2 class="text-yellow-300 text-2xl md:text-4xl font-semibold">Terms and Conditions</h2>
<ul class="my-6 list-disc list-inside">
<li>You may not offer to sell service from SupaDB.</li>
<li>You may not use SupaDB for commercial gain.</li>
<li>You may not purposely jam the traffic by invoking unneccesary request.</li>
</ul>
<p>Admin has the right to revoke your token without prior notice if any of the terms and conditions was broken.</p>
</div>
</template>
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/plugins/router.ts | TypeScript | import { store } from "@/store"
import { createRouter, createWebHistory } from "vue-router"
import routes from "~pages"
export const router = createRouter({
history: createWebHistory(),
routes,
})
router.beforeEach((to, from) => {
const toName = to.name?.toString() ?? ""
if (!store.user && toName.includes("settings")) {
return { name: "login" }
}
})
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/plugins/shiki.ts | TypeScript | import { setCDN, setOnigasmWASM, Highlighter, getHighlighter } from "shiki"
setOnigasmWASM(import.meta.env.DEV ? "" : "/shiki/dist/onigasm.wasm")
setCDN(import.meta.env.DEV ? "node_modules/shiki/" : "/shiki/")
export let highlighter: Highlighter
export async function initHighlighter() {
highlighter = await getHighlighter({
themes: ["dark-plus"],
langs: ["ts", "graphql"],
})
}
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/plugins/supabase.ts | TypeScript | import { createClient } from "@supabase/supabase-js"
export const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON)
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
src/store.ts | TypeScript | import { User } from "@supabase/gotrue-js"
import { computed, reactive } from "vue"
export const store = reactive({
user: null as User | null | undefined,
})
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
vite.config.ts | TypeScript | import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
import WindiCSS from "vite-plugin-windicss"
import Icons from "unplugin-icons/vite"
import IconsResolver from "unplugin-icons/resolver"
import Components from "unplugin-vue-components/vite"
import Pages from "vite-plugin-pages"
import { resolve } from "path"
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: {
"@": resolve(__dirname, "./src"),
},
},
plugins: [
vue(),
WindiCSS(),
Components({
resolvers: [IconsResolver()],
}),
Icons(),
Pages(),
],
})
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
windi.config.ts | TypeScript | import { defineConfig } from "windicss/helpers"
export default defineConfig({
theme: {
extend: {},
},
plugins: [require("@windicss/plugin-animations")({})],
})
| zernonia/supadb | 47 | Connect and play with Supabase REST API / Graphql easily | Vue | zernonia | zernonia | Troop Travel |
app.vue | Vue | <script setup lang="ts">
//@ts-ignore
import Logo from "~~/assets/logo.svg";
useHead({
title: "Tweetic | Convert Tweets to Static HTML ",
viewport: "width=device-width, initial-scale=1, maximum-scale=1",
charset: "utf-8",
link: [{ rel: "icon", href: "/logo.png" }],
meta: [
{
name: "description",
content: "Create your testimonial wall statically and style it however you want! Free • Open Source",
},
{ name: "twitter:card", content: "summary_large_image" },
{ name: "twitter:site", content: "@zernonia" },
{ name: "twitter:title", content: "Tweetic | Convert Tweets to Static HTML" },
{
name: "twitter:description",
content: "Create your testimonial wall statically and style it however you want! Free • Open Source",
},
{ name: "twitter:image", content: "https://tweetic.zernonia.com/og.png" },
{ property: "og:type", content: "website" },
{ property: "og:title", content: "Tweetic | Convert Tweets to Static HTML" },
{ property: "og:url", content: "https://tweetic.zernonia.com" },
{ property: "og:image", content: "https://tweetic.zernonia.com/og.png" },
{
property: "og:description",
content: "Create your testimonial wall statically and style it however you want! Free • Open Source",
},
],
});
</script>
<template>
<NuxtLoadingIndicator></NuxtLoadingIndicator>
<div class="p-4 md:p-8 w-full max-w-screen-[1300px]">
<div class="flex items-center justify-between mb-6">
<NuxtLink to="/"><img :src="Logo" alt="tweetic logo" class="h-12 md:h-16" /></NuxtLink>
<div class="flex items-center space-x-2">
<NuxtLink class="btn btn-pale w-20 text-center relative" to="/docs">API</NuxtLink>
<NuxtLink class="btn btn-primary" to="/create">Create</NuxtLink>
</div>
</div>
<NuxtPage></NuxtPage>
<div class="flex flex-col md:flex-row items-center justify-center mt-20 space-y-2 md:space-x-2 md:space-y-0">
<p class="flex items-center w-max">
Coded with 💙 <a class="ml-4" target="_blank" href="https://twitter.com/zernonia">by Zernonia</a>
</p>
<span class="hidden md:block">|</span>
<a target="_blank" href="https://github.com/zernonia/tweetic">⭐️ GitHub</a>
<span class="hidden md:block">|</span>
<a href="https://www.buymeacoffee.com/zernonia" target="_blank"
><img
src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png"
alt="Buy Me A Coffee"
style="height: 32px !important; width: auto !important"
/></a>
</div>
</div>
</template>
<style lang="postcss">
.tweet {
width: 500px;
padding: 2rem;
color: var(--text-primary);
border: 1px solid var(--border);
border-radius: 1rem;
background: var(--bg-primary);
}
.tweet-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.tweet-author {
display: flex;
align-items: center;
}
.tweet-author-image {
width: 48px;
height: 48px;
border-radius: 9999px;
}
.tweet-author-info {
margin-left: 1rem;
}
.tweet-author-title {
display: flex;
align-items: center;
}
.tweet-author-name {
line-height: 1rem;
font-weight: 500;
}
.tweet-author-verified {
width: 1.25rem;
height: 1.25rem;
margin-left: 0.25rem;
color: var(--text-secondary);
}
.tweet-author-handler {
line-height: 1.8rem;
color: var(--text-secondary);
}
.tweet-logo {
color: var(--text-secondary);
}
.tweet-content {
margin-top: 1rem;
}
.tweet-content a {
color: var(--text-secondary);
}
.tweet-content .emoji {
display: inline-block;
height: 1.2em;
width: 1.2em;
margin: 0 0.05em 0 0.1em;
vertical-align: -0.1em;
}
.tweet-media {
margin-top: 1rem;
border: 1px solid var(--border);
border-radius: 1rem;
overflow: hidden;
}
.tweet-summary {
display: flex;
}
.tweet-summary img {
width: 130px;
height: 130px;
}
.tweet-summary > div {
display: flex;
flex-direction: column;
justify-content: center;
border-left: 1px solid var(--border);
border-top: 0px !important;
}
.tweet-summary-card-text {
border-top: 1px solid var(--border);
padding: 0.75rem;
font-size: 0.95rem;
color: var(--subtext-primary);
}
.tweet-summary-card-text span {
font-size: 0.9rem;
}
.tweet-summary-card-text h2 {
color: var(--text-primary);
}
.tweet-quoted .tweet {
margin-top: 1rem;
width: 100%;
}
.tweet-info {
margin-top: 1rem;
font-size: 0.875rem;
line-height: 1.25rem;
display: flex;
align-items: center;
color: var(--subtext-primary);
}
.tweet-info-favourite {
width: 1.25rem;
height: 1.25rem;
margin-right: 0.5rem;
}
.tweet-info-date {
margin-left: 1rem;
}
[data-style="supabase"] {
width: 400px;
}
[data-style="supabase"] .tweet-author {
position: relative;
}
[data-style="supabase"] .tweet-logo {
width: 20px;
height: 20px;
position: absolute;
top: -4px;
left: -8px;
background: var(--text-secondary);
color: var(--bg-primary);
border-radius: 9999px;
padding: 0.2rem;
}
@media only screen and (max-width: 500px) {
.tweet {
width: 100%;
max-width: 500px;
}
[data-style="supabase"] {
width: 100%;
max-width: 400px;
}
}
</style>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
assets/main.css | CSS | :root {
--border: rgb(234, 234, 234);
--bg-primary: white;
--text-primary: rgb(35 35 35);
--text-secondary: rgb(31, 155, 240);
--subtext-primary: rgb(148, 163, 184);
}
body {
@apply min-h-screen bg-light-300;
}
#__nuxt {
@apply w-full flex flex-col items-center;
}
.btn {
@apply border px-4 py-2 rounded-xl transition focus:outline-blue-500;
}
.btn-primary {
@apply bg-blue-500 hover:bg-blue-600 text-white border-blue-500 focus:outline-blue-600;
}
.btn-pale {
@apply bg-white hover:bg-light-50 text-blue-500;
}
.tag {
@apply w-min px-4 py-2 rounded-xl transition text-white text-xs font-bold;
}
.description {
@apply text-sm italic text-gray-400;
}
label {
@apply mb-1;
}
input,
select {
@apply px-4 py-2 rounded-lg border placeholder-gray-300 transition focus:outline-blue-500;
}
.hljs-tag,
.hljs-name,
.hljs-punctuation,
.hljs-attr,
.hljs-attribute,
.hljs-function .hljs-title,
.hljs-section,
.hljs-title.function_,
.ruby .hljs-property,
.hljs-selector-pseudo,
.hljs-selector-tag {
@apply !text-gray-400;
}
.hljs-selector-class {
color: #183691;
}
.Vue-Toastification__container {
@apply !mt-4 md:!mt-0 !px-4;
}
.Vue-Toastification__toast {
@apply !rounded-xl;
}
.Vue-Toastification__toast--success {
@apply !bg-blue-500;
}
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
components/Arrow.vue | Vue | <template>
<svg width="148" height="139" viewBox="0 0 148 139" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M3.16858 112.804C7.08569 119.902 12.5672 129.344 17.5765 135.598M17.5765 135.598C18.1534 136.319 22.0417 130.583 22.1986 130.303C25.6464 124.175 28.1863 117.783 30.6351 111.213M17.5765 135.598C5.27393 93.2968 21.9793 52.0078 50.6447 39.1739C53.4857 37.9019 56.5793 36.5205 59.7825 35.4203M59.7825 35.4203C64.8836 33.6682 70.2626 32.6295 75.3422 33.8825C80.0302 35.039 85.6499 38.5204 87.0073 43.3865C89.5424 52.4766 79.3224 59.7024 70.8619 56.3635C63.4271 53.4297 57.7955 43.0738 59.7825 35.4203ZM59.7825 35.4203C59.8244 35.2588 59.8697 35.0986 59.9184 34.9396C71.6848 -3.42292 118.859 -4.05902 144.433 16.5368"
stroke="currentColor"
stroke-width="5.58817"
stroke-miterlimit="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
components/Modal.vue | Vue | <script setup lang="ts">
import { onClickOutside } from "@vueuse/core";
const prop = defineProps({
open: Boolean,
});
const emit = defineEmits(["close"]);
const target = ref();
onClickOutside(target, (e) => {
emit("close");
});
watch(
() => prop.open,
(n) => {
n ? document.body.classList.add("overflow-hidden") : document.body.classList.remove("overflow-hidden");
}
);
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="w-screen h-screen fixed flex justify-center items-center top-0 left-0 bg-light-100 bg-opacity-25 p-4 md:p-8"
>
<div
ref="target"
class="overflow-y-scroll bg-white w-full max-w-screen-md h-full max-h-screen-md rounded-2xl border flex flex-col"
>
<slot></slot>
</div>
</div>
</Teleport>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
components/Toggle.vue | Vue | <script setup lang="ts">
defineProps({
modelValue: Boolean,
name: String,
});
const emits = defineEmits(["update:modelValue"]);
const onClick = (ev: Event) => {
let el = ev.target as HTMLInputElement;
emits("update:modelValue", el.checked);
};
</script>
<template>
<label :for="name" class="inline-flex flex-col w-max">
<slot></slot>
<div class="relative mt-1 cursor-pointer">
<input type="checkbox" :id="name" class="sr-only" :value="modelValue" @change="onClick" />
<div class="toggle-bg bg-gray-200 border-2 border-gray-200 h-6 w-11 rounded-full transition"></div>
</div>
</label>
</template>
<style lang="postcss">
.toggle-bg:after {
content: "";
@apply absolute top-0.5 left-0.5 bg-white border border-gray-300 rounded-full h-5 w-5 transition shadow-sm;
}
input:checked + .toggle-bg:after {
transform: translateX(100%);
@apply border-white;
}
input:checked + .toggle-bg {
@apply bg-blue-500 border-blue-500;
}
</style>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
components/Tweet.vue | Vue | <script setup lang="ts">
const props = defineProps({
url: String,
layout: { type: String, default: "" },
css: { type: String, default: "" },
enable_twemoji: { type: Boolean, default: true },
show_media: { type: Boolean, default: false },
show_quoted_tweet: { type: Boolean, default: false },
show_info: { type: Boolean, default: false },
redirect: { type: Boolean, default: true },
});
const { data, pending } = await useAsyncData(
JSON.stringify(props),
() =>
$fetch("/api/tweet", {
params: { ...props },
}),
{ watch: [props] }
);
const onClick = () => {
if (props.redirect) {
window.open(props.url, "_blank");
}
};
defineExpose({ data });
</script>
<template>
<div class="relative h-max">
<div
class="ring-0 hover:ring-3 ring-blue-400 transition rounded-2xl cursor-pointer"
@click="onClick"
v-if="data?.html?.length"
v-html="data.html"
></div>
<div v-if="pending" class="absolute top-0 left-0 w-full h-full overflow-hidden">
<div class="tweet !h-full !w-full" :data-style="props.layout">
<div class="flex items-center animate-pulse">
<div class="flex items-center">
<div class="w-12 h-12 rounded-full bg-light-600"></div>
<div class="ml-4">
<p class="w-16 h-4 bg-light-600"></p>
<p class="w-16 h-4 mt-1 bg-light-600"></p>
</div>
</div>
</div>
<div class="mt-4 flex flex-col space-y-2 animate-pulse">
<div class="w-full h-4 bg-light-600"></div>
<div class="w-full h-4 bg-light-600"></div>
<div class="w-full h-4 bg-light-600"></div>
<div class="w-full h-4 bg-light-600"></div>
</div>
</div>
</div>
</div>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
components/TweetWall.vue | Vue | <script setup lang="ts">
import { PropType } from "vue";
const props = defineProps({
urls: Object as PropType<string[]>,
options: Object,
isEditing: { type: Boolean, default: false },
});
const emits = defineEmits<{
(e: "click-tweet", payload: string): void;
}>();
const sortedUrls = computed(() => {
let col1: string[] = [];
let col2: string[] = [];
props.urls?.forEach((url, index) => {
const col = index % 2;
col == 0 ? col1.push(url) : col2.push(url);
});
return [...col1, ...col2];
});
</script>
<template>
<div class="columns lg:columns-2 gap-6 mt-6">
<Tweet
v-for="url in sortedUrls"
:id="url.split('/status/')[1]"
class="tweet-container mb-6 flex justify-center"
style="break-inside: avoid"
@click="emits('click-tweet', url)"
:url="url"
:redirect="!isEditing"
v-bind="options"
></Tweet>
</div>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
components/Underline.vue | Vue | <template>
<svg width="307" height="29" viewBox="0 0 307 29" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M213.014 26.8415C178.272 19.4138 139.489 23.4441 104.338 24.1263C94.2307 24.3226 83.8895 25.6318 73.7918 25.0712C72.4748 24.9984 66.7288 24.7252 65.6509 23.2654C65.5102 23.0755 69.9908 22.3264 72.1676 22.006C76.4002 21.3829 80.6309 20.9232 84.86 20.2652C95.9785 18.5363 107.291 17.6927 118.507 16.9156C147.298 14.9223 198.803 8.77966 226.942 17.4422C228.336 17.8714 224.026 17.3684 222.568 17.3285C220.172 17.2635 217.778 17.1695 215.381 17.0942C207.566 16.8496 199.685 16.4146 191.869 16.483C166.68 16.702 141.403 15.6497 116.221 16.5922C108.643 16.8762 101.09 17.4658 93.5093 17.6937C89.1182 17.8256 89.315 17.9373 84.7768 17.7833C82.8091 17.7163 77.3531 18.3084 78.9093 17.1021C81.6501 14.9769 90.2167 15.5085 93.5299 15.0749C108.658 13.0974 123.749 10.515 138.954 9.1276C177.942 5.57026 217.632 5.56189 256.709 7.05018C272.694 7.65899 288.845 5.30402 304.762 7.20672C266.14 2.21866 225.996 2.92687 187.163 3.07107C143.44 3.23349 99.7666 3.24431 56.043 4.16564C38.0928 4.54362 20.5048 7.96207 2.5 7.71255"
stroke="currentColor"
stroke-width="4.05049"
stroke-miterlimit="1.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
components/docs/Base.vue | Vue | <script setup lang="ts">
defineProps({
method: String,
url: String,
description: String,
});
</script>
<template>
<div class="mt-20">
<div class="relative flex items-center p-2 bg-light-600 rounded-xl">
<div class="tag bg-blue-500 mr-4">{{ method }}</div>
<div>{{ url }}</div>
<span class="absolute text-sm text-gray-400 right-4 top-full md:top-auto">{{ description }}</span>
</div>
<div class="flex flex-col md:flex-row mt-12 md:space-x-6">
<div class="md:w-1/2 flex flex-col">
<div class="flex flex-col">
<h4 class="text-xl font-semibold mb-4 text-gray-400">Query Params</h4>
<slot name="config"></slot>
</div>
<div class="flex flex-col">
<h4 class="mt-20 text-xl font-semibold mb-4 text-gray-400">Results</h4>
<div class="tag bg-green-500">200</div>
<div class="mt-4">
<slot name="result"></slot>
</div>
</div>
</div>
<div class="min-h-80 md:w-1/2 p-4 md:p-8 mt-4 md:mt-0 rounded-2xl bg-light-600">
<slot name="preview"></slot>
</div>
</div>
</div>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
components/docs/DocsTweet.vue | Vue | <script setup lang="ts">
const params = ref({
url: "https://twitter.com/zernonia/status/1524620865987506176",
layout: "",
css: "tailwind",
enable_twemoji: true,
show_media: true,
show_quoted_tweet: true,
show_info: true,
});
const { $hljs } = useNuxtApp();
const tweetRef = ref();
const highlightResponse = computed(() =>
tweetRef.value?.data
? $hljs.highlight(JSON.stringify(tweetRef.value.data, null, " "), { language: "json", ignoreIllegals: false })
.value
: ""
);
</script>
<template>
<DocsBase method="GET" url="https://tweetic.zernonia.com/api/tweet" description="Obtain static tweets">
<template #config>
<label for="url">url</label>
<input type="text" name="url" id="url" v-model="params.url" />
<label class="mt-2" for="layout">layout <span class="description"> ("" | "supabase")</span></label>
<select v-model="params.layout" name="layout" id="layout">
<option value="">Default</option>
<option value="supabase">Supabase</option>
</select>
<label class="mt-2" for="css">css <span class="description"> ("" | "tailwind")</span></label>
<select v-model="params.css" name="css" id="css">
<option value="">Default CSS</option>
<option value="tailwind">Tailwind</option>
</select>
<Toggle class="mt-2" name="enable_twemoji" v-model="params.enable_twemoji"> enable_twemoji </Toggle>
<Toggle class="mt-2" name="show_media" v-model="params.show_media"> show_media </Toggle>
<Toggle class="mt-2" name="show_quoted_tweet" v-model="params.show_quoted_tweet"> show_quoted_tweet </Toggle>
<Toggle class="mt-2" name="show_info" v-model="params.show_info"> show_info </Toggle>
</template>
<template #result>
<p>html - <span class="description">HTML that are ready to render</span></p>
<p>meta - <span class="description">Meta data from Twitter</span></p>
</template>
<template #preview>
<div class="flex justify-center">
<Tweet ref="tweetRef" v-bind="params"></Tweet>
</div>
<pre class="overflow-x-scroll text-gray-400 mt-4 text-sm" v-html="highlightResponse"></pre>
</template>
</DocsBase>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
composables/useCustomHead.ts | TypeScript | export const useCustomHead = (title: string, description?: string, image?: string) => {
useHead({
title,
meta: [
{ name: "description", content: description ?? "Convert Tweets to Static HTML | Free • Open Source" },
{ name: "twitter:card", content: "summary_large_image" },
{ name: "twitter:site", content: "@zernonia" },
{ name: "twitter:title", content: title },
{
name: "twitter:description",
content: description ?? "Convert Tweets to Static HTML | Free • Open Source",
},
{ name: "twitter:image", content: image ?? "https://tweetic.zernonia.com/og.png" },
{ property: "og:type", content: "website" },
{ property: "og:title", content: title },
{ property: "og:url", content: "https://tweetic.zernonia.com" },
{ property: "og:image", content: image ?? "https://tweetic.zernonia.com/og.png" },
{
property: "og:description",
content: description ?? "Convert Tweets to Static HTML | Free • Open Source",
},
],
});
};
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
nuxt.config.ts | TypeScript | // https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
modules: ["nuxt-windicss", "@nuxtjs/supabase"],
css: ["~~/assets/main.css", "vue-toastification/dist/index.css"],
build: {
transpile: ["twitter-api-v2"],
},
runtimeConfig: {
API_SECRET_KEY: process.env.API_SECRET_KEY,
TWITTER_BEARER_TOKEN: process.env.TWITTER_BEARER_TOKEN,
SUPABASE_URL: process.env.SUPABASE_URL,
SUPABASE_KEY: process.env.SUPABASE_KEY,
},
routeRules: {
"/": { static: true },
"/thank-you": { static: true },
"/wall-of-tweets/**": { static: true },
},
});
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
pages/create.vue | Vue | <script setup lang="ts">
import { useStorage } from "@vueuse/core";
import { useClipboard } from "@vueuse/core";
import { obtainCss } from "~~/utils/function";
import { TweetOptions } from "~~/utils/types";
import { useToast } from "vue-toastification";
const toast = useToast();
const tweetsInput = useStorage("tweets", ["", "", "", "", ""]);
const tweetsOptions = useStorage<TweetOptions>("tweets-options", {
layout: "",
css: "",
show_original_link: false,
enable_twemoji: true,
show_media: true,
show_quoted_tweet: true,
show_info: true,
});
const exportOptions = useStorage("export-options", {});
const computedInput = computed(() => tweetsInput.value.filter((i) => i != ""));
const getTweetsHTML = () => {
let tweets = document.querySelectorAll(".tweet-container > div");
let innerHTMLs = "";
tweets.forEach((i) => {
innerHTMLs += i.innerHTML;
});
return innerHTMLs;
};
const { copy, copied } = useClipboard();
const copyTweet = async (url: string) => {
let tweet = document.getElementById(`${url.split("/status/")[1]}`);
let text = tweet?.querySelector("div")?.innerHTML;
try {
if (!text) throw Error("No html found");
await copy(text);
toast.success("Copied Static Tweet");
} catch (err) {
toast.error("Something wrong...");
}
};
const copyAll = async () => {
let text = getTweetsHTML() + obtainCss(tweetsOptions.value);
if (!text.length) return;
try {
await copy(text);
toast.success("Copied All Static Tweets");
} catch (err) {
toast.error("Something wrong...");
}
};
const downloadAll = () => {
let innerHTML = getTweetsHTML();
if (!innerHTML.length) return;
const a = document.createElement("a");
a.download = "download.html";
a.href = "data:text/html;charset=UTF-8," + encodeURIComponent(getTweetsHTML()) + obtainCss(tweetsOptions.value);
a.click();
a.remove();
};
const isModalOpen = ref(false);
const isPreviewingCSS = ref(false);
const openModal = () => {
isModalOpen.value = true;
};
const closeModal = (ev: boolean) => {
isModalOpen.value = ev;
isPreviewingCSS.value = false;
};
useCustomHead("Tweetic | Create now!", "Create your own static tweets now!");
</script>
<template>
<div class="w-full">
<h2 class="text-3xl md:text-4xl font-bold text-center">Create static tweets</h2>
<ClientOnly>
<div class="flex flex-col md:flex-row mt-8 justify-center items-center md:items-stretch">
<div class="flex flex-col space-y-2">
<h4 class="text-xl mb-2 font-medium">Tweets</h4>
<div class="md:w-128 flex items-center group" v-for="(tweet, index) in tweetsInput">
<input
placeholder="https://twitter.com/<user_name>/status/<tweet_id>"
class="w-full"
type="text"
v-model="tweetsInput[index]"
/>
<button
class="p-3 h-full text-xs rounded-lg bg-light-300 transition text-light-300 group-hover:text-dark-800 hover:bg-light-500"
@click="tweetsInput.splice(index, 1)"
>
✗
</button>
</div>
<button @click="tweetsInput.push('')" class="btn btn-pale md:w-120">+</button>
</div>
<div class="mt-12 md:mt-0 md:ml-6 flex flex-col justify-between">
<div class="flex flex-col">
<h4 class="text-xl mb-2 font-medium">Option</h4>
<label for="layout">Layout</label>
<select class="w-48" v-model="tweetsOptions.layout" name="layout" id="layout">
<option value="">Default</option>
<option value="supabase">Supabase</option>
</select>
<label class="mt-2" for="css">CSS</label>
<select class="w-48" v-model="tweetsOptions.css" name="css" id="css">
<option value="">Default CSS</option>
<option value="tailwind">TailwindCSS</option>
</select>
<Toggle class="mt-2" name="enable_twemoji" v-model="tweetsOptions.enable_twemoji"> Enable Twemoji </Toggle>
<Toggle class="mt-2" name="show_media" v-model="tweetsOptions.show_media"> Show Media </Toggle>
<Toggle class="mt-2" name="show_quoted_tweet" v-model="tweetsOptions.show_quoted_tweet">
Show Quoted Tweet
</Toggle>
<Toggle class="mt-2" name="show_info" v-model="tweetsOptions.show_info"> Show Info </Toggle>
</div>
<div class="mt-20 flex flex-col">
<div class="mt-2 flex space-x-2">
<button @click="openModal" class="btn btn-primary">Preview Code</button>
</div>
</div>
</div>
</div>
<hr class="my-10" />
<h2 class="text-center text-3xl md:text-4xl font-bold">Preview</h2>
<TweetWall is-editing :urls="computedInput" :options="tweetsOptions" @click-tweet="copyTweet"></TweetWall>
<Modal :open="isModalOpen" @close="closeModal">
<div class="p-4 md:p-8 !pb-0 flex items-center justify-between">
<h2 class="text-2xl md:text-4xl font-bold text-gray-300">Export</h2>
<div class="flex items-center">
<button
v-if="tweetsOptions.css != 'tailwind'"
@click="isPreviewingCSS = !isPreviewingCSS"
class="btn btn-pale mr-2"
>
Switch to {{ isPreviewingCSS ? "HTML" : "CSS" }}
</button>
<button @click="copyAll" class="btn btn-primary">{{ copied ? "Copied" : "Copy All" }}</button>
</div>
</div>
<div class="p-4 md:p-8 !pt-4 w-full h-full">
<pre
class="overflow-x-auto text-sm p-2 rounded-xl bg-light-400"
v-html="
isPreviewingCSS
? $hljs.highlight(obtainCss(tweetsOptions), { language: 'css' }).value
: $hljs.highlight(getTweetsHTML(), { language: 'html' }).value
"
></pre>
</div>
</Modal>
</ClientOnly>
</div>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
pages/docs.vue | Vue | <template>
<div>
<DocsTweet></DocsTweet>
</div>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
pages/index.vue | Vue | <script setup lang="ts"></script>
<template>
<div class="mt-32 flex flex-col items-center overflow-hidden xl:overflow-visible">
<h1 class="text-4xl md:text-7xl font-bold text-center">
Convert Tweets to <br />
Static HTML
</h1>
<h2 class="text-center mt-8 text-xl md:text-2xl text-gray-400">
Create your testimonial wall statically and<br />
style it however you want!
</h2>
<div class="md:text-xl mt-8 flex items-center flex-col md:flex-row space-y-2 md:space-y-0 md:space-x-2">
<NuxtLink class="btn btn-primary" to="/create">Create now</NuxtLink>
<a
href="https://www.producthunt.com/posts/tweetic-io?utm_source=badge-featured&utm_medium=badge&utm_souce=badge-tweetic-io"
target="_blank"
><img
src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=346188&theme=light"
alt="Tweetic.io - Convert Tweets to Static HTML | Product Hunt"
style="width: 240px; height: 48px"
width="250"
height="54"
/></a>
</div>
<div class="flex flex-wrap">
<NuxtLink to="/wall-of-tweets/supabase" class="flex flex-col m-4 items-center mt-8 text-gray-400">
<span>Supabase</span>
<Underline class="w-16 -mt-2"></Underline>
</NuxtLink>
<NuxtLink to="/wall-of-tweets/nuxt" class="flex flex-col m-4 items-center mt-8 text-gray-400">
<span>Nuxt</span>
<Underline class="w-16 -mt-2"></Underline>
</NuxtLink>
<NuxtLink to="/thank-you" class="flex flex-col m-4 items-center mt-8 text-gray-400">
<span>Appreciation</span>
<Underline class="w-16 -mt-2"></Underline>
</NuxtLink>
</div>
<div class="flex flex-col items-center space-y-4 md:relative mt-8 md:mt-32 w-full md:h-224">
<div class="md:absolute flex items-center -top-20 left-10 text-gray-400">
<Arrow class="w-12"></Arrow>
<span>Static HTML tweets</span>
</div>
<Tweet
class="md:absolute md:top-0 md:left-0"
url="https://twitter.com/zernonia/status/1513020247690809346"
layout="supabase"
></Tweet>
<Tweet
class="md:absolute md:right-0 md:-top-4"
url="https://twitter.com/sudonymously/status/1521878033929539584"
></Tweet>
<Tweet
class="md:absolute md:left-1/3 md:top-40"
url="https://twitter.com/supabase/status/1524055594587795456"
></Tweet>
<div class="md:absolute flex items-center left-1/2 top-26 text-gray-400">
<span>Create manually or API</span>
<Arrow class="w-12 transform rotate-180 mr-4"></Arrow>
</div>
<div class="md:absolute flex items-center md:top-84 md:left-36 text-gray-400">
<Arrow class="w-12 transform rotate-20 mr-4"></Arrow>
<span>Free & Open Source</span>
</div>
<Tweet
class="md:absolute md:-left-20 md:top-108"
url="https://twitter.com/CodiferousCoder/status/1522233113207836675"
></Tweet>
<Tweet
class="md:absolute md:-right-1/10 md:top-48"
url="https://twitter.com/OSSInsight/status/1524071559865937920"
layout="supabase"
></Tweet>
<Tweet
class="md:absolute md:top-132 md:right-1/10"
url="https://twitter.com/sweekiat_lim/status/1517707225430519809"
layout="supabase"
></Tweet>
<div class="md:absolute flex items-center right-10 top-110 text-gray-400">
<Arrow class="w-12 transform rotate-x-180 md:rotate-x-0 mr-4"></Arrow>
<span>Custom CSS class for styling</span>
</div>
<div class="w-96 h-96 bg-blue-300 filter blur-[100px] hidden md:block absolute top-48 -z-1"></div>
</div>
</div>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
pages/thank-you.vue | Vue | <script setup lang="ts">
const tweets = ref([
"https://twitter.com/dominiksumer/status/1524741858009694209",
"https://twitter.com/maazarin/status/1524732072832774147",
"https://twitter.com/kecrily/status/1524665293540589569",
"https://twitter.com/pramit_armpit/status/1524637652565524481",
"https://twitter.com/ImnNazri/status/1524626328167010304",
"https://twitter.com/frouo/status/1524840028123320326",
]);
useCustomHead("Thank you for your kind word! | Tweetic");
</script>
<template>
<div class="mb-32">
<h2 class="text-4xl md:text-6xl text-center font-semibold my-8 md:my-20">Thank you everyone!!</h2>
<TweetWall :urls="tweets" :options="{ layout: 'supabase' }"></TweetWall>
<p class="text-center mt-8 md:mt-20">...and everyone who likes and retweet!</p>
</div>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
pages/wall-of-tweets/[keyword].vue | Vue | <script setup lang="ts">
import { capitalizeFirstLetter } from "~~/utils/function";
const route = useRoute();
const keyword = route.params.keyword?.toString();
const { data, pending } = await useLazyFetch("/api/wall-of-tweets", { params: { keyword }, key: keyword });
useCustomHead(`${capitalizeFirstLetter(keyword.toString())}'s Wall of Tweets! | Tweetic`);
</script>
<template>
<div>
<div class="flex flex-col items-center justify-center my-8 md:my-16 md:space-y-2">
<h2 class="font-bold text-4xl md:text-6xl capitalize">{{ keyword }}'s</h2>
<h3 class="font-semibold text-2xl md:text-4xl text-gray-300">Wall of Tweets</h3>
</div>
<TweetWall
v-if="data?.length"
:urls="data"
:options="{ layout: 'supabase', show_media: true, show_info: true }"
></TweetWall>
<p v-if="pending" class="text-center my-40 text-gray-300 font-semibold">Loading...</p>
<p v-else class="text-center my-40 text-gray-300 font-semibold">No tweets crawled...</p>
</div>
</template>
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
plugins/highlight.ts | TypeScript | import hljs from "highlight.js/lib/core"
import json from "highlight.js/lib/languages/json"
import html from "highlight.js/lib/languages/xml"
import css from "highlight.js/lib/languages/css"
import "highlight.js/styles/base16/github.css"
export default defineNuxtPlugin(() => {
hljs.registerLanguage("json", json)
hljs.registerLanguage("html", html)
hljs.registerLanguage("css", css)
return {
provide: {
hljs,
},
}
})
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
plugins/toast.client.ts | TypeScript | import Toast, { PluginOptions, POSITION } from "vue-toastification/dist/index.mjs";
const options: PluginOptions = {
position: POSITION.TOP_CENTER,
maxToasts: 1,
timeout: 2000,
transition: "Vue-Toastification__fade",
};
export default defineNuxtPlugin((nuxt) => {
nuxt.vueApp.use(Toast, options);
});
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
plugins/umami.client.ts | TypeScript | import { defineNuxtPlugin } from "#app";
export default defineNuxtPlugin(() => {
const moduleOptions = {
scriptUrl: "https://umami-zernonia.vercel.app/umami.js",
websiteId: "91452ea0-c879-4497-8bf0-0dd74ee96bb8",
domains: "tweetic.zernonia.com",
};
const options = { ...moduleOptions };
loadScript(options);
});
function loadScript(options: any) {
const head = document.head || document.getElementsByTagName("head")[0];
const script = document.createElement("script");
script.async = true;
script.defer = true;
script.dataset.websiteId = options.websiteId;
script.dataset.domains = options.domains;
script.src = options.scriptUrl;
head.appendChild(script);
}
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
server/_lib/parser.ts | TypeScript | import { TweetOptions, TweetContent, TweetSyndication } from "~~/utils/types";
import { mapClass } from "./reference";
import { format } from "date-fns";
import Twemoji from "twemoji";
export const constructHtml = (data: TweetSyndication, options: TweetOptions, isQuotedTweet = false) => {
try {
const mapClassOptions = (key: string) => mapClass(key, options);
const { meta, html: content, user, media_html, card_html, quoted_tweet } = getTweetContent(data, options);
const quoted_html = getQuotedHtml(quoted_tweet as any, options);
const tweet_class = isQuotedTweet
? mapClassOptions("tweet").replace("w-[400px]", "").replace("w-[500px]", "").concat(" mt-4")
: mapClassOptions("tweet");
let favorite_count_str;
if (meta.favorite_count >= 1000000) {
favorite_count_str = (meta.favorite_count / 1000000).toFixed(1) + " m";
} else if (meta.favorite_count >= 10000) {
favorite_count_str = (meta.favorite_count / 1000).toFixed(1) + " K";
} else {
favorite_count_str = meta.favorite_count?.toLocaleString("en-US");
}
const html: string = `
<div class="${tweet_class} " data-style="${options.layout}">
<div class="${mapClassOptions("tweet-header")}">
${
options.layout == "supabase"
? `<div class="${mapClassOptions("tweet-author")}">
<svg class="${mapClassOptions(
"tweet-logo"
)}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--mdi" width="32" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path fill="currentColor" d="M22.46 6c-.77.35-1.6.58-2.46.69c.88-.53 1.56-1.37 1.88-2.38c-.83.5-1.75.85-2.72 1.05C18.37 4.5 17.26 4 16 4c-2.35 0-4.27 1.92-4.27 4.29c0 .34.04.67.11.98C8.28 9.09 5.11 7.38 3 4.79c-.37.63-.58 1.37-.58 2.15c0 1.49.75 2.81 1.91 3.56c-.71 0-1.37-.2-1.95-.5v.03c0 2.08 1.48 3.82 3.44 4.21a4.22 4.22 0 0 1-1.93.07a4.28 4.28 0 0 0 4 2.98a8.521 8.521 0 0 1-5.33 1.84c-.34 0-.68-.02-1.02-.06C3.44 20.29 5.7 21 8.12 21C16 21 20.33 14.46 20.33 8.79c0-.19 0-.37-.01-.56c.84-.6 1.56-1.36 2.14-2.23Z"></path></svg>
<img class="${mapClassOptions("tweet-author-image")}" src="${user.profile_image_url_https}" >
<div class="${mapClassOptions("tweet-author-info")}">
<p class="${mapClassOptions("tweet-author-name")}"></p>
<a class="${mapClassOptions("tweet-author-handler")}" target="_blank" href="https://twitter.com/${
user.screen_name
}">@${user.screen_name}</a>
</div>
</div>`
: `<div class="${mapClassOptions("tweet-author")}">
<img class="${mapClassOptions("tweet-author-image")}" src="${user.profile_image_url_https}" >
<div class="${mapClassOptions("tweet-author-info")}">
<div class="${mapClassOptions("tweet-author-title")}"
<p class="${mapClassOptions("tweet-author-name")}">${user.name}</p>
${
user.verified
? `<svg class="${mapClassOptions(
"tweet-author-verified"
)}" viewBox="0 0 24 24"><g><path fill="currentColor" d="M22.5 12.5c0-1.58-.875-2.95-2.148-3.6.154-.435.238-.905.238-1.4 0-2.21-1.71-3.998-3.818-3.998-.47 0-.92.084-1.336.25C14.818 2.415 13.51 1.5 12 1.5s-2.816.917-3.437 2.25c-.415-.165-.866-.25-1.336-.25-2.11 0-3.818 1.79-3.818 4 0 .494.083.964.237 1.4-1.272.65-2.147 2.018-2.147 3.6 0 1.495.782 2.798 1.942 3.486-.02.17-.032.34-.032.514 0 2.21 1.708 4 3.818 4 .47 0 .92-.086 1.335-.25.62 1.334 1.926 2.25 3.437 2.25 1.512 0 2.818-.916 3.437-2.25.415.163.865.248 1.336.248 2.11 0 3.818-1.79 3.818-4 0-.174-.012-.344-.033-.513 1.158-.687 1.943-1.99 1.943-3.484zm-6.616-3.334l-4.334 6.5c-.145.217-.382.334-.625.334-.143 0-.288-.04-.416-.126l-.115-.094-2.415-2.415c-.293-.293-.293-.768 0-1.06s.768-.294 1.06 0l1.77 1.767 3.825-5.74c.23-.345.696-.436 1.04-.207.346.23.44.696.21 1.04z"></path></g></svg>`
: ""
}
</div>
<a class="${mapClassOptions("tweet-author-handler")}" target="_blank" href="https://twitter.com/${
user.screen_name
}">@${user.screen_name}
</a>
</div>
</div>
<svg class="${mapClassOptions(
"tweet-logo"
)}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--mdi" width="32" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path fill="currentColor" d="M22.46 6c-.77.35-1.6.58-2.46.69c.88-.53 1.56-1.37 1.88-2.38c-.83.5-1.75.85-2.72 1.05C18.37 4.5 17.26 4 16 4c-2.35 0-4.27 1.92-4.27 4.29c0 .34.04.67.11.98C8.28 9.09 5.11 7.38 3 4.79c-.37.63-.58 1.37-.58 2.15c0 1.49.75 2.81 1.91 3.56c-.71 0-1.37-.2-1.95-.5v.03c0 2.08 1.48 3.82 3.44 4.21a4.22 4.22 0 0 1-1.93.07a4.28 4.28 0 0 0 4 2.98a8.521 8.521 0 0 1-5.33 1.84c-.34 0-.68-.02-1.02-.06C3.44 20.29 5.7 21 8.12 21C16 21 20.33 14.46 20.33 8.79c0-.19 0-.37-.01-.56c.84-.6 1.56-1.36 2.14-2.23Z"></path></svg>`
}
</div>
<div class="${mapClassOptions("tweet-content")}">
${content}
${options.show_media ? media_html : ""}
${options.show_media ? card_html : ""}
${options.show_quoted_tweet ? quoted_html : ""}
</div>
${
options.show_info && !isQuotedTweet
? `
<div class="${mapClassOptions("tweet-info")}" >
<svg class="${mapClassOptions(
"tweet-info-favourite"
)}" width="24" height="24" viewBox="0 0 24 24"><path class="fill-current" d="M12 21.638h-.014C9.403 21.59 1.95 14.856 1.95 8.478c0-3.064 2.525-5.754 5.403-5.754 2.29 0 3.83 1.58 4.646 2.73.813-1.148 2.353-2.73 4.644-2.73 2.88 0 5.404 2.69 5.404 5.755 0 6.375-7.454 13.11-10.037 13.156H12zM7.354 4.225c-2.08 0-3.903 1.988-3.903 4.255 0 5.74 7.035 11.596 8.55 11.658 1.52-.062 8.55-5.917 8.55-11.658 0-2.267-1.822-4.255-3.902-4.255-2.528 0-3.94 2.936-3.952 2.965-.23.562-1.156.562-1.387 0-.015-.03-1.426-2.965-3.955-2.965z"></path></svg>
<span>${favorite_count_str}</span>
<div class="${mapClassOptions("tweet-info-date")}">${format(new Date(meta.created_at), "h:mm a · MMM d, y")}</div>
</div>
`
: ""
}
</div>
`;
return { html, meta };
} catch (err) {
throw err;
}
};
export const getSyndication = async (id: string) => {
return await $fetch<TweetSyndication>(`https://cdn.syndication.twimg.com/tweet-result?id=${id}`);
};
export const getTweetContent = (data: TweetSyndication, options: TweetOptions) => {
try {
const { display_text_range, entities, user, card, text, quoted_tweet, photos, video } = data;
let html = text.substr(display_text_range[0]);
const meta = {
user_id: user.id_str,
name: user.name,
screen_name: user.screen_name,
verified: user.verified,
profile_image_url_https: user.profile_image_url_https,
url: "https://twitter.com/" + user.screen_name + "/status/" + data.id_str,
profile_url: "https://twitter.com/" + user.screen_name,
created_at: data.created_at,
favorite_count: data.favorite_count,
conversation_count: data.conversation_count,
};
const linkClass = options.css == "tailwind" ? "text-blue-400" : "tweet-content-link";
entities.urls?.forEach((i) => {
html = html.replace(
i.url,
i.display_url.includes("twitter.com")
? ""
: `<a class="${linkClass}" href="${i.url}" target="_blank">${i.display_url}</a>`
);
});
entities.media?.forEach((i) => {
html = html.replace(i.url, "");
});
entities.hashtags?.forEach((i) => {
html = html.replace(
`#${i.text}`,
`<a class="${linkClass}" href="https://twitter.com/hashtag/${i.text}" target="_blank">#${i.text}</a>`
);
});
entities.user_mentions?.forEach((i) => {
html = html.replace(
`@${i.screen_name}`,
`<a class="${linkClass}" href="https://twitter.com/${i.screen_name}" target="_blank">@${i.screen_name}</a>`
);
});
html = html.replace(/\n/g, "<br />");
if (options.enable_twemoji) {
html = Twemoji.parse(html, {
base: "https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/",
folder: "svg",
ext: ".svg",
className:
options.css === "tailwind"
? "inline-block align-text-bottom w-[1.2em] h-[1.2em] mr-[0.05em] ml-[0.1em]"
: "emoji",
});
}
let card_html = "";
const mediaClass =
options.css == "tailwind" ? "border border-gray-200 rounded-2xl mt-4 overflow-hidden" : "tweet-media";
if (card?.name === "summary_large_image") {
html.replace(card.url, "");
card_html =
options.css === "tailwind"
? `
<a href="${card.url}" target="_blank">
<div class="${mediaClass}">
<img src="${card.binding_values.thumbnail_image_large.image_value.url}" >
<div class="border-t border-gray-200 text-slate-400 text-[0.95rem] p-3">
<span class="text-[0.9rem]">${card.binding_values.vanity_url.string_value}</span>
<h2 class="text-black leading-relaxed my-0.5">${card.binding_values.title.string_value}</h2>
<p class="leading-snug">${card.binding_values.description.string_value}</p>
</div>
</div>
</a>`
: `
<a href="${card.url}" target="_blank">
<div class="${mediaClass} tweet-summary-large-image">
<img src="${card.binding_values.thumbnail_image_large.image_value.url}" >
<div class="tweet-summary-card-text">
<span>${card.binding_values.vanity_url.string_value}</span>
<h2>${card.binding_values.title.string_value}</h2>
<p>${card.binding_values.description.string_value}</p>
</div>
</div>
</a>`;
}
if (card?.name === "summary") {
html.replace(card.url, "");
card_html =
options.css === "tailwind"
? `
<a href="${card.url}" target="_blank">
<div class="${mediaClass} flex">
<img class="w-[130px] h-[130px]" src="${card.binding_values.thumbnail_image_large.image_value.url}" >
<div class="flex flex-col justify-center border-l border-gray-200 text-slate-400 text-[0.95rem] p-3">
<span class="text-[0.9rem]">${card.binding_values.vanity_url.string_value}</span>
<h2 class="text-black leading-relaxed my-0.5">${card.binding_values.title.string_value}</h2>
<p class="leading-snug">${card.binding_values.description.string_value}</p>
</div>
</div>
</a>`
: `
<a href="${card.url}" target="_blank">
<div class="${mediaClass} tweet-summary">
<img src="${card.binding_values.thumbnail_image_large.image_value.url}" >
<div class="tweet-summary-card-text">
<span>${card.binding_values.vanity_url.string_value}</span>
<h2>${card.binding_values.title.string_value}</h2>
<p>${card.binding_values.description.string_value}</p>
</div>
</div>
</a>`;
}
let media_html = "";
if (photos) {
media_html = `<div class="${mediaClass}">`;
photos.map((photo) => {
media_html += `<img style="width: 100%" class="tweet-image" src="${photo.url}">`;
});
media_html += `</div>`;
}
if (video) {
const mp4 = video.variants.find((i) => i.type === "video/mp4");
media_html = `
<div class="${mediaClass}">
<video style="width: 100%" autoplay muted loop src="${mp4.src}"></video>
</div>`;
}
return {
meta,
html,
user,
card_html,
media_html,
quoted_tweet,
};
} catch (err) {
throw err;
}
};
const getQuotedHtml = (data: TweetSyndication, options: TweetOptions) => {
if (!data) return "";
const url = `https://twitter.com/${data.user.screen_name}/status/${data.id_str}`;
return `<div class="tweet-quoted">
${constructHtml(data, options, true).html}
</div>`;
};
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
server/_lib/reference.ts | TypeScript | import { TweetOptions } from "~~/utils/types";
const tailwindClassBasic = {
"tweet-header": " flex items-center justify-between",
"tweet-author": "relative flex items-center",
"tweet-author-image": "w-12 h-12 rounded-full",
"tweet-author-info": "ml-4",
"tweet-author-name": "font-medium",
"tweet-author-handler": "text-blue-400",
"tweet-content": "mt-4",
"tweet-content-link": "text-blue-400",
"tweet-info": "mt-4 text-sm flex items-center text-slate-400",
"tweet-info-favourite": "w-5 h-5 mr-2",
"tweet-info-date": "ml-4",
};
const tailwindClassDefaultReference = {
...tailwindClassBasic,
tweet: "w-[500px] p-8 text-black border border-gray-200 bg-white rounded-2xl",
"tweet-author-title": "flex items-center",
"tweet-author-verified": "ml-1 w-5 h-5 text-blue-400",
"tweet-logo": "text-blue-400",
};
const tailwindClassSupabaseReference = {
...tailwindClassBasic,
tweet: "w-[400px] p-8 text-black border border-gray-200 bg-white rounded-2xl",
"tweet-logo": "bg-blue-400 text-white w-5 h-5 absolute -top-1 -left-2 rounded-full p-[0.2rem]",
};
export const mapClass = (key: string, options: TweetOptions): string => {
if (options.css == "tailwind") {
return options.layout == "supabase" ? tailwindClassSupabaseReference[key] : tailwindClassDefaultReference[key];
} else return key;
};
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
server/_lib/verify.ts | TypeScript | import { H3Event } from "h3";
export const verify = (event: H3Event) => {
const { authorization } = event.req.headers;
let authorized = true;
if (process.env.NODE_ENV !== "development" && authorization !== `Bearer ${useRuntimeConfig().API_SECRET_KEY}`) {
event.res.statusCode = 401;
authorized = false;
}
return authorized;
};
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
server/api/crawl-all.ts | TypeScript | import { TwitterApi } from "twitter-api-v2";
import { verify } from "../_lib/verify";
import { serverSupabaseClient } from "#supabase/server";
export default defineEventHandler(async (event) => {
const authorized = verify(event);
const client = serverSupabaseClient(event);
if (!authorized) return "Unauthorized";
const { keyword } = getQuery(event);
const twitterClient = new TwitterApi(useRuntimeConfig().TWITTER_BEARER_TOKEN);
const roClient = twitterClient.readOnly;
const results = await roClient.v2.search(`${keyword ?? "supabase"} lang:en -is:retweet -is:reply -is:quote`, {
expansions: "author_id",
max_results: 100,
"tweet.fields": "created_at",
});
const tweets = results.data.data.map((i) => {
let author = results.data?.includes?.users?.find((j) => j.id === i.author_id);
let id = i.id;
delete i.id;
delete i.author_id;
return {
id,
keyword,
metadata: {
...i,
author,
},
};
});
const { data, error } = await client.from("tweets").upsert(tweets);
return {
data,
error,
};
});
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
server/api/crawl.ts | TypeScript | import { TwitterApi } from "twitter-api-v2";
import { verify } from "../_lib/verify";
import { serverSupabaseClient } from "#supabase/server";
export default defineEventHandler(async (event) => {
const authorized = verify(event);
const client = serverSupabaseClient(event);
if (!authorized) return "Unauthorized";
const { keyword } = getQuery(event);
const twitterClient = new TwitterApi(useRuntimeConfig().TWITTER_BEARER_TOKEN);
const roClient = twitterClient.readOnly;
const results = await roClient.v2.search(
`${
keyword ?? "supabase"
} -is:reply (happy OR exciting OR wonderful OR excited OR favorite OR fav OR amazing OR incredible OR best OR good OR love) -paid -course -hour -join`,
{
expansions: "author_id",
max_results: 100,
}
);
const tweets = results.data.data.map((i) => {
let author_name = results.data?.includes?.users?.find((j) => j.id === i.author_id)?.username;
return {
id: i.id,
url: `${author_name}/status/${i.id}`,
keyword,
raw: i,
};
});
const { data, error } = await client.from("wall_of_tweets").upsert(tweets);
return {
data,
error,
};
});
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
server/api/tweet.ts | TypeScript | import { defu } from "defu";
import { TweetOptions, TweetQueryOptions, TweetSyndication } from "~~/utils/types";
import { constructHtml, getSyndication } from "../_lib/parser";
import { setResponseHeader } from "h3";
// Create Capture Group for twitter url.
const getTwitterId = (url: string): string | boolean => {
// @see https://regex101.com/r/AAtIUu/1
let match = url.match(/(https:\/\/twitter.com\/.*\/status\/)|([0-9]+)/g);
if (match && match.length === 2) {
return match[1];
}
return false;
};
const cachedData: { [key: string]: TweetSyndication } = {};
export default defineEventHandler(async (event) => {
setResponseHeader(event, "Access-Control-Allow-Origin", "*");
try {
const query: TweetQueryOptions = getQuery(event);
const { url, layout, css, enable_twemoji, show_media, show_quoted_tweet, show_info } = defu(query, {
enable_twemoji: false,
show_media: false,
show_quoted_tweet: false,
show_info: false,
});
if (!url) throw new Error("Invalid Twitter URL or not defined.");
const id = getTwitterId(url);
// Check valid twitter id
if (typeof id !== "string") throw new Error("Invalid Twitter ID or not defined.");
const options: TweetOptions = {
layout: layout?.toString(),
css: css?.toString(),
enable_twemoji: JSON.parse(enable_twemoji.toString()),
show_media: JSON.parse(show_media.toString()),
show_quoted_tweet: JSON.parse(show_quoted_tweet.toString()),
show_info: JSON.parse(show_info.toString()),
};
let data: TweetSyndication;
if (cachedData[id]) {
data = cachedData[id];
} else {
data = await getSyndication(id.toString());
cachedData[id] = data;
}
const { html, meta } = constructHtml(data, options);
return { html, meta };
} catch (err) {
return {};
}
});
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
server/api/wall-of-tweets.ts | TypeScript | import { serverSupabaseClient } from "#supabase/server";
export default defineEventHandler(async (event) => {
try {
const { keyword } = getQuery(event);
const client = serverSupabaseClient(event);
const { data } = await client.from("wall_of_tweets").select("url").eq("keyword", keyword);
return data?.map((i) => `https://twitter.com/${i.url}`);
} catch (err) {
return sendError(event, Error(`${err}`), process.env.NODE_ENV === "development");
}
});
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
server/middleware/swr.ts | TypeScript | export default defineEventHandler(async (event) => {
event.context.res?.setHeader("Cache-Control", "s-maxage=7200, stale-while-revalidate");
});
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
utils/function.ts | TypeScript | import { TweetOptions, ExportOptions } from "./types"
const baseStyle = `
:root {
--border: rgb(234, 234, 234);
--bg-primary: white;
--text-primary: rgb(35 35 35);
--text-secondary: rgb(31, 155, 240);
}
body { font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";}
h1, h2, h4, hr, p { margin: 0 }
a { color: inherit; text-decoration: inherit; }
.tweet-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.tweet-author-image {
width: 48px;
height: 48px;
border-radius: 9999px;
}
.tweet-author-info {
margin-left: 1rem;
}
.tweet-author-name {
line-height: 1rem;
font-weight: 500;
}
.tweet-author-handler {
line-height: 1.8rem;
color: var(--text-secondary);
}
.tweet-content {
margin-top: 1rem;
}
.tweet-content a {
color: var(--text-secondary);
}
.tweet-content .emoji {
display: inline-block;
height: 1.2em;
width: 1.2em;
margin: 0 0.05em 0 0.1em;
vertical-align: -0.1em;
}
.tweet-media {
margin-top: 1rem;
border: 1px solid var(--border);
border-radius: 1rem;
overflow: hidden;
}
.tweet-summary-card-text {
border-top: 1px solid var(--border);
padding: 0.75rem;
font-size: 0.95rem;
color: var(--subtext-primary);
}
.tweet-summary-card-text span {
font-size: 0.9rem;
}
.tweet-summary-card-text h2 {
color: var(--text-primary);
}
.tweet-summary {
display: flex;
}
.tweet-summary img {
width: 130px;
height: 130px;
}
.tweet-summary > div {
display: flex;
flex-direction: column;
justify-content: center;
border-left: 1px solid var(--border);
border-top: 0px !important;
}
.tweet-image {
width: 100%;
}
.tweet-quoted .tweet {
margin-top: 1rem;
width: 100%;
}
`
export const obtainCss = (tweetOptions: TweetOptions) => {
if (tweetOptions.css == "tailwind") return ""
let style = "<style>" + baseStyle
if (tweetOptions.layout == "supabase") {
style += `
.tweet {
width: 400px;
padding: 2rem;
color: var(--text-primary);
border: 1px solid var(--border);
border-radius: 1rem;
background: var(--bg-primary);
}
.tweet-author {
display: flex;
position: relative;
align-items: center;
}
.tweet-logo {
color: var(--text-secondary);
width: 20px;
height: 20px;
position: absolute;
top: -4px;
left: -8px;
background: var(--text-secondary);
color: var(--bg-primary);
border-radius: 9999px;
padding: 0.2rem;
}`
} else {
style += `
.tweet {
width: 500px;
padding: 2rem;
color: var(--text-primary);
border: 1px solid var(--border);
border-radius: 1rem;
background: var(--bg-primary);
}
.tweet-author {
display: flex;
align-items: center;
}
.tweet-author-title {
display: flex;
align-items: center;
}
.tweet-author-verified {
width: 1.25rem;
height: 1.25rem;
margin-left: 0.25rem;
color: var(--text-secondary);
}
.tweet-logo {
color: var(--text-secondary);
}`
}
return style + "</style>"
}
export const capitalizeFirstLetter = (string: string) => {
return string.charAt(0).toUpperCase() + string.slice(1)
}
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
utils/types/index.ts | TypeScript | export * from "./syndication"
export * from "./interface"
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
utils/types/interface.ts | TypeScript | export interface TweetOembed {
author_name: string
author_url: string
cache_age: string
height: number | null
html: string
provider_name: string
provider_url: string
type: string
url: string
version: string
width: number | null
}
export interface TweetOptions {
layout?: string
css?: string
show_original_link?: boolean
enable_twemoji?: boolean
show_media?: boolean
show_quoted_tweet?: boolean
show_info?: boolean
}
export interface TweetQueryOptions extends TweetOptions {
url?: string
}
export interface ExportOptions {
css: string
}
export interface TweetContent {
meta: {
id?: string
url?: string
avatar?: {
[key: string]: string
}
name?: string
username?: string
profile_url?: string
created_at?: number
heart_count?: string
cta_type?: string
cta_count?: string
[key: string]: any
}
html: string
quoted_tweet?: {
id: string
url: string
}
media_html?: string
}
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
utils/types/syndication.ts | TypeScript | export interface TweetSyndication {
lang: string
favorite_count: number
self_thread: SelfThread
created_at: string
display_text_range: number[]
entities: Entities
id_str: string
text: string
user: User
conversation_count: number
news_action_type: string
card: Card
photos: Photo[]
video: Video
quoted_tweet: QuotedTweet
}
export interface ImageValue {
height: number
width: number
url: string
}
export interface SelfThread {
id_str: string
}
export interface Entities {
hashtags: HashTag[]
urls: Url[]
media: Url[]
user_mentions: UserMention[]
symbols: any[]
}
export interface Url {
display_url: string
expanded_url: string
indices: number[]
url: string
}
export interface HashTag {
indices: number[]
text: string
}
export interface UserMention {
id_str: string
indices: number[]
name: string
screen_name: string
}
export interface User {
id_str: string
name: string
profile_image_url_https: string
screen_name: string
verified: boolean
}
export interface Card {
card_platform: CardPlatform
name: string
url: string
binding_values: BindingValues
}
export interface CardPlatform {
platform: Platform
}
export interface Platform {
audience: Audience
device: Device
}
export interface Audience {
name: string
}
export interface Device {
name: string
version: string
}
export interface BindingValues {
photo_image_full_size_large: PhotoImageFullSizeLarge
thumbnail_image: ThumbnailImage
description: Description
domain: Domain
thumbnail_image_large: ThumbnailImageLarge
summary_photo_image_small: SummaryPhotoImageSmall
thumbnail_image_original: ThumbnailImageOriginal
site: Site
photo_image_full_size_small: PhotoImageFullSizeSmall
summary_photo_image_large: SummaryPhotoImageLarge
thumbnail_image_small: ThumbnailImageSmall
thumbnail_image_x_large: ThumbnailImageXLarge
photo_image_full_size_original: PhotoImageFullSizeOriginal
vanity_url: VanityUrl
photo_image_full_size: PhotoImageFullSize
thumbnail_image_color: ThumbnailImageColor
title: Title
summary_photo_image_color: SummaryPhotoImageColor
summary_photo_image_x_large: SummaryPhotoImageXLarge
summary_photo_image: SummaryPhotoImage
photo_image_full_size_color: PhotoImageFullSizeColor
photo_image_full_size_x_large: PhotoImageFullSizeXLarge
card_url: CardUrl
summary_photo_image_original: SummaryPhotoImageOriginal
}
export interface PhotoImageFullSizeLarge {
image_value: ImageValue
type: string
}
export interface ThumbnailImage {
image_value: ImageValue
type: string
}
export interface Description {
string_value: string
type: string
}
export interface Domain {
string_value: string
type: string
}
export interface ThumbnailImageLarge {
image_value: ImageValue
type: string
}
export interface SummaryPhotoImageSmall {
image_value: ImageValue
type: string
}
export interface ThumbnailImageOriginal {
image_value: ImageValue
type: string
}
export interface Site {
scribe_key: string
type: string
user_value: UserValue
}
export interface UserValue {
id_str: string
path: any[]
}
export interface PhotoImageFullSizeSmall {
image_value: ImageValue
type: string
}
export interface SummaryPhotoImageLarge {
image_value: ImageValue
type: string
}
export interface ThumbnailImageSmall {
image_value: ImageValue
type: string
}
export interface ThumbnailImageXLarge {
image_value: ImageValue
type: string
}
export interface PhotoImageFullSizeOriginal {
image_value: ImageValue
type: string
}
export interface VanityUrl {
scribe_key: string
string_value: string
type: string
}
export interface PhotoImageFullSize {
image_value: ImageValue
type: string
}
export interface ThumbnailImageColor {
image_color_value: ImageColorValue
type: string
}
export interface ImageColorValue {
palette: Palette[]
}
export interface Title {
string_value: string
type: string
}
export interface SummaryPhotoImageColor {
image_color_value: ImageColorValue
type: string
}
export interface SummaryPhotoImageXLarge {
image_value: ImageValue
type: string
}
export interface SummaryPhotoImage {
image_value: ImageValue
type: string
}
export interface PhotoImageFullSizeColor {
image_color_value: ImageColorValue
type: string
}
export interface Palette {
rgb: Rgb
percentage: number
}
export interface Rgb {
blue: number
green: number
red: number
}
export interface PhotoImageFullSizeXLarge {
image_value: ImageValue
type: string
}
export interface CardUrl {
scribe_key: string
string_value: string
type: string
}
export interface SummaryPhotoImageOriginal {
image_value: ImageValue
type: string
}
export interface QuotedTweet {
lang: string
reply_count: number
retweet_count: number
favorite_count: number
created_at: string
display_text_range: number[]
entities: Entities
id_str: string
text: string
user: User
photos: Photo[]
}
export interface Photo {
backgroundColor: BackgroundColor
cropCandidates: CropCandidate[]
expandedUrl: string
url: string
width: number
height: number
}
export interface BackgroundColor {
red: number
green: number
blue: number
}
export interface CropCandidate {
x: number
y: number
w: number
h: number
}
export interface Video {
aspectRatio: number[]
contentType: string
durationMs: number
mediaAvailability: MediaAvailability
poster: string
variants: Variant[]
videoId: VideoId
viewCount: number
}
export interface MediaAvailability {
status: string
}
export interface Variant {
type: string
src: string
}
export interface VideoId {
type: string
id: string
}
| zernonia/tweetic | 248 | Convert Tweets to Static HTML | TypeScript | zernonia | zernonia | Troop Travel |
app.vue | Vue | <script setup lang="ts">
const { name } = toRefs(useRoute());
const routeName = computed(
() => name.value && name.value.toString().charAt(0).toLocaleUpperCase() + name.value.toString().slice(1)
);
useHead({
titleTemplate: (title) => `${title ?? routeName.value} | Vista`,
link: [{ rel: "icon", href: "/logo.svg" }],
});
</script>
<template>
<NuxtLayout>
<NuxtPage></NuxtPage>
</NuxtLayout>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
assets/main.css | CSS | @import "@vueform/slider/themes/default.css";
:root {
--slider-connect-bg: #3b82f6;
--slider-tooltip-bg: #3b82f6;
--slider-handle-ring-color: #3b82f630;
}
img {
@apply inline-block;
}
input[type="number"],
input[type="text"] {
@apply w-full border shadow-sm px-3 py-2 rounded-lg;
}
label {
@apply text-sm mt-3 mb-2 font-medium text-dark-200;
}
.vc-color-wrap {
@apply rounded-lg !w-full !h-10 border shadow-sm !shadow-none;
}
h1 {
@apply text-center font-bold text-5xl text-dark-50;
}
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Completed.vue | Vue | <script setup lang="ts">
import { downloadBlob } from "@/utils/functions";
defineProps({
url: { type: String, default: "" },
});
const emits = defineEmits(["edit"]);
</script>
<template>
<div class="w-max mx-auto my-20">
<h1 class="mb-16">Completed! 🎉</h1>
<Preview :url="url" />
<PreviewControls />
<div class="grid grid-cols-3 gap-4 mt-12">
<button class="btn-primary" @click="downloadBlob(url)">
Download
<div class="ml-2 text-xl i-bx-download"></div>
</button>
<button class="btn-plain" @click="emits('edit')">
Edit
<div class="ml-2 text-xl i-bx-edit"></div>
</button>
<NuxtLink
target="_blank"
to="https://twitter.com/intent/tweet?original_referer=https://www.vistaeditor.com/&text=Check%20out%20Vista%20Editor%20by%20@zernonia&url=https://www.vistaeditor.com/"
class="btn-plain"
>
Share
<div class="ml-2 text-xl i-bx-share-alt"></div>
</NuxtLink>
</div>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Edit.vue | Vue | <script setup lang="ts">
import html2canvas from "html2canvas";
import { chunk, toBlob, wait } from "@/utils/functions";
import type { PropType } from "vue";
const props = defineProps({
video: { type: Object as PropType<Blob | File> },
});
const emits = defineEmits(["save", "active", "completed", "error"]);
const { video } = toRefs(props);
const transcribe = useTranscription();
const { transcode } = useTranscode();
const { computedStyle, computedHighlightStyle } = useConfig();
const { currentTime, ratio } = usePlayback();
const url = computed(() => (video?.value ? URL.createObjectURL(video.value) : undefined));
const domRef = ref<HTMLDivElement>();
const CHUNK_SIZE = 4;
// todo: need to add frame extension (before & after) on sentence
const groupedTranscribe = computed(() =>
chunk(transcribe.value, CHUNK_SIZE).map((i) => i.map((j, index) => ({ ...j, end: i[index + 1]?.start ?? j.end })))
);
const currentChunk = computed(() =>
groupedTranscribe.value.find(
(i) => currentTime.value >= i[0].start / 1000 && currentTime.value <= i[i.length - 1]?.end / 1000
)
);
const step = ref(0);
const blobs = ref<Blob[]>([]);
const magicClick = async () => {
if (!domRef.value) return;
for (let i = 0; i < transcribe.value.length; i++) {
step.value = i;
await wait(1);
const c = await html2canvas(domRef.value, { backgroundColor: null });
const result = await toBlob(c);
console.log(domRef.value.innerHTML);
blobs.value.push(result as Blob);
}
};
const handleTranscode = async () => {
try {
emits("save");
emits("active", true);
await wait(500);
await magicClick();
await transcode(video?.value, blobs.value, groupedTranscribe.value.flat());
emits("completed");
} catch (err) {
console.log(err);
emits("error");
}
};
const tab = ref<"config" | "transcribe">("config");
</script>
<template>
<div>
<div ref="domRef" class="absolute text-shadow-sm -z-1" :style="[computedStyle, { transform: `scale(${ratio})` }]">
<span
:style="item.start === transcribe[step].start ? computedHighlightStyle : undefined"
v-for="item in groupedTranscribe.find((i) => i.find((j) => j.start === transcribe[step].start))"
>{{ item.text }} </span
>
</div>
<div class="flex flex-col-reverse md:flex-row items-center">
<div class="flex flex-col mr-6 mt-20 w-full">
<div class="grid grid-cols-2 rounded-full bg-gray-100 p-1.5 mx-6 overflow-hidden">
<button
class="btn"
:class="[tab == 'config' ? 'bg-white py-4 text-blue-500 shadow-xl shadow-gray-200' : 'text-gray-300']"
@click="tab = 'config'"
>
Style
</button>
<button
class="btn"
:class="[tab == 'transcribe' ? 'bg-white py-4 text-blue-500 shadow-xl shadow-gray-200' : 'text-gray-300']"
@click="tab = 'transcribe'"
>
Subtitle
</button>
</div>
<div class="mt-6 rounded-3xl mt-4 px-8 py-10 h-min drop-shadow-2xl drop-shadow-color-gray-200 bg-white">
<div>
<TranscribeConfig v-if="tab === 'config'"></TranscribeConfig>
<TranscribeSubtitle v-if="tab === 'transcribe'" :chunks="groupedTranscribe"></TranscribeSubtitle>
</div>
</div>
<div class="mt-20 mx-6">
<button class="btn btn-plain mr-4" @click="emits('save')">Save</button>
<button class="btn btn-primary" :disabled="!video" @click="handleTranscode">Transcode</button>
</div>
</div>
<div>
<Preview :url="url">
<PreviewText :chunks="groupedTranscribe"></PreviewText>
</Preview>
<PreviewControls></PreviewControls>
</div>
</div>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Loading.vue | Vue | <template>
<svg class="w-12 h-12 text-blue-500 animate-spin" width="32" height="32" viewBox="0 0 24 24">
<g fill="currentColor">
<path
fill-rule="evenodd"
d="M12 19a7 7 0 1 0 0-14a7 7 0 0 0 0 14Zm0 3c5.523 0 10-4.477 10-10S17.523 2 12 2S2 6.477 2 12s4.477 10 10 10Z"
clip-rule="evenodd"
opacity=".2"
/>
<path d="M12 22c5.523 0 10-4.477 10-10h-3a7 7 0 0 1-7 7v3ZM2 12C2 6.477 6.477 2 12 2v3a7 7 0 0 0-7 7H2Z" />
</g>
</svg>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Overlay.vue | Vue | <script setup lang="ts">
import { animate, stagger } from "motion";
const props = defineProps({ active: Boolean });
const { active } = toRefs(props);
const stripCount = 5;
const startAnimation = () => {
animate(".overlay", { display: "block" }, { duration: 0 });
animate(".strip", { width: "100%" }, { delay: stagger(0.1), duration: 0.5 });
animate(".overlay-content", { opacity: 1, scale: 1 }, { delay: 0.5, duration: 0.5 });
};
const closeAnimation = () => {
animate(".overlay-content", { opacity: 0, scale: 0 }, { duration: 0.5 });
animate(".strip", { width: "0%" }, { delay: stagger(0.1), duration: 0.5 });
animate(".overlay", { display: "none" }, { delay: 0.5 });
};
watch(active, () => {
if (active.value) {
startAnimation();
} else {
closeAnimation();
}
});
</script>
<template>
<div class="hidden overlay w-screen h-screen fixed top-0 left-0 z-100">
<div class="relative w-full h-full">
<div
v-for="i of stripCount"
class="strip bg-gray-50 absolute left-0 w-0"
:style="{ top: `${((i - 1) / 5) * 100}%`, height: `${100 / 5}vh` }"
></div>
<div class="overlay-content absolute w-full h-full flex items-center justify-center scale-0 opacity-0">
<slot>Slot content </slot>
</div>
</div>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Preview.vue | Vue | <script setup lang="ts">
defineProps({
url: String,
});
const { el, videoWidth, videoHeight, playing } = usePlayback();
const loadedVideo = () => {
videoWidth.value = el.value?.videoWidth ?? 0;
videoHeight.value = el.value?.videoHeight ?? 0;
};
</script>
<template>
<div class="relative w-120 min-h-64 h-min flex-shrink-0 overflow-hidden">
<button class="w-full" @click="playing = !playing">
<video ref="el" :src="url" class="w-full rounded-3xl border" v-show="url" @loadedmetadata="loadedVideo"></video>
<div v-if="!url" class="my-20 flex w-full items-center justify-center">
<Loading class="w-12 h-12 text-blue-500 animate-spin"></Loading>
</div>
</button>
<slot></slot>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Preview/Controls.vue | Vue | <script setup lang="ts">
import Slider from "@vueform/slider";
const { duration, currentTime, playing } = usePlayback();
const disabledTagName = ["BUTTON", "A", "INPUT"];
onKeyStroke(
" ",
(e) => {
if (
activeElement.value &&
!disabledTagName.includes(activeElement.value?.tagName) &&
!activeElement.value.hasAttribute("contenteditable")
) {
playing.value = !playing.value;
}
},
{ eventName: "keyup" }
);
const activeElement = useActiveElement();
const format = (value: number) => value.toFixed(2);
</script>
<template>
<div class="w-full flex items-center mt-8">
<button @click="playing = !playing" class="rounded-full bg-blue-100 text-blue p-1 flex items-center justify-center">
<div v-if="!playing" class="i-bx-play text-4xl"></div>
<div v-else class="i-bx-pause text-4xl"></div>
</button>
<Slider
class="ml-6 w-full"
:format="format"
v-model="currentTime"
:max="duration"
showTooltip="focus"
:step="0.001"
></Slider>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Preview/Text.vue | Vue | <script setup lang="ts">
import type { PropType } from "vue";
import type { Transcribe } from "@/utils/interface";
const props = defineProps({
chunks: Array as PropType<Transcribe[][]>,
});
const { currentTime } = usePlayback();
const { chunks } = toRefs(props);
const { computedStyle, computedHighlightStyle } = useConfig();
const timestamp = computed(() => currentTime.value * 1000);
const currentChunk = computed(() =>
chunks?.value?.find((i) => timestamp.value >= i?.[0]?.start && timestamp.value <= i?.[i.length - 1]?.end)
);
const activeTranscribe = computed(() =>
currentChunk.value?.find((i) => timestamp.value >= i.start && timestamp.value <= i.end)
);
const el = ref();
defineExpose({ el });
</script>
<template>
<p class="absolute text-shadow-sm" ref="el" :style="computedStyle" v-if="activeTranscribe">
<span
:style="activeTranscribe?.start === transribe.start ? computedHighlightStyle : undefined"
v-for="transribe in currentChunk"
>{{ transribe.text }} </span
>
</p>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Transcribe/Config.vue | Vue | <script setup lang="ts">
import Slider from "@vueform/slider";
const { config } = useConfig();
// @ts-ignore
import { ColorPicker } from "vue3-colorpicker";
// @ts-ignore
import "vue3-colorpicker/style.css";
const { videoWidth, videoHeight, ratio } = usePlayback();
</script>
<template>
<div class="flex flex-col">
<label for="size">Font Size</label>
<div class="flex items-center">
<input type="number" v-model="config.style.fontSize" min="1" name="size" id="size" />
<span class="ml-2">px</span>
</div>
<label for="weight">Font Weight</label>
<input type="number" v-model="config.style.fontWeight" step="100" max="900" min="100" name="weight" id="weight" />
<div class="w-full flex items-center space-x-4">
<div class="flex flex-col">
<label for="left">X</label>
<div class="flex items-center">
<input type="number" v-model="config.style.left" name="left" id="left" />
<span class="ml-2">px</span>
</div>
<Slider
class="mt-4"
:lazy="false"
v-model="config.style.left"
showTooltip="focus"
:min="-480"
:max="480"
></Slider>
</div>
<div class="flex flex-col">
<label for="top">Y</label>
<div class="flex items-center">
<input type="number" v-model="config.style.top" name="top" id="top" />
<span class="ml-2">px</span>
</div>
<Slider
class="mt-4"
:lazy="false"
v-model="config.style.top"
showTooltip="focus"
:min="-400"
:max="1400"
></Slider>
</div>
</div>
<div class="mt-4 grid grid-cols-3 gap-4">
<div class="flex flex-col">
<label for="bg-color">Background</label>
<ColorPicker id="bg-color" v-model:pure-color="config.style.backgroundColor" />
</div>
<div class="flex flex-col">
<label for="text-color">Text</label>
<ColorPicker id="text-color" v-model:pure-color="config.style.color" />
</div>
<div class="flex flex-col">
<label for="highlight-color">Highlight</label>
<ColorPicker id="highlight-color" v-model:pure-color="config.highlight_style.color" />
</div>
</div>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/Transcribe/Subtitle.vue | Vue | <script setup lang="ts">
import type { PropType } from "vue";
import type { Transcribe } from "@/utils/interface";
const props = defineProps({
chunks: { type: Array as PropType<Transcribe[][]>, required: true },
});
const { chunks } = toRefs(props);
const transcribe = useTranscription();
const { currentTime } = usePlayback();
const updateText = (ev: Event, item: Transcribe) => {
const value = (ev.target as HTMLDivElement)?.innerText;
const originalIndex = transcribe.value.findIndex((i) => i.start === item.start);
transcribe.value[originalIndex].text = value;
};
const currentChunk = computed(() =>
chunks.value.find((i) => currentTime.value >= i[0].start / 1000 && currentTime.value <= i[i.length - 1]?.end / 1000)
);
</script>
<template>
<div>
<ul v-if="chunks.length" class="w-full flex flex-col">
<button
v-for="transcribes in chunks"
class="p-2 mb-2 transition rounded-xl hover:bg-gray-50"
:class="{ 'bg-gray-50 ': currentChunk?.[0].start === transcribes[0].start }"
@click="currentTime = transcribes[0].start / 1000"
>
<div
class="flex text-sm mb-2 rounded-full px-3 py-1.5 transition w-max"
:class="[
currentChunk?.[0].start === transcribes[0].start ? 'bg-blue-500 text-white' : 'bg-blue-50 text-blue-500',
]"
>
<span>{{ (transcribes[0].start / 1000).toFixed(2) }}</span>
<span class="mx-2">-</span>
<span>{{ (transcribes[transcribes.length - 1].end / 1000).toFixed(2) }}</span>
</div>
<div class="flex ml-2 text-dark-200">
<div
role="textbox"
class="mr-1"
contenteditable
v-for="item in transcribes"
@input="updateText($event, item)"
>
{{ item.text }}
</div>
</div>
</button>
</ul>
<div v-else class="flex justify-center my-20 text-blue-500 animate-spin">
<Loading class="w-12 h-12"></Loading>
</div>
</div>
</template>
<style scoped lang="postcss">
div[contenteditable] {
@apply focus:px-2 focus:outline-blue-400;
}
</style>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
components/User.vue | Vue | <script setup lang="ts">
const user = useSupabaseUser();
</script>
<template>
<div>
<NuxtLink v-if="user" to="/home">
<img
class="rounded-full w-14"
referrerpolicy="no-referrer"
crossorigin="anonymous"
:src="user?.user_metadata?.avatar_url"
:alt="user?.email"
v-if="user?.user_metadata?.avatar_url"
/>
<span v-else>{{ user?.email }}</span>
</NuxtLink>
<NuxtLink v-else to="/login" class="btn-primary">Login</NuxtLink>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
composables/useConfig.ts | TypeScript | export const useConfig = () => {
const defaultConfig = {
style: {
left: 100,
top: 100,
paddingX: 14,
paddingY: 8,
borderRadius: 8,
fontSize: 20,
fontWeight: 500,
backgroundColor: "#3b82f6",
color: "#d1d5db",
},
highlight_style: {
color: "#ffffff",
},
};
const config = useState(() => defaultConfig);
const computedStyle = computed(() => ({
...config.value.style,
left: config.value.style.left + "px",
top: config.value.style.top + "px",
padding: `${config.value.style.paddingY}px ${config.value.style.paddingX}px`,
borderRadius: config.value.style.borderRadius + "px",
fontSize: config.value.style.fontSize + "px",
}));
const computedHighlightStyle = computed(() => config.value.highlight_style);
const resetConfig = () => (config.value = defaultConfig);
return {
config,
computedStyle,
computedHighlightStyle,
resetConfig,
};
};
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
composables/useCustomHead.ts | TypeScript | import { ComputedRef } from "vue";
export const useCustomHead = (
title?: string | ComputedRef<string>,
description?: string | ComputedRef<string>,
image?: string | ComputedRef<string>
) => {
useHead({
title,
meta: [
{
name: "description",
content: description ?? "An app that turns your plain video into perfect video with animated subtitle!",
},
{ name: "twitter:card", content: "summary_large_image" },
{ name: "twitter:site", content: "@zernonia" },
{ name: "twitter:title", content: title ?? "Vista | Add animated subtitle to your video automatically" },
{
name: "twitter:description",
content: description ?? "An app that turns your plain video into perfect video with animated subtitle!",
},
{ name: "twitter:image", content: image ?? "https://www.vistaeditor.com/og.png" },
{ property: "og:type", content: "website" },
{ property: "og:title", content: title ?? "Vista | Add animated subtitle to your video automatically" },
{ property: "og:url", content: "https://www.vistaeditor.com/" },
{ property: "og:image", content: image ?? "https://www.vistaeditor.com/og.png" },
{ property: "og:image:secure_url", content: image ?? "https://www.vistaeditor.com/og.png" },
{ property: "og:image:type", content: "image/png" },
{
property: "og:description",
content: description ?? "An app that turns your plain video into perfect video with animated subtitle!",
},
],
});
};
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
composables/useInMemoryFile.ts | TypeScript | export const useInMemoryFile = () => useState<{ [key: string]: File }>("new-upload", () => ({}));
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
composables/usePlayback.ts | TypeScript | export const usePlayback = () => {
const el = useState<HTMLVideoElement | null>("video-element", () => null);
const videoWidth = useState("video-width", () => 0);
const videoHeight = useState("video-height", () => 0);
const ratio = computed(() => videoWidth.value / 480);
const controls = useMediaControls(el);
return {
el,
ratio,
videoWidth,
videoHeight,
...controls,
};
};
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
composables/useSupabase.ts | TypeScript | import { Database } from "~~/utils/database.types";
export const useSupabase = () => useSupabaseClient<Database>();
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
composables/useTranscode.ts | TypeScript | import { createFFmpeg, fetchFile } from "@ffmpeg/ffmpeg";
import { chunk } from "@/utils/functions";
import type { FFmpeg } from "@ffmpeg/ffmpeg";
export const useTranscode = createSharedComposable(() => {
let ffmpeg: FFmpeg;
const message = ref("Starting");
const video = ref<string>();
const progress = ref(0);
const { config } = useConfig();
const { ratio } = usePlayback();
const CHUNK_SIZE = 10;
onMounted(() => {
ffmpeg = createFFmpeg({
log: true,
});
});
const applyOverlay = (overlay: Blob[], starting_index: number, transcribe: any) => {
const baseCmd = ["-i", starting_index === 0 ? "base.mp4" : `output-${starting_index / CHUNK_SIZE}.mp4`];
const overlayInput = overlay?.map((b, i) => ["-i", `${i + starting_index}.png`]).flat() ?? [];
const overlayCmd = overlay
? [
"-filter_complex",
overlay
.map(
(b, i) =>
`[${i === 0 ? "0:v" : "v" + i}][${i + 1}:v]overlay=${config.value.style.left * ratio.value}:${
config.value.style.top * ratio.value
}:enable='between(t,${transcribe[i + starting_index].start / 1000},${
transcribe[i + starting_index].end / 1000
})'[v${i + 1}]`
)
.join("; "),
]
: [];
const outputCmd = [
"-map",
`[v${overlay?.length}]`,
"-map",
"0:a",
"-c:a",
"copy",
`output-${starting_index / CHUNK_SIZE + 1}.mp4`,
];
// const outputCmd = ["-c:v", "copy", "-c:a", "copy", "output.mp4"];
return ffmpeg.run(...baseCmd, ...overlayInput, ...overlayCmd, ...outputCmd);
};
const transcode = async (file?: File | Blob, overlay?: Blob[], transcribe?: any) => {
try {
if (!file || !overlay || !transcribe) return;
progress.value = 0.05;
message.value = "Loading ffmeg-core.js";
if (!ffmpeg.isLoaded()) {
await ffmpeg.load();
}
message.value = "Start saving data in-memory";
progress.value = 0.1;
const start_time = new Date().getTime();
if (overlay) {
for (let i = 0; i < overlay.length; i++) {
ffmpeg.FS("writeFile", `${i}.png`, await fetchFile(overlay[i]));
}
}
ffmpeg.FS("writeFile", "base.mp4", await fetchFile(file));
const overlayChunk = chunk(overlay, CHUNK_SIZE);
for (let i = 0; i < overlayChunk.length; i++) {
message.value = `Start trancoding chunk (${i + 1}/${overlayChunk.length})`;
progress.value = 0.1 + 0.6 * ((i + 1) / overlayChunk.length);
await applyOverlay(overlayChunk[i], i * CHUNK_SIZE, transcribe);
}
progress.value = 1;
message.value = "Complete transcoding";
const data = ffmpeg.FS("readFile", `output-${overlayChunk.length}.mp4`);
video.value = URL.createObjectURL(new Blob([data.buffer], { type: "video/mp4" }));
const end_time = new Date().getTime();
console.log("Time taken", (end_time - start_time) / 1000 / 60, "minutes");
setTimeout(() => {
progress.value = 0;
}, 500);
} catch (err) {
console.log(err);
message.value = "Something wrong. Please contact Zernonia";
throw Error("Something wrong. Please contact Zernonia");
}
};
return {
transcode,
video,
message,
progress,
};
});
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
composables/useTranscription.ts | TypeScript | import { Transcribe } from "~~/utils/interface";
export const useTranscription = () => {
const transcribe = useState<Transcribe[]>("transcribe", () => []);
return transcribe;
};
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
layouts/default.vue | Vue | <script setup lang="ts"></script>
<template>
<div class="bg-white">
<div class="px-12 py-6 max-w-screen-lg mx-auto">
<header class="flex items-center justify-between">
<NuxtLink to="/" class="flex items-center">
<img class="w-12 h-12" src="~~/assets/logo.svg" alt="Vista logo" />
<span class="ml-4 font-bold text-4xl text-blue-500">Vista</span>
</NuxtLink>
<User></User>
</header>
<div class="mt-6">
<slot></slot>
</div>
</div>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
middleware/auth.ts | TypeScript | export default defineNuxtRouteMiddleware((to, _from) => {
const user = useSupabaseUser();
if (!user.value) {
return navigateTo("/login");
}
});
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
nuxt.config.ts | TypeScript | import transformerDirective from "@unocss/transformer-directives";
import { defineNuxtConfig } from "nuxt/config";
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
modules: ["@unocss/nuxt", "@vueuse/nuxt", "@nuxtjs/supabase", "@nuxt/image-edge"],
css: ["@unocss/reset/tailwind.css", "~~/assets/main.css"],
runtimeConfig: {
public: {
UMAMI_WEBSITE_ID: process.env.UMAMI_WEBSITE_ID,
},
},
unocss: {
// presets
uno: true, // enabled `@unocss/preset-uno`
icons: true, // enabled `@unocss/preset-icons`,
transformers: [transformerDirective({ enforce: "pre" })], // enabled `@unocss/transformer-directives`,
// core options
shortcuts: [
{
btn: " text-sm md:text-base font-medium rounded-full py-3 px-6 transition ring-3 ring-transparent disabled:opacity-50 relative inline-flex justify-center items-center shadow-none",
"btn-plain":
"btn bg-gray-100 hover:bg-gray-200 font-semibold text-gray-400 focus:text-dark-50 hover:text-dark-50",
"btn-primary": "btn bg-blue-500 hover:bg-blue-600 text-white focus:ring-blue-600 focus:shadow-xl",
"btn-secondary": "btn bg-white hover:bg-gray-100 focus:ring-gray-100",
"btn-danger": "btn bg-red-500 text-white hover:bg-red-600 focus:ring-red-300",
},
],
safelist: [...Array.from({ length: 5 }, (_, i) => `bg-blue-${i + 1}00`)],
rules: [],
},
image: {
domains: ["avatars0.githubusercontent.com", "avatars.githubusercontent.com/", "images.unsplash.com/"],
},
routeRules: {
"/v/**": { ssr: false },
},
build: {
transpile: process.env.NODE_ENV === "development" ? [] : ["vue3-colorpicker", "vue3-angle"],
},
});
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
pages/create.vue | Vue | <script setup lang="ts">
import { wait } from "@/utils/functions";
const { file, fileName, open } = useFileSystemAccess({
dataType: "Blob",
types: [
{
description: "Videos",
accept: {
"video/*": [".mp4", ".avi", ".wmv"],
},
},
],
excludeAcceptAllOption: true,
});
const user = useSupabaseUser();
const client = useSupabase();
const { el, duration, playing } = usePlayback();
const inMemoryFile = useInMemoryFile();
const DURATION_LIMIT = 15;
const title = ref("");
const isOffLimit = computed(() => duration.value >= DURATION_LIMIT);
const url = computed(() => (file.value ? URL.createObjectURL(file.value) : undefined));
const progress = ref(0);
const isProcessing = computed(() => progress.value !== 0);
// if non login, only max 20seconds
const uploadToStorage = async () => {
if (!file.value || !title.value) return;
try {
progress.value = 0.2;
const { data: assetData } = await client.storage
.from("assets")
.upload(`${user.value?.id}/${fileName.value}`, file.value, { upsert: true });
const { data: transcriptionData } = await client.functions.invoke("transcribe", {
body: {
video_key: assetData?.path,
},
});
progress.value = 0.6;
const { data: projectData } = await client
.from("projects")
.insert({
user_id: user.value?.id,
title: title.value,
video_key: assetData?.path,
transcription_id: transcriptionData.id,
})
.select("id")
.single();
progress.value = 1;
if (projectData?.id && url.value) {
// save in-memory file into states
await wait(300);
inMemoryFile.value[projectData.id] = file.value;
navigateTo(`/v/${projectData.id}`);
}
} catch (err) {
progress.value = 0;
console.log(err);
}
};
definePageMeta({
middleware: "auth",
});
</script>
<template>
<div>
<h1 class="my-4">Create</h1>
<div class="flex justify-center">
<button :class="[url ? 'btn-plain' : 'btn-primary my-10']" @click="open()">
Select/Drop a video (max {{ DURATION_LIMIT }}s, for now)
</button>
</div>
<div v-if="file" class="flex flex-col items-center mt-4">
<div class="max-w-screen-md m-auto">
<button @click="playing = !playing" class="border relative rounded-3xl overflow-hidden">
<video ref="el" class="max-h-screen-sm" :src="url"></video>
<div
class="overlay absolute right-0 top-0 h-full bg-opacity-30 transition-all duration-300 ease-in-out border-l-2 border-white border-opacity-50"
:class="[isProcessing ? 'bg-dark-100' : 'bg-transparent']"
:style="{ width: isProcessing ? (1 - progress) * 100 + '%' : '100%' }"
></div>
</button>
<PreviewControls></PreviewControls>
</div>
<div v-if="isOffLimit" class="text-red font-semibold my-4">
Video is too long, currently only max {{ DURATION_LIMIT }} seconds.
</div>
<div v-if="!isProcessing" class="mt-12 flex items-center">
<input type="text" class="mr-4 w-full !rounded-full !px-4 !py-3" v-model="title" placeholder="Project title" />
<button :disabled="isOffLimit || !title" @click="uploadToStorage" class="btn-primary">Upload</button>
</div>
</div>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
pages/home.vue | Vue | <script setup lang="ts">
const client = useSupabase();
const { data } = useAsyncData(async () => {
const { data } = await client.from("projects").select("id, title").order("created_at", { ascending: false });
return data;
});
definePageMeta({
middleware: "auth",
});
</script>
<template>
<div class="flex flex-col items-center justify-center">
<h1 class="my-4">My projects</h1>
<NuxtLink class="btn-primary" to="/create">Create</NuxtLink>
<div class="flex flex-col mt-12">
<NuxtLink class="btn-plain mb-3" v-for="item in data" :to="`/v/${item.id}`">
{{ item.title ?? item.id }}
</NuxtLink>
</div>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
pages/index.vue | Vue | <script setup lang="ts">
useCustomHead("Vista | Add animated subtitle to your video automatically");
</script>
<template>
<div>
<div>
<h1 class="mt-40 mb-20 text-6xl leading-tight">
Add animated subtitle <br />
to your video <span class="px-8 pt-2 pb-3 bg-blue-500 rounded-full text-white">automatically</span>
</h1>
<h2></h2>
</div>
<NuxtLink class="flex items-center justify-center" to="/create">
<video
src="https://res.cloudinary.com/zernonia/video/upload/v1673245844/Projects/Vista/original_aopjoc.mp4"
autoplay
referrerpolicy="no-referrer"
crossorigin="anonymous"
muted
class="h-128 w-min rounded-3xl shadow-xl"
loop
></video>
<div class="mx-10">
<div class="i-bx-bxs-right-arrow-circle text-6xl text-blue-500"></div>
</div>
<video
src="https://res.cloudinary.com/zernonia/video/upload/v1673245846/Projects/Vista/demo_vu9fqd.mp4"
autoplay
muted
referrerpolicy="no-referrer"
crossorigin="anonymous"
class="h-128 w-min rounded-3xl shadow-xl"
loop
></video>
</NuxtLink>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
pages/login.vue | Vue | <script setup lang="ts">
import type { Provider } from "@supabase/gotrue-js";
const client = useSupabaseAuthClient();
const user = useSupabaseUser();
const login = async (provider: Provider) => {
const { error } = await client.auth.signInWithOAuth({
provider,
options: {
redirectTo: window.location.origin + "/home",
},
});
if (error) {
console.log("Something went wrong !");
}
};
watch(
user,
() => {
if (user.value?.id) navigateTo("/home");
},
{ immediate: true }
);
</script>
<template>
<div class="flex flex-col items-center">
<h1 class="mt-20 mb-12">Login</h1>
<button @click="login('google')" class="btn-primary">Login with Google</button>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
pages/v/[id].vue | Vue | <script setup lang="ts">
const client = useSupabase();
const inMemoryFile = useInMemoryFile();
const transcribe = useTranscription();
const { config, resetConfig } = useConfig();
const { message, progress, video: renderedResult } = useTranscode();
const channel = client
.channel("public:projects")
.on("postgres_changes", { event: "UPDATE", schema: "public", table: "projects" }, (payload) => {
// @ts-ignore
data.value = payload.new;
transcribe.value = payload.new.words;
console.log(payload);
})
.subscribe();
const video = ref<Blob | File>();
const id = useRoute().params.id.toString();
const { data, pending } = useAsyncData(id, async () => {
const { data } = await client.from("projects").select("*").eq("id", id).single();
// if transcription ready, remove websocket
if (data?.words) {
// @ts-ignore
transcribe.value = data.words;
client.removeChannel(channel);
}
return data;
});
const handleSave = async () => {
await client
.from("projects")
.update({
// @ts-ignore
words: transcribe.value.length ? transcribe.value : undefined,
config: config.value,
})
.eq("id", id);
};
onUnmounted(() => {
client.removeChannel(channel);
});
onMounted(() => {
const file = inMemoryFile.value[id];
if (file) video.value = file;
});
whenever(data, async () => {
if (!data.value?.video_key || inMemoryFile.value[id]) return;
const result = await client.storage.from("assets").download(data.value.video_key);
if (result.data) video.value = result.data;
});
watch(
data,
() => {
resetConfig();
// @ts-ignore
if (data.value?.config) config.value = data.value.config;
},
{ immediate: true }
);
const isActive = ref(false);
const isCompleted = ref(false);
const isSomethingWrong = ref(false);
const handleCompleted = () => {
isCompleted.value = true;
isActive.value = false;
};
const handleError = async () => {
isSomethingWrong.value = true;
};
onMounted(() => {
window.onbeforeunload = function () {
if (isActive.value) return "You haven't saved your changes.";
};
});
definePageMeta({
middleware: "auth",
});
useCustomHead(computed(() => `Edit: ${data.value?.title ?? ""}`));
</script>
<template>
<div>
<div v-if="pending && !data" class="my-20 flex items-center justify-center">
<Loading></Loading>
</div>
<div v-else-if="!isCompleted">
<h1 class="mt-4 mb-8">{{ data?.title }}</h1>
<Edit
:video="video"
@active="isActive = $event"
@completed="handleCompleted"
@save="handleSave"
@error="handleError"
></Edit>
</div>
<Completed @edit="isCompleted = false" v-else :url="renderedResult"></Completed>
<Overlay :active="isActive">
<div class="flex" v-if="isSomethingWrong">
<div>
<p>Sorry, something is wrong</p>
<p>Please try create and transcode with this video (for demo purposes).</p>
<a
href="https://raw.githubusercontent.com/zernonia/vista/main/assets/original.mp4"
target="_blank"
class="mt-4 underline text-blue-500"
>Demo video</a
>
</div>
</div>
<div v-else class="flex flex-col">
<div class="flex rounded-full p-4 bg-white w-80 shadow-xl">
<Loading></Loading>
<div class="flex flex-col ml-6 text-blue-500">
<p class="mt-1">{{ message }}</p>
<p class="text-sm font-semibold">{{ (progress * 100).toFixed(0) }}%</p>
</div>
</div>
<div class="mt-6 px-4">
<p class="text-sm text-dark-50">While waiting, perhaps...</p>
<div class="ml-2">
<NuxtLink
class="mt-4 text-gray-300 hover:text-gray-800 transition flex items-center"
target="_blank"
to="https://github.com/zernonia/vista"
><div class="i-bx-bxl-github text-3xl mr-2"></div>
Star repo
</NuxtLink>
<NuxtLink
class="mt-1 text-gray-300 hover:text-gray-800 transition flex items-center"
target="_blank"
to="https://twitter.com/intent/tweet?original_referer=https://www.vistaeditor.com/&text=Check%20out%20Vista%20Editor%20by%20@zernonia&url=https://www.vistaeditor.com/"
><div class="i-bx-bxl-twitter text-3xl mr-2"></div>
Share on Twitter
</NuxtLink>
</div>
</div>
</div>
</Overlay>
</div>
</template>
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
server/middleware/headers.ts | TypeScript | export default defineEventHandler((event) => {
event.node.res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
event.node.res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
});
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
supabase/functions/transcribe-webhook/index.ts | TypeScript | import { serve } from "https://deno.land/std@0.131.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.2.0";
serve(async (req) => {
try {
if (req.headers.get("Authorization") !== `Bearer ${Deno.env.get("WEBHOOK_KEY")}`) throw Error("Invalid key");
const { transcript_id } = await req.json();
const supabaseClient = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
const jsonResponse = await fetch(`https://api.assemblyai.com/v2/transcript/${transcript_id}`, {
method: "GET",
headers: {
authorization: Deno.env.get("ASSEMBLY_AI_KEY") ?? "",
},
});
const jsonData = await jsonResponse.json();
console.log(jsonData);
await supabaseClient
.from("projects")
.update({
words: jsonData.words,
})
.eq("transcription_id", transcript_id);
return new Response(JSON.stringify(jsonData), { headers: { "Content-Type": "application/json" } });
} catch (err) {
console.log(err);
return new Response(JSON.stringify(err), {
headers: { "Content-Type": "application/json" },
status: 500,
});
}
});
// supabase functions deploy transcribe-webhook --no-verify-jwt
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
supabase/functions/transcribe/index.ts | TypeScript | import { serve } from "https://deno.land/std@0.131.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.2.0";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
serve(async (req) => {
try {
// This is needed if you're planning to invoke your function from a browser.
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
const { video_key } = await req.json();
const supabaseClient = createClient(Deno.env.get("SUPABASE_URL") ?? "", Deno.env.get("SUPABASE_ANON_KEY") ?? "", {
global: { headers: { Authorization: req.headers.get("Authorization")! } },
});
const { data: videoData, error: videoError } = await supabaseClient.storage
.from("assets")
.createSignedUrl(video_key, 600);
if (videoError) throw Error(videoError.message);
const jsonResponse = await fetch("https://api.assemblyai.com/v2/transcript", {
method: "POST",
headers: {
authorization: Deno.env.get("ASSEMBLY_AI_KEY") ?? "",
},
body: JSON.stringify({
audio_url: videoData?.signedUrl,
webhook_url: `${Deno.env.get("SUPABASE_FUNCTION_URL")}/transcribe-webhook`,
webhook_auth_header_name: "Authorization",
webhook_auth_header_value: `Bearer ${Deno.env.get("WEBHOOK_KEY")}`,
}),
});
const jsonData = await jsonResponse.json();
return new Response(JSON.stringify(jsonData), { headers: { ...corsHeaders, "Content-Type": "application/json" } });
} catch (err) {
console.log(err);
return new Response(JSON.stringify(err), {
headers: { ...corsHeaders, "Content-Type": "application/json" },
status: 500,
});
}
});
// supabase functions deploy transcribe
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
utils/database.types.ts | TypeScript | export type Json =
| string
| number
| boolean
| null
| { [key: string]: Json }
| Json[]
export interface Database {
public: {
Tables: {
projects: {
Row: {
id: string
user_id: string | null
created_at: string | null
video_key: string | null
transcription_id: string | null
words: Json[] | null
title: string | null
config: Json | null
}
Insert: {
id?: string
user_id?: string | null
created_at?: string | null
video_key?: string | null
transcription_id?: string | null
words?: Json[] | null
title?: string | null
config?: Json | null
}
Update: {
id?: string
user_id?: string | null
created_at?: string | null
video_key?: string | null
transcription_id?: string | null
words?: Json[] | null
title?: string | null
config?: Json | null
}
}
users: {
Row: {
id: string
updated_at: string | null
username: string | null
full_name: string | null
avatar_url: string | null
}
Insert: {
id: string
updated_at?: string | null
username?: string | null
full_name?: string | null
avatar_url?: string | null
}
Update: {
id?: string
updated_at?: string | null
username?: string | null
full_name?: string | null
avatar_url?: string | null
}
}
}
Views: {
[_ in never]: never
}
Functions: {
[_ in never]: never
}
Enums: {
[_ in never]: never
}
}
}
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
utils/functions.ts | TypeScript | export const chunk = <T>(array: T[], size: number) =>
Array.from({ length: Math.ceil(array.length / size) }, (value, index) =>
array.slice(index * size, index * size + size)
);
export const wait = (m: number) => new Promise((r) => setTimeout(r, m));
export const toBlob = (canvas: HTMLCanvasElement): Promise<Blob> =>
new Promise((resolve, reject) => {
canvas.toBlob((result) => {
resolve(result as Blob);
});
});
export const downloadBlob = (blobUrl: string, name = "output.mp4") => {
// Create a link element
const link = document.createElement("a");
// Set link's href to point to the Blob URL
link.href = blobUrl;
link.download = name;
// Append link to the body
document.body.appendChild(link);
// Dispatch click event on the link
// This is necessary as link.click() does not work on the latest firefox
link.dispatchEvent(
new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window,
})
);
// Remove link from body
document.body.removeChild(link);
};
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
utils/interface.ts | TypeScript | import { StyleValue } from "nuxt/dist/app/compat/capi";
export interface Transcribe {
text: string;
modified_text?: string;
start: number;
end: number;
confidence: number;
}
export interface Config {
style: StyleValue;
highlight_style: StyleValue;
}
| zernonia/vista | 107 | Add animated subtitle to your video automatically | Vue | zernonia | zernonia | Troop Travel |
app.vue | Vue | <script setup lang="ts">
</script>
<template>
<UiTooltipProvider>
<NuxtLoadingIndicator color="hsl(var(--primary))" />
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</UiTooltipProvider>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
assets/css/tailwind.css | CSS | @tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--primary: 222.2 47.4% 11.2%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--ring: 222.2 84% 4.9%;
--radius: 0.65rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--ring: 212.7 26.8% 83.9%;
}
}
@layer base {
* {
@apply border-border antialiased;
}
html {
font-family: 'Inter', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"
}
body {
@apply bg-background text-foreground;
}
} | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/DialogAction.vue | Vue | <script setup lang="ts">
defineProps<{
title?: string
description?: string
}>()
</script>
<template>
<UiDialog>
<UiDialogTrigger v-if="$slots.default" as-child>
<slot />
</UiDialogTrigger>
<UiDialogContent>
<UiDialogHeader v-if="title || description">
<UiDialogTitle v-if="title">
{{ title }}
</UiDialogTitle>
<UiDialogDescription v-if="description">
{{ description }}
</UiDialogDescription>
</UiDialogHeader>
<slot name="body" />
<UiDialogFooter v-if="$slots.footer" class="sm:justify-center">
<slot name="footer" />
</UiDialogFooter>
</UiDialogContent>
</UiDialog>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/DialogDelete.vue | Vue | <script setup lang="ts">
defineProps<{
title?: string
description?: string
}>()
</script>
<template>
<UiAlertDialog>
<UiAlertDialogTrigger as-child>
<slot />
</UiAlertDialogTrigger>
<UiAlertDialogContent>
<UiAlertDialogHeader>
<UiAlertDialogTitle>{{ title }}</UiAlertDialogTitle>
<UiAlertDialogDescription>{{ description }}</UiAlertDialogDescription>
</UiAlertDialogHeader>
<UiAlertDialogFooter>
<slot name="footer" />
</UiAlertDialogFooter>
</UiAlertDialogContent>
</UiAlertDialog>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/GeneratedList.vue | Vue | <script setup lang="ts">
const props = defineProps<{
data: DBComponent[] | null
}>()
const PAGE_SIZE = 15
const total = computed(() => (props.data?.length ?? 0))
const { currentPage } = useOffsetPagination({
total,
page: 1,
pageSize: PAGE_SIZE,
})
const currentPageData = computed(() => props.data?.slice(((currentPage.value - 1) * PAGE_SIZE), (currentPage.value * PAGE_SIZE)))
</script>
<template>
<div>
<div v-if="data?.length" class="w-full md:px-4 grid md:grid-cols-3 gap-4 md:gap-8 max-w-[1200px] mx-auto">
<NuxtLink
v-for="item in currentPageData"
:key="item.id"
:to="`/t/${item.slug}`"
>
<UiCard class="shadow-none hover:shadow-lg hover:outline-primary overflow-hidden outline-transparent outline outline-1 transition-all flex">
<UiCardContent class="w-full h-full p-0">
<UiAspectRatio :ratio="16 / 9">
<img :src="`/api/image/${item.id}`" class="w-full h-full object-cover">
</UiAspectRatio>
</UiCardContent>
</UiCard>
<UiTooltip>
<div class="px-4 py-2 flex gap-2 items-center w-full">
<UiAvatar v-if="item.user" class="w-6 h-6 flex-shrink-0">
<UiAvatarImage :src="item.user.avatarUrl ?? ''" />
<UiAvatarFallback>{{ item.user.name?.slice(0, 1) }}</UiAvatarFallback>
</UiAvatar>
<UiTooltipTrigger as="div">
<p class="text-sm line-clamp-1 overflow-hidden">
{{ item.description }}
</p>
</UiTooltipTrigger>
<UiTooltipContent class="max-w-64 text-sm">
{{ item.description }}
</UiTooltipContent>
</div>
</UiTooltip>
</NuxtLink>
</div>
<div v-if="data?.length" class="w-full flex mt-8 mb-4 justify-center">
<UiPagination v-model:page="currentPage" :total="total" :sibling-count="1" :items-per-page="PAGE_SIZE">
<UiPaginationList v-slot="{ items }" class="flex items-center gap-2">
<UiTooltip>
<UiTooltipTrigger>
<UiPaginationFirst />
</UiTooltipTrigger>
<UiTooltipContent>
Go to first page
</UiTooltipContent>
</UiTooltip>
<UiTooltip>
<UiTooltipTrigger>
<UiPaginationPrev />
</UiTooltipTrigger>
<UiTooltipContent>
Go to previous page
</UiTooltipContent>
</UiTooltip>
<template v-for="(item, index) in items">
<UiPaginationListItem v-if="item.type === 'page'" :key="index" :value="item.value" as-child>
<UiButton class="w-10 h-10 p-0" :variant="item.value === currentPage ? 'default' : 'outline'">
{{ item.value }}
</UiButton>
</UiPaginationListItem>
<UiPaginationEllipsis v-else :key="item.type" :index="index" />
</template>
<UiTooltip>
<UiTooltipTrigger>
<UiPaginationNext />
</UiTooltipTrigger>
<UiTooltipContent>
Go to next page
</UiTooltipContent>
</UiTooltip>
<UiTooltip>
<UiTooltipTrigger>
<UiPaginationLast />
</UiTooltipTrigger>
<UiTooltipContent>
Go to last page
</UiTooltipContent>
</UiTooltip>
</UiPaginationList>
</UiPagination>
</div>
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/Loading.vue | Vue | <script setup lang="ts">
import { cva } from 'class-variance-authority'
import { Loader2 } from 'lucide-vue-next'
defineProps<{
size?: NonNullable<Parameters<typeof loaderVariants>[0]>['size']
}>()
const loaderVariants = cva(
'animate-spin',
{
variants: {
size: {
default: 'h-6 w-6',
sm: 'h-4 w-4',
lg: 'h-9 w-9',
},
},
defaultVariants: {
size: 'default',
},
},
)
</script>
<template>
<Loader2 :class="cn(loaderVariants({ size }), $attrs.class ?? '')" />
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/Logo.vue | Vue | <script setup lang="ts">
</script>
<template>
<svg width="100%" height="100%" viewBox="0 0 197 197" fill="none" xmlns="http://www.w3.org/2000/svg">
<path class="scale-100 group-hover:scale-125 origin-center transition duration-500" d="M159 85.5C159 119.466 131.466 147 97.5 147C63.5345 147 36 119.466 36 85.5C36 51.5345 63.5345 24 97.5 24C131.466 24 159 51.5345 159 85.5Z" fill="#262626" />
<path d="M180.939 32.8358L98.0596 176.356L15.18 32.8358H82.2288L96.4718 57.3807L98.0596 60.1169L99.6474 57.3806L113.89 32.8358H180.939ZM96.474 121.356L98.0604 124.074L99.6455 121.355L134.814 61.0279L136.423 58.2676H133.228H101.457H100.452L99.9102 59.1153L98.051 62.0264L96.1663 59.1076L95.6239 58.2676H94.6241H62.8538H59.657L61.2683 61.0287L96.474 121.356Z" fill="white" stroke="#262626" stroke-width="3.67152" />
</svg>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/OgImage/Generated.vue | Vue | <script setup lang="ts">
withDefaults(defineProps<{
title?: string
avatarUrl?: string
imageUrl?: string
}>(), {
title: 'title',
})
</script>
<template>
<div class="relative h-full w-full flex items-center justify-center bg-slate-100">
<div class="flex items-center justify-center w-full h-full">
<img :src="imageUrl" class="w-[48rem] h-[27rem] mb-12 border border-solid border-slate-200 rounded-2xl overflow-hidden">
</div>
<div class="absolute bottom-8 left-8 flex items-center">
<img :src="avatarUrl" class="flex-shrink-0 w-32 h-32 rounded-full overflow-hidden">
<p class="max-w-[1000px] text-balance text-4xl font-semibold ml-6">
{{ title }}
</p>
</div>
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/Output.client.vue | Vue | <!-- eslint-disable vue/one-component-per-file -->
<script setup lang="ts">
import { computed, defineComponent, ref, watch } from 'vue'
import { compileScript, parse } from '@vue/compiler-sfc'
import * as Icon from 'lucide-vue-next'
import { useToast } from '@/components/ui/toast'
const props = defineProps<{
sfcString: string
errorMessage: string | null | undefined
}>()
const files = import.meta.glob('../components/ui/**/*.ts', { eager: true })
const Comp = computed(() => {
if (props.errorMessage) {
return defineComponent({
template: `<div class="w-screen h-screen flex items-center justify-center text-destructive"><div>Error: ${props.errorMessage}</div></div>`,
})
}
const [_, templateString] = props?.sfcString?.split('<template>')
if (!templateString || !props?.sfcString) {
return defineComponent({
template: '<div class="w-screen h-screen flex items-center justify-center"><div>Generating...</div></div>',
})
}
const { descriptor } = parse(props?.sfcString)
const template = parseTemplate(templateString ?? '')
const script = compileScript(descriptor, { id: '123' })
const components = {}
Object.entries(script.imports!).forEach(async ([key, value]) => {
if (value.source === 'lucide-vue-next')
// @ts-expect-error ignore ts
components[key] = Icon[key]
if (value.source.includes('components/ui')) {
const path = `${value.source.replace('@/components/', './')}/index.ts`
// @ts-expect-error ignore ts
components[key] = files[path]?.[key]
}
})
const otherNodes = script.scriptSetupAst?.filter(i => i.type !== 'ImportDeclaration')
const variableNodes = script.scriptSetupAst?.filter(i => i.type === 'VariableDeclaration')
const returnedValue: string[] = []
variableNodes?.forEach((node) => {
if ('declarations' in node) {
const childNode = node.declarations[0].id
switch (childNode.type) {
case 'Identifier': {
returnedValue.push(childNode.name)
break
}
case 'ObjectPattern': {
if (childNode.properties[0].type === 'ObjectProperty' && childNode.properties[0].value.type === 'Identifier')
returnedValue.push(childNode.properties[0].value.name)
break
}
default: {
// very bad manual parsing.. not sure if there's a better way
}
}
}
})
// no-eval allow eval temporarily
// eslint-disable-next-line no-eval
const setupString = eval(`({ setup() {
${otherNodes?.map(node => `${script.loc.source.slice(node.start!, node.end!)}\n`).join('')}
return { ${returnedValue.join(',')} }
}})`)
console.log({
setupString,
template,
})
return defineComponent({
components,
setup: setupString?.setup,
template: template ?? '<div class="w-screen h-screen flex items-center justify-center"><div>Empty</div></div>',
})
})
</script>
<template>
<Comp />
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/OutputCode.client.vue | Vue | <script setup lang="ts">
import { getHighlighter } from 'shikiji'
const props = defineProps<{
sfcString: string
}>()
const highlighter = await getHighlighter({
langs: ['vue'],
themes: [
{
name: 'my-theme',
settings: [
{
scope: 'string',
settings: {
foreground: '#00D8FF',
},
},
{
scope: 'entity.other.attribute-name',
settings: {
foreground: '#E62286',
},
},
{
scope: 'keyword',
settings: {
foreground: '#9f9f9f',
},
},
{
scope: 'comment',
settings: {
foreground: '#9f9f9f',
},
},
],
bg: 'hsl(var(--primary))',
fg: 'hsl(var(--secondary))',
},
],
})
const code = computed(() => highlighter.codeToHtml(props.sfcString, {
lang: 'vue',
theme: 'my-theme',
}))
</script>
<template>
<div class="text-sm px-6 pb-6 absolute w-full overflow-y-auto h-full z-[100] bg-primary text-primary-foreground" v-html="code" />
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/OutputWrapper.vue | Vue | <script setup lang="ts">
</script>
<template>
<NuxtErrorBoundary>
<Suspense>
<slot />
<template #fallback>
<p> loading...</p>
</template>
</Suspense>
<template #error="{ error }">
<p>An error occurred: {{ error }}</p>
</template>
</NuxtErrorBoundary>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/PromptInput.vue | Vue | <script setup lang="ts">
import { SparklesIcon } from 'lucide-vue-next'
const props = defineProps<{
modelValue?: string
loading?: boolean
disabled?: boolean
placeholder?: string
}>()
const emits = defineEmits<{
'update:modelValue': [payload: string]
'submit': [prompt: string]
}>()
const modelValue = useVModel(props, 'modelValue', emits, {
passive: true,
})
const { textarea, input } = useTextareaAutosize()
const textareaFocused = ref(false)
// @ts-expect-error based on docs it shouldn't need 3rd argument
syncRef(input, modelValue)
useMagicKeys({
passive: false,
onEventFired(e) {
// only trigger on slash and blurred
if (e.code === 'Slash' && e.type === 'keydown' && document.activeElement !== textarea.value) {
e.preventDefault()
textarea.value?.focus()
}
},
})
</script>
<template>
<div class="flex items-end px-2 md:px-4 py-2 text-sm border rounded-lg text-muted-foreground bg-muted focus-within:ring-1 focus-within:ring-primary">
<textarea
ref="textarea"
v-model="input"
:disabled="loading || disabled"
class="outline-none resize-none my-1 h-[20px] no-scrollbar font-medium w-full md:min-w-[26rem] bg-transparent px-1"
:placeholder="`${placeholder}. ${textareaFocused ? '(Press ‘Cmd+Enter‘ to generate)' : '(Press ‘/‘ to type)'}`"
@focus="textareaFocused = true"
@blur="textareaFocused = false"
@keydown.meta.enter="emits('submit', input)"
@keydown.ctrl.enter="emits('submit', input)"
/>
<UiTooltip :delay-duration="100">
<UiTooltipTrigger as-child>
<UiButton size="icon" class="ml-4 mb-0.5 p-0 w-6 h-6 rounded" variant="ghost" :loading="loading" :disabled="disabled || loading || !input?.length" @click="emits('submit', input)">
<SparklesIcon class="p-0.5" />
</UiButton>
</UiTooltipTrigger>
<UiTooltipContent>
Click to submit prompt
</UiTooltipContent>
</UiTooltip>
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/UserMenu.vue | Vue | <script setup lang="ts">
import { Bug, GalleryThumbnails, Github, LogOut, Menu, MessageCircleQuestion } from 'lucide-vue-next'
const openaiKey = useOpenAIKey()
const { loggedIn, user, clear } = useUserSession()
</script>
<template>
<UiDropdownMenu>
<UiDropdownMenuTrigger as-child>
<UiButton class="relative flex-shrink-0 rounded-full" size="icon" variant="secondary">
<div class=" rounded-full overflow-hidden">
<Menu v-if="!loggedIn" class="p-1" />
<img v-else-if="user.avatar_url" :src="user.avatar_url" class="w-full h-full">
</div>
<div v-if="!openaiKey" class="absolute -bottom-0.5 -left-1">
<div class="w-3 h-3 rounded-full bg-green-500" />
<div class="w-3 h-3 absolute top-0 rounded-full bg-green-400 animate-ping" />
</div>
</UiButton>
</UiDropdownMenuTrigger>
<UiDropdownMenuContent align="end" class="w-64">
<UiDropdownMenuItem v-if="!loggedIn" as-child>
<a href="/api/auth/github" @click="umTrackEvent('login')">
<Github class="mr-2 h-4 w-4" />
<span>Login with GitHub</span>
</a>
</UiDropdownMenuItem>
<UiDropdownMenuGroup v-if="loggedIn">
<UiDropdownMenuLabel class="text-xs">
OpenAI Key *
</UiDropdownMenuLabel>
<div class="px-1 pb-1">
<UiInput v-model="openaiKey" placeholder="sk-************ (Required)" />
</div>
</UiDropdownMenuGroup>
<UiDropdownMenuSeparator />
<UiDropdownMenuItem v-if="user" as-child>
<NuxtLink :to="`/${user.login}`">
<GalleryThumbnails class="mr-2 h-4 w-4" />
<span>Gallery</span>
</NuxtLink>
</UiDropdownMenuItem>
<UiDropdownMenuItem as-child>
<NuxtLink to="/faq">
<MessageCircleQuestion class="mr-2 h-4 w-4" />
<span>FAQs</span>
</NuxtLink>
</UiDropdownMenuItem>
<UiDropdownMenuItem as-child>
<NuxtLink to="https://github.com/zernonia/vue0/issues/new?labels=bug&title=New+bug+report" target="_blank">
<Bug class="mr-2 h-4 w-4" />
<span>Report an issue</span>
</NuxtLink>
</UiDropdownMenuItem>
<template v-if="loggedIn">
<UiDropdownMenuSeparator />
<UiDropdownMenuItem @click="clear">
<LogOut class="mr-2 h-4 w-4" />
<span>Log out</span>
</UiDropdownMenuItem>
</template>
</UiDropdownMenuContent>
</UiDropdownMenu>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/ui/accordion/Accordion.vue | Vue | <script setup lang="ts">
import {
AccordionRoot,
type AccordionRootEmits,
type AccordionRootProps,
useEmitAsProps,
} from 'radix-vue'
const props = defineProps<AccordionRootProps>()
const emits = defineEmits<AccordionRootEmits>()
</script>
<template>
<AccordionRoot v-bind="{ ...props, ...useEmitAsProps(emits) }">
<slot />
</AccordionRoot>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.