forked from aymerick/douceur
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inliner.go
243 lines (195 loc) · 5.19 KB
/
inliner.go
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package inliner
import (
"fmt"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/aymerick/douceur/css"
"github.com/aymerick/douceur/parser"
"golang.org/x/net/html"
)
const (
eltMarkerAttr = "douceur-mark"
)
var unsupportedSelectors = []string{
":active", ":after", ":before", ":checked", ":disabled", ":enabled",
":first-line", ":first-letter", ":focus", ":hover", ":invalid", ":in-range",
":lang", ":link", ":root", ":selection", ":target", ":valid", ":visited"}
// Inliner presents a CSS Inliner
type Inliner struct {
// Raw HTML
html string
// Parsed HTML document
doc *goquery.Document
// Parsed stylesheets
stylesheets []*css.Stylesheet
// Collected inlinable style rules
rules []*StyleRule
// HTML elements matching collected inlinable style rules
elements map[string]*Element
// CSS rules that are not inlinable but that must be inserted in output document
rawRules []fmt.Stringer
// current element marker value
eltMarker int
}
// NewInliner instanciates a new Inliner
func NewInliner(html string) *Inliner {
return &Inliner{
html: html,
elements: make(map[string]*Element),
}
}
// Inline inlines css into html document
func Inline(html string) (string, error) {
result, err := NewInliner(html).Inline()
if err != nil {
return "", err
}
return result, nil
}
// Inline inlines CSS and returns HTML
func (inliner *Inliner) Inline() (string, error) {
// parse HTML document
if err := inliner.parseHTML(); err != nil {
return "", err
}
// parse stylesheets
if err := inliner.parseStylesheets(); err != nil {
return "", err
}
// collect elements and style rules
inliner.collectElementsAndRules()
// inline css
if err := inliner.inlineStyleRules(); err != nil {
return "", err
}
// insert raw stylesheet
inliner.insertRawStylesheet()
// generate HTML document
return inliner.genHTML()
}
// Parses raw html
func (inliner *Inliner) parseHTML() error {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(inliner.html))
if err != nil {
return err
}
inliner.doc = doc
return nil
}
// Parses and removes stylesheets from HTML document
func (inliner *Inliner) parseStylesheets() error {
var result error
inliner.doc.Find("style").EachWithBreak(func(i int, s *goquery.Selection) bool {
stylesheet, err := parser.Parse(s.Text())
if err != nil {
result = err
return false
}
inliner.stylesheets = append(inliner.stylesheets, stylesheet)
// removes parsed stylesheet
s.Remove()
return true
})
return result
}
// Collects HTML elements matching parsed stylesheets, and thus collect used style rules
func (inliner *Inliner) collectElementsAndRules() {
for _, stylesheet := range inliner.stylesheets {
for _, rule := range stylesheet.Rules {
if rule.Kind == css.QualifiedRule {
// Let's go!
inliner.handleQualifiedRule(rule)
} else {
// Keep it 'as is'
inliner.rawRules = append(inliner.rawRules, rule)
}
}
}
}
// Handles parsed qualified rule
func (inliner *Inliner) handleQualifiedRule(rule *css.Rule) {
for _, selector := range rule.Selectors {
if Inlinable(selector) {
inliner.doc.Find(selector).Each(func(i int, s *goquery.Selection) {
// get marker
eltMarker, exists := s.Attr(eltMarkerAttr)
if !exists {
// mark element
eltMarker = strconv.Itoa(inliner.eltMarker)
s.SetAttr(eltMarkerAttr, eltMarker)
inliner.eltMarker++
// add new element
inliner.elements[eltMarker] = NewElement(s)
}
// add style rule for element
inliner.elements[eltMarker].addStyleRule(NewStyleRule(selector, rule.Declarations))
})
} else {
// Keep it 'as is'
inliner.rawRules = append(inliner.rawRules, NewStyleRule(selector, rule.Declarations))
}
}
}
// Inline style rules in HTML document
func (inliner *Inliner) inlineStyleRules() error {
for _, element := range inliner.elements {
// remove marker
element.elt.RemoveAttr(eltMarkerAttr)
// inline element
err := element.inline()
if err != nil {
return err
}
}
return nil
}
// Computes raw CSS rules
func (inliner *Inliner) computeRawCSS() string {
result := ""
for _, rawRule := range inliner.rawRules {
result += rawRule.String()
result += "\n"
}
return result
}
// Insert raw CSS rules into HTML document
func (inliner *Inliner) insertRawStylesheet() {
rawCSS := inliner.computeRawCSS()
if rawCSS != "" {
// create <style> element
cssNode := &html.Node{
Type: html.TextNode,
Data: "\n" + rawCSS,
}
styleNode := &html.Node{
Type: html.ElementNode,
Data: "style",
Attr: []html.Attribute{html.Attribute{Key: "type", Val: "text/css"}},
}
styleNode.AppendChild(cssNode)
// append to <head> element
headNode := inliner.doc.Find("head")
if headNode == nil {
// @todo Create head node !
panic("NOT IMPLEMENTED: create missing <head> node")
}
headNode.AppendNodes(styleNode)
}
}
// Generates HTML
func (inliner *Inliner) genHTML() (string, error) {
return inliner.doc.Html()
}
// Inlinable returns true if given selector is inlinable
func Inlinable(selector string) bool {
if strings.Contains(selector, "::") {
return false
}
for _, badSel := range unsupportedSelectors {
if strings.Contains(selector, badSel) {
return false
}
}
return true
}