Insert formatted content from HTML in Quill editor on load - javascript

I want to use Quill for writing articles on my website, however I may need to edit those articles at some point.
To retrieve my formatted content from Quill and put it into the database, I call quill.root.innerHTML, and everything goes well.
However, I'm struggling to find how I could get this HTML content, and then have it displayed in my Quill editor, formatted exactly as it was when I submitted it, when the page loads.
Any help would be welcome, thanks in advance!

Quill's contents are described by the JSON Delta format, and the API provides methods to getContents and setContents using this format:
// Retrieve JSON using the Quill API
const delta = quill.getContents()
const ops = delta.ops;
// Store the JSON representation instead of the raw HTML
storeInDB(ops);
Then you can retrieve the JSON and it should all "just work":
const ops = fetchFromDB();
quill.setContents(ops);

Related

How to use Google Sheets as read-only database for Angular, without making the sheet public

I'm trying to use Google Sheets document as read-only database for my angular application.
I tried some methods to do that, but the problem with all of these methods is that they require the Sheet to be shared publicly (anyone with the link can access the sheet). But what I want is to share it with specific user using Service Account through credentials.
I'm using Angular 14
There is no reference to Angular in Google Sheets for Developers.
If you know any solution or come across an article about this topic, please share it with me.
Thank you.
Here are the steps you'll need to take in order to read from Google Sheets into Angular:
Step 1: Prepare your Google Sheet
1.) Make sure ALL the cells in your sheet are formatted as "Plain text". To do this, click in the upper-left corner of the sheet nexus where the rows and columns intersect to select all cells, then select Format > Number > Plain text from the top menu.
2.) Go to Share, then under "General Access", select "Anyone with the link", then click Done. I believe in your case that this step is optional, since you do not want the sheet to be public.
3.) Go to File > Share > Publish to web in the top menu. Set the scope of what you want to publish, then click Publish. Unfortunately in your case, this step is NOT optional!
Step 2: Fetch the Google Sheet Data
Use the following code example to fetch the raw data from your Google Sheet as plain text:
const docId = '1vLjJqvLGdaS39ccsvoU58kEWXngzV_VXtto07Ki6qVo';
const sheetId = ''; // to get a specific sheet by ID, use '&gid=###'
const url = `https://docs.google.com/spreadsheets/d/${docId}/gviz/tq?tqx=out:json${sheetId}`;
this.http.get(url, {
responseType: 'text',
}).subscribe((response: string): void => {
console.log(response);
});
Step 3: Parse the Raw Text as JSON
Use the following example to parse the raw text to JSON:
const rawJSONText = response.match(/google\.visualization\.Query\.setResponse\(([\s\S\w]+)\)/); // strip the header response
const json = JSON.parse(rawJSONText[1]);
console.log(json);
Hope this helps. Cheers!

Custom blot format in Quill not translating to HTML

I am setting up Quill to use as a rich text editor in a blog project. I have the editor working correctly and can store user posts in mongoDB, retrieve them later, and display them.
My code for doing this involves grabbing the delta from quill, stringifying it, then encoding this as a URI. This is what is stored in my db. These actions take place upon hitting my post button but before submitting the form. I am also storing the plain text for other purposes.
function parseQuill(){
document.getElementById("body").value = encodeURIComponent(JSON.stringify(quill.getContents()));
document.getElementById("bodyText").value = quill.getText();
document.getElementById("compose-form").submit();
}
When accessing a blog post, the delta is retrieved from the db and converted back into html for viewing.
This takes place on the backend. The decoded HTML is sent to my post page and rendered with ejs.
app.get("/posts/:postID", function(req, res){
User.findOne({name: "user1"}, function(err, foundUser){
let posts = foundUser.posts;
posts.forEach(function(post){
if (post._id == req.params.postID){
const decoded = JSON.parse(decodeURIComponent(post.content));
const converter = new QuillDeltaToHtmlConverter(decoded.ops);
const decodedHTML = converter.convert();
console.log(decodedHTML);
post.decoded_HTML = decodedHTML;
res.render("post", {post: post});
}
}
);
});
});
This works for all of the default formats that quill offers.
I have been following along with the Quill guide "Cloning medium with parchment" and have attempted to implement the custom divider blot. My code is identical to what is happening there minus the jQuery. My horizontal rule appears in the text editor and behaves as expected.
My issue arises when saving the delta and attempting to convert it back to html. The delta.ops for a post with a horizontal rule looks something like this.
{"ops":[
{"insert":"Some text followed by a horizontal rule.\n"},
{"insert":{"divider":true}},
{"insert":"Some more text.\n"}]}"
The line representing the horizontal rule is the second insert statement of "divider": true. After storing this as a URI component and decoding it back to HTML, the HTML looks like this:
<p>Some text followed by a horizontal rule.<br/>Some more text.</p>
The horizontal rule tag is nowhere to be found. How can I get this to be interpreted correctly and show up?
If I produce a hidden Quill editor container on my post page, I can load in the pure delta and extract the html with quill.root.innerHTML. This produces HTML that contains the HR. I was hoping to avoid inserting the hidden quill container, if at all possible.
I was an idiot and missed an important step in the html decoding process. Leaving this question up with this answer (which solves the problem) incase anyone else stumbles upon a moment of mental ineptitude.
I was using the package quill-delta-to-html to convert my delta's back to usable html. Of course this package doesn't know how to register custom blots. You have to do that manually before converting.
const dividerOp = {
insert: {
type: "divider",
value: true
},
attributes: {
renderAsBlock: true
}
}
converter.renderCustomWith(function(dividerOp){
if (dividerOp.insert.type === "divider"){
return "<hr>"
} else {
console.log("custom blot convert error");
}
});
const decodedHTML = converter.convert();
Quill was doing everything right on it's end. I had a lapse in memory and forgot I was relying on an external package to handle my delta to html conversions. Adding this customBlot render solves the issue.

