/*
|
* Copyright 2014 Tom <tw201207@gmail.com>
|
*
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
* you may not use this file except in compliance with the License.
|
* You may obtain a copy of the License at
|
*
|
* http://www.apache.org/licenses/LICENSE-2.0
|
*
|
* Unless required by applicable law or agreed to in writing, software
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
* See the License for the specific language governing permissions and
|
* limitations under the License.
|
*/
|
package com.gitblit.utils;
|
|
import org.jsoup.nodes.Document;
|
import org.jsoup.nodes.Element;
|
import org.jsoup.parser.Tag;
|
|
/**
|
* Simple helper class to hide some common setup needed to use JSoup as an HTML generator.
|
* A {@link HtmlBuilder} has a root element that can be manipulated in all the usual JSoup
|
* ways (but not added to some {@link Document}); to generate HTML for that root element,
|
* the builder's {@link #toString()} method can be used. (Or one can invoke toString()
|
* directly on the root element.) By default, a HTML builder does not pretty-print the HTML.
|
*
|
* @author Tom <tw201207@gmail.com>
|
*/
|
public class HtmlBuilder {
|
|
private final Document shell;
|
private final Element root;
|
|
/**
|
* Creates a new HTML builder with a root element with the given {@code tagName}.
|
*
|
* @param tagName
|
* of the {@link Element} to set as the root element.
|
*/
|
public HtmlBuilder(String tagName) {
|
this(new Element(Tag.valueOf(tagName), ""));
|
}
|
|
/**
|
* Creates a new HTML builder for the given element.
|
*
|
* @param element
|
* to set as the root element of this HTML builder.
|
*/
|
public HtmlBuilder(Element element) {
|
shell = Document.createShell("");
|
shell.outputSettings().prettyPrint(false);
|
shell.body().appendChild(element);
|
root = element;
|
}
|
|
/** @return the root element of this HTML builder */
|
public Element getRoot() {
|
return root;
|
}
|
|
/** @return the root element of this HTML builder */
|
public Element root() {
|
return root;
|
}
|
|
/** @return whether this HTML builder will pretty-print the HTML generated by {@link #toString()} */
|
public boolean prettyPrint() {
|
return shell.outputSettings().prettyPrint();
|
}
|
|
/**
|
* Sets whether this HTML builder will produce pretty-printed HTML in its {@link #toString()} method.
|
*
|
* @param pretty
|
* whether to pretty-print
|
* @return the HTML builder itself
|
*/
|
public HtmlBuilder prettyPrint(boolean pretty) {
|
shell.outputSettings().prettyPrint(pretty);
|
return this;
|
}
|
|
/** @return the HTML for the root element. */
|
@Override
|
public String toString() {
|
return root.toString();
|
}
|
|
/** @return the {@link Document} used as generation shell. */
|
protected Document getShell() {
|
return shell;
|
}
|
}
|