|
| 1 | +using System; |
| 2 | +using System.Threading; |
| 3 | +using System.Windows; |
| 4 | +using Microsoft.Web.WebView2.Core; |
| 5 | + |
| 6 | +namespace Microsoft.JavaScript.NodeApi.Examples; |
| 7 | + |
| 8 | +public partial class Window1 : Window |
| 9 | +{ |
| 10 | + private readonly string markdown; |
| 11 | + |
| 12 | + public static void CreateWebView2Window(string markdown) |
| 13 | + { |
| 14 | + StaThreadWrapper(() => { new Window1(markdown).ShowDialog(); }); |
| 15 | + } |
| 16 | + |
| 17 | + private Window1(string markdown) |
| 18 | + { |
| 19 | + this.markdown = markdown; |
| 20 | + InitializeComponent(); |
| 21 | + } |
| 22 | + |
| 23 | + private static void StaThreadWrapper(Action action) |
| 24 | + { |
| 25 | + var t = new Thread(o => |
| 26 | + { |
| 27 | + action(); |
| 28 | + ////System.Windows.Threading.Dispatcher.Run(); |
| 29 | + }); |
| 30 | + t.SetApartmentState(ApartmentState.STA); |
| 31 | + t.Start(); |
| 32 | + t.Join(); |
| 33 | + } |
| 34 | + |
| 35 | + protected override async void OnContentRendered(EventArgs e) |
| 36 | + { |
| 37 | + base.OnContentRendered(e); |
| 38 | + await webView.EnsureCoreWebView2Async(); // This will work just fine |
| 39 | + |
| 40 | + webView.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived; |
| 41 | + |
| 42 | + string html = $@" |
| 43 | + <!DOCTYPE html> |
| 44 | + <html lang=""en""> |
| 45 | + <body onload=""drawDiagram()""> |
| 46 | + <script type=""module""> |
| 47 | + import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs'; |
| 48 | + window.mermaid = mermaid; |
| 49 | + </script> |
| 50 | + <script> |
| 51 | + const drawDiagram = async function () {{ |
| 52 | + mermaid.initialize({{ securityLevel: ""sandbox"" }}) |
| 53 | + const graphDefinition = `{markdown}`; |
| 54 | + const {{ svg }} = await mermaid.render('graphDiv', graphDefinition); |
| 55 | + window.chrome.webview.postMessage(svg); |
| 56 | + document.getElementById('diagram').innerHTML = svg; |
| 57 | + }} |
| 58 | + </script> |
| 59 | + <div id=""diagram""></div> |
| 60 | + </body> |
| 61 | + </html> |
| 62 | + "; |
| 63 | + webView.NavigateToString(html); |
| 64 | + } |
| 65 | + |
| 66 | + /// <summary> |
| 67 | + /// Triggers when Mermaid svg is generated |
| 68 | + /// </summary> |
| 69 | + private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) |
| 70 | + { |
| 71 | + string data = e.TryGetWebMessageAsString(); |
| 72 | + Console.Write(data); |
| 73 | + ////Close(); |
| 74 | + } |
| 75 | +} |
0 commit comments