golang.org/x/playground@v0.0.0-20230418134305-14ebe15bcd59/static/playground-embed.js (about)

     1  // Copyright 2015 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // opts is an object with these keys
     6  //  codeEl - code editor element
     7  //  embedEl - embed checkbox element
     8  //  embedLabelEl - embed label element, containing embedEl
     9  //  embedHTMLEl - embed HTML text input element
    10  function playgroundEmbed(opts) {
    11    if (opts.codeEl === null || opts.embedEl === null || opts.embedLabelEl === null || opts.embedHTMLEl === null) {
    12      return;
    13    }
    14  
    15    var code = $(opts.codeEl);
    16    var embed = $(opts.embedEl);
    17    var embedLabel = $(opts.embedLabelEl);
    18  
    19    function inIFrame(){
    20      return window.self !== window.top;
    21    }
    22    embedLabel.hide();
    23    if (inIFrame()) {
    24      $("body").addClass("embedded");
    25      return;
    26    }
    27  
    28    function origin(href) {
    29      return (""+href).split("/").slice(0, 3).join("/");
    30    }
    31  
    32    function inputChanged() {
    33      embedLabel.hide();
    34    }
    35  
    36    if (window.history && window.history.pushState && window.addEventListener) {
    37      code[0].addEventListener('input', inputChanged);
    38    }
    39  
    40    var embedHTML = $(opts.embedHTMLEl).hide();
    41    var embedding = false;
    42    embed.change(function() {
    43      if (embedding) return;
    44      embedding = true;
    45      var embeddingData = code.val();
    46      $.ajax("/share", {
    47        processData: false,
    48        data: embeddingData,
    49        type: "POST",
    50        complete: function(xhr) {
    51          embedding = false;
    52          if (xhr.status != 200) {
    53            alert("Server error; try again.");
    54            return;
    55          }
    56          if (embedHTML) {
    57            var path = "/p/" + xhr.responseText;
    58            var url = origin(window.location) + path;
    59            if (embed.prop('checked')){
    60              url = "<iframe src=\"" + url + "\" frameborder=\"0\" style=\"width: 100%; height: 100%\"><a href=\"" + url + "\">see this code in play.golang.org</a></iframe>";
    61            }
    62            embedHTML.show().val(url).focus().select();
    63          }
    64        }
    65      });
    66    });
    67  }