Skip to content

Commit

Permalink
fix: 编辑器资源快速引入
Browse files Browse the repository at this point in the history
  • Loading branch information
yanghua committed Jan 30, 2025
1 parent a636b82 commit 55e7e03
Show file tree
Hide file tree
Showing 12 changed files with 309 additions and 29 deletions.
68 changes: 61 additions & 7 deletions backend/api/resource/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,30 @@ import (
"errors"
"fmt"
"io"
"strconv"

"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"github.com/kehuay/aimemos/api/memo"
"github.com/kehuay/aimemos/store"
)

// 定义类型

type ResourceCreate struct {
Data []byte `json:"data"`
Type string `json:"type"`
Id uuid.UUID `json:"id,omitempty"`
Data []byte `json:"data"`
Type string `json:"type"`
Id uuid.UUID `json:"id,omitempty"`
CreatorId int64 `json:"creator_id,omitempty"`
}

type ResourceQuery struct {
CreatorId int64 `json:"creator_id,omitempty"`
}

type Resource struct {
Url string `json:"url"`
Id string `json:"id"`
}

// 定义函数
Expand All @@ -25,8 +37,9 @@ func NewResourceApi(group fiber.Router) fiber.Router {
resourceApi := group.Group("/resource")

// 新建
resourceApi.Post("", createResource)
resourceApi.Post("", memo.GetUserInfo, createResource)
resourceApi.Get("/:id", getResource)
resourceApi.Post("/all", memo.GetUserInfo, getResources)

return resourceApi
}
Expand Down Expand Up @@ -66,10 +79,19 @@ func createResource(c *fiber.Ctx) error {

_store := c.Locals("store").(*store.Store)

user_id := c.Locals("user_id").(string)

resourceCreate.CreatorId, err = strconv.ParseInt(user_id, 10, 64)

if err != nil {
return err
}

_, err = store.CreateResource(store.Resource{
Id: resourceCreate.Id,
Type: resourceCreate.Type,
Data: resourceCreate.Data,
Id: resourceCreate.Id,
Type: resourceCreate.Type,
Data: resourceCreate.Data,
CreatorId: resourceCreate.CreatorId,
}, *_store)

// log.Println(resourceCreate)
Expand Down Expand Up @@ -104,3 +126,35 @@ func getResource(c *fiber.Ctx) error {

return c.Send(resource.Data)
}

func getResources(c *fiber.Ctx) error {

user_id := c.Locals("user_id").(string)
_store := c.Locals("store").(*store.Store)

_user_id, err := strconv.ParseInt(user_id, 10, 64)

if err != nil {
return err
}

rows, err := store.QueryResources(store.Resource{
CreatorId: _user_id,
}, *_store)

if err != nil {
return err
}

resource := make([]Resource, 0)

for _, row := range rows {
resource = append(resource, Resource{
Url: fmt.Sprintf("/api/resource/%s", row.Id),
Id: row.Id.String(),
})
}

return c.JSON(resource)

}
34 changes: 30 additions & 4 deletions backend/store/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,20 @@ import (
)

type Resource struct {
Id uuid.UUID `json:"id"`
Type string `json:"type"`
Data []byte `json:"data"`
Id uuid.UUID `json:"id"`
Type string `json:"type"`
Data []byte `json:"data"`
CreatorId int64 `json:"creator_id"`
}

func CreateResource(resource Resource, store Store) (Resource, error) {

err := store.db.QueryRow(
"insert into resources (id, type, data) values ($1, $2, $3) returning id, type, data",
"insert into resources (id, type, data,creator_id) values ($1, $2, $3, $4) returning id, type, data",
resource.Id,
resource.Type,
resource.Data,
resource.CreatorId,
).Scan(&resource.Id, &resource.Type, &resource.Data)

return resource, err
Expand All @@ -36,3 +38,27 @@ func QueryResource(id string, store Store) (Resource, error) {

return resource, nil
}

func QueryResources(resource Resource, store Store) ([]Resource, error) {
rows, err := store.db.Query(
"select id,creator_id,type from resources where creator_id=$1 order by created_at desc;",
resource.CreatorId,
)

if err != nil {
return []Resource{}, err
}

rowList := make([]Resource, 0)

for rows.Next() {
resource := Resource{}
err = rows.Scan(&resource.Id, &resource.CreatorId, &resource.Type)
if err != nil {
return rowList, err
}
rowList = append(rowList, resource)
}

return rowList, nil
}
24 changes: 18 additions & 6 deletions mark-parser/parser/blocks/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const (
Paragraph
List
Code
Image
)

type Block struct {
Expand All @@ -30,6 +31,8 @@ type Indexes struct {
Type BlockType
}

type SkipInlineParseTypeSet map[BlockType]struct{}

func (indexes Indexes) GetNextContent(text []byte) []byte {
if (indexes.Indexes[1] + 1) > len(text) {
return []byte{}
Expand Down Expand Up @@ -75,6 +78,12 @@ func BlockParse(
parsers []Block,
inlineParsers []inline.Inline,
) []token.Token {

SkipParseSet := make(SkipInlineParseTypeSet)

SkipParseSet[Image] = struct{}{}
// SkipParseSet[Code] = struct{}{}

blockStartIndex := 0
for {
var indexes Indexes
Expand All @@ -92,12 +101,15 @@ func BlockParse(
Text: indexes.Indexes[:2], // 从块开始索引开始的下标
Children: []token.Token{},
})
tokens = inline.InlineParse(
inlineContent,
tokens,
blockStartIndex+indexes.GetContentStartIndex(),
inlineParsers,
)
if _, ok := SkipParseSet[indexes.Type]; !ok {
tokens = inline.InlineParse(
inlineContent,
tokens,
blockStartIndex+indexes.GetContentStartIndex(),
inlineParsers,
)
}

tokens = append(tokens, token.Token{
Type: "block-end",
Tag: int(indexes.Type),
Expand Down
35 changes: 35 additions & 0 deletions mark-parser/parser/blocks/image.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package blocks

import (
"regexp"
)

const (
ImageRegexp = `^!\[(.*)\]\(@([a-zA-Z0-9-]*)(\?w=(\d+)&h=(\d*.?\d+))?\)`
)

func FindImageIndex(texts []byte) (Indexes, bool) {
re, _ := regexp.Compile(ImageRegexp)

matches := re.FindSubmatchIndex(texts)

// log.Println(matches)

if len(matches) >= 6 {
return Indexes{
Indexes: matches,
Matches: matches[2:],
Type: Image,
}, true
}

return Indexes{}, false
}

func GetImageCaption(texts []byte, matches []int) []byte {
return texts[matches[2]:matches[3]]
}

func GetImageId(texts []byte, matches []int) []byte {
return texts[matches[4]:matches[5]]
}
5 changes: 5 additions & 0 deletions mark-parser/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ func Parser(text []byte) []token.Token {
Tag: "code",
Matcher: blocks.FindCodeIndex,
},
{
Type: blocks.Image,
Tag: "img",
Matcher: blocks.FindImageIndex,
},
{
Type: blocks.Paragraph,
Tag: "p",
Expand Down
37 changes: 37 additions & 0 deletions mark-parser/render/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package render

import (
"fmt"
"strconv"

"github.com/kehuay/mark-parser/parser/blocks"
"github.com/kehuay/mark-parser/parser/inline"
Expand Down Expand Up @@ -39,6 +40,40 @@ func RenderBlockStart(texts []byte, token token.Token) string {
// 获取语言
lang := string(texts[token.BlockStartIndex+token.Matches[0] : token.BlockStartIndex+token.Matches[1]])
return fmt.Sprintf("<pre class=\"%s\"><code>", lang)
case int(blocks.Image):
// 提取宽度
style := ""
var width float64 = 0
var height float64 = 0
if token.Matches[6] != -1 && token.Matches[7] != -1 && token.Matches[8] != -1 && token.Matches[9] != -1 {
widthStr := string(texts[token.BlockStartIndex+token.Matches[6] : token.BlockStartIndex+token.Matches[7]])
heightStr := string(texts[token.BlockStartIndex+token.Matches[8] : token.BlockStartIndex+token.Matches[9]])
width, _ = strconv.ParseFloat(widthStr, 64)
height, _ = strconv.ParseFloat(heightStr, 64)
}

if width > 0 {
style += fmt.Sprint(
"width: ",
width,
"%;",
)
height = height * width
}

if height > 0 {
style += fmt.Sprint(
"aspect-ratio: ",
fmt.Sprintf("%.0f/%.0f", width, height),
";",
)
}

return fmt.Sprintf(
"<div class=\"img\"><img src=\"/api/resource/%s\" style=\"%s\" />",
texts[token.BlockStartIndex+token.Matches[2]:token.BlockStartIndex+token.Matches[3]],
style,
)
}
return "<div>"
}
Expand All @@ -54,6 +89,8 @@ func RenderBlockEnd(texts []byte, token token.Token) string {
return "</li>"
case int(blocks.Code):
return "</code></pre>"
case int(blocks.Image):
return "</div>"
}
return "</div>"
}
Expand Down
25 changes: 25 additions & 0 deletions src/api/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ export async function createResource(file: File) {
formData.append("type", "image")
formData.append("files", file)

const accessToken = localStorage.getItem("access-token") ?? ""

const response = await fetch("/api/resource", {
method: 'POST',
headers: {
'authorization': `bearer ${accessToken}`
},
body: formData
})

Expand All @@ -19,5 +24,25 @@ export async function createResource(file: File) {

const data = await response.json()

return data
}

export async function getResources() {
const accessToken = localStorage.getItem("access-token") ?? ""
const response = await fetch("/api/resource/all", {
method: 'POST',
headers: {
'authorization': `bearer ${accessToken}`
},
})

if (!response.ok) {
return {
code: RequestCode.REQUEST_ERROR
}
}

const data = await response.json()

return data
}
9 changes: 9 additions & 0 deletions src/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,13 @@ li.list-item::before {
content: '#';
color: blue;
font-size: 0.5em;
}

.img {
margin: 16px 0;
}

.img>img {
margin: 0 auto;
object-fit: cover;
}
10 changes: 5 additions & 5 deletions src/ui/Home.vue
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function dataTransform(data: any) {
}
function onCreate(data: any) {
console.log(data)
// console.log(data)
memosList.value = [...dataTransform([data]), ...memosList.value]
}
Expand All @@ -99,15 +99,15 @@ onMounted(async () => {

<template>
<!-- 首页 -->
<div class="max-w-768px mx-auto flex gap-16px">
<div class="max-w-896px mx-auto flex gap-16px">
<div class="grow">
<Editor @create="onCreate" />
<div class="mt-16px">
<div v-if="isLoading"
<!-- <div v-if="isLoading"
class="mx-auto relative animate-spin w-20px h-20px rounded-1/2 border-2px bg-gradient-conic bg-gradient-from-blue bg-gradient-to-lime before:(content-[''] absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-1/2 w-75% h-75% bg-white)">
</div>
</div> -->
<!-- memos卡片列表 -->
<MemosCard v-else v-for="memo in memosList" :key="memo.id" v-bind="memo" class="first:mt-0 mt-8px" />
<MemosCard v-for="memo in memosList" :key="memo.id" v-bind="memo" class="first:mt-0 mt-8px" />

<div v-if="isMore" ref="loading" class="flex flex-col items-center mt-16px">
<div
Expand Down
Loading

0 comments on commit 55e7e03

Please sign in to comment.