Git Product home page Git Product logo

quill-delta-to-html's People

Contributors

asliwinski avatar bch36 avatar buildai avatar dcsaszar avatar dependabot[bot] avatar edeych avatar joaomarcoslopes avatar kfirzuberi avatar nozer avatar parthdesai93 avatar seeekr avatar thecodinglinguist avatar volser avatar zuberikfir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

quill-delta-to-html's Issues

Type definitions for quill-delta-to-html

I see that this project is written in TypeScript, but doesn't seem to have any associated type definitions in the final artifact. It'd be pretty handy to have the type definitions!

TypeError: Cannot read property of 'QuillDeltaToHtmlConverter' of undefined

Just found this library and trying to implement it into a project. I'm using requireJS to load my js files and I'm getting the following error.

Uncaught TypeError: Cannot read property 'QuillDeltaToHtmlConverter' of undefined at QuillDeltaToHtmlConverter.bundle.js:1178

Here is how I am loading and running the script:

require(['quill-delta-to-html'], function( QuillDeltaToHtmlConverter ) {
        // Get quill contents
        var delta = JSON.parse( $('input[name=league_description]').val() );

        // Log contents delta ops to console
        console.log( delta.ops );
        console.log( window.opts_ );

        // Convert quill ops delta to html
        var converter = new QuillDeltaToHtmlConverter( delta.ops, {} );
        var html = converter.convert();

        // Log html to console
        console.log(html);

        // Update converted view
        document.getElementById('league-description-view').innerHTML = html;
    });

Any help would be greatly appreciated, thanks.

Empty Line Between Headings Not Rendered

Use the header toolbar option:
[{ 'header': [1, 2, false] }]

Edit a document:

  • Add a line of text with "Heading 1"
  • Add a blank line under Heading 1
  • Add a line under the blank formatted with Heading 2

Notice that quill-delta-to-html did not render a
between the two headings.

See it in action here: https://www.screencast.com/t/1EzZhD3XPvQq

Here is the HTML inside quill:
<h1>Heading1</h1><p><br></p><h2>Heading2</h2>

Here is where quill-delta-to-html came up with:
<h1>Heading1</h1><p></p><h2>Heading2</h2>

Pull requests, not an issue/not priority

I'm willing to invest some time in this project as it's proving useful for a couple other projects of mine.

I'd like to beef up the demo file (ie, improve performance, update quill and ui) and assist in any testing, are you open to pull requests?

Convert quill-emoji to html

Hello,
I am new to this project so kindly excuse my complete ignorance.
I am trying to integrate quill into a forum, To that end I need to render quill's delta.
Your plugin is awesome, and does the job, but converting the quill-emoji.
The output of the converter is basically empty.
Is there something I am doing wrong?
Thank you in advance!
JJ.

Module build failed: TypeError: Path must be a string. Received [Function]

Hi. After I import this module, error happens when webpack build as bellow:

Module build failed: TypeError: Path must be a string. Received [Function] at assertPath (path.js:28:11) at Object.normalize (path.js:346:5) at normalizePaths (F:\DevCenter\node_modules\stylus-loader\lib\pathcache.js:301:21) at stylusFile (F:\DevCenter\node_modules\stylus-loader\lib\pathcache.js:102:14) at F:\DevCenter\node_modules\stylus-loader\lib\pathcache.js:159:32

there should has some conflict with webpack or stylus-loader, but i have no idea about it, could you help and give some advice pls?
node version: v8.9.3 npm version: 5.6.0 webpack version: 3.0.0 stylus-loader version: 3.0.1
Thanks very much!

Type errors

Hi. I get the following type errors:

 ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts(4,5):
    TS2411: Property ''name'' of type 'string | undefined' is not assignable to string index type 'string'.
    
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts(5,5):
    TS2411: Property ''target'' of type 'string | undefined' is not assignable to string index type 'string'.
    
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts(6,5):
    TS2411: Property ''slug'' of type 'string | undefined' is not assignable to string index type 'string'.
    
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts(7,5):
    TS2411: Property ''class'' of type 'string | undefined' is not assignable to string index type 'string'.
    
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts(8,5):
    TS2411: Property ''avatar'' of type 'string | undefined' is not assignable to string index type 'string'.
    
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts(9,5):
    TS2411: Property ''id'' of type 'string | undefined' is not assignable to string index type 'string'.
    
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts
    ERROR in /home/circleci/project/node_modules/quill-delta-to-html/dist/commonjs/mentions/MentionSanitizer.d.ts(10,5):
    TS2411: Property ''end-point'' of type 'string | undefined' is not assignable to string index type 'string'.

