├── .babelrc ├── .circleci └── config.yml ├── .editorconfig ├── .eslintignore ├── .eslintrc ├── .flowconfig ├── .gitignore ├── LICENSE.md ├── README.md ├── __setup__ └── enzyme.js ├── example ├── .babelrc ├── .eslintrc ├── .flowconfig ├── .gitignore ├── .watchmanconfig ├── App.js ├── README.md ├── app.json ├── package.json ├── rn-cli.config.js └── yarn.lock ├── issue_template.md ├── package.json ├── src ├── index.js ├── renderers │ ├── block-renderer.js │ ├── html-renderer.js │ ├── iframe-renderer.js │ ├── image-renderer.js │ ├── list-renderer.js │ └── text-renderer.js └── utils │ ├── filter-styles.js │ ├── parse-html.js │ └── render-native.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["react-native"] 3 | } 4 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | defaults: &defaults 4 | docker: 5 | - image: circleci/node:7.10 6 | working_directory: ~/project 7 | 8 | jobs: 9 | install-dependencies: 10 | <<: *defaults 11 | steps: 12 | - checkout 13 | - attach_workspace: 14 | at: ~/project 15 | - restore_cache: 16 | keys: 17 | - v1-dependencies-{{ checksum "package.json" }} 18 | - v1-dependencies- 19 | - restore_cache: 20 | keys: 21 | - v1-dependencies-example-{{ checksum "example/package.json" }} 22 | - v1-dependencies-example- 23 | - run: | 24 | yarn install 25 | cd example; yarn install; cd .. 26 | - save_cache: 27 | key: v1-dependencies-{{ checksum "package.json" }} 28 | paths: node_modules 29 | - save_cache: 30 | key: v1-dependencies-example-{{ checksum "example/package.json" }} 31 | paths: example/node_modules 32 | - persist_to_workspace: 33 | root: . 34 | paths: . 35 | lint-and-flow: 36 | <<: *defaults 37 | steps: 38 | - attach_workspace: 39 | at: ~/project 40 | - run: | 41 | yarn run lint 42 | yarn run flow 43 | unit-tests: 44 | <<: *defaults 45 | steps: 46 | - attach_workspace: 47 | at: ~/project 48 | - run: yarn test -- --coverage 49 | - store_artifacts: 50 | path: coverage 51 | destination: coverage 52 | 53 | workflows: 54 | version: 2 55 | build-and-test: 56 | jobs: 57 | - install-dependencies 58 | - lint-and-flow: 59 | requires: 60 | - install-dependencies 61 | - unit-tests: 62 | requires: 63 | - install-dependencies 64 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | 8 | [*] 9 | 10 | # change these settings to your own preference 11 | indent_style = space 12 | indent_size = 2 13 | 14 | # we recommend you to keep these unchanged 15 | end_of_line = lf 16 | charset = utf-8 17 | trim_trailing_whitespace = true 18 | insert_final_newline = true 19 | 20 | [*.md] 21 | trim_trailing_whitespace = false 22 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | flow-typed/ 3 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "plugins": ["react", "react-native", "flowtype", "prettier", "standard"], 4 | "parserOptions": { 5 | "sourceType": "module", 6 | "ecmaFeatures": { 7 | "jsx": true, 8 | "modules": true 9 | } 10 | }, 11 | "extends": [ 12 | "eslint:recommended", 13 | "airbnb-base", 14 | "airbnb", 15 | "plugin:flowtype/recommended", 16 | "plugin:react/recommended", 17 | "prettier", 18 | "prettier/flowtype", 19 | "prettier/react", 20 | "prettier/standard" 21 | ], 22 | "rules": { 23 | "max-len": ["error", { "code": 100, "ignoreUrls": true }], 24 | "arrow-body-style": "warn", 25 | "no-return-assign": "off", 26 | "class-methods-use-this": "off", 27 | "global-require": "off", 28 | "jsx-a11y/href-no-hash": "off", 29 | "react/display-name": "off", 30 | "react/require-default-props": "off", 31 | "react/jsx-filename-extension": [ 32 | "warn", 33 | { 34 | "extensions": [".js", ".jsx"] 35 | } 36 | ], 37 | "react/forbid-prop-types": "off", 38 | "no-multiple-empty-lines": [ 39 | "warn", 40 | { 41 | "max": 1 42 | } 43 | ], 44 | "react-native/no-unused-styles": 2, 45 | "react-native/split-platform-components": 0, 46 | "react-native/no-inline-styles": 2, 47 | "react-native/no-color-literals": 2, 48 | "no-use-before-define": 0, 49 | "prettier/prettier": "error", 50 | "no-plusplus": [2, { 51 | "allowForLoopAfterthoughts": true 52 | }] 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ; We fork some components by platform 3 | .*/*[.]android.js 4 | 5 | ; Ignore templates for 'react-native init' 6 | .*/local-cli/templates/.* 7 | 8 | ; Ignore the website subdir 9 | /website/.* 10 | 11 | ; Ignore "BUCK" generated dirs 12 | /\.buckd/ 13 | 14 | ; Ignore unexpected extra "@providesModule" 15 | .*/node_modules/.*/node_modules/fbjs/.* 16 | 17 | ; Ignore duplicate module providers 18 | ; For RN Apps installed via npm, "Libraries" folder is inside 19 | ; "node_modules/react-native" but in the source repo it is in the root 20 | .*/Libraries/react-native/React.js 21 | .*/Libraries/react-native/ReactNative.js 22 | 23 | ; Ignore duplicate modules under example/ 24 | .*/example/node_modules/fbjs 25 | .*/example/node_modules/fbemitter 26 | .*/example/node_modules/react 27 | .*/example/node_modules/react-native 28 | .*/example/node_modules/expo 29 | .*/example/node_modules/xdl 30 | .*/example/node_modules/reqwest 31 | .*/example/\.buckd/ 32 | 33 | .*/node_modules/react-native-gesture-handler 34 | 35 | [include] 36 | 37 | [libs] 38 | node_modules/react-native/Libraries/react-native/react-native-interface.js 39 | node_modules/react-native/flow 40 | 41 | [options] 42 | emoji=true 43 | 44 | module.system=haste 45 | 46 | experimental.strict_type_args=true 47 | 48 | munge_underscores=true 49 | 50 | module.name_mapper='^react-native-jumbo-html$' -> '/src' 51 | 52 | module.name_mapper='^expo$' -> 'emptyObject' 53 | module.name_mapper='^react-native-gesture-handler$' -> 'emptyObject' 54 | 55 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub' 56 | 57 | suppress_type=$FlowIssue 58 | suppress_type=$FlowFixMe 59 | suppress_type=$FlowFixMeProps 60 | suppress_type=$FlowFixMeState 61 | suppress_type=$FixMe 62 | 63 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(5[0-6]\\|[1-4][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*[react_native_oss|react_native_fb][a-z,_]*\\)?)\\) 64 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(5[0-6]\\|[1-4][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*[react_native_oss|react_native_fb][a-z,_]*\\)?)\\)?:? #[0-9]+ 65 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy 66 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError 67 | 68 | unsafe.enable_getters_and_setters=true 69 | 70 | [version] 71 | ^0.56.0 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | tsconfig.json 11 | jsconfig.json 12 | 13 | # Xcode 14 | # 15 | build/ 16 | *.pbxuser 17 | !default.pbxuser 18 | *.mode1v3 19 | !default.mode1v3 20 | *.mode2v3 21 | !default.mode2v3 22 | *.perspectivev3 23 | !default.perspectivev3 24 | xcuserdata 25 | *.xccheckout 26 | *.moved-aside 27 | DerivedData 28 | *.hmap 29 | *.ipa 30 | *.xcuserstate 31 | project.xcworkspace 32 | 33 | # Android/IJ 34 | # 35 | .idea 36 | .gradle 37 | local.properties 38 | 39 | # node.js 40 | # 41 | node_modules/ 42 | npm-debug.log 43 | yarn-debug.log 44 | yarn-error.log 45 | 46 | # BUCK 47 | buck-out/ 48 | \.buckd/ 49 | android/app/libs 50 | android/keystores/debug.keystore 51 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 React Native Community 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 all 13 | 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 THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Native Jumbo HTML 🐘 2 | 3 | [![Build Status][build-badge]][build] 4 | [![Version][version-badge]][package] 5 | [![MIT License][license-badge]][license] 6 | 7 | Render HTML tags as React Native components. 8 | 9 | ## Features 10 | 11 | - Supports custom renderers for tags 12 | - Supports inline styles in HTML 13 | - Supports StyleSheet object with tag and class name based styles 14 | - Inbuilt renderers for various tags including images, iframes, list items etc. 15 | 16 | ## Installation 17 | 18 | ```sh 19 | yarn add react-native-jumbo-html 20 | ``` 21 | 22 | ## API 23 | 24 | ### `HTMLRenderer` 25 | 26 | React component which takes an HTML string and renders it as React Native components. 27 | 28 | #### Props 29 | 30 | - `html` - string containing the HTML to render 31 | - `mappings` - an object with mappings for tags to React components 32 | - `sheet` - an object with a style sheet, they keys can be tag name or class name selectors 33 | 34 | Each component in the `mappings` object will receive the following props: 35 | 36 | - `tagName` - name of the tag that's being rendered 37 | - `classList` - an array with the list of class names on the tag 38 | - `attrs` - an object with all the attributes of the tag 39 | - `style` - styles for the component 40 | - `children` - children elements for the component 41 | 42 | #### Example 43 | 44 | For quick working demo, use Expo app to preview the example: https://expo.io/@usrbowe2/jumbo-html 45 | 46 | ```js 47 | import * as React from 'react'; 48 | import { StyleSheet } from 'react-native'; 49 | import { HTMLRenderer } from 'react-native-jumbo-html'; 50 | import CustomImage from './CustomImage'; 51 | 52 | const html = ` 53 |

