Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Improve iframe behavior #45

Merged
merged 5 commits into from
Mar 10, 2017
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 25 additions & 12 deletions docs-public/snippets.js
Expand Up @@ -94,6 +94,11 @@ SnippetRunner.prototype = {
resizeFrame: function() {
var RESIZE_THRESHOLD = 5;

if ($(this.iframe).closest("[data-height]").length) {
// height is set through {% meta %}
return;
}

try {
var iframe = this.iframe;
var body = iframe.contents().find("body")[0];
Expand All @@ -112,14 +117,6 @@ SnippetRunner.prototype = {
}
},

pollResize: function() {
if (this._resizeTimeout) {
this.resizeFrame();
}

this._resizeTimeout = window.setTimeout(this.pollResize.bind(this), 250);
},

call: function(name) {
var iframe = this.iframe[0];
var iframeWnd = iframe.contentWindow || iframe;
Expand All @@ -128,16 +125,34 @@ SnippetRunner.prototype = {
method.apply(iframeWnd, Array.prototype.slice.call(arguments, 1));
},

_closestHeader: function(element) {
return element.closest('article > *').prevAll('h1,h2,h3,h4,h5,h6').first();
},

_idFromText: function(text) {
return $.trim(text.toLowerCase()).replace(/\s+/g, '-');
},

update: function(content) {
window.clearTimeout(this._resizeTimeout);
this.container.empty();

var attributes = { src: 'javascript:void(0)' };

var metaContainer = $(this.container).closest("[data-height]");
var height = metaContainer.attr("data-height") || 340;
attributes.style = 'height:' + height + 'px';

var id = metaContainer.attr("data-id") || this._idFromText(this._closestHeader(this.container).text());
attributes.id = 'example-' + id;

this.iframe =
$('<iframe class="snippet-runner">')
.attr("src", 'javascript:void(0)')
.attr(attributes)
.show()
.appendTo(this.container);

metaContainer.height("");

var contents = this.iframe.contents();
contents[0].open();
contents[0].write(content);
Expand All @@ -146,8 +161,6 @@ SnippetRunner.prototype = {
var iframe = this.iframe[0];
var iframeWnd = iframe.contentWindow || iframe;
iframeWnd._runnerInit = this.resizeFrame.bind(this);

this.pollResize();
}
};

Expand Down