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:
1 parent
907298779c
commit
ed3f93de53
109 files changed
+40520
-427
No files matched your search
+69
-46
@@ -1,66 +1,89 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest"
|
||||
import { apiGet, getRecentPages } from "./api"
|
||||
|
||||
function mockFetchJson(data: unknown, ok = true) {
|
||||
return vi.spyOn(globalThis, "fetch").mockResolvedValue({
|
||||
ok,
|
||||
json: async () => data,
|
||||
} as Response)
|
||||
}
|
||||
vi.mock("./pb", () => ({
|
||||
pb: {
|
||||
baseURL: "http://127.0.0.1:8090",
|
||||
collection: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { getUrls, getRecentPages } from "./api"
|
||||
import { pb } from "./pb"
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe("apiGet", () => {
|
||||
it("should call factory with fetched data on success", async () => {
|
||||
const data = { value: 1 }
|
||||
mockFetchJson(data)
|
||||
const factory = vi.fn((d: typeof data) => d.value)
|
||||
const result = await apiGet(factory)("https://example.com/api", () => -1)
|
||||
expect(factory).toHaveBeenCalledWith(data)
|
||||
expect(result).toBe(1)
|
||||
describe("getUrls", () => {
|
||||
it("should return slugs from all non-draft pages", async () => {
|
||||
const mockGetFullList = vi.fn().mockResolvedValue([
|
||||
{ slug: "/info" },
|
||||
{ slug: "/2024/test" },
|
||||
])
|
||||
vi.mocked(pb.collection).mockReturnValue({
|
||||
getFullList: mockGetFullList,
|
||||
} as never)
|
||||
|
||||
const result = await getUrls()
|
||||
expect(result).toEqual(["/info", "/2024/test"])
|
||||
expect(pb.collection).toHaveBeenCalledWith("pages")
|
||||
expect(mockGetFullList).toHaveBeenCalledWith({
|
||||
fields: "slug",
|
||||
filter: "draft=false",
|
||||
})
|
||||
})
|
||||
|
||||
it("should return default on non-ok response", async () => {
|
||||
mockFetchJson(null, false)
|
||||
const factory = vi.fn()
|
||||
const result = await apiGet(factory)("https://example.com/api", () => "default")
|
||||
expect(factory).not.toHaveBeenCalled()
|
||||
expect(result).toBe("default")
|
||||
})
|
||||
it("should return empty array on error", async () => {
|
||||
vi.mocked(pb.collection).mockReturnValue({
|
||||
getFullList: vi.fn().mockRejectedValue(new Error("fail")),
|
||||
} as never)
|
||||
vi.spyOn(console, "error").mockImplementation(() => {})
|
||||
|
||||
it("should return default and log error on network failure", async () => {
|
||||
vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("network"))
|
||||
const spy = vi.spyOn(console, "error").mockImplementation(() => {})
|
||||
const factory = vi.fn()
|
||||
const result = await apiGet(factory)("https://example.com/api", () => "fallback")
|
||||
expect(factory).not.toHaveBeenCalled()
|
||||
expect(result).toBe("fallback")
|
||||
expect(spy).toHaveBeenCalled()
|
||||
const result = await getUrls()
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe("getRecentPages", () => {
|
||||
it("should fetch with default limit of 30", async () => {
|
||||
const spy = mockFetchJson([])
|
||||
await getRecentPages()
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
"https://hudozka.tmshv.com/pages?_sort=date:DESC&_limit=30",
|
||||
)
|
||||
it("should fetch recent pages with default limit", async () => {
|
||||
const mockGetList = vi.fn().mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: "x1",
|
||||
title: "Recent",
|
||||
slug: "/2024/recent",
|
||||
date: "2024-03-01",
|
||||
excerpt: "Summary",
|
||||
doc: { version: 1, blocks: [] },
|
||||
tags: [],
|
||||
draft: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
vi.mocked(pb.collection).mockReturnValue({
|
||||
getList: mockGetList,
|
||||
} as never)
|
||||
|
||||
const result = await getRecentPages()
|
||||
expect(result).toEqual([{
|
||||
id: "x1",
|
||||
title: "Recent",
|
||||
url: "/2024/recent",
|
||||
date: "2024-03-01",
|
||||
excerpt: "Summary",
|
||||
}])
|
||||
expect(mockGetList).toHaveBeenCalledWith(1, 30, {
|
||||
filter: "date!='' && draft=false",
|
||||
sort: "-date",
|
||||
})
|
||||
})
|
||||
|
||||
it("should fetch with custom limit", async () => {
|
||||
const spy = mockFetchJson([])
|
||||
await getRecentPages(10)
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
"https://hudozka.tmshv.com/pages?_sort=date:DESC&_limit=10",
|
||||
)
|
||||
})
|
||||
|
||||
it("should return empty array on failure", async () => {
|
||||
vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("fail"))
|
||||
it("should return empty array on error", async () => {
|
||||
vi.mocked(pb.collection).mockReturnValue({
|
||||
getList: vi.fn().mockRejectedValue(new Error("fail")),
|
||||
} as never)
|
||||
vi.spyOn(console, "error").mockImplementation(() => {})
|
||||
|
||||
const result = await getRecentPages()
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
+153
-44
@@ -1,70 +1,179 @@
|
||||
import { createHomeCards, createMenu, createPage, createPageUrls, createFeedPages } from "@/remote/factory"
|
||||
import { pb } from "./pb"
|
||||
import { createPage, createHomeCards, createMenu, createFeedPages } from "./factory"
|
||||
import type { PbPage, PbImage, PbFile, PbTag, PbHomeData, PbMenuData } from "./types"
|
||||
import type { DocV1Block } from "./doc"
|
||||
import type { MenuItem, Page, PageCardDto, FeedPage } from "@/types"
|
||||
|
||||
const backendUrl = "https://hudozka.tmshv.com"
|
||||
function buildIdFilter(ids: string[]): string {
|
||||
return ids.map(id => `id="${id}"`).join(" || ")
|
||||
}
|
||||
|
||||
export type FactoryFunction<I, O> =
|
||||
| ((response: I) => O)
|
||||
| ((response: I) => Promise<O>)
|
||||
export type ApiDefaultResponse<O> = () => O
|
||||
async function fetchImagesByIds(ids: string[]): Promise<Map<string, PbImage>> {
|
||||
if (ids.length === 0) return new Map()
|
||||
const records = await pb.collection("images").getFullList<PbImage>({
|
||||
filter: buildIdFilter(ids),
|
||||
})
|
||||
return new Map(records.map(r => [r.id, r]))
|
||||
}
|
||||
|
||||
export function apiGet<I, O>(factory: FactoryFunction<I, O>) {
|
||||
return async (url: string, getDefaultResponse: ApiDefaultResponse<O>) => {
|
||||
try {
|
||||
const res = await fetch(url)
|
||||
if (res.ok) {
|
||||
const data = await res.json() as I
|
||||
return factory(data)
|
||||
async function fetchFilesByIds(ids: string[]): Promise<Map<string, PbFile>> {
|
||||
if (ids.length === 0) return new Map()
|
||||
const records = await pb.collection("files").getFullList<PbFile>({
|
||||
filter: buildIdFilter(ids),
|
||||
})
|
||||
return new Map(records.map(r => [r.id, r]))
|
||||
}
|
||||
|
||||
async function fetchPagesByIds(ids: string[]): Promise<Map<string, PbPage>> {
|
||||
if (ids.length === 0) return new Map()
|
||||
const records = await pb.collection("pages").getFullList<PbPage>({
|
||||
filter: buildIdFilter(ids),
|
||||
})
|
||||
return new Map(records.map(r => [r.id, r]))
|
||||
}
|
||||
|
||||
async function fetchTagsByIds(ids: string[]): Promise<PbTag[]> {
|
||||
if (ids.length === 0) return []
|
||||
return pb.collection("tags").getFullList<PbTag>({
|
||||
filter: buildIdFilter(ids),
|
||||
})
|
||||
}
|
||||
|
||||
function collectBlockRefs(blocks: DocV1Block[]) {
|
||||
const imageIds = new Set<string>()
|
||||
const fileIds = new Set<string>()
|
||||
const pageIds = new Set<string>()
|
||||
|
||||
for (const block of blocks) {
|
||||
switch (block.type) {
|
||||
case "image":
|
||||
imageIds.add(block.image)
|
||||
break
|
||||
case "document":
|
||||
fileIds.add(block.file)
|
||||
break
|
||||
case "card-grid":
|
||||
for (const item of block.items) {
|
||||
pageIds.add(item.page)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed fetch request: ${error}`)
|
||||
return getDefaultResponse()
|
||||
break
|
||||
}
|
||||
|
||||
return getDefaultResponse()
|
||||
}
|
||||
|
||||
return { imageIds, fileIds, pageIds }
|
||||
}
|
||||
|
||||
export async function getUrls(): Promise<string[]> {
|
||||
let urls: string[] = []
|
||||
const limit = 100
|
||||
let start = 0
|
||||
while (true) {
|
||||
const url = `${backendUrl}/pages?_limit=${limit}&_start=${start}`
|
||||
const res = await apiGet(createPageUrls)(url, () => ({ items: [] }))
|
||||
if (!res || res.items.length === 0) {
|
||||
break
|
||||
}
|
||||
|
||||
start += limit
|
||||
urls = [...urls, ...res.items]
|
||||
try {
|
||||
const records = await pb.collection("pages").getFullList<PbPage>({
|
||||
fields: "slug",
|
||||
filter: "draft=false",
|
||||
})
|
||||
return records.map(r => r.slug)
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch URLs: ${error}`)
|
||||
return []
|
||||
}
|
||||
|
||||
return urls
|
||||
}
|
||||
|
||||
export async function getPageBySlug(slug: string): Promise<Page | null> {
|
||||
const url = `${backendUrl}/pages?slug=${slug}`
|
||||
const page = await apiGet(createPage)(url, () => null)
|
||||
if (!page) {
|
||||
try {
|
||||
const record = await pb.collection("pages").getFirstListItem<PbPage>(
|
||||
`slug="${slug}"`,
|
||||
)
|
||||
|
||||
// Collect all referenced IDs from blocks
|
||||
const refs = collectBlockRefs(record.doc.blocks)
|
||||
|
||||
// Include cover image ID
|
||||
if (record.cover) {
|
||||
refs.imageIds.add(record.cover)
|
||||
}
|
||||
|
||||
// Round 2: fetch images, files, tags, card-grid pages in parallel
|
||||
const [images, files, tags, cardGridPages] = await Promise.all([
|
||||
fetchImagesByIds([...refs.imageIds]),
|
||||
fetchFilesByIds([...refs.fileIds]),
|
||||
fetchTagsByIds(record.tags),
|
||||
fetchPagesByIds([...refs.pageIds]),
|
||||
])
|
||||
|
||||
// Round 3: fetch cover images for card-grid pages
|
||||
const cardGridCoverIds = new Set<string>()
|
||||
for (const page of cardGridPages.values()) {
|
||||
if (page.cover && !images.has(page.cover)) {
|
||||
cardGridCoverIds.add(page.cover)
|
||||
}
|
||||
}
|
||||
const cardGridImages = cardGridCoverIds.size > 0
|
||||
? await fetchImagesByIds([...cardGridCoverIds])
|
||||
: new Map<string, PbImage>()
|
||||
|
||||
// Merge all images for card-grid covers
|
||||
const allCardGridImages = new Map([...images, ...cardGridImages])
|
||||
|
||||
return createPage(record, images, files, tags, cardGridPages, allCardGridImages)
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch page: ${error}`)
|
||||
return null
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
export async function getHomeCards(): Promise<PageCardDto[]> {
|
||||
const items = await apiGet(createHomeCards)(`${backendUrl}/home`, async () => [])
|
||||
return items
|
||||
try {
|
||||
const kv = await pb.collection("kv").getFirstListItem<{ data: PbHomeData }>(
|
||||
"key=\"home\"",
|
||||
)
|
||||
const data = kv.data
|
||||
if (!data.cards || data.cards.length === 0) return []
|
||||
|
||||
const pageIds = data.cards.map(c => c.page)
|
||||
const pages = await fetchPagesByIds(pageIds)
|
||||
|
||||
const coverIds = [...pages.values()]
|
||||
.map(p => p.cover)
|
||||
.filter(Boolean)
|
||||
const images = await fetchImagesByIds(coverIds)
|
||||
|
||||
return createHomeCards(data, pages, images)
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch home cards: ${error}`)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMenu(): Promise<MenuItem[]> {
|
||||
const menu = await apiGet(createMenu)(`${backendUrl}/menu`, () => [])
|
||||
return menu
|
||||
try {
|
||||
const kv = await pb.collection("kv").getFirstListItem<{ data: PbMenuData }>(
|
||||
"key=\"menu\"",
|
||||
)
|
||||
const data = kv.data
|
||||
if (!data.items || data.items.length === 0) {
|
||||
return [{
|
||||
href: "/",
|
||||
name: data.homeLabel,
|
||||
}]
|
||||
}
|
||||
|
||||
const pageIds = data.items.map(i => i.page)
|
||||
const pages = await fetchPagesByIds(pageIds)
|
||||
|
||||
return createMenu(data, pages)
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch menu: ${error}`)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export async function getRecentPages(limit: number = 30): Promise<FeedPage[]> {
|
||||
const url = `${backendUrl}/pages?_sort=date:DESC&_limit=${limit}`
|
||||
const pages = await apiGet(createFeedPages)(url, () => [])
|
||||
return pages
|
||||
try {
|
||||
const result = await pb.collection("pages").getList<PbPage>(1, limit, {
|
||||
filter: "date!='' && draft=false",
|
||||
sort: "-date",
|
||||
})
|
||||
return createFeedPages(result.items)
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch recent pages: ${error}`)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
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[]
|
||||
}
|
||||
+18
-20
@@ -1,29 +1,32 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { createFeedPages } from "./factory"
|
||||
import type { StrapiPage, StrapiTag } from "./types"
|
||||
import type { PbPage } from "./types"
|
||||
|
||||
function stubPage(overrides: Partial<StrapiPage> = {}): StrapiPage {
|
||||
function stubPage(overrides: Partial<PbPage> = {}): PbPage {
|
||||
return {
|
||||
id: 1,
|
||||
id: "abc123",
|
||||
collectionId: "pbc_1125843985",
|
||||
collectionName: "pages",
|
||||
created: "2026-01-01T00:00:00.000Z",
|
||||
updated: "2026-01-01T00:00:00.000Z",
|
||||
title: "Test",
|
||||
excerpt: "Excerpt",
|
||||
slug: "/test",
|
||||
excerpt: "Excerpt",
|
||||
date: "2024-01-15",
|
||||
published_at: "",
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
content: [],
|
||||
tags: [] as StrapiTag[],
|
||||
cover: "",
|
||||
doc: { version: 1, blocks: [] },
|
||||
tags: [],
|
||||
draft: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe("createFeedPages", () => {
|
||||
it("should map strapi pages to feed pages", () => {
|
||||
const pages = [stubPage({ id: 42, title: "Hello", slug: "/hello", date: "2024-03-01", excerpt: "Summary" })]
|
||||
it("should map PB pages to feed pages", () => {
|
||||
const pages = [stubPage({ id: "x1", title: "Hello", slug: "/hello", date: "2024-03-01", excerpt: "Summary" })]
|
||||
const result = createFeedPages(pages)
|
||||
expect(result).toEqual([{
|
||||
id: "42",
|
||||
id: "x1",
|
||||
title: "Hello",
|
||||
url: "/hello",
|
||||
date: "2024-03-01",
|
||||
@@ -33,20 +36,15 @@ describe("createFeedPages", () => {
|
||||
|
||||
it("should filter out pages without date", () => {
|
||||
const pages = [
|
||||
stubPage({ id: 1, date: "2024-01-01" }),
|
||||
stubPage({ id: 2, date: null }),
|
||||
stubPage({ id: "a", date: "2024-01-01" }),
|
||||
stubPage({ id: "b", date: "" }),
|
||||
]
|
||||
const result = createFeedPages(pages)
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].id).toBe("1")
|
||||
expect(result[0].id).toBe("a")
|
||||
})
|
||||
|
||||
it("should return empty array for empty input", () => {
|
||||
expect(createFeedPages([])).toEqual([])
|
||||
})
|
||||
|
||||
it("should convert numeric id to string", () => {
|
||||
const result = createFeedPages([stubPage({ id: 99 })])
|
||||
expect(result[0].id).toBe("99")
|
||||
})
|
||||
})
|
||||
+169
-142
@@ -1,227 +1,254 @@
|
||||
import type { MenuItem, Page, Tag, PageCardDto, Pic, Token, FeedPage } from "@/types"
|
||||
import { asItem } from "./lib"
|
||||
import type { StrapiComponentEmbed, StrapiComponent, StrapiHome, StrapiPage, StrapiPageCard, StrapiTag, StrapiMedia, StrapiMenu } from "./types"
|
||||
import type { PbPage, PbImage, PbFile, PbTag, PbHomeData, PbMenuData } from "./types"
|
||||
import type { DocV1Block } from "./doc"
|
||||
import { typograf, markdownToHtml } from "@/lib/text"
|
||||
import { encodeImageToBlurhash } from "./image"
|
||||
import { pb } from "./pb"
|
||||
|
||||
const md = (text: string) => typograf(markdownToHtml(text))
|
||||
|
||||
export function createPageUrls(pages: StrapiPage[]) {
|
||||
return {
|
||||
items: pages.map(page => page.slug),
|
||||
const DEFAULT_COVER: Pic = {
|
||||
src: "/static/img/main.jpg",
|
||||
width: 1920,
|
||||
height: 1858,
|
||||
}
|
||||
|
||||
function pbFileUrl(collectionId: string, recordId: string, filename: string): string {
|
||||
return `${pb.baseURL}/api/files/${collectionId}/${recordId}/${filename}`
|
||||
}
|
||||
|
||||
function imageRecordToPic(image: PbImage, overrides?: { alt?: string; caption?: string }): Pic {
|
||||
const pic: Pic = {
|
||||
src: pbFileUrl(image.collectionId, image.id, image.file),
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
}
|
||||
|
||||
const alt = overrides?.alt || image.alt || undefined
|
||||
if (alt) {
|
||||
pic.alt = alt
|
||||
}
|
||||
|
||||
const caption = overrides?.caption || image.caption || undefined
|
||||
if (caption) {
|
||||
pic.caption = caption
|
||||
}
|
||||
|
||||
if (image.blurhash) {
|
||||
pic.blur = image.blurhash
|
||||
}
|
||||
|
||||
return pic
|
||||
}
|
||||
|
||||
function getCoverPic(coverId: string, images: Map<string, PbImage>): Pic {
|
||||
if (coverId) {
|
||||
const image = images.get(coverId)
|
||||
if (image) {
|
||||
return imageRecordToPic(image)
|
||||
}
|
||||
}
|
||||
return DEFAULT_COVER
|
||||
}
|
||||
|
||||
export function isYoutubeUrl(url: string): boolean {
|
||||
return /youtube\.com/.test(url)
|
||||
}
|
||||
|
||||
export function createEmbed(component: StrapiComponentEmbed): Token {
|
||||
if (isYoutubeUrl(component.src)) {
|
||||
export function createEmbed(src: string): Token {
|
||||
if (isYoutubeUrl(src)) {
|
||||
return {
|
||||
token: "youtube",
|
||||
data: {
|
||||
url: component.src,
|
||||
},
|
||||
data: { url: src },
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
token: "html",
|
||||
data: `<iframe src="${component.src}" width="100%" height="480" frameborder="0"></iframe>`,
|
||||
data: `<iframe src="${src}" width="100%" height="480" frameborder="0"></iframe>`,
|
||||
}
|
||||
}
|
||||
|
||||
export async function createPageToken(component: StrapiComponent): Promise<Token> {
|
||||
switch (component.__component) {
|
||||
case "hudozka.text": {
|
||||
export function createPageToken(
|
||||
block: DocV1Block,
|
||||
images: Map<string, PbImage>,
|
||||
files: Map<string, PbFile>,
|
||||
cardGridPages: Map<string, PbPage>,
|
||||
cardGridImages: Map<string, PbImage>,
|
||||
): Token {
|
||||
switch (block.type) {
|
||||
case "text":
|
||||
return {
|
||||
token: "html",
|
||||
data: md(component.text),
|
||||
data: md(block.text),
|
||||
}
|
||||
}
|
||||
|
||||
case "hudozka.image": {
|
||||
const data = await createPicFromMedia(component.media, {
|
||||
alternativeText: component.caption,
|
||||
caption: component.caption,
|
||||
})
|
||||
|
||||
case "image": {
|
||||
const image = images.get(block.image)
|
||||
if (!image) {
|
||||
return { token: "text", data: "" }
|
||||
}
|
||||
return {
|
||||
token: "image",
|
||||
wide: component.wide,
|
||||
data,
|
||||
wide: block.wide,
|
||||
data: imageRecordToPic(image, {
|
||||
alt: block.caption,
|
||||
caption: block.caption,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
case "hudozka.document": {
|
||||
case "document": {
|
||||
const file = files.get(block.file)
|
||||
if (!file) {
|
||||
return { token: "text", data: "" }
|
||||
}
|
||||
const fileUrl = pbFileUrl(file.collectionId, file.id, file.file)
|
||||
return {
|
||||
token: "file",
|
||||
data: {
|
||||
url: component.media.url,
|
||||
slug: "jopa",
|
||||
image_url: component.media.url,
|
||||
file_url: component.media.url,
|
||||
title: component.title,
|
||||
file_size: component.media.size * 1000,
|
||||
// file_size: component.media.size,
|
||||
file_format: component.media.mime,
|
||||
url: fileUrl,
|
||||
slug: "",
|
||||
image_url: fileUrl,
|
||||
file_url: fileUrl,
|
||||
title: block.title,
|
||||
file_size: file.size,
|
||||
file_format: file.mime,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
case "hudozka.embed": {
|
||||
return createEmbed(component)
|
||||
}
|
||||
case "embed":
|
||||
return createEmbed(block.src)
|
||||
|
||||
case "hudozka.card-grid": {
|
||||
const items = await Promise.all(component.items
|
||||
.filter(Boolean)
|
||||
.map(createCardGrid),
|
||||
)
|
||||
case "card-grid": {
|
||||
const items: PageCardDto[] = block.items
|
||||
.map(item => {
|
||||
const page = cardGridPages.get(item.page)
|
||||
if (!page) {
|
||||
return null
|
||||
}
|
||||
const cover = getCoverPic(page.cover, cardGridImages)
|
||||
return {
|
||||
id: page.id,
|
||||
url: page.slug,
|
||||
title: page.title,
|
||||
featured: item.layout === "big" || item.layout === "medium",
|
||||
date: page.date || null,
|
||||
cover,
|
||||
}
|
||||
})
|
||||
.filter((x): x is PageCardDto => x !== null)
|
||||
return {
|
||||
token: "grid",
|
||||
data: {
|
||||
items,
|
||||
},
|
||||
data: { items },
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
token: "text",
|
||||
data: ` ${JSON.stringify(component)}`,
|
||||
data: JSON.stringify(block),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createMenu(res: StrapiMenu): MenuItem[] {
|
||||
const items: MenuItem[] = res.menu.items.map(x => ({
|
||||
href: x.page.slug,
|
||||
name: x.page.title,
|
||||
}))
|
||||
export function createPage(
|
||||
record: PbPage,
|
||||
images: Map<string, PbImage>,
|
||||
files: Map<string, PbFile>,
|
||||
tags: PbTag[],
|
||||
cardGridPages: Map<string, PbPage>,
|
||||
cardGridImages: Map<string, PbImage>,
|
||||
): Page {
|
||||
const cover = getCoverPic(record.cover, images)
|
||||
|
||||
return [{
|
||||
href: "/",
|
||||
name: res.homeLabel,
|
||||
}, ...items]
|
||||
}
|
||||
|
||||
export async function createPage(res: StrapiPage | StrapiPage[]): Promise<Page | null> {
|
||||
const item = asItem(res)
|
||||
if (!item) {
|
||||
return null
|
||||
}
|
||||
|
||||
const cover = await getCoverImage(item.cover)
|
||||
const tags: Tag[] = item.tags.map(tag => ({
|
||||
const pageTags: Tag[] = tags.map(tag => ({
|
||||
id: tag.id,
|
||||
name: tag.name,
|
||||
name: tag.label,
|
||||
slug: tag.slug,
|
||||
href: `/tags/${tag.slug}`,
|
||||
count: 0,
|
||||
}))
|
||||
|
||||
const tokens = await Promise.all(item.content.map(createPageToken))
|
||||
const tokens: Token[] = record.doc.blocks.map(block =>
|
||||
createPageToken(block, images, files, cardGridPages, cardGridImages),
|
||||
)
|
||||
|
||||
return {
|
||||
title: item.title,
|
||||
description: item.excerpt,
|
||||
id: `${item.id}`,
|
||||
url: item.slug,
|
||||
|
||||
title: record.title,
|
||||
description: record.excerpt,
|
||||
id: record.id,
|
||||
url: record.slug,
|
||||
data: "",
|
||||
date: "",
|
||||
cover,
|
||||
tokens: [
|
||||
{
|
||||
token: "html",
|
||||
data: md(`# ${item.title}`),
|
||||
data: md(`# ${record.title}`),
|
||||
},
|
||||
|
||||
...tokens.filter(Boolean),
|
||||
...tokens,
|
||||
],
|
||||
tags,
|
||||
// breadcrumb?: [],
|
||||
tags: pageTags,
|
||||
featured: false,
|
||||
}
|
||||
}
|
||||
|
||||
function isCardFeatured(card: StrapiPageCard): boolean {
|
||||
return card.layout === "big" || card.layout === "medium"
|
||||
export function createHomeCards(
|
||||
data: PbHomeData,
|
||||
pages: Map<string, PbPage>,
|
||||
images: Map<string, PbImage>,
|
||||
): PageCardDto[] {
|
||||
return data.cards
|
||||
.map(card => {
|
||||
const page = pages.get(card.page)
|
||||
if (!page) {
|
||||
return null
|
||||
}
|
||||
const cover = getCoverPic(page.cover, images)
|
||||
return {
|
||||
id: page.id,
|
||||
url: page.slug,
|
||||
title: page.title,
|
||||
featured: card.layout === "big" || card.layout === "medium",
|
||||
date: page.date || null,
|
||||
cover,
|
||||
}
|
||||
})
|
||||
.filter((x): x is PageCardDto => x !== null)
|
||||
}
|
||||
|
||||
export async function getCoverImage(media?: StrapiMedia): Promise<Pic> {
|
||||
if (media) {
|
||||
return createPicFromMedia(media)
|
||||
}
|
||||
export function createMenu(
|
||||
data: PbMenuData,
|
||||
pages: Map<string, PbPage>,
|
||||
): MenuItem[] {
|
||||
const items: MenuItem[] = data.items
|
||||
.map(item => {
|
||||
const page = pages.get(item.page)
|
||||
if (!page) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
href: page.slug,
|
||||
name: page.title,
|
||||
}
|
||||
})
|
||||
.filter((x): x is MenuItem => x !== null)
|
||||
|
||||
return {
|
||||
src: "https://hudozkacdn.tmshv.com/main_fad9fdf29a.jpg",
|
||||
width: 1920,
|
||||
height: 1858,
|
||||
// alt: '',
|
||||
// caption: '',
|
||||
// blur: '',
|
||||
}
|
||||
return [{
|
||||
href: "/",
|
||||
name: data.homeLabel,
|
||||
}, ...items]
|
||||
}
|
||||
|
||||
async function createPicFromMedia(media: StrapiMedia, overrides?: Partial<StrapiMedia>): Promise<Pic> {
|
||||
const src = media.formats?.large?.url ?? media.url
|
||||
const pic: Pic = {
|
||||
src,
|
||||
width: media.width,
|
||||
height: media.height,
|
||||
}
|
||||
|
||||
const alt = overrides?.alternativeText ?? media.alternativeText ?? undefined
|
||||
if (alt) {
|
||||
pic.alt = alt
|
||||
}
|
||||
|
||||
const caption = overrides?.caption ?? media.caption ?? undefined
|
||||
if (caption) {
|
||||
pic.caption = caption
|
||||
}
|
||||
|
||||
const thumb = media.formats?.thumbnail?.url ?? media.url
|
||||
const blur = await encodeImageToBlurhash(thumb)
|
||||
if (blur) {
|
||||
pic.blur = blur
|
||||
}
|
||||
|
||||
return pic
|
||||
}
|
||||
|
||||
export async function createCardGrid(card: StrapiPageCard): Promise<PageCardDto> {
|
||||
const cover = await getCoverImage(card.page.cover)
|
||||
|
||||
return {
|
||||
id: card.id,
|
||||
url: card.page.slug,
|
||||
title: card.page.title,
|
||||
featured: isCardFeatured(card),
|
||||
date: card.page.date,
|
||||
cover,
|
||||
}
|
||||
}
|
||||
|
||||
export async function createHomeCards(data: StrapiHome): Promise<PageCardDto[]> {
|
||||
const items = await Promise.all(data.cards
|
||||
.map(createCardGrid),
|
||||
)
|
||||
return items
|
||||
.filter(x => !!x.url)
|
||||
}
|
||||
|
||||
export function createFeedPages(pages: StrapiPage[]): FeedPage[] {
|
||||
export function createFeedPages(pages: PbPage[]): FeedPage[] {
|
||||
return pages
|
||||
.filter(page => page.date)
|
||||
.map(page => ({
|
||||
id: `${page.id}`,
|
||||
id: page.id,
|
||||
title: page.title,
|
||||
url: page.slug,
|
||||
date: page.date!,
|
||||
date: page.date,
|
||||
excerpt: page.excerpt,
|
||||
}))
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import sharp from "sharp"
|
||||
|
||||
async function fetchBuffer(url: string) {
|
||||
try {
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) {
|
||||
return undefined
|
||||
}
|
||||
const data = await res.arrayBuffer()
|
||||
return Buffer.from(data)
|
||||
} catch (error) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export async function encodeImageToBlurhash(url: string) {
|
||||
const buffer = await fetchBuffer(url)
|
||||
if (!buffer) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const t = sharp(buffer)
|
||||
.raw()
|
||||
.resize(8, 8, { fit: "inside" })
|
||||
.toFormat("jpeg")
|
||||
|
||||
const { data } = await t.toBuffer({ resolveWithObject: true })
|
||||
|
||||
return `data:image/jpeg;base64,${data.toString("base64")}`
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
export function asArray<T>(value: T | T[]) {
|
||||
return Array.isArray(value)
|
||||
? value
|
||||
: [value]
|
||||
}
|
||||
|
||||
export function asItem<T>(value: T | T[]) {
|
||||
return Array.isArray(value)
|
||||
? value[0]
|
||||
: value
|
||||
}
|
||||
|
||||
export function paramsToSlug(parts: string | string[]): string {
|
||||
const slug = asArray(parts).join("/")
|
||||
|
||||
return `/${slug}`
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import PocketBase from "pocketbase"
|
||||
|
||||
const pb = new PocketBase(process.env.POCKETBASE_URL)
|
||||
pb.autoCancellation(false)
|
||||
|
||||
export { pb }
|
||||
+49
-126
@@ -1,135 +1,58 @@
|
||||
type StrapiMediaObject = {
|
||||
url: string,
|
||||
name: string,
|
||||
hash: string,
|
||||
ext: string,
|
||||
mime: string,
|
||||
width: number,
|
||||
height: number,
|
||||
size: number,
|
||||
// "path": null,
|
||||
import type { DocV1 } from "./doc"
|
||||
|
||||
export type PbRecord = {
|
||||
id: string
|
||||
collectionId: string
|
||||
collectionName: string
|
||||
created: string
|
||||
updated: string
|
||||
}
|
||||
|
||||
export type StrapiMedia = StrapiMediaObject & {
|
||||
id: number,
|
||||
alternativeText: string | null,
|
||||
caption: string | null,
|
||||
// "previewUrl": null,
|
||||
// "provider": "digitalocean",
|
||||
// "provider_metadata": null,
|
||||
// "created_at": "2021-01-31T20:55:04.027Z",
|
||||
// "updated_at": "2021-01-31T20:55:04.027Z"
|
||||
formats: null | {
|
||||
thumbnail: StrapiMediaObject,
|
||||
large: StrapiMediaObject,
|
||||
medium: StrapiMediaObject,
|
||||
small: StrapiMediaObject,
|
||||
},
|
||||
export type PbImage = PbRecord & {
|
||||
file: string
|
||||
filename: string
|
||||
width: number
|
||||
height: number
|
||||
blurhash: string
|
||||
alt: string
|
||||
caption: string
|
||||
}
|
||||
|
||||
type StrapiComponentText = {
|
||||
__component: "hudozka.text",
|
||||
id: number,
|
||||
text: string,
|
||||
}
|
||||
|
||||
type StrapiComponentImage = {
|
||||
__component: "hudozka.image",
|
||||
id: number,
|
||||
wide: boolean,
|
||||
caption: string,
|
||||
media: StrapiMedia,
|
||||
}
|
||||
|
||||
type StrapiComponentDocument = {
|
||||
__component: "hudozka.document",
|
||||
id: number,
|
||||
title: string,
|
||||
media: StrapiMediaObject
|
||||
// "media": {
|
||||
// "id": 210,
|
||||
// "name": "Положение.pdf",
|
||||
// // "alternativeText": null,
|
||||
// // "caption": null,
|
||||
// // "width": null,
|
||||
// // "height": null,
|
||||
// // "formats": null,
|
||||
// // "hash": "Polozhenie_efaf157737",
|
||||
// // "ext": ".pdf",
|
||||
// // "mime": "application/pdf",
|
||||
// // "size": 103.79,
|
||||
// "url": "https://hudozkacdn.tmshv.com/Polozhenie_efaf157737.pdf",
|
||||
// // "previewUrl": null,
|
||||
// // "provider": "digitalocean",
|
||||
// // "provider_metadata": null,
|
||||
// // "created_at": "2021-01-31T21:14:03.158Z",
|
||||
// // "updated_at": "2021-01-31T21:14:03.158Z",
|
||||
// }
|
||||
}
|
||||
|
||||
export type StrapiComponentEmbed = {
|
||||
__component: "hudozka.embed",
|
||||
id: number,
|
||||
src: string,
|
||||
}
|
||||
|
||||
export type StrapiComponentCardGrid = {
|
||||
__component: "hudozka.card-grid",
|
||||
id: number,
|
||||
items: StrapiPageCard[],
|
||||
}
|
||||
|
||||
export type StrapiComponent =
|
||||
| StrapiComponentText
|
||||
| StrapiComponentImage
|
||||
| StrapiComponentDocument
|
||||
| StrapiComponentEmbed
|
||||
| StrapiComponentCardGrid
|
||||
|
||||
export type StrapiTag = {
|
||||
id: number,
|
||||
slug: string,
|
||||
name: string,
|
||||
page: StrapiPage,
|
||||
// "created_at": "2021-01-31T20:38:39.373Z",
|
||||
// "updated_at": "2021-02-17T07:37:54.749Z"
|
||||
}
|
||||
|
||||
export type StrapiPage = {
|
||||
id: number,
|
||||
title: string,
|
||||
excerpt: string,
|
||||
slug: string,
|
||||
date: string | null,
|
||||
cover?: StrapiMedia,
|
||||
published_at: string,
|
||||
created_at: string,
|
||||
updated_at: string,
|
||||
content: StrapiComponent[],
|
||||
tags: StrapiTag[],
|
||||
// "breadcrumbs": [],
|
||||
// "breadcrumbRelations": []
|
||||
}
|
||||
|
||||
export type StrapiHome = {
|
||||
id: number,
|
||||
export type PbFile = PbRecord & {
|
||||
file: string
|
||||
filename: string
|
||||
mime: string
|
||||
size: number
|
||||
title: string
|
||||
cards: StrapiPageCard[]
|
||||
// "created_at": "2021-02-04T04:12:38.291Z",
|
||||
// "updated_at": "2021-02-04T16:28:30.961Z",
|
||||
preview: string
|
||||
}
|
||||
|
||||
export type StrapiMenu = {
|
||||
id: number,
|
||||
export type PbPage = PbRecord & {
|
||||
title: string
|
||||
slug: string
|
||||
excerpt: string
|
||||
date: string
|
||||
cover: string
|
||||
doc: DocV1
|
||||
tags: string[]
|
||||
draft: boolean
|
||||
}
|
||||
|
||||
export type PbTag = PbRecord & {
|
||||
slug: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export type PbKv = PbRecord & {
|
||||
key: string
|
||||
data: unknown
|
||||
}
|
||||
|
||||
export type PbHomeData = {
|
||||
cards: { page: string; layout: "small" | "medium" | "big" }[]
|
||||
}
|
||||
|
||||
export type PbMenuData = {
|
||||
homeLabel: string
|
||||
menu: StrapiComponentCardGrid
|
||||
// "created_at": "2021-02-04T04:12:38.291Z",
|
||||
// "updated_at": "2021-02-04T16:28:30.961Z",
|
||||
}
|
||||
|
||||
export type StrapiPageCard = {
|
||||
__component: "hudozka.page-card",
|
||||
id: number,
|
||||
page: StrapiPage,
|
||||
layout: "small" | "medium" | "big",
|
||||
items: { page: string }[]
|
||||
}
|
||||
+2
-2
@@ -9,7 +9,7 @@ export type BreadcrumbPart = {
|
||||
}
|
||||
|
||||
export type PageCardDto = {
|
||||
id: number
|
||||
id: string
|
||||
url: string
|
||||
title: string
|
||||
featured: boolean
|
||||
@@ -79,7 +79,7 @@ export type Meta = {
|
||||
|
||||
|
||||
export type Tag = {
|
||||
id: number
|
||||
id: string
|
||||
name: string
|
||||
slug: string
|
||||
href: string
|
||||
|
||||
Reference in new issue
Block a user