How to use npm Marked with HighlightJS - readme

How do you use npm Marked with HighlightJS? I'm trying to automate my docs to be parsed and styled. Looking at the following example from marked docs:
// Using async version of marked
marked(markdownString, function (err, content) {
if (err) throw err;
// console.log(content);
});
// Synchronous highlighting with highlight.js
marked.setOptions({
highlight: function (code) {
return require('highlight.js').highlightAuto(code).value;
}
});
console.log(marked(markdownString));
I don't see how to use a README.md file instead of a string with manually escaped special characters. The usage examples don't involve any references to a .md document as input for the markdownString.
How can i pass the markdown string as a document (like form a file called README.md) instead of a manually escaped string and also have the final output include the styling?
The goal is to be able to pass in a linted (I'm using VS code markdownlint) README.md, the main document CSS and or highlightJS css and have the return value of the last line (marked(markdownString)) be something i can write directly to a .html file.
Another note if it matters: My markdown files also specify the the language in multi-line code blocks. For example a multi-line block of JSON in my README.md looks like this:
**BODY**:
```JSON
{
"username": "example#example.com",
"p2setting": "4xx72"
}
```

Based on this post, the docs once specified the following but its been removed from the docs:
var fs = require('fs');
var hljs = require('highlight.js');
var marked = require('marked');
var markdownString = fs.readFileSync('./README.md');
marked.setOptions({
highlight: function(code, lang) {
return hljs.highlight(lang, code).value;
}
});
var output = marked(markdownString);
Note you need to specify the encoding fs.readFileSync('./README.md', "utf8").
A working example is:
const fs = require('fs');
const hljs = require('highlight.js');
const marked = require('marked');
const markdownString = fs.readFileSync('./README.md', "utf8");
const style1 = fs.readFileSync('./node_modules/highlight.js/styles/railscasts.css', "utf8");
// const style1 = fs.readFileSync('./node_modules/highlight.js/styles/solarized-dark.css', "utf8");
marked.setOptions({
highlight: function(code) {
return hljs.highlightAuto(code).value;
}
});
const doc = `<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Marked</title>
<style>${style1}</style>
</head>
<body>${marked(markdownString)}</body>
</html>
`
fs.writeFileSync('./index.html', doc);

Related

Call vue-html-to-paper print function on a new window

I have a Vue component I'd like to print. When the user presses a print button, a function is called which opens the component in a new window to isolate the HTML, and get the formatting right.
async openPrintDetailsDialogue() {
const prtHtml = document.getElementById('printable').innerHTML;
let stylesHtml = '';
for (const node of [...document.querySelectorAll('link[rel="stylesheet"], style')]) {
stylesHtml += node.outerHTML;
}
var newWindow = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
newWindow.document.write(`<!DOCTYPE html>
<html>
<head>
${stylesHtml}
</head>
<body id="printme">
${prtHtml}
</body>
</html>`);
newWindow.document.close();
newWindow.focus();
...
I then try to print using $htmlToPaper.
...
await this.$htmlToPaper('printme');
newWindow.close();
}
However, the main window alerts Element to print #printme not found!.
I add the plugin VueHtmlToPaper in my mounted() function:
mounted() {
Vue.use(VueHtmlToPaper);
}
I've already tried passing my existing styles.css to the $htmlToPaper() call options, which changed nothing. I also have some styles in my vue file's <style scoped>, which couldn't be included in the options parameter either.
How can I get VueHtmlToPaper to "point" to newWindow?
By opening a new window you have a new separate webpage, where is no Vue Js instance. It does not work so and you will not make it work this way. You should use a Modal, change the current page or make a new page with Vue instance for printing.

How to remove ui-light.css from WinJS build?

WinJS or MobileFirst is injecting this piece of code on my index.html, the problem is ui-light.css is messing up with my .css even though it is the very first <link> on the <head>
Is there a way to remove this .css injection? I'd rather avoid doing javascript to remove a code that was just injected by javascript.
<script>
var head = document.getElementsByTagName('head')[0];
if (window.clientInformation.userAgent.indexOf("Windows Phone 8.1") > -1) {
var fileref1 = document.createElement("script");
var fileref2 = document.createElement("script");
var link = document.createElement('link');
fileref1.setAttribute("type", "text/javascript");
fileref1.setAttribute("src", "//Microsoft.Phone.WinJS.2.1/js/base.js");
fileref2.setAttribute("type", "text/javascript");
fileref2.setAttribute("src", "//Microsoft.Phone.WinJS.2.1/js/ui.js");
link.setAttribute("rel", "stylesheet");
link.setAttribute("href", "//Microsoft.Phone.WinJS.2.1/css/ui-light.css");
head.appendChild(fileref1);
head.appendChild(fileref2);
head.appendChild(link);
} else {
var fileref1 = document.createElement("script");
var fileref2 = document.createElement("script");
var link = document.createElement("link");
fileref1.setAttribute("type", "text/javascript");
fileref1.setAttribute("src", "//Microsoft.WinJS.2.0/js/base.js ");
fileref2.setAttribute("type", "text/javascript");
fileref2.setAttribute("src", "//Microsoft.WinJS.2.0/js/ui.js");
link.setAttribute("rel", "stylesheet");
link.setAttribute("href", "//Microsoft.WinJS.2.0/css/ui-light.css");
head.appendChild(fileref1);
head.appendChild(fileref2);
head.appendChild(link);
}
</script>
The latest version of winJS was 4.4. The ui-light/dark.css file was included in the WinJS library as a standalone css file. You can choose not to add it if it was messed up with your css. So, please try to update to winJS 4.4.

durandal IE8 "undefined is null or not an object" error in viewEngine.js

I get the above error in IE only.
the line that throws the error is apparently
element.setAttribute('data-view', viewId);
in viewEngine.js
createView: function(viewId) {
var that = this;
var requirePath = this.convertViewIdToRequirePath(viewId);
var existing = this.tryGetViewFromCache(requirePath);
if (existing) {
return system.defer(function(dfd) {
dfd.resolve(existing.cloneNode(true));
}).promise();
}
return system.defer(function(dfd) {
system.acquire(requirePath).then(function(markup) {
var element = that.processMarkup(markup);
element.setAttribute('data-view', viewId);
that.putViewInCache(requirePath, element);
dfd.resolve(element.cloneNode(true));
}).fail(function(err) {
that.createFallbackView(viewId, requirePath, err).then(function(element) {
element.setAttribute('data-view', viewId);
that.cache[requirePath] = element;
dfd.resolve(element.cloneNode(true));
});
});
}).promise();
},
edit:
I narrowed it down to the error happening between activate() and binding() in the lifecycle. Not sure if this is of any help, though.
edit2: upon further investigation i found that the processMarkup(markup) doesn't return a HtmlDivElement like it should and normally does for all other modules...
Looks like IE8 has issues with the setAttribute method.
To solve try the following:
Use this as your doctype
<!DOCTYPE html>
and then put this in the head of the document
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Resource Link: Replace setAttribute with IE compatible script
I found the mistake and it was not part of any javascript code.
the $.parseHTML() function in Durandals viewEngine.js only returns an object if the html markup supplied has syntactical correct HTML tags. I forgot to close one div at the very end of the view and that was the problem.

Get the loaded LESS file and compile it on demand

I'm trying to compile a small LESS portion of code and mixing it with a bigger one already compiled in the page.
I thought there was some way to reuse the compiled less or maybe load it again, mix it with the newer code and then compile it mixed in the page.
I thought to load it in some way like the example below:
var runtime_less = '#bg:red; .selector { background-color:#bg; }';
var library_less = '#var:bla bla bla...';
var library_parser = new(less.Parser)({
paths: ['.', './lib'], // Specify search paths for #import directives
filename: 'css/full_library.less' // Specify a filename, for better error messages
});
frontsize_parser.parse('', function (e, tree) {
library_less = tree;
});
var runtime_parser = new(less.Parser)({});
runtime_parser.parse(library_less, function (e, tree) {
// this should be inside some load event
$("#container-style").text(library_less.toCSS() + ' ' + tree.toCSS());
});
Does exist some way to get the current page loaded LESS file and treat it in some way?
Or does exist some way to load LESS files and then mix the LESS data with a string with additional LESS code?
with t.less containing:
#color: lightgreen;
You can use the following code:
<link type="text/css" href="t.less" rel="stylesheet/less">
<script>
less = {
env: "development"
};
</script>
<script src="/less.js/dist/less.js"></script>
<script>
var tmp = less.parse;
less.parse = function(input,option,callback) {
tmp(input + ' h1 {color:#color;}',option,callback);
}
less.refreshStyles();
</script>

Passing image from Processing to Javascript and then saving said image back to server using AJAX / PHP?

I'm working on a project where I want to load a processing sketch into a canvas, have some things happen to the image when a user mouses over (got that part), and then when they leave the canvas save the image back to the server.
I've looked at these other questions, and can't quite figure this out:
HTML5 CANVAS: How to save and reopen image from server
That's not really working for me.
Uploading 'canvas' image data to the server
I don't exactly understand where to put everything in this.
http://j-query.blogspot.in/2011/02/save-base64-encoded-canvas-image-to-png.html
From outside of Stackoverflow, but I got there from here.
Version 1
This isn't working all the way, I feel like I'm close, the processing sketch is working, and it's kicking out an image, I just can't grab it with JS, and then I don't know what to do with it to get it back to the server.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Processing Page</title>
<script type="text/javascript" src="../../processingjs/processing.js"></script>
<script type="text/javascript"> //This is for communicating between Processing and Javascript
function showXYCoordinates(x, y) {
document.getElementById('xcoord').value = x;
document.getElementById('ycoord').value = y;
}
var bound = false;
function bindJavascript(instance) {
var pjs = Processing.getInstanceById(instance);
if(pjs != null) {
pjs.bindJavascript(this);
bound = true;
}
if(!bound) {
setTimeout(bindJavascript, 250);
}
}
bindJavascript('B_103');
var processingOutput = Processing.getInstanceByID('B_103');
var img = processingOutput.mouseOut();
</script>
</head>
<body>
<canvas id="B_103" data-processing-sources="B_103/B_103.pde" width="300px" height="300px"></canvas>
<?php
// requires php5
echo $_GET['img'];
define('UPLOAD_DIR', 'B_103/data/');
$img = $_POST['img'];
// $img = str_replace('data:image/png;base64,', '', $img);
// $img = str_replace(' ', '+', $img);
// $data = base64_decode($img);
$file = UPLOAD_DIR . 'image.jpg';
$success = file_put_contents($file, $data);
print $success ? $file : 'Not able to save the file.';
?></body>
</html>
And then there is this:
Version 2
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Processing Page</title>
<script type="text/javascript" src="../../processingjs/processing.js"></script>
<script type="text/javascript"> //This is for communicating between Processing and Javascript
function showXYCoordinates(x, y) {
document.getElementById('xcoord').value = x;
document.getElementById('ycoord').value = y;
}
var bound = false;
function bindJavascript(instance) {
var pjs = Processing.getInstanceById(instance);
if(pjs != null) {
pjs.bindJavascript(this);
bound = true;
}
if(!bound) {
setTimeout(bindJavascript, 250);
}
}
bindJavascript('B_103');
//var processingOutput = Processing.getInstanceByID('B_103');
//var img = processingOutput.mouseOut();
function save(){ //saves the canvas into a string as a base64 png image. jsvalue is sent to the server by an html form
var b_canvas = document.getElementById("B_103");
var b_context = b_canvas.getContext("2d");
var img = b_canvas.file_put_contents('backpicture.png',base64_decode(substr($str,22)));
}
</script>
</head>
<body>
<canvas id="B_103" data-processing-sources="B_103/B_103.pde" width="300px" height="300px"></canvas>
<?php
echo $_GET['img'];
$str=$_POST['img'];
$file=fopen("B_103/data/image.txt","w");
if(isset($_POST['submit']))
fwrite($file,$str);
fclose($file)
?>
</body>
</html>
So this one is saving a file backwards, but the file has nothing in it. I can deal with Base64 (with the answer to one question about using it in processing) but this file doesn't have it in there.
Any thoughts appreciated, thank you!
Way too much code there =)
Canvas can give you a base64 encoded image with a single function call, so just use canvas.toDataURL("image/png") or canvas.toDataURL("image/jpg") to get that string, and then save it to your server with a normal POST operation.
When it's required again, ask your server for the data using whatever format your GET request takes, and then unpack it as an Image, then draw that image onto your sketch:
var dataURI = /* get the string from your server */
var img = new Image();
img.src = dataURI;
sketch.image(img,0,0);
And we should be good to go.
Thanks Mike, it's working. Here's what I did.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Processing Page</title>
<script type="text/javascript" src="../../processingjs/processing.js"></script>
<script type="text/javascript"> //This is for communicating between Processing and Javascript
function showXYCoordinates(x, y) {
document.getElementById('xcoord').value = x;
document.getElementById('ycoord').value = y;
}
var bound = false;
function bindJavascript(instance) {
var pjs = Processing.getInstanceById(instance);
if(pjs != null) {
pjs.bindJavascript(this);
bound = true;
}
if(!bound) {
setTimeout(bindJavascript, 250);
}
}
bindJavascript('B104');
//var processingOutput = Processing.getInstanceByID('B_104');
//var img = processingOutput.mouseOut();
function postAjax(){
var canvasB104 = document.getElementById('B104');
var canvasData = canvasB104.toDataURL('image/png');
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
}
</script>
</head>
<body>
<canvas id="B104" data-processing-sources="B_104/B_104.pde" width="300px" height="300px" onmouseout="postAjax()"></canvas>
Plus, I have a PHP file, that I got from this tutorial: http://permadi.com/blog/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/
One of the things I goofed up, which is probably a rookie thing to do, was I had the variable canvasData in quotes, which I see now is incorrect of course (because I wanted the string not the actual word 'canvasData')
In case anyone wants to see it working: http://graphic-interaction.com/mfa-thesis/testing-group02/pro-ex-07.php