Hello world

54 | `; 55 | 56 | const mappings = { 57 | img: CustomImage 58 | }; 59 | 60 | export default function App() { 61 | return ( 62 | 67 | ); 68 | } 69 | 70 | const styles = StyleSheet.create({ 71 | a: { 72 | color: 'blue' 73 | }, 74 | '.red': { 75 | color: 'red' 76 | } 77 | }); 78 | ``` 79 | 80 | ### `RendererMappings` 81 | 82 | The default list of mappings. You can reuse the mappings when adding additional functionality and don't have to re-implement the components. 83 | 84 | ## Contributing 85 | 86 | While developing, you can run the [example app](/example/) to test your changes. 87 | 88 | Make sure your code passes Flow and ESLint. Run the following to verify: 89 | 90 | ```sh 91 | yarn run flow 92 | yarn run lint 93 | ``` 94 | 95 | To fix formatting errors, run the following: 96 | 97 | ```sh 98 | yarn run lint -- --fix 99 | ``` 100 | 101 | Remember to add tests for your change if possible. 102 | 103 | 104 | [build-badge]: https://img.shields.io/circleci/project/github/smartkarma/react-native-jumbo-html/master.svg?style=flat-square 105 | [build]: https://circleci.com/gh/smartkarma/react-native-jumbo-html 106 | [version-badge]: https://img.shields.io/npm/v/react-native-jumbo-html.svg?style=flat-square 107 | [package]: https://www.npmjs.com/package/react-native-jumbo-html 108 | [license-badge]: https://img.shields.io/npm/l/react-native-jumbo-html.svg?style=flat-square 109 | [license]: https://opensource.org/licenses/MIT 110 | -------------------------------------------------------------------------------- /__setup__/enzyme.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-extraneous-dependencies */ 2 | 3 | import Enzyme from "enzyme"; 4 | import Adapter from "enzyme-adapter-react-16"; 5 | 6 | Enzyme.configure({ adapter: new Adapter() }); 7 | -------------------------------------------------------------------------------- /example/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["babel-preset-expo"], 3 | "plugins": [ 4 | ["module-resolver", { 5 | "alias": { 6 | "react-native-jumbo-html": "../src" 7 | } 8 | }] 9 | ], 10 | "env": { 11 | "development": { 12 | "plugins": ["transform-react-jsx-source"] 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "settings": { 3 | "import/core-modules": [ "expo", "react-native-jumbo-html" ] 4 | }, 5 | 6 | "rules": { 7 | "react/prop-types": "off", 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /example/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ; We fork some components by platform 3 | .*/*[.]android.js 4 | 5 | ; Ignore templates for 'react-native init' 6 | /node_modules/react-native/local-cli/templates/.* 7 | 8 | ; Ignore RN jest 9 | /node_modules/react-native/jest/.* 10 | 11 | ; Ignore RNTester 12 | /node_modules/react-native/RNTester/.* 13 | 14 | ; Ignore the website subdir 15 | /node_modules/react-native/website/.* 16 | 17 | ; Ignore the Dangerfile 18 | /node_modules/react-native/danger/dangerfile.js 19 | 20 | ; Ignore Fbemitter 21 | /node_modules/fbemitter/.* 22 | 23 | ; Ignore "BUCK" generated dirs 24 | /node_modules/react-native/\.buckd/ 25 | 26 | ; Ignore unexpected extra "@providesModule" 27 | .*/node_modules/.*/node_modules/fbjs/.* 28 | 29 | ; Ignore polyfills 30 | /node_modules/react-native/Libraries/polyfills/.* 31 | 32 | ; Ignore various node_modules 33 | /node_modules/react-native-gesture-handler/.* 34 | /node_modules/expo/.* 35 | /node_modules/react-navigation/.* 36 | /node_modules/xdl/.* 37 | /node_modules/reqwest/.* 38 | /node_modules/metro-bundler/.* 39 | 40 | [include] 41 | 42 | [libs] 43 | node_modules/react-native/Libraries/react-native/react-native-interface.js 44 | node_modules/react-native/flow/ 45 | node_modules/expo/flow/ 46 | 47 | [options] 48 | emoji=true 49 | 50 | module.system=haste 51 | 52 | module.file_ext=.js 53 | module.file_ext=.jsx 54 | module.file_ext=.json 55 | module.file_ext=.ios.js 56 | 57 | munge_underscores=true 58 | 59 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub' 60 | 61 | suppress_type=$FlowIssue 62 | suppress_type=$FlowFixMe 63 | suppress_type=$FlowFixMeProps 64 | suppress_type=$FlowFixMeState 65 | suppress_type=$FixMe 66 | 67 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(5[0-6]\\|[1-4][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native_oss[a-z,_]*\\)?)\\) 68 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(5[0-6]\\|[1-4][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native_oss[a-z,_]*\\)?)\\)?:? #[0-9]+ 69 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy 70 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError 71 | 72 | unsafe.enable_getters_and_setters=true 73 | 74 | [version] 75 | ^0.56.0 76 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # expo 4 | .expo/ 5 | 6 | # dependencies 7 | /node_modules 8 | 9 | # misc 10 | .env.local 11 | .env.development.local 12 | .env.test.local 13 | .env.production.local 14 | 15 | npm-debug.log* 16 | yarn-debug.log* 17 | yarn-error.log* 18 | -------------------------------------------------------------------------------- /example/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /example/App.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | /* eslint-disable max-len */ 3 | 4 | import React from "react"; 5 | import { StyleSheet, ScrollView, Linking } from "react-native"; 6 | import { Constants } from "expo"; 7 | import { HTMLRenderer, RendererMappings } from "react-native-jumbo-html"; 8 | import type { RendererProps } from "react-native-jumbo-html"; 9 | 10 | const html = ` 11 |
12 |
13 |
14 |