How to get data from Viadeo with X-Ray and NodeJs

So I am trying to scrape some content with node.js x-ray scraping framework. While I can get the content from a single page but for exemple only for one employee I can't get my head around on how to get for all the employees.
Working Exemple but return me the first employee:
const request =require('request');
const Xray=require('x-ray');
var x = Xray();
x('http://www.viadeo.com/fr/company/unicef',
'.pan',[{
name:'.pan-emp-name',
job:'.pan-emp-pos',
since:'.pan-emp-age'
// job:'#profile #overview-summary-current ol'
}]).write('result.json')
Thank you so much
x('http://www.viadeo.com/fr/company/unicef',
'#pan-emp .pan-employees .pan-empployee',[{
company:'#company-info .company-logo-picture',
nom:'.pan-emp-name',
job:'.pan-emp-pos',
depuis:'.pan-emp-age'
// job:'#profile #overview-summary-current ol'
}]).write('result.json')
Working like a charm,
So now my problem is to get the company info

Dygraph not plotting graphs using csv link

I am not able to plot graph using dygraph with csv link.
If I use http://jsfiddle.net/eM2Mg/ this link it works. When I replace data with link, it just shows empty graph. I tested in debugger tool and I do get proper response from file. If I just try to plot the graph using same data from file but adding the data in javascript as static content like the example provided in jsfiddle it works.
Things I tried -
1. I tried .txt, .csv and file without extension and nothing worked
2. I tried on different data and when I insert data in static way in javascript it works. So data is in url is definitely not incorrect.
3. When checked response for url in debugger tool I get correct response
image of response
html code -
<div id="graph"></div>
Javascript -
g = new Dygraph(document.getElementById("graph"),
// For possible data formats, see http://dygraphs.com/data.html
"https://files.fm/down.php?i=8v88usam&n=testing_file_2.txt",
{
});
Your dates are in the wrong format, see Dygraphs Data Format
Here are some valid date formats for CSV:
2009-07-12
2009/07/12
2009/07/12 12
2009/07/12 12:34
2009/07/12 12:34:56

Storing HTML in Firebase (AngularFire), good idea or bad?

Is it a good idea to store HTML in Firebase (AngularFire)?
I have a website where I am creating an admin site where users can make HTML elements. I want people to save these elements and the order and the content within the elements. So I thought it would be much easier to just store the whole HTML as a string and load it in when they return. Bad idea?
Here is what I have (simplification):
$scope.save = function() {
var refState = new Firebase("https://<name>.firebaseio.com/users/" + currentAuth.uid + "/state");
var html = "<div>hello</div>";
refState.set({
"state": html
}, function(error) {
if (error) {
console.log("not been saved")
}
})
}
And in my HTML I retrieve want to display it like this using Angular, (yeah I know now how to render HTML in Angular thanks to the comments :)
<div class="well col-md-12">
{{sync[3].state}}
</div>
Storing stringified HTML in firebase is no worse than storing it in a different datastore. You'll want to consider XSS issues, including things like what if they define <style>body{display:none}</style> in their html.
Are you creating a real full fleshed content creation system? If so, it's sometimes hard to get away from user defined HTML, usually from CKeditor, tinymce, etc. However, if the items that they're building are all similar, you should consider how you can store/restore them in a better data format. Most of the time there is a better way to save and restore user defined content that storing straight HTML.
I'd suggest checking out Firepad.
Firepad is a drop-in "Open source collaborative code and text editing" experience for Firebase apps.
"Firepad can use either the CodeMirror editor or the Ace editor to render documents."
Easily allows for a rich text-editor experience that seamlessly stores/syncs the content in a Firebase instance.
As the documentation describes, this is how you initialize Firepad:
<div id="firepad"></div>
<script>
var firepadRef = new Firebase('<FIREBASE URL>');
var codeMirror = CodeMirror(document.getElementById('firepad'), { lineWrapping: true });
var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror,
{ richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!' });
</script>
It's perfectly fine to store HTML in Firebase.
Koding.com, Nitrous.io, and more use Firepad for their collaborative code editor products.
I think it's very bad idea to store html in firebase, store only pain text
How to render html with angular templates

Categories

Resources