feat(compose): 正文内嵌隐藏块并升级 Markdown 编辑器
去掉整帖可见性表单,改为 :::hide 按块脱敏;工具栏补齐代码块、链接/图片对话框与粘贴拖拽上传。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -96,8 +96,6 @@ type CreatePostRequest struct {
|
|||||||
Content string `json:"content" binding:"required,min=1"`
|
Content string `json:"content" binding:"required,min=1"`
|
||||||
Tags string `json:"tags"`
|
Tags string `json:"tags"`
|
||||||
PostType string `json:"post_type"`
|
PostType string `json:"post_type"`
|
||||||
ContentAccess string `json:"content_access"`
|
|
||||||
AccessPoints int `json:"access_points"`
|
|
||||||
TypeMeta string `json:"type_meta"`
|
TypeMeta string `json:"type_meta"`
|
||||||
AttachmentIDs []uint `json:"attachment_ids"`
|
AttachmentIDs []uint `json:"attachment_ids"`
|
||||||
}
|
}
|
||||||
@@ -118,8 +116,6 @@ func (h *Handlers) CreatePost(c *gin.Context) {
|
|||||||
Content: req.Content,
|
Content: req.Content,
|
||||||
Tags: req.Tags,
|
Tags: req.Tags,
|
||||||
PostType: req.PostType,
|
PostType: req.PostType,
|
||||||
ContentAccess: req.ContentAccess,
|
|
||||||
AccessPoints: req.AccessPoints,
|
|
||||||
TypeMeta: req.TypeMeta,
|
TypeMeta: req.TypeMeta,
|
||||||
Status: status,
|
Status: status,
|
||||||
AttachmentIDs: req.AttachmentIDs,
|
AttachmentIDs: req.AttachmentIDs,
|
||||||
@@ -141,8 +137,6 @@ type UpdatePostRequest struct {
|
|||||||
Title string `json:"title" binding:"omitempty,min=1,max=256"`
|
Title string `json:"title" binding:"omitempty,min=1,max=256"`
|
||||||
Content string `json:"content" binding:"omitempty,min=1"`
|
Content string `json:"content" binding:"omitempty,min=1"`
|
||||||
Tags string `json:"tags"`
|
Tags string `json:"tags"`
|
||||||
ContentAccess *string `json:"content_access"`
|
|
||||||
AccessPoints *int `json:"access_points"`
|
|
||||||
TypeMeta *string `json:"type_meta"`
|
TypeMeta *string `json:"type_meta"`
|
||||||
AttachmentIDs *[]uint `json:"attachment_ids"`
|
AttachmentIDs *[]uint `json:"attachment_ids"`
|
||||||
}
|
}
|
||||||
@@ -165,8 +159,6 @@ func (h *Handlers) UpdatePost(c *gin.Context) {
|
|||||||
Title: req.Title,
|
Title: req.Title,
|
||||||
Content: req.Content,
|
Content: req.Content,
|
||||||
Tags: req.Tags,
|
Tags: req.Tags,
|
||||||
ContentAccess: req.ContentAccess,
|
|
||||||
AccessPoints: req.AccessPoints,
|
|
||||||
TypeMeta: req.TypeMeta,
|
TypeMeta: req.TypeMeta,
|
||||||
AttachmentIDs: req.AttachmentIDs,
|
AttachmentIDs: req.AttachmentIDs,
|
||||||
})
|
})
|
||||||
|
|||||||
324
backend/markdown/hide.go
Normal file
324
backend/markdown/hide.go
Normal file
@@ -0,0 +1,324 @@
|
|||||||
|
// Package markdown 提供帖子正文隐藏块(:::hide)的解析、校验与脱敏。
|
||||||
|
package markdown
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
HideKindLogin = "login"
|
||||||
|
HideKindReply = "reply"
|
||||||
|
HideKindPoints = "points"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HideBlock 正文中的一段隐藏内容
|
||||||
|
type HideBlock struct {
|
||||||
|
Kind string // login | reply | points
|
||||||
|
Points int // 仅 points 有效
|
||||||
|
Body string // 块内 Markdown(不含开闭标记行)
|
||||||
|
Start int // 开标记行在 lines 中的下标
|
||||||
|
End int // 闭标记行在 lines 中的下标(含)
|
||||||
|
Locked bool // 开标记是否已带 locked(脱敏输出)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DerivedAccess 由正文隐藏块派生的帖级可见性
|
||||||
|
type DerivedAccess struct {
|
||||||
|
Access string // public | login | reply | points | mixed
|
||||||
|
Points int // 所有积分块价格之和
|
||||||
|
}
|
||||||
|
|
||||||
|
// ViewerCaps 读者对隐藏块的能力(由 service 填充)
|
||||||
|
type ViewerCaps struct {
|
||||||
|
Bypass bool // 作者 / 版主
|
||||||
|
LoggedIn bool
|
||||||
|
HasReplied bool
|
||||||
|
PointsPaid bool // 已支付本帖积分解锁
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrHideNested = errors.New("隐藏块不可嵌套")
|
||||||
|
ErrHideUnclosed = errors.New("隐藏块未正确闭合")
|
||||||
|
ErrHideInvalid = errors.New("隐藏块语法无效")
|
||||||
|
ErrHidePointsNeed = errors.New("积分可见块须指定 1–100000 的积分")
|
||||||
|
)
|
||||||
|
|
||||||
|
// ParseHideBlocks 扫描正文中的 :::hide 块(忽略代码围栏内伪语法)。
|
||||||
|
// 校验失败返回 error(用于 Create/Update)。
|
||||||
|
func ParseHideBlocks(content string) ([]HideBlock, error) {
|
||||||
|
lines := splitLines(content)
|
||||||
|
var blocks []HideBlock
|
||||||
|
inCode := false
|
||||||
|
i := 0
|
||||||
|
for i < len(lines) {
|
||||||
|
trimmed := strings.TrimSpace(lines[i])
|
||||||
|
|
||||||
|
if strings.HasPrefix(trimmed, "```") {
|
||||||
|
inCode = !inCode
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if inCode {
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if kind, pts, locked, ok := parseOpenMarker(trimmed); ok {
|
||||||
|
j := i + 1
|
||||||
|
bodyLines := make([]string, 0)
|
||||||
|
foundClose := false
|
||||||
|
innerCode := false
|
||||||
|
for j < len(lines) {
|
||||||
|
inner := strings.TrimSpace(lines[j])
|
||||||
|
if strings.HasPrefix(inner, "```") {
|
||||||
|
innerCode = !innerCode
|
||||||
|
bodyLines = append(bodyLines, lines[j])
|
||||||
|
j++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if innerCode {
|
||||||
|
bodyLines = append(bodyLines, lines[j])
|
||||||
|
j++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, _, _, isOpen := parseOpenMarker(inner); isOpen {
|
||||||
|
return nil, ErrHideNested
|
||||||
|
}
|
||||||
|
if isCloseMarker(inner) {
|
||||||
|
foundClose = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
bodyLines = append(bodyLines, lines[j])
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
if !foundClose {
|
||||||
|
return nil, ErrHideUnclosed
|
||||||
|
}
|
||||||
|
if kind == HideKindPoints {
|
||||||
|
if pts < 1 || pts > 100000 {
|
||||||
|
return nil, ErrHidePointsNeed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
blocks = append(blocks, HideBlock{
|
||||||
|
Kind: kind,
|
||||||
|
Points: pts,
|
||||||
|
Body: strings.Join(bodyLines, "\n"),
|
||||||
|
Start: i,
|
||||||
|
End: j,
|
||||||
|
Locked: locked,
|
||||||
|
})
|
||||||
|
i = j + 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if isCloseMarker(trimmed) {
|
||||||
|
return nil, ErrHideInvalid
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return blocks, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeriveAccess 由隐藏块列表派生帖级 content_access / access_points
|
||||||
|
func DeriveAccess(blocks []HideBlock) DerivedAccess {
|
||||||
|
if len(blocks) == 0 {
|
||||||
|
return DerivedAccess{Access: "public", Points: 0}
|
||||||
|
}
|
||||||
|
kinds := map[string]struct{}{}
|
||||||
|
totalPts := 0
|
||||||
|
for _, b := range blocks {
|
||||||
|
kinds[b.Kind] = struct{}{}
|
||||||
|
if b.Kind == HideKindPoints {
|
||||||
|
totalPts += b.Points
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(kinds) > 1 {
|
||||||
|
return DerivedAccess{Access: "mixed", Points: totalPts}
|
||||||
|
}
|
||||||
|
for k := range kinds {
|
||||||
|
return DerivedAccess{Access: k, Points: totalPts}
|
||||||
|
}
|
||||||
|
return DerivedAccess{Access: "public", Points: 0}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeriveAccessFromContent 解析并派生;校验失败返回 error
|
||||||
|
func DeriveAccessFromContent(content string) (DerivedAccess, error) {
|
||||||
|
blocks, err := ParseHideBlocks(content)
|
||||||
|
if err != nil {
|
||||||
|
return DerivedAccess{}, err
|
||||||
|
}
|
||||||
|
return DeriveAccess(blocks), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SanitizeForViewer 按读者能力脱敏:未满足条件的块清空正文并加 locked。
|
||||||
|
// fullyLocked 表示读者当前看不到任何可见正文(整篇都在锁块里或公开区为空)。
|
||||||
|
func SanitizeForViewer(content string, caps ViewerCaps) (sanitized string, fullyLocked bool) {
|
||||||
|
blocks, err := ParseHideBlocks(content)
|
||||||
|
if err != nil {
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
if len(blocks) == 0 {
|
||||||
|
return content, strings.TrimSpace(content) == ""
|
||||||
|
}
|
||||||
|
if caps.Bypass {
|
||||||
|
return content, false
|
||||||
|
}
|
||||||
|
|
||||||
|
lines := splitLines(content)
|
||||||
|
var out []string
|
||||||
|
cursor := 0
|
||||||
|
anyVisible := false
|
||||||
|
|
||||||
|
for _, b := range blocks {
|
||||||
|
for i := cursor; i < b.Start; i++ {
|
||||||
|
out = append(out, lines[i])
|
||||||
|
if strings.TrimSpace(lines[i]) != "" {
|
||||||
|
anyVisible = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if blockUnlocked(b, caps) {
|
||||||
|
out = append(out, openMarkerLine(b.Kind, b.Points, false))
|
||||||
|
if b.Body != "" {
|
||||||
|
out = append(out, splitLines(b.Body)...)
|
||||||
|
if strings.TrimSpace(b.Body) != "" {
|
||||||
|
anyVisible = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, ":::")
|
||||||
|
} else {
|
||||||
|
out = append(out, openMarkerLine(b.Kind, b.Points, true))
|
||||||
|
out = append(out, ":::")
|
||||||
|
}
|
||||||
|
cursor = b.End + 1
|
||||||
|
}
|
||||||
|
for i := cursor; i < len(lines); i++ {
|
||||||
|
out = append(out, lines[i])
|
||||||
|
if strings.TrimSpace(lines[i]) != "" {
|
||||||
|
anyVisible = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.Join(out, "\n"), !anyVisible
|
||||||
|
}
|
||||||
|
|
||||||
|
// WrapContentAsHide 将整篇正文包进单一隐藏块(旧帖迁移用)
|
||||||
|
func WrapContentAsHide(kind string, points int, content string) string {
|
||||||
|
body := strings.TrimRight(content, "\n")
|
||||||
|
open := openMarkerLine(kind, points, false)
|
||||||
|
if body == "" {
|
||||||
|
return open + "\n:::\n"
|
||||||
|
}
|
||||||
|
return open + "\n" + body + "\n:::\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasHideBlocks 快速判断正文是否已含隐藏块(迁移幂等)
|
||||||
|
func HasHideBlocks(content string) bool {
|
||||||
|
blocks, err := ParseHideBlocks(content)
|
||||||
|
if err != nil {
|
||||||
|
return strings.Contains(content, ":::hide")
|
||||||
|
}
|
||||||
|
return len(blocks) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func blockUnlocked(b HideBlock, caps ViewerCaps) bool {
|
||||||
|
switch b.Kind {
|
||||||
|
case HideKindLogin:
|
||||||
|
return caps.LoggedIn
|
||||||
|
case HideKindReply:
|
||||||
|
return caps.HasReplied
|
||||||
|
case HideKindPoints:
|
||||||
|
return caps.PointsPaid
|
||||||
|
default:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func openMarkerLine(kind string, points int, locked bool) string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(":::hide ")
|
||||||
|
b.WriteString(kind)
|
||||||
|
if kind == HideKindPoints && points > 0 {
|
||||||
|
b.WriteByte(' ')
|
||||||
|
b.WriteString(strconv.Itoa(points))
|
||||||
|
}
|
||||||
|
if locked {
|
||||||
|
b.WriteString(" locked")
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseOpenMarker(trimmed string) (kind string, points int, locked bool, ok bool) {
|
||||||
|
if !strings.HasPrefix(trimmed, ":::hide") {
|
||||||
|
return "", 0, false, false
|
||||||
|
}
|
||||||
|
rest := strings.TrimSpace(trimmed[len(":::hide"):])
|
||||||
|
if rest == "" {
|
||||||
|
return "", 0, false, false
|
||||||
|
}
|
||||||
|
parts := strings.Fields(rest)
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return "", 0, false, false
|
||||||
|
}
|
||||||
|
kind = parts[0]
|
||||||
|
switch kind {
|
||||||
|
case HideKindLogin, HideKindReply, HideKindPoints:
|
||||||
|
default:
|
||||||
|
return "", 0, false, false
|
||||||
|
}
|
||||||
|
idx := 1
|
||||||
|
if kind == HideKindPoints {
|
||||||
|
if idx >= len(parts) {
|
||||||
|
return "", 0, false, false
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(parts[idx])
|
||||||
|
if err != nil {
|
||||||
|
return "", 0, false, false
|
||||||
|
}
|
||||||
|
points = n
|
||||||
|
idx++
|
||||||
|
}
|
||||||
|
for ; idx < len(parts); idx++ {
|
||||||
|
if parts[idx] == "locked" {
|
||||||
|
locked = true
|
||||||
|
} else {
|
||||||
|
return "", 0, false, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return kind, points, locked, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func isCloseMarker(trimmed string) bool {
|
||||||
|
return trimmed == ":::"
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitLines(s string) []string {
|
||||||
|
if s == "" {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
s = strings.ReplaceAll(s, "\r\n", "\n")
|
||||||
|
s = strings.ReplaceAll(s, "\r", "\n")
|
||||||
|
return strings.Split(s, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateHideContent 校验正文隐藏块;失败返回用户可读错误
|
||||||
|
func ValidateHideContent(content string) error {
|
||||||
|
_, err := ParseHideBlocks(content)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, ErrHideNested):
|
||||||
|
return fmt.Errorf("隐藏块不可嵌套")
|
||||||
|
case errors.Is(err, ErrHideUnclosed):
|
||||||
|
return fmt.Errorf("隐藏块未正确闭合,请检查 ::: 标记")
|
||||||
|
case errors.Is(err, ErrHidePointsNeed):
|
||||||
|
return fmt.Errorf("积分可见块须指定 1–100000 的积分")
|
||||||
|
case errors.Is(err, ErrHideInvalid):
|
||||||
|
return fmt.Errorf("隐藏块语法无效")
|
||||||
|
default:
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
122
backend/markdown/hide_test.go
Normal file
122
backend/markdown/hide_test.go
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
package markdown
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseIgnoreCodeFence(t *testing.T) {
|
||||||
|
src := "公开\n\n```\n:::hide login\n假的\n:::\n```\n\n结尾\n"
|
||||||
|
blocks, err := ParseHideBlocks(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(blocks) != 0 {
|
||||||
|
t.Fatalf("expected 0 blocks, got %d", len(blocks))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseMixedAndDerive(t *testing.T) {
|
||||||
|
src := "公开段\n\n:::hide login\n登录内容\n:::\n\n:::hide points 10\n积分A\n:::\n\n:::hide points 5\n积分B\n:::\n"
|
||||||
|
blocks, err := ParseHideBlocks(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(blocks) != 3 {
|
||||||
|
t.Fatalf("expected 3 blocks, got %d", len(blocks))
|
||||||
|
}
|
||||||
|
d := DeriveAccess(blocks)
|
||||||
|
if d.Access != "mixed" {
|
||||||
|
t.Fatalf("access=%s", d.Access)
|
||||||
|
}
|
||||||
|
if d.Points != 15 {
|
||||||
|
t.Fatalf("points=%d", d.Points)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseNestedRejected(t *testing.T) {
|
||||||
|
src := ":::hide login\n外\n:::hide reply\n内\n:::\n:::\n"
|
||||||
|
_, err := ParseHideBlocks(src)
|
||||||
|
if err != ErrHideNested {
|
||||||
|
t.Fatalf("want ErrHideNested, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSanitizeLocksBody(t *testing.T) {
|
||||||
|
src := "公开\n\n:::hide login\n秘密内容\n:::\n\n尾\n"
|
||||||
|
out, fully := SanitizeForViewer(src, ViewerCaps{})
|
||||||
|
if fully {
|
||||||
|
t.Fatal("should not be fully locked")
|
||||||
|
}
|
||||||
|
if strings.Contains(out, "秘密内容") {
|
||||||
|
t.Fatalf("leaked: %q", out)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, ":::hide login locked") {
|
||||||
|
t.Fatalf("missing locked marker: %q", out)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "公开") || !strings.Contains(out, "尾") {
|
||||||
|
t.Fatalf("public parts lost: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSanitizeUnlockLogin(t *testing.T) {
|
||||||
|
src := ":::hide login\n秘密\n:::\n"
|
||||||
|
out, fully := SanitizeForViewer(src, ViewerCaps{LoggedIn: true})
|
||||||
|
if fully {
|
||||||
|
t.Fatal("should see content")
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "秘密") {
|
||||||
|
t.Fatalf("missing body: %q", out)
|
||||||
|
}
|
||||||
|
if strings.Contains(out, "locked") {
|
||||||
|
t.Fatalf("should not lock: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSanitizeBypass(t *testing.T) {
|
||||||
|
src := ":::hide points 9\n付费\n:::\n"
|
||||||
|
out, _ := SanitizeForViewer(src, ViewerCaps{Bypass: true})
|
||||||
|
if !strings.Contains(out, "付费") {
|
||||||
|
t.Fatalf("bypass failed: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSanitizePointsPaid(t *testing.T) {
|
||||||
|
src := ":::hide points 3\n付费文\n:::\n"
|
||||||
|
out, _ := SanitizeForViewer(src, ViewerCaps{LoggedIn: true, PointsPaid: true})
|
||||||
|
if !strings.Contains(out, "付费文") {
|
||||||
|
t.Fatalf("paid unlock failed: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFullyLocked(t *testing.T) {
|
||||||
|
src := ":::hide reply\n仅回复\n:::\n"
|
||||||
|
_, fully := SanitizeForViewer(src, ViewerCaps{LoggedIn: true})
|
||||||
|
if !fully {
|
||||||
|
t.Fatal("expected fully locked")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCodeInsideHide(t *testing.T) {
|
||||||
|
src := ":::hide login\n```\n:::hide reply\n伪\n:::\n```\n真\n:::\n"
|
||||||
|
blocks, err := ParseHideBlocks(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(blocks) != 1 {
|
||||||
|
t.Fatalf("got %d", len(blocks))
|
||||||
|
}
|
||||||
|
if !strings.Contains(blocks[0].Body, "真") {
|
||||||
|
t.Fatalf("body=%q", blocks[0].Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrapContentAsHide(t *testing.T) {
|
||||||
|
got := WrapContentAsHide("points", 20, "旧正文")
|
||||||
|
if !strings.HasPrefix(got, ":::hide points 20\n") {
|
||||||
|
t.Fatalf("%q", got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(got, "旧正文") {
|
||||||
|
t.Fatal(got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
|
"github.com/freefire/jiang13-bbs/markdown"
|
||||||
"gorm.io/driver/postgres"
|
"gorm.io/driver/postgres"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
"gorm.io/gorm/logger"
|
||||||
@@ -45,6 +46,11 @@ func InitDB(dsn string) error {
|
|||||||
return fmt.Errorf("自动迁移失败: %w", err)
|
return fmt.Errorf("自动迁移失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 旧帖整帖可见性 → 正文 :::hide 块(幂等)
|
||||||
|
if err := migratePostContentAccessToHideBlocks(db); err != nil {
|
||||||
|
return fmt.Errorf("正文隐藏块迁移失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
// 一次性:用签到累计回填 User.Points(仅余额仍为 0 且有签到积分的用户)
|
// 一次性:用签到累计回填 User.Points(仅余额仍为 0 且有签到积分的用户)
|
||||||
if err := backfillPointsFromCheckin(db); err != nil {
|
if err := backfillPointsFromCheckin(db); err != nil {
|
||||||
return fmt.Errorf("积分余额回填失败: %w", err)
|
return fmt.Errorf("积分余额回填失败: %w", err)
|
||||||
@@ -365,3 +371,39 @@ func ensureDefaultChatMemberships(db *gorm.DB) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// migratePostContentAccessToHideBlocks 将旧帖整帖可见性包进 :::hide 块(幂等)。
|
||||||
|
func migratePostContentAccessToHideBlocks(db *gorm.DB) error {
|
||||||
|
var posts []Post
|
||||||
|
if err := db.Unscoped().
|
||||||
|
Where("content_access IN ? AND deleted_at IS NULL",
|
||||||
|
[]string{ContentAccessLogin, ContentAccessReply, ContentAccessPoints}).
|
||||||
|
Find(&posts).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
n := 0
|
||||||
|
for i := range posts {
|
||||||
|
p := &posts[i]
|
||||||
|
if markdown.HasHideBlocks(p.Content) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
kind := NormalizeContentAccess(p.ContentAccess)
|
||||||
|
pts := 0
|
||||||
|
if kind == ContentAccessPoints {
|
||||||
|
pts = p.AccessPoints
|
||||||
|
if pts <= 0 {
|
||||||
|
pts = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wrapped := markdown.WrapContentAsHide(kind, pts, p.Content)
|
||||||
|
if err := db.Model(&Post{}).Where("id = ?", p.ID).
|
||||||
|
Update("content", wrapped).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
log.Printf("[model] 旧帖可见性已迁入隐藏块:%d 篇", n)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -80,18 +80,19 @@ func NormalizePostType(t string) string {
|
|||||||
return PostTypeDiscussion
|
return PostTypeDiscussion
|
||||||
}
|
}
|
||||||
|
|
||||||
// 正文可见性
|
// 正文可见性(由正文 :::hide 块派生;mixed = 多种隐藏类型并存)
|
||||||
const (
|
const (
|
||||||
ContentAccessPublic = "public" // 公开
|
ContentAccessPublic = "public" // 公开
|
||||||
ContentAccessLogin = "login" // 登录可见
|
ContentAccessLogin = "login" // 仅登录可见块
|
||||||
ContentAccessReply = "reply" // 回复可见
|
ContentAccessReply = "reply" // 仅回复可见块
|
||||||
ContentAccessPoints = "points" // 积分购买可见
|
ContentAccessPoints = "points" // 仅积分可见块
|
||||||
|
ContentAccessMixed = "mixed" // 多种隐藏块混合
|
||||||
)
|
)
|
||||||
|
|
||||||
// ValidContentAccess 可见性白名单
|
// ValidContentAccess 可见性白名单
|
||||||
func ValidContentAccess(a string) bool {
|
func ValidContentAccess(a string) bool {
|
||||||
switch a {
|
switch a {
|
||||||
case ContentAccessPublic, ContentAccessLogin, ContentAccessReply, ContentAccessPoints:
|
case ContentAccessPublic, ContentAccessLogin, ContentAccessReply, ContentAccessPoints, ContentAccessMixed:
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
@@ -167,8 +168,8 @@ type Post struct {
|
|||||||
Content string `gorm:"type:text;not null" json:"content"`
|
Content string `gorm:"type:text;not null" json:"content"`
|
||||||
Tags string `gorm:"size:256" json:"tags"`
|
Tags string `gorm:"size:256" json:"tags"`
|
||||||
PostType string `gorm:"size:16;default:discussion;index" json:"post_type"`
|
PostType string `gorm:"size:16;default:discussion;index" json:"post_type"`
|
||||||
ContentAccess string `gorm:"size:16;default:public;index" json:"content_access"` // public|login|reply|points
|
ContentAccess string `gorm:"size:16;default:public;index" json:"content_access"` // public|login|reply|points|mixed(由正文隐藏块派生)
|
||||||
AccessPoints int `gorm:"not null;default:0" json:"access_points"` // points 可见时所需积分
|
AccessPoints int `gorm:"not null;default:0" json:"access_points"` // 积分隐藏块价格之和
|
||||||
TypeMeta string `gorm:"type:text;default:''" json:"type_meta"` // 类型扩展 JSON(投票/悬赏/抽奖壳)
|
TypeMeta string `gorm:"type:text;default:''" json:"type_meta"` // 类型扩展 JSON(投票/悬赏/抽奖壳)
|
||||||
Pinned int `gorm:"default:0" json:"pinned"`
|
Pinned int `gorm:"default:0" json:"pinned"`
|
||||||
Recommended bool `gorm:"default:false;index" json:"recommended"`
|
Recommended bool `gorm:"default:false;index" json:"recommended"`
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/freefire/jiang13-bbs/markdown"
|
||||||
"github.com/freefire/jiang13-bbs/model"
|
"github.com/freefire/jiang13-bbs/model"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
@@ -402,7 +403,7 @@ type PostDetail struct {
|
|||||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreatePostInput 发帖入参
|
// CreatePostInput 发帖入参(content_access / access_points 由正文 :::hide 派生)
|
||||||
type CreatePostInput struct {
|
type CreatePostInput struct {
|
||||||
UserID uint
|
UserID uint
|
||||||
BoardID uint
|
BoardID uint
|
||||||
@@ -410,8 +411,6 @@ type CreatePostInput struct {
|
|||||||
Content string
|
Content string
|
||||||
Tags string
|
Tags string
|
||||||
PostType string
|
PostType string
|
||||||
ContentAccess string
|
|
||||||
AccessPoints int
|
|
||||||
TypeMeta string
|
TypeMeta string
|
||||||
Status string
|
Status string
|
||||||
AttachmentIDs []uint
|
AttachmentIDs []uint
|
||||||
@@ -422,8 +421,6 @@ type UpdatePostInput struct {
|
|||||||
Title string
|
Title string
|
||||||
Content string
|
Content string
|
||||||
Tags string
|
Tags string
|
||||||
ContentAccess *string
|
|
||||||
AccessPoints *int
|
|
||||||
TypeMeta *string
|
TypeMeta *string
|
||||||
AttachmentIDs *[]uint // nil=不改附件;非 nil=替换列表
|
AttachmentIDs *[]uint // nil=不改附件;非 nil=替换列表
|
||||||
}
|
}
|
||||||
@@ -464,12 +461,10 @@ func (s *PostService) GetByIDForViewer(id, viewerID uint, loadActor func() *Acto
|
|||||||
post.ViewCount++
|
post.ViewCount++
|
||||||
|
|
||||||
detail := buildPostDetail(&post)
|
detail := buildPostDetail(&post)
|
||||||
locked, hint := s.evalContentAccess(&post, viewerID, loadActor)
|
sanitized, fullyLocked, hint := s.sanitizePostContent(&post, viewerID, loadActor)
|
||||||
detail.ContentLocked = locked
|
detail.Content = sanitized
|
||||||
|
detail.ContentLocked = fullyLocked
|
||||||
detail.AccessHint = hint
|
detail.AccessHint = hint
|
||||||
if locked {
|
|
||||||
detail.Content = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
atts, _ := s.listAttachmentDTOs(post.ID, viewerID, post.UserID)
|
atts, _ := s.listAttachmentDTOs(post.ID, viewerID, post.UserID)
|
||||||
detail.Attachments = atts
|
detail.Attachments = atts
|
||||||
@@ -521,56 +516,81 @@ func buildPostDetail(post *model.Post) *PostDetail {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *PostService) evalContentAccess(post *model.Post, viewerID uint, loadActor func() *Actor) (locked bool, hint string) {
|
// sanitizePostContent 按读者能力对正文 :::hide 块脱敏;fullyLocked 表示无可见正文。
|
||||||
access := model.NormalizeContentAccess(post.ContentAccess)
|
func (s *PostService) sanitizePostContent(post *model.Post, viewerID uint, loadActor func() *Actor) (content string, fullyLocked bool, hint string) {
|
||||||
if access == model.ContentAccessPublic {
|
caps := s.buildHideViewerCaps(post, viewerID, loadActor)
|
||||||
return false, ""
|
sanitized, fully := markdown.SanitizeForViewer(post.Content, caps)
|
||||||
|
if !fully {
|
||||||
|
return sanitized, false, ""
|
||||||
}
|
}
|
||||||
// 作者与版主始终可见
|
access := model.NormalizeContentAccess(post.ContentAccess)
|
||||||
|
switch access {
|
||||||
|
case model.ContentAccessPoints:
|
||||||
|
return sanitized, true, "支付积分后可见隐藏内容"
|
||||||
|
case model.ContentAccessMixed:
|
||||||
|
if post.AccessPoints > 0 {
|
||||||
|
return sanitized, true, "满足条件后可见隐藏内容"
|
||||||
|
}
|
||||||
|
return sanitized, true, "满足条件后可见隐藏内容"
|
||||||
|
case model.ContentAccessReply:
|
||||||
|
return sanitized, true, "回复本帖后可见隐藏内容"
|
||||||
|
case model.ContentAccessLogin:
|
||||||
|
return sanitized, true, "登录后可见隐藏内容"
|
||||||
|
default:
|
||||||
|
return sanitized, true, "正文暂不可见"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostService) buildHideViewerCaps(post *model.Post, viewerID uint, loadActor func() *Actor) markdown.ViewerCaps {
|
||||||
|
caps := markdown.ViewerCaps{}
|
||||||
if viewerID > 0 && post.UserID == viewerID {
|
if viewerID > 0 && post.UserID == viewerID {
|
||||||
return false, ""
|
caps.Bypass = true
|
||||||
|
caps.LoggedIn = true
|
||||||
|
return caps
|
||||||
}
|
}
|
||||||
if loadActor != nil && loadActor().CanModerateBoard(post.BoardID) {
|
if loadActor != nil && loadActor().CanModerateBoard(post.BoardID) {
|
||||||
return false, ""
|
caps.Bypass = true
|
||||||
|
caps.LoggedIn = true
|
||||||
|
return caps
|
||||||
|
}
|
||||||
|
if viewerID == 0 {
|
||||||
|
return caps
|
||||||
|
}
|
||||||
|
caps.LoggedIn = true
|
||||||
|
|
||||||
|
needReply := false
|
||||||
|
needPoints := false
|
||||||
|
blocks, err := markdown.ParseHideBlocks(post.Content)
|
||||||
|
if err == nil {
|
||||||
|
for _, b := range blocks {
|
||||||
|
if b.Kind == markdown.HideKindReply {
|
||||||
|
needReply = true
|
||||||
|
}
|
||||||
|
if b.Kind == markdown.HideKindPoints {
|
||||||
|
needPoints = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
access := model.NormalizeContentAccess(post.ContentAccess)
|
||||||
|
needReply = access == model.ContentAccessReply || access == model.ContentAccessMixed
|
||||||
|
needPoints = post.AccessPoints > 0 || access == model.ContentAccessPoints || access == model.ContentAccessMixed
|
||||||
}
|
}
|
||||||
|
|
||||||
switch access {
|
if needReply {
|
||||||
case model.ContentAccessLogin:
|
|
||||||
if viewerID == 0 {
|
|
||||||
return true, "登录后可见全文"
|
|
||||||
}
|
|
||||||
return false, ""
|
|
||||||
case model.ContentAccessReply:
|
|
||||||
if viewerID == 0 {
|
|
||||||
return true, "回复本帖后可见全文"
|
|
||||||
}
|
|
||||||
var n int64
|
var n int64
|
||||||
s.db.Model(&model.Comment{}).
|
s.db.Model(&model.Comment{}).
|
||||||
Where("post_id = ? AND user_id = ? AND status = ? AND deleted_at IS NULL",
|
Where("post_id = ? AND user_id = ? AND status = ? AND deleted_at IS NULL",
|
||||||
post.ID, viewerID, model.ContentStatusPublished).
|
post.ID, viewerID, model.ContentStatusPublished).
|
||||||
Count(&n)
|
Count(&n)
|
||||||
if n == 0 {
|
caps.HasReplied = n > 0
|
||||||
return true, "回复本帖后可见全文"
|
|
||||||
}
|
|
||||||
return false, ""
|
|
||||||
case model.ContentAccessPoints:
|
|
||||||
need := post.AccessPoints
|
|
||||||
if need <= 0 {
|
|
||||||
need = 1
|
|
||||||
}
|
|
||||||
if viewerID == 0 {
|
|
||||||
return true, "支付积分后可见全文"
|
|
||||||
}
|
}
|
||||||
|
if needPoints {
|
||||||
var n int64
|
var n int64
|
||||||
s.db.Model(&model.PostContentUnlock{}).
|
s.db.Model(&model.PostContentUnlock{}).
|
||||||
Where("post_id = ? AND user_id = ?", post.ID, viewerID).Count(&n)
|
Where("post_id = ? AND user_id = ?", post.ID, viewerID).Count(&n)
|
||||||
if n > 0 {
|
caps.PointsPaid = n > 0
|
||||||
return false, ""
|
|
||||||
}
|
|
||||||
return true, "支付积分后可见全文"
|
|
||||||
default:
|
|
||||||
return false, ""
|
|
||||||
}
|
}
|
||||||
|
return caps
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *PostService) listAttachmentDTOs(postID, viewerID, authorID uint) ([]PostAttachmentDTO, error) {
|
func (s *PostService) listAttachmentDTOs(postID, viewerID, authorID uint) ([]PostAttachmentDTO, error) {
|
||||||
@@ -605,21 +625,25 @@ func (s *PostService) listAttachmentDTOs(postID, viewerID, authorID uint) ([]Pos
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UnlockContent 积分解锁正文
|
// UnlockContent 积分解锁正文隐藏块(一次支付解锁本帖全部积分块)
|
||||||
func (s *PostService) UnlockContent(userID, postID uint) (*PostDetail, error) {
|
func (s *PostService) UnlockContent(userID, postID uint) (*PostDetail, error) {
|
||||||
var post model.Post
|
var post model.Post
|
||||||
if err := s.db.Preload("Board").Preload("User").First(&post, postID).Error; err != nil {
|
if err := s.db.Preload("Board").Preload("User").First(&post, postID).Error; err != nil {
|
||||||
return nil, ErrPostNotFound
|
return nil, ErrPostNotFound
|
||||||
}
|
}
|
||||||
if model.NormalizeContentAccess(post.ContentAccess) != model.ContentAccessPoints {
|
derived, derr := markdown.DeriveAccessFromContent(post.Content)
|
||||||
|
if derr != nil {
|
||||||
|
return nil, derr
|
||||||
|
}
|
||||||
|
need := derived.Points
|
||||||
|
if need <= 0 {
|
||||||
|
need = post.AccessPoints
|
||||||
|
}
|
||||||
|
if need <= 0 {
|
||||||
return nil, errors.New("本文无需积分解锁")
|
return nil, errors.New("本文无需积分解锁")
|
||||||
}
|
}
|
||||||
if post.UserID == userID {
|
if post.UserID == userID {
|
||||||
return buildPostDetail(&post), nil
|
return s.detailAfterInteract(&post, userID)
|
||||||
}
|
|
||||||
need := post.AccessPoints
|
|
||||||
if need <= 0 {
|
|
||||||
need = 1
|
|
||||||
}
|
}
|
||||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
var n int64
|
var n int64
|
||||||
@@ -645,11 +669,7 @@ func (s *PostService) UnlockContent(userID, postID uint) (*PostDetail, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
detail := buildPostDetail(&post)
|
return s.detailAfterInteract(&post, userID)
|
||||||
atts, _ := s.listAttachmentDTOs(post.ID, userID, post.UserID)
|
|
||||||
detail.Attachments = atts
|
|
||||||
s.fillInteractState(detail, &post, userID, nil)
|
|
||||||
return detail, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create 创建帖子。status 由 handler 按角色计算
|
// Create 创建帖子。status 由 handler 按角色计算
|
||||||
@@ -673,18 +693,15 @@ func (s *PostService) Create(in CreatePostInput) (*PostDetail, error) {
|
|||||||
if !model.ValidPostType(postType) {
|
if !model.ValidPostType(postType) {
|
||||||
return nil, errors.New("无效的帖子类型")
|
return nil, errors.New("无效的帖子类型")
|
||||||
}
|
}
|
||||||
access := model.NormalizeContentAccess(in.ContentAccess)
|
if err := markdown.ValidateHideContent(content); err != nil {
|
||||||
accessPts := in.AccessPoints
|
return nil, err
|
||||||
if access == model.ContentAccessPoints {
|
|
||||||
if accessPts <= 0 {
|
|
||||||
return nil, errors.New("请设置解锁所需积分")
|
|
||||||
}
|
}
|
||||||
if accessPts > 100000 {
|
derived, err := markdown.DeriveAccessFromContent(content)
|
||||||
return nil, errors.New("解锁积分过高")
|
if err != nil {
|
||||||
}
|
return nil, err
|
||||||
} else {
|
|
||||||
accessPts = 0
|
|
||||||
}
|
}
|
||||||
|
access := model.NormalizeContentAccess(derived.Access)
|
||||||
|
accessPts := derived.Points
|
||||||
typeMeta, err := NormalizeAndValidateTypeMeta(postType, in.TypeMeta)
|
typeMeta, err := NormalizeAndValidateTypeMeta(postType, in.TypeMeta)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -840,31 +857,19 @@ func (s *PostService) Update(actor *Actor, postID, userID uint, in UpdatePostInp
|
|||||||
if c == "" {
|
if c == "" {
|
||||||
return nil, errors.New("内容不能为空")
|
return nil, errors.New("内容不能为空")
|
||||||
}
|
}
|
||||||
|
if err := markdown.ValidateHideContent(c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
derived, err := markdown.DeriveAccessFromContent(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
updates["content"] = c
|
updates["content"] = c
|
||||||
|
updates["content_access"] = model.NormalizeContentAccess(derived.Access)
|
||||||
|
updates["access_points"] = derived.Points
|
||||||
}
|
}
|
||||||
updates["tags"] = in.Tags
|
updates["tags"] = in.Tags
|
||||||
|
|
||||||
if in.ContentAccess != nil {
|
|
||||||
access := model.NormalizeContentAccess(*in.ContentAccess)
|
|
||||||
updates["content_access"] = access
|
|
||||||
if access == model.ContentAccessPoints {
|
|
||||||
pts := post.AccessPoints
|
|
||||||
if in.AccessPoints != nil {
|
|
||||||
pts = *in.AccessPoints
|
|
||||||
}
|
|
||||||
if pts <= 0 {
|
|
||||||
return nil, errors.New("请设置解锁所需积分")
|
|
||||||
}
|
|
||||||
updates["access_points"] = pts
|
|
||||||
} else {
|
|
||||||
updates["access_points"] = 0
|
|
||||||
}
|
|
||||||
} else if in.AccessPoints != nil && model.NormalizeContentAccess(post.ContentAccess) == model.ContentAccessPoints {
|
|
||||||
if *in.AccessPoints <= 0 {
|
|
||||||
return nil, errors.New("请设置解锁所需积分")
|
|
||||||
}
|
|
||||||
updates["access_points"] = *in.AccessPoints
|
|
||||||
}
|
|
||||||
if in.TypeMeta != nil {
|
if in.TypeMeta != nil {
|
||||||
pt := model.NormalizePostType(post.PostType)
|
pt := model.NormalizePostType(post.PostType)
|
||||||
meta, err := NormalizeAndValidateTypeMeta(pt, *in.TypeMeta)
|
meta, err := NormalizeAndValidateTypeMeta(pt, *in.TypeMeta)
|
||||||
|
|||||||
@@ -1320,9 +1320,137 @@ body {
|
|||||||
color: var(--accent);
|
color: var(--accent);
|
||||||
}
|
}
|
||||||
.j13-md-tool:disabled { opacity: 0.4; }
|
.j13-md-tool:disabled { opacity: 0.4; }
|
||||||
.j13-md-tool:focus-visible {
|
.j13-md-tool.is-active {
|
||||||
|
background: var(--accent-soft);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.j13-md-sep {
|
||||||
|
width: 1px;
|
||||||
|
height: 18px;
|
||||||
|
margin: 0 4px;
|
||||||
|
background: var(--line);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.j13-md-popover-anchor {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
.j13-md-popover {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 6px);
|
||||||
|
left: 0;
|
||||||
|
z-index: 40;
|
||||||
|
min-width: 168px;
|
||||||
|
padding: 6px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
.j13-md-popover-wide {
|
||||||
|
min-width: 200px;
|
||||||
|
max-height: 280px;
|
||||||
|
}
|
||||||
|
.j13-md-popover-form {
|
||||||
|
min-width: 260px;
|
||||||
|
padding: 10px;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.j13-md-popover button[role="menuitem"],
|
||||||
|
.j13-md-menu-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--ink);
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
.j13-md-popover button[role="menuitem"]:hover,
|
||||||
|
.j13-md-menu-item:hover {
|
||||||
|
background: var(--accent-soft);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.j13-md-popover-input {
|
||||||
|
width: 100%;
|
||||||
|
height: 34px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--ink);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.j13-md-popover-input:focus {
|
||||||
outline: 2px solid var(--accent);
|
outline: 2px solid var(--accent);
|
||||||
outline-offset: 1px;
|
outline-offset: 0;
|
||||||
|
}
|
||||||
|
.j13-md-popover-list {
|
||||||
|
max-height: 200px;
|
||||||
|
overflow-y: auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1px;
|
||||||
|
}
|
||||||
|
.j13-md-popover-list button {
|
||||||
|
text-align: left;
|
||||||
|
padding: 7px 10px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-family: var(--font-mono, ui-monospace, monospace);
|
||||||
|
color: var(--ink-2);
|
||||||
|
}
|
||||||
|
.j13-md-popover-list button:hover {
|
||||||
|
background: var(--accent-soft);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.j13-md-field {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--ink-3);
|
||||||
|
}
|
||||||
|
.j13-md-popover-footer {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
.btn-sm {
|
||||||
|
height: 30px;
|
||||||
|
padding: 0 12px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
.j13-md-write-wrap {
|
||||||
|
position: relative;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
.j13-md-write-wrap.is-dragover .j13-md-textarea {
|
||||||
|
opacity: 0.35;
|
||||||
|
}
|
||||||
|
.j13-md-drop-mask {
|
||||||
|
position: absolute;
|
||||||
|
inset: 8px 0;
|
||||||
|
z-index: 5;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 2px dashed var(--accent);
|
||||||
|
background: color-mix(in srgb, var(--accent-soft) 80%, transparent);
|
||||||
|
color: var(--accent);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 14px;
|
||||||
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
.j13-md-mode {
|
.j13-md-mode {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -1394,6 +1522,66 @@ body {
|
|||||||
background: transparent;
|
background: transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 正文内嵌隐藏块 */
|
||||||
|
.j13-hide-block {
|
||||||
|
margin: 1.1rem 0;
|
||||||
|
border-radius: 14px;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent) 22%, var(--line));
|
||||||
|
background: color-mix(in srgb, var(--accent-soft) 55%, var(--panel));
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.j13-hide-block-bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 8px 14px;
|
||||||
|
border-bottom: 1px solid color-mix(in srgb, var(--accent) 14%, var(--line));
|
||||||
|
}
|
||||||
|
.j13-hide-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 22px;
|
||||||
|
padding: 0 9px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 11.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--accent);
|
||||||
|
background: var(--accent-soft);
|
||||||
|
}
|
||||||
|
.j13-hide-block-body {
|
||||||
|
padding: 12px 16px 14px;
|
||||||
|
}
|
||||||
|
.j13-hide-block-body > :first-child { margin-top: 0; }
|
||||||
|
.j13-hide-block-body > :last-child { margin-bottom: 0; }
|
||||||
|
.j13-hide-gate {
|
||||||
|
margin: 1.1rem 0;
|
||||||
|
border-radius: 14px;
|
||||||
|
padding: 1.35rem 1.25rem;
|
||||||
|
text-align: center;
|
||||||
|
background: var(--accent-soft);
|
||||||
|
border: 1px dashed color-mix(in srgb, var(--accent) 35%, transparent);
|
||||||
|
}
|
||||||
|
.j13-hide-gate-icon {
|
||||||
|
margin: 0 auto 0.55rem;
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.j13-hide-gate-title {
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 15px;
|
||||||
|
color: var(--ink);
|
||||||
|
margin-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
.j13-hide-gate-desc {
|
||||||
|
margin-bottom: 0.9rem;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.j13-hide-gate-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
.j13-compose-shell {
|
.j13-compose-shell {
|
||||||
background: var(--panel);
|
background: var(--panel);
|
||||||
border: 1px solid var(--line);
|
border: 1px solid var(--line);
|
||||||
|
|||||||
@@ -9,8 +9,6 @@ type Props = {
|
|||||||
initialContent: string;
|
initialContent: string;
|
||||||
initialTags: string;
|
initialTags: string;
|
||||||
initialPostType?: string;
|
initialPostType?: string;
|
||||||
initialContentAccess?: string;
|
|
||||||
initialAccessPoints?: number;
|
|
||||||
initialTypeMeta?: string;
|
initialTypeMeta?: string;
|
||||||
initialAttachments?: PostAttachment[];
|
initialAttachments?: PostAttachment[];
|
||||||
canEditPollOptions?: boolean;
|
canEditPollOptions?: boolean;
|
||||||
@@ -26,8 +24,6 @@ export default function EditPostClient({
|
|||||||
initialContent,
|
initialContent,
|
||||||
initialTags,
|
initialTags,
|
||||||
initialPostType,
|
initialPostType,
|
||||||
initialContentAccess,
|
|
||||||
initialAccessPoints,
|
|
||||||
initialTypeMeta,
|
initialTypeMeta,
|
||||||
initialAttachments,
|
initialAttachments,
|
||||||
canEditPollOptions,
|
canEditPollOptions,
|
||||||
@@ -44,8 +40,6 @@ export default function EditPostClient({
|
|||||||
initialContent={initialContent}
|
initialContent={initialContent}
|
||||||
initialTags={initialTags}
|
initialTags={initialTags}
|
||||||
initialPostType={initialPostType}
|
initialPostType={initialPostType}
|
||||||
initialContentAccess={initialContentAccess}
|
|
||||||
initialAccessPoints={initialAccessPoints}
|
|
||||||
initialTypeMeta={initialTypeMeta}
|
initialTypeMeta={initialTypeMeta}
|
||||||
initialAttachments={initialAttachments}
|
initialAttachments={initialAttachments}
|
||||||
canEditPollOptions={canEditPollOptions}
|
canEditPollOptions={canEditPollOptions}
|
||||||
|
|||||||
@@ -60,8 +60,6 @@ export default async function EditPostPage({ params }: PageProps) {
|
|||||||
initialContent={post.content}
|
initialContent={post.content}
|
||||||
initialTags={post.tags || ""}
|
initialTags={post.tags || ""}
|
||||||
initialPostType={post.post_type}
|
initialPostType={post.post_type}
|
||||||
initialContentAccess={post.content_access}
|
|
||||||
initialAccessPoints={post.access_points}
|
|
||||||
initialTypeMeta={post.type_meta}
|
initialTypeMeta={post.type_meta}
|
||||||
initialAttachments={post.attachments || []}
|
initialAttachments={post.attachments || []}
|
||||||
canEditPollOptions={post.poll?.can_edit_options !== false}
|
canEditPollOptions={post.poll?.can_edit_options !== false}
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ import MobilePostBar from "@/components/MobilePostBar";
|
|||||||
import Avatar from "@/components/Avatar";
|
import Avatar from "@/components/Avatar";
|
||||||
import RoleBadge from "@/components/RoleBadge";
|
import RoleBadge from "@/components/RoleBadge";
|
||||||
import MarkdownBody from "@/components/MarkdownBody";
|
import MarkdownBody from "@/components/MarkdownBody";
|
||||||
import ContentLockGate from "@/components/ContentLockGate";
|
import { publicMarkdownForSeo } from "@/lib/hideBlocks";
|
||||||
import PostAttachments from "@/components/PostAttachments";
|
import PostAttachments from "@/components/PostAttachments";
|
||||||
import PostInteractPanels, { QuestionStatusCard } from "@/components/PostInteractPanels";
|
import PostInteractPanels, { QuestionStatusCard } from "@/components/PostInteractPanels";
|
||||||
import AcceptedAnswerCard from "@/components/AcceptedAnswerCard";
|
import AcceptedAnswerCard from "@/components/AcceptedAnswerCard";
|
||||||
@@ -60,9 +60,10 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
|
|||||||
robots: { index: false, follow: false },
|
robots: { index: false, follow: false },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const desc = post.content_locked
|
const publicBody = publicMarkdownForSeo(post.content || "");
|
||||||
? post.access_hint || "部分内容需满足条件后可见"
|
const desc = publicBody
|
||||||
: (post.content || "").slice(0, 160);
|
? publicBody.slice(0, 160)
|
||||||
|
: post.access_hint || "部分内容需满足条件后可见";
|
||||||
return {
|
return {
|
||||||
title: post.title,
|
title: post.title,
|
||||||
description: desc,
|
description: desc,
|
||||||
@@ -481,10 +482,11 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
|||||||
const related = (relatedData?.posts ?? []).filter((p) => p.id !== post.id).slice(0, 5);
|
const related = (relatedData?.posts ?? []).filter((p) => p.id !== post.id).slice(0, 5);
|
||||||
const authorPosts = (profile?.posts ?? []).filter((p) => p.id !== post.id).slice(0, 5);
|
const authorPosts = (profile?.posts ?? []).filter((p) => p.id !== post.id).slice(0, 5);
|
||||||
|
|
||||||
const toc = post.content_locked ? [] : extractToc(post.content);
|
const publicBody = publicMarkdownForSeo(post.content || "");
|
||||||
|
const toc = extractToc(publicBody);
|
||||||
const readingMinutes = Math.max(
|
const readingMinutes = Math.max(
|
||||||
1,
|
1,
|
||||||
Math.ceil((post.content_locked ? post.title.length : post.content.length) / 400)
|
Math.ceil((publicBody.length > 0 ? publicBody.length : post.title.length) / 400)
|
||||||
);
|
);
|
||||||
const edited =
|
const edited =
|
||||||
new Date(post.updated_at).getTime() - new Date(post.created_at).getTime() > 60_000;
|
new Date(post.updated_at).getTime() - new Date(post.created_at).getTime() > 60_000;
|
||||||
@@ -527,8 +529,8 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
|||||||
"@context": "https://schema.org",
|
"@context": "https://schema.org",
|
||||||
"@type": "DiscussionForumPosting",
|
"@type": "DiscussionForumPosting",
|
||||||
headline: post.title,
|
headline: post.title,
|
||||||
// 锁定正文不进 JSON-LD,避免 SEO 泄露付费/回复可见内容
|
// 仅公开片段进 JSON-LD,避免 SEO 泄露隐藏块原文
|
||||||
articleBody: post.content_locked ? undefined : post.content,
|
articleBody: publicBody || undefined,
|
||||||
datePublished: post.created_at,
|
datePublished: post.created_at,
|
||||||
dateModified: post.updated_at,
|
dateModified: post.updated_at,
|
||||||
author: { "@type": "Person", name: post.user.nickname },
|
author: { "@type": "Person", name: post.user.nickname },
|
||||||
@@ -541,7 +543,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
|||||||
...(allowComments &&
|
...(allowComments &&
|
||||||
acceptedAnswer &&
|
acceptedAnswer &&
|
||||||
!acceptedAnswer.deleted &&
|
!acceptedAnswer.deleted &&
|
||||||
!post.content_locked && {
|
!!publicBody && {
|
||||||
acceptedAnswer: {
|
acceptedAnswer: {
|
||||||
"@type": "Comment",
|
"@type": "Comment",
|
||||||
text: acceptedAnswer.content,
|
text: acceptedAnswer.content,
|
||||||
@@ -718,24 +720,14 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{post.content_locked ? (
|
|
||||||
<ContentLockGate
|
|
||||||
postId={post.id}
|
|
||||||
hint={post.access_hint}
|
|
||||||
access={post.content_access}
|
|
||||||
points={post.access_points}
|
|
||||||
loggedIn={!!me.user}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<MarkdownBody
|
<MarkdownBody
|
||||||
content={post.content}
|
content={post.content}
|
||||||
|
postId={post.id}
|
||||||
|
loggedIn={!!me.user}
|
||||||
components={{ h2: headingRenderer("h2"), h3: headingRenderer("h3") }}
|
components={{ h2: headingRenderer("h2"), h3: headingRenderer("h3") }}
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
|
|
||||||
{!post.content_locked && (
|
|
||||||
<PostAttachments postId={post.id} items={post.attachments || []} />
|
<PostAttachments postId={post.id} items={post.attachments || []} />
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 类型特殊块(投票/悬赏/抽奖/问答)统一放正文最下方 */}
|
{/* 类型特殊块(投票/悬赏/抽奖/问答)统一放正文最下方 */}
|
||||||
<PostInteractPanels
|
<PostInteractPanels
|
||||||
@@ -745,7 +737,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
|||||||
lottery={post.lottery}
|
lottery={post.lottery}
|
||||||
loggedIn={!!me.user}
|
loggedIn={!!me.user}
|
||||||
/>
|
/>
|
||||||
{!post.content_locked && allowComments && acceptedAnswer ? (
|
{allowComments && acceptedAnswer ? (
|
||||||
<AcceptedAnswerCard
|
<AcceptedAnswerCard
|
||||||
answer={acceptedAnswer}
|
answer={acceptedAnswer}
|
||||||
variant={acceptedAnswerVariant}
|
variant={acceptedAnswerVariant}
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { Lock } from "lucide-react";
|
|
||||||
import { apiUnlockPost } from "@/lib/api";
|
|
||||||
import { toast } from "@/lib/toast";
|
|
||||||
|
|
||||||
export default function ContentLockGate({
|
|
||||||
postId,
|
|
||||||
hint,
|
|
||||||
access,
|
|
||||||
points,
|
|
||||||
loggedIn,
|
|
||||||
}: {
|
|
||||||
postId: number;
|
|
||||||
hint?: string;
|
|
||||||
access?: string;
|
|
||||||
points?: number;
|
|
||||||
loggedIn: boolean;
|
|
||||||
}) {
|
|
||||||
const router = useRouter();
|
|
||||||
const [busy, setBusy] = useState(false);
|
|
||||||
|
|
||||||
const unlock = async () => {
|
|
||||||
setBusy(true);
|
|
||||||
try {
|
|
||||||
const res = await apiUnlockPost(String(postId));
|
|
||||||
if (res.post) {
|
|
||||||
toast("已解锁全文", "ok");
|
|
||||||
router.refresh();
|
|
||||||
} else {
|
|
||||||
toast(res.error || "解锁失败", "error");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
toast("解锁失败", "error");
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className="rounded-[14px] px-6 py-10 text-center my-4"
|
|
||||||
style={{
|
|
||||||
background: "var(--accent-soft)",
|
|
||||||
border: "1px solid color-mix(in srgb, var(--accent) 20%, transparent)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Lock size={28} className="mx-auto mb-3" style={{ color: "var(--accent)" }} />
|
|
||||||
<p className="font-bold text-[16px] mb-1" style={{ color: "var(--ink)" }}>
|
|
||||||
{hint || "正文暂不可见"}
|
|
||||||
</p>
|
|
||||||
<p className="meta text-[13px] mb-5">
|
|
||||||
{access === "points"
|
|
||||||
? `支付 ${points || 0} 积分后可阅读全文`
|
|
||||||
: access === "reply"
|
|
||||||
? "发表一条回复后即可阅读全文"
|
|
||||||
: access === "login"
|
|
||||||
? "登录后即可阅读全文"
|
|
||||||
: null}
|
|
||||||
</p>
|
|
||||||
{access === "login" && !loggedIn && (
|
|
||||||
<Link
|
|
||||||
href={`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`}
|
|
||||||
className="btn btn-primary"
|
|
||||||
>
|
|
||||||
去登录
|
|
||||||
</Link>
|
|
||||||
)}
|
|
||||||
{access === "points" && loggedIn && (
|
|
||||||
<button type="button" className="btn btn-primary" disabled={busy} onClick={() => void unlock()}>
|
|
||||||
{busy ? "解锁中…" : `支付 ${points || 0} 积分解锁`}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{access === "points" && !loggedIn && (
|
|
||||||
<Link
|
|
||||||
href={`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`}
|
|
||||||
className="btn btn-primary"
|
|
||||||
>
|
|
||||||
登录后解锁
|
|
||||||
</Link>
|
|
||||||
)}
|
|
||||||
{access === "reply" && (
|
|
||||||
<a href="#comments" className="btn btn-primary">
|
|
||||||
去回复
|
|
||||||
</a>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,61 @@
|
|||||||
import type { Components } from "react-markdown";
|
import type { Components } from "react-markdown";
|
||||||
import { renderMarkdownToReact } from "@/components/markdown/renderMarkdown";
|
import { renderMarkdownToReact } from "@/components/markdown/renderMarkdown";
|
||||||
|
import { splitHideSegments, type HideKind } from "@/lib/hideBlocks";
|
||||||
|
import MdHideBlock from "@/components/markdown/MdHideBlock";
|
||||||
|
|
||||||
type MarkdownBodyProps = {
|
type MarkdownBodyProps = {
|
||||||
content: string;
|
content: string;
|
||||||
className?: string;
|
className?: string;
|
||||||
components?: Components;
|
components?: Components;
|
||||||
|
/** 详情页解锁门禁需要 */
|
||||||
|
postId?: number;
|
||||||
|
loggedIn?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 站点统一 Markdown 渲染(服务端):GFM + Shiki 双主题、图箱、代码块复制/折叠。
|
* 站点统一 Markdown 渲染(服务端):GFM + Shiki;支持 :::hide 内嵌块。
|
||||||
* 客户端预览请用 MarkdownBodyClient。
|
|
||||||
*/
|
*/
|
||||||
export default async function MarkdownBody({
|
export default async function MarkdownBody({
|
||||||
content,
|
content,
|
||||||
className = "prose-content",
|
className = "prose-content",
|
||||||
components,
|
components,
|
||||||
|
postId,
|
||||||
|
loggedIn = false,
|
||||||
}: MarkdownBodyProps) {
|
}: MarkdownBodyProps) {
|
||||||
const tree = await renderMarkdownToReact(content, components);
|
const segs = splitHideSegments(content || "");
|
||||||
return <div className={className}>{tree}</div>;
|
const nodes = [];
|
||||||
|
for (let i = 0; i < segs.length; i++) {
|
||||||
|
const seg = segs[i];
|
||||||
|
if (seg.type === "md") {
|
||||||
|
if (!seg.text.trim()) continue;
|
||||||
|
nodes.push(
|
||||||
|
<div key={`md-${i}`}>{await renderMarkdownToReact(seg.text, components)}</div>
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kind = seg.kind as HideKind;
|
||||||
|
if (seg.locked) {
|
||||||
|
nodes.push(
|
||||||
|
<MdHideBlock
|
||||||
|
key={`hide-${i}`}
|
||||||
|
kind={kind}
|
||||||
|
points={seg.points}
|
||||||
|
locked
|
||||||
|
postId={postId}
|
||||||
|
loggedIn={loggedIn}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const inner = seg.body.trim()
|
||||||
|
? await renderMarkdownToReact(seg.body, components)
|
||||||
|
: null;
|
||||||
|
nodes.push(
|
||||||
|
<MdHideBlock key={`hide-${i}`} kind={kind} points={seg.points}>
|
||||||
|
{inner}
|
||||||
|
</MdHideBlock>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className={className}>{nodes}</div>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,30 +3,64 @@
|
|||||||
import ReactMarkdown, { type Components } from "react-markdown";
|
import ReactMarkdown, { type Components } from "react-markdown";
|
||||||
import remarkGfm from "remark-gfm";
|
import remarkGfm from "remark-gfm";
|
||||||
import { mergeMarkdownComponents } from "@/components/markdown/mergeComponents";
|
import { mergeMarkdownComponents } from "@/components/markdown/mergeComponents";
|
||||||
|
import { splitHideSegments, type HideKind } from "@/lib/hideBlocks";
|
||||||
|
import MdHideBlock from "@/components/markdown/MdHideBlock";
|
||||||
|
|
||||||
type MarkdownBodyClientProps = {
|
type MarkdownBodyClientProps = {
|
||||||
content: string;
|
content: string;
|
||||||
className?: string;
|
className?: string;
|
||||||
components?: Components;
|
components?: Components;
|
||||||
|
postId?: number;
|
||||||
|
loggedIn?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 客户端 Markdown(发帖预览 / 评论):GFM + 图箱 / 代码折叠复制。
|
* 客户端 Markdown(发帖预览 / 评论):GFM + 隐藏块徽章预览。
|
||||||
* 语法高亮在 MdCodeBlock 内按需用 Shiki 补齐。
|
|
||||||
*/
|
*/
|
||||||
export default function MarkdownBodyClient({
|
export default function MarkdownBodyClient({
|
||||||
content,
|
content,
|
||||||
className = "prose-content",
|
className = "prose-content",
|
||||||
components,
|
components,
|
||||||
|
postId,
|
||||||
|
loggedIn = false,
|
||||||
}: MarkdownBodyClientProps) {
|
}: MarkdownBodyClientProps) {
|
||||||
|
const segs = splitHideSegments(content || "");
|
||||||
|
const mdComponents = mergeMarkdownComponents(components);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={className}>
|
<div className={className}>
|
||||||
<ReactMarkdown
|
{segs.map((seg, i) => {
|
||||||
remarkPlugins={[remarkGfm]}
|
if (seg.type === "md") {
|
||||||
components={mergeMarkdownComponents(components)}
|
if (!seg.text.trim()) return null;
|
||||||
>
|
return (
|
||||||
{content || ""}
|
<ReactMarkdown key={`md-${i}`} remarkPlugins={[remarkGfm]} components={mdComponents}>
|
||||||
|
{seg.text}
|
||||||
</ReactMarkdown>
|
</ReactMarkdown>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const kind = seg.kind as HideKind;
|
||||||
|
if (seg.locked) {
|
||||||
|
return (
|
||||||
|
<MdHideBlock
|
||||||
|
key={`hide-${i}`}
|
||||||
|
kind={kind}
|
||||||
|
points={seg.points}
|
||||||
|
locked
|
||||||
|
postId={postId}
|
||||||
|
loggedIn={loggedIn}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<MdHideBlock key={`hide-${i}`} kind={kind} points={seg.points}>
|
||||||
|
{seg.body.trim() ? (
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]} components={mdComponents}>
|
||||||
|
{seg.body}
|
||||||
|
</ReactMarkdown>
|
||||||
|
) : null}
|
||||||
|
</MdHideBlock>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,41 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRef, useState, useCallback, useEffect, type ReactNode } from "react";
|
import {
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
useCallback,
|
||||||
|
useEffect,
|
||||||
|
type ReactNode,
|
||||||
|
type KeyboardEvent as ReactKeyboardEvent,
|
||||||
|
} from "react";
|
||||||
import {
|
import {
|
||||||
Bold,
|
Bold,
|
||||||
Italic,
|
Italic,
|
||||||
|
Strikethrough,
|
||||||
Code,
|
Code,
|
||||||
|
Code2,
|
||||||
Quote,
|
Quote,
|
||||||
List,
|
List,
|
||||||
|
ListOrdered,
|
||||||
Heading2,
|
Heading2,
|
||||||
|
Heading3,
|
||||||
Link as LinkIcon,
|
Link as LinkIcon,
|
||||||
Image as ImageIcon,
|
Image as ImageIcon,
|
||||||
|
Table,
|
||||||
|
Minus,
|
||||||
Eye,
|
Eye,
|
||||||
Pencil,
|
Pencil,
|
||||||
Maximize2,
|
Maximize2,
|
||||||
Minimize2,
|
Minimize2,
|
||||||
|
Lock,
|
||||||
|
ChevronDown,
|
||||||
|
Upload,
|
||||||
|
Link2,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { apiUploadPostImage } from "@/lib/api";
|
import { apiUploadPostImage } from "@/lib/api";
|
||||||
import { toast } from "@/lib/toast";
|
import { toast } from "@/lib/toast";
|
||||||
import MarkdownBodyClient from "@/components/MarkdownBodyClient";
|
import MarkdownBodyClient from "@/components/MarkdownBodyClient";
|
||||||
|
import { SHIKI_LANG_IDS } from "@/components/markdown/shikiHighlighter";
|
||||||
|
|
||||||
type MarkdownEditorProps = {
|
type MarkdownEditorProps = {
|
||||||
value: string;
|
value: string;
|
||||||
@@ -36,6 +54,10 @@ type WrapOpts = {
|
|||||||
linePrefix?: string;
|
linePrefix?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type PopoverKind = "link" | "imageUrl" | "code" | "hide" | "heading" | "image" | null;
|
||||||
|
|
||||||
|
const CODE_LANGS = ["plaintext", "aardio", ...SHIKI_LANG_IDS.filter((l) => l !== "plaintext")] as const;
|
||||||
|
|
||||||
function applyWrap(
|
function applyWrap(
|
||||||
el: HTMLTextAreaElement,
|
el: HTMLTextAreaElement,
|
||||||
value: string,
|
value: string,
|
||||||
@@ -53,11 +75,7 @@ function applyWrap(
|
|||||||
);
|
);
|
||||||
const inserted = lines.join("\n");
|
const inserted = lines.join("\n");
|
||||||
const next = value.slice(0, start) + inserted + value.slice(end);
|
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||||
return {
|
return { next, selStart: start, selEnd: start + inserted.length };
|
||||||
next,
|
|
||||||
selStart: start,
|
|
||||||
selEnd: start + inserted.length,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const inner = selected || opts.placeholder || "";
|
const inner = selected || opts.placeholder || "";
|
||||||
@@ -68,6 +86,15 @@ function applyWrap(
|
|||||||
return { next, selStart, selEnd };
|
return { next, selStart, selEnd };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isHttpUrl(raw: string): boolean {
|
||||||
|
try {
|
||||||
|
const u = new URL(raw.trim());
|
||||||
|
return u.protocol === "http:" || u.protocol === "https:";
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default function MarkdownEditor({
|
export default function MarkdownEditor({
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
@@ -79,16 +106,28 @@ export default function MarkdownEditor({
|
|||||||
}: MarkdownEditorProps) {
|
}: MarkdownEditorProps) {
|
||||||
const taRef = useRef<HTMLTextAreaElement>(null);
|
const taRef = useRef<HTMLTextAreaElement>(null);
|
||||||
const fileRef = useRef<HTMLInputElement>(null);
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
|
const toolbarRef = useRef<HTMLDivElement>(null);
|
||||||
const [mode, setMode] = useState<"write" | "preview">("write");
|
const [mode, setMode] = useState<"write" | "preview">("write");
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
const [fullscreen, setFullscreen] = useState(false);
|
const [fullscreen, setFullscreen] = useState(false);
|
||||||
|
const [dragOver, setDragOver] = useState(false);
|
||||||
|
const [popover, setPopover] = useState<PopoverKind>(null);
|
||||||
|
const [linkText, setLinkText] = useState("");
|
||||||
|
const [linkUrl, setLinkUrl] = useState("https://");
|
||||||
|
const [imageUrl, setImageUrl] = useState("https://");
|
||||||
|
const [imageAlt, setImageAlt] = useState("图片");
|
||||||
|
const [codeQuery, setCodeQuery] = useState("");
|
||||||
|
const [hidePoints, setHidePoints] = useState(10);
|
||||||
|
const [hideStep, setHideStep] = useState<"menu" | "points">("menu");
|
||||||
|
const savedSel = useRef<{ start: number; end: number } | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!fullscreen) return;
|
if (!fullscreen) return;
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
if (e.key === "Escape") {
|
if (e.key === "Escape") {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setFullscreen(false);
|
if (popover) setPopover(null);
|
||||||
|
else setFullscreen(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const prev = document.body.style.overflow;
|
const prev = document.body.style.overflow;
|
||||||
@@ -98,7 +137,40 @@ export default function MarkdownEditor({
|
|||||||
document.body.style.overflow = prev;
|
document.body.style.overflow = prev;
|
||||||
window.removeEventListener("keydown", onKey);
|
window.removeEventListener("keydown", onKey);
|
||||||
};
|
};
|
||||||
}, [fullscreen]);
|
}, [fullscreen, popover]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!popover) return;
|
||||||
|
const onDoc = (e: MouseEvent) => {
|
||||||
|
const t = e.target as Node;
|
||||||
|
if (toolbarRef.current && !toolbarRef.current.contains(t)) {
|
||||||
|
setPopover(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onEsc = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === "Escape") setPopover(null);
|
||||||
|
};
|
||||||
|
document.addEventListener("mousedown", onDoc);
|
||||||
|
document.addEventListener("keydown", onEsc);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("mousedown", onDoc);
|
||||||
|
document.removeEventListener("keydown", onEsc);
|
||||||
|
};
|
||||||
|
}, [popover]);
|
||||||
|
|
||||||
|
const rememberSel = () => {
|
||||||
|
const el = taRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
savedSel.current = { start: el.selectionStart, end: el.selectionEnd };
|
||||||
|
};
|
||||||
|
|
||||||
|
const restoreSel = () => {
|
||||||
|
const el = taRef.current;
|
||||||
|
const sel = savedSel.current;
|
||||||
|
if (!el || !sel) return;
|
||||||
|
el.focus();
|
||||||
|
el.setSelectionRange(sel.start, sel.end);
|
||||||
|
};
|
||||||
|
|
||||||
const runWrap = useCallback(
|
const runWrap = useCallback(
|
||||||
(opts: WrapOpts) => {
|
(opts: WrapOpts) => {
|
||||||
@@ -115,29 +187,35 @@ export default function MarkdownEditor({
|
|||||||
);
|
);
|
||||||
|
|
||||||
const insertAtCursor = useCallback(
|
const insertAtCursor = useCallback(
|
||||||
(text: string) => {
|
(text: string, selectInner?: { offset: number; length: number }) => {
|
||||||
const el = taRef.current;
|
const el = taRef.current;
|
||||||
if (!el) {
|
if (!el) {
|
||||||
onChange(value + (value.endsWith("\n") || !value ? "" : "\n") + text);
|
onChange(value + (value.endsWith("\n") || !value ? "" : "\n") + text);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const start = el.selectionStart;
|
const start = savedSel.current?.start ?? el.selectionStart;
|
||||||
const end = el.selectionEnd;
|
const end = savedSel.current?.end ?? el.selectionEnd;
|
||||||
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
|
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
|
||||||
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
|
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
|
||||||
const inserted = padBefore + text + padAfter;
|
const inserted = padBefore + text + padAfter;
|
||||||
const next = value.slice(0, start) + inserted + value.slice(end);
|
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||||
onChange(next);
|
onChange(next);
|
||||||
const caret = start + inserted.length;
|
|
||||||
requestAnimationFrame(() => {
|
requestAnimationFrame(() => {
|
||||||
el.focus();
|
el.focus();
|
||||||
|
if (selectInner) {
|
||||||
|
const a = start + padBefore.length + selectInner.offset;
|
||||||
|
el.setSelectionRange(a, a + selectInner.length);
|
||||||
|
} else {
|
||||||
|
const caret = start + inserted.length;
|
||||||
el.setSelectionRange(caret, caret);
|
el.setSelectionRange(caret, caret);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
savedSel.current = null;
|
||||||
},
|
},
|
||||||
[value, onChange]
|
[value, onChange]
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleImagePick = async (file: File | null) => {
|
const uploadImageFile = async (file: File | null) => {
|
||||||
if (!file || disabled) return;
|
if (!file || disabled) return;
|
||||||
if (!/^image\/(jpeg|png|webp)$/i.test(file.type)) {
|
if (!/^image\/(jpeg|png|webp)$/i.test(file.type)) {
|
||||||
toast("仅支持 JPEG / PNG / WebP", "error");
|
toast("仅支持 JPEG / PNG / WebP", "error");
|
||||||
@@ -166,82 +244,536 @@ export default function MarkdownEditor({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const tools: {
|
const openPopover = (kind: PopoverKind) => {
|
||||||
key: string;
|
rememberSel();
|
||||||
|
if (kind === "link") {
|
||||||
|
const el = taRef.current;
|
||||||
|
const selected = el ? value.slice(el.selectionStart, el.selectionEnd) : "";
|
||||||
|
setLinkText(selected || "链接文字");
|
||||||
|
setLinkUrl("https://");
|
||||||
|
}
|
||||||
|
if (kind === "imageUrl") {
|
||||||
|
setImageUrl("https://");
|
||||||
|
setImageAlt("图片");
|
||||||
|
}
|
||||||
|
if (kind === "code") setCodeQuery("");
|
||||||
|
if (kind === "hide") {
|
||||||
|
setHideStep("menu");
|
||||||
|
setHidePoints(10);
|
||||||
|
}
|
||||||
|
setPopover((prev) => (prev === kind ? null : kind));
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyLink = () => {
|
||||||
|
const url = linkUrl.trim();
|
||||||
|
if (!isHttpUrl(url)) {
|
||||||
|
toast("请输入有效的 http(s) 链接", "error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const el = taRef.current;
|
||||||
|
restoreSel();
|
||||||
|
const start = el?.selectionStart ?? 0;
|
||||||
|
const end = el?.selectionEnd ?? 0;
|
||||||
|
const selected = value.slice(start, end);
|
||||||
|
const label = (selected || linkText.trim() || url).trim() || url;
|
||||||
|
const md = `[${label}](${url})`;
|
||||||
|
const next = value.slice(0, start) + md + value.slice(end);
|
||||||
|
onChange(next);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
if (!el) return;
|
||||||
|
el.focus();
|
||||||
|
el.setSelectionRange(start + md.length, start + md.length);
|
||||||
|
});
|
||||||
|
setPopover(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyImageUrl = () => {
|
||||||
|
const url = imageUrl.trim();
|
||||||
|
if (!isHttpUrl(url)) {
|
||||||
|
toast("请输入有效的图片 URL(http/https)", "error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const alt = imageAlt.trim() || "图片";
|
||||||
|
insertAtCursor(``);
|
||||||
|
setPopover(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const insertCodeBlock = (lang: string) => {
|
||||||
|
const el = taRef.current;
|
||||||
|
restoreSel();
|
||||||
|
const start = el?.selectionStart ?? 0;
|
||||||
|
const end = el?.selectionEnd ?? 0;
|
||||||
|
const selected = value.slice(start, end);
|
||||||
|
const body = selected || "代码";
|
||||||
|
const fence = "```" + lang + "\n" + body + "\n```";
|
||||||
|
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
|
||||||
|
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
|
||||||
|
const inserted = padBefore + fence + padAfter;
|
||||||
|
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||||
|
onChange(next);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
if (!el) return;
|
||||||
|
el.focus();
|
||||||
|
const bodyStart = start + padBefore.length + 3 + lang.length + 1;
|
||||||
|
el.setSelectionRange(bodyStart, bodyStart + body.length);
|
||||||
|
});
|
||||||
|
setPopover(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const insertHide = (kind: "login" | "reply" | "points", points?: number) => {
|
||||||
|
restoreSel();
|
||||||
|
const el = taRef.current;
|
||||||
|
const start = el?.selectionStart ?? 0;
|
||||||
|
const end = el?.selectionEnd ?? 0;
|
||||||
|
const selected = value.slice(start, end);
|
||||||
|
const body = selected || "在此填写隐藏内容";
|
||||||
|
const open =
|
||||||
|
kind === "points"
|
||||||
|
? `:::hide points ${points || 10}`
|
||||||
|
: `:::hide ${kind}`;
|
||||||
|
const block = `${open}\n${body}\n:::`;
|
||||||
|
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
|
||||||
|
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
|
||||||
|
const inserted = padBefore + block + padAfter;
|
||||||
|
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||||
|
onChange(next);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
if (!el) return;
|
||||||
|
el.focus();
|
||||||
|
const bodyStart = start + padBefore.length + open.length + 1;
|
||||||
|
el.setSelectionRange(bodyStart, bodyStart + body.length);
|
||||||
|
});
|
||||||
|
setPopover(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const insertOrderedList = () => {
|
||||||
|
const el = taRef.current;
|
||||||
|
if (!el || disabled) return;
|
||||||
|
const start = el.selectionStart;
|
||||||
|
const end = el.selectionEnd;
|
||||||
|
const selected = value.slice(start, end) || "列表项";
|
||||||
|
const lines = selected.split("\n").map((l, i) => {
|
||||||
|
if (/^\d+\.\s/.test(l)) return l;
|
||||||
|
return `${i + 1}. ${l}`;
|
||||||
|
});
|
||||||
|
const inserted = lines.join("\n");
|
||||||
|
const next = value.slice(0, start) + inserted + value.slice(end);
|
||||||
|
onChange(next);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
el.focus();
|
||||||
|
el.setSelectionRange(start, start + inserted.length);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const insertTable = () => {
|
||||||
|
insertAtCursor(
|
||||||
|
"| 列1 | 列2 | 列3 |\n| --- | --- | --- |\n| | | |\n| | | |"
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onTextareaKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
onSubmitShortcut?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === "b") {
|
||||||
|
e.preventDefault();
|
||||||
|
runWrap({ before: "**", after: "**", placeholder: "粗体" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === "i") {
|
||||||
|
e.preventDefault();
|
||||||
|
runWrap({ before: "*", after: "*", placeholder: "斜体" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === "k") {
|
||||||
|
e.preventDefault();
|
||||||
|
openPopover("link");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === "c") {
|
||||||
|
e.preventDefault();
|
||||||
|
openPopover("code");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onPaste = async (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
|
||||||
|
const items = e.clipboardData?.items;
|
||||||
|
if (items) {
|
||||||
|
for (const item of items) {
|
||||||
|
if (item.type.startsWith("image/")) {
|
||||||
|
e.preventDefault();
|
||||||
|
const file = item.getAsFile();
|
||||||
|
await uploadImageFile(file);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const text = e.clipboardData?.getData("text/plain")?.trim() || "";
|
||||||
|
if (text && isHttpUrl(text)) {
|
||||||
|
const el = taRef.current;
|
||||||
|
if (el && el.selectionStart !== el.selectionEnd) {
|
||||||
|
e.preventDefault();
|
||||||
|
const start = el.selectionStart;
|
||||||
|
const end = el.selectionEnd;
|
||||||
|
const selected = value.slice(start, end);
|
||||||
|
const md = `[${selected}](${text})`;
|
||||||
|
const next = value.slice(0, start) + md + value.slice(end);
|
||||||
|
onChange(next);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
el.focus();
|
||||||
|
el.setSelectionRange(start + md.length, start + md.length);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const filteredLangs = CODE_LANGS.filter((l) =>
|
||||||
|
l.toLowerCase().includes(codeQuery.trim().toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
const ToolBtn = ({
|
||||||
|
label,
|
||||||
|
icon,
|
||||||
|
onClick,
|
||||||
|
active,
|
||||||
|
disabled: dis,
|
||||||
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
icon: ReactNode;
|
icon: ReactNode;
|
||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
}[] = [
|
active?: boolean;
|
||||||
{
|
disabled?: boolean;
|
||||||
key: "bold",
|
}) => (
|
||||||
label: "粗体",
|
<button
|
||||||
icon: <Bold size={15} />,
|
type="button"
|
||||||
onClick: () => runWrap({ before: "**", after: "**", placeholder: "粗体" }),
|
className={`j13-md-tool${active ? " is-active" : ""}`}
|
||||||
},
|
data-tip={label}
|
||||||
{
|
aria-label={label}
|
||||||
key: "italic",
|
disabled={disabled || dis}
|
||||||
label: "斜体",
|
onClick={onClick}
|
||||||
icon: <Italic size={15} />,
|
>
|
||||||
onClick: () => runWrap({ before: "*", after: "*", placeholder: "斜体" }),
|
{icon}
|
||||||
},
|
</button>
|
||||||
{
|
);
|
||||||
key: "code",
|
|
||||||
label: "行内代码",
|
const Sep = () => <span className="j13-md-sep" aria-hidden />;
|
||||||
icon: <Code size={15} />,
|
|
||||||
onClick: () => runWrap({ before: "`", after: "`", placeholder: "code" }),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "quote",
|
|
||||||
label: "引用",
|
|
||||||
icon: <Quote size={15} />,
|
|
||||||
onClick: () =>
|
|
||||||
runWrap({ before: "", linePrefix: "> ", placeholder: "引用内容" }),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "list",
|
|
||||||
label: "列表",
|
|
||||||
icon: <List size={15} />,
|
|
||||||
onClick: () =>
|
|
||||||
runWrap({ before: "", linePrefix: "- ", placeholder: "列表项" }),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "h2",
|
|
||||||
label: "二级标题",
|
|
||||||
icon: <Heading2 size={15} />,
|
|
||||||
onClick: () => runWrap({ before: "## ", after: "", placeholder: "标题" }),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "link",
|
|
||||||
label: "链接",
|
|
||||||
icon: <LinkIcon size={15} />,
|
|
||||||
onClick: () =>
|
|
||||||
runWrap({ before: "[", after: "](https://)", placeholder: "链接文字" }),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "image",
|
|
||||||
label: uploading ? "上传中…" : "插入图片",
|
|
||||||
icon: <ImageIcon size={15} />,
|
|
||||||
onClick: () => fileRef.current?.click(),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`j13-md-editor${fullscreen ? " is-fullscreen" : ""}`}>
|
<div className={`j13-md-editor${fullscreen ? " is-fullscreen" : ""}`}>
|
||||||
<div className="j13-md-toolbar">
|
<div className="j13-md-toolbar" ref={toolbarRef}>
|
||||||
<div className="flex items-center gap-0.5 flex-1 flex-wrap min-w-0">
|
<div className="j13-md-tool-groups flex items-center gap-0.5 flex-1 flex-wrap min-w-0">
|
||||||
{tools.map((t) => (
|
<ToolBtn
|
||||||
|
label="粗体 Ctrl+B"
|
||||||
|
icon={<Bold size={15} />}
|
||||||
|
onClick={() => runWrap({ before: "**", after: "**", placeholder: "粗体" })}
|
||||||
|
/>
|
||||||
|
<ToolBtn
|
||||||
|
label="斜体 Ctrl+I"
|
||||||
|
icon={<Italic size={15} />}
|
||||||
|
onClick={() => runWrap({ before: "*", after: "*", placeholder: "斜体" })}
|
||||||
|
/>
|
||||||
|
<ToolBtn
|
||||||
|
label="删除线"
|
||||||
|
icon={<Strikethrough size={15} />}
|
||||||
|
onClick={() => runWrap({ before: "~~", after: "~~", placeholder: "删除线" })}
|
||||||
|
/>
|
||||||
|
<Sep />
|
||||||
|
<div className="j13-md-popover-anchor relative">
|
||||||
|
<ToolBtn
|
||||||
|
label="标题"
|
||||||
|
icon={
|
||||||
|
<span className="inline-flex items-center gap-0.5">
|
||||||
|
<Heading2 size={15} />
|
||||||
|
<ChevronDown size={11} />
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
active={popover === "heading"}
|
||||||
|
onClick={() => openPopover("heading")}
|
||||||
|
/>
|
||||||
|
{popover === "heading" && (
|
||||||
|
<div className="j13-md-popover" role="menu">
|
||||||
<button
|
<button
|
||||||
key={t.key}
|
|
||||||
type="button"
|
type="button"
|
||||||
className="j13-md-tool"
|
role="menuitem"
|
||||||
data-tip={t.label}
|
onClick={() => {
|
||||||
aria-label={t.label}
|
runWrap({ before: "## ", after: "", placeholder: "二级标题" });
|
||||||
disabled={disabled || (t.key === "image" && uploading)}
|
setPopover(null);
|
||||||
onClick={t.onClick}
|
}}
|
||||||
>
|
>
|
||||||
{t.icon}
|
<Heading2 size={14} /> 二级标题
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
onClick={() => {
|
||||||
|
runWrap({ before: "### ", after: "", placeholder: "三级标题" });
|
||||||
|
setPopover(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Heading3 size={14} /> 三级标题
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Sep />
|
||||||
|
<ToolBtn
|
||||||
|
label="引用"
|
||||||
|
icon={<Quote size={15} />}
|
||||||
|
onClick={() =>
|
||||||
|
runWrap({ before: "", linePrefix: "> ", placeholder: "引用内容" })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<ToolBtn
|
||||||
|
label="无序列表"
|
||||||
|
icon={<List size={15} />}
|
||||||
|
onClick={() =>
|
||||||
|
runWrap({ before: "", linePrefix: "- ", placeholder: "列表项" })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<ToolBtn
|
||||||
|
label="有序列表"
|
||||||
|
icon={<ListOrdered size={15} />}
|
||||||
|
onClick={insertOrderedList}
|
||||||
|
/>
|
||||||
|
<ToolBtn label="表格" icon={<Table size={15} />} onClick={insertTable} />
|
||||||
|
<ToolBtn
|
||||||
|
label="分割线"
|
||||||
|
icon={<Minus size={15} />}
|
||||||
|
onClick={() => insertAtCursor("---")}
|
||||||
|
/>
|
||||||
|
<Sep />
|
||||||
|
<ToolBtn
|
||||||
|
label="行内代码"
|
||||||
|
icon={<Code size={15} />}
|
||||||
|
onClick={() => runWrap({ before: "`", after: "`", placeholder: "code" })}
|
||||||
|
/>
|
||||||
|
<div className="j13-md-popover-anchor relative">
|
||||||
|
<ToolBtn
|
||||||
|
label="代码块 Ctrl+Shift+C"
|
||||||
|
icon={<Code2 size={15} />}
|
||||||
|
active={popover === "code"}
|
||||||
|
onClick={() => openPopover("code")}
|
||||||
|
/>
|
||||||
|
{popover === "code" && (
|
||||||
|
<div className="j13-md-popover j13-md-popover-wide" role="dialog" aria-label="选择语言">
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
className="j13-md-popover-input"
|
||||||
|
placeholder="搜索语言…"
|
||||||
|
value={codeQuery}
|
||||||
|
onChange={(e) => setCodeQuery(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter" && filteredLangs[0]) {
|
||||||
|
e.preventDefault();
|
||||||
|
insertCodeBlock(filteredLangs[0]);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<div className="j13-md-popover-list">
|
||||||
|
{filteredLangs.map((lang) => (
|
||||||
|
<button
|
||||||
|
key={lang}
|
||||||
|
type="button"
|
||||||
|
onClick={() => insertCodeBlock(lang)}
|
||||||
|
>
|
||||||
|
{lang}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
|
{filteredLangs.length === 0 && (
|
||||||
|
<p className="meta px-2 py-3 text-center">无匹配语言</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Sep />
|
||||||
|
<div className="j13-md-popover-anchor relative">
|
||||||
|
<ToolBtn
|
||||||
|
label="链接 Ctrl+K"
|
||||||
|
icon={<LinkIcon size={15} />}
|
||||||
|
active={popover === "link"}
|
||||||
|
onClick={() => openPopover("link")}
|
||||||
|
/>
|
||||||
|
{popover === "link" && (
|
||||||
|
<div className="j13-md-popover j13-md-popover-form" role="dialog" aria-label="插入链接">
|
||||||
|
<label className="j13-md-field">
|
||||||
|
<span>文字</span>
|
||||||
|
<input
|
||||||
|
value={linkText}
|
||||||
|
onChange={(e) => setLinkText(e.target.value)}
|
||||||
|
className="j13-md-popover-input"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="j13-md-field">
|
||||||
|
<span>URL</span>
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
value={linkUrl}
|
||||||
|
onChange={(e) => setLinkUrl(e.target.value)}
|
||||||
|
className="j13-md-popover-input"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
applyLink();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="j13-md-popover-footer">
|
||||||
|
<button type="button" className="btn btn-line btn-sm" onClick={() => setPopover(null)}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn btn-primary btn-sm" onClick={applyLink}>
|
||||||
|
插入
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="j13-md-popover-anchor relative">
|
||||||
|
<ToolBtn
|
||||||
|
label={uploading ? "上传中…" : "图片"}
|
||||||
|
icon={<ImageIcon size={15} />}
|
||||||
|
active={popover === "image" || popover === "imageUrl"}
|
||||||
|
disabled={uploading}
|
||||||
|
onClick={() => openPopover("image")}
|
||||||
|
/>
|
||||||
|
{popover === "image" && (
|
||||||
|
<div className="j13-md-popover" role="menu">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
disabled={uploading}
|
||||||
|
onClick={() => {
|
||||||
|
setPopover(null);
|
||||||
|
fileRef.current?.click();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Upload size={14} /> 上传图片
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
onClick={() => openPopover("imageUrl")}
|
||||||
|
>
|
||||||
|
<Link2 size={14} /> 图片地址
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{popover === "imageUrl" && (
|
||||||
|
<div className="j13-md-popover j13-md-popover-form" role="dialog" aria-label="插入图片 URL">
|
||||||
|
<label className="j13-md-field">
|
||||||
|
<span>说明</span>
|
||||||
|
<input
|
||||||
|
value={imageAlt}
|
||||||
|
onChange={(e) => setImageAlt(e.target.value)}
|
||||||
|
className="j13-md-popover-input"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="j13-md-field">
|
||||||
|
<span>URL</span>
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
value={imageUrl}
|
||||||
|
onChange={(e) => setImageUrl(e.target.value)}
|
||||||
|
className="j13-md-popover-input"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
applyImageUrl();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="j13-md-popover-footer">
|
||||||
|
<button type="button" className="btn btn-line btn-sm" onClick={() => setPopover(null)}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn btn-primary btn-sm" onClick={applyImageUrl}>
|
||||||
|
插入
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Sep />
|
||||||
|
<div className="j13-md-popover-anchor relative">
|
||||||
|
<ToolBtn
|
||||||
|
label="隐藏内容"
|
||||||
|
icon={<Lock size={15} />}
|
||||||
|
active={popover === "hide"}
|
||||||
|
onClick={() => openPopover("hide")}
|
||||||
|
/>
|
||||||
|
{popover === "hide" && (
|
||||||
|
<div className="j13-md-popover j13-md-popover-form" role="dialog" aria-label="插入隐藏内容">
|
||||||
|
{hideStep === "menu" ? (
|
||||||
|
<>
|
||||||
|
<button type="button" className="j13-md-menu-item" onClick={() => insertHide("login")}>
|
||||||
|
登录可见
|
||||||
|
</button>
|
||||||
|
<button type="button" className="j13-md-menu-item" onClick={() => insertHide("reply")}>
|
||||||
|
回复可见
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="j13-md-menu-item"
|
||||||
|
onClick={() => setHideStep("points")}
|
||||||
|
>
|
||||||
|
积分可见…
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<label className="j13-md-field">
|
||||||
|
<span>所需积分</span>
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={100000}
|
||||||
|
value={hidePoints}
|
||||||
|
onChange={(e) => setHidePoints(Number(e.target.value) || 1)}
|
||||||
|
className="j13-md-popover-input"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
if (hidePoints >= 1 && hidePoints <= 100000) {
|
||||||
|
insertHide("points", hidePoints);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="j13-md-popover-footer">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-line btn-sm"
|
||||||
|
onClick={() => setHideStep("menu")}
|
||||||
|
>
|
||||||
|
返回
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary btn-sm"
|
||||||
|
onClick={() => {
|
||||||
|
if (hidePoints < 1 || hidePoints > 100000) {
|
||||||
|
toast("积分须在 1–100000", "error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
insertHide("points", hidePoints);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
插入
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2 shrink-0">
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
<div className="j13-md-mode" role="tablist" aria-label="编辑模式">
|
<div className="j13-md-mode" role="tablist" aria-label="编辑模式">
|
||||||
@@ -281,10 +813,32 @@ export default function MarkdownEditor({
|
|||||||
type="file"
|
type="file"
|
||||||
accept="image/jpeg,image/png,image/webp"
|
accept="image/jpeg,image/png,image/webp"
|
||||||
className="hidden"
|
className="hidden"
|
||||||
onChange={(e) => handleImagePick(e.target.files?.[0] ?? null)}
|
onChange={(e) => void uploadImageFile(e.target.files?.[0] ?? null)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{mode === "write" ? (
|
{mode === "write" ? (
|
||||||
|
<div
|
||||||
|
className={`j13-md-write-wrap${dragOver ? " is-dragover" : ""}`}
|
||||||
|
onDragEnter={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (e.dataTransfer.types.includes("Files")) setDragOver(true);
|
||||||
|
}}
|
||||||
|
onDragOver={(e) => e.preventDefault()}
|
||||||
|
onDragLeave={(e) => {
|
||||||
|
if (e.currentTarget === e.target) setDragOver(false);
|
||||||
|
}}
|
||||||
|
onDrop={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(false);
|
||||||
|
const file = e.dataTransfer.files?.[0];
|
||||||
|
if (file) void uploadImageFile(file);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{dragOver && (
|
||||||
|
<div className="j13-md-drop-mask" aria-hidden>
|
||||||
|
放开以上传图片
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<textarea
|
<textarea
|
||||||
ref={taRef}
|
ref={taRef}
|
||||||
id={id}
|
id={id}
|
||||||
@@ -294,13 +848,11 @@ export default function MarkdownEditor({
|
|||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
className="j13-md-textarea"
|
className="j13-md-textarea"
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={(e) => onChange(e.target.value)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={onTextareaKeyDown}
|
||||||
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
|
onPaste={(e) => void onPaste(e)}
|
||||||
e.preventDefault();
|
onSelect={rememberSel}
|
||||||
onSubmitShortcut?.();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="j13-md-preview">
|
<div className="j13-md-preview">
|
||||||
{value.trim() ? (
|
{value.trim() ? (
|
||||||
@@ -312,7 +864,7 @@ export default function MarkdownEditor({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="j13-md-foot">
|
<div className="j13-md-foot">
|
||||||
<span>Markdown · Ctrl/⌘ + Enter 提交</span>
|
<span>支持粘贴/拖拽图片 · Markdown · Ctrl/⌘ + Enter 提交</span>
|
||||||
<span className="tabular-nums">{value.length} 字</span>
|
<span className="tabular-nums">{value.length} 字</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -17,13 +17,11 @@ import {
|
|||||||
} from "@/lib/api";
|
} from "@/lib/api";
|
||||||
import {
|
import {
|
||||||
POST_TYPES,
|
POST_TYPES,
|
||||||
CONTENT_ACCESS,
|
|
||||||
BOUNTY_EXPIRE_DAYS,
|
BOUNTY_EXPIRE_DAYS,
|
||||||
LOTTERY_EXPIRE_DAYS,
|
LOTTERY_EXPIRE_DAYS,
|
||||||
POLL_EXPIRE_DAYS,
|
POLL_EXPIRE_DAYS,
|
||||||
normalizePostType,
|
normalizePostType,
|
||||||
type PostTypeValue,
|
type PostTypeValue,
|
||||||
type ContentAccessValue,
|
|
||||||
} from "@/lib/postMeta";
|
} from "@/lib/postMeta";
|
||||||
import { toast } from "@/lib/toast";
|
import { toast } from "@/lib/toast";
|
||||||
import MarkdownEditor from "@/components/MarkdownEditor";
|
import MarkdownEditor from "@/components/MarkdownEditor";
|
||||||
@@ -44,8 +42,6 @@ type ComposeDraft = {
|
|||||||
tags: string;
|
tags: string;
|
||||||
boardId: number;
|
boardId: number;
|
||||||
postType?: string;
|
postType?: string;
|
||||||
contentAccess?: string;
|
|
||||||
accessPoints?: number;
|
|
||||||
typeMeta?: string;
|
typeMeta?: string;
|
||||||
updatedAt: number;
|
updatedAt: number;
|
||||||
};
|
};
|
||||||
@@ -128,8 +124,6 @@ type EditProps = {
|
|||||||
initialContent: string;
|
initialContent: string;
|
||||||
initialTags?: string;
|
initialTags?: string;
|
||||||
initialPostType?: string;
|
initialPostType?: string;
|
||||||
initialContentAccess?: string;
|
|
||||||
initialAccessPoints?: number;
|
|
||||||
initialTypeMeta?: string;
|
initialTypeMeta?: string;
|
||||||
initialAttachments?: PostAttachment[];
|
initialAttachments?: PostAttachment[];
|
||||||
/** 投票帖:有票后禁止改选项 */
|
/** 投票帖:有票后禁止改选项 */
|
||||||
@@ -162,14 +156,6 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
const [postType, setPostType] = useState<PostTypeValue>(
|
const [postType, setPostType] = useState<PostTypeValue>(
|
||||||
normalizePostType(isCreate ? "discussion" : props.initialPostType)
|
normalizePostType(isCreate ? "discussion" : props.initialPostType)
|
||||||
);
|
);
|
||||||
const [contentAccess, setContentAccess] = useState<ContentAccessValue>(
|
|
||||||
(isCreate
|
|
||||||
? "public"
|
|
||||||
: (props.initialContentAccess as ContentAccessValue) || "public") as ContentAccessValue
|
|
||||||
);
|
|
||||||
const [accessPoints, setAccessPoints] = useState(
|
|
||||||
isCreate ? 10 : props.initialAccessPoints || 10
|
|
||||||
);
|
|
||||||
const [typeMeta, setTypeMeta] = useState(
|
const [typeMeta, setTypeMeta] = useState(
|
||||||
isCreate ? "" : props.initialTypeMeta || ""
|
isCreate ? "" : props.initialTypeMeta || ""
|
||||||
);
|
);
|
||||||
@@ -364,8 +350,6 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
tags: serializeTags(tagList),
|
tags: serializeTags(tagList),
|
||||||
boardId,
|
boardId,
|
||||||
postType,
|
postType,
|
||||||
contentAccess,
|
|
||||||
accessPoints,
|
|
||||||
typeMeta,
|
typeMeta,
|
||||||
updatedAt: Date.now(),
|
updatedAt: Date.now(),
|
||||||
});
|
});
|
||||||
@@ -380,8 +364,6 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
tagList,
|
tagList,
|
||||||
boardId,
|
boardId,
|
||||||
postType,
|
postType,
|
||||||
contentAccess,
|
|
||||||
accessPoints,
|
|
||||||
typeMeta,
|
typeMeta,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -392,10 +374,6 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
setTagList(parseTags(draftBanner.tags || ""));
|
setTagList(parseTags(draftBanner.tags || ""));
|
||||||
if (draftBanner.boardId) setBoardId(draftBanner.boardId);
|
if (draftBanner.boardId) setBoardId(draftBanner.boardId);
|
||||||
if (draftBanner.postType) setPostType(normalizePostType(draftBanner.postType));
|
if (draftBanner.postType) setPostType(normalizePostType(draftBanner.postType));
|
||||||
if (draftBanner.contentAccess) {
|
|
||||||
setContentAccess(draftBanner.contentAccess as ContentAccessValue);
|
|
||||||
}
|
|
||||||
if (draftBanner.accessPoints) setAccessPoints(draftBanner.accessPoints);
|
|
||||||
if (draftBanner.typeMeta) setTypeMeta(draftBanner.typeMeta);
|
if (draftBanner.typeMeta) setTypeMeta(draftBanner.typeMeta);
|
||||||
setDraftBanner(null);
|
setDraftBanner(null);
|
||||||
skipDraftSave.current = false;
|
skipDraftSave.current = false;
|
||||||
@@ -533,7 +511,6 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
title.trim().length > 0 &&
|
title.trim().length > 0 &&
|
||||||
content.trim().length > 0 &&
|
content.trim().length > 0 &&
|
||||||
(isCreate ? boardsReady && boardId > 0 : true) &&
|
(isCreate ? boardsReady && boardId > 0 : true) &&
|
||||||
(contentAccess !== "points" || accessPoints > 0) &&
|
|
||||||
(postType !== "poll" ||
|
(postType !== "poll" ||
|
||||||
pollOptions.map((o) => o.trim()).filter(Boolean).length >= 2) &&
|
pollOptions.map((o) => o.trim()).filter(Boolean).length >= 2) &&
|
||||||
(postType !== "bounty" ||
|
(postType !== "bounty" ||
|
||||||
@@ -609,8 +586,6 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
content: content.trim(),
|
content: content.trim(),
|
||||||
tags,
|
tags,
|
||||||
post_type: postType,
|
post_type: postType,
|
||||||
content_access: contentAccess,
|
|
||||||
access_points: contentAccess === "points" ? accessPoints : 0,
|
|
||||||
type_meta: meta,
|
type_meta: meta,
|
||||||
attachment_ids: attIds,
|
attachment_ids: attIds,
|
||||||
});
|
});
|
||||||
@@ -634,8 +609,6 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
title: title.trim(),
|
title: title.trim(),
|
||||||
content: content.trim(),
|
content: content.trim(),
|
||||||
tags,
|
tags,
|
||||||
content_access: contentAccess,
|
|
||||||
access_points: contentAccess === "points" ? accessPoints : 0,
|
|
||||||
type_meta: meta,
|
type_meta: meta,
|
||||||
attachment_ids: attIds,
|
attachment_ids: attIds,
|
||||||
});
|
});
|
||||||
@@ -818,42 +791,6 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="j13-compose-meta-access">
|
|
||||||
<label className="field-label" htmlFor="compose-access">
|
|
||||||
正文可见性
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
id="compose-access"
|
|
||||||
className="j13-compose-field"
|
|
||||||
value={contentAccess}
|
|
||||||
disabled={loading}
|
|
||||||
onChange={(e) => setContentAccess(e.target.value as ContentAccessValue)}
|
|
||||||
>
|
|
||||||
{CONTENT_ACCESS.map((a) => (
|
|
||||||
<option key={a.value} value={a.value}>
|
|
||||||
{a.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
{contentAccess === "points" && (
|
|
||||||
<div className="mt-2 flex items-center gap-2">
|
|
||||||
<label className="meta text-[12.5px] shrink-0" htmlFor="compose-access-pts">
|
|
||||||
所需积分
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="compose-access-pts"
|
|
||||||
type="number"
|
|
||||||
min={1}
|
|
||||||
max={100000}
|
|
||||||
value={accessPoints}
|
|
||||||
disabled={loading}
|
|
||||||
onChange={(e) => setAccessPoints(Number(e.target.value) || 0)}
|
|
||||||
className="j13-compose-field !py-1.5 w-28"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
@@ -1241,7 +1178,7 @@ export default function PostComposer(props: PostComposerProps) {
|
|||||||
disabled={loading}
|
disabled={loading}
|
||||||
rows={18}
|
rows={18}
|
||||||
placeholder={
|
placeholder={
|
||||||
"从这里开始写正文…\n\n支持 Markdown;可用工具栏插入格式与图片。可点全屏沉浸写作。"
|
"从这里开始写正文…\n\n工具栏可插入格式、代码块、链接、图片与隐藏内容(登录/回复/积分可见)。支持粘贴与拖拽上传图片。"
|
||||||
}
|
}
|
||||||
onSubmitShortcut={() => {
|
onSubmitShortcut={() => {
|
||||||
if (canSubmit) void handleSubmit();
|
if (canSubmit) void handleSubmit();
|
||||||
|
|||||||
116
frontend/components/markdown/MdHideBlock.tsx
Normal file
116
frontend/components/markdown/MdHideBlock.tsx
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { Lock } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { apiUnlockPost } from "@/lib/api";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
import { hideKindLabel, type HideKind } from "@/lib/hideBlocks";
|
||||||
|
|
||||||
|
type MdHideBlockProps = {
|
||||||
|
kind: HideKind;
|
||||||
|
points?: number;
|
||||||
|
locked?: boolean;
|
||||||
|
postId?: number;
|
||||||
|
loggedIn?: boolean;
|
||||||
|
children?: ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 正文内嵌隐藏块:已解锁显示徽章容器;locked 显示就地门禁 */
|
||||||
|
export default function MdHideBlock({
|
||||||
|
kind,
|
||||||
|
points = 0,
|
||||||
|
locked = false,
|
||||||
|
postId,
|
||||||
|
loggedIn = false,
|
||||||
|
children,
|
||||||
|
}: MdHideBlockProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const label = hideKindLabel(kind);
|
||||||
|
|
||||||
|
if (locked) {
|
||||||
|
const unlock = async () => {
|
||||||
|
if (!postId) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await apiUnlockPost(String(postId));
|
||||||
|
if (res.post) {
|
||||||
|
toast("已解锁隐藏内容", "ok");
|
||||||
|
router.refresh();
|
||||||
|
} else {
|
||||||
|
toast(res.error || "解锁失败", "error");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast("解锁失败", "error");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside
|
||||||
|
className="j13-hide-gate"
|
||||||
|
role="note"
|
||||||
|
aria-label={`${label}(未解锁)`}
|
||||||
|
>
|
||||||
|
<Lock size={22} className="j13-hide-gate-icon" aria-hidden />
|
||||||
|
<p className="j13-hide-gate-title">此段内容{label}</p>
|
||||||
|
<p className="j13-hide-gate-desc meta">
|
||||||
|
{kind === "points"
|
||||||
|
? `支付 ${points || 0} 积分后可阅读此段`
|
||||||
|
: kind === "reply"
|
||||||
|
? "发表一条回复后即可阅读此段"
|
||||||
|
: "登录后即可阅读此段"}
|
||||||
|
</p>
|
||||||
|
<div className="j13-hide-gate-actions">
|
||||||
|
{kind === "login" && !loggedIn && postId && (
|
||||||
|
<Link
|
||||||
|
href={`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`}
|
||||||
|
className="btn btn-primary"
|
||||||
|
>
|
||||||
|
去登录
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{kind === "points" && loggedIn && postId && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void unlock()}
|
||||||
|
>
|
||||||
|
{busy ? "解锁中…" : `支付 ${points || 0} 积分解锁`}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{kind === "points" && !loggedIn && postId && (
|
||||||
|
<Link
|
||||||
|
href={`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`}
|
||||||
|
className="btn btn-primary"
|
||||||
|
>
|
||||||
|
登录后解锁
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{kind === "reply" && (
|
||||||
|
<a href="#comments" className="btn btn-primary">
|
||||||
|
去回复
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="j13-hide-block" data-hide-kind={kind}>
|
||||||
|
<div className="j13-hide-block-bar">
|
||||||
|
<span className="j13-hide-badge">{label}</span>
|
||||||
|
{kind === "points" && points > 0 && (
|
||||||
|
<span className="meta text-[12px]">{points} 积分</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="j13-hide-block-body">{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -792,8 +792,6 @@ export async function apiCreatePost(data: {
|
|||||||
content: string;
|
content: string;
|
||||||
tags?: string;
|
tags?: string;
|
||||||
post_type?: string;
|
post_type?: string;
|
||||||
content_access?: string;
|
|
||||||
access_points?: number;
|
|
||||||
type_meta?: string;
|
type_meta?: string;
|
||||||
attachment_ids?: number[];
|
attachment_ids?: number[];
|
||||||
}) {
|
}) {
|
||||||
@@ -820,8 +818,6 @@ export async function apiUpdatePost(
|
|||||||
title?: string;
|
title?: string;
|
||||||
content?: string;
|
content?: string;
|
||||||
tags?: string;
|
tags?: string;
|
||||||
content_access?: string;
|
|
||||||
access_points?: number;
|
|
||||||
type_meta?: string;
|
type_meta?: string;
|
||||||
attachment_ids?: number[];
|
attachment_ids?: number[];
|
||||||
}
|
}
|
||||||
|
|||||||
154
frontend/lib/hideBlocks.ts
Normal file
154
frontend/lib/hideBlocks.ts
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
/** 正文 :::hide 块解析(与 backend/markdown/hide.go 契约一致) */
|
||||||
|
|
||||||
|
export type HideKind = "login" | "reply" | "points";
|
||||||
|
|
||||||
|
export type HideSegment =
|
||||||
|
| { type: "md"; text: string }
|
||||||
|
| {
|
||||||
|
type: "hide";
|
||||||
|
kind: HideKind;
|
||||||
|
points: number;
|
||||||
|
locked: boolean;
|
||||||
|
body: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const OPEN_RE = /^:::hide\s+(login|reply|points)(?:\s+(\d+))?(?:\s+(locked))?\s*$/;
|
||||||
|
|
||||||
|
function isClose(line: string): boolean {
|
||||||
|
return line.trim() === ":::";
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseOpen(trimmed: string): {
|
||||||
|
kind: HideKind;
|
||||||
|
points: number;
|
||||||
|
locked: boolean;
|
||||||
|
} | null {
|
||||||
|
const m = OPEN_RE.exec(trimmed);
|
||||||
|
if (!m) return null;
|
||||||
|
const kind = m[1] as HideKind;
|
||||||
|
const points = m[2] ? Number(m[2]) : 0;
|
||||||
|
const locked = m[3] === "locked";
|
||||||
|
if (kind === "points" && (!Number.isFinite(points) || points < 1)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return { kind, points: kind === "points" ? points : 0, locked };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将正文拆成公开 Markdown 段与隐藏块(忽略代码围栏内伪语法)。
|
||||||
|
* 解析失败时整篇当作普通 Markdown,避免渲染崩溃。
|
||||||
|
*/
|
||||||
|
export function splitHideSegments(content: string): HideSegment[] {
|
||||||
|
if (!content) return [{ type: "md", text: "" }];
|
||||||
|
const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
||||||
|
const out: HideSegment[] = [];
|
||||||
|
let buf: string[] = [];
|
||||||
|
let inCode = false;
|
||||||
|
let i = 0;
|
||||||
|
|
||||||
|
const flushMd = () => {
|
||||||
|
if (buf.length === 0) return;
|
||||||
|
out.push({ type: "md", text: buf.join("\n") });
|
||||||
|
buf = [];
|
||||||
|
};
|
||||||
|
|
||||||
|
while (i < lines.length) {
|
||||||
|
const trimmed = lines[i].trim();
|
||||||
|
if (trimmed.startsWith("```")) {
|
||||||
|
inCode = !inCode;
|
||||||
|
buf.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (inCode) {
|
||||||
|
buf.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const open = parseOpen(trimmed);
|
||||||
|
if (open) {
|
||||||
|
flushMd();
|
||||||
|
const bodyLines: string[] = [];
|
||||||
|
let j = i + 1;
|
||||||
|
let innerCode = false;
|
||||||
|
let found = false;
|
||||||
|
while (j < lines.length) {
|
||||||
|
const inner = lines[j].trim();
|
||||||
|
if (inner.startsWith("```")) {
|
||||||
|
innerCode = !innerCode;
|
||||||
|
bodyLines.push(lines[j]);
|
||||||
|
j++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (innerCode) {
|
||||||
|
bodyLines.push(lines[j]);
|
||||||
|
j++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (parseOpen(inner)) {
|
||||||
|
// 嵌套:放弃隐藏语义,整段当普通文本
|
||||||
|
buf.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
found = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (isClose(inner)) {
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
bodyLines.push(lines[j]);
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
if (!found) {
|
||||||
|
// 未闭合:开标记行起当普通文本
|
||||||
|
buf.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push({
|
||||||
|
type: "hide",
|
||||||
|
kind: open.kind,
|
||||||
|
points: open.points,
|
||||||
|
locked: open.locked,
|
||||||
|
body: bodyLines.join("\n"),
|
||||||
|
});
|
||||||
|
i = j + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
buf.push(lines[i]);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
flushMd();
|
||||||
|
return out.length > 0 ? out : [{ type: "md", text: content }];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 去掉锁块与标记后,供 SEO / TOC / description 使用的公开纯文本片段 */
|
||||||
|
export function publicMarkdownForSeo(content: string): string {
|
||||||
|
const segs = splitHideSegments(content);
|
||||||
|
return segs
|
||||||
|
.filter((s): s is Extract<HideSegment, { type: "md" }> => s.type === "md")
|
||||||
|
.map((s) => s.text)
|
||||||
|
.concat(
|
||||||
|
segs
|
||||||
|
.filter(
|
||||||
|
(s): s is Extract<HideSegment, { type: "hide" }> =>
|
||||||
|
s.type === "hide" && !s.locked
|
||||||
|
)
|
||||||
|
.map((s) => s.body)
|
||||||
|
)
|
||||||
|
.join("\n\n")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hideKindLabel(kind: HideKind): string {
|
||||||
|
switch (kind) {
|
||||||
|
case "login":
|
||||||
|
return "登录可见";
|
||||||
|
case "reply":
|
||||||
|
return "回复可见";
|
||||||
|
case "points":
|
||||||
|
return "积分可见";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ export const CONTENT_ACCESS = [
|
|||||||
{ value: "login", label: "登录可见" },
|
{ value: "login", label: "登录可见" },
|
||||||
{ value: "reply", label: "回复可见" },
|
{ value: "reply", label: "回复可见" },
|
||||||
{ value: "points", label: "积分可见" },
|
{ value: "points", label: "积分可见" },
|
||||||
|
{ value: "mixed", label: "含隐藏内容" },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type ContentAccessValue = (typeof CONTENT_ACCESS)[number]["value"];
|
export type ContentAccessValue = (typeof CONTENT_ACCESS)[number]["value"];
|
||||||
|
|||||||
Reference in New Issue
Block a user