memos/plugin/gomark/parser/image.go

76 lines
1.8 KiB
Go
Raw Normal View History

package parser
2023-12-13 09:06:47 +08:00
import (
"github.com/usememos/memos/plugin/gomark/ast"
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
)
2023-12-13 09:06:47 +08:00
type ImageParser struct{}
var defaultImageParser = &ImageParser{}
func NewImageParser() *ImageParser {
2023-12-13 09:06:47 +08:00
return defaultImageParser
}
2023-12-13 09:06:47 +08:00
func (*ImageParser) Match(tokens []*tokenizer.Token) (int, bool) {
if len(tokens) < 5 {
2023-12-13 09:06:47 +08:00
return 0, false
}
if tokens[0].Type != tokenizer.ExclamationMark {
2023-12-13 09:06:47 +08:00
return 0, false
}
if tokens[1].Type != tokenizer.LeftSquareBracket {
2023-12-13 09:06:47 +08:00
return 0, false
}
cursor, altText := 2, ""
for ; cursor < len(tokens)-2; cursor++ {
if tokens[cursor].Type == tokenizer.Newline {
2023-12-13 09:06:47 +08:00
return 0, false
}
if tokens[cursor].Type == tokenizer.RightSquareBracket {
break
}
altText += tokens[cursor].Value
}
if tokens[cursor+1].Type != tokenizer.LeftParenthesis {
2023-12-13 09:06:47 +08:00
return 0, false
}
2023-12-13 09:06:47 +08:00
cursor += 2
contentTokens, matched := []*tokenizer.Token{}, false
for _, token := range tokens[cursor:] {
if token.Type == tokenizer.Newline || token.Type == tokenizer.Space {
2023-12-13 09:06:47 +08:00
return 0, false
}
if token.Type == tokenizer.RightParenthesis {
matched = true
break
}
2023-12-13 09:06:47 +08:00
contentTokens = append(contentTokens, token)
}
if !matched || len(contentTokens) == 0 {
return 0, false
}
2023-12-13 09:06:47 +08:00
return cursor + len(contentTokens) + 1, true
}
func (p *ImageParser) Parse(tokens []*tokenizer.Token) ast.Node {
size, ok := p.Match(tokens)
if size == 0 || !ok {
return nil
}
2023-12-13 09:06:47 +08:00
altTextTokens := []*tokenizer.Token{}
for _, token := range tokens[2:] {
if token.Type == tokenizer.RightSquareBracket {
break
}
altTextTokens = append(altTextTokens, token)
}
contentTokens := tokens[2+len(altTextTokens)+2 : size-1]
return &ast.Image{
AltText: tokenizer.Stringify(altTextTokens),
URL: tokenizer.Stringify(contentTokens),
}
}