001package org.hl7.fhir.utilities.xhtml;
002
003import static org.apache.commons.lang3.StringUtils.isNotBlank;
004
005/*
006  Copyright (c) 2011+, HL7, Inc.
007  All rights reserved.
008  
009  Redistribution and use in source and binary forms, with or without modification, 
010  are permitted provided that the following conditions are met:
011    
012   * Redistributions of source code must retain the above copyright notice, this 
013     list of conditions and the following disclaimer.
014   * Redistributions in binary form must reproduce the above copyright notice, 
015     this list of conditions and the following disclaimer in the documentation 
016     and/or other materials provided with the distribution.
017   * Neither the name of HL7 nor the names of its contributors may be used to 
018     endorse or promote products derived from this software without specific 
019     prior written permission.
020  
021  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
022  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
023  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
024  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
025  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
026  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
027  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
028  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
029  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
030  POSSIBILITY OF SUCH DAMAGE.
031  
032 */
033
034
035
036import java.io.IOException;
037import java.io.Serializable;
038import java.util.ArrayList;
039import java.util.HashMap;
040import java.util.List;
041import java.util.Map;
042import java.util.Set;
043
044import org.hl7.fhir.exceptions.FHIRException;
045import org.hl7.fhir.instance.model.api.IBaseXhtml;
046import org.hl7.fhir.utilities.Utilities;
047
048import ca.uhn.fhir.model.primitive.XhtmlDt;
049
050@ca.uhn.fhir.model.api.annotation.DatatypeDef(name="xhtml")
051public class XhtmlNode extends XhtmlFluent implements IBaseXhtml {
052  private static final long serialVersionUID = -4362547161441436492L;
053
054
055  public static class Location implements Serializable {
056    private static final long serialVersionUID = -4079302502900219721L;
057    private int line;
058    private int column;
059    public Location(int line, int column) {
060      super();
061      this.line = line;
062      this.column = column;
063    }
064    public int getLine() {
065      return line;
066    }
067    public int getColumn() {
068      return column;
069    }
070    @Override
071    public String toString() {
072      return "Line "+Integer.toString(line)+", column "+Integer.toString(column);
073    }
074  }
075
076  private static boolean checkParaGeneral = false;
077  private boolean checkParaTree = false;
078  
079  public static final String NBSP = Character.toString((char)0xa0);
080  public static final String XMLNS = "http://www.w3.org/1999/xhtml";
081  private static final String DECL_XMLNS = " xmlns=\""+XMLNS+"\"";
082  private static final String NS_SVG = "http://www.w3.org/2000/svg";
083  private static final String NS_XLINK = "http://www.w3.org/1999/xlink";
084
085  private Location location;
086  private NodeType nodeType;
087  private String name;
088  protected Map<String, String> attributes;
089  protected XhtmlNodeList childNodes;
090  private String content;
091  private boolean notPretty;
092  private boolean seperated;  
093  private Boolean emptyExpanded;
094  private Map<String, XhtmlNode> namedParams;
095  private Map<String, String> namedParamValues;
096
097  public XhtmlNode() {
098    super();
099    checkParaTree = checkParaGeneral;
100  }
101
102
103  public XhtmlNode(NodeType nodeType, String name) {
104    super();
105    this.nodeType = nodeType;
106    this.name = name;
107  }
108
109  public XhtmlNode(NodeType nodeType) {
110    super();
111    this.nodeType = nodeType;
112  }
113
114  public NodeType getNodeType() {
115    return nodeType;
116  }
117
118  public void setNodeType(NodeType nodeType) {
119    this.nodeType = nodeType;
120  }
121
122  public String getName() {
123    return name;
124  }
125
126  public XhtmlNode setName(String name) {
127    assert name.contains(":") == false : "Name should not contain any : but was " + name;
128    if (checkParaTree && "p".equals(name)) {
129      isInPara = true;
130    }
131    this.name = name;
132    return this;
133  }
134
135  public boolean hasAttributes() {
136    return attributes != null && !attributes.isEmpty();
137  }
138  
139  public Map<String, String> getAttributes() {
140    if (attributes == null) {
141      attributes = new HashMap<String, String>();
142    }
143    return attributes;
144  }
145
146  public boolean hasChildren() {
147    return childNodes != null && !childNodes.isEmpty();
148  }
149
150
151  public XhtmlNodeList getChildNodes() {
152    if (childNodes == null) {
153      childNodes = new XhtmlNodeList();
154    }
155    return childNodes;
156  }
157
158  public String getContent() {
159    return content;
160  }
161
162  public XhtmlNode setContent(String content) {
163    if (!(nodeType != NodeType.Text || nodeType != NodeType.Comment)) 
164      throw new Error("Wrong node type");
165    this.content = content;
166    return this;
167  }
168
169  public void validate(List<String> errors, String path, boolean inResource, boolean inPara, boolean inLink) {
170    if (nodeType == NodeType.Element || nodeType == NodeType.Document) {
171      path = Utilities.noString(path) ? name : path+"/"+name;
172      if (inResource) {
173        if (!Utilities.existsInList(name, "p", "br", "div", "h1", "h2", "h3", "h4", "h5", "h6", "a", "span", "b", "em", "i", "strong",
174            "small", "big", "tt", "small", "dfn", "q", "var", "abbr", "acronym", "cite", "blockquote", "hr", "address", "bdo", "kbd", "q", "sub", "sup",
175            "ul", "ol", "li", "dl", "dt", "dd", "pre", "table", "caption", "colgroup", "col", "thead", "tr", "tfoot", "tbody", "th", "td",
176            "code", "samp", "img", "map", "area")) {
177          errors.add("Error at "+path+": Found "+name+" in a resource");          
178        }      
179        if (hasAttributes()) {
180          for (String an : attributes.keySet()) {
181            boolean ok = an.startsWith("xmlns") || Utilities.existsInList(an,
182                "title", "style", "class", "ID", "lang", "xml:lang", "dir", "accesskey", "tabindex",
183                // tables
184                "span", "width", "align", "valign", "char", "charoff", "abbr", "axis", "headers", "scope", "rowspan", "colspan") ||
185                Utilities.existsInList(name + "." + an, "a.href", "a.name", "img.src", "img.border", "div.xmlns", "blockquote.cite", "q.cite",
186                    "a.charset", "a.type", "a.name", "a.href", "a.hreflang", "a.rel", "a.rev", "a.shape", "a.coords", "img.src",
187                    "img.alt", "img.longdesc", "img.height", "img.width", "img.usemap", "img.ismap", "map.name", "area.shape",
188                    "area.coords", "area.href", "area.nohref", "area.alt", "table.summary", "table.width", "table.border",
189                    "table.frame", "table.rules", "table.cellspacing", "table.cellpadding", "pre.space", "td.nowrap"
190                    );
191            if (!ok)
192              errors.add("Error at "+path+": Found attribute "+name+"."+an+" in a resource");          
193          }
194        }
195      }
196      if (inPara && Utilities.existsInList(name, "div",  "blockquote", "table", "ol", "ul", "p")) {
197        errors.add("Error at "+path+": Found "+name+" inside an html paragraph");
198      }
199      if (inLink && Utilities.existsInList(name, "a")) {
200        errors.add("Error at "+path+": Found an <a> inside an <a> paragraph");
201      }
202
203      if (hasChildren()) {
204        if ("p".equals(name)) {
205          inPara = true;
206        }
207        if ("a".equals(name)) {
208          inLink = true;
209        }
210        for (XhtmlNode child : childNodes) {
211          child.validate(errors, path, inResource, inPara, inLink);
212        }
213      }
214    }
215  }
216  
217  private XhtmlNode makeTag(String name) {
218    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document))  {
219      throw new Error("Wrong node type - node is "+nodeType.toString()+" ('"+getName()+"/"+getContent()+"')");
220    }
221//  if (inPara && name.equals("p")) {
222//  throw new FHIRException("nested Para");
223//}
224//if (inLink && name.equals("a")) {
225//  throw new FHIRException("Nested Link");
226//}
227    XhtmlNode node = new XhtmlNode(NodeType.Element);
228    node.setName(name);
229    if (getChildNodes().isInPara() || name.equals("p")) {
230      node.getChildNodes().setInPara(true);
231    }
232    if (getChildNodes().isInLink() || name.equals("a")) {
233      node.getChildNodes().setInLink(true);
234    }
235    if (Utilities.existsInList(name, "b", "big", "i", "small", "tt", "abbr", "acronym", "cite", "code", "dfn", "em", "kbd", "strong", "samp", "var", "a", "bdo", "br", "img", "map", "object", "q", "script", "span", "sub", "sup", " button", "input", "label", "select", "textarea", "style", "script")) {
236      node.notPretty();
237    }        
238    return node;
239  }
240  
241  public XhtmlNode addTag(String name) {
242    XhtmlNode node = makeTag(name);
243    addChildNode(node);
244    return node;
245  }
246  
247  public XhtmlNode addTag(String name, XhtmlNode insertionPoint) {
248    XhtmlNode node = makeTag(name);
249    if (insertionPoint != null) {
250      addChildNode(getChildNodes().indexOf(insertionPoint), node);
251    } else {
252      addChildNode(node);
253    }
254    return node;
255  }
256  
257  
258
259  public XhtmlNode addTag(int index, String name) {
260    XhtmlNode node = makeTag(name);
261    addChildNode(index, node);
262    return node;
263  }
264
265
266  public XhtmlNode addComment(String content) {
267    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document))
268      throw new Error("Wrong node type");
269    XhtmlNode node = new XhtmlNode(NodeType.Comment);
270    node.setContent(content);
271    addChildNode(node);
272    return node;
273  }
274
275  public XhtmlNode addCData(String content) {
276    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document))
277      throw new Error("Wrong node type");
278    XhtmlNode node = new XhtmlNode(NodeType.CData);
279    node.setContent(content);
280    addChildNode(node);
281    return node;
282  }
283
284  public XhtmlNode addDocType(String content) {
285    if (!(nodeType == NodeType.Document)) 
286      throw new Error("Wrong node type");
287    XhtmlNode node = new XhtmlNode(NodeType.DocType);
288    node.setContent(content);
289    addChildNode(node);
290    return node;
291  }
292
293  public XhtmlNode addInstruction(String content) {
294    if (!(nodeType == NodeType.Document)) 
295      throw new Error("Wrong node type");
296    XhtmlNode node = new XhtmlNode(NodeType.Instruction);
297    node.setContent(content);
298    addChildNode(node);
299    return node;
300  }
301  
302  public XhtmlNode addText(String content) {
303    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
304      throw new Error("Wrong node type");
305    if (content != null) {
306      XhtmlNode node = new XhtmlNode(NodeType.Text);
307      node.setContent(content);
308      addChildNode(node);
309      return node;
310    } else {
311      return null;
312    }
313  }
314
315  public void addTextWithLineBreaks(String content) {
316    if (content != null) {
317      boolean first = true;
318      for (String line : content.split("\\r?\\n")) {
319        if (first) {
320          first = false;
321        } else {
322          br();
323        }
324        tx(line);
325      }
326    }
327  }
328
329  public XhtmlNode addText(int index, String content) {
330    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
331      throw new Error("Wrong node type");
332    if (content == null)
333      throw new Error("Content cannot be null");
334
335    XhtmlNode node = new XhtmlNode(NodeType.Text);
336    node.setContent(content);
337    addChildNode(index, node);
338    return node;
339  }
340
341  public boolean allChildrenAreText() {
342    boolean res = true;
343    if (hasChildren()) {
344      for (XhtmlNode n : childNodes) {
345        res = res && n.getNodeType() == NodeType.Text;
346      }
347    }
348    return res;
349  }
350
351  public XhtmlNode getElement(String name) {
352    if (hasChildren()) {
353      for (XhtmlNode n : childNodes)
354        if (n.getNodeType() == NodeType.Element && name.equals(n.getName())) 
355          return n;
356    }
357    return null;
358  }
359
360  public XhtmlNode getFirstElement() {
361    if (hasChildren()) {
362      for (XhtmlNode n : childNodes)
363        if (n.getNodeType() == NodeType.Element) 
364          return n;
365    }
366    return null;
367  }
368
369  public String allText() {
370    if (!hasChildren()) {
371      if (getContent() == null) {
372        return "";
373      } else {
374        return getContent();
375      }
376    }
377    
378    StringBuilder b = new StringBuilder();
379    for (XhtmlNode n : childNodes) {
380      if (n.getNodeType() == NodeType.Element && Utilities.existsInList(n.getName(), "li")) {
381        b.append("* ");
382      }
383      if (n.getNodeType() == NodeType.Text) {
384        if (n.getContent() != null) {
385          b.append(n.getContent());
386        }
387      } 
388      if (n.getNodeType() == NodeType.Element) {
389        if (!Utilities.existsInList(n.getName(), "img")) {
390          b.append(n.allText());          
391        } else if (n.hasAttribute("alt")) {
392          b.append(n.getAttribute("alt"));
393        } else {
394          b.append("[image]");
395        }
396        if (Utilities.existsInList(n.getName(), "p", "div", "tr", "th", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6")) {
397          b.append("\r\n");
398        } else if (Utilities.existsInList(n.getName(), "th", "td", "span")) {
399          b.append(" ");
400        }
401      }
402    }
403    return b.toString();
404  }
405
406  public String toLiteralText() {
407    if (!hasChildren()) {
408      if (getContent() == null) {
409        return "";
410      } else {
411        return getContent();
412      }
413    }
414
415    StringBuilder b = new StringBuilder();
416    for (XhtmlNode n : childNodes) {
417      if (n.getNodeType() == NodeType.Text) {
418        if (n.getContent() != null) {
419          b.append(n.getContent());
420        }
421      }
422      if (n.getNodeType() == NodeType.Element) {
423        b.append(n.toLiteralText());
424      }
425    }
426    return b.toString();
427  }
428
429  public XhtmlNode attribute(String name, String value) {
430    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
431      throw new Error("Wrong node type");
432    if (name == null)
433      throw new Error("name is null");
434    if (value == null)
435      throw new Error("value is null");
436    getAttributes().put(name, value);
437    return this;
438  }
439
440  public XhtmlNode attributeNN(String name, String value) {
441    if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) 
442      throw new Error("Wrong node type");
443    if (name == null)
444      throw new Error("name is null");
445    if (value != null) {
446      getAttributes().put(name, value);
447    }
448    return this;
449  }
450
451  public boolean hasAttribute(String name) {
452    return hasAttributes() && getAttributes().containsKey(name);
453  }
454
455  public boolean hasAttribute(String name, String value) {
456    return hasAttributes() && getAttributes().containsKey(name) && value.equals(getAttributes().get(name));
457  }
458
459  public String getAttribute(String name) {
460    return hasAttributes() ? getAttributes().get(name) : null;
461  }
462
463  public XhtmlNode setAttribute(String name, String value) {
464    if (nodeType != NodeType.Element) {
465      throw new Error("Attempt to set an attribute on something that is not an element");
466    }
467    getAttributes().put(name, value);
468    return this;    
469  }
470
471  public XhtmlNode copy() {
472    XhtmlNode dst = new XhtmlNode(nodeType);
473    dst.name = name;
474    if (hasAttributes()) {
475      for (String n : attributes.keySet()) {
476        dst.getAttributes().put(n, attributes.get(n));
477      }
478    }
479    if (hasChildren()) {
480      for (XhtmlNode n : childNodes)
481        dst.addChildNode(n.copy());
482    }
483    dst.content = content;
484    return dst;
485  }
486
487  @Override
488  public boolean isEmpty() {
489    return !hasChildren() && content == null;
490  }
491
492  public boolean equalsDeep(XhtmlNode other) {
493    if (other == null) {
494      return false;
495    }
496
497    if (!(nodeType == other.nodeType) || !compare(name, other.name) || !compare(content, other.content))
498      return false;
499    if (hasAttributes() != other.hasAttributes()) {
500      return false;
501    }
502    if (hasAttributes()) {
503      if (attributes.size() != other.attributes.size())
504        return false;
505      for (String an : attributes.keySet())
506        if (!attributes.get(an).equals(other.attributes.get(an)))
507          return false;
508    }
509    if (hasChildren() != other.hasChildren()) {
510      return false;
511    }
512    if (hasChildren()) {
513      if (childNodes.size() != other.childNodes.size())
514        return false;
515      for (int i = 0; i < childNodes.size(); i++) {
516        if (!compareDeep(childNodes.get(i), other.childNodes.get(i)))
517          return false;
518      }
519    }
520    return true;
521  }
522
523  private boolean compare(String s1, String s2) {
524    if (s1 == null && s2 == null)
525      return true;
526    if (s1 == null || s2 == null)
527      return false;
528    return s1.equals(s2);
529  }
530
531  private static boolean compareDeep(XhtmlNode e1, XhtmlNode e2) {
532    if (e1 == null && e2 == null)
533      return true;
534    if (e1 == null || e2 == null)
535      return false;
536    return e1.equalsDeep(e2);
537  }
538
539  public String getNsDecl() {
540    if (hasAttributes()) {
541      for (String an : attributes.keySet()) {
542        if (an.equals("xmlns")) {
543          return attributes.get(an);
544        }
545      }
546    }
547    return null;
548  }
549
550
551  public Boolean getEmptyExpanded() {
552    return emptyExpanded;
553  }
554
555  public boolean hasEmptyExpanded() {
556    return emptyExpanded != null;
557  }
558
559  public void setEmptyExpanded(Boolean emptyExpanded) {
560    this.emptyExpanded = emptyExpanded;
561  }
562
563
564  @Override
565  public String getValueAsString() {
566    if (isEmpty()) {
567      return null;
568    }
569    try {
570      String retVal = new XhtmlComposer(XhtmlComposer.XML).compose(this);
571      retVal = XhtmlDt.preprocessXhtmlNamespaceDeclaration(retVal);
572      return retVal;
573    } catch (Exception e) {
574      // TODO: composer shouldn't throw exception like this
575      throw new RuntimeException(e);
576    }
577  }
578
579  @Override
580  public void setValueAsString(String theValue) throws IllegalArgumentException {
581    this.attributes = null;
582    this.childNodes = null;
583    this.content = null;
584    this.name = null;
585    this.nodeType= null;
586    if (theValue == null || theValue.length() == 0) {
587      return;
588    }
589
590    String val = theValue.trim();
591
592    if (!val.startsWith("<")) {
593      val = "<div" + DECL_XMLNS +">" + val + "</div>";
594    }
595    if (val.startsWith("<?") && val.endsWith("?>")) {
596      return;
597    }
598
599    val = XhtmlDt.preprocessXhtmlNamespaceDeclaration(val);
600
601    try {
602      XhtmlDocument fragment = new XhtmlParser().parse(val, "div");
603      // Skip the <? .. ?> declaration if one was present
604      XhtmlNodeList nodes = fragment.getChildNodes();
605      XhtmlNode root = nodes.get((nodes.size() > 0 && nodes.get(0) != null && nodes.get(0).getNodeType() == NodeType.Instruction)  ? 1 : 0);
606      this.attributes = root.attributes;
607      this.childNodes = root.childNodes;
608      this.content = root.getContent();
609      this.name = root.getName();
610      this.nodeType= root.getNodeType();
611    } catch (Exception e) {
612      // TODO: composer shouldn't throw exception like this
613      throw new RuntimeException(e);
614    }
615  }
616
617  public XhtmlNode getElementByIndex(int i) {
618    int c = 0;
619    for (XhtmlNode n : childNodes)
620      if (n.getNodeType() == NodeType.Element) {
621        if (c == i)
622          return n;
623        else
624          c++;
625      }
626    return null;
627  }
628
629  @Override
630  public String getValue() {
631    return getValueAsString();
632  }
633
634  public boolean hasValue() {
635    return isNotBlank(getValueAsString());
636  }
637
638  @Override
639  public XhtmlNode setValue(String theValue) throws IllegalArgumentException {
640    setValueAsString(theValue);
641    return this;
642  }
643
644  /**
645   * Returns false
646   */
647  public boolean hasFormatComment() {
648    return false;
649  }
650
651  /**
652   * NOT SUPPORTED - Throws {@link UnsupportedOperationException}
653   */
654  public List<String> getFormatCommentsPre() {
655    throw new UnsupportedOperationException();
656  }
657
658  /**
659   * NOT SUPPORTED - Throws {@link UnsupportedOperationException}
660   */
661  public List<String> getFormatCommentsPost() {
662    throw new UnsupportedOperationException();
663  }
664
665  private Map<String, Object> userData;
666  private boolean isInPara;
667  
668  public Object getUserData(String theName) {
669    if (hasUserData(theName)) {
670      return userData.get(theName);
671    } else {
672      return null;
673    }
674  }
675
676  public boolean hasUserData(String theName) {
677    return userData != null && userData.containsKey(theName);
678  }
679
680  public void setUserData(String theName, Object theValue) {
681    if (userData == null) {
682      userData = new HashMap<>();
683    }
684    userData.put(theName, theValue);
685  }
686
687
688  public Location getLocation() {
689    return location;
690  }
691
692
693  public void setLocation(Location location) {
694    this.location = location;
695  }
696
697  // xhtml easy adders -----------------------------------------------
698  
699
700  @Override
701  public String toString() {
702    if (nodeType == null) {
703      return super.toString();
704    }
705    switch (nodeType) {
706    case Document: 
707    case Element:
708      return new XhtmlComposer(XhtmlComposer.HTML).compose(this);
709    case Text:
710      return this.content;
711    case Comment:
712      return "<!-- "+this.content+" -->";
713    case DocType: 
714      return "<? "+this.content+" />";
715    case Instruction:
716      return "<? "+this.content+" />";
717    }
718    return super.toString();
719  }
720
721
722  public XhtmlNode getNextElement(XhtmlNode c) {
723    boolean f = false;
724    for (XhtmlNode n : childNodes) {
725      if (n == c)
726        f = true;
727      else if (f && n.getNodeType() == NodeType.Element) 
728        return n;
729    }
730    return null;
731  }
732
733
734  public XhtmlNode notPretty() {
735    notPretty = true;
736    return this;
737  }
738
739
740  public boolean isNoPretty() {
741    return notPretty;
742  }
743
744
745  public XhtmlNode style(String style) {
746    if (hasAttribute("style")) {
747      setAttribute("style", getAttribute("style")+"; "+style);
748    } else {
749      setAttribute("style", style);
750    }
751    return this;
752  }
753
754
755  public XhtmlNode nbsp() {
756    addText(NBSP);
757    return this;
758  }
759
760
761  public XhtmlNode para(String text) {
762    XhtmlNode p = para();
763    p.addText(text);
764    return p;
765    
766  }
767
768  public XhtmlNode add(XhtmlNode n) {
769    addChildNode(n);
770    return this;
771  }
772
773
774  public XhtmlNode addChildren(List<XhtmlNode> children) {
775    addChildNodes(children);
776    return this;
777  }
778
779  public XhtmlNode addChildren(XhtmlNode x) {
780    if (x != null) {
781      addChildNodes(x.getChildNodes());
782    }
783    return this;
784  }
785
786
787  public XhtmlNode input(String name, String type, String placeholder, int size) {
788    XhtmlNode p = new XhtmlNode(NodeType.Element, "input");
789    if (name != null) {
790      p.attribute("name", name);
791    }
792    p.attribute("type", type);
793    if (placeholder != null) {
794      p.attribute("placeholder", placeholder);
795    }
796    if (size > 0) {
797        p.attribute("size", Integer.toString(size));
798    }
799    addChildNode(p);
800    return p;
801  }
802
803  public XhtmlNode select(String name) {
804    XhtmlNode p = new XhtmlNode(NodeType.Element, "select");
805    p.attribute("name", name);
806    p.attribute("size", "1");
807    addChildNode(p);
808    return p;
809  }
810  
811  public XhtmlNode option(String value, String text, boolean selected) {
812    XhtmlNode p = new XhtmlNode(NodeType.Element, "option");
813    p.attribute("value", value);
814    p.attribute("selected", Boolean.toString(selected));
815    p.tx(text);
816    addChildNode(p);
817    return p;
818  }
819
820
821  public XhtmlNode remove(XhtmlNode x) {
822    getChildNodes().remove(x);
823    return this;
824    
825  }
826
827
828  public void clear() {
829    getChildNodes().clear();
830    
831  }
832
833
834  public XhtmlNode backgroundColor(String color) {
835    style("background-color: "+color);
836    return this;
837  }
838
839
840  public boolean isPara() {
841    return "p".equals(name);
842  }
843
844  public XhtmlNode sep(String separator) {
845    // if there's already text, add the separator. otherwise, we'll add it next time
846    if (!seperated) {
847      seperated = true;
848      return this;
849    }
850    return tx(separator);
851  }
852
853
854  public XhtmlNode sepBr() {
855    // if there's already text, add the separator. otherwise, we'll add it next time
856    if (!seperated) {
857      seperated = true;
858      return this;
859    }
860    br();
861    return this;
862  }
863
864
865  // more fluent
866  
867  public XhtmlNode colspan(String n) {
868    return setAttribute("colspan", n);
869  }
870
871  public XhtmlNode colspan(int n) {
872    return setAttribute("colspan", Integer.toString(n));
873  }
874
875  public XhtmlNode rowspan(int n) {
876    if (n > 1) {
877      return setAttribute("rowspan", Integer.toString(n));      
878    } else {
879      return this;
880    }
881  }
882
883  @Override
884  protected void addChildren(XhtmlNodeList childNodes) {
885    this.addChildNodes(childNodes);    
886  }
887
888
889  public XhtmlNode color(String color) {
890    return span("color: "+color, null);
891  }
892  
893  public void startScript(String name) {
894    if (namedParams != null) {
895      throw new Error("Sequence Error - script is already open @ "+name);
896    }
897    namedParams = new HashMap<>();    
898    namedParamValues = new HashMap<>();
899  }
900  
901  public XhtmlNode param(String name) {
902    if (namedParams == null) {
903      throw new Error("Sequence Error - script is not already open");
904    }
905    XhtmlNode node = new XhtmlNode(NodeType.Element, "p"); // this node is dead will never appear anywhere, but we are in paragraph mode
906    namedParams.put(name, node);
907    return node;
908  }
909
910
911  public void paramValue(String name, String value) {
912    if (namedParamValues == null) {
913      throw new Error("Sequence Error - script is not already open");
914    }
915    namedParamValues.put(name, value); 
916  }
917
918  public void paramValue(String name, int value) {
919    if (namedParamValues == null) {
920      throw new Error("Sequence Error - script is not already open");
921    }
922    namedParamValues.put(name, Integer.toString(value)); 
923  }
924
925  /**
926   * To set up a script, you do the following:
927   * 
928   * * call startScript - setting up the parameter infrastructure 
929   * * define a set of parameters. Parameter values can be provided as string or integer, or:
930   * * you can use param(name) to render an arbitrarily complicated html fragment that will be inserted by the script
931   * * you can redefine parameters with the same name 
932   * * call execScript() to execute the script. You can call this any number of times
933   * * call closeScript
934   * 
935   * The script format is an xhtml fragment that can have any html in it, and also the following tags:
936   *   param: <param name="{name}"/> - replace this tag with the named parameter (or delete it if no value)
937   *   if: <if test="{condition}"/> - condition is param op value, where value is a string, and op is =, != <, >
938   *   
939   * @param structure
940   * @throws FHIRException
941   * @throws IOException
942   */
943  public void execScript(String structure) throws FHIRException, IOException {
944    XhtmlNode script = new XhtmlParser().parseFragment("<div>"+structure+"</div>");
945    parseNodes(script.getChildNodes(), this.getChildNodes());
946  }
947
948  private void parseNodes(XhtmlNodeList source, XhtmlNodeList dest) {
949    for (XhtmlNode n : source) {
950      if ("param".equals(n.getName())) {
951        XhtmlNode node = namedParams.get(n.getAttribute("name"));
952        if (node != null) {
953          parseNodes(node.getChildNodes(), dest);
954        }
955      } else if ("if".equals(n.getName())) {
956        String test = n.getAttribute("test");
957        if (passesTest(test)) {
958          parseNodes(n.getChildNodes(), dest);
959        }
960      } else {
961        dest.add(n);
962      }
963    }
964
965  }
966
967
968  public void closeScript() {
969    if (namedParams == null) {
970      throw new Error("Sequence Error - script is not already open");
971    }
972    namedParams = null;    
973    namedParamValues = null;
974  }
975
976  private boolean passesTest(String test) {
977    String[] p = test.split("\\s+");
978    if (p.length != 3) {
979      return false;
980    }
981    if (!namedParamValues.containsKey(p[0])) {
982      return false;
983    }
984    String pv = namedParamValues.get(p[0]);
985    switch (p[1]) {
986    case "=": return p[2].equalsIgnoreCase(pv);
987    case "!=": return !p[2].equalsIgnoreCase(pv);
988    case "<": return Utilities.isInteger(p[2]) && Utilities.isInteger(pv) && Integer.parseInt(pv) < Integer.parseInt(p[2]);
989    case "<=": return Utilities.isInteger(p[2]) && Utilities.isInteger(pv) && Integer.parseInt(pv) <= Integer.parseInt(p[2]);
990    case ">": return Utilities.isInteger(p[2]) && Utilities.isInteger(pv) && Integer.parseInt(pv) > Integer.parseInt(p[2]);
991    case ">=": return Utilities.isInteger(p[2]) && Utilities.isInteger(pv) && Integer.parseInt(pv) >= Integer.parseInt(p[2]);
992    }
993    return false;
994  }
995
996
997  public XhtmlNode getElementById(String id) {
998    if (id.equals(getAttribute("id"))) {
999      return this;
1000    }
1001    if (childNodes != null) {
1002      for (XhtmlNode x : childNodes) {
1003        XhtmlNode r = x.getElementById(id);
1004        if (r != null) {
1005          return r;
1006        }   
1007      }
1008    }
1009    return null;
1010  }
1011
1012
1013  public List<XhtmlNode> getChildren(String name) {
1014    List<XhtmlNode> res = new ArrayList<>();
1015    XhtmlNode x = getFirstElement();
1016    while (x != null) {
1017      if (name.equals(x.getName())) {
1018        res.add(x);
1019      }
1020      x = getNextElement(x);
1021    }
1022    return res;
1023  }
1024
1025
1026  public XhtmlNode strikethrough() {
1027    return addTag("s");
1028  }
1029
1030
1031  public XhtmlNode svg() {
1032    XhtmlNode svg = addTag("svg");
1033    svg.setAttribute("xmlns", NS_SVG);
1034    svg.setAttribute("xmlns:xlink", NS_XLINK);
1035    return svg;
1036  }
1037
1038
1039  public XhtmlNode path(String value) {
1040    return addTag("path").attribute("d", value);
1041    
1042  }
1043
1044
1045  public void copyAllContent(XhtmlNode other) {
1046    addChildNodes(other.getChildNodes());
1047    getAttributes().putAll(other.getAttributes());
1048    if (!Utilities.noString(other.getContent())) {
1049      tx(other.getContent());
1050    }    
1051  }
1052
1053  public boolean isClass(String name) {
1054    return hasAttribute("class", name);
1055  }
1056
1057  public XhtmlNode clss(String name) {
1058    if (hasAttribute("class")) {
1059      setAttribute("class", getAttribute("class")+" "+name);      
1060    } else {
1061      setAttribute("class", name);
1062    }
1063    return this;
1064  }
1065
1066  public void styleCells(XhtmlNode x) {
1067    setUserData("cells", x);    
1068  }
1069
1070
1071  public XhtmlNode td(int index) {
1072    XhtmlNode x = addTag(index, "td");
1073    XhtmlNode t = (XhtmlNode) getUserData("cells");
1074    if (t != null) {
1075      x.copyAllContent(t);
1076    }
1077    return x;    
1078  }
1079  
1080  public XhtmlNode td() {
1081    XhtmlNode x = addTag("td");
1082    XhtmlNode t = (XhtmlNode) getUserData("cells");
1083    if (t != null) {
1084      x.copyAllContent(t);
1085    }
1086    return x;
1087  }
1088
1089  public XhtmlNode td(int index, String width) {
1090    XhtmlNode x = addTag(index, "td");
1091    x.attribute("width", width);
1092    XhtmlNode t = (XhtmlNode) getUserData("cells");
1093    if (t != null) {
1094      x.copyAllContent(t);
1095    }
1096    return x;    
1097  }
1098  
1099  public XhtmlNode tdW(int width) {
1100    XhtmlNode x = addTag("td");
1101    x.attribute("width", Integer.toString(width));
1102    XhtmlNode t = (XhtmlNode) getUserData("cells");
1103    if (t != null) {
1104      x.copyAllContent(t);
1105    }
1106    return x;
1107  }
1108
1109
1110
1111  // differs from tx because it returns the owner node, not the created text
1112  public XhtmlNode txN(String cnt) {
1113    addText(cnt);
1114    return this;
1115  }
1116  
1117  public XhtmlNode txOrCode(boolean code, String cnt) {
1118    if (code) {
1119      XhtmlNode c = code();
1120      boolean first = true;
1121      for (String line : cnt.split("\\r?\\n")) {
1122        if (first) first = false; else c.br();
1123        c.tx(line.replace(" ", Character.toString(0xA0)));
1124      }
1125    } else {
1126      addText(cnt);
1127    }
1128    return this;
1129  }
1130
1131
1132  public XhtmlNode iff(boolean test) {
1133    if (test) {
1134      return this;
1135    } else {
1136      return new XhtmlNode(NodeType.Element, "span"); // which will never be connected
1137    }
1138  }
1139
1140
1141  public XhtmlNode button(String class_, String title) {
1142    XhtmlNode btn = addTag("button");
1143    if (class_ != null) {
1144      btn.attribute("class", class_);
1145    }
1146    if (title != null) {
1147      btn.attribute("title", title);
1148    }
1149    return btn;
1150  }
1151
1152
1153  public XhtmlNode head() {
1154    return addTag("head");
1155  }
1156  
1157  public XhtmlNode body() {
1158    return addTag("body");
1159  }
1160  public XhtmlNode title(String title) {
1161    return addTag("title").tx(title);
1162  }
1163  
1164  public XhtmlNode link(String rel, String href) {
1165    return addTag("link").attribute("rel", rel).attribute("href", href);
1166  }
1167
1168  public XhtmlNode ahOrNot(String href) {
1169    if (href == null) {
1170      return this;
1171    }
1172    XhtmlNode x = addTag("a").attribute("href", href);
1173    return x;
1174  }
1175
1176  public XhtmlNode ahOrNot(String href, String title) {
1177    if (href == null) {
1178      return addTag("span").attributeNN("title", title);
1179    } else {
1180      return addTag("a").attribute("href", href).attributeNN("title", title);
1181    }
1182  }
1183
1184
1185  public void wbr() {
1186    addTag("wbr");
1187    
1188  }
1189  
1190  protected int indexOfNode(XhtmlNode node) {
1191    return getChildNodes().indexOf(node);
1192  }
1193  
1194  public int compareTo(XhtmlNode other) {
1195    return compare(this, other);
1196  }
1197
1198  private static int compare(XhtmlNode base, XhtmlNode other) {
1199    if (base == null || other == null) {
1200      return 0;
1201    } else if (base.getNodeType() != other.getNodeType()) {
1202      return base.getNodeType().ordinal() - other.getNodeType().ordinal();
1203    } else switch (base.getNodeType()) {
1204    case Comment: return base.getContent().compareTo(other.getContent());
1205    case DocType: return 0;
1206    case Element:
1207      int r = base.getName().compareTo(other.getName());
1208      if (r != 0) {
1209        return r;
1210      }
1211    case Document:
1212      if (base.getAttributes().size() != other.getAttributes().size()) {
1213        return base.getAttributes().size() - other.getAttributes().size();
1214      } else {
1215        for (String n : base.getAttributes().keySet()) {
1216          String vb = base.getAttributes().get(n);
1217          String vo = other.getAttributes().get(n);
1218          r = vo == null ? -1 : vb.compareTo(vo);
1219          if (r != 0) {
1220            return r;
1221          }
1222        }
1223      }
1224      if (base.getChildNodes().size() != other.getChildNodes().size()) {
1225        return base.getChildNodes().size() - other.getChildNodes().size();
1226      } else {
1227        for (int i = 0; i < base.getChildNodes().size(); i++) {
1228          r = compare(base, other);
1229          if (r != 0) {
1230            return r;
1231          }
1232        }
1233       }
1234      return 0;
1235    case Instruction: return 0;
1236    case Text: return base.getContent().compareTo(other.getContent());
1237    default: return 0;
1238    } 
1239  }
1240
1241
1242  public void stripAnchorsByName(Set<String> anchors) {
1243    if (hasChildren()) {
1244      childNodes.removeIf(n -> "a".equals(n.getName()) && anchors.contains(n.getAttribute("name")));
1245      for (XhtmlNode c : childNodes) {
1246        c.stripAnchorsByName(anchors);
1247      }
1248    }
1249  }
1250
1251  public void addChildNodes(List<XhtmlNode> nodes) {
1252    for (XhtmlNode node : nodes) {
1253      addChildNode(node);
1254    }
1255  }
1256
1257  public void addChildNode(XhtmlNode node) {
1258    checkWhenAddingNode(node);
1259    getChildNodes().add(node);
1260  }
1261
1262  @Override
1263  public void addChild(XhtmlNode node) {
1264    checkWhenAddingNode(node);
1265    getChildNodes().add(node);
1266  }
1267
1268
1269  private void checkWhenAddingNode(XhtmlNode node) {
1270    node.checkParaTree = checkParaTree;
1271    if (checkParaTree) {
1272      if (isInPara) {
1273        if (Utilities.existsInList(node.name, "div",  "blockquote", "table", "ol", "ul", "p")) {
1274          throw new Error("Error: attempt to add "+node.name+" inside an html paragraph");
1275        }
1276        node.isInPara = true;
1277      } 
1278    }
1279  }
1280
1281  public void addChildNode(int index, XhtmlNode node) {
1282    checkWhenAddingNode(node);
1283    getChildNodes().add(index, node);
1284  }
1285
1286
1287  public static boolean isCheckParaGeneral() {
1288    return checkParaGeneral;
1289  }
1290
1291
1292  public static void setCheckParaGeneral(boolean checkParaGeneral) {
1293    XhtmlNode.checkParaGeneral = checkParaGeneral;
1294  }
1295
1296
1297  public boolean isCheckParaTree() {
1298    return checkParaTree;
1299  }
1300
1301
1302  public void setCheckParaTree(boolean checkParaTree) {
1303    this.checkParaTree = checkParaTree;
1304  }
1305
1306
1307  public XhtmlNode id(String id) {
1308    attribute("id", id);
1309    return this;
1310  }
1311
1312
1313  public XhtmlNode supr(String tx) {
1314    addTag("sup").tx(tx);
1315    return this;
1316  }
1317
1318  // -- SVG functions ------------
1319
1320  public XhtmlNode svgG(XhtmlNode insertionPoint) {
1321    return addTag("g", insertionPoint);
1322  }
1323
1324
1325  public XhtmlNode svgRect(XhtmlNode insertionPoint) {
1326    return addTag("rect", insertionPoint);
1327  }
1328
1329
1330  public XhtmlNode svgLine(XhtmlNode insertionPoint) {
1331    return addTag("line", insertionPoint);
1332  }
1333
1334
1335  public XhtmlNode svgText(XhtmlNode insertionPoint) {
1336    return addTag("text", insertionPoint).attribute("text-anchor", "middle"); // cause browsers just do that, but Inkscape doesn't
1337  }
1338
1339
1340  public XhtmlNode svgAx(String link) {
1341    if (link == null) {
1342      return this;
1343    }
1344    var a = addTag("a");
1345    a.attribute("xlink:href", link);
1346    return a;
1347  }
1348
1349
1350  public XhtmlNode svgTspan() {
1351    return addTag("tspan");
1352  }
1353
1354
1355  public XhtmlNode svgPolygon(XhtmlNode insertionPoint) {
1356    return addTag("polygon", insertionPoint);
1357  }
1358
1359
1360  public XhtmlNode htmlObject(double left, double top, double width, double height) {
1361    var x = addTag("foreignObject");
1362    x.attribute("x", Double.toString(left));
1363    x.attribute("y", Double.toString(top));
1364    x.attribute("width", Double.toString(width));
1365    x.attribute("height", Double.toString(height));
1366    return x;
1367  }
1368
1369
1370  public XhtmlNode svgPath(XhtmlNode insertionPoint) {
1371    var x = addTag("path", insertionPoint);
1372    return x;
1373  }
1374
1375
1376  public boolean hasContent() {
1377    if (nodeType == NodeType.Text) {
1378      return content != null && content.trim().length() > 0;
1379    }
1380    if (nodeType == NodeType.Element) {
1381      for (XhtmlNode n : getChildNodes()) {
1382        if (n.hasContent()) {
1383          return true;
1384        }
1385      }
1386    }
1387    return false;
1388  }
1389
1390  public String getPathName() {
1391    if (getName() == null) {
1392      return getNodeType().toCode();      
1393    } else {
1394      return getName();
1395    }
1396  }
1397
1398
1399  public int countByPathName(XhtmlNode node) {
1400    int count = 0;
1401    for (XhtmlNode t : getChildNodes()) {
1402      if (t.getPathName().equals(node.getPathName())) {
1403        count++;
1404      }
1405    }
1406    return count;
1407  }
1408
1409  public int indexByPathName(XhtmlNode node) {
1410    int count = 0;
1411    for (XhtmlNode t : getChildNodes()) {
1412      if (t == node) {
1413        return count;        
1414      }
1415      if (t.getPathName().equals(node.getPathName())) {
1416        count++;
1417      }
1418    }
1419    return count;
1420  }
1421
1422  public void js(String s) {
1423    XhtmlNode x = addTag("script");
1424    x.tx("\r\n"+s+"\r\n");
1425  }
1426  public void jsSrc(String s) {
1427    XhtmlNode x = addTag("script");
1428    x.setAttribute("src", s);
1429    x.tx(" ");
1430  }
1431  public void styles(String s) {
1432    XhtmlNode x = addTag("style");
1433    x.tx("\r\n"+s+"\r\n");
1434  }
1435
1436  public void styleChildren(String style) {
1437    for (XhtmlNode t : getChildNodes()) {
1438      t.style(style);
1439    }
1440  }
1441
1442  /**
1443   * we only want to actually mark something as generated in some modes,
1444   * but it's more fluent to handle the actual implementation here
1445   *
1446   * @param actuallyMark
1447   * @return
1448   */
1449  public XhtmlNode markGenerated(boolean actuallyMark) {
1450    if (actuallyMark) {
1451      this.attribute("data-fhir", "generated");
1452    }
1453    return this;
1454  }
1455
1456  public XhtmlNode firstNamedDescendent(String name) {
1457    for (XhtmlNode t : getChildNodes()) {
1458      if (name.equals(t.getName())) {
1459        return t;
1460      }
1461      XhtmlNode r = t.firstNamedDescendent(name);
1462      if (r != null) {
1463        return r;
1464      }
1465    }
1466    return null;
1467  }
1468
1469  public int countChildrenByName(String p) {
1470    int count = 0;
1471    for (XhtmlNode t : getChildNodes()) {
1472      if (p.equals(t.getName())) {
1473        count++;
1474      }
1475    }
1476    return count;
1477  }
1478}