tsconfig:

{
  "compilerOptions": {
    "module": "esnext",
    "moduleResolution": "node",
    "target": "es5",
    "lib": [
      "dom",
      "es6",
      "dom.iterable",
      "scripthost",
      "es2017"
    ],
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "strictNullChecks": true,
    "alwaysStrict": true,
    "allowSyntheticDefaultImports": true,
    "allowJs": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": [
    "./assets/src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

Thanks!

Support for link `target` is broken 😿

V 0.9.9

Input

[{"attributes":{"target":"_self","link":"#"},"insert":"Ok"},{"insert":"\n"}]'

Expected output

<p><a href="#" target="_self">Ok</a></p>

Actual output

<p><a href="#">Ok</a></p>

Advice for converting a custom blot?

I have a custom embed blot that looks something like the following in the delta json:

{"insert": {"my-blot": {"id": "1761", "value": "Some Name"}}}

I'm wondering if there are examples for adding conversion of custom blots.

I see the code fall though InsertOpsConverter.convertInsertVal and since my insertVal is not a string or any of the DataTypes handled there null is return. Is this the function where I should start to handle my custom blot?

Any advice that would save me some time is appreciated.

module import

Is it possible to import the QuillDeltaToHtmlConverter constructor in a module base project after installing it with npm?

Thanks, great library!

Uncaught TypeError: QuillDeltaToHtmlConverter is not a constructor

Having the following issue loading through require.

####Error
Uncaught TypeError: QuillDeltaToHtmlConverter is not a constructor

####Code Sample

require(['quill-delta-to-html'], function( QuillDeltaToHtmlConverter ) {
        // Get quill contents
        var delta = JSON.parse( $('input[name=league_description]').val() );

        // Log contents delta ops to console
        console.log( delta.ops );
        console.log( window.opts_ );

        // Convert quill ops delta to html
        var converter = new QuillDeltaToHtmlConverter( delta.ops, window.opts_ );
        var html = converter.convert();

        // Log html to console
        console.log(html);

        // Update converted view
        document.getElementById('league-description-view').innerHTML = html;
    });

Thanks in advance for the help.

Support for classless HTML

Hey,

I'm using this library to convert a quill delta into a block of HTML, which I want to embed inside an email. As such, a) I don't want to have any tags with classes, because not all email client support classes and b) in our product we let customers supply their own HTML header and footer, so it's not trivial for me to inject classes into the HTML <head> tag anyways.

So what I'd like is an option like inlineStyles: true which would generate something like:

<span style="text-align: center">Blah</span>

instead of:

<span class="ql-align-center">Blah</span>

So I was wondering if you were interested in a PR to do such a thing?

Bullets don't show up

I am not sure if this is specific to my configuration. But list bullets don't seem to be showing up in the rendered HTML. This is using the demo-browser.html. And in real use cases, the bullet text seems to be missing entirely.

The following is the delta we are looking to render:

{"ops":[{"insert":"Based on the announcement any material that falls under the below needs to be approved by the authorities prior to use:\n"},{"insert":"Brochures, detail aids, drop cards, deave behind materials with medical claims.","attributes":{"list":"bullet"}},{"insert":"\n","attributes":{"list":"bullet","indent":1}},{"insert":"Posters, roll ups, pop ups, congress booth with medical claims.","attributes":{"list":"bullet"}},{"insert":"\n","attributes":{"list":"bullet","indent":1}},{"insert":"Patient educational guide, physician educational guide","attributes":{"list":"bullet"}},{"insert":"\n","attributes":{"list":"bullet","indent":1}},{"insert":"Social Media site: Allowed only for over the counter (OTC) drugs.","attributes":{"list":"bullet"}},{"insert":"\n","attributes":{"list":"bullet","indent":1}}]}

This looks fine in the quill editor, but does not get rendered properly when passed through quill-delta-to-html.

Custom Blots

Hey I'm using this library and I'm trying to render with a custom blot which eventually adds a custom attribute. I was planning to do it from this line
Pointer in library

I'm planning to patch the code in the line indicated above. Is this fine or is there a better way to extend and use this library for custom blots.

adding extra new lines when dealing with code-block

When using the delta:

[
  {
    "insert": "handler(range: { index: Number, length: Number },"
  },
  {
    "attributes": {
      "code-block": true
    },
    "insert": "\n"
  },
  {
    "insert": "        oldRange: { index: Number, length: Number },"
  },
  {
    "attributes": {
      "code-block": true
    },
    "insert": "\n"
  },
  {
    "insert": "        source: String)"
  },
  {
    "attributes": {
      "code-block": true
    },
    "insert": "\n"
  }
]

the expected behavior is to get something like:

<pre>handler(range: { index: Number, length: Number },
        oldRange: { index: Number, length: Number },
        source: String)
</pre>

but instead we are getting this:

<pre>handler(range: { index: Number, length: Number },


        oldRange: { index: Number, length: Number },


        source: String)</pre>

Am I missing something?

Inline `code` swallows other inline elements

Input: [{"attributes":{"italic":true,"link":"#top","code":true},"insert":"Top"},{"insert":"\n"}]

Expected output

<p><code><a href="#top"><em>Top</em></a></code></p> (the nesting order may differ)

Actual output

<p><code>Top</code></p>

new lines to br or p

i'm comparing a simple ops entry of

{{employee.profile.first_name}}\ntest\n\ntest\n

Using quill the editor converts the \n to paragraphs while quill-delta-to-html lib is converting to <br> Is this by design? Is there an option to change behavior?

<br> instead of <p>

I have single op delta:

{ops: [
  { insert: 'TEST\nTEST\nTEST\nTEST\n' }
]}

And I get something like this when I convert:

<p>
  TEST
  <br>
  TEST
  <br>
  TEST
</p>

But Quill renders this as:

<p>TEST</p>
<p>TEST</p>
<p>TEST</p>

BTW I was not able to create <p> with breaklines here https://quilljs.com/playground/ or in demo-browser.html. It's a new paragraph each time I hit enter or paste text with breaklines.

Support for tables

This feature has been in the making for over a year and is available in various Quill 2.0 development releases.

slab/quill#117

Until Quill's official 2.0 release, table support could be optionally enabled in this package? Any idea how much work would it be to implement it?

converter.renderCustomWith doesn't return width attribute in callback

Hey, first of all thanks for this library. Saved me a week's worth of work. :)

I'm trying to render HTML along with custom blot from quill ops object ( which will be saved in db) and width attribute is not being returned for some reason.

This is my sample ops object.

let ops = [ 
  {
    insert: 'random Text goes here'
  },
  {
    attributes: { link: 'http://www.link.com' },
    insert: 'http://www.link.com'
  },
  {
    attributes: { width: '600px', height: '807px', someother: 'dadsa' },
    insert: {
      media:
        'https://www.exampleurltomedia.com/id'
    }
  }
];

let converter = new QuillDeltaToHtmlConverter(ops, {});
  converter.renderCustomWith(ops => {
    if (ops.insert.type === 'media') {
      console.log('ops', ops);
      let val = ops.insert.value;
      return `<iframe src="${val}" frameborder="none" height=${ops.attributes
        .height} width=${ops.attributes.width}></iframe>`;
    }
});

The output for console.log('ops', ops) looks like this:

ops DeltaInsertOp {
 insert:
 InsertDataCustom {
   type: 'media',
   value: 'https://www.exampleurltomedia.com/id' 
 },
  attributes: { height: '807px', someothr: 'dadsa' }
}

If i change width to width1 or anything else it shows up in attributes object. I tried looking at the code but couldn't find where it is stripping the width attribute.

Do let me know if my question is not clear enough.

Link blot target attribute is not respected

Background

We have a customized Quill editor, which supports custom link targets.

Reproduce

Use this delta ops input:

[
{"attributes":{"target":"_self","link":"#"},"insert":"A"},
{"attributes":{"target":"_blank","link":"#"},"insert":"A"},
{"attributes":{"link":"#"},"insert":"A"},{"insert":"\n"}
]

Expected output

<p><a href="#" target="_self">A</a><a href="#" target="_blank">A</a><a href="#">A</a></p>

Actual output

<p><a href="#" target="_blank">A</a><a href="#" target="_blank">A</a><a href="#" target="_blank">A</a></p>

Notes

I think the issue lies here:
https://github.com/nozer/quill-delta-to-html/blob/master/src/OpToHtmlConverter.ts#L182

Unfortunately the default Quill doesn't set the target attribute for the delta op. So this should be configurable in some way.

Alternatively, it would be nice to be able to override known blots with a custom implementation (like renderCustomWith, which was my first attempt btw.).

Multiline text is represented by separated lines instead of separate paragraphs

When typing three lines in Quill the ops become:

[{"insert":"a\nb\nc\n"}]

In Quill's WYSIWYG the three lines are represented by three P paragraphs.

Actual

quill-delta-to-html currently outputs <p>a<br/>b<br/>c</p>, which may break the WYSIWYG aspect.

Expected

<p>a</p><p>b</p><p>c</p>

Notes

In Quill, blank lines are represented by <p><br></p>

Support for Quill Mention

I had written a custom blot handler to support the DOMStringMap object that quill-mention uses to render their mentions.

      // Custom Blot Handler
      converter.renderCustomWith((customOp) => {
        // Conditionally renders blot of mention type
        if(customOp.insert.type === 'mention'){
          // Get Mention Blot Data
          const mention = customOp.insert.value;

          // Template Return Data
          return (
            `
            <span
              class="mention"
              data-index="${mention.index}"
              data-denotation-char="${mention.denotationChar}"
              data-key="${mention.key}"
              data-link="${mention.link}"
              data-value='${mention.value}'
            >
              <span contenteditable="false">
                ${mention.value}
              </span>
            </span>
            `
          )
        }
      })

Maybe we can add a way to render this as html. I'm not too sure how the current mention support works, but maybe we can build on top of that. Regardless, I could just be missing something and there already is support for this.

Unable to get the group types 'InlineGroup','videoItem' etc in React Native production

In React Native debug mode, the following method works to get the type of each groupedOp ('InlineGroup','videoItem').

var QuillDeltaToHtmlConverter = require('quill-delta-to-html');

let converter = new QuillDeltaToHtmlConverter(data.ops);
let groupedOps = converter.getGroupedOps();
groupedOps.map((groupedOp, key) => {
            console.log(groupedOp)
            let groupType = groupedOp.constructor.name 
          // also tried groupedOp.constructor["name"]

            switch (groupType) {
                case "InlineGroup":
                case "ListGroup":
                case "BlockGroup":
                case "VideoItem":
                default:
                    console.log(`Unknown instance`)
                    return;
            }
        })

But I just found out that groupType was undefined in React Native production. I guess the JS minifier may have messed up class.constructor.name in production build (https://stackoverflow.com/a/42660666/2598292). How would you get the type other than constructor.name?

I think one of the solutions for this is storing the type name explicitly in each groupedOp.

Logs:

09-06 00:57:26.041 25561 25619 I ReactNativeJS: { ops: 
09-06 00:57:26.041 25561 25619 I ReactNativeJS:    [ { insert: { type: 'text', value: 'Some text!!!!' },
09-06 00:57:26.041 25561 25619 I ReactNativeJS:        attributes: {} },
09-06 00:57:26.041 25561 25619 I ReactNativeJS:        attributes: {} },
09-06 00:57:26.041 25561 25619 I ReactNativeJS:      { insert: { type: 'text', value: '\n' }, attributes: {} } ] }
09-06 00:57:26.042 25561 25619 I ReactNativeJS: Unknown instance

Custom blot fails to be recognized as blockGroup in `converter.getGroupedOps()`

Here's a custom image blot "imageBlock" that is an extension of BlockEmbed. This is not a replacement of the default "image" blot.

import React, { Component } from 'react';
import ReactQuill from 'react-quill';

// / Custom ImageBlot to add alt text to inline images / ///

const Quill = ReactQuill.Quill;
const BlockEmbed = Quill.import('blots/block/embed');

class ImageBlot extends BlockEmbed {
  static create(value) {
    const node = super.create();
    node.setAttribute('alt', value.alt);
    node.setAttribute('src', value.url);
    return node;
  }

  static value(node) {
    return {
      alt: node.getAttribute('alt'),
      url: node.getAttribute('src'),
    };
  }
}
ImageBlot.blotName = 'imageBlock';
ImageBlot.tagName = 'img';
ImageBlot.className = 'inline-img';
Quill.register(ImageBlot);

When I run the converter, this custom blot is recognized as InsertDataCustom but it falls into the inlineGroup group instead of blockGroup. Is there any problem with the custom blot above that makes it fail to be recognized as blockGroup?

    let converter = new QuillDeltaToHtmlConverter(html.ops);
    let groupedOps = converter.getGroupedOps();
    console.log(groupedOps)

allow linkRel for individual link op

Same as with linkTarget it should be possible to define rel values for each individual link op. For instance you have one paragraph with two links: one internal, one external.

{
        'attributes': {
            'link': '#',
            'target': '_blank',
            'rel': 'nofollow noopener'
          },
          'insert': 'external link'
        },
        {
          'attributes': {
            'link': '#'
          },
          'insert': 'internal link'
        }
}