h1 HTML5 Kitchen Sink

15 |

h2 Back in my quaint garden

16 |

h3 Jaunty zinnias vie with flaunting phlox

17 |

h4 Five or six big jet planes zoomed quickly by the new tower.

18 |
h5 Expect skilled signwriters to use many jazzy, quaint old alphabets effectively.
19 |
h6 Pack my box with five dozen liquor jugs.
20 |
21 |
22 |
23 |
24 |
25 | 32 |
33 |
34 |

This paragraph is nested inside an article. It contains many different, sometimes useful, HTML5 tags. Of course there are classics like emphasis, strong, and small but there are many others as well. Hover the following text for abbreviation tag: abbr. Similarly, you can use acronym tag like this: ftw. You can define deleted text which often gets replaced with inserted text.

35 |

You can also use keyboard text, which sometimes is styled similarly to the <code> or samp tags. Even more specifically, there is a tag just for variables. Not to be mistaken with blockquotes 36 | below, the quote tag lets you denote something as quoted text. Lastly don't forget the sub (H2O) and sup (E = MC2) tags.

37 |
38 |
39 |
40 |
41 |
42 |

Blockquote: I quickly explained that many big jobs involve few hazards

43 |
44 |
45 |

This is a mult-line blockquote with a cite reference. People think focus means saying yes to the thing you’ve got to focus on. But that’s not what it means at all. It means saying no to the hundred other good ideas that there are. You have to pick 46 | carefully. I’m actually as proud of the things we haven’tdone as the things I have done. Innovation is saying no to 1,000 things. 47 | Steve Jobs – Apple Worldwide Developers’ Conference, 1997 48 |

49 |
50 |
51 |
52 |
53 |
    54 |
  • Unordered List item one 55 |
      56 |
    • Nested list item 57 |
        58 |
      • Level 3, item one
      • 59 |
      • Level 3, item two
      • 60 |
      • Level 3, item three
      • 61 |
      • Level 3, item four
      • 62 |
      63 |
    • 64 |
    • List item two
    • 65 |
    • List item three
    • 66 |
    • List item four
    • 67 |
    68 |
  • 69 |
  • List item two
  • 70 |
  • List item three
  • 71 |
  • List item four
  • 72 |
73 |
74 |
    75 |
  1. List item one 76 |
      77 |
    1. List item one 78 |
        79 |
      1. List item one
      2. 80 |
      3. List item two
      4. 81 |
      5. List item three
      6. 82 |
      7. List item four
      8. 83 |
      84 |
    2. 85 |
    3. List item two
    4. 86 |
    5. List item three
    6. 87 |
    7. List item four
    8. 88 |
    89 |
  2. 90 |
  3. List item two
  4. 91 |
  5. List item three
  6. 92 |
  7. List item four
  8. 93 |
