PB + Writer (#287)

* add pb models

* api rules has updated to view public

* pb setup is completed

* add migrate script

* add pb migrations

* ignore storage

* add pocketbase SDK dependency

* change Tag.id and PageCardDto.id to string for PocketBase

* add DocV1 content block types

* add PB client singleton and PB record types

* rewrite factory for PocketBase record types

* rewrite api.ts for PocketBase SDK

* remove unused Strapi files, add PB to config

* mark Task 7 complete in plan

* feat: verify build, tests, and lint pass with PocketBase API layer

* move completed plan: 2026-04-06-pocketbase-api-layer.md

* scaffold hudozka-writer with Vite 8, React 19, TS 5.9, Tiptap

* add PocketBase client and DocV1 types to writer

* add Login component for PocketBase superuser auth

* add App shell with auth gate and page loader

* add DocV1 <-> Tiptap serialization layer

* mark Task 5 complete in writer redesign plan

* add custom Tiptap nodes for DocV1 block types

* add Tiptap editor with toolbar and save to PocketBase

* add image picker with browse and upload

* feat: verify writer build and complete integration task

* move completed plan: 2026-04-06-hudozka-writer-redesign.md

* add local env

* rm textblock from writer

* add writer editor improvements design spec

* add writer editor improvements implementation plan

* feat: use @tiptap/markdown for text block serialization

* feat: add global markdown/rendered toggle

* feat: add BlockMenu component for block type selection

* feat: add hover + button for block insertion

* feat: add slash commands for block insertion

* feat: add interactive file block editor with FilePicker

* feat: show resolved page titles in card grid block

* move completed plan: 2026-04-07-writer-editor-improvements.md

* writer ui improved

* pages migration

* spec: draft/publish workflow for hudozka-writer

* spec: rename draft_doc to draft in spec

* plan: writer draft/publish implementation

* plan has moved

* gitignores

* plans upd

* feat(writer): update PbPage type for draft/publish workflow

* feat(writer): add save/publish/discard handlers with dirty tracking

* feat(writer): add DraftBanner component

* feat(writer): add Publish button and update toolbar layout

* feat(writer): add published toggle and update duplicate for new schema

* docs: mark manual verification steps as skipped in writer draft/publish plan

* move completed plan: 20260407-writer-draft-publish.md

* feat(writer): add BlockActions component for inline block menus

* feat(writer): add draggable NodeViews for text blocks

* feat(writer): use BlockActions in custom block NodeViews

* feat(writer): replace floating BlockInsert with inline BlockActions

* fix(writer): ensure all block wrappers have position: relative for BlockActions

* chore: mark manual verification tasks as skipped in writer block actions plan

* move completed plan: 20260408-writer-block-actions.md

* writer update

* refactor(writer): simplify BlockActions to always-visible delete + drag handle

* feat(writer): add BlockInsert component for inserting blocks between nodes

* feat(writer): redesign block sidebar with always-visible actions and insert button

* move completed plan: 20260408-writer-block-actions-redesign.md

* add spec: textblock container redesign for writer editor

* feat(writer): add TextBlock container node definition

* feat(writer): replace DraggableXxx wrappers with TextBlock container

* feat(writer): update Editor extensions for TextBlock container

* feat(writer): add split button to BlockActions for text blocks

* feat(writer): update serialization for TextBlock container

* feat(writer): update BlockMenu and SlashCommands for TextBlock

* fix(writer): use Fragment.from() for replaceWith calls in BlockActions and SlashCommands

* move completed plan: 20260408-textblock-container.md

* add air
This commit is contained in:
tmshv authored and GitHub committed 2026-04-12 19:02:03 +03:00
1 parent 907298779c
commit ed3f93de53
109 files changed
+40520 -427

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
.app {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.app-header {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 20px;
border-bottom: 1px solid #e0e0e0;
}
.app-title {
font-weight: 600;
}
.app-slug {
color: #888;
font-family: monospace;
}
.app-header button {
padding: 4px 12px;
border: 1px solid #ccc;
border-radius: 4px;
background: white;
cursor: pointer;
}
.app-header button:first-of-type {
margin-left: auto;
}
.app-main {
flex: 1;
padding: 20px;
max-width: 800px;
margin: 0 auto;
width: 100%;
}
.app-message {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
min-height: 100vh;
}
.app-error {
color: #c00;
}
.app-published-toggle {
display: flex;
align-items: center;
gap: 4px;
font-size: 0.9rem;
cursor: pointer;
user-select: none;
}
.app-published-toggle input {
cursor: pointer;
}
+134
View File
@@ -0,0 +1,134 @@
import { useState, useEffect, useCallback } from "react"
import { pb } from "./pb"
import { Login } from "./components/Login"
import { Editor } from "./components/Editor"
import type { PbPage } from "./types"
import "./App.css"
function getSlugFromUrl(): string | null {
const params = new URLSearchParams(window.location.search)
return params.get("page")
}
export function App() {
const [authenticated, setAuthenticated] = useState(pb.authStore.isValid)
const [page, setPage] = useState<PbPage | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState("")
const slug = getSlugFromUrl()
const loadPage = useCallback(async (slug: string) => {
setLoading(true)
setError("")
try {
const record = await pb.collection("pages").getFirstListItem<PbPage>(
`slug="${slug}"`,
)
setPage(record)
} catch {
setError(`Page "${slug}" not found`)
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
if (authenticated && slug) {
loadPage(slug)
}
}, [authenticated, slug, loadPage])
function handleLogout() {
pb.authStore.clear()
setAuthenticated(false)
setPage(null)
}
async function handleDuplicate() {
if (!page) return
const newSlug = `${page.slug}-copy`
try {
const record = await pb.collection("pages").create<PbPage>({
title: `${page.title} (copy)`,
slug: newSlug,
excerpt: page.excerpt,
date: page.date,
cover: page.cover,
doc: page.doc,
tags: page.tags,
published: false,
draft: null,
})
window.location.search = `?page=${record.slug}`
} catch (err) {
console.error("Duplicate failed:", err)
alert("Duplicate failed. Check console.")
}
}
async function handleTogglePublished() {
if (!page) return
try {
const updated = await pb.collection("pages").update<PbPage>(page.id, {
published: !page.published,
})
setPage(updated)
} catch (err) {
console.error("Toggle published failed:", err)
alert("Toggle published failed. Check console.")
}
}
if (!authenticated) {
return <Login onLogin={() => setAuthenticated(true)} />
}
if (!slug) {
return (
<div className="app-message">
<p>Add <code>?page=slug</code> to the URL to edit a page.</p>
<button onClick={handleLogout}>Logout</button>
</div>
)
}
if (loading) {
return <div className="app-message">Loading...</div>
}
if (error) {
return (
<div className="app-message">
<p className="app-error">{error}</p>
<button onClick={handleLogout}>Logout</button>
</div>
)
}
if (!page) {
return <div className="app-message">Loading...</div>
}
return (
<div className="app">
<header className="app-header">
<span className="app-title">{page.title}</span>
<span className="app-slug">/{page.slug}</span>
<label className="app-published-toggle">
<input
type="checkbox"
checked={page.published}
onChange={handleTogglePublished}
/>
Published
</label>
<button onClick={handleDuplicate}>Duplicate</button>
<button onClick={handleLogout}>Logout</button>
</header>
<main className="app-main">
<Editor page={page} />
</main>
</div>
)
}
@@ -0,0 +1,69 @@
.block-actions {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
flex-shrink: 0;
width: 28px;
padding-top: 2px;
user-select: none;
}
.block-action-btn {
width: 24px;
height: 24px;
border-radius: 4px;
border: 1px solid transparent;
background: none;
cursor: pointer;
font-size: 16px;
line-height: 1;
color: #ccc;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.15s ease;
padding: 0;
}
.block-action-btn:hover {
border-color: #ddd;
color: #666;
background: #f5f5f5;
}
.block-action-delete:hover {
border-color: #c00;
color: #c00;
background: #fff0f0;
}
.block-action-split:hover {
border-color: #2563eb;
color: #2563eb;
background: #eff6ff;
}
.block-drag-handle {
cursor: grab;
}
.block-drag-handle:active {
cursor: grabbing;
}
[data-node-view-wrapper] {
position: relative;
}
.node-view-block {
display: flex;
flex-direction: row;
align-items: stretch;
gap: 4px;
}
.node-view-content {
flex: 1;
min-width: 0;
}
@@ -0,0 +1,148 @@
import { useEffect, useCallback } from "react"
import type { Editor } from "@tiptap/react"
import { Fragment } from "@tiptap/pm/model"
import "./BlockActions.css"
export type BlockActionsProps = {
editor: Editor
getPos: () => number | undefined
showSplit?: boolean
}
export function BlockActions({ editor, getPos, showSplit }: BlockActionsProps) {
const getWrapper = useCallback(() => {
const pos = getPos()
if (typeof pos !== "number") return null
const dom = editor.view.nodeDOM(pos)
if (!dom || !(dom instanceof HTMLElement)) return null
return dom.closest("[data-node-view-wrapper]") as HTMLElement | null
}, [editor, getPos])
useEffect(() => {
const checkActive = () => {
const wrapper = getWrapper()
if (!wrapper) return
const pos = getPos()
if (typeof pos !== "number") {
wrapper.classList.remove("active-block")
return
}
const { from } = editor.state.selection
const resolved = editor.state.doc.resolve(from)
if (resolved.depth < 1) {
wrapper.classList.remove("active-block")
return
}
const blockPos = resolved.before(1)
if (blockPos === pos) {
wrapper.classList.add("active-block")
} else {
wrapper.classList.remove("active-block")
}
}
const handleBlur = () => {
const wrapper = getWrapper()
wrapper?.classList.remove("active-block")
}
checkActive()
editor.on("selectionUpdate", checkActive)
editor.on("focus", checkActive)
editor.on("blur", handleBlur)
return () => {
editor.off("selectionUpdate", checkActive)
editor.off("focus", checkActive)
editor.off("blur", handleBlur)
const wrapper = getWrapper()
wrapper?.classList.remove("active-block")
}
}, [editor, getPos, getWrapper])
const handleDelete = (e: React.MouseEvent) => {
e.preventDefault()
const pos = getPos()
if (typeof pos !== "number") return
const node = editor.state.doc.nodeAt(pos)
if (!node) return
editor.chain().focus().deleteRange({
from: pos,
to: pos + node.nodeSize,
}).run()
}
const handleSplit = (e: React.MouseEvent) => {
e.preventDefault()
const pos = getPos()
if (typeof pos !== "number") return
const node = editor.state.doc.nodeAt(pos)
if (!node || node.childCount < 2) return
const { from } = editor.state.selection
let childOffset = pos + 1
let splitAfter = -1
for (let i = 0; i < node.childCount; i++) {
const child = node.child(i)
const childEnd = childOffset + child.nodeSize
if (from >= childOffset && from < childEnd) {
splitAfter = i
break
}
childOffset = childEnd
}
if (splitAfter < 0 || splitAfter >= node.childCount - 1) return
const firstChildren = []
const secondChildren = []
for (let i = 0; i < node.childCount; i++) {
if (i <= splitAfter) {
firstChildren.push(node.child(i))
} else {
secondChildren.push(node.child(i))
}
}
const { schema } = editor.state
const textBlockType = schema.nodes.textBlock
const first = textBlockType.create(null, firstChildren)
const second = textBlockType.create(null, secondChildren)
const tr = editor.state.tr
tr.replaceWith(pos, pos + node.nodeSize, Fragment.from([first, second]))
editor.view.dispatch(tr)
}
return (
<div className="block-actions" contentEditable={false}>
<button
className="block-action-btn block-action-delete"
title="Delete block"
onClick={handleDelete}
>
&times;
</button>
{showSplit && (
<button
className="block-action-btn block-action-split"
title="Split block"
onClick={handleSplit}
>
&#x2702;
</button>
)}
<div
className="block-action-btn block-drag-handle"
data-drag-handle
draggable
title="Drag to reorder"
>
&#x2807;
</div>
</div>
)
}
@@ -0,0 +1,39 @@
.block-insert {
position: relative;
display: flex;
align-items: center;
justify-content: flex-start;
padding: 8px 0 8px 28px;
}
.block-insert-btn {
position: relative;
width: 24px;
height: 24px;
border-radius: 50%;
border: 1px solid transparent;
background: none;
cursor: pointer;
font-size: 18px;
line-height: 1;
color: #ccc;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.15s ease;
padding: 0;
z-index: 10;
}
.block-insert-btn:hover {
border-color: #ddd;
color: #666;
background: #f5f5f5;
}
.block-insert-menu {
position: absolute;
top: 12px;
left: 56px;
z-index: 50;
}
@@ -0,0 +1,51 @@
import { useState } from "react"
import type { Editor } from "@tiptap/react"
import { BlockMenu } from "./BlockMenu"
import "./BlockInsert.css"
export type BlockInsertProps = {
editor: Editor
getPos: () => number | undefined
}
export function BlockInsert({ editor, getPos }: BlockInsertProps) {
const [menuOpen, setMenuOpen] = useState(false)
const insertPos = (() => {
const pos = getPos()
if (typeof pos !== "number") return 0
const node = editor.state.doc.nodeAt(pos)
return node ? pos + node.nodeSize : 0
})()
const handleToggle = (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
setMenuOpen(!menuOpen)
}
const handleClose = () => {
setMenuOpen(false)
}
return (
<div className="block-insert" contentEditable={false}>
<button
className="block-insert-btn"
title="Add block"
onClick={handleToggle}
>
+
</button>
{menuOpen && (
<div className="block-insert-menu">
<BlockMenu
editor={editor}
position={insertPos}
onClose={handleClose}
/>
</div>
)}
</div>
)
}
@@ -0,0 +1,24 @@
.block-menu {
background: white;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
padding: 4px 0;
min-width: 160px;
z-index: 50;
}
.block-menu-item {
display: block;
width: 100%;
padding: 8px 12px;
border: none;
background: none;
text-align: left;
cursor: pointer;
font-size: 0.9rem;
}
.block-menu-item:hover {
background: #f0f4ff;
}
@@ -0,0 +1,65 @@
import type { Editor } from "@tiptap/react"
import { generateBlockId } from "../lib/id"
import "./BlockMenu.css"
type BlockType = {
label: string
type: string
attrs?: Record<string, unknown>
}
const BLOCK_TYPES: BlockType[] = [
{ label: "Text", type: "textBlock" },
{ label: "Image", type: "imageBlock", attrs: { id: "", imageId: "", wide: false, caption: "" } },
{ label: "File", type: "documentBlock", attrs: { id: "", fileId: "", title: "" } },
{ label: "Embed", type: "embedBlock", attrs: { id: "", src: "" } },
{ label: "Card Grid", type: "cardGridBlock", attrs: { id: "", items: "[]" } },
]
export type BlockMenuProps = {
editor: Editor
position: number
onClose: () => void
filter?: string
}
export function BlockMenu({ editor, position, onClose, filter }: BlockMenuProps) {
const filtered = filter
? BLOCK_TYPES.filter((b) => b.label.toLowerCase().includes(filter.toLowerCase()))
: BLOCK_TYPES
function handleInsert(block: BlockType) {
const id = generateBlockId()
if (block.type === "textBlock") {
editor.chain().focus().insertContentAt(position, {
type: "textBlock",
content: [{ type: "paragraph" }],
}).run()
} else {
editor.chain().focus().insertContentAt(position, {
type: block.type,
attrs: { ...block.attrs, id },
}).run()
}
onClose()
}
if (filtered.length === 0) return null
return (
<div className="block-menu">
{filtered.map((block) => (
<button
key={block.type}
className="block-menu-item"
onClick={() => handleInsert(block)}
>
{block.label}
</button>
))}
</div>
)
}
export { BLOCK_TYPES }
export type { BlockType }
@@ -0,0 +1,24 @@
.draft-banner {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
background: #fff8e1;
border: 1px solid #ffe082;
border-radius: 4px;
margin-bottom: 12px;
font-size: 0.9rem;
}
.draft-banner-discard {
padding: 4px 12px;
border: 1px solid #ccc;
border-radius: 4px;
background: white;
cursor: pointer;
font-size: 0.85rem;
}
.draft-banner-discard:hover {
background: #f0f0f0;
}
@@ -0,0 +1,16 @@
import "./DraftBanner.css"
export type DraftBannerProps = {
onDiscard: () => void
}
export function DraftBanner({ onDiscard }: DraftBannerProps) {
return (
<div className="draft-banner">
<span>You have unpublished changes</span>
<button onClick={onDiscard} className="draft-banner-discard">
Discard
</button>
</div>
)
}
@@ -0,0 +1,88 @@
.editor {
width: 100%;
}
.editor-content {
position: relative;
}
.editor-content .tiptap {
outline: none;
min-height: 400px;
}
.editor-content .tiptap > * + * {
margin-top: 0.75em;
}
.editor-content .tiptap h1 {
font-size: 2rem;
}
.editor-content .tiptap h2 {
font-size: 1.5rem;
}
.editor-content .tiptap h3 {
font-size: 1.25rem;
}
.editor-content .tiptap blockquote {
border-left: 3px solid #e0e0e0;
padding-left: 1rem;
color: #666;
}
.editor-content .tiptap pre {
background: #f5f5f5;
border-radius: 4px;
padding: 12px;
font-family: monospace;
}
.editor-content .tiptap code {
background: #f0f0f0;
border-radius: 2px;
padding: 0.1em 0.3em;
font-size: 0.9em;
}
.editor-content .tiptap hr {
border: none;
border-top: 1px solid #e0e0e0;
margin: 1.5em 0;
}
.editor-content .tiptap a {
color: #2563eb;
text-decoration: underline;
}
.editor-content .tiptap ul,
.editor-content .tiptap ol {
padding-left: 1.5em;
}
.editor-markdown {
width: 100%;
min-height: 400px;
padding: 16px;
font-family: monospace;
font-size: 14px;
line-height: 1.6;
border: 1px solid #e0e0e0;
border-radius: 4px;
resize: vertical;
outline: none;
box-sizing: border-box;
}
.editor-markdown:focus {
border-color: #213547;
}
.editor-content .tiptap [data-node-view-wrapper].active-block > .node-view-content {
outline: 2px solid #d0d5dd;
outline-offset: 2px;
border-radius: 4px;
}
@@ -0,0 +1,174 @@
import { useEditor, EditorContent } from "@tiptap/react"
import StarterKit from "@tiptap/starter-kit"
import { Markdown } from "@tiptap/markdown"
import Link from "@tiptap/extension-link"
import { useState, useCallback, useRef, useEffect } from "react"
import { pb } from "../pb"
import { docToTiptap, tiptapToDoc } from "../lib/serialize"
import { Toolbar } from "./Toolbar"
import { DraftBanner } from "./DraftBanner"
import {
WriterDocument,
TextBlock,
ImageBlock,
DocumentBlock,
EmbedBlock,
CardGridBlock,
} from "../nodes"
import { SlashCommands } from "../extensions/SlashCommands"
import "../nodes/nodes.css"
import "./Editor.css"
import type { PbPage, DocV1 } from "../types"
function serializeDoc(doc: DocV1): string {
return JSON.stringify(doc)
}
export type EditorProps = {
page: PbPage
}
export function Editor({ page }: EditorProps) {
const [saving, setSaving] = useState(false)
const [publishing, setPublishing] = useState(false)
const [markdownMode, setMarkdownMode] = useState(false)
const [markdownText, setMarkdownText] = useState("")
const [dirty, setDirty] = useState(false)
const [hasDraft, setHasDraft] = useState(page.draft !== null)
const [publishedDoc, setPublishedDoc] = useState(page.doc)
const snapshotRef = useRef("")
const initialDoc = page.draft ?? page.doc
const tiptapDoc = docToTiptap(initialDoc)
// Set initial snapshot
useEffect(() => {
snapshotRef.current = serializeDoc(initialDoc)
}, []) // eslint-disable-line react-hooks/exhaustive-deps
const editor = useEditor({
extensions: [
WriterDocument,
StarterKit.configure({
document: false,
}),
TextBlock,
Markdown,
Link.configure({ openOnClick: false }),
ImageBlock,
DocumentBlock,
EmbedBlock,
CardGridBlock,
SlashCommands,
],
content: tiptapDoc,
onUpdate: ({ editor }) => {
const json = editor.getJSON()
const doc = tiptapToDoc(json.content ?? [])
const current = serializeDoc(doc)
setDirty(current !== snapshotRef.current)
},
})
const getCurrentDoc = useCallback((): DocV1 => {
if (!editor) return { version: 1, blocks: [] }
if (markdownMode) {
editor.commands.setContent(markdownText, { contentType: "markdown" })
setMarkdownMode(false)
}
const json = editor.getJSON()
return tiptapToDoc(json.content ?? [])
}, [editor, markdownMode, markdownText])
const handleToggleMarkdown = useCallback(() => {
if (!editor) return
if (!markdownMode) {
const md = editor.getMarkdown()
setMarkdownText(md)
setMarkdownMode(true)
} else {
editor.commands.setContent(markdownText, { contentType: "markdown" })
setMarkdownMode(false)
}
}, [editor, markdownMode, markdownText])
const handleSave = useCallback(async () => {
if (!editor) return
setSaving(true)
try {
const doc = getCurrentDoc()
await pb.collection("pages").update(page.id, { draft: doc })
snapshotRef.current = serializeDoc(doc)
setDirty(false)
setHasDraft(true)
} catch (err) {
console.error("Save failed:", err)
alert("Save failed. Check console.")
} finally {
setSaving(false)
}
}, [editor, page.id, getCurrentDoc])
const handlePublish = useCallback(async () => {
if (!editor) return
setPublishing(true)
try {
const doc = getCurrentDoc()
await pb.collection("pages").update(page.id, { doc, draft: null })
snapshotRef.current = serializeDoc(doc)
setDirty(false)
setHasDraft(false)
setPublishedDoc(doc)
} catch (err) {
console.error("Publish failed:", err)
alert("Publish failed. Check console.")
} finally {
setPublishing(false)
}
}, [editor, page.id, getCurrentDoc])
const handleDiscard = useCallback(async () => {
if (!editor) return
try {
await pb.collection("pages").update(page.id, { draft: null })
const tiptap = docToTiptap(publishedDoc)
editor.commands.setContent(tiptap)
snapshotRef.current = serializeDoc(publishedDoc)
setDirty(false)
setHasDraft(false)
setMarkdownMode(false)
} catch (err) {
console.error("Discard failed:", err)
alert("Discard failed. Check console.")
}
}, [editor, page.id, publishedDoc])
return (
<div className="editor">
<Toolbar
editor={editor}
onSave={handleSave}
onPublish={handlePublish}
saving={saving}
publishing={publishing}
dirty={dirty}
hasDraft={hasDraft}
markdownMode={markdownMode}
onToggleMarkdown={handleToggleMarkdown}
/>
{hasDraft && (
<DraftBanner onDiscard={handleDiscard} />
)}
{markdownMode ? (
<textarea
className="editor-markdown"
value={markdownText}
onChange={(e) => setMarkdownText(e.target.value)}
/>
) : (
<EditorContent editor={editor} className="editor-content" />
)}
</div>
)
}
@@ -0,0 +1,32 @@
.file-picker-list {
display: flex;
flex-direction: column;
gap: 2px;
}
.file-picker-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: none;
background: none;
cursor: pointer;
text-align: left;
border-radius: 4px;
font-size: 0.9rem;
}
.file-picker-item:hover {
background: #f0f4ff;
}
.file-picker-icon {
font-size: 1.1rem;
}
.file-picker-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@@ -0,0 +1,123 @@
import { useState, useEffect, useRef } from "react"
import { pb } from "../pb"
import type { PbFile } from "../types"
import "./FilePicker.css"
export type FilePickerProps = {
onSelect: (fileId: string) => void
onClose: () => void
}
export function FilePicker({ onSelect, onClose }: FilePickerProps) {
const [files, setFiles] = useState<PbFile[]>([])
const [page, setPage] = useState(1)
const [totalPages, setTotalPages] = useState(1)
const [loading, setLoading] = useState(false)
const [uploading, setUploading] = useState(false)
const [tab, setTab] = useState<"browse" | "upload">("browse")
const fileRef = useRef<HTMLInputElement>(null)
useEffect(() => {
loadFiles(page)
}, [page])
async function loadFiles(p: number) {
setLoading(true)
try {
const result = await pb.collection("files").getList<PbFile>(p, 20, {
sort: "-created",
})
setFiles(result.items)
setTotalPages(result.totalPages)
} catch (err) {
console.error("Failed to load files:", err)
} finally {
setLoading(false)
}
}
async function handleUpload() {
const file = fileRef.current?.files?.[0]
if (!file) return
setUploading(true)
try {
const record = await pb.collection("files").create<PbFile>({
file,
filename: file.name,
})
onSelect(record.id)
} catch (err) {
console.error("Upload failed:", err)
alert("Upload failed. Check console.")
} finally {
setUploading(false)
}
}
return (
<div className="picker-overlay" onClick={onClose}>
<div className="picker" onClick={(e) => e.stopPropagation()}>
<div className="picker-header">
<button
className={tab === "browse" ? "active" : ""}
onClick={() => setTab("browse")}
>
Browse
</button>
<button
className={tab === "upload" ? "active" : ""}
onClick={() => setTab("upload")}
>
Upload
</button>
<button className="picker-close" onClick={onClose}>×</button>
</div>
{tab === "browse" && (
<div className="picker-browse">
{loading ? (
<div className="picker-loading">Loading...</div>
) : (
<div className="file-picker-list">
{files.map((f) => (
<button
key={f.id}
className="file-picker-item"
onClick={() => onSelect(f.id)}
>
<span className="file-picker-icon">📎</span>
<span className="file-picker-name">{f.filename}</span>
</button>
))}
</div>
)}
<div className="picker-pagination">
<button
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
>
Prev
</button>
<span>{page} / {totalPages}</span>
<button
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
)}
{tab === "upload" && (
<div className="picker-upload">
<input type="file" ref={fileRef} />
<button onClick={handleUpload} disabled={uploading}>
{uploading ? "Uploading..." : "Upload"}
</button>
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,127 @@
.picker-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
}
.picker {
background: white;
border-radius: 8px;
width: 600px;
max-width: 90vw;
max-height: 80vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.picker-header {
display: flex;
gap: 4px;
padding: 8px;
border-bottom: 1px solid #e0e0e0;
}
.picker-header button {
padding: 4px 12px;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
cursor: pointer;
}
.picker-header button.active {
background: #213547;
color: white;
border-color: #213547;
}
.picker-close {
margin-left: auto !important;
font-size: 1.2rem;
}
.picker-browse {
flex: 1;
overflow-y: auto;
padding: 8px;
}
.picker-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 8px;
}
.picker-thumb {
border: 2px solid transparent;
border-radius: 4px;
padding: 0;
background: none;
cursor: pointer;
overflow: hidden;
aspect-ratio: 1;
}
.picker-thumb:hover {
border-color: #213547;
}
.picker-thumb img {
width: 100%;
height: 100%;
object-fit: cover;
}
.picker-pagination {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
padding: 8px;
}
.picker-pagination button {
padding: 4px 12px;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
cursor: pointer;
}
.picker-pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.picker-loading {
text-align: center;
padding: 40px;
color: #888;
}
.picker-upload {
display: flex;
flex-direction: column;
gap: 12px;
padding: 20px;
align-items: flex-start;
}
.picker-upload button {
padding: 8px 16px;
border: none;
border-radius: 4px;
background: #213547;
color: white;
cursor: pointer;
}
.picker-upload button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
@@ -0,0 +1,131 @@
import { useState, useEffect, useRef } from "react"
import { pb } from "../pb"
import type { PbImage } from "../types"
import "./ImagePicker.css"
export type ImagePickerProps = {
onSelect: (imageId: string) => void
onClose: () => void
}
export function ImagePicker({ onSelect, onClose }: ImagePickerProps) {
const [images, setImages] = useState<PbImage[]>([])
const [page, setPage] = useState(1)
const [totalPages, setTotalPages] = useState(1)
const [loading, setLoading] = useState(false)
const [uploading, setUploading] = useState(false)
const [tab, setTab] = useState<"browse" | "upload">("browse")
const fileRef = useRef<HTMLInputElement>(null)
useEffect(() => {
loadImages(page)
}, [page])
async function loadImages(p: number) {
setLoading(true)
try {
const result = await pb.collection("images").getList<PbImage>(p, 20, {
sort: "-created",
})
setImages(result.items)
setTotalPages(result.totalPages)
} catch (err) {
console.error("Failed to load images:", err)
} finally {
setLoading(false)
}
}
async function handleUpload() {
const file = fileRef.current?.files?.[0]
if (!file) return
setUploading(true)
try {
const record = await pb.collection("images").create<PbImage>({
file,
filename: file.name,
width: 0,
height: 0,
alt: "",
caption: "",
blurhash: "",
})
onSelect(record.id)
} catch (err) {
console.error("Upload failed:", err)
alert("Upload failed. Check console.")
} finally {
setUploading(false)
}
}
function getThumbUrl(img: PbImage): string {
return pb.files.getURL(img, img.file, { thumb: "150x150" })
}
return (
<div className="picker-overlay" onClick={onClose}>
<div className="picker" onClick={(e) => e.stopPropagation()}>
<div className="picker-header">
<button
className={tab === "browse" ? "active" : ""}
onClick={() => setTab("browse")}
>
Browse
</button>
<button
className={tab === "upload" ? "active" : ""}
onClick={() => setTab("upload")}
>
Upload
</button>
<button className="picker-close" onClick={onClose}>×</button>
</div>
{tab === "browse" && (
<div className="picker-browse">
{loading ? (
<div className="picker-loading">Loading...</div>
) : (
<div className="picker-grid">
{images.map((img) => (
<button
key={img.id}
className="picker-thumb"
onClick={() => onSelect(img.id)}
>
<img src={getThumbUrl(img)} alt={img.alt || img.filename} />
</button>
))}
</div>
)}
<div className="picker-pagination">
<button
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
>
Prev
</button>
<span>{page} / {totalPages}</span>
<button
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
)}
{tab === "upload" && (
<div className="picker-upload">
<input type="file" accept="image/*" ref={fileRef} />
<button onClick={handleUpload} disabled={uploading}>
{uploading ? "Uploading..." : "Upload"}
</button>
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,45 @@
.login {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.login-form {
display: flex;
flex-direction: column;
gap: 12px;
width: 320px;
}
.login-form h1 {
font-size: 1.4rem;
margin-bottom: 8px;
}
.login-form input {
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}
.login-form button {
padding: 8px 12px;
border: none;
border-radius: 4px;
background: #213547;
color: white;
font-size: 1rem;
cursor: pointer;
}
.login-form button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.login-error {
color: #c00;
font-size: 0.9rem;
}
@@ -0,0 +1,55 @@
import { useState } from "react"
import type { FormEvent } from "react"
import { pb } from "../pb"
import "./Login.css"
export type LoginProps = {
onLogin: () => void
}
export function Login({ onLogin }: LoginProps) {
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [error, setError] = useState("")
const [loading, setLoading] = useState(false)
async function handleSubmit(e: FormEvent) {
e.preventDefault()
setError("")
setLoading(true)
try {
await pb.collection("_superusers").authWithPassword(email, password)
onLogin()
} catch {
setError("Authentication failed")
} finally {
setLoading(false)
}
}
return (
<div className="login">
<form className="login-form" onSubmit={handleSubmit}>
<h1>Hudozka Writer</h1>
{error && <p className="login-error">{error}</p>}
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button type="submit" disabled={loading}>
{loading ? "Signing in..." : "Sign in"}
</button>
</form>
</div>
)
}
@@ -0,0 +1,63 @@
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 4px;
padding: 8px 0;
border-bottom: 1px solid #e0e0e0;
margin-bottom: 16px;
position: sticky;
top: 0;
background: white;
z-index: 10;
}
.toolbar-group {
display: flex;
gap: 2px;
}
.toolbar button {
padding: 4px 8px;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
cursor: pointer;
font-size: 0.85rem;
min-width: 32px;
}
.toolbar button:hover {
background: #f0f0f0;
}
.toolbar button.active {
background: #213547;
color: white;
border-color: #213547;
}
.toolbar-actions {
margin-left: auto;
gap: 4px;
}
.toolbar-save-btn {
padding: 4px 16px !important;
}
.toolbar-save-btn:disabled {
opacity: 0.6;
cursor: not-allowed !important;
}
.toolbar-publish-btn {
background: #213547 !important;
color: white !important;
border-color: #213547 !important;
padding: 4px 16px !important;
}
.toolbar-publish-btn:disabled {
opacity: 0.6;
cursor: not-allowed !important;
}
@@ -0,0 +1,151 @@
import type { Editor } from "@tiptap/react"
import "./Toolbar.css"
export type ToolbarProps = {
editor: Editor | null
onSave: () => void
onPublish: () => void
saving: boolean
publishing: boolean
dirty: boolean
hasDraft: boolean
markdownMode: boolean
onToggleMarkdown: () => void
}
export function Toolbar({
editor,
onSave,
onPublish,
saving,
publishing,
dirty,
hasDraft,
markdownMode,
onToggleMarkdown,
}: ToolbarProps) {
if (!editor) return null
const canSave = dirty
const canPublish = dirty || hasDraft
return (
<div className="toolbar">
<div className="toolbar-group">
<button
onClick={() => editor.chain().focus().toggleBold().run()}
className={editor.isActive("bold") ? "active" : ""}
title="Bold"
>
B
</button>
<button
onClick={() => editor.chain().focus().toggleItalic().run()}
className={editor.isActive("italic") ? "active" : ""}
title="Italic"
>
I
</button>
<button
onClick={() => editor.chain().focus().toggleStrike().run()}
className={editor.isActive("strike") ? "active" : ""}
title="Strikethrough"
>
S
</button>
<button
onClick={() => editor.chain().focus().toggleCode().run()}
className={editor.isActive("code") ? "active" : ""}
title="Inline code"
>
&lt;/&gt;
</button>
</div>
<div className="toolbar-group">
<button
onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
className={editor.isActive("heading", { level: 1 }) ? "active" : ""}
>
H1
</button>
<button
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
className={editor.isActive("heading", { level: 2 }) ? "active" : ""}
>
H2
</button>
<button
onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
className={editor.isActive("heading", { level: 3 }) ? "active" : ""}
>
H3
</button>
</div>
<div className="toolbar-group">
<button
onClick={() => editor.chain().focus().toggleBulletList().run()}
className={editor.isActive("bulletList") ? "active" : ""}
title="Bullet list"
>
List
</button>
<button
onClick={() => editor.chain().focus().toggleOrderedList().run()}
className={editor.isActive("orderedList") ? "active" : ""}
title="Numbered list"
>
1.
</button>
<button
onClick={() => editor.chain().focus().toggleBlockquote().run()}
className={editor.isActive("blockquote") ? "active" : ""}
title="Blockquote"
>
&ldquo;
</button>
<button
onClick={() => editor.chain().focus().toggleCodeBlock().run()}
className={editor.isActive("codeBlock") ? "active" : ""}
title="Code block"
>
Code
</button>
<button
onClick={() => editor.chain().focus().setHorizontalRule().run()}
title="Horizontal rule"
>
---
</button>
</div>
<div className="toolbar-group">
<button
onClick={onToggleMarkdown}
className={markdownMode ? "active" : ""}
title="Toggle markdown view"
>
MD
</button>
</div>
<div className="toolbar-group toolbar-actions">
<button
onClick={onSave}
disabled={!canSave || saving}
className="toolbar-save-btn"
>
{saving ? "Saving..." : "Save"}
</button>
<button
onClick={onPublish}
disabled={!canPublish || publishing}
className="toolbar-publish-btn"
>
{publishing ? "Publishing..." : "Publish"}
</button>
</div>
</div>
)
}
@@ -0,0 +1,28 @@
.slash-command-container {
z-index: 50;
}
.slash-menu {
background: white;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
padding: 4px 0;
min-width: 160px;
}
.slash-menu-item {
display: block;
width: 100%;
padding: 8px 12px;
border: none;
background: none;
text-align: left;
cursor: pointer;
font-size: 0.9rem;
}
.slash-menu-item:hover,
.slash-menu-item--selected {
background: #f0f4ff;
}
@@ -0,0 +1,255 @@
import { Extension } from "@tiptap/core"
import { PluginKey } from "@tiptap/pm/state"
import { Fragment } from "@tiptap/pm/model"
import type { ResolvedPos, Node as PmNode } from "@tiptap/pm/model"
import Suggestion from "@tiptap/suggestion"
import type { SuggestionOptions, SuggestionProps, SuggestionKeyDownProps } from "@tiptap/suggestion"
import { createRoot } from "react-dom/client"
import { generateBlockId } from "../lib/id"
import type { Editor } from "@tiptap/react"
import "./SlashCommands.css"
type SlashCommandItem = {
label: string
type: string
attrs?: Record<string, unknown>
}
const ITEMS: SlashCommandItem[] = [
{ label: "Text", type: "textBlock" },
{ label: "Image", type: "imageBlock", attrs: { id: "", imageId: "", wide: false, caption: "" } },
{ label: "File", type: "documentBlock", attrs: { id: "", fileId: "", title: "" } },
{ label: "Embed", type: "embedBlock", attrs: { id: "", src: "" } },
{ label: "Card Grid", type: "cardGridBlock", attrs: { id: "", items: "[]" } },
]
const slashCommandsPluginKey = new PluginKey("slashCommands")
function findTextBlockDepth($pos: ResolvedPos): number | null {
for (let d = $pos.depth; d > 0; d--) {
if ($pos.node(d).type.name === "textBlock") {
return d
}
}
return null
}
function SlashMenu({ items, command, selectedIndex }: { items: SlashCommandItem[]; command: (item: SlashCommandItem) => void; selectedIndex: number }) {
if (items.length === 0) return null
return (
<div className="slash-menu">
{items.map((item, index) => (
<button
key={item.type}
className={`slash-menu-item${index === selectedIndex ? " slash-menu-item--selected" : ""}`}
onClick={() => command(item)}
>
{item.label}
</button>
))}
</div>
)
}
export const SlashCommands = Extension.create({
name: "slashCommands",
addOptions() {
return {
suggestion: {
char: "/",
pluginKey: slashCommandsPluginKey,
startOfLine: true,
items: ({ query }: { query: string }) => {
return ITEMS.filter((item) =>
item.label.toLowerCase().includes(query.toLowerCase())
)
},
render: () => {
let container: HTMLDivElement | null = null
let root: ReturnType<typeof createRoot> | null = null
let selectedIndex = 0
let currentItems: SlashCommandItem[] = []
let currentCommand: ((item: SlashCommandItem) => void) | null = null
function renderMenu() {
if (!root) return
root.render(
<SlashMenu
items={currentItems}
command={currentCommand!}
selectedIndex={selectedIndex}
/>
)
}
return {
onStart: (props: SuggestionProps<SlashCommandItem, SlashCommandItem>) => {
container = document.createElement("div")
container.className = "slash-command-container"
document.body.appendChild(container)
root = createRoot(container)
const rect = props.clientRect?.()
if (rect && container) {
container.style.position = "fixed"
container.style.left = `${rect.left}px`
container.style.top = `${rect.bottom + 4}px`
container.style.zIndex = "50"
}
selectedIndex = 0
currentItems = props.items
currentCommand = props.command
renderMenu()
},
onUpdate: (props: SuggestionProps<SlashCommandItem, SlashCommandItem>) => {
if (!root || !container) return
const rect = props.clientRect?.()
if (rect && container) {
container.style.left = `${rect.left}px`
container.style.top = `${rect.bottom + 4}px`
}
currentItems = props.items
currentCommand = props.command
selectedIndex = 0
renderMenu()
},
onExit: () => {
root?.unmount()
container?.remove()
container = null
root = null
},
onKeyDown: (props: SuggestionKeyDownProps) => {
const { key } = props.event
if (key === "Escape") {
root?.unmount()
container?.remove()
container = null
root = null
return true
}
if (key === "ArrowDown") {
selectedIndex = (selectedIndex + 1) % currentItems.length
renderMenu()
return true
}
if (key === "ArrowUp") {
selectedIndex = (selectedIndex - 1 + currentItems.length) % currentItems.length
renderMenu()
return true
}
if (key === "Enter") {
if (currentItems[selectedIndex] && currentCommand) {
currentCommand(currentItems[selectedIndex])
}
return true
}
return false
},
}
},
command: ({ editor, range, props }: { editor: Editor; range: { from: number; to: number }; props: SlashCommandItem }) => {
// Delete the slash command text
editor.chain().focus().deleteRange(range).run()
if (props.type === "textBlock") {
// Already inside a textBlock paragraph — nothing to do
return
}
const { from } = editor.state.selection
const id = generateBlockId()
const newNode = { type: props.type, attrs: { ...props.attrs, id } }
// Check if we're inside a textBlock
const $pos = editor.state.doc.resolve(from)
const textBlockDepth = findTextBlockDepth($pos)
if (textBlockDepth === null) {
// Not inside a textBlock — insert directly
editor.chain().focus().insertContentAt(from, newNode).run()
return
}
// Inside a textBlock — split it and insert the custom block between halves
const textBlockPos = $pos.before(textBlockDepth)
const textBlockNode = editor.state.doc.nodeAt(textBlockPos)
if (!textBlockNode) return
// Find which child contains the cursor
let childOffset = textBlockPos + 1
let splitAfter = -1
for (let i = 0; i < textBlockNode.childCount; i++) {
const child = textBlockNode.child(i)
const childEnd = childOffset + child.nodeSize
if (from >= childOffset && from <= childEnd) {
// If the paragraph is empty (just deleted the slash), split before it
const curChild = textBlockNode.child(i)
if (curChild.content.size === 0 && i > 0) {
splitAfter = i - 1
} else if (curChild.content.size === 0 && i === 0) {
splitAfter = -1 // cursor in empty first child
} else {
splitAfter = i
}
break
}
childOffset = childEnd
}
const { schema } = editor.state
const textBlockType = schema.nodes.textBlock
const fragments: PmNode[] = []
// Build first textBlock (children 0..splitAfter) — skip if empty
if (splitAfter >= 0) {
const children = []
for (let i = 0; i <= splitAfter; i++) {
children.push(textBlockNode.child(i))
}
// Skip if all children are empty paragraphs
const hasContent = children.some((c) => c.content.size > 0)
if (hasContent) {
fragments.push(textBlockType.create(null, children))
}
}
// Insert the custom block
fragments.push(schema.nodes[props.type].create(
{ ...props.attrs, id },
))
// Build second textBlock (children after splitAfter) — skip empty
const remaining = []
const startIdx = splitAfter + 1
for (let i = startIdx; i < textBlockNode.childCount; i++) {
remaining.push(textBlockNode.child(i))
}
// Filter out empty paragraphs at the edges
const nonEmpty = remaining.filter((c) => c.content.size > 0)
if (nonEmpty.length > 0) {
fragments.push(textBlockType.create(null, remaining))
}
const tr = editor.state.tr
tr.replaceWith(textBlockPos, textBlockPos + textBlockNode.nodeSize, Fragment.from(fragments))
editor.view.dispatch(tr)
},
} satisfies Partial<SuggestionOptions<SlashCommandItem, SlashCommandItem>>,
}
},
addProseMirrorPlugins() {
return [
Suggestion({
editor: this.editor,
...this.options.suggestion,
}),
]
},
})
+16
View File
@@ -0,0 +1,16 @@
:root {
font-family: system-ui, -apple-system, sans-serif;
line-height: 1.5;
color: #213547;
background-color: #ffffff;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
}
+3
View File
@@ -0,0 +1,3 @@
export function generateBlockId(): string {
return crypto.randomUUID().slice(0, 8)
}
@@ -0,0 +1,17 @@
import { MarkdownManager } from "@tiptap/markdown"
import StarterKit from "@tiptap/starter-kit"
import Link from "@tiptap/extension-link"
let manager: MarkdownManager | null = null
export function getMarkdownManager(): MarkdownManager {
if (!manager) {
manager = new MarkdownManager({
extensions: [
StarterKit,
Link,
],
})
}
return manager
}
+168
View File
@@ -0,0 +1,168 @@
import type { JSONContent } from "@tiptap/core"
import type {
DocV1,
DocV1Block,
DocV1BlockText,
DocV1BlockImage,
DocV1BlockDocument,
DocV1BlockEmbed,
DocV1BlockCardGrid,
} from "../types"
import { generateBlockId } from "./id"
import { getMarkdownManager } from "./markdown"
// -- DocV1 -> Tiptap JSON --
function textBlockToTiptap(block: DocV1BlockText): JSONContent {
const manager = getMarkdownManager()
const parsed = manager.parse(block.text)
return {
type: "textBlock",
content: parsed.content ?? [],
}
}
function imageBlockToTiptap(block: DocV1BlockImage): JSONContent {
return {
type: "imageBlock",
attrs: {
id: block.id,
imageId: block.image,
wide: block.wide,
caption: block.caption,
},
}
}
function documentBlockToTiptap(block: DocV1BlockDocument): JSONContent {
return {
type: "documentBlock",
attrs: {
id: block.id,
fileId: block.file,
title: block.title,
},
}
}
function embedBlockToTiptap(block: DocV1BlockEmbed): JSONContent {
return {
type: "embedBlock",
attrs: {
id: block.id,
src: block.src,
},
}
}
function cardGridBlockToTiptap(block: DocV1BlockCardGrid): JSONContent {
return {
type: "cardGridBlock",
attrs: {
id: block.id,
items: JSON.stringify(block.items),
},
}
}
export function docToTiptap(doc: DocV1): JSONContent {
const content: JSONContent[] = []
for (const block of doc.blocks) {
switch (block.type) {
case "text":
content.push(textBlockToTiptap(block))
break
case "image":
content.push(imageBlockToTiptap(block))
break
case "document":
content.push(documentBlockToTiptap(block))
break
case "embed":
content.push(embedBlockToTiptap(block))
break
case "card-grid":
content.push(cardGridBlockToTiptap(block))
break
}
}
return {
type: "doc",
content,
}
}
// -- Tiptap JSON -> DocV1 --
function textNodesToMarkdown(nodes: JSONContent[]): string {
const manager = getMarkdownManager()
const doc: JSONContent = { type: "doc", content: nodes }
return manager.serialize(doc)
}
export function tiptapToDoc(content: JSONContent[]): DocV1 {
const blocks: DocV1Block[] = []
for (const node of content) {
switch (node.type) {
case "textBlock": {
const text = textNodesToMarkdown(node.content ?? [])
if (text.trim()) {
blocks.push({
type: "text",
id: generateBlockId(),
text,
})
}
break
}
case "imageBlock": {
const attrs = node.attrs ?? {}
blocks.push({
type: "image",
id: attrs.id ?? generateBlockId(),
image: attrs.imageId ?? "",
wide: attrs.wide ?? false,
caption: attrs.caption ?? "",
})
break
}
case "documentBlock": {
const attrs = node.attrs ?? {}
blocks.push({
type: "document",
id: attrs.id ?? generateBlockId(),
file: attrs.fileId ?? "",
title: attrs.title ?? "",
})
break
}
case "embedBlock": {
const attrs = node.attrs ?? {}
blocks.push({
type: "embed",
id: attrs.id ?? generateBlockId(),
src: attrs.src ?? "",
})
break
}
case "cardGridBlock": {
const attrs = node.attrs ?? {}
blocks.push({
type: "card-grid",
id: attrs.id ?? generateBlockId(),
items: JSON.parse(attrs.items ?? "[]"),
})
break
}
}
}
return { version: 1, blocks }
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { App } from "./App"
import "./index.css"
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
)
@@ -0,0 +1,92 @@
import { Node, mergeAttributes } from "@tiptap/core"
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react"
import type { NodeViewProps } from "@tiptap/react"
import { useState, useEffect } from "react"
import { pb } from "../pb"
import type { PbPage } from "../types"
import { BlockActions } from "../components/BlockActions"
import { BlockInsert } from "../components/BlockInsert"
type ResolvedItem = {
page: string
title: string | null
}
function CardGridBlockView({ node, editor, getPos }: NodeViewProps) {
const items = JSON.parse(node.attrs.items || "[]")
const [resolved, setResolved] = useState<ResolvedItem[]>([])
const [loading, setLoading] = useState(false)
useEffect(() => {
if (items.length === 0) {
setResolved([])
return
}
setLoading(true)
Promise.all(
items.map(async (item: { page: string }) => {
try {
const page = await pb.collection("pages").getOne<PbPage>(item.page)
return { page: item.page, title: page.title }
} catch {
return { page: item.page, title: null }
}
})
).then((results) => {
setResolved(results)
setLoading(false)
})
}, [node.attrs.items])
return (
<>
<NodeViewWrapper className="node-view-block node-readonly-block">
<BlockActions editor={editor} getPos={getPos} />
<div className="node-view-content">
<div className="node-block-label">
Card Grid ({items.length})
</div>
{loading ? (
<div className="node-block-info">Loading...</div>
) : (
<ul className="node-cardgrid-list">
{resolved.map((item) => (
<li key={item.page} className="node-cardgrid-item">
{item.title ?? item.page}
</li>
))}
</ul>
)}
</div>
</NodeViewWrapper>
<BlockInsert editor={editor} getPos={getPos} />
</>
)
}
export const CardGridBlock = Node.create({
name: "cardGridBlock",
group: "block",
atom: true,
draggable: true,
addAttributes() {
return {
id: { default: null },
items: { default: "[]" },
}
},
parseHTML() {
return [{ tag: "div[data-card-grid-block]" }]
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes, { "data-card-grid-block": "" })]
},
addNodeView() {
return ReactNodeViewRenderer(CardGridBlockView)
},
})
@@ -0,0 +1,106 @@
import { Node, mergeAttributes } from "@tiptap/core"
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react"
import type { NodeViewProps } from "@tiptap/react"
import { useState, useEffect } from "react"
import { pb } from "../pb"
import { FilePicker } from "../components/FilePicker"
import type { PbFile } from "../types"
import { BlockActions } from "../components/BlockActions"
import { BlockInsert } from "../components/BlockInsert"
function DocumentBlockView({ node, updateAttributes, editor, getPos }: NodeViewProps) {
const { fileId, title } = node.attrs
const [filename, setFilename] = useState<string | null>(null)
const [showPicker, setShowPicker] = useState(false)
useEffect(() => {
if (!fileId) return
pb.collection("files").getOne<PbFile>(fileId).then((f) => {
setFilename(f.filename)
}).catch(() => {
setFilename(null)
})
}, [fileId])
function handleSelect(newFileId: string) {
updateAttributes({ fileId: newFileId })
setShowPicker(false)
}
return (
<>
<NodeViewWrapper className="node-view-block node-document-block">
<BlockActions editor={editor} getPos={getPos} />
<div className="node-view-content">
<div className="node-block-label">File</div>
{fileId ? (
<div
className="node-document-file"
onClick={() => setShowPicker(true)}
style={{ cursor: "pointer" }}
>
📎 {filename ?? fileId}
</div>
) : (
<div
className="node-document-placeholder"
onClick={() => setShowPicker(true)}
style={{ cursor: "pointer" }}
>
Click to select file
</div>
)}
<div className="node-document-controls">
<input
type="text"
placeholder="Title"
value={title || ""}
onChange={(e) => updateAttributes({ title: e.target.value })}
className="node-document-title"
/>
<button
className="node-image-pick-btn"
onClick={() => setShowPicker(true)}
>
Pick
</button>
</div>
{showPicker && (
<FilePicker
onSelect={handleSelect}
onClose={() => setShowPicker(false)}
/>
)}
</div>
</NodeViewWrapper>
<BlockInsert editor={editor} getPos={getPos} />
</>
)
}
export const DocumentBlock = Node.create({
name: "documentBlock",
group: "block",
atom: true,
draggable: true,
addAttributes() {
return {
id: { default: null },
fileId: { default: "" },
title: { default: "" },
}
},
parseHTML() {
return [{ tag: "div[data-document-block]" }]
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes, { "data-document-block": "" })]
},
addNodeView() {
return ReactNodeViewRenderer(DocumentBlockView)
},
})
@@ -0,0 +1,48 @@
import { Node, mergeAttributes } from "@tiptap/core"
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react"
import type { NodeViewProps } from "@tiptap/react"
import { BlockActions } from "../components/BlockActions"
import { BlockInsert } from "../components/BlockInsert"
function EmbedBlockView({ node, editor, getPos }: NodeViewProps) {
return (
<>
<NodeViewWrapper className="node-view-block node-readonly-block">
<BlockActions editor={editor} getPos={getPos} />
<div className="node-view-content">
<div className="node-block-label">Embed</div>
<div className="node-block-info">
<code>{node.attrs.src}</code>
</div>
</div>
</NodeViewWrapper>
<BlockInsert editor={editor} getPos={getPos} />
</>
)
}
export const EmbedBlock = Node.create({
name: "embedBlock",
group: "block",
atom: true,
draggable: true,
addAttributes() {
return {
id: { default: null },
src: { default: "" },
}
},
parseHTML() {
return [{ tag: "div[data-embed-block]" }]
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes, { "data-embed-block": "" })]
},
addNodeView() {
return ReactNodeViewRenderer(EmbedBlockView)
},
})
@@ -0,0 +1,116 @@
import { Node, mergeAttributes } from "@tiptap/core"
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react"
import type { NodeViewProps } from "@tiptap/react"
import { pb } from "../pb"
import type { PbImage } from "../types"
import { useState, useEffect } from "react"
import { ImagePicker } from "../components/ImagePicker"
import { BlockActions } from "../components/BlockActions"
import { BlockInsert } from "../components/BlockInsert"
function ImageBlockView({ node, updateAttributes, editor, getPos }: NodeViewProps) {
const { imageId, wide, caption } = node.attrs
const [thumbnail, setThumbnail] = useState<string | null>(null)
const [showPicker, setShowPicker] = useState(false)
useEffect(() => {
if (!imageId) return
pb.collection("images").getOne<PbImage>(imageId).then((img) => {
const url = pb.files.getURL(img, img.file, { thumb: "300x200" })
setThumbnail(url)
}).catch(() => {
setThumbnail(null)
})
}, [imageId])
function handleSelect(newImageId: string) {
updateAttributes({ imageId: newImageId })
setShowPicker(false)
}
return (
<>
<NodeViewWrapper className="node-view-block node-image-block">
<BlockActions editor={editor} getPos={getPos} />
<div className="node-view-content">
<div className="node-block-label">Image</div>
{thumbnail ? (
<img
src={thumbnail}
alt={caption || "image"}
className="node-image-thumb"
onClick={() => setShowPicker(true)}
style={{ cursor: "pointer" }}
/>
) : (
<div
className="node-image-placeholder"
onClick={() => setShowPicker(true)}
style={{ cursor: "pointer" }}
>
{imageId ? "Loading..." : "Click to select image"}
</div>
)}
<div className="node-image-controls">
<label>
<input
type="checkbox"
checked={wide}
onChange={(e) => updateAttributes({ wide: e.target.checked })}
/>
Wide
</label>
<input
type="text"
placeholder="Caption"
value={caption || ""}
onChange={(e) => updateAttributes({ caption: e.target.value })}
className="node-image-caption"
/>
<button
className="node-image-pick-btn"
onClick={() => setShowPicker(true)}
>
Pick
</button>
</div>
{showPicker && (
<ImagePicker
onSelect={handleSelect}
onClose={() => setShowPicker(false)}
/>
)}
</div>
</NodeViewWrapper>
<BlockInsert editor={editor} getPos={getPos} />
</>
)
}
export const ImageBlock = Node.create({
name: "imageBlock",
group: "block",
atom: true,
draggable: true,
addAttributes() {
return {
id: { default: null },
imageId: { default: "" },
wide: { default: false },
caption: { default: "" },
}
},
parseHTML() {
return [{ tag: "div[data-image-block]" }]
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes, { "data-image-block": "" })]
},
addNodeView() {
return ReactNodeViewRenderer(ImageBlockView)
},
})
@@ -0,0 +1,37 @@
import { Node, mergeAttributes } from "@tiptap/core"
import { ReactNodeViewRenderer, NodeViewWrapper, NodeViewContent } from "@tiptap/react"
import type { NodeViewProps } from "@tiptap/react"
import { BlockActions } from "../components/BlockActions"
import { BlockInsert } from "../components/BlockInsert"
function TextBlockView({ editor, getPos }: NodeViewProps) {
return (
<>
<NodeViewWrapper className="node-view-block node-text-block">
<BlockActions editor={editor} getPos={getPos} />
<NodeViewContent className="node-view-content" />
</NodeViewWrapper>
<BlockInsert editor={editor} getPos={getPos} />
</>
)
}
export const TextBlock = Node.create({
name: "textBlock",
group: "block",
content: "(paragraph | heading | bulletList | orderedList | blockquote | codeBlock | horizontalRule)+",
draggable: true,
defining: true,
parseHTML() {
return [{ tag: "div[data-text-block]" }]
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes, { "data-text-block": "" }), 0]
},
addNodeView() {
return ReactNodeViewRenderer(TextBlockView)
},
})
@@ -0,0 +1,7 @@
import { Node } from "@tiptap/core"
export const WriterDocument = Node.create({
name: "doc",
topNode: true,
content: "(textBlock | imageBlock | documentBlock | embedBlock | cardGridBlock)+",
})
@@ -0,0 +1,6 @@
export { WriterDocument } from "./WriterDocument"
export { TextBlock } from "./TextBlock"
export { ImageBlock } from "./ImageBlock"
export { DocumentBlock } from "./DocumentBlock"
export { EmbedBlock } from "./EmbedBlock"
export { CardGridBlock } from "./CardGridBlock"
+109
View File
@@ -0,0 +1,109 @@
.node-block-label {
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #888;
margin-bottom: 4px;
}
.node-image-block > .node-view-content,
.node-readonly-block > .node-view-content,
.node-document-block > .node-view-content {
border: 1px solid #e0e0e0;
border-radius: 6px;
padding: 12px;
background: #fafafa;
}
.node-image-thumb {
max-width: 100%;
max-height: 200px;
border-radius: 4px;
object-fit: cover;
}
.node-image-placeholder {
height: 100px;
display: flex;
align-items: center;
justify-content: center;
background: #f0f0f0;
border-radius: 4px;
color: #888;
}
.node-image-controls {
display: flex;
gap: 12px;
align-items: center;
margin-top: 8px;
}
.node-image-caption {
flex: 1;
padding: 4px 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 0.9rem;
}
.node-block-info {
display: flex;
gap: 8px;
align-items: center;
}
.node-block-info code {
font-size: 0.8rem;
color: #666;
}
.node-image-pick-btn {
padding: 2px 8px;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
cursor: pointer;
font-size: 0.85rem;
}
.node-document-file {
padding: 8px;
background: #f0f0f0;
border-radius: 4px;
font-size: 0.9rem;
}
.node-document-placeholder {
padding: 8px;
background: #f0f0f0;
border-radius: 4px;
color: #888;
text-align: center;
}
.node-document-controls {
display: flex;
gap: 12px;
align-items: center;
margin-top: 8px;
}
.node-document-title {
flex: 1;
padding: 4px 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 0.9rem;
}
.node-cardgrid-list {
margin: 4px 0 0;
padding-left: 20px;
font-size: 0.9rem;
}
.node-cardgrid-item {
color: #444;
line-height: 1.6;
}
+7
View File
@@ -0,0 +1,7 @@
import PocketBase from "pocketbase"
// Default to same origin; override via env for dev
const url = import.meta.env.VITE_PB_URL ?? "http://127.0.0.1:8090"
export const pb = new PocketBase(url)
pb.autoCancellation(false)
+90
View File
@@ -0,0 +1,90 @@
// -- PocketBase record base --
export type PbRecord = {
id: string
collectionId: string
collectionName: string
created: string
updated: string
}
// -- PocketBase collection types --
export type PbImage = PbRecord & {
file: string
filename: string
width: number
height: number
blurhash: string
alt: string
caption: string
}
export type PbFile = PbRecord & {
file: string
filename: string
}
export type PbPage = PbRecord & {
title: string
slug: string
excerpt: string
date: string
cover: string
doc: DocV1
tags: string[]
published: boolean
draft: DocV1 | null
}
// -- DocV1 document format --
export type DocV1BlockText = {
type: "text"
id: string
text: string
}
export type DocV1BlockImage = {
type: "image"
id: string
image: string
wide: boolean
caption: string
}
export type DocV1BlockDocument = {
type: "document"
id: string
file: string
title: string
}
export type DocV1BlockEmbed = {
type: "embed"
id: string
src: string
}
export type DocV1BlockCardGridItem = {
page: string
layout: "small" | "medium" | "big"
}
export type DocV1BlockCardGrid = {
type: "card-grid"
id: string
items: DocV1BlockCardGridItem[]
}
export type DocV1Block =
| DocV1BlockText
| DocV1BlockImage
| DocV1BlockDocument
| DocV1BlockEmbed
| DocV1BlockCardGrid
export type DocV1 = {
version: 1
blocks: DocV1Block[]
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />