draftjs_html 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 007b3fd847f3459f78a1a8d93b04f7483a30b885aef9413ade39f60de7e93651
4
+ data.tar.gz: b6a44a4f153ff355937e362474e2700b216101a06f610a772a8230908ac7598e
5
+ SHA512:
6
+ metadata.gz: 34b4e47439bbdb80e0a033ea98ebfab2ebfae8cce677df6c8b3e60f5e924fe470c289b7f56f23067087f449443a0047dbdea243190d865786232d11d05df8e29
7
+ data.tar.gz: d3e28487c9700f2beacbb092ead7391e8f7e7e680531cc343978f8b3b0fe7c302a5d07c87ea981da01b84d51bac210b151b561c5f4330e934aabbf719be0c659
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at dugancathal@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in draftjs_html.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 TJ Taylor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # DraftjsHtml
2
+
3
+ This gem provides conversion utilities between "raw" [DraftJS] JSON and HTML.
4
+ My team and I have found a need on many occasions to manipulate and convert
5
+ DraftJS on our Ruby backend - this library is the result.
6
+
7
+ [DraftJS]: https://draftjs.org/
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby gem 'draftjs_html' ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install draftjs_html
22
+
23
+ ## Usage
24
+
25
+ This gem aims to provide a very high-level API for conversion. The most
26
+ basic usage is:
27
+
28
+ ```ruby
29
+ raw_draftjs = { 'blocks' => [{ 'text' => 'Hello world!' }], 'entityMap' => {} }
30
+ DraftjsHtml.to_html(raw_draftjs) # => <p>Hello world!</p>
31
+ ```
32
+
33
+ Things can get more complicated as you have custom entities and/or inline
34
+ styles. If this is the case, you can supply various configuration options
35
+ to the top-level conversion method(s) for describing how to translate your
36
+ content. One example might look like:
37
+
38
+ ```ruby
39
+ raw_draftjs = {
40
+ 'blocks' => [
41
+ {
42
+ 'text' => 'Hello @Arya!',
43
+ 'entityRanges' => [{ 'key' => 'abc', 'offset' => 6, 'length' => 5 }],
44
+ }
45
+ ],
46
+ 'entityMap' => {
47
+ 'abc' => {
48
+ 'mutability' => 'IMMUTABLE',
49
+ 'type' => 'mention',
50
+ 'data' => {
51
+ 'user_id' => 123
52
+ },
53
+ },
54
+ },
55
+ }
56
+
57
+ DraftjsHtml.to_html(raw_draftjs, {
58
+ entity_style_mappings: {
59
+ link: ->(entity, content) {
60
+ %Q{<a href="#{entity.data['url']}">#{content}</a>}
61
+ },
62
+ },
63
+ }) # => <p>Hello </p>
64
+ ```
65
+
66
+ Almost all of the options support Procs (or otherwise `.call`-ables) to provide
67
+ flexibility in the conversion process. As the library uses Nokogiri to generate
68
+ HTML, it's also possible to return `Nokogiri::Node` objects or String objects.
69
+
70
+ ## Development
71
+
72
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
73
+ `rake spec` to run the tests. You can also run `bin/console` for an interactive
74
+ prompt that will allow you to experiment.
75
+
76
+ To install this gem onto your local machine, run `bundle exec rake install`. To
77
+ release a new version, update the version number in `version.rb`, and then run
78
+ `bundle exec rake release`, which will create a git tag for the version, push
79
+ git commits and the created tag, and push the `.gem` file to
80
+ [rubygems.org](https://rubygems.org).
81
+
82
+ ## Contributing
83
+
84
+ Bug reports and pull requests are welcome on GitHub at
85
+ https://github.com/dugancathal/draftjs_html. This project is intended to be a
86
+ safe, welcoming space for collaboration, and contributors are expected to adhere
87
+ to the [code of
88
+ conduct](https://github.com/dugancathal/draftjs_html/blob/main/CODE_OF_CONDUCT.md).
89
+
90
+ ## License
91
+
92
+ The gem is available as open source under the terms of the [MIT
93
+ License](https://opensource.org/licenses/MIT).
94
+
95
+ ## Code of Conduct
96
+
97
+ Everyone interacting in the DraftjsHtml project's codebases, issue trackers,
98
+ chat rooms and mailing lists is expected to follow the [code of
99
+ conduct](https://github.com/dugancathal/draftjs_html/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: %i[spec]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "draftjs_html"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/draftjs_html/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "draftjs_html"
7
+ spec.version = DraftjsHtml::VERSION
8
+ spec.authors = ["TJ Taylor"]
9
+ spec.email = ["dugancathal@gmail.com"]
10
+
11
+ spec.summary = "A tool for converting DraftJS JSON to HTML (and back again)"
12
+ spec.description = "A tool for converting DraftJS JSON to HTML (and back again)"
13
+ spec.homepage = "https://github.com/dugancathal/draftjs_html"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = "#{spec.homepage}/tree/main/CHANGELOG.md"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
25
+ end
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_dependency "nokogiri", "~> 1.13"
31
+ spec.add_development_dependency "rspec", "~> 3.0"
32
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DraftjsHtml
4
+ module Draftjs
5
+ ApplicableRange = Struct.new(:name, :range, keyword_init: true) do
6
+ def self.parse(name, raw)
7
+ new(name: name, range: (raw['offset']..(raw['offset'] + raw['length'] - 1)))
8
+ end
9
+
10
+ def offset
11
+ range.begin
12
+ end
13
+
14
+ def length
15
+ range.size
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DraftjsHtml
4
+ module Draftjs
5
+ Block = Struct.new(:key, :text, :type, :inline_style_ranges, :raw_entity_ranges, keyword_init: true) do
6
+ def self.parse(raw)
7
+ new(
8
+ key: raw['key'],
9
+ text: raw['text'],
10
+ type: raw['type'],
11
+ inline_style_ranges: Array(raw['inlineStyleRanges']),
12
+ raw_entity_ranges: Array(raw['entityRanges']),
13
+ )
14
+ end
15
+
16
+ def length
17
+ text.length
18
+ end
19
+
20
+ def each_char
21
+ return to_enum(:each_char) unless block_given?
22
+
23
+ text.chars.map.with_index do |char, index|
24
+ yield CharacterMeta.new(
25
+ char: char,
26
+ style_names: inline_styles.select { _1.range.cover?(index) }.map(&:name),
27
+ entity_key: entity_ranges.select { _1.range.cover?(index) }.map(&:name).first,
28
+ )
29
+ end
30
+ end
31
+
32
+ CharRange = Struct.new(:text, :style_names, :entity_key, keyword_init: true)
33
+ def each_range
34
+ return to_enum(:each_range) unless block_given?
35
+
36
+ current_styles = []
37
+ current_entity = nil
38
+ ranges = [CharRange.new(text: '', style_names: current_styles, entity_key: current_entity)]
39
+
40
+ each_char.with_index do |char, index|
41
+ if char.style_names != current_styles || char.entity_key != current_entity
42
+ current_styles = char.style_names
43
+ current_entity = char.entity_key
44
+ yield(ranges.last) unless index == 0
45
+ ranges << CharRange.new(text: '', style_names: current_styles, entity_key: current_entity)
46
+ end
47
+
48
+ ranges.last.text += char.char
49
+ end
50
+
51
+ yield ranges.last
52
+ end
53
+
54
+ alias plaintext text
55
+
56
+ def inline_styles
57
+ @inline_styles ||= inline_style_ranges.map do |raw|
58
+ ApplicableRange.parse(raw['style'], raw)
59
+ end
60
+ end
61
+
62
+ def entity_ranges
63
+ @entity_ranges ||= raw_entity_ranges.map do |raw|
64
+ ApplicableRange.parse(raw['key'], raw)
65
+ end
66
+ end
67
+
68
+ def add_style(name, range)
69
+ inline_styles << ApplicableRange.new(name: name, range: range)
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DraftjsHtml
4
+ module Draftjs
5
+ CharacterMeta = Struct.new(:char, :style_names, :entity_key, keyword_init: true)
6
+ end
7
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DraftjsHtml
4
+ module Draftjs
5
+ class Content
6
+ def self.parse(raw)
7
+ new(raw['blocks'].map { Block.parse(**_1) }, EntityMap.parse(raw['entityMap']))
8
+ end
9
+
10
+ attr_reader :blocks, :entity_map
11
+
12
+ def initialize(blocks, entity_map)
13
+ @blocks = blocks
14
+ @entity_map = entity_map
15
+ end
16
+
17
+ def find_entity(key)
18
+ entity_map[key]
19
+ end
20
+
21
+ def to_raw
22
+ ToRaw.new.convert(self)
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DraftjsHtml
4
+ module Draftjs
5
+ Entity = Struct.new(:type, :mutability, :data, keyword_init: true) do
6
+ def self.parse(raw)
7
+ new(
8
+ type: raw['type'],
9
+ mutability: raw['mutability'],
10
+ data: raw['data'],
11
+ )
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DraftjsHtml
4
+ module Draftjs
5
+ class EntityMap < Hash
6
+ def self.parse(raw)
7
+ instance = new
8
+ raw.each { |key, raw_entity| instance[key] = Entity.parse(raw_entity) }
9
+ instance
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DraftjsHtml
4
+ module Draftjs
5
+ class ToRaw
6
+ def convert(parsed)
7
+ {
8
+ 'blocks' => parsed.blocks.map(&method(:convert_block)),
9
+ 'entityMap' => convert_entity_map(parsed.entity_map),
10
+ }
11
+ end
12
+
13
+ private
14
+
15
+ def convert_block(block)
16
+ {
17
+ 'text' => block.text,
18
+ 'type' => block.type,
19
+ 'inlineStyleRanges' => block.inline_styles.map { { 'style' => _1.name, 'offset' => _1.offset, 'length' => _1.length } },
20
+ 'entityRanges' => block.entity_ranges.map { { 'key' => _1.name, 'offset' => _1.offset, 'length' => _1.length } },
21
+ }
22
+ end
23
+
24
+ def convert_entity_map(entity_map)
25
+ entity_map.each_with_object({}) do |(key, entity), h|
26
+ h[key] = {
27
+ 'type' => entity.type,
28
+ 'mutability' => entity.mutability,
29
+ 'data' => entity.data,
30
+ }
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'draftjs/content'
4
+ require_relative 'draftjs/character_meta'
5
+ require_relative 'draftjs/applicable_range'
6
+ require_relative 'draftjs/block'
7
+ require_relative 'draftjs/entity_map'
8
+ require_relative 'draftjs/entity'
9
+ require_relative 'draftjs/to_raw'
10
+
11
+ module DraftjsHtml
12
+ module Draftjs
13
+ def self.parse(raw)
14
+ Content.parse(raw)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,146 @@
1
+ module DraftjsHtml
2
+ class ToHtml
3
+ BLOCK_TYPE_TO_HTML = {
4
+ 'unstyled' => 'p',
5
+ 'paragraph' => 'p',
6
+ 'header-one' => 'h1',
7
+ 'header-two' => 'h2',
8
+ 'header-three' => 'h3',
9
+ 'header-four' => 'h4',
10
+ 'header-five' => 'h5',
11
+ 'header-six' => 'h6',
12
+ 'blockquote' => 'blockquote',
13
+ 'code-block' => 'code',
14
+ 'ordered-list-item' => 'li',
15
+ 'unordered-list-item' => 'li',
16
+ 'atomic' => 'figure',
17
+ }.freeze
18
+ BLOCK_TYPE_TO_HTML_WRAPPER = {
19
+ 'code-block' => 'pre',
20
+ 'ordered-list-item' => 'ol',
21
+ 'unordered-list-item' => 'ul',
22
+ }.freeze
23
+ STYLE_MAP = {
24
+ 'BOLD' => 'b',
25
+ 'ITALIC' => 'i',
26
+ 'STRIKETHROUGH' => 'del',
27
+ 'UNDERLINE' => 'u',
28
+ }.freeze
29
+
30
+ DEFAULT_ENTITY_STYLE_FN = ->(_entity, chars) { chars }
31
+ ENTITY_ATTRIBUTE_NAME_MAP = {
32
+ 'className' => 'class',
33
+ 'url' => 'href',
34
+ }.freeze
35
+ ENTITY_CONVERSION_MAP = {
36
+ 'LINK' => ->(entity, content) {
37
+ node = Nokogiri::HTML::DocumentFragment.parse('<a>').children.first
38
+ node.content = content
39
+ entity.data.slice('url', 'rel', 'target', 'title', 'className').each do |attr, value|
40
+ node[ENTITY_ATTRIBUTE_NAME_MAP.fetch(attr, attr)] = value
41
+ end
42
+
43
+ node
44
+ },
45
+ 'IMAGE' => ->(entity, _content) {
46
+ node = Nokogiri::HTML::DocumentFragment.parse('<img>').children.first
47
+ entity.data.slice('src', 'alt', 'className', 'width', 'height').each do |attr, value|
48
+ node[ENTITY_ATTRIBUTE_NAME_MAP.fetch(attr, attr)] = value
49
+ end
50
+
51
+ node
52
+ }
53
+ }.freeze
54
+
55
+ def initialize(options)
56
+ @document = Nokogiri::HTML::Builder.new
57
+ @options = ensure_options!(options)
58
+ end
59
+
60
+ def convert(raw_draftjs)
61
+ draftjs = Draftjs.parse(raw_draftjs)
62
+
63
+ @document.html do |html|
64
+ html.body do |body|
65
+ @previous_parent = body.parent
66
+
67
+ draftjs.blocks.each do |block|
68
+ ensure_nesting_depth(block, body)
69
+
70
+ body.public_send(block_element_for(block)) do |block_body|
71
+ block.each_range do |char_range|
72
+ content = try_apply_entity_to(draftjs, char_range)
73
+
74
+ apply_styles_to(block_body, char_range.style_names, content)
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
80
+
81
+ @document.doc.css('body').first.children.to_html.strip
82
+ end
83
+
84
+ private
85
+
86
+ def ensure_nesting_depth(block, body)
87
+ new_wrapper_tag = BLOCK_TYPE_TO_HTML_WRAPPER[block.type]
88
+ if body.parent.name != new_wrapper_tag
89
+ if new_wrapper_tag
90
+ push_nesting(body, new_wrapper_tag)
91
+ else
92
+ pop_nesting(body)
93
+ end
94
+ end
95
+ end
96
+
97
+ def apply_styles_to(html, style_names, text)
98
+ return html.parent << text if style_names.empty?
99
+
100
+ custom_render_content = @options[:inline_style_renderer].call(style_names, text)
101
+ return html.parent << custom_render_content if custom_render_content
102
+
103
+ style, *rest = style_names
104
+ html.public_send(style_element_for(style)) do
105
+ apply_styles_to(html, rest, text)
106
+ end
107
+ end
108
+
109
+ def block_element_for(block)
110
+ @options[:block_type_mapping].fetch(block.type)
111
+ end
112
+
113
+ def style_element_for(style)
114
+ @options[:inline_style_mapping][style]
115
+ end
116
+
117
+ def try_apply_entity_to(draftjs, char_range)
118
+ entity = draftjs.find_entity(char_range.entity_key)
119
+ content = char_range.text
120
+ content = (@options[:entity_style_mappings][entity.type] || DEFAULT_ENTITY_STYLE_FN).call(entity, content) if entity
121
+ content
122
+ end
123
+
124
+ def push_nesting(builder, tagname)
125
+ node = create_child(builder, tagname)
126
+ @previous_parent = builder.parent
127
+ builder.parent = node
128
+ end
129
+
130
+ def pop_nesting(builder)
131
+ builder.parent = @previous_parent
132
+ end
133
+
134
+ def create_child(builder, tagname)
135
+ builder.parent.add_child(builder.doc.create_element(tagname))
136
+ end
137
+
138
+ def ensure_options!(opts)
139
+ opts[:entity_style_mappings] = ENTITY_CONVERSION_MAP.merge(opts[:entity_style_mappings] || {}).transform_keys(&:to_s)
140
+ opts[:block_type_mapping] = BLOCK_TYPE_TO_HTML.merge(opts[:block_type_mapping] || {})
141
+ opts[:inline_style_mapping] = STYLE_MAP.merge(opts[:inline_style_mapping] || {}).transform_keys(&:to_s)
142
+ opts[:inline_style_renderer] ||= ->(*) { nil }
143
+ opts
144
+ end
145
+ end
146
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DraftjsHtml
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "draftjs_html/version"
4
+ require 'nokogiri'
5
+ require_relative 'draftjs_html/draftjs'
6
+ require_relative 'draftjs_html/to_html'
7
+
8
+ module DraftjsHtml
9
+ class Error < StandardError; end
10
+
11
+ def self.to_html(raw_draftjs, options: {})
12
+ ToHtml.new(options).convert(raw_draftjs)
13
+ end
14
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: draftjs_html
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - TJ Taylor
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-09-30 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: nokogiri
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.13'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.13'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.0'
41
+ description: A tool for converting DraftJS JSON to HTML (and back again)
42
+ email:
43
+ - dugancathal@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".gitignore"
49
+ - ".rspec"
50
+ - CODE_OF_CONDUCT.md
51
+ - Gemfile
52
+ - LICENSE.txt
53
+ - README.md
54
+ - Rakefile
55
+ - bin/console
56
+ - bin/setup
57
+ - draftjs_html.gemspec
58
+ - lib/draftjs_html.rb
59
+ - lib/draftjs_html/draftjs.rb
60
+ - lib/draftjs_html/draftjs/applicable_range.rb
61
+ - lib/draftjs_html/draftjs/block.rb
62
+ - lib/draftjs_html/draftjs/character_meta.rb
63
+ - lib/draftjs_html/draftjs/content.rb
64
+ - lib/draftjs_html/draftjs/entity.rb
65
+ - lib/draftjs_html/draftjs/entity_map.rb
66
+ - lib/draftjs_html/draftjs/to_raw.rb
67
+ - lib/draftjs_html/to_html.rb
68
+ - lib/draftjs_html/version.rb
69
+ homepage: https://github.com/dugancathal/draftjs_html
70
+ licenses:
71
+ - MIT
72
+ metadata:
73
+ homepage_uri: https://github.com/dugancathal/draftjs_html
74
+ source_code_uri: https://github.com/dugancathal/draftjs_html
75
+ changelog_uri: https://github.com/dugancathal/draftjs_html/tree/main/CHANGELOG.md
76
+ post_install_message:
77
+ rdoc_options: []
78
+ require_paths:
79
+ - lib
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: 2.4.0
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ requirements: []
91
+ rubygems_version: 3.1.6
92
+ signing_key:
93
+ specification_version: 4
94
+ summary: A tool for converting DraftJS JSON to HTML (and back again)
95
+ test_files: []