aboutsummaryrefslogtreecommitdiff
path: root/word_definition.go
blob: 385ba9d80d01efc3101a25b16e919931521dae1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// SPDX-FileCopyrightText: 2020 M. Shulhan <ms@kilabit.info>
// SPDX-License-Identifier: GPL-3.0-or-later

package kbbi

import (
	"fmt"
	"strings"

	"git.sr.ht/~shulhan/pakakeh.go/lib/html"
	libstrings "git.sr.ht/~shulhan/pakakeh.go/lib/strings"
)

// WordDefinition contains the meaning of word in dictionary, and optional
// attribute for word classifications and examples.
type WordDefinition struct {
	Value    string   `json:"isi"`
	Classes  []string `json:"kelas,omitempty"`
	Examples []string `json:"contoh,omitempty"`
}

func parseWordDefinition(in string, li *html.Node) (defKata *WordDefinition, err error) {
	elFont := li.GetFirstChild()
	if elFont == nil || elFont.Data != tagNameFont {
		return nil, nil
	}
	elItalic := elFont.GetFirstChild()
	if elItalic == nil || elItalic.Data != tagNameItalic {
		return nil, nil
	}

	defKata = &WordDefinition{}

	elSpan := elItalic.GetFirstChild()
	for elSpan != nil && elSpan.Data == tagNameSpan {
		kelas := elSpan.GetAttrValue(attrNameTitle)
		if len(kelas) > 0 {
			defKata.Classes = append(defKata.Classes, kelas)
		}
		elSpan = elSpan.GetNextSibling()
	}

	el := elFont.GetNextSibling()
	if el == nil {
		return defKata, nil
	}

	defKata.Value = strings.TrimSpace(libstrings.SingleSpace(el.Data))

	if defKata.Value == "→" {
		defKata.Value = ""
		el = el.GetNextSibling()
		if el == nil || el.Data != tagNameAnchor {
			return nil, nil
		}
		el = el.GetFirstChild()
		return nil, fmt.Errorf(`%q adalah bentuk tidak baku dari %q`,
			in, el.Data)
	}

	if defKata.Value[len(defKata.Value)-1] != ':' {
		return defKata, nil
	}

	defKata.Value = defKata.Value[:len(defKata.Value)-1]

	// Parse the example of kata in the next sibling.
	el = el.GetNextSibling()
	for el != nil {
		if el.Data != tagNameFont {
			break
		}

		elItalic = el.GetFirstChild()
		if elItalic.Data != tagNameItalic {
			break
		}

		elText := elItalic.GetFirstChild()
		if elText != nil {
			contoh := strings.TrimSpace(elText.Data)
			if len(contoh) > 0 && contoh != ";" {
				defKata.Examples = append(defKata.Examples, elText.Data)
			}
		}

		el = el.GetNextSibling()
	}

	return defKata, nil
}