chapter-editor-header.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. import { countChapterBodyWords } from "@/lib/chapter-word-count"
  2. import { buildChapterWordCountLabel, getChapterStatusLabel } from "@/lib/chapter-display"
  3. import { parseFrontmatter } from "@/lib/frontmatter"
  4. import { normalizeChapterStatus, type ChapterStatus } from "@/lib/novel/chapter-meta"
  5. function getChapterTitleInputWidth(heading: string): number {
  6. const visualWidth = Array.from(heading).reduce((total, char) => {
  7. return total + (char.charCodeAt(0) > 255 ? 2 : 1)
  8. }, 0)
  9. return Math.max(visualWidth, 4)
  10. }
  11. export function buildChapterEditorHeader(markdown: string): {
  12. heading: string
  13. status: ChapterStatus
  14. statusLabel: string
  15. wordCountLabel: string
  16. titleInputWidthCh: number
  17. } {
  18. const { frontmatter } = parseFrontmatter(markdown)
  19. const match = markdown.match(/^#\s+(.+)$/m)
  20. const heading = match?.[1]
  21. ?? (typeof frontmatter?.title === "string" ? frontmatter.title.trim() : "")
  22. const status = normalizeChapterStatus(frontmatter?.chapter_status)
  23. const wordCount = countChapterBodyWords(markdown)
  24. return {
  25. heading,
  26. status,
  27. statusLabel: getChapterStatusLabel(status),
  28. wordCountLabel: buildChapterWordCountLabel(wordCount),
  29. titleInputWidthCh: getChapterTitleInputWidth(heading),
  30. }
  31. }