94 |
95 |
96 |
97 |
1 Infinite Loop
98 | Cupertino, CA 95014
99 | United States
100 |
101 |
102 |
103 |
104 | pre {
105 |   display: block;
106 |   padding: 7px;
107 |   background-color: #F5F5F5;
108 |   border: 1px solid #E1E1E8;
109 |   border-radius: 3px;
110 |   white-space: pre-wrap;
111 |   word-break: break-all;
112 |   font-family: Menlo, Monaco;
113 |   line-height: 160%;
114 | }
115 |
116 |
117 |
118 | 119 |
Fig1. A picture of Bill Murray from fillmurray.com
120 |
121 |
122 | `; 123 | 124 | const mappings = { 125 | a: function Anchor(props: RendererProps) { 126 | const Link = RendererMappings.a; 127 | return ( 128 | { 131 | if (props.attrs && props.attrs.href) { 132 | Linking.openURL(props.attrs.href); 133 | } 134 | }} 135 | /> 136 | ); 137 | } 138 | }; 139 | 140 | export default function App() { 141 | return ( 142 | 143 | 144 | 145 | ); 146 | } 147 | 148 | const styles = StyleSheet.create({ 149 | content: { 150 | padding: 16, 151 | paddingTop: Constants.statusBarHeight + 16 152 | } 153 | }); 154 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React Native App](https://github.com/react-community/create-react-native-app). 2 | 3 | Below you'll find information about performing common tasks. The most recent version of this guide is available [here](https://github.com/react-community/create-react-native-app/blob/master/react-native-scripts/template/README.md). 4 | 5 | ## Table of Contents 6 | 7 | * [Updating to New Releases](#updating-to-new-releases) 8 | * [Available Scripts](#available-scripts) 9 | * [npm start](#npm-start) 10 | * [npm test](#npm-test) 11 | * [npm run ios](#npm-run-ios) 12 | * [npm run android](#npm-run-android) 13 | * [npm run eject](#npm-run-eject) 14 | * [Writing and Running Tests](#writing-and-running-tests) 15 | * [Environment Variables](#environment-variables) 16 | * [Configuring Packager IP Address](#configuring-packager-ip-address) 17 | * [Adding Flow](#adding-flow) 18 | * [Customizing App Display Name and Icon](#customizing-app-display-name-and-icon) 19 | * [Sharing and Deployment](#sharing-and-deployment) 20 | * [Publishing to Expo's React Native Community](#publishing-to-expos-react-native-community) 21 | * [Building an Expo "standalone" app](#building-an-expo-standalone-app) 22 | * [Ejecting from Create React Native App](#ejecting-from-create-react-native-app) 23 | * [Build Dependencies (Xcode & Android Studio)](#build-dependencies-xcode-android-studio) 24 | * [Should I Use ExpoKit?](#should-i-use-expokit) 25 | * [Troubleshooting](#troubleshooting) 26 | * [Networking](#networking) 27 | * [iOS Simulator won't open](#ios-simulator-wont-open) 28 | * [QR Code does not scan](#qr-code-does-not-scan) 29 | 30 | ## Updating to New Releases 31 | 32 | You should only need to update the global installation of `create-react-native-app` very rarely, ideally never. 33 | 34 | Updating the `react-native-scripts` dependency of your app should be as simple as bumping the version number in `package.json` and reinstalling your project's dependencies. 35 | 36 | Upgrading to a new version of React Native requires updating the `react-native`, `react`, and `expo` package versions, and setting the correct `sdkVersion` in `app.json`. See the [versioning guide](https://github.com/react-community/create-react-native-app/blob/master/VERSIONS.md) for up-to-date information about package version compatibility. 37 | 38 | ## Available Scripts 39 | 40 | If Yarn was installed when the project was initialized, then dependencies will have been installed via Yarn, and you should probably use it to run these commands as well. Unlike dependency installation, command running syntax is identical for Yarn and NPM at the time of this writing. 41 | 42 | ### `npm start` 43 | 44 | Runs your app in development mode. 45 | 46 | Open it in the [Expo app](https://expo.io) on your phone to view it. It will reload if you save edits to your files, and you will see build errors and logs in the terminal. 47 | 48 | Sometimes you may need to reset or clear the React Native packager's cache. To do so, you can pass the `--reset-cache` flag to the start script: 49 | 50 | ``` 51 | npm start -- --reset-cache 52 | # or 53 | yarn start -- --reset-cache 54 | ``` 55 | 56 | #### `npm test` 57 | 58 | Runs the [jest](https://github.com/facebook/jest) test runner on your tests. 59 | 60 | #### `npm run ios` 61 | 62 | Like `npm start`, but also attempts to open your app in the iOS Simulator if you're on a Mac and have it installed. 63 | 64 | #### `npm run android` 65 | 66 | Like `npm start`, but also attempts to open your app on a connected Android device or emulator. Requires an installation of Android build tools (see [React Native docs](https://facebook.github.io/react-native/docs/getting-started.html) for detailed setup). We also recommend installing Genymotion as your Android emulator. Once you've finished setting up the native build environment, there are two options for making the right copy of `adb` available to Create React Native App: 67 | 68 | ##### Using Android Studio's `adb` 69 | 70 | 1. Make sure that you can run adb from your terminal. 71 | 2. Open Genymotion and navigate to `Settings -> ADB`. Select “Use custom Android SDK tools” and update with your [Android SDK directory](https://stackoverflow.com/questions/25176594/android-sdk-location). 72 | 73 | ##### Using Genymotion's `adb` 74 | 75 | 1. Find Genymotion’s copy of adb. On macOS for example, this is normally `/Applications/Genymotion.app/Contents/MacOS/tools/`. 76 | 2. Add the Genymotion tools directory to your path (instructions for [Mac](http://osxdaily.com/2014/08/14/add-new-path-to-path-command-line/), [Linux](http://www.computerhope.com/issues/ch001647.htm), and [Windows](https://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/)). 77 | 3. Make sure that you can run adb from your terminal. 78 | 79 | #### `npm run eject` 80 | 81 | This will start the process of "ejecting" from Create React Native App's build scripts. You'll be asked a couple of questions about how you'd like to build your project. 82 | 83 | **Warning:** Running eject is a permanent action (aside from whatever version control system you use). An ejected app will require you to have an [Xcode and/or Android Studio environment](https://facebook.github.io/react-native/docs/getting-started.html) set up. 84 | 85 | ## Customizing App Display Name and Icon 86 | 87 | You can edit `app.json` to include [configuration keys](https://docs.expo.io/versions/latest/guides/configuration.html) under the `expo` key. 88 | 89 | To change your app's display name, set the `expo.name` key in `app.json` to an appropriate string. 90 | 91 | To set an app icon, set the `expo.icon` key in `app.json` to be either a local path or a URL. It's recommended that you use a 512x512 png file with transparency. 92 | 93 | ## Writing and Running Tests 94 | 95 | This project is set up to use [jest](https://facebook.github.io/jest/) for tests. You can configure whatever testing strategy you like, but jest works out of the box. Create test files in directories called `__tests__` or with the `.test` extension to have the files loaded by jest. See the [the template project](https://github.com/react-community/create-react-native-app/blob/master/react-native-scripts/template/App.test.js) for an example test. The [jest documentation](https://facebook.github.io/jest/docs/en/getting-started.html) is also a wonderful resource, as is the [React Native testing tutorial](https://facebook.github.io/jest/docs/en/tutorial-react-native.html). 96 | 97 | ## Environment Variables 98 | 99 | You can configure some of Create React Native App's behavior using environment variables. 100 | 101 | ### Configuring Packager IP Address 102 | 103 | When starting your project, you'll see something like this for your project URL: 104 | 105 | ``` 106 | exp://192.168.0.2:19000 107 | ``` 108 | 109 | The "manifest" at that URL tells the Expo app how to retrieve and load your app's JavaScript bundle, so even if you load it in the app via a URL like `exp://localhost:19000`, the Expo client app will still try to retrieve your app at the IP address that the start script provides. 110 | 111 | In some cases, this is less than ideal. This might be the case if you need to run your project inside of a virtual machine and you have to access the packager via a different IP address than the one which prints by default. In order to override the IP address or hostname that is detected by Create React Native App, you can specify your own hostname via the `REACT_NATIVE_PACKAGER_HOSTNAME` environment variable: 112 | 113 | Mac and Linux: 114 | 115 | ``` 116 | REACT_NATIVE_PACKAGER_HOSTNAME='my-custom-ip-address-or-hostname' npm start 117 | ``` 118 | 119 | Windows: 120 | ``` 121 | set REACT_NATIVE_PACKAGER_HOSTNAME='my-custom-ip-address-or-hostname' 122 | npm start 123 | ``` 124 | 125 | The above example would cause the development server to listen on `exp://my-custom-ip-address-or-hostname:19000`. 126 | 127 | ## Adding Flow 128 | 129 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 130 | 131 | React Native works with [Flow](http://flowtype.org/) out of the box, as long as your Flow version matches the one used in the version of React Native. 132 | 133 | To add a local dependency to the correct Flow version to a Create React Native App project, follow these steps: 134 | 135 | 1. Find the Flow `[version]` at the bottom of the included [.flowconfig](.flowconfig) 136 | 2. Run `npm install --save-dev flow-bin@x.y.z` (or `yarn add --dev flow-bin@x.y.z`), where `x.y.z` is the .flowconfig version number. 137 | 3. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 138 | 4. Add `// @flow` to any files you want to type check (for example, to `App.js`). 139 | 140 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 141 | You can optionally use a [plugin for your IDE or editor](https://flow.org/en/docs/editors/) for a better integrated experience. 142 | 143 | To learn more about Flow, check out [its documentation](https://flow.org/). 144 | 145 | ## Sharing and Deployment 146 | 147 | Create React Native App does a lot of work to make app setup and development simple and straightforward, but it's very difficult to do the same for deploying to Apple's App Store or Google's Play Store without relying on a hosted service. 148 | 149 | ### Publishing to Expo's React Native Community 150 | 151 | Expo provides free hosting for the JS-only apps created by CRNA, allowing you to share your app through the Expo client app. This requires registration for an Expo account. 152 | 153 | Install the `exp` command-line tool, and run the publish command: 154 | 155 | ``` 156 | $ npm i -g exp 157 | $ exp publish 158 | ``` 159 | 160 | ### Building an Expo "standalone" app 161 | 162 | You can also use a service like [Expo's standalone builds](https://docs.expo.io/versions/latest/guides/building-standalone-apps.html) if you want to get an IPA/APK for distribution without having to build the native code yourself. 163 | 164 | ### Ejecting from Create React Native App 165 | 166 | If you want to build and deploy your app yourself, you'll need to eject from CRNA and use Xcode and Android Studio. 167 | 168 | This is usually as simple as running `npm run eject` in your project, which will walk you through the process. Make sure to install `react-native-cli` and follow the [native code getting started guide for React Native](https://facebook.github.io/react-native/docs/getting-started.html). 169 | 170 | #### Should I Use ExpoKit? 171 | 172 | If you have made use of Expo APIs while working on your project, then those API calls will stop working if you eject to a regular React Native project. If you want to continue using those APIs, you can eject to "React Native + ExpoKit" which will still allow you to build your own native code and continue using the Expo APIs. See the [ejecting guide](https://github.com/react-community/create-react-native-app/blob/master/EJECTING.md) for more details about this option. 173 | 174 | ## Troubleshooting 175 | 176 | ### Networking 177 | 178 | If you're unable to load your app on your phone due to a network timeout or a refused connection, a good first step is to verify that your phone and computer are on the same network and that they can reach each other. Create React Native App needs access to ports 19000 and 19001 so ensure that your network and firewall settings allow access from your device to your computer on both of these ports. 179 | 180 | Try opening a web browser on your phone and opening the URL that the packager script prints, replacing `exp://` with `http://`. So, for example, if underneath the QR code in your terminal you see: 181 | 182 | ``` 183 | exp://192.168.0.1:19000 184 | ``` 185 | 186 | Try opening Safari or Chrome on your phone and loading 187 | 188 | ``` 189 | http://192.168.0.1:19000 190 | ``` 191 | 192 | and 193 | 194 | ``` 195 | http://192.168.0.1:19001 196 | ``` 197 | 198 | If this works, but you're still unable to load your app by scanning the QR code, please open an issue on the [Create React Native App repository](https://github.com/react-community/create-react-native-app) with details about these steps and any other error messages you may have received. 199 | 200 | If you're not able to load the `http` URL in your phone's web browser, try using the tethering/mobile hotspot feature on your phone (beware of data usage, though), connecting your computer to that WiFi network, and restarting the packager. 201 | 202 | ### iOS Simulator won't open 203 | 204 | If you're on a Mac, there are a few errors that users sometimes see when attempting to `npm run ios`: 205 | 206 | * "non-zero exit code: 107" 207 | * "You may need to install Xcode" but it is already installed 208 | * and others 209 | 210 | There are a few steps you may want to take to troubleshoot these kinds of errors: 211 | 212 | 1. Make sure Xcode is installed and open it to accept the license agreement if it prompts you. You can install it from the Mac App Store. 213 | 2. Open Xcode's Preferences, the Locations tab, and make sure that the `Command Line Tools` menu option is set to something. Sometimes when the CLI tools are first installed by Homebrew this option is left blank, which can prevent Apple utilities from finding the simulator. Make sure to re-run `npm/yarn run ios` after doing so. 214 | 3. If that doesn't work, open the Simulator, and under the app menu select `Reset Contents and Settings...`. After that has finished, quit the Simulator, and re-run `npm/yarn run ios`. 215 | 216 | ### QR Code does not scan 217 | 218 | If you're not able to scan the QR code, make sure your phone's camera is focusing correctly, and also make sure that the contrast on the two colors in your terminal is high enough. For example, WebStorm's default themes may [not have enough contrast](https://github.com/react-community/create-react-native-app/issues/49) for terminal QR codes to be scannable with the system barcode scanners that the Expo app uses. 219 | 220 | If this causes problems for you, you may want to try changing your terminal's color theme to have more contrast, or running Create React Native App from a different terminal. You can also manually enter the URL printed by the packager script in the Expo app's search bar to load it manually. 221 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "expo": { 3 | "sdkVersion": "23.0.0", 4 | "packagerOpts": { 5 | "config": "./rn-cli.config.js", 6 | "projectRoots": "" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-jumbo-html-example", 3 | "version": "0.1.0", 4 | "private": true, 5 | "devDependencies": { 6 | "babel-plugin-module-resolver": "^3.0.0", 7 | "collapse-whitespace": "^1.1.6", 8 | "css-to-react-native": "^2.0.4", 9 | "glob-to-regexp": "^0.3.0", 10 | "htmlclean": "^3.0.5", 11 | "htmlparser2-without-node-native": "^3.9.2", 12 | "jest-expo": "23.0.0", 13 | "prop-types": "^15.6.0", 14 | "react-native-scripts": "1.8.1", 15 | "react-test-renderer": "16.0.0" 16 | }, 17 | "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js", 18 | "scripts": { 19 | "start": "react-native-scripts start", 20 | "eject": "react-native-scripts eject", 21 | "android": "react-native-scripts android", 22 | "ios": "react-native-scripts ios", 23 | "test": "node node_modules/jest/bin/jest.js --watch" 24 | }, 25 | "jest": { 26 | "preset": "jest-expo" 27 | }, 28 | "dependencies": { 29 | "expo": "^23.0.4", 30 | "react": "16.0.0", 31 | "react-native": "0.50.3" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /example/rn-cli.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-commonjs, import/no-extraneous-dependencies */ 2 | 3 | const path = require("path"); 4 | const glob = require("glob-to-regexp"); 5 | const blacklist = require("metro-bundler/src/blacklist"); 6 | const pak = require("../package.json"); 7 | 8 | const dependencies = Object.keys(pak.dependencies); 9 | const peerDependencies = Object.keys(pak.peerDependencies); 10 | 11 | module.exports = { 12 | getProjectRoots() { 13 | return [__dirname, path.resolve(__dirname, "..")]; 14 | }, 15 | getProvidesModuleNodeModules() { 16 | return [...dependencies, ...peerDependencies]; 17 | }, 18 | getBlacklistRE() { 19 | return blacklist([ 20 | glob(`${path.resolve(__dirname, "..")}/node_modules/*`), 21 | glob(`${__dirname}/node_modules/*/{${dependencies.join(",")}}`, { 22 | extended: true 23 | }) 24 | ]); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /issue_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### Expected behaviour 4 | 5 | ### Actual behaviour 6 | 7 | ### Code sample, screenshots 8 | 9 | ### What have you tried 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-jumbo-html", 3 | "version": "0.1.0", 4 | "description": "Render HTML tags as React Native components", 5 | "main": "src/index.js", 6 | "files": [ 7 | "src/" 8 | ], 9 | "scripts": { 10 | "test": "jest", 11 | "flow": "flow", 12 | "lint": "eslint ." 13 | }, 14 | "keywords": [ 15 | "react-native-component", 16 | "react-component", 17 | "react-native", 18 | "ios", 19 | "android", 20 | "html" 21 | ], 22 | "repository": { 23 | "type": "git", 24 | "url": "git+https://github.com/smartkarma/react-native-jumbo-html.git" 25 | }, 26 | "author": "Satyajit Sahoo (https://github.com/satya164/)", 27 | "license": "MIT", 28 | "bugs": { 29 | "url": "https://github.com/smartkarma/react-native-jumbo-html/issues" 30 | }, 31 | "homepage": "https://github.com/smartkarma/react-native-jumbo-html#readme", 32 | "dependencies": { 33 | "collapse-whitespace": "^1.1.6", 34 | "css-to-react-native": "^2.0.4", 35 | "htmlclean": "^3.0.5", 36 | "htmlparser2-without-node-native": "^3.9.2", 37 | "prop-types": "^15.6.0" 38 | }, 39 | "devDependencies": { 40 | "babel-eslint": "^8.1.2", 41 | "babel-jest": "^21.2.0", 42 | "babel-preset-react-native": "^4.0.0", 43 | "enzyme": "3.2.0", 44 | "enzyme-adapter-react-16": "^1.1.0", 45 | "enzyme-to-json": "^3.2.2", 46 | "eslint": "^4.15.0", 47 | "eslint-config-airbnb": "^16.1.0", 48 | "eslint-config-airbnb-base": "^12.1.0", 49 | "eslint-config-prettier": "^2.9.0", 50 | "eslint-plugin-flowtype": "^2.41.0", 51 | "eslint-plugin-import": "^2.8.0", 52 | "eslint-plugin-jsx-a11y": "^6.0.3", 53 | "eslint-plugin-prettier": "^2.4.0", 54 | "eslint-plugin-react": "^7.5.1", 55 | "eslint-plugin-react-native": "^3.2.0", 56 | "eslint-plugin-standard": "^3.0.1", 57 | "flow-bin": "~0.56.0", 58 | "jest": "^21.2.1", 59 | "prettier": "^1.8.2", 60 | "react": "16.0.0", 61 | "react-dom": "16.0.0", 62 | "react-native": "~0.50.4", 63 | "react-test-renderer": "16.2.0" 64 | }, 65 | "peerDependencies": { 66 | "react": "*", 67 | "react-native": "*" 68 | }, 69 | "jest": { 70 | "preset": "react-native", 71 | "setupFiles": [ 72 | "/__setup__/enzyme.js" 73 | ], 74 | "modulePathIgnorePatterns": [ 75 | "/example/node_modules" 76 | ], 77 | "snapshotSerializers": [ 78 | "enzyme-to-json/serializer" 79 | ] 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | import type { RendererProps as _RendererProps } from "./utils/render-native"; 4 | 5 | export type RendererProps = _RendererProps; 6 | 7 | export { default as HTMLRenderer } from "./renderers/html-renderer"; 8 | export { mappings as RendererMappings } from "./utils/render-native"; 9 | -------------------------------------------------------------------------------- /src/renderers/block-renderer.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import * as React from "react"; 3 | import { View } from "react-native"; 4 | import PropTypes from "prop-types"; 5 | import ViewStylePropTypes from "react-native/Libraries/Components/View/ViewStylePropTypes"; 6 | import TextStylePropTypes from "react-native/Libraries/Text/TextStylePropTypes"; 7 | import TextRenderer from "./text-renderer"; 8 | import filterStyles from "../utils/filter-styles"; 9 | import { INLINE_TAGS } from "../utils/render-native"; 10 | import type { RendererProps } from "../utils/render-native"; 11 | 12 | const channel = ":root-text-styles"; 13 | 14 | export default class BlockRenderer extends React.PureComponent { 15 | static contextTypes = { 16 | [channel]: PropTypes.object 17 | }; 18 | 19 | render() { 20 | const { tagName, attrs, classList, style, children, ...rest } = this.props; 21 | 22 | // Split the styles to valid view and text styles 23 | // Pass down any text styles so that they are respected in nested elements 24 | const [viewStyles, textStyles] = filterStyles(style, [ 25 | ViewStylePropTypes, 26 | { ...TextStylePropTypes, textTransform: true } 27 | ]); 28 | 29 | // Get text styles from the context 30 | // This is useful to set global styles such as fonts 31 | const rootStyles = this.context[channel]; 32 | 33 | const isChildrenInline = React.Children.toArray(children).every( 34 | child => 35 | child 36 | ? typeof child === "string" || 37 | INLINE_TAGS.includes(child.props.tagName) 38 | : true 39 | ); 40 | 41 | return ( 42 | 43 | {isChildrenInline ? ( 44 | {children} 45 | ) : ( 46 | React.Children.map(children, child => { 47 | if (typeof child === "string") { 48 | // Since View cannot contain string, nest it in text renderer 49 | return {child}; 50 | } 51 | 52 | if (child) { 53 | return React.cloneElement(child, { 54 | style: [rootStyles, textStyles, child.props.style] 55 | }); 56 | } 57 | 58 | return child; 59 | }) 60 | )} 61 | 62 | ); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/renderers/html-renderer.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | /* eslint-disable react-native/no-unused-styles, react-native/no-color-literals */ 3 | 4 | import { PureComponent } from "react"; 5 | import PropTypes from "prop-types"; 6 | import { StyleSheet, Platform } from "react-native"; 7 | import TextStylePropTypes from "react-native/Libraries/Text/TextStylePropTypes"; 8 | import parseHTML from "../utils/parse-html"; 9 | import renderNative from "../utils/render-native"; 10 | import filterStyles from "../utils/filter-styles"; 11 | 12 | type Props = { 13 | html: string, 14 | mappings?: { [tag: string]: Function }, 15 | sheet?: Object 16 | }; 17 | 18 | const channel = ":root-text-styles"; 19 | 20 | export default class HTMLRenderer extends PureComponent { 21 | static childContextTypes = { 22 | [channel]: PropTypes.object 23 | }; 24 | 25 | getChildContext() { 26 | return { 27 | [channel]: this.getTextStyle() 28 | }; 29 | } 30 | 31 | getTextStyle = () => { 32 | if (this.textStyleCache) { 33 | return this.textStyleCache; 34 | } 35 | 36 | const style = 37 | // eslint-disable-next-line react/prop-types 38 | this.props.sheet && this.props.sheet[":root"] 39 | ? this.props.sheet[":root"] 40 | : null; 41 | 42 | if (style) { 43 | // eslint-disable-next-line prefer-destructuring 44 | this.textStyleCache = filterStyles(style, [TextStylePropTypes])[0]; 45 | return this.textStyleCache; 46 | } 47 | 48 | return null; 49 | }; 50 | 51 | textStyleCache = null; 52 | 53 | render() { 54 | const sheets = [styles]; 55 | 56 | if (this.props.sheet) { 57 | sheets.push(this.props.sheet); 58 | } 59 | 60 | return renderNative( 61 | parseHTML(this.props.html), 62 | this.props.mappings, 63 | sheets 64 | ); 65 | } 66 | } 67 | 68 | const MONOSPACE_FONT = Platform.OS === "ios" ? "Courier New" : "monospace"; 69 | 70 | const styles = StyleSheet.create({ 71 | h1: { 72 | fontWeight: "bold", 73 | fontSize: 28, 74 | lineHeight: 30, 75 | marginVertical: 12 76 | }, 77 | h2: { 78 | fontWeight: "bold", 79 | fontSize: 24, 80 | lineHeight: 26, 81 | marginVertical: 10 82 | }, 83 | h3: { 84 | fontWeight: "bold", 85 | fontSize: 22, 86 | lineHeight: 24, 87 | marginVertical: 8 88 | }, 89 | h4: { 90 | fontWeight: "bold", 91 | fontSize: 20, 92 | lineHeight: 22, 93 | marginVertical: 6 94 | }, 95 | h5: { 96 | fontWeight: "bold", 97 | fontSize: 18, 98 | lineHeight: 20, 99 | marginVertical: 4 100 | }, 101 | h6: { 102 | fontWeight: "bold", 103 | fontSize: 16, 104 | lineHeight: 18, 105 | marginVertical: 4 106 | }, 107 | p: { 108 | marginVertical: 8 109 | }, 110 | blockquote: { 111 | marginVertical: 8, 112 | paddingLeft: 8, 113 | borderLeftColor: "lightgrey", 114 | borderLeftWidth: 2, 115 | fontStyle: "italic" 116 | }, 117 | hr: { 118 | height: StyleSheet.hairlineWidth, 119 | backgroundColor: "lightgrey", 120 | marginVertical: 7 121 | }, 122 | pre: { 123 | fontFamily: MONOSPACE_FONT 124 | }, 125 | code: { 126 | fontFamily: MONOSPACE_FONT 127 | }, 128 | kbd: { 129 | fontFamily: MONOSPACE_FONT 130 | }, 131 | samp: { 132 | fontFamily: MONOSPACE_FONT 133 | }, 134 | a: { 135 | color: "blue", 136 | textDecorationLine: "underline" 137 | }, 138 | b: { 139 | fontWeight: "bold" 140 | }, 141 | u: { 142 | textDecorationLine: "underline" 143 | }, 144 | s: { 145 | textDecorationLine: "line-through" 146 | }, 147 | strike: { 148 | textDecorationLine: "line-through" 149 | }, 150 | del: { 151 | textDecorationLine: "line-through" 152 | }, 153 | i: { 154 | fontStyle: "italic" 155 | }, 156 | em: { 157 | fontStyle: "italic" 158 | }, 159 | strong: { 160 | fontWeight: "bold" 161 | }, 162 | small: { 163 | fontSize: 12 164 | }, 165 | dfn: { 166 | fontStyle: "italic" 167 | }, 168 | mark: { 169 | backgroundColor: "#ff0", 170 | color: "#000" 171 | }, 172 | ul: { 173 | marginLeft: 28 174 | }, 175 | ol: { 176 | marginLeft: 28 177 | } 178 | }); 179 | -------------------------------------------------------------------------------- /src/renderers/iframe-renderer.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import * as React from "react"; 3 | import { WebView, StyleSheet } from "react-native"; 4 | import ViewStylePropTypes from "react-native/Libraries/Components/View/ViewStylePropTypes"; 5 | import filterStyles from "../utils/filter-styles"; 6 | import type { RendererProps } from "../utils/render-native"; 7 | 8 | type Props = RendererProps & { 9 | attrs: { 10 | src?: string, 11 | width?: string, 12 | height?: string 13 | } 14 | }; 15 | 16 | const styles = StyleSheet.create({ 17 | iframe: { 18 | width: "100%", 19 | height: 360 20 | } 21 | }); 22 | 23 | export default class IframeRenderer extends React.PureComponent { 24 | render() { 25 | const { tagName, attrs, classList, style, ...rest } = this.props; 26 | 27 | let { src } = attrs; 28 | 29 | if (!src) { 30 | return null; 31 | } 32 | 33 | if (src.startsWith("//")) { 34 | src = `https:${src}`; 35 | } 36 | 37 | const flattened = StyleSheet.flatten(style); 38 | 39 | const width = parseFloat(attrs.width); 40 | const height = parseFloat(attrs.height); 41 | 42 | const dimensions = {}; 43 | 44 | if (Number.isFinite(width)) { 45 | dimensions.width = width; 46 | } 47 | 48 | if (Number.isFinite(height)) { 49 | dimensions.height = height; 50 | } 51 | 52 | if ( 53 | flattened && 54 | Number.isFinite(height) && 55 | Number.isFinite(width) && 56 | Number.isFinite(flattened.maxWidth) && 57 | width > flattened.maxWidth 58 | ) { 59 | // If a maxWidth is specified, we scale down the iframe height 60 | dimensions.height = height * (flattened.maxWidth / width); 61 | dimensions.width = flattened.maxWidth; 62 | } 63 | 64 | return ( 65 | 74 | ); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/renderers/image-renderer.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | /* eslint-disable react-native/no-unused-styles, react-native/no-color-literals */ 3 | 4 | import * as React from "react"; 5 | import { View, Image, StyleSheet } from "react-native"; 6 | import ImageStylePropTypes from "react-native/Libraries/Image/ImageStylePropTypes"; 7 | import ViewStylePropTypes from "react-native/Libraries/Components/View/ViewStylePropTypes"; 8 | import filterStyles from "../utils/filter-styles"; 9 | import type { RendererProps } from "../utils/render-native"; 10 | 11 | type Props = RendererProps & { 12 | attrs: { 13 | src: string 14 | }, 15 | navigation: { 16 | navigate: Function 17 | } 18 | }; 19 | 20 | type State = { 21 | height: number, 22 | width: number, 23 | error: ?Error 24 | }; 25 | 26 | export default class ImageRenderer extends React.PureComponent { 27 | state: State = { 28 | height: 0, 29 | width: 0, 30 | error: null 31 | }; 32 | 33 | componentDidMount() { 34 | this.updateImageSize(this.props); 35 | } 36 | 37 | componentWillReceiveProps(nextProps: Props) { 38 | if (this.props.attrs.src !== nextProps.attrs.src) { 39 | this.updateImageSize(nextProps); 40 | } 41 | } 42 | 43 | updateImageSize = (props: Props) => { 44 | const flattened = StyleSheet.flatten(props.style); 45 | 46 | if (flattened && flattened.height && flattened.width) { 47 | // Only try to fetch the image dimensions if not specified 48 | return; 49 | } 50 | 51 | Image.getSize( 52 | props.attrs.src, 53 | (width, height) => { 54 | let ratio = 1; 55 | 56 | if ( 57 | flattened && 58 | Number.isFinite(flattened.maxWidth) && 59 | width > flattened.maxWidth 60 | ) { 61 | // If a maxWidth is specified, we scale down the image height too 62 | ratio = flattened.maxWidth / width; 63 | } 64 | 65 | this.setState({ 66 | width: width * ratio, 67 | height: height * ratio, 68 | error: null 69 | }); 70 | }, 71 | error => this.setState({ error }) 72 | ); 73 | }; 74 | 75 | render() { 76 | const { tagName, attrs, classList, style, children, ...rest } = this.props; 77 | 78 | if (this.state.error) { 79 | return ( 80 | 87 | ); 88 | } 89 | 90 | return ( 91 | 99 | ); 100 | } 101 | } 102 | 103 | const styles = StyleSheet.create({ 104 | broken: { 105 | backgroundColor: "lightgrey", 106 | borderColor: "red", 107 | borderWidth: StyleSheet.hairlineWidth, 108 | height: 50, 109 | width: 50 110 | } 111 | }); 112 | -------------------------------------------------------------------------------- /src/renderers/list-renderer.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import * as React from "react"; 3 | import { StyleSheet } from "react-native"; 4 | import BlockRenderer from "./block-renderer"; 5 | import TextRenderer from "./text-renderer"; 6 | import type { RendererProps } from "../utils/render-native"; 7 | 8 | export default class ListRenderer extends React.PureComponent { 9 | render() { 10 | const { children, ...rest } = this.props; 11 | 12 | return ( 13 | 14 | {React.Children.map(children, (child, i) => { 15 | if ( 16 | typeof child === "object" && 17 | child && 18 | child.props.tagName === "li" 19 | ) { 20 | return ( 21 | /* eslint-disable no-use-before-define */ 22 | 23 | 24 | {rest.tagName === "ul" ? "•" : `${i + 1}.`} 25 | 26 | {child} 27 | 28 | ); 29 | } 30 | 31 | return child; 32 | })} 33 | 34 | ); 35 | } 36 | } 37 | 38 | const styles = StyleSheet.create({ 39 | item: { 40 | flexDirection: "row" 41 | }, 42 | bullet: { 43 | position: "absolute", 44 | left: -20 45 | } 46 | }); 47 | -------------------------------------------------------------------------------- /src/renderers/text-renderer.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import * as React from "react"; 3 | import { View, Text, StyleSheet } from "react-native"; 4 | import TextStylePropTypes from "react-native/Libraries/Text/TextStylePropTypes"; 5 | import filterStyles from "../utils/filter-styles"; 6 | import { BLOCK_TAGS } from "../utils/render-native"; 7 | import type { RendererProps } from "../utils/render-native"; 8 | 9 | type Props = RendererProps & { 10 | onPress?: () => mixed 11 | }; 12 | 13 | const styles = StyleSheet.create({ 14 | // eslint-disable-next-line react-native/no-color-literals 15 | text: { 16 | backgroundColor: "transparent" 17 | } 18 | }); 19 | 20 | export default class TextRenderer extends React.PureComponent { 21 | isChildrenBlock = (children: any | void) => 22 | React.Children.toArray(children).some( 23 | child => 24 | child 25 | ? typeof child !== "string" && 26 | child.props && 27 | (BLOCK_TAGS.includes(child.props.tagName) || 28 | this.isChildrenBlock(child.props.children)) 29 | : false 30 | ); 31 | 32 | render() { 33 | const { tagName, attrs, classList, style, children, ...rest } = this.props; 34 | 35 | const [textStyle, additional] = filterStyles(style, [ 36 | TextStylePropTypes, 37 | { textTransform: true } 38 | ]); 39 | 40 | const isChildrenBlock = this.isChildrenBlock(children); 41 | 42 | const transformedChildren = React.Children.map(children, child => { 43 | if (typeof child === "string") { 44 | /* $FlowFixMe */ 45 | switch (additional.textTransform) { // eslint-disable-line default-case 46 | case "uppercase": 47 | return child.toUpperCase(); 48 | case "lowercase": 49 | return child.toLowerCase(); 50 | case "capitalize": 51 | return child.charAt(0).toUpperCase() + child.slice(1); 52 | } 53 | } 54 | 55 | return child; 56 | }); 57 | 58 | if (isChildrenBlock) { 59 | return ( 60 | 61 | {transformedChildren.map(child => { 62 | if (typeof child === "string") { 63 | return {child}; 64 | } 65 | 66 | return child; 67 | })} 68 | 69 | ); 70 | } 71 | 72 | return ( 73 | 74 | {transformedChildren} 75 | 76 | ); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/utils/filter-styles.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | import { StyleSheet } from "react-native"; 4 | 5 | const validateStyles = { 6 | fontSize: [value => Number.isFinite(value)] 7 | }; 8 | 9 | const isValidStyle = (style, value) => { 10 | const rules = validateStyles[style] || []; 11 | if (rules.length > 0) { 12 | return !rules.some(rule => rule(value) === false); 13 | } 14 | return true; 15 | }; 16 | 17 | export default function filterStyles(styles: *, types: Object[]) { 18 | const flattened = StyleSheet.flatten(styles); 19 | 20 | // Loop over the array of propTypes to validate styles 21 | return types.map( 22 | propTypes => 23 | flattened 24 | ? Object.keys(flattened).reduce((acc, prop) => { 25 | if (flattened[prop] !== undefined && propTypes[prop]) { 26 | // If the style property exists in the valid types, consume it 27 | // Set the property to undefined so it's not consumed multiple times 28 | if (isValidStyle(prop, flattened[prop])) { 29 | acc[prop] = flattened[prop]; 30 | flattened[prop] = undefined; 31 | } 32 | } 33 | return acc; 34 | }, {}) 35 | : {} 36 | ); 37 | } 38 | -------------------------------------------------------------------------------- /src/utils/parse-html.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | import HTMLParser from "htmlparser2-without-node-native"; 4 | import clean from "htmlclean"; 5 | 6 | export class HTMLNode { 7 | constructor(type: string, attrs: {}) { 8 | this.type = type.toLowerCase(); 9 | this.attrs = attrs; 10 | } 11 | 12 | type: string; 13 | attrs: { [key: string]: string }; 14 | children: Array = []; 15 | parentNode: HTMLNode; 16 | 17 | append(child: HTMLNode | string) { 18 | if (child instanceof HTMLNode) { 19 | // eslint-disable-next-line no-param-reassign 20 | child.parentNode = this; 21 | } 22 | 23 | this.children.push(child); 24 | } 25 | } 26 | 27 | export default function parseHTML(content: string): HTMLNode { 28 | const root: HTMLNode = new HTMLNode("div", {}); 29 | 30 | let last = root; 31 | 32 | const html = new HTMLParser.Parser( 33 | { 34 | onopentag(name, attrs) { 35 | const node = new HTMLNode(name, attrs); 36 | last.append(node); 37 | last = node; 38 | }, 39 | 40 | ontext(text) { 41 | if (!/^\s*$/.test(text)) { 42 | last.append(text); 43 | } 44 | }, 45 | 46 | onclosetag() { 47 | last = last.parentNode; 48 | } 49 | }, 50 | { decodeEntities: true } 51 | ); 52 | 53 | html.write(clean(content)); 54 | html.end(); 55 | 56 | return root; 57 | } 58 | -------------------------------------------------------------------------------- /src/utils/render-native.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | import * as React from "react"; 4 | import css from "css-to-react-native"; 5 | import BlockRenderer from "../renderers/block-renderer"; 6 | import TextRenderer from "../renderers/text-renderer"; 7 | import ImageRenderer from "../renderers/image-renderer"; 8 | import IframeRenderer from "../renderers/iframe-renderer"; 9 | import ListRenderer from "../renderers/list-renderer"; 10 | import { HTMLNode } from "./parse-html"; 11 | 12 | export type RendererProps = { 13 | tagName?: string, 14 | classList?: string[], 15 | attrs?: { [key: string]: string }, 16 | style: any, 17 | children?: any 18 | }; 19 | 20 | export const BLOCK_TAGS = [ 21 | "address", 22 | "area", 23 | "article", 24 | "aside", 25 | "blockquote", 26 | "body", 27 | "center", 28 | "cite", 29 | "data", 30 | "dd", 31 | "div", 32 | "dl", 33 | "dt", 34 | "figure", 35 | "footer", 36 | "h1", 37 | "h2", 38 | "h3", 39 | "h4", 40 | "h5", 41 | "h6", 42 | "hgroup", 43 | "hr", 44 | "html", 45 | "li", 46 | "main", 47 | "map", 48 | "nav", 49 | "ol", 50 | "p", 51 | "pre", 52 | "rp", 53 | "rtc", 54 | "ruby", 55 | "section", 56 | "table", 57 | "tbody", 58 | "td", 59 | "th", 60 | "tr", 61 | "ul" 62 | ]; 63 | 64 | export const INLINE_TAGS = [ 65 | "a", 66 | "abbr", 67 | "b", 68 | "bdi", 69 | "bdo", 70 | "big", 71 | "blink", 72 | "bold", 73 | "br", 74 | "code", 75 | "del", 76 | "dfn", 77 | "em", 78 | "figcaption", 79 | "font", 80 | "i", 81 | "ins", 82 | "kbd", 83 | "mark", 84 | "q", 85 | "rt", 86 | "s", 87 | "samp", 88 | "small", 89 | "span", 90 | "strong", 91 | "sub", 92 | "sup", 93 | "time", 94 | "u", 95 | "var", 96 | "wbr" 97 | ]; 98 | 99 | export const mappings = { 100 | // Set renderer for the default block elements 101 | ...BLOCK_TAGS.reduce((acc, curr) => { 102 | acc[curr] = BlockRenderer; 103 | return acc; 104 | }, {}), 105 | // Set renderer for default inline elements 106 | ...INLINE_TAGS.reduce((acc, curr) => { 107 | acc[curr] = TextRenderer; 108 | return acc; 109 | }, {}), 110 | img: ImageRenderer, 111 | iframe: IframeRenderer, 112 | ul: ListRenderer, 113 | ol: ListRenderer 114 | }; 115 | 116 | export default function renderNative( 117 | node: HTMLNode | string, 118 | customMappings: ?{ [tag: string]: Function }, 119 | sheets: any[] 120 | ) { 121 | if (typeof node === "string") { 122 | // Don't process node if it's a string 123 | // Renderers can check and handle strings 124 | return node; 125 | } 126 | 127 | const Comp = 128 | // If a custom mapping is provided for the tag, use it 129 | // Otherwise use the one from default mapping 130 | customMappings && node.type in customMappings 131 | ? customMappings[node.type] 132 | : mappings[node.type]; 133 | 134 | if (typeof Comp !== "function") { 135 | // Don't render a tag if it doesn't have a mapping 136 | return null; 137 | } 138 | 139 | let style; 140 | 141 | try { 142 | style = node.attrs.style 143 | ? css( 144 | // Generate a 2D array from the inline style string 145 | node.attrs.style 146 | // Split lines to 'property: value' pair and filter empty values 147 | .split(";") 148 | .filter(Boolean) 149 | // Split 'property: value' pair to an array 150 | .map(r => r.split(":").map(it => it.trim())) 151 | ) 152 | : undefined; 153 | } catch (error) { 154 | // eslint-disable-next-line no-console 155 | console.warn(error); 156 | } 157 | 158 | // Extract the class names from the class attribute 159 | const classList = node.attrs.class 160 | ? node.attrs.class.split(" ").map(c => c.trim()) 161 | : []; 162 | 163 | // Prepend the tag name as a selector as it has a lower specificity 164 | const selectors = [node.type, ...classList.map(c => `.${c}`)]; 165 | 166 | const props = { 167 | tagName: node.type, 168 | classList, 169 | attrs: node.attrs, 170 | // Replace the style attribute with our style object 171 | style: [ 172 | // Select styles from provided styles sheet objects based on the selectors 173 | ...selectors.map(s => sheets.map(sheet => sheet[s])), 174 | // Inline styles should override styles from stylesheet 175 | style 176 | ] 177 | }; 178 | 179 | // Loop over children nodes to render as react elements 180 | const children = node.children.map((child, i) => { 181 | const el = renderNative(child, customMappings, sheets); 182 | return typeof el === "object" && el != null 183 | ? // Add index as the key for valid elements to suppress warning from React 184 | React.cloneElement(el, { key: i }) // eslint-disable-line react/no-array-index-key 185 | : el; 186 | }); 187 | 188 | return {children}; 189 | } 190 | --------------------------------------------------------------------------------