Skip to content

Instantly share code, notes, and snippets.

@k1sul1
Last active October 31, 2016 13:05
Show Gist options
  • Save k1sul1/5e072da2127b6e92614c59a3e5d4b5d3 to your computer and use it in GitHub Desktop.
Save k1sul1/5e072da2127b6e92614c59a3e5d4b5d3 to your computer and use it in GitHub Desktop.
Compile Stylus at runtime
<?php
add_action('admin_footer', function() {
$screen = get_current_screen();
if ($screen->base === 'post') {
?>
<script src="http://stylus-lang.com/try/stylus.min.js"></script>
<!-- Please DO NOT hotlink to the file in your code.
Instead, save it locally and refer to the local file instead. -->
<style lang="text/stylus" id="source-stylus">
<?php require('src/styl/variables.styl'); ?>
<?php require('src/styl/typography.styl'); ?>
</style>
<!-- I know, it looks horrible. This is necessary for it to work.
Otherwise you'll end up with extra indentation, and Stylus *will*
go apeshit about it. As in, your compile will fail.
Also take note that since this is a browser environment,
any require / import / json / or any other call that uses an external file will probably not work.
This is why I've required variable.styl separately.
-->
<script>
var source = document.querySelector('#source-stylus');
var result = null;
var frame = null;
var render = function(){
frame = document.querySelector('#content_ifr');
if (frame !== null) {
frame = frame.contentDocument || frame.contentWindow.document;
var style = document.createElement('style');
style.innerHTML = result;
frame.querySelector('head').appendChild(style);
} else {
setTimeout(render, 50);
}
};
stylus(source.textContent)
.render(function(err, str) {
if(err) {
return console.error(err);
}
result = str;
render();
});
</script>
<?php
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment