chore: implement part of nodes

This commit is contained in:
Steven
2023-12-13 09:06:47 +08:00
parent dd83782522
commit b20e0097cf
16 changed files with 227 additions and 142 deletions

View File

@ -1,30 +1,32 @@
package parser
import "github.com/usememos/memos/plugin/gomark/parser/tokenizer"
import (
"github.com/usememos/memos/plugin/gomark/ast"
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
)
type ImageParser struct {
AltText string
URL string
}
type ImageParser struct{}
var defaultImageParser = &ImageParser{}
func NewImageParser() *ImageParser {
return &ImageParser{}
return defaultImageParser
}
func (*ImageParser) Match(tokens []*tokenizer.Token) *ImageParser {
func (*ImageParser) Match(tokens []*tokenizer.Token) (int, bool) {
if len(tokens) < 5 {
return nil
return 0, false
}
if tokens[0].Type != tokenizer.ExclamationMark {
return nil
return 0, false
}
if tokens[1].Type != tokenizer.LeftSquareBracket {
return nil
return 0, false
}
cursor, altText := 2, ""
for ; cursor < len(tokens)-2; cursor++ {
if tokens[cursor].Type == tokenizer.Newline {
return nil
return 0, false
}
if tokens[cursor].Type == tokenizer.RightSquareBracket {
break
@ -32,24 +34,42 @@ func (*ImageParser) Match(tokens []*tokenizer.Token) *ImageParser {
altText += tokens[cursor].Value
}
if tokens[cursor+1].Type != tokenizer.LeftParenthesis {
return nil
return 0, false
}
matched, url := false, ""
for _, token := range tokens[cursor+2:] {
cursor += 2
contentTokens, matched := []*tokenizer.Token{}, false
for _, token := range tokens[cursor:] {
if token.Type == tokenizer.Newline || token.Type == tokenizer.Space {
return nil
return 0, false
}
if token.Type == tokenizer.RightParenthesis {
matched = true
break
}
url += token.Value
contentTokens = append(contentTokens, token)
}
if !matched || url == "" {
if !matched || len(contentTokens) == 0 {
return 0, false
}
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
}
return &ImageParser{
AltText: altText,
URL: url,
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),
}
}