├── .github └── workflows │ ├── deploy-demo.yml │ ├── publish.yml │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── datasette_json_html └── __init__.py ├── setup.py └── tests ├── __init__.py ├── test_datasette_json_html.py └── test_urllib_quote_plus.py /.github/workflows/deploy-demo.yml: -------------------------------------------------------------------------------- 1 | name: Deploy demo 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | deploy: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Set up Python 14 | uses: actions/setup-python@v2 15 | with: 16 | python-version: 3.8 17 | - uses: actions/cache@v2 18 | name: Configure pip caching 19 | with: 20 | path: ~/.cache/pip 21 | key: ${{ runner.os }}-pip- 22 | restore-keys: | 23 | ${{ runner.os }}-pip- 24 | - name: Install Python dependencies 25 | run: pip install sqlite-utils datasette 26 | - name: Build database 27 | run: |- 28 | echo '[ 29 | { 30 | "package": "datasette-cluster-map", 31 | "url": "https://github.com/simonw/datasette-cluster-map" 32 | }, 33 | { 34 | "package": "datasette-jellyfish", 35 | "url": "https://github.com/simonw/datasette-jellyfish" 36 | }, 37 | { 38 | "package": "datasette-jq", 39 | "url": "https://github.com/simonw/datasette-jq" 40 | }, 41 | { 42 | "package": "datasette-json-html", 43 | "url": "https://github.com/simonw/datasette-json-html" 44 | }, 45 | { 46 | "package": "datasette-pretty-json", 47 | "url": "https://github.com/simonw/datasette-pretty-json" 48 | }, 49 | { 50 | "package": "datasette-vega", 51 | "url": "https://github.com/simonw/datasette-vega" 52 | } 53 | ]' | sqlite-utils insert demo.db packages - --pk=package 54 | - name: Create Metadata 55 | run: | 56 | echo '{ 57 | "title": "datasette-json-html demo", 58 | "about": "simonw/datasette-json-html", 59 | "about_url": "https://github.com/simonw/datasette-json-html" 60 | }' > metadata.json 61 | - name: Set up Cloud Run 62 | uses: google-github-actions/setup-gcloud@v0 63 | with: 64 | version: '275.0.0' 65 | service_account_email: ${{ secrets.GCP_SA_EMAIL }} 66 | service_account_key: ${{ secrets.GCP_SA_KEY }} 67 | - name: Deploy to Cloud Run 68 | run: |- 69 | gcloud config set run/region us-central1 70 | gcloud config set project datasette-222320 71 | datasette publish cloudrun demo.db \ 72 | -m metadata.json \ 73 | --install=https://github.com/simonw/datasette-json-html/archive/$GITHUB_SHA.zip \ 74 | --service datasette-json-html-demo 75 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python Package 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"] 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Set up Python ${{ matrix.python-version }} 16 | uses: actions/setup-python@v2 17 | with: 18 | python-version: ${{ matrix.python-version }} 19 | - uses: actions/cache@v2 20 | name: Configure pip caching 21 | with: 22 | path: ~/.cache/pip 23 | key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} 24 | restore-keys: | 25 | ${{ runner.os }}-pip- 26 | - name: Install dependencies 27 | run: | 28 | pip install -e '.[test]' 29 | - name: Run tests 30 | run: | 31 | pytest 32 | deploy: 33 | runs-on: ubuntu-latest 34 | needs: [test] 35 | steps: 36 | - uses: actions/checkout@v2 37 | - name: Set up Python 38 | uses: actions/setup-python@v2 39 | with: 40 | python-version: "3.10" 41 | - uses: actions/cache@v2 42 | name: Configure pip caching 43 | with: 44 | path: ~/.cache/pip 45 | key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }} 46 | restore-keys: | 47 | ${{ runner.os }}-publish-pip- 48 | - name: Install dependencies 49 | run: | 50 | pip install setuptools wheel twine build 51 | - name: Publish 52 | env: 53 | TWINE_USERNAME: __token__ 54 | TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} 55 | run: | 56 | python -m build 57 | twine upload dist/* 58 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"] 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Set up Python ${{ matrix.python-version }} 14 | uses: actions/setup-python@v2 15 | with: 16 | python-version: ${{ matrix.python-version }} 17 | - uses: actions/cache@v2 18 | name: Configure pip caching 19 | with: 20 | path: ~/.cache/pip 21 | key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} 22 | restore-keys: | 23 | ${{ runner.os }}-pip- 24 | - name: Install dependencies 25 | run: | 26 | pip install -e '.[test]' 27 | - name: Run tests 28 | run: | 29 | pytest 30 | 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | venv 6 | .eggs 7 | .pytest_cache 8 | *.egg-info 9 | .DS_Store 10 | .vscode 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # datasette-json-html 2 | 3 | [![PyPI](https://img.shields.io/pypi/v/datasette-json-html.svg)](https://pypi.org/project/datasette-json-html/) 4 | [![Changelog](https://img.shields.io/github/v/release/simonw/datasette-json-html?include_prereleases&label=changelog)](https://github.com/simonw/datasette-json-html/releases) 5 | [![Tests](https://github.com/simonw/datasette-json-html/workflows/Test/badge.svg)](https://github.com/simonw/datasette-remote-metadata/actions?query=workflow%3ATest) 6 | [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/datasette-json-html/blob/main/LICENSE) 7 | 8 | Datasette plugin for rendering HTML based on JSON values, using the [render_cell plugin hook](https://docs.datasette.io/en/stable/plugin_hooks.html#render-cell-value-column-table-database-datasette). 9 | 10 | This plugin looks for cell values that match a very specific JSON format and converts them into HTML when they are rendered by the Datasette interface. 11 | 12 | ## Links 13 | 14 | { 15 | "href": "https://simonwillison.net/", 16 | "label": "Simon Willison" 17 | } 18 | 19 | Will be rendered as an `` link: 20 | 21 | Simon Willison 22 | 23 | You can set a tooltip on the link using a `"title"` key: 24 | 25 | 26 | { 27 | "href": "https://simonwillison.net/", 28 | "label": "Simon Willison", 29 | "title": "My blog" 30 | } 31 | 32 | Produces: 33 | 34 | Simon Willison 35 | 36 | You can also include a description, which will be displayed below the link. If descriptions include newlines they will be converted to `
` elements: 37 | 38 | select json_object( 39 | "href", "https://simonwillison.net/", 40 | "label", "Simon Willison", 41 | "description", "This can contain" || x'0a' || "newlines" 42 | ) 43 | 44 | Produces: 45 | 46 | Simon Willison
This can contain
newlines 47 | 48 | * [Literal JSON link demo](https://datasette-json-html.datasette.io/demo?sql=select+%27%7B%0D%0A++++%22href%22%3A+%22https%3A%2F%2Fsimonwillison.net%2F%22%2C%0D%0A++++%22label%22%3A+%22Simon+Willison%22%2C%0D%0A++++%22title%22%3A+%22My+blog%22%0D%0A%7D%27) 49 | 50 | ## List of links 51 | 52 | [ 53 | { 54 | "href": "https://simonwillison.net/", 55 | "label": "Simon Willison" 56 | }, 57 | { 58 | "href": "https://github.com/simonw/datasette", 59 | "label": "Datasette" 60 | } 61 | ] 62 | 63 | Will be rendered as a comma-separated list of `` links: 64 | 65 | Simon Willison, 66 | Datasette 67 | 68 | The `href` property must begin with `https://` or `http://` or `/`, to avoid potential XSS injection attacks (for example URLs that begin with `javascript:`). 69 | 70 | Lists of links cannot include `"description"` keys. 71 | 72 | * [Literal list of links demo](https://datasette-json-html.datasette.io/demo?sql=select+%27%5B%0D%0A++++%7B%0D%0A++++++++%22href%22%3A+%22https%3A%2F%2Fsimonwillison.net%2F%22%2C%0D%0A++++++++%22label%22%3A+%22Simon+Willison%22%0D%0A++++%7D%2C%0D%0A++++%7B%0D%0A++++++++%22href%22%3A+%22https%3A%2F%2Fgithub.com%2Fsimonw%2Fdatasette%22%2C%0D%0A++++++++%22label%22%3A+%22Datasette%22%0D%0A++++%7D%0D%0A%5D%27) 73 | 74 | ## Images 75 | 76 | The image tag is more complex. The most basic version looks like this: 77 | 78 | { 79 | "img_src": "https://placekitten.com/200/300" 80 | } 81 | 82 | This will render as: 83 | 84 | 85 | 86 | But you can also include one or more of `alt`, `caption`, `width` and `href`. 87 | 88 | If you include width or alt, they will be added as attributes: 89 | 90 | { 91 | "img_src": "https://placekitten.com/200/300", 92 | "alt": "Kitten", 93 | "width": 200 94 | } 95 | 96 | Produces: 97 | 98 | Kitten 100 | 101 | * [Literal image demo](https://datasette-json-html.datasette.io/demo?sql=select+%27%7B%0D%0A++++%22img_src%22%3A+%22https%3A%2F%2Fplacekitten.com%2F200%2F300%22%2C%0D%0A++++%22alt%22%3A+%22Kitten%22%2C%0D%0A++++%22width%22%3A+200%0D%0A%7D%27) 102 | 103 | The `href` key will cause the image to be wrapped in a link: 104 | 105 | { 106 | "img_src": "https://placekitten.com/200/300", 107 | "href": "http://www.example.com" 108 | } 109 | 110 | Produces: 111 | 112 | 113 | 114 | 115 | 116 | The `caption` key wraps everything in a fancy figure/figcaption block: 117 | 118 | { 119 | "img_src": "https://placekitten.com/200/300", 120 | "caption": "Kitten caption" 121 | } 122 | 123 | Produces: 124 | 125 |
126 | 127 |
Kitten caption
128 |
129 | 130 | ## Preformatted text 131 | 132 | You can use `{"pre": "text"}` to render text in a `
` HTML tag:
133 | 
134 |     {
135 |         "pre": "This\nhas\nnewlines"
136 |     }
137 | 
138 | Produces:
139 | 
140 |     
This
141 |     has
142 |     newlines
143 | 144 | If the value attached to the `"pre"` key is itself a JSON object, that JSON will be pretty-printed: 145 | 146 | { 147 | "pre": { 148 | "this": { 149 | "object": ["is", "nested"] 150 | } 151 | } 152 | } 153 | 154 | Produces: 155 | 156 |
{
157 |       "this": {
158 |         "object": [
159 |           "is",
160 |           "nested"
161 |         ]
162 |       }
163 |     }
164 | 165 | * [Preformatted text with JSON demo](https://datasette-json-html.datasette.io/demo?sql=select+%27%7B%0D%0A++++%22pre%22%3A+%7B%0D%0A++++++++%22this%22%3A+%7B%0D%0A++++++++++++%22object%22%3A+%5B%22is%22%2C+%22nested%22%5D%0D%0A++++++++%7D%0D%0A++++%7D%0D%0A%7D%27) 166 | * [Preformatted text demo showing the Mandelbrot Set](https://datasette-json-html.datasette.io/demo?sql=WITH+RECURSIVE%0D%0A++xaxis%28x%29+AS+%28VALUES%28-2.0%29+UNION+ALL+SELECT+x%2B0.05+FROM+xaxis+WHERE+x%3C1.2%29%2C%0D%0A++yaxis%28y%29+AS+%28VALUES%28-1.0%29+UNION+ALL+SELECT+y%2B0.1+FROM+yaxis+WHERE+y%3C1.0%29%2C%0D%0A++m%28iter%2C+cx%2C+cy%2C+x%2C+y%29+AS+%28%0D%0A++++SELECT+0%2C+x%2C+y%2C+0.0%2C+0.0+FROM+xaxis%2C+yaxis%0D%0A++++UNION+ALL%0D%0A++++SELECT+iter%2B1%2C+cx%2C+cy%2C+x*x-y*y+%2B+cx%2C+2.0*x*y+%2B+cy+FROM+m+%0D%0A+++++WHERE+%28x*x+%2B+y*y%29+%3C+4.0+AND+iter%3C28%0D%0A++%29%2C%0D%0A++m2%28iter%2C+cx%2C+cy%29+AS+%28%0D%0A++++SELECT+max%28iter%29%2C+cx%2C+cy+FROM+m+GROUP+BY+cx%2C+cy%0D%0A++%29%2C%0D%0A++a%28t%29+AS+%28%0D%0A++++SELECT+group_concat%28+substr%28%27+.%2B*%23%27%2C+1%2Bmin%28iter%2F7%2C4%29%2C+1%29%2C+%27%27%29+%0D%0A++++FROM+m2+GROUP+BY+cy%0D%0A++%29%0D%0ASELECT+json_object%28%27pre%27%2C+group_concat%28rtrim%28t%29%2Cx%270a%27%29%29+FROM+a%3B) using [this example](https://www.sqlite.org/lang_with.html#outlandish_recursive_query_examples) from the SQLite documentation 167 | 168 | ## Using these with SQLite JSON functions 169 | 170 | The most powerful way to make use of this plugin is in conjunction with SQLite's [JSON functions](https://www.sqlite.org/json1.html). For example: 171 | 172 | select json_object( 173 | "href", "https://simonwillison.net/", 174 | "label", "Simon Willison" 175 | ); 176 | 177 | * [json_object() link demo](https://datasette-json-html.datasette.io/demo?sql=select+json_object%28%0D%0A++++%22href%22%2C+%22https%3A%2F%2Fsimonwillison.net%2F%22%2C%0D%0A++++%22label%22%2C+%22Simon+Willison%22%0D%0A%29%3B) 178 | 179 | You can use these functions to construct JSON objects that work with the plugin from data in a table: 180 | 181 | select id, json_object( 182 | "href", url, "label", text 183 | ) from mytable; 184 | 185 | * [Demo that builds links against a table](https://datasette-json-html.datasette.io/demo?sql=select+json_object%28%22href%22%2C+url%2C+%22label%22%2C+package%2C+%22title%22%2C+package+%7C%7C+%22+%22+%7C%7C+url%29+as+package+from+packages) 186 | 187 | The `json_group_array()` function is an aggregate function similar to `group_concat()` - it allows you to construct lists of JSON objects in conjunction with a `GROUP BY` clause. 188 | 189 | This means you can use it to construct dynamic lists of links, for example: 190 | 191 | select 192 | substr(package, 0, 12) as prefix, 193 | json_group_array( 194 | json_object( 195 | "href", url, 196 | "label", package 197 | ) 198 | ) as package_links 199 | from packages 200 | group by prefix 201 | 202 | * [Demo of json_group_array()](https://datasette-json-html.datasette.io/demo?sql=select%0D%0A++++substr%28package%2C+0%2C+12%29+as+prefix%2C%0D%0A++++json_group_array%28%0D%0A++++++++json_object%28%0D%0A++++++++++++%22href%22%2C+url%2C%0D%0A++++++++++++%22label%22%2C+package%0D%0A++++++++%29%0D%0A++++%29+as+package_links%0D%0Afrom+packages%0D%0Agroup+by+prefix) 203 | 204 | ## The `urllib_quote_plus()` SQL function 205 | 206 | Since this plugin is designed to be used with SQL that constructs the underlying JSON structure, it is likely you will need to construct dynamic URLs from results returned by a SQL query. 207 | 208 | This plugin registers a custom SQLite function called `urllib_quote_plus()` to help you do that. It lets you use Python's [urllib.parse.quote\_plus() function](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus) from within a SQL query. 209 | 210 | Here's an example of how you might use it: 211 | 212 | select id, json_object( 213 | "href", 214 | "/mydatabase/other_table?_search=" || urllib_quote_plus(text), 215 | "label", text 216 | ) from mytable; 217 | -------------------------------------------------------------------------------- /datasette_json_html/__init__.py: -------------------------------------------------------------------------------- 1 | from datasette import hookimpl 2 | import json 3 | import markupsafe 4 | import urllib 5 | 6 | valid_link_keys = ( 7 | {"href", "label"}, 8 | {"href", "label", "title"}, 9 | {"href", "label", "title", "description"}, 10 | {"href", "label", "description"}, 11 | ) 12 | valid_link_keys_no_description = ({"href", "label"}, {"href", "label", "title"}) 13 | 14 | # Add urllib_quote_plus SQLite function` 15 | @hookimpl 16 | def prepare_connection(conn): 17 | conn.create_function("urllib_quote_plus", 1, urllib.parse.quote_plus) 18 | 19 | 20 | @hookimpl 21 | def render_cell(value): 22 | if not isinstance(value, str): 23 | return None 24 | stripped = value.strip() 25 | if not ( 26 | (stripped.startswith("{") and stripped.endswith("}")) 27 | or (stripped.startswith("[") and stripped.endswith("]")) 28 | ): 29 | return None 30 | try: 31 | data = json.loads(value) 32 | except ValueError: 33 | return None 34 | if isinstance(data, list): 35 | # Handle list-of-links 36 | if len(data) == 0: 37 | return None 38 | if all( 39 | isinstance(item, dict) 40 | and set(item.keys()) in valid_link_keys_no_description 41 | and is_sensible_href(item["href"]) 42 | for item in data 43 | ): 44 | bits = [build_link(item) for item in data] 45 | return markupsafe.Markup(", ".join(bits)) 46 | else: 47 | return None 48 | keys = set(data.keys()) 49 | if keys in valid_link_keys: 50 | # Render {"href": "...", "label": "..."} as link 51 | href = data["href"] 52 | if not is_sensible_href(href): 53 | return None 54 | return markupsafe.Markup(build_link(data)) 55 | elif keys == {"pre"}: 56 | value = data["pre"] 57 | if isinstance(value, str): 58 | pre = value 59 | else: 60 | pre = json.dumps(value, indent=2) 61 | return markupsafe.Markup("
{pre}
".format(pre=markupsafe.escape(pre))) 62 | elif "img_src" in keys and keys.issubset( 63 | {"img_src", "alt", "href", "caption", "width"} 64 | ): 65 | # Render , optionally with alt, wrapping link and/or caption 66 | html = ''.format( 67 | img_src=markupsafe.escape(data["img_src"]), 68 | optional_alt=' alt="{}"'.format(markupsafe.escape(data["alt"])) 69 | if data.get("alt") 70 | else "", 71 | optional_width=' width="{}"'.format(markupsafe.escape(data["width"])) 72 | if data.get("width") 73 | else "", 74 | ) 75 | if data.get("href") and is_sensible_href(data["href"]): 76 | html = '{html}'.format( 77 | href=markupsafe.escape(data["href"]), html=html 78 | ) 79 | if data.get("caption"): 80 | html = "
{html}
{caption}
".format( 81 | caption=markupsafe.escape(data["caption"]), html=html 82 | ) 83 | return markupsafe.Markup(html) 84 | 85 | 86 | def is_sensible_href(href): 87 | return ( 88 | href.startswith("/") 89 | or href.startswith("http://") 90 | or href.startswith("https://") 91 | ) 92 | 93 | 94 | def build_link(item): 95 | html = '{label}'.format( 96 | href=markupsafe.escape(item["href"]), 97 | label=markupsafe.escape(item["label"] or "") or " ", 98 | title=' title="{}"'.format(markupsafe.escape(item["title"])) 99 | if item.get("title") 100 | else "", 101 | ) 102 | if item.get("description"): 103 | description = ( 104 | markupsafe.escape(item["description"]) 105 | .replace("\r\n", "\n") 106 | .replace("\n", markupsafe.Markup("
")) 107 | ) 108 | html = "{}
{}".format(html, description) 109 | return html 110 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | import os 3 | 4 | VERSION = "1.0.1" 5 | 6 | 7 | def get_long_description(): 8 | with open( 9 | os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), 10 | encoding="utf8", 11 | ) as fp: 12 | return fp.read() 13 | 14 | 15 | setup( 16 | name="datasette-json-html", 17 | description="Datasette plugin for rendering HTML based on JSON values", 18 | long_description=get_long_description(), 19 | long_description_content_type="text/markdown", 20 | author="Simon Willison", 21 | url="https://datasette.io/plugins/datasette-json-html", 22 | project_urls={ 23 | "Issues": "https://github.com/simonw/datasette-json-html/issues", 24 | "CI": "https://github.com/simonw/datasette-json-html/actions", 25 | "Changelog": "https://github.com/simonw/datasette-json-html/releases", 26 | }, 27 | license="Apache License, Version 2.0", 28 | version=VERSION, 29 | packages=["datasette_json_html"], 30 | entry_points={"datasette": ["json_html = datasette_json_html"]}, 31 | install_requires=["datasette"], 32 | extras_require={"test": ["pytest", "pytest-asyncio", "httpx"]}, 33 | tests_require=["datasette-json-html[test]"], 34 | ) 35 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonw/datasette-json-html/bb4c2ed9538745f866a781be8db04f70e0531cc8/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_datasette_json_html.py: -------------------------------------------------------------------------------- 1 | from datasette_json_html import render_cell 2 | import markupsafe 3 | import json 4 | import pytest 5 | 6 | 7 | @pytest.mark.parametrize( 8 | "input,expected", 9 | ( 10 | # Ignore unrecognized JSON structure: 11 | ({"blah": "blah"}, None), 12 | # Ignore empty list 13 | ([], None), 14 | # Basic link: 15 | ( 16 | {"href": "http://example.com/", "label": "Example"}, 17 | 'Example', 18 | ), 19 | # Evil links should not be rendered: 20 | ({"href": "javascript:alert('evil')", "label": "Evil"}, None), 21 | # Link with a tooltip: 22 | ( 23 | {"href": "http://example.com/", "label": "Example", "title": "Tooltip"}, 24 | 'Example', 25 | ), 26 | # Image tests: 27 | ( 28 | {"img_src": "https://placekitten.com/200/300"}, 29 | '', 30 | ), 31 | ( 32 | { 33 | "img_src": "https://placekitten.com/200/300", 34 | "alt": "Kitten", 35 | "width": 200, 36 | }, 37 | 'Kitten', 38 | ), 39 | ( 40 | { 41 | "img_src": "https://placekitten.com/200/300", 42 | "href": "http://www.example.com", 43 | }, 44 | '', 45 | ), 46 | ( 47 | {"img_src": "https://placekitten.com/200/300", "caption": "Kitten caption"}, 48 | '
' 49 | "
Kitten caption
", 50 | ), 51 | # List of links: 52 | ( 53 | [ 54 | {"href": "http://example.com/", "label": "Example"}, 55 | { 56 | "href": "http://blah.com/", 57 | "label": "Blah", 58 | "title": "Tooltip & change", 59 | }, 60 | ], 61 | 'Example, ' 62 | 'Blah', 63 | ), 64 | # Link with description 65 | ( 66 | { 67 | "href": "http://example.com/", 68 | "label": "Example", 69 | "description": "Hello there\nwith a break", 70 | }, 71 | 'Example
' 72 | "Hello there
with a break", 73 | ), 74 | #
 with string contents
75 |         (
76 |             {"pre": "Hello\n  two step indent\nBack again"},
77 |             "
Hello\n  two step indent\nBack again
", 78 | ), 79 | #
 with JSON object contents
80 |         (
81 |             {"pre": {"this": {"is": "nested"}}},
82 |             "
{\n  "this": {\n    "is": "nested"\n  }\n}
", 83 | ), 84 | ), 85 | ) 86 | def test_render_cell(input, expected): 87 | actual = render_cell(json.dumps(input)) 88 | assert expected == actual 89 | assert actual is None or isinstance(actual, markupsafe.Markup) 90 | -------------------------------------------------------------------------------- /tests/test_urllib_quote_plus.py: -------------------------------------------------------------------------------- 1 | from datasette_json_html import prepare_connection 2 | import sqlite3 3 | 4 | 5 | def test_urllib_quote_plus(): 6 | conn = sqlite3.connect(":memory:") 7 | prepare_connection(conn) 8 | result = conn.execute( 9 | """ 10 | select urllib_quote_plus("/foo/bar?baz=bam") 11 | """ 12 | ).fetchone()[0] 13 | assert "%2Ffoo%2Fbar%3Fbaz%3Dbam" == result 14 | --------------------------------------------------------------------------------