|
19 | 19 | */ |
20 | 20 | package com.flowingcode.vaadin.addons.demo; |
21 | 21 |
|
22 | | -import com.vaadin.flow.component.Composite; |
23 | | -import com.vaadin.flow.component.html.IFrame; |
| 22 | +import com.vaadin.flow.component.AttachEvent; |
| 23 | +import com.vaadin.flow.component.Component; |
| 24 | +import com.vaadin.flow.component.HasSize; |
| 25 | +import com.vaadin.flow.component.Tag; |
| 26 | +import com.vaadin.flow.component.dependency.JsModule; |
| 27 | +import com.vaadin.flow.component.dependency.NpmPackage; |
| 28 | +import com.vaadin.flow.component.html.Div; |
24 | 29 |
|
25 | 30 | @SuppressWarnings("serial") |
26 | | -class SourceCodeView extends Composite<IFrame> { |
| 31 | +@NpmPackage(value = "polymer-code-highlighter", version = "1.0.5") |
| 32 | +@JsModule("polymer-code-highlighter/code-highlighter.js") |
| 33 | +class SourceCodeView extends Div implements HasSize { |
| 34 | + |
| 35 | + private String sourceUrl; |
27 | 36 |
|
28 | 37 | public SourceCodeView(String sourceUrl) { |
29 | | - getContent().getElement().setAttribute("frameborder", "0"); |
30 | | - getContent().setMinHeight("0"); |
31 | | - getContent().setMinWidth("0"); |
32 | | - getContent().getElement().setAttribute("srcdoc", getSrcdoc(sourceUrl)); |
33 | | - getContent().setSizeFull(); |
| 38 | + this.sourceUrl = translateSource(sourceUrl); |
34 | 39 | } |
35 | 40 |
|
36 | | - private String getSrcdoc(String sourceUrl) { |
37 | | - return "<html style=\"overflow-y:hidden; height:100%;\"><body style=\"overflow-y: scroll; height:100%;\"><script src=\"https://gist-it.appspot.com/" |
38 | | - + sourceUrl |
39 | | - + "\"></script></body></html>"; |
| 41 | + @Override |
| 42 | + protected void onAttach(AttachEvent attachEvent) { |
| 43 | + super.onAttach(attachEvent); |
| 44 | + |
| 45 | + getElement().executeJs( |
| 46 | + "var self=this;" |
| 47 | + + "var xhr = new XMLHttpRequest();" |
| 48 | + + "xhr.onreadystatechange = function() {" |
| 49 | + + "if (this.readyState == 4 && this.status == 200) {" |
| 50 | + + " var elem = document.createElement('code-highlighter');" |
| 51 | + + " elem.setAttribute('lang','java');" |
| 52 | + + " elem.innerHTML = this.responseText;" |
| 53 | + + " self.appendChild(elem);" |
| 54 | + + "}};" |
| 55 | + + "xhr.open('GET', $0, true);" |
| 56 | + + "xhr.send();", sourceUrl); |
40 | 57 | } |
41 | 58 |
|
42 | | - public void setSizeFull() { |
43 | | - getContent().setSizeFull(); |
| 59 | + private static String translateSource(String url) { |
| 60 | + if (url.startsWith("https://github.com")) { |
| 61 | + url = url.replaceFirst("github.com", "raw.githubusercontent.com"); |
| 62 | + url = url.replaceFirst("/blob", ""); |
| 63 | + } |
| 64 | + return url; |
44 | 65 | } |
| 66 | + |
45 | 67 | } |
0 commit comments