Expected output

<a href="#" target="_blank" rel="nofollow noopener">external link</a><a href="#">internal link</a>

Actual output

<a href="#" target="_blank">external link</a><a href="#">internal link</a>

Notes

global linkRel option is not applicable since "rel=nofollow" shouldn't be used for every link including internal links.

Add a license

Hi, I would like to use this, but I don't see any license.

Image size

Hi Nozer,

You did a great job, your module is very useful to me and simple to use. But I have some troubles with images, as you know the images are save in base64 with the width attribute. When I resize it, it works, but when I'm saving then displaying it out of Quill the image is displayed with its original size. But when I come back to Quill the image is displayed properly.

I saw that you've just pushed a commit one day ago about supporting width image attribute. What a luck! Can you please release it so I can use it on my prod server by installing it with npm?

Thank you very much

Add support of check lists

Open quill and type [] or [x] to get check list. Could be checked and unchecked
<ul data-checked="false"></ul>, <ul data-checked="true"></ul>

Support for rendering direct to react?

Would be cool if this could output React instead of HTML as I will have to process the out from this into react rather than use __dangerousSetInnnerHtml

How to handle custom attributes?

I need to wrap text elements with custom blots that has a specific attribute.

The ops:

{
    "ops": [
        {
            "attributes": {
                "spoiler": true
            },
            "insert": "Testing spoiler tags"
        },
        {
            "insert": ". ignore this\n"
        }
    ]
}

What it currently outputs:
<p>Testing spoiler tags. ignore this</p>

What i want it to output
<p><spoiler>Testing spoiler tags</spoiler>. ignore this</p>

Text and some blots are losing values when implementing custom rendering

I've added a renderCustomWith() handler to perform rendering of custom blots. I've also added a beforeRender to capture certain elements and alter their rendering. The captured elements are lists and contain child blots that are being rendered by invoking a new instance of the converter with the child ops.

When processing the ops, any text and some other blots, such as images, that are encountered are converted into an InsertDataCustom object with type and value attributes set as such: { type: "type", value: "<ACTUAL_TYPE>" } where <ACTUAL_TYPE> is the value that was previously reported for the value of the type field.

This is relatively trivial to fix for text blots, as the code is designed to treat ordinary strings as text. However, I am trying to use an image custom blot, but because the value field is being overwritten by the type, the URL to the image is lost. The attributes hash retains its former values. Unfortunately, the URL to the image is not included there (nor is the text in the case of a text blot).

This appears to be happening in InsertOpsConverter.convertInsertVal(insertPropVal) and seems to happen because there is no image field. If I hook into the items and add the image field, the problem goes away (for images).

Mention Support?

I see that functionality was added to this project to support mentions. Is there a quill mention module that is compatible with the mentions code in here?

