@snippetify/book-reader
Version:
Book reader utilities
86 lines (69 loc) • 1.64 kB
JavaScript
class StyleBuilder {
constructor () {
this.styles = {}
this.config = {}
this.rootElement = document
}
static getInstance () {
return new StyleBuilder()
}
setRootElement (element) {
this.rootElement = element
return this
}
setConfig (config) {
this.config = config
this.styles = config.styles
return this
}
find (key) {
return this.styles[key]
}
setMany (items) {
this.styles = items || {}
return this
}
add (name, content) {
this.styles[name] = content
return this
}
remove (name) {
delete this.styles[name]
return this
}
removeMany (items) {
items.forEach(v => this.remove(v))
return this
}
removeAll (print) {
this.styles = {}
if (print) { this.unprint() }
return this
}
build () {
let content = ''
$.each(this.styles, (name, values) => {
content += name.includes('::') ? `.${this.config.vendor} ${name}{` : `.${this.config.vendor} .${name}{`
$.each(values, (key, value) => {
content += `${key}:${value};`
})
content += '}'
})
if (!$(this.rootElement).hasClass(this.config.vendor)) {
$(this.rootElement).addClass(this.config.vendor)
}
return content
}
print () {
let tag = $(`#${this.config.vendor}`)
const tagExists = tag.length > 0
tag = (tagExists ? tag : $('<style />', { id: this.config.vendor })).html(this.build())
if (!tagExists) { tag.appendTo('head') }
return this
}
unprint () {
$(`#${this.config.vendor}`).remove()
}
}
module.exports = StyleBuilder
module.exports.default = StyleBuilder