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
postcss.config.js
JavaScript
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, }
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend
tailwind.config.js
JavaScript
import type { Config } from 'tailwindcss' const config: Config = { content: [ './app/**/*.{js,ts,jsx,tsx,mdx}', // Note the addition of the `app` directory. './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}', // Or if using `src` directory: './src/**/*.{js,ts,jsx,tsx,mdx}', ], theme: { extend: {}, }, plugins: [], } export default config
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend
app.vue
Vue
<script setup lang="ts"> import { createFocusTrap } from "focus-trap" useHead({ charset: "utf-8", titleTemplate: (title) => `${title} | KeyPress`, link: [{ rel: "icon", href: "/logo.svg" }], }) onMounted(() => { const trap = createFocusTrap("body", { escapeDeactivates: false }) trap.activate() }) </script> <template> <div class="relative"> <NuxtLayout> <NuxtPage></NuxtPage> </NuxtLayout> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
app/router.options.ts
TypeScript
import type { RouterOptions } from "@nuxt/schema" // https://router.vuejs.org/api/interfaces/routeroptions.html export default <RouterOptions>{ routes: (_routes) => { const { ssrContext } = useNuxtApp() const subdomain = useSubdomain() if (ssrContext?.event.context.subdomain) subdomain.value = ssrContext?.event.context.subdomain if (subdomain.value) { const userRoute = _routes.filter((i) => i.path.includes("/user/:siteId")) const userRouteMapped = userRoute.map((i) => ({ ...i, path: i.path === "/user/:siteId" ? i.path.replace("/user/:siteId", "/") : i.path.replace("/user/:siteId/", "/"), })) return userRouteMapped } }, scrollBehavior(to, from, savedPosition) { if (savedPosition) return savedPosition if (to.hash) { const el = document.querySelector(to.hash) as HTMLElement return { left: 0, top: (el?.offsetTop ?? 0) - 30, behavior: "smooth" } } if (to.fullPath === from.fullPath) return return { left: 0, top: 0, behavior: "smooth" } }, }
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
assets/main.css
CSS
/* for easy focus tracking */ button:not(:where(.not-default, [data-tippy-root])), a:not(:where(.not-default, [data-tippy-root])) { outline: 2px solid transparent; outline-offset: 15px; transition: 0.3s all ease !important; } button:not(:where(.not-default)):focus, a:not(:where(.not-default)):focus { outline-offset: 2px; outline: 2px solid #2d2d2d; border-radius: 1rem; } html { scroll-behavior: smooth; } body { @apply text-dark-300 overflow-x-hidden; } ::-moz-selection { /* Code for Firefox */ @apply bg-gray-200; } ::selection { @apply bg-gray-200; } ::-webkit-scrollbar { @apply bg-light-300 w-6px h-6px md:w-8px md:h-8px; } ::-webkit-scrollbar-thumb { @apply rounded-xl transition bg-light-900; } ::-webkit-scrollbar-thumb:hover { @apply bg-gray-300; } ::-webkit-scrollbar-track { @apply rounded-xl bg-transparent; } kbd { height: 20px; width: 20px; border-radius: 4px; padding: 0 4px; display: flex; align-items: center; justify-content: center; font-family: inherit; @apply text-gray-400 bg-light-300; } kbd:first-of-type { margin-left: 8px; } input[type="text"]:not(:where(.not-default)), input[type="url"]:not(:where(.not-default)) { @apply flex items-center rounded-2xl w-full h-10 py-1 md:py-2 px-5 bg-light-300 placeholder-gray-400 outline-none transition ring-3 ring-transparent !focus-within:ring-gray-400; } .fade-enter-active, .fade-leave-active { transition: all 0.3s ease-in-out; } .fade-enter-from, .fade-leave-to { opacity: 0; } .fade-enter-active .inner, .fade-leave-active .inner { transition: all 0.3s ease-in-out; } .fade-enter-from .inner, .fade-leave-to .inner { opacity: 0; transform: scale(0); } .slide-in-right-enter-active, .slide-in-right-leave-active { transition: all 0.3s ease-in-out; } .slide-in-right-enter-from, .slide-in-right-leave-to { opacity: 0; transform: translateX(300px); } .command-dialog-enter-active, .command-dialog-leave-active { transition: all 0.2s ease-in-out; } .command-dialog-enter-from, .command-dialog-leave-to { opacity: 0; transform: scale(0.95); } .prose :where(iframe):not(:where(.not-prose, .not-prose *)) { width: 100%; max-width: 100%; } /* .prose pre { background: #0d0d0d; color: #fff; font-family: "JetBrainsMono", monospace; padding: 0.75rem 1rem; border-radius: 0.5rem; } */ .hljs-comment, .hljs-quote { color: #616161; } .hljs-variable, .hljs-template-variable, .hljs-attribute, .hljs-tag, .hljs-name, .hljs-regexp, .hljs-link, .hljs-name, .hljs-selector-id, .hljs-selector-class { color: #f98181; } .hljs-number, .hljs-meta, .hljs-built_in, .hljs-builtin-name, .hljs-literal, .hljs-type, .hljs-params { color: #fbbc88; } .hljs-string, .hljs-symbol, .hljs-bullet { color: #b9f18d; } .hljs-title, .hljs-section { color: #faf594; } .hljs-keyword, .hljs-selector-tag { color: #70cff8; } .hljs-emphasis { font-style: italic; } .hljs-strong { font-weight: 700; }
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Button.vue
Vue
<script setup lang="ts"> defineProps({ loading: Boolean, }) </script> <template> <button :data-loading="loading" :disabled="loading" class="btn-loader" v-bind="$attrs"> <slot></slot> </button> </template> <style> .btn-loader[data-loading="true"]::before, [data-loading] [data-type="submit"] .formkit-input::before { -webkit-animation: rotate 0.5s linear infinite; animation: rotate 0.5s linear infinite; width: 1rem; border: 0.1428571429em solid #fff; border-right-color: transparent; margin-right: 0.75em; } .btn-loader::before, [data-type="submit"] .formkit-input::before { box-sizing: border-box; content: ""; width: 0; margin-right: 0; height: 1rem; border: 0 solid transparent; border-radius: 1rem; transition: width 0.25s, border 0.25s, margin-right 0.25s; } @-ms-keyframes rotate { from { -ms-transform: rotate(0deg); } to { -ms-transform: rotate(360deg); } } @-moz-keyframes rotate { from { -moz-transform: rotate(0deg); } to { -moz-transform: rotate(360deg); } } @-webkit-keyframes rotate { from { -webkit-transform: rotate(0deg); } to { -webkit-transform: rotate(360deg); } } @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } </style>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Command.vue
Vue
<script lang="ts" setup> import { useFuse } from "@vueuse/integrations/useFuse" const router = useRouter() const user = useSupabaseUser() const subdomain = useSubdomain() const url = useUrl() const keys = useMagicKeys() const CmdK = keys["Meta+K"] const Escape = keys["Escape"] const isVisible = useState("command-visible", () => false) watch(CmdK, (v) => { if (v) { isVisible.value = !isVisible.value } }) watch(Escape, () => (isVisible.value = false)) const navAction = (path: string) => { router.push(path) isVisible.value = false searchTerm.value = "" } const navList = computed(() => subdomain.value ? [ { label: "Home", value: "home", action: () => navAction("/"), show: true }, { label: "Write", value: "write", action: () => (window.location.href = url + "/write"), show: true, }, { label: "Login", value: "login", action: () => (window.location.href = url + "/login"), show: !user.value?.id, }, { label: "Dashboard", value: "dashboard", action: () => (window.location.href = url + "/dashboard/posts"), show: user.value?.id, }, { label: "KeyPress", value: "keypress", action: () => (window.location.href = url), show: true, }, ] : [ { label: "Home", value: "home", action: () => navAction("/"), show: true }, { label: "Write", value: "write", action: () => navAction("/write"), show: true }, { label: "Posts", value: "posts", action: () => navAction("/posts"), show: true }, { label: "Login", value: "login", action: () => navAction("/login"), show: !user.value?.id }, { label: "Dashboard", value: "dashboard", action: () => navAction("/dashboard/posts"), show: user.value?.id }, ] ) const searchTerm = ref("") const { results } = useFuse( searchTerm, navList.value.filter((i) => i.show), { fuseOptions: { keys: ["label"], }, matchAllWhenSearchEmpty: true, } ) </script> <template> <div> <button class="btn-plain" @click="isVisible = true">⌘K</button> <Modal class="!items-start" inner-class="!max-w-screen-sm rounded-xl mt-48" v-model:open="isVisible"> <div class="p-2"> <div> <input type="text" class="not-default p-2 w-full focus-visible:outline-none text-sm" v-model="searchTerm" placeholder="Search for commands..." /> </div> <div class="py-6"> <ul v-if="results?.length"> <div class="text-xs p-2">Navigation</div> <li v-for="{ item } in results"> <button @click="item.action()" class="not-default outline-none bg-transparent focus-visible:bg-light-300 rounded-lg transition-all p-2 my-0.5 w-full text-left text-sm" > {{ item.label }} </button> </li> </ul> <div v-else class="p-8 text-sm text-center">No results found.</div> </div> </div> </Modal> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Drawer.vue
Vue
<script setup lang="ts"> import { useFocusTrap } from "@vueuse/integrations/useFocusTrap" const props = defineProps({ open: Boolean, confirmAction: Function }) const emits = defineEmits(["update:open"]) const el = ref() onClickOutside(el, () => { emits("update:open", !props.open) }) const { activate, deactivate } = useFocusTrap(el) onKeyStroke("Escape", () => emits("update:open", false)) watch( () => props.open, (n) => nextTick(() => (n ? activate() : deactivate())), { immediate: true } ) </script> <template> <transition name="slide-in-right"> <div v-if="open" class="fixed top-0 left-0 w-screen h-screen z-100 flex justify-end"> <div ref="el" class="inner w-full max-w-112 ml-8 bg-white rounded-xl shadow-xl overflow-hidden"> <slot>Content</slot> </div> </div> </transition> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Drawer/EditPost.vue
Vue
<script setup lang="ts"> import { PropType } from "vue" const props = defineProps({ show: Boolean, settings: Object as PropType<{ image: string active: boolean tags: string[] }>, }) const emits = defineEmits(["update:show"]) const { settings } = toRefs(props) watch( () => props.show, () => { if (!props.show) { const editorEl = document.querySelector(".content .ProseMirror") as HTMLDivElement if (editorEl) editorEl.focus() } } ) </script> <template> <Drawer :open="show" @update:open="emits('update:show', $event)"> <div class="flex flex-col px-4 py-12"> <h2 class="text-3xl font-bold">Settings</h2> <div class="mt-8"> <Toggle class="mt-4" v-model="settings.active">Publish</Toggle> </div> <div class="mt-8"> <label for="url">Cover image: </label> <Upload class="mt-4" v-model="settings.image"></Upload> </div> <div class="mt-8"> <label for="url">Tags: </label> <TagsInput class="mt-4" v-model="settings.tags"></TagsInput> </div> </div> </Drawer> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Footer.vue
Vue
<script setup lang="ts"> const url = useUrl() </script> <template> <div class="max-w-screen-lg mx-auto"> <footer class="mt-12 py-6 border-t-2 border-light-700 flex flex-col sm:flex-row justify-between"> <div> <NuxtLink class="flex items-center font-bold text-xl text-dark-300" to="/" ><NuxtImg src="/banner.png" class="w-auto h-10 mr-4"></NuxtImg> </NuxtLink> </div> <div class="mt-4 sm:mt-0 flex text-sm sm:text-base space-x-6"> <ul> <h5 class="pr-10 mb-4 font-semibold text-dark-50">Menu</h5> <li class="py-0.5"> <NuxtLink class="text-gray-400 hover:text-dark-300 transition" :to="`${url}/write`">Write</NuxtLink> </li> <li class="py-0.5"> <NuxtLink class="text-gray-400 hover:text-dark-300 transition" :to="`${url}/posts`">All Posts</NuxtLink> </li> <li class="py-0.5"> <NuxtLink class="text-gray-400 hover:text-dark-300 transition" :to="`${url}/login`">Login</NuxtLink> </li> </ul> <ul> <h5 class="pr-10 mb-4 font-semibold text-dark-50">Open Source</h5> <li class="py-0.5"> <NuxtLink class="text-gray-400 hover:text-dark-300 transition" to="https://github.com/zernonia/keypress" target="_blank" >GitHub</NuxtLink > </li> </ul> </div> </footer> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Loader.vue
Vue
<template> <div class="my-20 flex flex-col justify-center w-full items-center"> <Logo class="w-12 h-12 animate-spin animate-duration-1500 animate-ease-in-out"></Logo> <div class="mt-12 font-medium text-gray-400 flex"> <p class="mr-2">Tips:</p> <p>⌘ + K to search for commands</p> </div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Logo.vue
Vue
<script setup lang="ts"></script> <template> <svg viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M0 50C0 8.825 8.825 0 50 0C91.175 0 100 8.825 100 50C100 91.175 91.175 100 50 100C8.825 100 0 91.175 0 50Z" fill="#2D2D2D" /> <path d="M29.4375 30.4688H46.25V72.9375H29.4375V30.4688ZM51.4375 42.0312C51.4375 37.4271 52.6042 34.3333 54.9375 32.75C57.1458 31.2708 61.3021 30.5312 67.4062 30.5312H70.5625V36.4375C70.5625 41.1458 69.3646 44.5 66.9688 46.5C64.5312 48.5 60.3333 49.5 54.375 49.5H51.4375V42.0312ZM51.4375 52.75H54.375C60.25 52.75 64.4479 53.9167 66.9688 56.25C69.3646 58.4792 70.5625 62 70.5625 66.8125V73H67.4062C61.4271 73 57.2708 72.1042 54.9375 70.3125C52.6042 68.5 51.4375 65.25 51.4375 60.5625V52.75Z" fill="white" /> </svg> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Modal.vue
Vue
<script setup lang="ts"> import { useFocusTrap } from "@vueuse/integrations/useFocusTrap" const props = defineProps({ open: Boolean, confirmAction: Function, innerClass: String }) const emits = defineEmits(["update:open"]) const el = ref() onClickOutside(el, () => { emits("update:open", !props.open) }) const { activate, deactivate } = useFocusTrap(el, { immediate: true }) onKeyStroke("Escape", () => emits("update:open", false)) watch( () => props.open, (n) => nextTick(() => (n ? activate() : deactivate())) ) </script> <template> <transition name="command-dialog"> <div v-if="open" class="fixed top-0 left-0 w-screen h-screen z-300 flex items-center justify-center"> <div ref="el" class="inner w-full mx-4 max-w-112 bg-white rounded-2xl shadow-xl overflow-hidden" :class="innerClass" > <slot>Content</slot> </div> </div> </transition> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Modal/Login.vue
Vue
<script setup lang="ts"> const client = useSupabaseClient() defineProps({ show: Boolean, }) const emits = defineEmits(["update:show"]) const signIn = async () => { const { user } = await client.auth.signIn({ provider: "github" }) } </script> <template> <Modal :open="show" @update:open="emits('update:show', $event)"> <div class="flex flex-col items-center px-6 py-12"> <h1 class="text-4xl font-bold text-center">Login</h1> <button autofocus class="btn-primary w-max mt-6" @click="signIn">Login with GitHub</button> </div> </Modal> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Post/Card.vue
Vue
<script setup lang="ts"> import { stripHtml } from "string-strip-html"; import { format } from "date-fns"; import { PropType } from "vue"; import { Posts } from "~~/utils/types"; import { constructUrl } from "~~/utils/functions"; const props = defineProps({ subdomain: Boolean, post: Object as PropType<Posts>, }); const url = computed(() => constructUrl(props.post, props.subdomain)); </script> <template> <NuxtLink class="group block" :target="subdomain ? '' : '_blank'" :to="url"> <div class="p-4 md:p-6 my-4 flex flex-col-reverse md:flex-row bg-white shadow-none group-focus:shadow-xl group-focus:shadow-xl hover:shadow-xl shadow-gray-200 rounded-2xl transition-all" > <div class="w-full flex flex-col justify-between md:h-40"> <div> <div v-if="!subdomain" class="flex items-center space-x-2"> <NuxtImg class="w-5 h-5 rounded-full" :src="post.profiles.avatar_url"></NuxtImg> <h4 class="text-sm font-medium">{{ post.profiles.name }}</h4> <div v-if="post.featured" class="px-2 py-1 rounded-lg bg-light-300 text-gray-400 !ml-6 text-sm font-semibold flex items-center" > <div class="i-mdi-star mr-1"></div> <span>Featured</span> </div> </div> <h1 class="mt-2 font-semibold text-2xl">{{ post.title }}</h1> <p class="mt-1 text-gray-400">{{ stripHtml(post.body).result.slice(0, 120) }}...</p> </div> <div class="mt-4 text-sm text-gray-400 place-items-end"> <span> {{ format(new Date(post.created_at), "MMM d") }}</span> <NuxtLink v-if="post.tags" class="ml-2 bg-light-300 px-2 py-1 rounded">{{ post.tags?.[0] }}</NuxtLink> </div> </div> <NuxtImg class="w-full md:w-40 h-40 md:ml-12 mb-6 md:mb-0 rounded-xl flex-shrink-0" v-if="post.cover_img" :src="post.cover_img" ></NuxtImg> </div> </NuxtLink> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/TagsInput.vue
Vue
<script setup lang="ts"> import type { Tags } from "~~/utils/types" import { PropType } from "vue" import Multiselect from "@vueform/multiselect" const props = defineProps({ modelValue: { type: Object as PropType<string[]>, default: [] }, id: String, }) const emits = defineEmits(["update:modelValue"]) const client = useSupabaseClient() const { data: tags } = useAsyncData("tags", async () => { const { data } = await client.from<Tags>("tags_view").select("*") return data.map((i) => i.name) }) </script> <template> <div> <Multiselect v-model="modelValue" @change="emits('update:modelValue', $event)" :options="tags ?? []" createOption mode="tags" placeholder="Add tags" :close-on-select="false" :searchable="true" :classes="{ container: 'relative mx-auto p-2 w-full flex items-center justify-end cursor-pointer rounded-2xl bg-light-300', tag: 'bg-dark-300 text-white text-sm font-semibold py-0.5 pl-2 rounded-lg mr-1.5 mb-1.5 flex items-center whitespace-nowrap rtl:pl-0 rtl:pr-2 rtl:mr-0 rtl:ml-1', tagsSearch: 'not-default bg-transparent absolute inset-0 border-0 focus:ring-0 outline-none appearance-none p-0 text-base font-sans box-border w-full', tagsSearchCopy: 'invisible whitespace-pre-wrap inline-block h-px', placeholder: 'flex items-center h-full absolute left-2 top-0 pointer-events-none bg-transparent leading-snug pl-3.5 text-gray-400 rtl:left-auto rtl:right-0 rtl:pl-0 rtl:pr-3.5', dropdown: 'max-h-60 absolute -left-px -right-px bottom-0 transform translate-y-full -mt-px py-2 overflow-y-scroll z-50 bg-light-300 flex flex-col rounded-b-2xl shadow-lg', dropdownHidden: '!hidden', optionPointed: 'text-dark-300 bg-light-700', optionSelected: 'text-dark-300 bg-light-700', noResults: 'py-2 px-3 text-gray-400 text-center font-semibold', }" /> </div> </template> <style src="@vueform/multiselect/themes/default.css"></style> <style> .is-open { @apply rounded-b-none transition; } .is-active { @apply ring-3 ring-gray-400; } </style>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Tiptap.vue
Vue
<script lang="ts" setup> import { useEditor, EditorContent } from "@tiptap/vue-3" import StarterKit from "@tiptap/starter-kit" import Underline from "@tiptap/extension-underline" import Image from "@tiptap/extension-image" import Focus from "@tiptap/extension-focus" import Commands from "~~/utils/tiptap/commands" import suggestion from "~~/utils/tiptap/suggestion" import HardBreak from "~~/utils/tiptap/hardbreak" import Code from "~~/utils/tiptap/code" import Link from "~~/utils/tiptap/link" import Placeholder from "~~/utils/tiptap/placeholder" import Upload from "~~/utils/tiptap/upload" import Iframe from "~~/utils/tiptap/iframe" import Move from "~~/utils/tiptap/move" const props = defineProps<{ modelValue: string editable?: boolean }>() const emit = defineEmits(["update:modelValue"]) const editor = useEditor({ content: props.modelValue ?? "", extensions: [ Link, StarterKit, Image, Underline, Focus, Upload, HardBreak, Code, Placeholder, Iframe, Move, Commands.configure({ suggestion, }), ], editable: props.editable ?? false, onUpdate(props) { emit("update:modelValue", props.editor.getHTML()) }, }) watch( () => props.modelValue, (newValue) => { const isSame = editor.value.getHTML() === newValue if (isSame) return editor.value.commands.setContent(newValue, false) } ) </script> <template> <div> <TiptapBubble :editor="editor"></TiptapBubble> <EditorContent class="content" :editor="editor" /> </div> </template> <style lang="postcss"> .ProseMirror { @apply p-2 focus:outline-none; } .ProseMirror .is-empty::before { content: attr(data-placeholder); float: left; pointer-events: none; height: 0; @apply text-gray-300; } @keyframes highlight { 0% { @apply bg-light-700; } 100% { @apply bg-transparent; } } .has-focus { animation: highlight 0.75s ease-out; @apply rounded; } </style>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Tiptap/Bubble.vue
Vue
<script setup lang="ts"> // bubble menu: https://tiptap.dev/api/extensions/bubble-menu import { BubbleMenu } from "@tiptap/vue-3" import { PropType } from "vue" import type { Editor } from "@tiptap/core" import type { NodeSelection } from "prosemirror-state" import { TextSelection } from "prosemirror-state" const props = defineProps({ editor: Object as PropType<Editor>, }) type NodeType = "image" | "text" | "video" | "iframe" const nodeType = computed<NodeType | undefined>(() => { const selection = props.editor.state.selection as NodeSelection const isImage = selection.node?.type.name === "image" const isIframe = selection.node?.type.name === "iframe" const isText = selection instanceof TextSelection if (isImage) return "image" if (isIframe) return "iframe" if (isText) return "text" return undefined }) </script> <template> <BubbleMenu :editor="editor" :tippy-options="{ duration: 100 }" v-if="editor"> <div class="p-2 rounded-xl shadow-md bg-white"> <div v-if="nodeType === 'text'" class="flex items-center space-x-1 text-xl text-gray-400"> <button class="bubble-item" @click="editor.chain().focus().toggleBold().run()" :class="{ 'is-active': editor.isActive('bold') }" > <div class="i-ic-round-format-bold"></div> </button> <button class="bubble-item" @click="editor.chain().focus().toggleItalic().run()" :class="{ 'is-active': editor.isActive('italic') }" > <div class="i-ic-round-format-italic"></div> </button> <button class="bubble-item" @click="editor.chain().focus().toggleStrike().run()" :class="{ 'is-active': editor.isActive('strike') }" > <div class="i-ic-round-format-strikethrough"></div> </button> <button class="bubble-item" @click="editor.chain().focus().toggleUnderline().run()" :class="{ 'is-active': editor.isActive('underline') }" > <div class="i-ic-round-format-underlined"></div> </button> </div> <div v-if="nodeType === 'image'"> <button class="bubble-item" @click="editor.commands.openModal('image')">Edit</button> </div> <div v-if="nodeType === 'iframe'"> <button class="bubble-item" @click="editor.commands.openModal('iframe')">Edit</button> <button>Focus</button> </div> </div> </BubbleMenu> </template> <style lang="postcss"> .bubble-item { @apply focus:bg-light-500 focus:text-dark-300 p-1 rounded-lg transition; } .is-active { @apply !text-dark-300; } </style>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Tiptap/CommandList.vue
Vue
<template> <div class="bg-white px-2 py-4 rounded-xl shadow-xl flex flex-col w-72"> <template v-if="items.length"> <button class="p-2 flex flex-col text-sm text-left rounded-lg bg-transparent transition" :class="{ '!bg-light-300': index === selectedIndex }" v-for="(item, index) in items" :key="index" @click="selectItem(index)" > <span>{{ item.title }}</span> <span class="opacity-40 text-xs">{{ item.description }}</span> </button> </template> <div class="item" v-else>No result</div> </div> </template> <script setup lang="ts"> import { PropType } from "vue" interface Item { title: string description: string } const props = defineProps({ items: { type: Array as PropType<Item[]>, required: true, }, command: { type: Function, required: true, }, }) const { items } = toRefs(props) const selectedIndex = ref(0) watch(items, () => (selectedIndex.value = 0)) const selectItem = (index: number) => { const item = items.value[index] if (item) { props.command(item) } } const onKeyDown = (event: KeyboardEvent) => { if (event.key === "ArrowUp") { selectedIndex.value = (selectedIndex.value + items.value.length - 1) % items.value.length return true } if (event.key === "ArrowDown") { selectedIndex.value = (selectedIndex.value + 1) % items.value.length return true } if (event.key === "Enter") { selectItem(selectedIndex.value) return true } else return } defineExpose({ onKeyDown, }) </script>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Tiptap/ModalIframe.vue
Vue
<script setup lang="ts"> import type { Editor } from "@tiptap/core" import { PropType } from "vue" const props = defineProps({ show: Boolean, editor: Object as PropType<Editor>, }) const open = ref(props.show) const url = ref("") const save = () => { if (!url.value?.match(/[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi)) return props.editor .chain() .focus() .setIframe({ src: url.value, }) .run() open.value = false } watch(open, () => { if (!open.value) { const editorEl = document.querySelector(".content .ProseMirror") as HTMLDivElement if (editorEl) editorEl.focus() } }) </script> <template> <Modal v-model:open="open"> <div class="flex flex-col p-6"> <h2 class="text-3xl font-bold">Add iframe</h2> <div class="flex items-center my-6"> <label for="url" class="mr-4 flex-shrink-0">URL :</label> <input type="url" name="url" id="url" placeholder="https://supabase.com" v-model="url" /> </div> <div class="flex justify-end"> <button class="btn-plain" @click="open = false">Cancel</button> <Button class="btn-primary ml-2" @click="save">Save</Button> </div> </div> </Modal> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Tiptap/ModalImage.vue
Vue
<script setup lang="ts"> import type { Editor } from "@tiptap/core" import { PropType } from "vue" const props = defineProps({ show: Boolean, editor: Object as PropType<Editor>, }) const isVisible = ref(props.show) const alt = ref("") const image = ref("") const isLoading = ref(false) const save = async () => { if (!image.value) return isLoading.value = true props.editor .chain() .focus() .setImage({ src: image.value, alt: alt.value, }) .run() isLoading.value = false isVisible.value = false } watch(isVisible, () => { if (!isVisible.value) { const editorEl = document.querySelector(".content .ProseMirror") as HTMLDivElement if (editorEl) editorEl.focus() } }) </script> <template> <Modal v-model:open="isVisible"> <div class="flex flex-col p-6"> <h2 class="text-3xl font-bold">Add image</h2> <div class="my-6"> <Upload v-model="image"></Upload> <div class="mt-4 flex items-center"> <input type="text" name="alt-name" id="alt-name" placeholder="alternate" v-model="alt" /> </div> </div> <div class="flex justify-end"> <Button class="btn-primary ml-2" :loading="isLoading" @click="save">Save</Button> <button class="btn-plain" @click="isVisible = false">Cancel</button> </div> </div> </Modal> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/TiptapHeading.vue
Vue
<script lang="ts" setup> import { useEditor, EditorContent, Extension } from "@tiptap/vue-3" import Document from "@tiptap/extension-document" import Text from "@tiptap/extension-text" import Heading from "@tiptap/extension-heading" import Placeholder from "@tiptap/extension-placeholder" import Focus from "@tiptap/extension-focus" import History from "@tiptap/extension-history" const props = defineProps<{ modelValue: string }>() const emit = defineEmits(["update:modelValue"]) const focusNextEditor = () => { const editors = document.querySelectorAll(".ProseMirror") let nextEditor = editors.item(1) as HTMLElement if (nextEditor) { nextEditor.focus() return true } } const Enter = Extension.create({ addKeyboardShortcuts() { return { Enter: focusNextEditor, "Mod-Enter": focusNextEditor, ArrowDown: focusNextEditor, } }, }) const CustomDocument = Document.extend({ content: "heading", }) const editor = useEditor({ content: props.modelValue ?? "", extensions: [ CustomDocument, Text, Heading, Focus, Enter, History, Placeholder.configure({ placeholder: "What’s the title?", }), ], autofocus: true, onUpdate(props) { emit("update:modelValue", props.editor.getJSON().content?.[0].content?.[0].text) }, }) watch( () => props.modelValue, (newValue) => { const title = editor.value.getJSON().content?.[0].content?.[0].text const isSame = title === newValue if (isSame) return editor.value.commands.setContent(newValue, false) } ) </script> <template> <EditorContent :editor="editor" /> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Toggle.vue
Vue
<script setup lang="ts"> const props = defineProps({ modelValue: Boolean, id: String, }) const emits = defineEmits(["update:modelValue"]) const emitData = (ev: InputEvent) => { //@ts-ignore emits("update:modelValue", ev.target.checked) } </script> <template> <label :for="id" class="inline-flex relative items-center cursor-pointer"> <input type="checkbox" class="peer h-1px w-1px absolute border-0 outline-none" v-model="modelValue" :id="id" @change="emitData" /> <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-3 peer-focus:ring-gray-400 rounded-full peer-checked:bg-dark-300 transition" ></div> <div class="peer-checked:translate-x-full peer-checked:border-white absolute top-[2px] left-[2px] bg-white border-gray-400 rounded-full h-5 w-5 transition-all" ></div> <span class="ml-2"> <slot>Toggle</slot> </span> </label> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
components/Upload.vue
Vue
<script setup lang="ts"> const props = defineProps({ modelValue: String, }) const emits = defineEmits(["update:modelValue"]) const client = useSupabaseClient() const user = useSupabaseUser() const { files, open: openFileDialog, reset } = useFileDialog({ accept: "image/*" }) const { base64 } = useBase64(computed(() => files.value?.item?.(0))) const imageSrc = ref(props.modelValue) const isUploading = ref(false) const upload = async (file: File) => { isUploading.value = true const filename = `${user.value?.id}/${file.name}` const { data, error } = await client.storage.from("posts").upload(filename, file, { cacheControl: "3600" }) const { publicURL } = client.storage.from("posts").getPublicUrl(data?.Key?.replace("posts/", "") ?? filename) emits("update:modelValue", publicURL) isUploading.value = false } watch(files, async (n) => { if (n.length) { const file = n.item(0) upload(file) } }) watch(base64, (n) => (imageSrc.value = n)) </script> <template> <button :disabled="isUploading" accept="image/*" type="button" class="block w-full p-0 ring-3 ring-transparent hover:ring-gray-400 focus:ring-gray-400 rounded-2xl transition overflow-hidden" @click="openFileDialog()" > <div class="h-64 w-full bg-light-300 flex items-center justify-center"> <img class="w-full h-full object-scale-down" :src="imageSrc" v-if="imageSrc" /> <p v-else class="text-gray-400">Press 'Enter' to upload image</p> </div> </button> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
composables/dashboard.ts
TypeScript
import type { Profiles } from "~~/utils/types" import type { Ref } from "vue" export const useProfile = () => useState<Profiles>("profile", () => null) export const useProfileSave = (payload: Ref<Partial<Profiles>>) => { const user = useSupabaseUser() const client = useSupabaseClient() const isSaving = ref(false) const save = async () => { // validate input here (if any) isSaving.value = true console.log("save profile settings", payload.value) const { data } = await client .from<Profiles>("profiles") .upsert({ ...payload.value, id: user.value?.id }) .single() console.log({ data }) isSaving.value = false } useMagicKeys({ passive: false, onEventFired(e) { if ((e.ctrlKey || e.metaKey) && e.key === "s" && e.type === "keydown") { e.preventDefault() save() } }, }) return { save, isSaving, } }
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
composables/head.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 open-source blogging platform + free custom domains. Powered by Nuxt 3, Supabase & Vercel", }, { name: "twitter:card", content: "summary_large_image" }, { name: "twitter:site", content: "@zernonia" }, { name: "twitter:title", content: title ?? "KeyPress | Write your blog with keyboard only experience" }, { name: "twitter:description", content: description ?? "An open-source blogging platform + free custom domains. Powered by Nuxt 3, Supabase & Vercel", }, { name: "twitter:image", content: image ?? "https://keypress.blog/og.png" }, { property: "og:type", content: "website" }, { property: "og:title", content: title ?? "KeyPress | Write your blog with keyboard only experience" }, { property: "og:url", content: "https://keypress.blog/" }, { property: "og:image", content: image ?? "https://keypress.blog/og.png" }, { property: "og:image:secure_url", content: image ?? "https://keypress.blog/og.png" }, { property: "og:image:type", content: "image/png" }, { property: "og:description", content: description ?? "An open-source blogging platform + free custom domains. Powered by Nuxt 3, Supabase & Vercel", }, ], }) }
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
composables/subdomain.ts
TypeScript
import type { Profiles } from "~~/utils/types" export const useSubdomain = () => useState<string>("subdomain", () => null) export const useSubdomainProfile = () => useState<Profiles>("subdomain-profile", () => null)
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
composables/url.ts
TypeScript
export const useUrl = () => (process.dev ? "http://localhost:3000" : "https://keypress.blog")
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
layouts/default.vue
Vue
<script lang="ts" setup> const user = useSupabaseUser() </script> <template> <div class="p-4 bg-light-300 min-h-screen w-full flex flex-col"> <div class="max-w-screen-lg mx-auto w-full"> <nav class="flex justify-between items-center"> <NuxtLink to="/"> <Logo class="w-12 h-12"></Logo> </NuxtLink> <div class="flex items-center"> <Command class="mr-4"></Command> <NuxtLink to="/login" v-if="!user">Login</NuxtLink> <div> <NuxtImg v-if="user?.user_metadata?.avatar_url" class="w-10 h-10 rounded-full" :src="user?.user_metadata?.avatar_url" :alt="user?.user_metadata?.full_name" /> </div> </div> </nav> <slot /> </div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
layouts/user.vue
Vue
<script lang="ts" setup> const user = useSupabaseUser(); const url = useUrl(); </script> <template> <div class="p-4 bg-light-300 min-h-screen w-full flex flex-col"> <div class="max-w-screen-lg mx-auto w-full"> <nav class="flex justify-between items-center"> <NuxtLink to="/"> <Logo class="w-12 h-12"></Logo> </NuxtLink> <div class="flex items-center"> <Command class="mr-4"></Command> <NuxtLink rel="noopener" :to="`${url}/login`" v-if="!user">Login</NuxtLink> <div> <NuxtImg v-if="user?.user_metadata?.avatar_url" class="w-10 h-10 rounded-full" :src="user?.user_metadata?.avatar_url" :alt="user?.user_metadata?.full_name" /> </div> </div> </nav> <div class="min-h-screen"> <slot /> </div> <Footer></Footer> </div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
middleware/auth.ts
TypeScript
export default defineNuxtRouteMiddleware((to, from) => { const user = useSupabaseUser() if (!user.value && to.path !== "/write") { return navigateTo("/login") } })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
modules/og.ts
TypeScript
import { defineNuxtModule } from "@nuxt/kit" import { copyFile, cp } from "fs/promises" export default defineNuxtModule({ setup(options, nuxt) { nuxt.hook("close", async () => { await cp("public/fonts", ".vercel/output/functions/__nitro.func/public/fonts", { recursive: true }) }) }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
nuxt.config.ts
TypeScript
import transformerDirective from "@unocss/transformer-directives" // https://v3.nuxtjs.org/api/configuration/nuxt.config export default defineNuxtConfig({ modules: ["@unocss/nuxt", "@nuxtjs/supabase", "@vueuse/nuxt", "@nuxt/image-edge", "~~/modules/og"], 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`, typography: { cssExtend: { h1: { "font-weight": 700, }, img: { "border-radius": "1.5rem", }, pre: { "border-radius": "1.5rem", background: "white !important", }, iframe: { height: "400px", "border-radius": "1.5rem", }, "p code": { padding: "0.25rem 0.5rem", "border-radius": "0.35rem", "background-color": "#ececec", }, "code::before": { content: "''", }, "code::after": { content: "''", }, }, }, transformers: [transformerDirective({ enforce: "pre" })], // enabled `@unocss/transformer-directives`, safelist: [ "ic-round-format-bold", "ic-round-format-underlined", "ic-round-format-strikethrough", "ic-round-format-italic", ], // core options shortcuts: [ { btn: " text-sm md:text-base font-medium rounded-2xl py-2 px-4 transition ring-3 ring-transparent disabled:opacity-50 relative inline-flex justify-center items-center shadow-none", "btn-plain": "btn font-semibold text-gray-400 focus:text-dark-50 hover:text-dark-50", "btn-primary": "btn bg-dark-300 text-white focus:ring-gray-400 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", }, ], rules: [], }, image: { domains: ["avatars0.githubusercontent.com", "avatars.githubusercontent.com/", "images.unsplash.com/"], }, build: { transpile: ["@tiptap/extension-link", "@tiptap/extension-placeholder", "@tiptap/extension-document"], }, nitro: { preset: "vercel", }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/dashboard.vue
Vue
<script setup lang="ts"> import { Profiles } from "~~/utils/types" const user = useSupabaseUser() const client = useSupabaseClient() const profile = useProfile() const { pending } = useAsyncData( "profile", async () => { const { data } = await client .from<Profiles>("profiles") .select("*, domains(url, active), posts(id, title, created_at)") .order("created_at", { ascending: false, foreignTable: "posts" }) .eq("id", user.value?.id) .maybeSingle() profile.value = data return data }, { server: false } ) useCustomHead("Dashboard") definePageMeta({ middleware: "auth", }) </script> <template> <div class="my-12"> <h2 class="text-3xl font-bold">Dashboard</h2> <div class="flex"> <aside class="flex-shrink-0 w-72 my-8"> <ul> <li class="my-2"><NuxtLink to="/dashboard/posts">Posts</NuxtLink></li> <li class="my-2"><NuxtLink to="/dashboard/profile">Profile</NuxtLink></li> <li class="my-2"><NuxtLink to="/dashboard/domain">Domain</NuxtLink></li> </ul> </aside> <Loader v-if="pending"></Loader> <NuxtPage v-else></NuxtPage> </div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/dashboard/domain.vue
Vue
<script setup lang="ts"> const profile = useProfile() const payload = ref({ subdomain: profile.value.subdomain }) const isSaving = ref(false) const { save } = useProfileSave(payload) const saveDomain = async () => { // validate here try { isSaving.value = true // add domain and check first const data = await $fetch("/api/add-domain", { method: "POST", body: { domain: payload.value.subdomain, }, }) console.log(data) await Promise.all([save(), checkDomain()]) } catch (err) { console.log(err) } finally { isSaving.value = false } } const isCheckingDomain = ref(false) const isValid = ref(false) const checkDomain = async () => { isCheckingDomain.value = true const { valid } = await $fetch("/api/check-domain", { method: "POST", body: { domain: payload.value.subdomain, }, }) isValid.value = valid isCheckingDomain.value = false } onMounted(() => { if (profile.value.domains.active) { isValid.value = true } else if (!payload.value.subdomain) { isValid.value = false } else { checkDomain() } }) </script> <template> <div class="w-full"> <div class="flex w-full justify-end"> <Button :loading="isSaving" @click="saveDomain" class="mb-8 btn-primary" >Save <span class="ml-2">⌘S</span></Button > </div> <div class="flex items-center"> <label for="domain" class="flex-shrink-0 mr-2">Domain :</label> <input type="text" name="domain" id="domain" class="bg-white" v-model="payload.subdomain" placeholder="https://foo.bar.com" /> </div> <div v-if="!isValid && payload.subdomain"> <Button :loading="isCheckingDomain" class="btn-plain mt-12" @click="checkDomain">Check domain</Button> <div class="mt-4 bg-white p-6 rounded-2xl"> <p>Set the following record on your DNS provider to continue:</p> <div class="mt-6 flex items-center space-x-6"> <div class="flex-shrink-0 justify-start"> <p>Type</p> <p>CNAME</p> </div> <div class="flex-shrink-0"> <p>Name</p> <p>{{ payload.subdomain.split(".")[0] }}</p> </div> <div class="flex-grow"> <p>Value</p> <p>cname.vercel-dns.com</p> </div> </div> <div class="mt-4 text-sm text-gray-400"> Depending on your provider, it might take some time for the changes to apply. <NuxtLink target="_blank" to="https://vercel.com/guides/why-is-my-vercel-domain-unverified" >Learn More</NuxtLink > </div> </div> </div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/dashboard/index.vue
Vue
<script setup lang="ts"></script> <template> <div></div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/dashboard/posts.vue
Vue
<script setup lang="ts"> import { format } from "date-fns" const profile = useProfile() </script> <template> <div class="w-full"> <ul> <li v-for="post in profile.posts" class="my-4"> <NuxtLink :to="`/edit/${post.id}`" class="block"> <div class="p-4 rounded-2xl bg-white shadow-none focus:shadow-lg hover:shadow-lg transition"> <h2 class="text-lg font-semibold">{{ post.title }}</h2> <span class="text-sm text-gray-400"> {{ format(new Date(post.created_at), "MMM d") }}</span> </div> </NuxtLink> </li> </ul> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/dashboard/profile.vue
Vue
<script setup lang="ts"> const profile = useProfile() const payload = ref({ name: profile.value.name }) const { save, isSaving } = useProfileSave(payload) const saveProfile = async () => { // validate save() } </script> <template> <div class="w-full"> <div class="flex w-full justify-end"> <Button :loading="isSaving" @click="saveProfile" class="mb-8 btn-primary" >Save <span class="ml-2">⌘S</span></Button > </div> <div class="flex items-center"> <label for="name" class="flex-shrink-0 mr-2">Name :</label> <input type="text" name="name" id="name" class="bg-white" v-model="payload.name" /> </div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/edit/[id].vue
Vue
<script lang="ts" setup> import { stripHtml } from "string-strip-html" import slugify from "slugify" import { Posts } from "~~/utils/types" const user = useSupabaseUser() const client = useSupabaseClient() const { params } = useRoute() const postId = ref(params.id) const title = postId.value ? ref("") : useLocalStorage("new-post-title", "") const body = postId.value ? ref("") : useLocalStorage("new-post-body", "") const settings = ref({ image: "", active: false, tags: [], }) const isSaving = ref(false) const isLoginVisible = ref(false) const save = async () => { if (!title.value || !stripHtml(body.value).result || isSaving.value) return if (!user.value?.id) { // login modal isLoginVisible.value = true return } isSaving.value = true const { data, error } = await client .from<Posts>("posts") .upsert({ id: postId.value?.toString(), slug: slugify(title.value, { lower: true }), title: title.value, body: body.value, author_id: user.value.id, active: settings.value.active, cover_img: settings.value.image, tags: settings.value.tags, }) .single() console.log({ data }) if (data) { if (!postId.value) { postId.value = data.id // history.pushState(null, "Title?", `${window.origin}/edit/${postId.value}`) localStorage.removeItem("new-post-title") localStorage.removeItem("new-post-body") navigateTo(`/edit/${postId.value}`) } } isSaving.value = false } useMagicKeys({ passive: false, onEventFired(e) { if ((e.ctrlKey || e.metaKey) && e.key === "s" && e.type === "keydown") { e.preventDefault() save() } if ((e.ctrlKey || e.metaKey) && e.key === "e" && e.type === "keydown") { isDrawerOpen.value = !isDrawerOpen.value } }, }) const { pending } = await useAsyncData( `post-${postId.value}`, async () => { if (!postId.value) throw Error("no id found") const { data } = await client.from<Posts>("posts").select("*").eq("id", postId.value).single() title.value = data.title body.value = data.body settings.value = { image: data.cover_img ?? "", active: data.active ?? false, tags: data.tags ?? [], } return data }, { server: false, lazy: true } ) const isDrawerOpen = ref(false) useCustomHead("Write your post") definePageMeta({ alias: "/write", middleware: "auth", }) </script> <template> <div> <Loader v-if="pending"></Loader> <div v-else ref="el" class="flex flex-col mt-8"> <div class="flex justify-end prose mx-auto w-full"> <button :disabled="isSaving" class="btn-plain mr-6" @click="isDrawerOpen = true"> Settings <span class="ml-2">⌘E</span> </button> <Button :loading="isSaving" class="btn-primary" @click="save">Save <span class="ml-2">⌘S</span></Button> </div> <div class="md:p-2 prose mx-auto w-full" spellcheck="false"> <TiptapHeading v-model="title"></TiptapHeading> <Tiptap editable v-model="body"></Tiptap> </div> <DrawerEditPost v-model:show="isDrawerOpen" :settings="settings"></DrawerEditPost> <div id="modal"></div> <ModalLogin v-model:show="isLoginVisible"></ModalLogin> </div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/index.vue
Vue
<script setup lang="ts"> import { Posts } from "~~/utils/types"; useCustomHead("Experience keyboard-first blogging platform"); const client = useSupabaseClient(); const { data, pending } = useAsyncData( "posts", async () => { const { data } = await client .from<Posts>("posts") .select("*, profiles(avatar_url, name, username, domains (url, active) )") .eq("active", true) .order("featured", { ascending: false }) .order("created_at", { ascending: false }); return data; }, { lazy: true } ); const writeEl = ref(); const { Slash } = useMagicKeys(); watch(Slash, (n) => { if (n && writeEl.value) { writeEl.value.$el.focus(); setTimeout(() => { writeEl.value.$el.click(); }, 300); } }); </script> <template> <div class="pb-20"> <div class="relative my-20 md:my-30 text-center"> <div class="z-100"> <h1 class="text-4xl md:text-6xl font-bold"> Keyboard-first <br /> Blogging Platform </h1> <h2 class="mt-8 text-xl md:text-3xl font-semibold text-gray-300"> KeyPress let you write your blog <br /> with only keyboard </h2> <div class="mt-12 flex flex-col items-center justify-center"> <NuxtLink ref="writeEl" class="btn-primary text-xl" to="/write">Press '/' to write</NuxtLink> <span class="text-sm mt-2 text-gray-300">or 'Tab' to Navigate</span> </div> </div> </div> <NuxtLink to="https://github.com/zernonia/keypress" target="_blank" class="w-full relative block"> <NuxtImg style="object-position: 0 20%" class="w-full h-60 md:h-80 object-cover rounded-2xl" src="https://images.unsplash.com/photo-1665049420194-8f562db50cbd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=764&q=80" alt="" /> <h3 class="absolute left-4 md:left-1/2 top-8 md:top-1/2 md:-translate-x-1/2 md:-translate-y-1/2 md:text-3xl font-semibold flex flex-wrap items-center" > <div class="i-mdi-github mr-2"></div> Nuxt 3 + Supabase + Vercel </h3> </NuxtLink> <h2 class="mt-20 text-4xl font-bold">Posts</h2> <Loader v-if="pending"></Loader> <ul v-else class="mt-4"> <li v-for="post in data"> <PostCard :post="post"></PostCard> </li> </ul> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/login.vue
Vue
<script lang="ts" setup> const client = useSupabaseClient() const signIn = async () => { const { user } = await client.auth.signIn({ provider: "github" }) } useCustomHead("Login") </script> <template> <div class="flex flex-col mx-auto max-w-48 mt-20"> <h1 class="text-4xl font-bold text-center">Login</h1> <button autofocus class="btn-primary mt-4" @click="signIn">Login with GitHub</button> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/posts.vue
Vue
<script setup lang="ts"> import type { Posts, Tags } from "~~/utils/types"; const client = useSupabaseClient(); const { data, pending } = useAsyncData("posts", async () => { const { data } = await client .from<Posts>("posts") .select("*, profiles(avatar_url, name,username, domains (url, active))") .eq("active", true) .order("featured", { ascending: false }) .order("created_at", { ascending: false }); return data; }); const { data: tags } = useAsyncData("tags", async () => { const { data } = await client.from<Tags>("tags_view").select("*"); return data; }); useCustomHead("Explore all posts"); </script> <template> <div class="my-12"> <h1 class="text-4xl font-semibold">Posts</h1> <div class="flex flex-col-reverse md:flex-row"> <div class="w-full"> <div v-if="pending"> <Loader></Loader> </div> <ul v-else> <li class="my-4" v-for="post in data"> <PostCard :post="post"></PostCard> </li> </ul> </div> <aside class="md:ml-6 md:w-60 mt-3 flex-shrink-0"> <h5 class="text-xl font-medium">Tags</h5> <ul class="mt-4 p-4 bg-light-600 rounded-xl flex flex-col space-y-2"> <li v-for="tag in tags" class="flex justify-between items-center"> <div class="text-sm">{{ tag.name }}</div> <div class="text-xs px-1 py-0.5 flex items-center bg-gray-200 font-medium rounded">{{ tag.count }}</div> </li> </ul> </aside> </div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/user/[siteId].vue
Vue
<script setup lang="ts"> import { Profiles } from "~~/utils/types" const client = useSupabaseClient() const subdomain = useSubdomain() const profile = useSubdomainProfile() // this should fetch user's profiles and settings (if any) useAsyncData("profile", async () => { const { data, error } = await client .from<Profiles>("profiles") .select("*") .or(`username.eq.${subdomain.value}, subdomain.eq.${subdomain.value}`) .maybeSingle() profile.value = data return data }) definePageMeta({ layout: "user", }) </script> <template> <div> <NuxtPage v-if="profile"></NuxtPage> <div class="text-4xl my-20 font-bold text-center" v-else>Page not found</div> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/user/[siteId]/[slug].vue
Vue
<script setup lang="ts"> import { format } from "date-fns" import { Posts } from "~~/utils/types" import { stripHtml } from "string-strip-html" import { constructUrl } from "~~/utils/functions" const client = useSupabaseClient() const { params } = useRoute() const url = useUrl() const { data, pending } = useAsyncData(`posts-${params.slug}`, async () => { const { data } = await client .from<Posts>("posts") .select("*, profiles(avatar_url, name, username)") .eq("slug", params.slug) .single() return data }) useCustomHead( computed(() => data.value?.title), computed(() => (data.value?.body ? stripHtml(data.value?.body)?.result?.slice(0, 160) : undefined)), computed(() => (data.value?.cover_img === "" ? `${url}/og/${params.slug}` : data.value?.cover_img)) ) const fullUrl = computed(() => constructUrl(data.value, false)) </script> <template> <div> <Transition name="fade" mode="out-in"> <article class="prose mx-auto w-full" v-if="!pending && data"> <div class="not-prose flex items-center pt-8 pb-4"> <NuxtImg class="w-12 h-12 rounded-full mr-4" :src="data.profiles.avatar_url"></NuxtImg> <div> <h3 class="text-lg">{{ data.profiles?.name }}</h3> <h4 class="text-sm text-gray-400">{{ format(new Date(data.created_at), "MMMM d") }}</h4> </div> </div> <h1>{{ data.title }}</h1> <NuxtImg v-if="data.cover_img" :src="data.cover_img" class="my-8 w-full h-auto"></NuxtImg> <!-- <Tiptap v-model="data.body"></Tiptap> --> <div v-html="data.body"></div> <hr /> <div class="not-prose mt-2 flex items-center space-x-2"> <NuxtLink class="px-1 text-2xl text-gray-300 focus:text-dark-300 hover:text-dark-300 transition" :to="`https://twitter.com/intent/tweet?url=${fullUrl}&text=Check%20out%20this%20new%20post`" target="_blank" > <div class="i-mdi-twitter"></div> </NuxtLink> <NuxtLink class="px-1 text-2xl text-gray-300 focus:text-dark-300 hover:text-dark-300 transition" :to="`https://www.facebook.com/sharer/sharer.php?u=${fullUrl}`" target="_blank" > <div class="i-mdi-facebook"></div ></NuxtLink> <NuxtLink class="px-1 text-2xl text-gray-300 focus:text-dark-300 hover:text-dark-300 transition" :to="`https://www.linkedin.com/shareArticle?mini=true&url=${fullUrl}`" target="_blank" > <div class="i-mdi-linkedin"></div ></NuxtLink> </div> <!-- <div>More posts</div> --> <!-- <div>Comments</div> --> </article> <Loader v-else></Loader> </Transition> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/user/[siteId]/home.vue
Vue
<script setup lang="ts"> const { params } = useRoute() </script> <template> <div>Home for user {{ params.slug }}</div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
pages/user/[siteId]/index.vue
Vue
<script setup lang="ts"> import type { Posts } from "~~/utils/types"; const client = useSupabaseClient(); const profile = useSubdomainProfile(); const { data, pending } = useAsyncData("posts", async () => { const { data, error } = await client .from<Posts>("posts") .select("*, profiles!inner (username)") .eq("active", true) // @ts-ignore .eq("profiles.id", profile.value.id) .order("featured", { ascending: false }) .order("created_at", { ascending: false }); return data; }); useCustomHead(computed(() => `${profile.value?.name}'s blog`)); </script> <template> <div class="my-20"> <h1 class="text-4xl font-semibold">{{ profile?.name }}'s posts</h1> <div> <ul v-if="data"> <li class="my-4" v-for="post in data"> <PostCard subdomain v-if="post.id" :post="post"></PostCard> </li> </ul> <Loader v-if="pending"></Loader> </div> <!-- <aside></aside> --> </div> </template>
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
plugins/umami.client.ts
TypeScript
export default defineNuxtPlugin(() => { const cfg = useRuntimeConfig() const moduleOptions = { scriptUrl: "https://umami-zernonia.vercel.app/script.js", websiteId: cfg.public.UMAMI_WEBSITE_ID, } const options = { ...moduleOptions } if (moduleOptions.websiteId) { 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.setAttribute('data-website-id', options.websiteId); script.src = options.scriptUrl head.appendChild(script) }
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/api/_supabase/session.post.ts
TypeScript
import { setCookie, defineEventHandler } from "h3" export default defineEventHandler(async (event) => { const body = await useBody(event) const config = useRuntimeConfig().public const cookieOptions = config.supabase.cookies const { event: signEvent, session } = body if (!event) { throw new Error("Auth event missing!") } if (signEvent === "SIGNED_IN") { if (!session) { throw new Error("Auth session missing!") } setCookie(event, `${cookieOptions.name}-access-token`, session.access_token, { domain: cookieOptions.domain, maxAge: cookieOptions.lifetime ?? 0, path: cookieOptions.path, sameSite: cookieOptions.sameSite as boolean | "lax" | "strict" | "none", }) setCookie(event, `${cookieOptions.name}-refresh-token`, session.refresh_token, { domain: cookieOptions.domain, maxAge: cookieOptions.lifetime ?? 0, path: cookieOptions.path, sameSite: cookieOptions.sameSite as boolean | "lax" | "strict" | "none", }) } if (signEvent === "SIGNED_OUT") { setCookie(event, `${cookieOptions.name}-access-token`, "", { maxAge: -1, path: cookieOptions.path, }) } return "custom auth cookie set" })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/api/add-domain.post.ts
TypeScript
// ref: https://github.com/vercel/platforms/blob/main/lib/api/domain.ts import { serverSupabaseClient, serverSupabaseUser } from "#supabase/server" import type { Domains } from "~~/utils/types" export default defineEventHandler(async (event) => { try { const { domain, user_id } = await useBody(event) const user = await serverSupabaseUser(event) const client = serverSupabaseClient(event) if (Array.isArray(domain) || Array.isArray(user_id)) createError({ statusCode: 400, statusMessage: "Bad request. Query parameters are not valid." }) const { data: domainData } = await client.from<Domains>("domains").select("*").eq("url", domain).maybeSingle() if (domainData.user_id === user.id) return true const data = (await $fetch(`https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains`, { method: "POST", headers: { Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`, }, body: { name: domain, }, })) as any console.log({ domain, data }) // Domain is already owned by another team but you can request delegation to access it if (data.error?.code === "forbidden") return createError({ statusCode: 400, statusMessage: data.error.code }) // Domain is already being used by a different project if (data.error?.code === "domain_taken") return createError({ statusCode: 409, statusMessage: data.error.code }) const { error: domainError } = await client.from<Domains>("domains").upsert({ url: domain, user_id: user.id, active: false, }) if (domainError) return createError({ statusCode: 400, statusMessage: domainError.message }) return data } catch (err) { return createError({ statusCode: 500, statusMessage: err }) } })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/api/check-domain.post.ts
TypeScript
//ref: https://github.com/vercel/platforms/blob/main/pages/api/domain/check.ts import { serverSupabaseClient } from "#supabase/server" import type { Domains } from "~~/utils/types" export default defineEventHandler(async (event) => { try { const { domain, subdomain = false } = await useBody(event) const client = serverSupabaseClient(event) if (Array.isArray(domain)) return createError({ statusCode: 400, statusMessage: "Bad request. domain parameter cannot be an array." }) // if (subdomain) { // const sub = (domain as string).replace(/[^a-zA-Z0-9/-]+/g, ""); // const data = await prisma.site.findUnique({ // where: { // subdomain: sub, // }, // }); // const available = data === null && sub.length !== 0; // return res.status(200).json(available); // } const data = (await $fetch(`https://api.vercel.com/v6/domains/${domain}/config`, { headers: { Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`, }, })) as any console.log({ domain, data }) const valid = data?.configuredBy ? true : false if (valid) { const { error: domainError } = await client.from<Domains>("domains").update({ url: domain, active: true, }) if (domainError) return createError({ statusCode: 400, statusMessage: "Bad request. domain parameter cannot be an array." }) } return { valid } } catch (err) { return createError({ statusCode: 404, statusMessage: err }) } })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/api/delete-domain.post.ts
TypeScript
// ref: https://github.com/vercel/platforms/blob/main/lib/api/domain.ts export default defineEventHandler(async (event) => { try { const { domain, user_id } = await useBody(event) if (Array.isArray(domain) || Array.isArray(user_id)) createError({ statusCode: 400, statusMessage: "Bad request. Query parameters are not valid." }) const data = (await $fetch( `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}`, { method: "DELETE", headers: { Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`, }, } )) as any console.log({ domain, data }) // Domain is successfully added // await prisma.site.update({ // where: { // id: siteId, // }, // data: { // customDomain: domain, // }, // }); return data } catch (err) { return createError({ statusCode: 500, statusMessage: err }) } })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/api/request-delegation.ts
TypeScript
export default defineEventHandler((event) => { return 'Hello add-domain' })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/api/user-validation.post.ts
TypeScript
export default defineEventHandler(async (event) => { const { access_token } = await useBody(event) const hostname = event.req.headers.host // validate this token // setCookie(event, "sb-access-token", access_token, { // maxAge: 60 * 60 * 8 ?? 0, // path: "/", // sameSite: "lax", // }) return "auth cookie set" })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/middleware/login.ts
TypeScript
import { sendRedirect, defineEventHandler } from "h3" export default defineEventHandler(async (event) => { const { req, res } = event const referrer = req.headers.referer const cookie = useCookies(event) const accessToken = cookie["sb-access-token"] const refreshToken = cookie["sb-refresh-token"] // console.log({ url: req.url, referrer, accessToken, refreshToken, cookie }) // if cookie already exist in main route, then redirect with jwt if (req.url === "/login" && referrer && accessToken && refreshToken) { // redirect with same parameter as Supabase login return await sendRedirect( event, referrer + `#access_token=${accessToken}&expires_in=604800&provider_token=${process.env.GITHUB_PROVIDER_TOKEN}&refresh_token=${refreshToken}&token_type=bearer`, 302 ) } })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/middleware/subdomain.ts
TypeScript
export default defineEventHandler(({ req, res, context }) => { const hostname = req.headers.host || "keypress.blog" const mainDomain = ["localhost:3000", "keypress.blog"] if (!mainDomain.includes(hostname)) { const currentHost = process.env.NODE_ENV === "production" && process.env.VERCEL === "1" ? hostname.replace(`.keypress.blog`, "") : hostname.replace(`.localhost:3000`, "") console.log({ currentHost }) context.subdomain = currentHost } })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
server/routes/og/[slug].ts
TypeScript
import { readFileSync } from "fs" import { join, resolve } from "path" import { serverSupabaseClient } from "#supabase/server" import { useUrl } from "~~/composables/url" import { Resvg, ResvgRenderOptions } from "@resvg/resvg-js" import type { Posts } from "~~/utils/types" import satori from "satori" export default defineEventHandler(async (event) => { const client = serverSupabaseClient(event) const url = useUrl() const slug = event.context.params.slug const fonts = ["arial.ttf", "arial_bold.ttf"] try { const { data, error } = await client .from<Posts>("posts") .select("title, profiles(name, avatar_url)") .eq("slug", slug) .single() if (error) throw Error(error.message) // svg inspired from https://og-playground.vercel.app/ const svg = await satori( { type: "div", props: { style: { display: "flex", height: "100%", width: "100%", alignItems: "center", justifyContent: "center", letterSpacing: "-.02em", fontWeight: 700, background: "#f8f9fa", }, children: [ { type: "img", props: { style: { right: 42, bottom: 42, position: "absolute", display: "flex", alignItems: "center", width: "300px", }, src: url + "/banner.png", }, }, { type: "div", props: { style: { left: 42, bottom: 42, position: "absolute", display: "flex", alignItems: "center", }, children: [ { type: "img", props: { style: { width: "70px", height: "70px", borderRadius: "9999px", }, src: data.profiles.avatar_url, }, }, { type: "p", props: { style: { marginLeft: "20px", fontSize: "24px", }, children: data.profiles.name, }, }, ], }, }, { type: "div", props: { style: { display: "flex", flexWrap: "wrap", justifyContent: "center", padding: "20px 50px", margin: "0 42px 150px 42px", fontSize: "64px", width: "auto", maxWidth: 1200 - 48 * 2, textAlign: "center", backgroundColor: "#2D2D2D", borderRadius: "30px", color: "white", lineHeight: 1.4, }, children: data.title, }, }, ], }, }, { width: 1200, height: 630, fonts: [ { name: "Arial", data: readFileSync(join(process.cwd(), "public/fonts", fonts[0])), weight: 400, style: "normal", }, { name: "Arial", data: readFileSync(join(process.cwd(), "public/fonts", fonts[1])), weight: 700, style: "normal", }, ], } ) // render to svg as image const resvg = new Resvg(svg, { fitTo: { mode: "width", value: 1200, }, font: { fontFiles: fonts.map((i) => join(resolve("."), "public/fonts", i)), // Load custom fonts. loadSystemFonts: false, }, }) const resolved = await Promise.all( resvg.imagesToResolve().map(async (url) => { console.info("image url", url) const img = await fetch(url) const buffer = await img.arrayBuffer() return { url, buffer: Buffer.from(buffer), } }) ) if (resolved.length > 0) { for (const result of resolved) { const { url, buffer } = result resvg.resolveImage(url, buffer) } } const renderData = resvg.render() const pngBuffer = renderData.asPng() event.res.setHeader("Cache-Control", "s-maxage=7200, stale-while-revalidate") return pngBuffer } catch (err) { return createError({ statusCode: 500, statusMessage: err }) } })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/functions.ts
TypeScript
import { Posts } from "./types" export const constructUrl = (post: Posts, subdomain = false) => { if (subdomain) return `/${post.slug}` if (process.dev) return `http://${post?.profiles?.username}.localhost:3000/${post.slug}` else { if (post?.profiles?.domains?.active) return `https://${post.profiles.domains.url}/${post.slug}` else return `https://${post?.profiles?.username}.keypress.blog/${post.slug}` } }
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/code.ts
TypeScript
import { Extension } from "@tiptap/core" import Code from "@tiptap/extension-code" import CodeBlock from "@tiptap/extension-code-block" import CodeBlockLowLight from "@tiptap/extension-code-block-lowlight" import { lowlight } from "lowlight" import css from "highlight.js/lib/languages/css" import js from "highlight.js/lib/languages/javascript" import ts from "highlight.js/lib/languages/typescript" import html from "highlight.js/lib/languages/xml" // ref: https://tiptap.dev/experiments/commands lowlight.registerLanguage("html", html) lowlight.registerLanguage("css", css) lowlight.registerLanguage("js", js) lowlight.registerLanguage("ts", ts) export default Extension.create({ name: "code", addExtensions() { return [ Code, CodeBlock, CodeBlockLowLight.configure({ lowlight, }), ] }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/commands.ts
TypeScript
import { Extension } from "@tiptap/core" import Suggestion from "@tiptap/suggestion" // ref: https://tiptap.dev/experiments/commands export default Extension.create({ name: "commands", addOptions() { return { suggestion: { char: "/", command: ({ editor, range, props }) => { props.command({ editor, range }) }, }, } }, addProseMirrorPlugins() { return [ Suggestion({ editor: this.editor, startOfLine: true, ...this.options.suggestion, }), ] }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/hardbreak.ts
TypeScript
import { Extension } from "@tiptap/core" export default Extension.create({ addKeyboardShortcuts() { // copied from tiptap const defaultHandler = () => this.editor.commands.first(({ commands }) => [ () => commands.newlineInCode(), () => commands.createParagraphNear(), () => commands.liftEmptyBlock(), () => commands.splitListItem("listItem"), () => commands.splitBlock(), ]) const shiftEnter = () => { return this.editor.commands.first(({ commands }) => [ () => commands.newlineInCode(), () => commands.createParagraphNear(), ]) } const modEnter = () => { return this.editor.commands.first(({ commands }) => [ () => commands.newlineInCode(), (a) => { commands.selectTextblockEnd() return commands.createParagraphNear() }, ]) } return { Enter: defaultHandler, "Shift-Enter": shiftEnter, "Mod-Enter": modEnter, } }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/iframe.ts
TypeScript
// ref: https://github.com/ueberdosis/tiptap/blob/9afadeb7fe368f95064f84424d6a3dd6cd85b43d/demos/src/Experiments/Embeds/Vue/iframe.ts import { mergeAttributes, Node } from "@tiptap/core" export interface IframeOptions { allowFullscreen: boolean HTMLAttributes: { [key: string]: any } } declare module "@tiptap/core" { interface Commands<ReturnType> { iframe: { /** * Add an iframe */ setIframe: (options: { src: string }) => ReturnType } } } export default Node.create<IframeOptions>({ name: "iframe", group: "block", atom: true, addOptions() { return { allowFullscreen: true, HTMLAttributes: { class: "iframe-wrapper", }, } }, addAttributes() { return { src: { default: null, }, frameborder: { default: 0, }, allowfullscreen: { default: this.options.allowFullscreen, parseHTML: () => this.options.allowFullscreen, }, } }, parseHTML() { return [ { tag: "iframe", }, ] }, renderHTML({ HTMLAttributes }) { return [ "div", this.options.HTMLAttributes, ["iframe", mergeAttributes(HTMLAttributes, { frameborder: 10, tabindex: -1 })], ] }, addCommands() { return { setIframe: (options: { src: string }) => ({ tr, dispatch }) => { const { selection } = tr const node = this.type.create(options) if (dispatch) { tr.replaceRangeWith(selection.from, selection.to, node) } return true }, } }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/link.ts
TypeScript
// 1. Import the extension import Link from "@tiptap/extension-link" // 2. Overwrite the keyboard shortcuts export default Link.extend({ exitable: true, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/move.ts
TypeScript
import { CommandProps, Editor, Extension } from "@tiptap/core" import { findParentNodeOfType } from "prosemirror-utils" import { EditorState, NodeSelection, Selection, TextSelection } from "prosemirror-state" import { Fragment, NodeType, Slice } from "prosemirror-model" import { ReplaceStep } from "prosemirror-transform" declare module "@tiptap/core" { interface Commands<ReturnType> { move: { moveParent: (direction: "up" | "down") => ReturnType } } } // ref: https://github.com/bangle-io/bangle.dev/blob/960fb4706a953ef910a9ddf2d80a7f10bdd2921b/core/core-commands.js#L101 function arrayify(x: any) { if (x == null) { throw new Error("undefined value passed") } return Array.isArray(x) ? x : [x] } function mapChildren(node: any, callback: any) { const array = [] for (let i = 0; i < node.childCount; i++) { array.push(callback(node.child(i), i, node instanceof Fragment ? node : node.content)) } return array } const moveNode = (type: NodeType, dir: "up" | "down") => { const isDown = dir === "down" return (state: EditorState, dispatch: any) => { // @ts-ignore (node) only exist in custom element. eg: image, iframe const { $from, node } = state.selection const currentResolved = findParentNodeOfType(type)(state.selection) ?? { depth: 1, node, pos: 34, start: 34, } if (!currentResolved.node) { return false } const { node: currentNode } = currentResolved const parentDepth = currentResolved.depth - 1 const parent = $from.node(parentDepth) const parentPos = $from.start(parentDepth) if (currentNode.type !== type) { return false } const arr = mapChildren(parent, (node) => node) let index = arr.indexOf(currentNode) let swapWith = isDown ? index + 1 : index - 1 // If swap is out of bound if (swapWith >= arr.length || swapWith < 0) { return false } const swapWithNodeSize = arr[swapWith].nodeSize ;[arr[index], arr[swapWith]] = [arr[swapWith], arr[index]] let tr = state.tr let replaceStart = parentPos let replaceEnd = $from.end(parentDepth) const slice = new Slice(Fragment.fromArray(arr), 0, 0) // the zeros lol -- are not depth they are something that represents the opening closing // .toString on slice gives you an idea. for this case we want them balanced tr = tr.step(new ReplaceStep(replaceStart, replaceEnd, slice, false)) tr = tr.setSelection( Selection.near(tr.doc.resolve(isDown ? $from.pos + swapWithNodeSize : $from.pos - swapWithNodeSize)) ) if (dispatch) { dispatch(tr.scrollIntoView()) } return true } } export default Extension.create({ name: "move", addCommands() { return { moveParent: (direction: "up" | "down") => ({ editor, state, dispatch, ...a }) => { // @ts-ignore (node) only exist in custom element. eg: image, iframe const type = editor.state.selection.node?.type ?? editor.state.selection.$head.parent.type return moveNode(type, direction)(state, dispatch) }, } }, addKeyboardShortcuts() { return { "Alt-ArrowUp": () => this.editor.commands.moveParent("up"), "Alt-ArrowDown": () => this.editor.commands.moveParent("down"), } }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/placeholder.ts
TypeScript
// 1. Import the extension import Placeholder from "@tiptap/extension-placeholder" import { NodeSelection, TextSelection } from "prosemirror-state" // 2. Overwrite the keyboard shortcuts export default Placeholder.extend({ addOptions() { return { ...this.parent?.(), placeholder: ({ node, editor }) => { const selection = editor.state.selection as NodeSelection if (selection instanceof TextSelection) { return " Type '/' for commands" } }, includeChildren: true, } }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/suggestion.ts
TypeScript
import type { Editor, Range } from "@tiptap/core" import { VueRenderer } from "@tiptap/vue-3" import tippy from "tippy.js" import CommandsList from "~~/components/Tiptap/CommandList.vue" interface Command { editor: Editor range: Range } export default { items: ({ query }) => { return [ { title: "Heading 2", description: "Big section heading.", command: ({ editor, range }: Command) => { editor.chain().focus().deleteRange(range).setNode("heading", { level: 2 }).run() }, }, { title: "Heading 3", description: "Medium section heading.", command: ({ editor, range }: Command) => { editor.chain().focus().deleteRange(range).setNode("heading", { level: 3 }).run() }, }, { title: "Numbered List", description: "Create a list with numbering.", command: ({ editor, range }: Command) => { editor.chain().focus().deleteRange(range).wrapInList("orderedList").run() }, }, { title: "Bulleted List", description: "Create a simple bulleted list.", command: ({ editor, range }: Command) => { editor.chain().focus().deleteRange(range).wrapInList("bulletList").run() }, }, { title: "Image", description: "Upload or embed with link.", command: ({ editor, range }: Command) => { editor.chain().focus().deleteRange(range).openModal("image").run() }, }, { title: "Iframe", description: "Embed website with link.", command: ({ editor, range }: Command) => { editor.chain().focus().deleteRange(range).openModal("iframe").run() }, }, // { // title: "bold", // command: ({ editor, range }: Command) => { // editor.chain().focus().deleteRange(range).setMark("bold").run() // }, // }, // { // title: "underline", // command: ({ editor, range }: Command) => { // editor.chain().focus().deleteRange(range).setMark("underline").run() // }, // }, // { // title: "italic", // command: ({ editor, range }: Command) => { // editor.chain().focus().deleteRange(range).setMark("italic").run() // }, // }, ] .filter((item) => item.title.toLowerCase().startsWith(query.toLowerCase())) .slice(0, 10) }, render: () => { let component let popup return { onStart: (props) => { component = new VueRenderer(CommandsList, { props, editor: props.editor, }) if (!props.clientRect) { return } popup = tippy("body", { getReferenceClientRect: props.clientRect, appendTo: () => document.body, content: component.element, showOnCreate: true, interactive: true, trigger: "manual", placement: "bottom-start", }) }, onUpdate(props) { component.updateProps(props) if (!props.clientRect) { return } popup[0].setProps({ getReferenceClientRect: props.clientRect, }) }, onKeyDown(props) { if (props.event.key === "Escape") { popup[0].hide() return true } return component.ref?.onKeyDown(props.event) }, onExit() { popup[0].destroy() component.destroy() }, } }, }
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/tiptap/upload.ts
TypeScript
import { Extension } from "@tiptap/core" import ModalImage from "~~/components/Tiptap/ModalImage.vue" import ModalIframe from "~~/components/Tiptap/ModalIframe.vue" import { createApp } from "vue" declare module "@tiptap/core" { interface Commands<ReturnType> { upload: { openModal: (type: "image" | "iframe") => ReturnType } } } export default Extension.create({ name: "upload", addCommands() { return { openModal: (type: "image" | "iframe") => ({ commands, editor }) => { let component: typeof ModalImage switch (type) { case "image": { component = ModalImage break } case "iframe": { component = ModalIframe break } } if (!component) return const instance = createApp(component, { show: true, editor, }).mount("#modal") return !!instance }, } }, })
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
utils/types.ts
TypeScript
// generated from https://supabase-schema.vercel.app/ export interface Profiles { id: string /* primary key */; username?: string; avatar_url?: string; name?: string; created_at?: string; subdomain?: string; domains: Domains; posts: Posts[]; } export interface Domains { user_id?: string /* foreign key to profiles.id */; url: string /* primary key */; active?: boolean; created_at?: string; profiles?: Profiles; } export interface Posts { id: string /* primary key */; author_id?: string /* foreign key to profiles.id */; created_at?: string; slug?: string; title?: string; body?: string; cover_img?: string; active?: boolean; tags?: string[]; profiles?: Profiles; featured?: boolean; } export interface Tags { name: string; count: number; }
zernonia/keypress
266
KeyPress - an open-source blogging platform + free custom domains.
Vue
zernonia
zernonia
Troop Travel
.eslintrc.cjs
JavaScript
module.exports = { extends: '@antfu', rules: { 'vue/no-unused-vars': 'warn', 'vue/valid-v-for': 'warn', }, }
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/.keys.ts
TypeScript
import type { InjectionKey, Ref } from "vue"; import type { Provider } from "./.types"; export const rootKey = Symbol() as InjectionKey<{ hideProviderLabel?: boolean; providers?: Provider[]; }>;
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/.types.ts
TypeScript
export type Provider = | "facebook" | "twitter" | "google" | "discord" | "github" | "gitlab" | "apple" | "slack" | "azure" | "bitbucket" | "tiktok" | "linkedin";
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/Form.vue
Vue
<script setup lang="ts"> const emits = defineEmits<{ (e: 'submit', payload: { [key: string]: any }): void }>() function handleSignIn(ev: Event) { ev.preventDefault() const form = ev.target as HTMLFormElement if (!form) return const formData = new FormData(form) emits( 'submit', Object.fromEntries(formData) as { email: string; password?: string }, ) } </script> <template> <form @submit="handleSignIn"> <slot /> </form> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/Form/Button.vue
Vue
<script setup lang="ts"> defineProps<{ label?: string }>() </script> <template> <input type="submit" style="cursor: pointer" :value="label ?? 'Sign In'"> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/Form/InputText.vue
Vue
<script setup lang="ts"> import type { InputHTMLAttributes } from 'vue' interface Props extends /* @vue-ignore */ InputHTMLAttributes { label: string name: string type: string } defineProps<Props>() </script> <script lang="ts"> export default { inheritAttrs: false, } </script> <template> <div> <label :for="name">{{ label }}</label> <input v-bind="$attrs" :id="name" required :type="type" :name="name"> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/Header.vue
Vue
<script setup lang="ts"></script> <template> <div> <slot name="logo" /> <slot> <h2>Create your account</h2> <p>to continue to Acme</p> </slot> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/SocialProvider.vue
Vue
<script setup lang="ts"> import type { Component } from 'vue' import { rootKey } from './.keys' import type { Provider } from './.types' const props = defineProps<{ provider: Provider is?: Component }>() const emits = defineEmits<{ (e: 'select', payload: Provider): void }>() const rootProps = inject(rootKey) const providerInfo = { facebook: { title: 'Facebook', icon: 'logos:facebook' }, twitter: { title: 'Twitter', icon: 'logos:twitter' }, google: { title: 'Google', icon: 'logos:google-icon' }, discord: { title: 'Discord', icon: 'logos:discord-icon' }, github: { title: 'GitHub', icon: 'devicon:github' }, gitlab: { title: 'gitlab', icon: 'devicon:gitlab' }, apple: { title: 'apple', icon: 'devicon:apple' }, slack: { title: 'slack', icon: 'devicon:slack' }, azure: { title: 'azure', icon: 'devicon:azure' }, bitbucket: { title: 'bitbucket', icon: 'devicon:bitbucket' }, tiktok: { title: 'TikTok', icon: 'logos-tiktok-icon' }, linkedin: { title: 'LinkedIn', icon: 'devicon:linkedin' }, } const mappedProvider = computed(() => providerInfo[props.provider]) const component = computed(() => { return props.is ?? 'button' }) </script> <template> <component :is="component" @click="emits('select', provider)"> <Icon :name="mappedProvider.icon" /> <div v-if="!rootProps?.hideProviderLabel"> <slot> Sign in with {{ mappedProvider.title }} </slot> </div> </component> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/SocialProviders.vue
Vue
<script setup lang="ts"> import { rootKey } from './.keys' import type { Provider } from './.types' const emits = defineEmits<{ (e: 'select', payload: Provider): void }>() const rootProps = inject(rootKey) </script> <script lang="ts"> export default { inheritAttrs: false, } </script> <template> <LegoAuthSocialProvider v-for="provider in rootProps?.providers" v-bind="$attrs" :key="provider" :provider="provider" @select="emits('select', $event)" /> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Auth/index.vue
Vue
<script setup lang="ts"> import { rootKey } from './.keys' import type { Provider } from './.types' const props = defineProps<{ hideProviderLabel?: boolean providers?: Provider[] }>() provide(rootKey, props) </script> <template> <div> <slot> <LegoAuthHeader /> <LegoAuthSocialProvider provider="google" /> <LegoAuthSocialProvider provider="facebook" /> <LegoAuthSocialProvider provider="twitter" /> <LegoAuthSocialProvider provider="github" /> <LegoAuthSocialProvider provider="tiktok" /> <LegoAuthSocialProvider provider="azure" /> <LegoAuthForm> <LegoAuthFormInputText name="email" type="email" label="Email Address" /> <LegoAuthFormInputText name="password" type="password" label="Password" /> <LegoAuthFormButton /> </LegoAuthForm> </slot> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/CountDown/index.vue
Vue
<script setup lang="ts"> const props = defineProps<{ date: Date enableDays?: boolean }>() const timestamp = useTimestamp() const dateInMilliseconds = computed(() => props.date?.getTime()) const differenceInSeconds = computed(() => (dateInMilliseconds.value - timestamp.value) / 1000) // in seconds const days = computed(() => props.enableDays ? Math.floor(differenceInSeconds.value / 86400) : undefined) const hours = computed(() => props.enableDays ? Math.floor((differenceInSeconds.value % 86400) / 3600) : Math.floor(differenceInSeconds.value / 3600)) const minutes = computed(() => Math.floor((differenceInSeconds.value % 3600) / 60)) const seconds = computed(() => Math.floor((differenceInSeconds.value % 60))) </script> <template> <div v-if="date"> <slot :days="days" :hours="hours" :minutes="minutes" :seconds="seconds"> {{ days }} days {{ hours }} hours {{ minutes }} minutes {{ seconds }} seconds </slot> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/GithubStar/index.vue
Vue
<script lang="ts" setup> import { withBase, withoutBase } from 'ufo' import { useFetch } from '#imports' const props = defineProps<{ repo: string raw?: boolean to?: string }>() const repo = computed(() => { // support users providing full github url return withoutBase(props.repo, 'https://github.com/') }) const link = computed(() => { return props.to || withBase(repo.value, 'https://github.com/') }) // pull the stars from the server const { data } = await useFetch('/api/get-github-stars', { query: { repo: repo.value, }, watch: [ repo, ], key: `github-stars-${repo.value}`, }).catch(() => { return { data: ref({ stars: 0 }), } }) const stars = computed(() => { if (props.raw) return data.value return new Intl.NumberFormat('en', { notation: 'compact' }).format(data.value) }) </script> <template> <NuxtLink :to="link" target="_blank" :aria-label="`Star ${repo} on GitHub`"> <slot :stars="stars"> <div>{{ stars }}</div> </slot> </NuxtLink> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/MarqueeBanner/.composables.ts
TypeScript
import { useSlots, inject, ref, type Ref, computed } from "vue" import { rootKey } from "./.keys" export const useMarqueeBanner = (el: Ref<HTMLElement[] | undefined>) => { const slots = useSlots() const rootInject = inject(rootKey, { width: ref(0), }) const componentsWidth = computed(() => el.value?.map((i) => { const computedStyle = window.getComputedStyle(i) const width = i.offsetWidth const marginLeft = parseInt(computedStyle.marginLeft, 0) const marginRight = parseInt(computedStyle.marginRight, 0) return width + marginLeft + marginRight }).reduce((prev, curr) => prev + curr, 0) ?? 0) const baseEl = computed(() => { const defaultSlots = slots.default?.() if (!defaultSlots?.length) return const slotItems = defaultSlots.flatMap((i) => { if (i.type.toString() === 'Symbol(v-fgt)') return i.children else return i }) return slotItems }) const shadowCount = computed(() => componentsWidth.value !== 0 ? Math.ceil(rootInject.width.value / componentsWidth.value) : rootInject.shadowCount) const shadowEl = computed(() => { return Array.from(Array(shadowCount.value).keys()).map(() => baseEl.value).flat() }) const isHovering = ref(false) const onMouseEnter = (event: MouseEvent) => { isHovering.value = true } const onMouseLeave = (event: MouseEvent) => { isHovering.value = false } return { componentsWidth, baseEl, shadowEl, shadowCount, isHovering, onMouseEnter, onMouseLeave } }
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/MarqueeBanner/.keys.ts
TypeScript
import type { InjectionKey, Ref } from "vue"; export const rootKey = Symbol() as InjectionKey<{ width: Ref<number>, speed?: number, hoveredSpeed?: number shadowCount?: number }>;
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/MarqueeBanner/Left.vue
Vue
<script setup lang="ts"> import { ref } from 'vue' import { rootKey } from './.keys' import { useMarqueeBanner } from './.composables' const el = ref<HTMLElement[]>() const offset = ref(0) const intervalId = ref() const rootInject = inject(rootKey, { speed: 1, hoveredSpeed: 0.5, }) const { componentsWidth, baseEl, shadowEl, isHovering, onMouseEnter, onMouseLeave } = useMarqueeBanner(el) onMounted(() => { intervalId.value = setInterval(() => { if (Math.abs(offset.value) >= (componentsWidth.value)) { offset.value = 0 } else { if (isHovering.value) offset.value -= rootInject.hoveredSpeed else offset.value -= rootInject.speed } }, 5) }) onUnmounted(() => { clearInterval(intervalId.value) }) </script> <template> <div dir="ltr" style="display: flex;" :style="{ transform: `translateX(${offset}px)` }" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave"> <component :is="component" v-for="(component, index) in baseEl" ref="el" :key="index" /> <component :is="component" v-for="(component, index) in shadowEl" :key="index" /> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/MarqueeBanner/Right.vue
Vue
<script setup lang="ts"> import { ref } from 'vue' import { rootKey } from './.keys' import { useMarqueeBanner } from './.composables' const rootInject = inject(rootKey, { speed: 1, hoveredSpeed: 0.5, }) const el = ref<HTMLElement[]>() const offset = ref(0) const intervalId = ref() const { componentsWidth, baseEl, shadowEl, isHovering, onMouseEnter, onMouseLeave } = useMarqueeBanner(el) onMounted(() => { intervalId.value = setInterval(() => { if (Math.abs(offset.value) >= (componentsWidth.value)) { offset.value = 0 } else { if (isHovering.value) offset.value += rootInject.hoveredSpeed else offset.value += rootInject.speed } }, 5) }) onUnmounted(() => { clearInterval(intervalId.value) }) </script> <template> <div dir="ltr" style="display: flex; position: relative; float: right" :style="{ transform: `translateX(${offset}px)` }" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave"> <component :is="component" v-for="(component, index) in baseEl" ref="el" :key="index" /> <component :is="component" v-for="(component, index) in shadowEl" :key="index" /> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/MarqueeBanner/index.vue
Vue
<script setup lang="ts"> import { provide, ref } from 'vue' import { rootKey } from './.keys' const props = withDefaults(defineProps<{ speed?: number hoveredSpeed?: number shadowCount?: number }>(), { speed: 1, hoveredSpeed: 0.5, shadowCount: 5, }) const el = ref<HTMLDivElement>() const { width } = useElementBounding(el) provide(rootKey, { width, ...props, }) </script> <template> <div ref="el" class="marquee-container" > <slot /> </div> </template> <style> .marquee-container { overflow: hidden; } </style>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/PageProgress/index.vue
Vue
<script setup lang="ts"> import type { MaybeElementRef } from '@vueuse/core' const props = defineProps<{ target: MaybeElementRef }>() const { target } = toRefs(props) const progress = ref(0) const offsetTop = ref(0) onMounted(() => { window.addEventListener('scroll', () => { const { documentElement, body } = document const windowScroll = (body.scrollTop || documentElement.scrollTop) - offsetTop.value const height = documentElement.scrollHeight - documentElement.clientHeight - offsetTop.value progress.value = Math.min((Math.max(0, windowScroll) / height) * 100, 100) }) }) whenever(target, () => { const el = unrefElement(target.value) as HTMLElement if (!el) return offsetTop.value = el.offsetTop }) </script> <template> <div> <slot :progress="progress"> <div>{{ progress }}</div> </slot> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Preview/.keys.ts
TypeScript
import type { InjectionKey, Ref } from "vue"; export const rootKey = Symbol() as InjectionKey<{ isPreviewActive: Ref<boolean>, }>;
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Preview/Dialog.vue
Vue
<script setup lang="ts"> import { rootKey } from './.keys' defineProps<{ name?: string }>() const { isPreviewActive } = inject(rootKey) </script> <script lang="ts"> export default { inheritAttrs: false, } </script> <template> <Teleport to="body"> <div v-if="isPreviewActive" v-bind="$attrs" role="dialog" style="cursor: zoom-out;" aira-modal="true" @click="isPreviewActive = false" /> </Teleport> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Preview/index.vue
Vue
<script setup lang="ts"> import { ref } from 'vue' import type { CSSProperties } from 'nuxt/dist/app/compat/capi' import { rootKey } from './.keys' const props = withDefaults(defineProps<{ duration?: number maxWidth?: number }>(), { duration: 500, maxWidth: 1000, }) const el = ref<HTMLElement>() const isPreviewActive = ref(false) const isTransitioning = refAutoReset(false, props.duration) const { width: windowWidth, height: windowHeight } = useWindowSize({ includeScrollbar: false, }) onKeyStroke('Escape', (e) => { e.preventDefault() isPreviewActive.value = false }) const computedStyle = ref<CSSProperties>({ position: 'absolute', zIndex: '999', }) const initialScrollPosition = ref(0) function handleScroll() { const diff = Math.abs(initialScrollPosition.value - window.scrollY) if (diff > 10) isPreviewActive.value = false } function applyStying() { if (!isPreviewActive.value || !el.value) return const { top, left, width, height } = el.value.getBoundingClientRect() const scaleX = Math.max(width, windowWidth.value) / width const scaleY = Math.max(height, windowHeight.value) / height const maxScaleX = props.maxWidth / width const scale = Math.min(Math.min(scaleX, maxScaleX), scaleY) const translateX = (-left + (windowWidth.value - width) / 2) / scale const translateY = (-top + (windowHeight.value - height) / 2) / scale const transform = `scale(${scale}) translate3d(${translateX}px, ${translateY}px, 0)` computedStyle.value.top = `${top + window.pageYOffset}px` computedStyle.value.left = `${left}px` computedStyle.value.width = `${width}px` computedStyle.value.transform = transform computedStyle.value.cursor = 'zoom-out' } function clearStyling() { computedStyle.value.transform = 'scale(1)' computedStyle.value.cursor = 'zoom-in' } watch(isPreviewActive, (n) => { // add scroll event listener if (n) { nextTick(() => { applyStying() initialScrollPosition.value = window.scrollY document.addEventListener('scroll', handleScroll) }) } else { clearStyling() initialScrollPosition.value = 0 isTransitioning.value = true document.removeEventListener('scroll', handleScroll) } }) watch(windowWidth, () => { applyStying() }) provide(rootKey, { isPreviewActive, }) </script> <script lang="ts"> export default { inheritAttrs: false, } </script> <template> <div ref="el" :style="{ opacity: isPreviewActive || isTransitioning ? '0' : '1', cursor: 'zoom-in', }" v-bind="$attrs" role="button" tabindex="0" @click="isPreviewActive = !isPreviewActive" @keydown.enter="isPreviewActive = !isPreviewActive" > <slot /> </div> <!-- Zoom element --> <div v-if="isPreviewActive || isTransitioning" v-bind="$attrs" :style="computedStyle" @click="isPreviewActive = !isPreviewActive" > <slot /> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/SocialShare/.keys.ts
TypeScript
import type { InjectionKey, Ref } from "vue"; export default Symbol() as InjectionKey<Ref<string>>;
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/SocialShare/Facebook.vue
Vue
<script setup lang="ts"> import key from './.keys' const path = inject(key) const url = computed( () => `https://www.facebook.com/sharer/sharer.php?u=${encodeURI( path?.value ?? '', )}`, ) </script> <template> <NuxtLink :to="url" target="_blank"> <slot> <Icon name="uil:facebook" /> </slot> </NuxtLink> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/SocialShare/Link.vue
Vue
<script setup lang="ts"> import key from './.keys' const path = inject(key) const { copy } = useClipboard({ source: path }) </script> <template> <button @click="copy()"> <slot> <Icon name="uil:share-alt" /> </slot> </button> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/SocialShare/LinkedIn.vue
Vue
<script setup lang="ts"> import key from './.keys' const props = defineProps<{ text?: string }>() const path = inject(key) const url = computed( () => `https://www.linkedin.com/shareArticle/?mini=true&url=${encodeURI( path?.value ?? '', )}&title=${encodeURI(props.text ?? '')}`, ) </script> <template> <NuxtLink :to="url" target="_blank"> <slot> <Icon name="uil:linkedin" /> </slot> </NuxtLink> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/SocialShare/Reddit.vue
Vue
<script setup lang="ts"> import key from './.keys' const props = defineProps<{ text?: string }>() const path = inject(key) const url = computed( () => `http://www.reddit.com/submit?url=${encodeURI( path?.value ?? '', )}&title=${encodeURI(props.text ?? '')}`, ) </script> <template> <NuxtLink :to="url" target="_blank"> <slot> <Icon name="mdi:reddit" /> </slot> </NuxtLink> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/SocialShare/Twitter.vue
Vue
<script setup lang="ts"> import key from './.keys' const props = defineProps<{ text?: string }>() const path = inject(key) const url = computed( () => `https://twitter.com/intent/tweet?url=${encodeURI( path?.value ?? '', )}&text=${encodeURI(props.text ?? '')}`, ) </script> <template> <NuxtLink :to="url" target="_blank"> <slot> <Icon name="uil:twitter" /> </slot> </NuxtLink> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/SocialShare/index.vue
Vue
<script setup lang="ts"> import key from './.keys' const props = defineProps<{ url?: string }>() const url = ref(props.url) onMounted(() => { if (!url.value) url.value = window.location.origin + window.location.pathname }) provide(key, url) </script> <template> <div> <slot> <LegoSocialShareLink /> </slot> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Toc/Links.vue
Vue
<script setup lang="ts"> import type { TocLink } from '@nuxt/content/dist/runtime/types' defineProps<{ links: TocLink[] }>() const router = useRouter() function scrollToHeading(id: string) { router.push(`#${id}`) } </script> <template> <ul> <li v-for="link in links" :key="link.text"> <a :href="`#${link.id}`" @click.prevent="scrollToHeading(link.id)"> <slot :link="link"> {{ link.text }} </slot> </a> <LegoTocLinks v-if="link.children" v-slot="{ link: childLink }" :links="link.children" :class="$attrs.class" :style="$attrs.style" > <slot :link="childLink" /> </LegoTocLinks> </li> </ul> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Toc/index.vue
Vue
<script setup lang="ts"></script> <template> <div> <div> <slot name="title"> Table of Contents </slot> </div> <slot>add <code>LegoTocLinks</code> </slot> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Tweet/.keys.ts
TypeScript
import type { InjectionKey, Ref } from "vue"; import type { Tweet } from "../../../types"; export default Symbol() as InjectionKey<Ref<Tweet>>;
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Tweet/Action.vue
Vue
<script setup lang="ts"></script> <template> <div> <slot> <LegoTweetActionLove /> <LegoTweetActionReply /> <LegoTweetActionCopy /> </slot> </div> </template>
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel
layer/components/Lego/Tweet/Action/.keys.ts
TypeScript
import type { InjectionKey, Ref } from "vue"; export const copiedKey = Symbol() as InjectionKey<Ref<Boolean>>;
zernonia/nuxt-lego
234
NuxtLego is an open source UI component layer for building your Nuxt content quick & beautiful.
Vue
zernonia
zernonia
Troop Travel