Why is it set indent to 0?

_renderListItem(li: ListItem): string {

      //if (!isOuterMost) {
      li.item.op.attributes.indent = 0;
      //}
      var converter = new OpToHtmlConverter(li.item.op, this.converterOptions);
      var parts = converter.getHtmlParts();
      var liElementsHtml = this._renderInlines(li.item.ops, false);
      return parts.openingTag + (liElementsHtml) +
         (li.innerList ? this._renderList(li.innerList) : '')
         + parts.closingTag;
   }

Explicit align left

I would like text-align:left styles to be added to align left text.

I thought this config would do the trick, but align left is still being ignored.

  inlineStyles: {
      align: {
        left: 'text-align:left',
        center: 'text-align:center',
        right: 'text-align:right'
      }
    }

Thanks for the help!

Background Color Support

It seems like quill-delta-to-html doesn't had the background color.

I guess this would not be too complicated to had it as there is already the color which is working perfectly.

This is the same logic but with the "background" attribute of the delta and it should set the "background-color" style of the node.

Tell me if I can help. ;)

Sanitize link attribute

I've found that people can inject xss in the link attribute:

{"ops":[{"attributes":{"link":"javascript:alert(8007)"},"insert":"link"}]}

The browser will execute the javascript when you click the link.

Would you consider removing this sort of injection in the link attribute by escaping these characters?

export function escapeLink(string) {
    return string
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/\(/g, "&#40;")
        .replace(/\)/g, "&#41;")
        .replace(/"/g, "&quot;");
};

Converting Font Sizes

My problem regards manually defined font sizes in the quill toolbar. I might be missing something... but quill is using style="font-size: 24px" as inline-styling and uses .ql classes for everything else. My theory is that the converter does not look at the predefined inline-styles and just constructs new ones based on the delta.

I'm creating my own vue wrapper for quill

Templated Font Size Toolbar

<select title="Size" class="ql-size" v-if="fontSize">
    <option v-for="size in fontSizes" :value="size">{{ size }}</option>
</select>

My Font Sizes

const FONT_SIZES = [
  '8px',
  '9px',
  '10px',
  '11px',
  '12px',
  '13px',
  '14px',
  '16px',
  '18px',
  '20px',
  '22px',
  '24px',
  '26px',
  '28px',
  '32px',
  '36px',
  '48px',
  '72px'
]

My Converter

    getHtml: function(){
       // Quill Editor Delta
      const delta = this.editor.getContents();

      // Initialize Array to store Mentioned Users
      const mentions = new Array;

      // Iterate through delta ops
      for(let op in delta.ops){
        // Get each operation from delta ops
        const opeartion = delta.ops[op];

        // If mention is defined, then store it in mentions array
        opeartion.insert.mention ? mentions.push(opeartion.insert.mention) : null;
      }

      let fonts = new Object();
      this.fonts.forEach((font) => {
        fonts[font.class] = `font-family: ${font.family}`
      })

      const styleOptions = {
        font: fonts
      }

      // Initialize Converter with options
      const converter = new QuillDeltaToHtmlConverter(delta.ops, {inlineStyles: styleOptions});

      // Custom Blot Handler
      converter.renderCustomWith((customOp) => {
        // Conditionally renders blot of mention type
        if(customOp.insert.type === 'mention'){
          // Get Mention Blot Data
          const mention = customOp.insert.value;

          // Template Return Data
          return (
            `<span
            class="mention"
            data-index="${mention.index}"
            data-denotation-char="${mention.denotationChar}"
            data-link="${mention.link}"
            data-value='${mention.value}'>
            <span contenteditable="false">
            ${mention.value}
            </span>
            </span>`
          )
        }
      })

      // Return Converted Delta's HTML
      return converter.convert();
    }

Quill Module

    const qFontSize = Quill.import('attributors/style/size');

    qFontSize.whitelist = FONT_SIZES;

    Quill.register(qFontSize, true);

    // Initialize the Quill Editor to the DOM Element
    this.editor = new Quill('#editor', quillConfig);

An method to just get `groupListsNested` from the convert method

I'm planning to use quill-delta-to-html in react native, and I'd like to render the delta ops into react native views.

Would you consider adding a method getGroupListsNested() so that I can loop groupListsNested myself to render the ops into react native views?

Example in QuillDeltaToHtmlConverter.ts

   getGroupListsNested(){
       var deltaOps = InsertOpsConverter.convert(this.rawDeltaOps);
       var pairedOps = Grouper.pairOpsWithTheirBlock(deltaOps);
       var groupedSameStyleBlocks = Grouper.groupConsecutiveSameStyleBlocks(pairedOps, {
           blockquotes: !!this.options.multiLineBlockquote,
           header: !!this.options.multiLineHeader,
           codeBlocks: !!this.options.multiLineCodeblock
       });
       var groupedOps = Grouper.reduceConsecutiveSameStyleBlocksToOne(groupedSameStyleBlocks);
       var listNester = new ListNester();
       var groupListsNested = listNester.nest(groupedOps);
       return groupListsNested
   }
   

   convert() {
      var groupListsNested = this.getGroupListsNested();
      var len = groupListsNested.length;
      var group: TDataGroup, html;
      var htmlArr: string[] = [];

      for (var i = 0; i < len; i++) {
         group = groupListsNested[i];

         if (group instanceof ListGroup) {

            html = this.renderWithCallbacks(
               GroupType.List, group, () => this.renderList(<ListGroup>group));

         } else if (group instanceof BlockGroup) {

            var g = <BlockGroup>group;

            html = this.renderWithCallbacks(
               GroupType.Block, group, () => this.renderBlock(g.op, g.ops));

         } else if (group instanceof VideoItem) {

            html = this.renderWithCallbacks(GroupType.Video, group, () => {
               var g = <VideoItem>group;
               var converter = new OpToHtmlConverter(g.op, this.converterOptions);
               return converter.getHtml();
            });

         } else { // InlineGroup
            html = this.renderWithCallbacks(GroupType.InlineGroup, group, () => {
               return this.renderInlines((<InlineGroup>group).ops);
            });
         }
         htmlArr.push(html);
      }

      return htmlArr.join('');
   }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.