├── .gitignore ├── .travis.yml ├── CREDITS ├── LICENSE ├── README.md ├── WHO-IS-USING.md ├── bower.json ├── dist ├── css │ ├── brutusin-json-forms.css │ └── brutusin-json-forms.min.css └── js │ ├── brutusin-json-forms-bootstrap.js │ ├── brutusin-json-forms-bootstrap.min.js │ ├── brutusin-json-forms.js │ └── brutusin-json-forms.min.js ├── gulp ├── index.js └── tasks │ ├── default.js │ ├── deploy.js │ └── minify.js ├── gulpfile.js ├── package.json └── src ├── css └── brutusin-json-forms.css └── js ├── addon ├── brutusin-json-forms-lan-de_DE.js ├── brutusin-json-forms-lan-es_ES.js └── brutusin-json-forms-lan-fr-FR.js ├── brutusin-json-forms-bootstrap.js └── brutusin-json-forms.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | bower_components 4 | .publish 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - stable 4 | before_install: 5 | - npm install -g bower 6 | - npm install rimraf 7 | before_script: 8 | - rm -rf node_modules/json-forms 9 | script: gulp 10 | sudo: false 11 | -------------------------------------------------------------------------------- /CREDITS: -------------------------------------------------------------------------------- 1 | Here are people who have contributed to development of json-forms: 2 | (version numbers in brackets indicate release in which the problem was fixed) 3 | 4 | fabifabi@github 5 | Several contributions regarding i18n. French translation 6 | (1.6.2) 7 | 8 | Omri Schwarz (ocschwar@github): 9 | #23: $ref, definitions, fixed oneOf, patternProperties 10 | (1.4.0) 11 | 12 | Stephen J. Fuhry (fuhrysteve@github) 13 | #20: Add support for date format 14 | (1.3.1) 15 | 16 | Matheus Graciano (graciano@github) 17 | #16: Propperly adding types to buttons 18 | (1.2.4) 19 | 20 | Volt220@github 21 | #15: Update brutusin-json-forms.css 22 | (1.2.3) 23 | 24 | Dirk Haage (e110c0@github) 25 | #14 Added version to package.json 26 | (1.2.1) 27 | 28 | Omri Schwarz (ocschwar@github): 29 | #11: Add handling for the oneOf option for schemas 30 | (1.2.0) 31 | -------------------------------------------------------------------------------- /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 2015 Ignacio del Valle Alles 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 | # json-forms 2 | [![bower version](https://img.shields.io/bower/v/json-forms.svg?style=flat-square)](#bower) 3 | [![Build Status](https://api.travis-ci.org/brutusin/json-forms.svg?branch=master)](https://travis-ci.org/brutusin/json-forms) 4 | 5 | `org.brutusin:json-forms` is a javascript library that generates HTML forms from [JSON Schemas](http://json-schema.org). 6 | 7 | ## Status 8 | > I am currently not having time to maintain this project, so first of all my apologies if some issues have been unresponded. 9 | Branch v2 contains a completely new rearchitecture of the project, that I started several months ago but left unfinished. If someone is interested in continuing my work I will be happy to guide them 10 | 11 | --- 12 | **Table of Contents:** 13 | 14 | - [org.brutusin:json-forms](#) 15 | - [Features](#features) 16 | - [Usage](#usage) 17 | - [Demo](#demo) 18 | - [Dynamic schemas](#dynamic-schemas) 19 | - [API](#api) 20 | - [CDN](#cdn) 21 | - [Support, bugs and requests](#support-bugs-and-requests) 22 | - [Authors](#authors) 23 | - [License](#license) 24 | 25 | ## Features 26 | * Dynamic schemas support 27 | * Extensible and customizable 28 | * No external libraries needed 29 | * Validation 30 | * Multiple forms per document supported 31 | 32 | ## Usage 33 | Include the main library dependencies: 34 | ```html 35 | 36 | 37 | ``` 38 | Optionally, include the bootstrap extension (requires bootstrap): 39 | ```html 40 | 41 | ``` 42 | Create the javascript `BrutusinForms` instance, `schema` being a javascript `object` representing the schema structure: 43 | ```javascript 44 | var schema = {"type": "boolean"} 45 | var BrutusinForms = brutusin["json-forms"]; 46 | var bf = BrutusinForms.create(schema); 47 | ``` 48 | And finally render the form inside a container with optional preloaded JSON initial data, `data`: 49 | ```javascript 50 | var container = document.getElementById('container'); 51 | bf.render(container, data); 52 | ``` 53 | 54 | ## Demo 55 | [![demo](http://brutusin.org/json-forms/img/json-forms.png)](http://brutusin.org/json-forms/) 56 | http://brutusin.org/json-forms/ 57 | 58 | ## Dynamic schemas 59 | This library supports dynamic schemas, that is, subschemas that can change depending on the value of other parts of the data. 60 | 61 | This lets creating **dynamic forms** that vary their shape depending on the values entered by the user. This is extremely useful for big autogenerated schemas, that aggregates lots of subschemas and have functional bindings, given that it allows to show the user a simpler, non-error-prone form, also avoiding asking for unneeded data. 62 | 63 | Dynamic schemas are built upon two main blocks: 64 | * Custom (non-standard) schema property called `dependsOn`, to build the subschemas dependency graph 65 | * [Brutusin DSL for path expressions](https://github.com/brutusin/json#path-expressions), for identifying subschemas. 66 | 67 | ### `dependsOn` schema extension 68 | ### Dynamic schema resolution 69 | 70 | ## API 71 | ### Static members: 72 | 73 | Member|Description 74 | ------| ------- 75 | `BrutusinForms.create(schema)`|BrutusinForms factory method 76 | `BrutusinForms.addDecorator(f(htmlElement, schema))`| Register a callback function to be notified after an HTML element has been rendered (passed as parameter). See [brutusin-json-forms-bootstrap.js](src/js/brutusin-json-forms-bootstrap.js) for an example of *bootstrap* decorator. 77 | `BrutusinForms.postRender(instance)`|Callback function to be notified after a BrutusinForms instance has been rendered (passed as parameter) 78 | `BrutusinForms.instances`|Array containing all the BrutusinForms instances created in the document by the factory method. 79 | 80 | ### Instance members: 81 | 82 | Member|Description 83 | ------| ------- 84 | `bf.render(container, data)`| Renders the form inside the the container, with the specified data preloaded 85 | `bf.validate()`| Returns `true` if the input data entered by the user passes validation 86 | `bf.getData()`| Returns the javascript object with the data entered by the user 87 | `bf.schemaResolver(schemaIdArray, data)`| Schema resolver for [dynamic schemas](#dynamic-schemas) 88 | 89 | ## CDN 90 | 91 | http://www.jsdelivr.com/projects/brutusin.json-forms 92 | 93 | ## Support bugs and requests 94 | https://github.com/brutusin/json-forms/issues 95 | 96 | ## Authors 97 | 98 | - Ignacio del Valle Alles () 99 | 100 | Contributions are always welcome and greatly appreciated! 101 | 102 | ## License 103 | Apache License, Version 2.0 104 | -------------------------------------------------------------------------------- /WHO-IS-USING.md: -------------------------------------------------------------------------------- 1 | # Who is using `json-forms`? 2 | 3 | > Are you using `json-forms`? Then send a pull request with your project at the bottom! 4 | 5 | - **[Brutusin-RPC](http://demo.rpc.brutusin.org/rpc/repo/#http-services/rpc.http.schema)**: `json-forms` had been originally created for automatically generating test UIs for `Brutusin-RPC` services. 6 | - **[Therapi JSON-RPC 2.0 Microframework for Java](https://github.com/dnault/therapi-json-rpc)**: Uses `json-forms` to generate interactive API documentation. 7 | - **[JSON Local Configurator](https://github.com/vincentmorneau/json-local-configurator)**: Turns `json-forms` into a npm package capable of generating Material Design forms from a JSON Schema and saving the result in a local directory. Useful for Node.js package development. 8 | - *Your project here* 9 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "json-forms", 3 | "homepage": "http://brutusin.org/json-forms/", 4 | "authors": [ 5 | "Ignacio del Valle Alles (http://brutusin.org)" 6 | ], 7 | "description": "Brutusin json-forms is a JSON Schema to HTML form generator, supporting dynamic subschemas (on the fly resolution). Extensible and customizable library with zero dependencies. Bootstrap add-on provided. See live demo at http://brutusin.org/json-forms", 8 | "main": "dist/brutusin-json-forms.min.js", 9 | "moduleType": [ 10 | "globals" 11 | ], 12 | "license": "Apache-2.0", 13 | "keywords": [ 14 | "form", 15 | "json", 16 | "json-schema", 17 | "schema" 18 | ], 19 | "ignore": [ 20 | "**/.*", 21 | "node_modules", 22 | "bower_components", 23 | "test", 24 | "tests" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /dist/css/brutusin-json-forms.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 brutusin.org 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * @author Ignacio del Valle Alles idelvall@brutusin.org 17 | */ 18 | .add-pattern-div{ 19 | margin-top: 6px; 20 | } 21 | .loading-layer{ 22 | position: absolute; 23 | top:0px; 24 | left:0px; 25 | z-index : 10; 26 | width: 100%; 27 | height: 100%; 28 | opacity: 0.7; 29 | background-color: white; 30 | } 31 | .loading-icon{ 32 | position: absolute; 33 | top:14px; 34 | left:50%; 35 | z-index : 11; 36 | } 37 | .loading-icon-select{ 38 | position: absolute; 39 | top:14px; 40 | left:50%; 41 | z-index : 11; 42 | } 43 | .loading-icon-checkbox{ 44 | position: absolute; 45 | top:7px; 46 | left:3px; 47 | z-index : 11; 48 | } 49 | .glyphicon-refresh-animate { 50 | animation: spin .7s infinite linear; 51 | -webkit-animation: spin2 .7s infinite linear; 52 | } 53 | 54 | @-webkit-keyframes spin2 { 55 | from { -webkit-transform: rotate(0deg);} 56 | to { -webkit-transform: rotate(360deg);} 57 | } 58 | 59 | @keyframes spin { 60 | from { transform: scale(1) rotate(0deg);} 61 | to { transform: scale(1) rotate(360deg);} 62 | } 63 | form.brutusin-form table, form.brutusin-form input, form.brutusin-form select, form.brutusin-form textarea{ 64 | width: 100% !important; 65 | min-width: 80px; 66 | } 67 | form.brutusin-form input[type=checkbox]{ 68 | width: auto !important; 69 | min-width: auto !important; 70 | } 71 | form.brutusin-form textarea{ 72 | height: 8em; 73 | } 74 | form.brutusin-form table table{ 75 | border-left: solid 1px; 76 | border-color: lightgray; 77 | margin: 4px; 78 | } 79 | form.brutusin-form td { 80 | vertical-align: top; 81 | padding: 4px; 82 | white-space: nowrap; 83 | } 84 | form.brutusin-form td.prop-name { 85 | text-align: right; 86 | } 87 | form.brutusin-form td.add-prop-name table { 88 | text-align: right; 89 | border: none; 90 | } 91 | form.brutusin-form td.add-prop-name table td { 92 | vertical-align: middle; 93 | } 94 | form.brutusin-form td.prop-value { 95 | width: 100%; 96 | text-align: left; 97 | } 98 | form.brutusin-form td.item-index{ 99 | font-size: 0.8em; 100 | color: lightgray; 101 | width: 25px; 102 | text-align: right; 103 | } 104 | form.brutusin-form td.item-action{ 105 | width: 30px; 106 | } 107 | form.brutusin-form .error { 108 | border-color: red; 109 | } 110 | form.brutusin-form .error-message { 111 | color: red; 112 | } 113 | -------------------------------------------------------------------------------- /dist/css/brutusin-json-forms.min.css: -------------------------------------------------------------------------------- 1 | .add-pattern-div{margin-top:6px}.loading-layer{position:absolute;top:0;left:0;z-index:10;width:100%;height:100%;opacity:.7;background-color:#fff}.loading-icon,.loading-icon-select{position:absolute;top:14px;left:50%;z-index:11}.loading-icon-checkbox{position:absolute;top:7px;left:3px;z-index:11}.glyphicon-refresh-animate{animation:spin .7s infinite linear;-webkit-animation:spin2 .7s infinite linear}@-webkit-keyframes spin2{from{-webkit-transform:rotate(0)}to{-webkit-transform:rotate(360deg)}}@keyframes spin{from{transform:scale(1) rotate(0)}to{transform:scale(1) rotate(360deg)}}form.brutusin-form input,form.brutusin-form select,form.brutusin-form table,form.brutusin-form textarea{width:100%!important;min-width:80px}form.brutusin-form input[type=checkbox]{width:auto!important;min-width:auto!important}form.brutusin-form textarea{height:8em}form.brutusin-form table table{border-left:solid 1px;border-color:#d3d3d3;margin:4px}form.brutusin-form td{vertical-align:top;padding:4px;white-space:nowrap}form.brutusin-form td.prop-name{text-align:right}form.brutusin-form td.add-prop-name table{text-align:right;border:none}form.brutusin-form td.add-prop-name table td{vertical-align:middle}form.brutusin-form td.prop-value{width:100%;text-align:left}form.brutusin-form td.item-index{font-size:.8em;color:#d3d3d3;width:25px;text-align:right}form.brutusin-form td.item-action{width:30px}form.brutusin-form .error{border-color:red}form.brutusin-form .error-message{color:red} -------------------------------------------------------------------------------- /dist/js/brutusin-json-forms-bootstrap.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 brutusin.org 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * @author Ignacio del Valle Alles idelvall@brutusin.org 17 | */ 18 | if ("undefined" === typeof brutusin || "undefined" === typeof brutusin["json-forms"]) { 19 | throw new Error("brutusin-json-forms-bootstrap.js requires brutusin-json-forms.js"); 20 | } 21 | if ("undefined" === typeof markdown && window.console) { 22 | console.warn("Include markdown.js (https://github.com/evilstreak/markdown-js) to add markdown support in property description popups"); 23 | } 24 | 25 | if (("undefined" === typeof $ || "undefined" === typeof $.fn || "undefined" === typeof $.fn.selectpicker) && window.console) { 26 | console.warn("Include bootstrap-select.js (https://github.com/silviomoreto/bootstrap-select) to turn native selects into bootstrap components"); 27 | } 28 | 29 | (function () { 30 | var BrutusinForms = brutusin["json-forms"]; 31 | 32 | // Basic bootstrap css 33 | BrutusinForms.addDecorator(function (element, schema) { 34 | if (element.tagName) { 35 | var tagName = element.tagName.toLowerCase(); 36 | if (tagName === "input" && element.type !== "checkbox" || tagName === "textarea") { 37 | element.className += " form-control"; 38 | } else if (tagName === "select") { 39 | element.className += " chosen-select form-control"; 40 | } else if (tagName === "button") { 41 | if (element.className === "remove") { 42 | element.className += " glyphicon glyphicon-remove"; 43 | while (element.firstChild) { 44 | element.removeChild(element.firstChild); 45 | } 46 | } 47 | element.className += " btn btn-primary btn-xs"; 48 | } else if (tagName === "form") { 49 | element.className += " form-inline"; 50 | } 51 | } 52 | }); 53 | 54 | 55 | // Description help icon 56 | BrutusinForms.addDecorator(function (element, schema) { 57 | if (element.tagName) { 58 | var tagName = element.tagName.toLowerCase(); 59 | if (tagName === "label" || tagName === "button") { 60 | if (element.title) { 61 | var helpLink = document.createElement("a"); 62 | helpLink.setAttribute("style", "outline: 0; text-decoration: none; margin-left: 2px;"); 63 | helpLink.setAttribute("tabIndex", -1); 64 | helpLink.className = "glyphicon glyphicon-info-sign" 65 | helpLink.setAttribute("data-toggle", "popover"); 66 | helpLink.setAttribute("data-trigger", "focus"); 67 | if ("undefined" === typeof markdown) { 68 | helpLink.setAttribute("data-content", element.title); 69 | } else { 70 | helpLink.setAttribute("data-content", markdown.toHTML(element.title)); 71 | } 72 | if (schema.title) { 73 | helpLink.title = schema.title; 74 | } else { 75 | helpLink.title = "Help"; 76 | } 77 | $(helpLink).popover({ 78 | placement: 'top', 79 | container: 'body', 80 | html: !("undefined" === typeof markdown) 81 | }); 82 | element.parentNode.appendChild(helpLink); 83 | } 84 | } 85 | } 86 | }); 87 | 88 | // Popover over inputs 89 | //BrutusinForms.addDecorator(function (element, schema) { 90 | //if (element.tagName) { 91 | // if (element.title && (tagName === "input" || tagName === "textarea" || tagName === "select")) { 92 | // element.setAttribute("data-toggle", "tooltip"); 93 | // element.setAttribute("data-trigger", "focus"); 94 | // if ("undefined" === typeof markdown) { 95 | // element.setAttribute("data-content", element.title); 96 | // } else { 97 | // element.setAttribute("data-content", markdown.toHTML(element.title)); 98 | // } 99 | // if (schema.title) { 100 | // element.title = schema.title; 101 | // } else { 102 | // element.title = "Help"; 103 | // } 104 | // $(element).popover({ 105 | // placement: 'top', 106 | // container: 'body', 107 | // html: !("undefined" === typeof markdown) 108 | // }); 109 | // }input 110 | // } 111 | //}); 112 | // Bootstrap select 113 | BrutusinForms.addDecorator(function (element, schema) { 114 | if (element.tagName) { 115 | var tagName = element.tagName.toLowerCase(); 116 | // https://github.com/silviomoreto/bootstrap-select 117 | if (!("undefined" === typeof $ || "undefined" === typeof $.fn || "undefined" === typeof $.fn.selectpicker) && tagName === "select") { 118 | element.title = ""; 119 | element.className += " selectpicker"; 120 | element.setAttribute("data-live-search", true); 121 | $(element).selectpicker(); 122 | } 123 | } 124 | }); 125 | BrutusinForms.bootstrap = new Object(); 126 | // helper button for string (with format) fields 127 | BrutusinForms.bootstrap.addFormatDecorator = function (format, inputType, glyphicon, cb) { 128 | BrutusinForms.addDecorator(function (element, schema) { 129 | if (element.tagName) { 130 | var tagName = element.tagName.toLowerCase(); 131 | if (tagName === "input" && schema.type === "string" && schema.format === format) { 132 | if (inputType) { 133 | element.type = inputType; 134 | } 135 | if (glyphicon) { 136 | var parent = element.parentNode; 137 | var table = document.createElement("table"); 138 | table.setAttribute("style", "border:none;margin:0"); 139 | var tr = document.createElement("tr"); 140 | var td1 = document.createElement("td"); 141 | td1.setAttribute("style", "width:100%; padding:0;padding-right:4px"); 142 | table.appendChild(tr); 143 | tr.appendChild(td1); 144 | parent.removeChild(element); 145 | td1.appendChild(element); 146 | parent.appendChild(table); 147 | var td = document.createElement("td"); 148 | tr.appendChild(td); 149 | td.setAttribute("style", "padding:0"); 150 | var searchButton = document.createElement("button"); 151 | searchButton.className = "btn btn-default glyphicon " + glyphicon; 152 | searchButton.onclick = function () { 153 | cb(element); 154 | }; 155 | td.appendChild(searchButton); 156 | } 157 | } 158 | } 159 | }); 160 | }; 161 | BrutusinForms.bootstrap.showLoading = function (element) { 162 | if (element && element.parentNode) { 163 | var loadingId = element.id + "_loading"; 164 | var loadingLayerId = element.id + "_loading-layer"; 165 | var loading = document.getElementById(loadingId); 166 | var loadingLayer = document.getElementById(loadingLayerId); 167 | if (!loading) { 168 | var tagName = element.tagName.toLowerCase(); 169 | element.parentNode.style.position = "relative"; 170 | loading = document.createElement("span"); 171 | loading.id = loadingId; 172 | loading.className = "glyphicon glyphicon-refresh glyphicon-refresh-animate"; 173 | if (tagName === "select") { 174 | loading.className += " loading-icon-select"; 175 | } else if (element.type === "checkbox") { 176 | loading.className += " loading-icon-checkbox"; 177 | } else { 178 | loading.className += " loading-icon"; 179 | } 180 | element.parentNode.appendChild(loading); 181 | loadingLayer = document.createElement("div"); 182 | loadingLayer.className = "loading-layer"; 183 | loadingLayer.appendChild(document.createTextNode("")); 184 | loadingLayer.id = loadingLayerId; 185 | element.parentNode.appendChild(loadingLayer); 186 | } 187 | loading.style.visibility = "visible"; 188 | loadingLayer.style.visibility = "visible"; 189 | } 190 | } 191 | BrutusinForms.bootstrap.hideLoading = function (element) { 192 | if (element) { 193 | var loadingId = element.id + "_loading"; 194 | var loadingLayerId = element.id + "_loading-layer"; 195 | var loading = document.getElementById(loadingId); 196 | var loadingLayer = document.getElementById(loadingLayerId); 197 | if (loading) { 198 | loading.style.visibility = "hidden"; 199 | } 200 | if (loadingLayer) { 201 | loadingLayer.style.visibility = "hidden"; 202 | } 203 | } 204 | } 205 | 206 | BrutusinForms.onResolutionStarted = BrutusinForms.bootstrap.showLoading; 207 | BrutusinForms.onResolutionFinished = BrutusinForms.bootstrap.hideLoading; 208 | 209 | BrutusinForms.onValidationSuccess = function (element) { 210 | element.parentNode.className = element.parentNode.className.replace(" has-error", ""); 211 | } 212 | BrutusinForms.onValidationError = function (element, message) { 213 | 214 | setTimeout(function () { 215 | var dataToggle = element.getAttribute("data-toggle"); 216 | var dataTrigger = element.getAttribute("data-trigger"); 217 | var dataContent = element.getAttribute("data-content"); 218 | var title = element.title; 219 | element.setAttribute("data-toggle", "popover"); 220 | element.setAttribute("data-trigger", "manual"); 221 | if ("undefined" === typeof markdown) { 222 | element.setAttribute("data-content", message); 223 | } else { 224 | element.setAttribute("data-content", markdown.toHTML(message)); 225 | } 226 | 227 | element.title = BrutusinForms.messages["validationError"]; 228 | if (!element.parentNode.className.includes("has-error")) { 229 | element.parentNode.className += " has-error"; 230 | } 231 | element.focus(); 232 | $(element).popover({ 233 | placement: 'top', 234 | container: 'body', 235 | html: true 236 | }); 237 | $(element).popover("show"); 238 | var onblur = element.onblur; 239 | element.onblur = function (e) { 240 | if (dataToggle) { 241 | $(element).popover('hide'); 242 | element.setAttribute("data-toggle", dataToggle); 243 | element.setAttribute("data-trigger", dataTrigger); 244 | element.setAttribute("data-content", dataContent); 245 | } else { 246 | $(element).popover('destroy'); 247 | element.removeAttribute("data-toggle"); 248 | element.removeAttribute("data-trigger"); 249 | element.removeAttribute("data-content"); 250 | } 251 | 252 | element.onblur = onblur; 253 | element.title = title; 254 | if (onblur) { 255 | onblur(); 256 | } 257 | } 258 | }, 259 | 200); 260 | } 261 | }()); -------------------------------------------------------------------------------- /dist/js/brutusin-json-forms-bootstrap.min.js: -------------------------------------------------------------------------------- 1 | if("undefined"==typeof brutusin||"undefined"==typeof brutusin["json-forms"])throw new Error("brutusin-json-forms-bootstrap.js requires brutusin-json-forms.js");"undefined"==typeof markdown&&window.console&&console.warn("Include markdown.js (https://github.com/evilstreak/markdown-js) to add markdown support in property description popups"),"undefined"!=typeof $&&"undefined"!=typeof $.fn&&"undefined"!=typeof $.fn.selectpicker||!window.console||console.warn("Include bootstrap-select.js (https://github.com/silviomoreto/bootstrap-select) to turn native selects into bootstrap components"),function(){var e=brutusin["json-forms"];e.addDecorator(function(e,t){if(e.tagName){var o=e.tagName.toLowerCase();if("input"===o&&"checkbox"!==e.type||"textarea"===o)e.className+=" form-control";else if("select"===o)e.className+=" chosen-select form-control";else if("button"===o){if("remove"===e.className)for(e.className+=" glyphicon glyphicon-remove";e.firstChild;)e.removeChild(e.firstChild);e.className+=" btn btn-primary btn-xs"}else"form"===o&&(e.className+=" form-inline")}}),e.addDecorator(function(e,t){if(e.tagName){var o=e.tagName.toLowerCase();if(("label"===o||"button"===o)&&e.title){var n=document.createElement("a");n.setAttribute("style","outline: 0; text-decoration: none; margin-left: 2px;"),n.setAttribute("tabIndex",-1),n.className="glyphicon glyphicon-info-sign",n.setAttribute("data-toggle","popover"),n.setAttribute("data-trigger","focus"),"undefined"==typeof markdown?n.setAttribute("data-content",e.title):n.setAttribute("data-content",markdown.toHTML(e.title)),t.title?n.title=t.title:n.title="Help",$(n).popover({placement:"top",container:"body",html:!("undefined"==typeof markdown)}),e.parentNode.appendChild(n)}}}),e.addDecorator(function(e,t){if(e.tagName){var o=e.tagName.toLowerCase();"undefined"!=typeof $&&"undefined"!=typeof $.fn&&"undefined"!=typeof $.fn.selectpicker&&"select"===o&&(e.title="",e.className+=" selectpicker",e.setAttribute("data-live-search",!0),$(e).selectpicker())}}),e.bootstrap=new Object,e.bootstrap.addFormatDecorator=function(t,o,n,a){e.addDecorator(function(e,i){if(e.tagName){var r=e.tagName.toLowerCase();if("input"===r&&"string"===i.type&&i.format===t&&(o&&(e.type=o),n)){var d=e.parentNode,s=document.createElement("table");s.setAttribute("style","border:none;margin:0");var l=document.createElement("tr"),c=document.createElement("td");c.setAttribute("style","width:100%; padding:0;padding-right:4px"),s.appendChild(l),l.appendChild(c),d.removeChild(e),c.appendChild(e),d.appendChild(s);var p=document.createElement("td");l.appendChild(p),p.setAttribute("style","padding:0");var u=document.createElement("button");u.className="btn btn-default glyphicon "+n,u.onclick=function(){a(e)},p.appendChild(u)}}})},e.bootstrap.showLoading=function(e){if(e&&e.parentNode){var t=e.id+"_loading",o=e.id+"_loading-layer",n=document.getElementById(t),a=document.getElementById(o);if(!n){var i=e.tagName.toLowerCase();e.parentNode.style.position="relative",n=document.createElement("span"),n.id=t,n.className="glyphicon glyphicon-refresh glyphicon-refresh-animate","select"===i?n.className+=" loading-icon-select":"checkbox"===e.type?n.className+=" loading-icon-checkbox":n.className+=" loading-icon",e.parentNode.appendChild(n),a=document.createElement("div"),a.className="loading-layer",a.appendChild(document.createTextNode("")),a.id=o,e.parentNode.appendChild(a)}n.style.visibility="visible",a.style.visibility="visible"}},e.bootstrap.hideLoading=function(e){if(e){var t=e.id+"_loading",o=e.id+"_loading-layer",n=document.getElementById(t),a=document.getElementById(o);n&&(n.style.visibility="hidden"),a&&(a.style.visibility="hidden")}},e.onResolutionStarted=e.bootstrap.showLoading,e.onResolutionFinished=e.bootstrap.hideLoading,e.onValidationSuccess=function(e){e.parentNode.className=e.parentNode.className.replace(" has-error","")},e.onValidationError=function(t,o){setTimeout(function(){var n=t.getAttribute("data-toggle"),a=t.getAttribute("data-trigger"),i=t.getAttribute("data-content"),r=t.title;t.setAttribute("data-toggle","popover"),t.setAttribute("data-trigger","manual"),"undefined"==typeof markdown?t.setAttribute("data-content",o):t.setAttribute("data-content",markdown.toHTML(o)),t.title=e.messages.validationError,t.parentNode.className.includes("has-error")||(t.parentNode.className+=" has-error"),t.focus(),$(t).popover({placement:"top",container:"body",html:!0}),$(t).popover("show");var d=t.onblur;t.onblur=function(e){n?($(t).popover("hide"),t.setAttribute("data-toggle",n),t.setAttribute("data-trigger",a),t.setAttribute("data-content",i)):($(t).popover("destroy"),t.removeAttribute("data-toggle"),t.removeAttribute("data-trigger"),t.removeAttribute("data-content")),t.onblur=d,t.title=r,d&&d()}},200)}}(); -------------------------------------------------------------------------------- /dist/js/brutusin-json-forms.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 brutusin.org 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "SuperLicense"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * @author Ignacio del Valle Alles idelvall@brutusin.org 17 | */ 18 | 19 | if (typeof brutusin === "undefined") { 20 | window.brutusin = new Object(); 21 | } else if (typeof brutusin !== "object") { 22 | throw ("brutusin global variable already exists"); 23 | } 24 | 25 | (function () { 26 | if (!String.prototype.startsWith) { 27 | String.prototype.startsWith = function (searchString, position) { 28 | position = position || 0; 29 | return this.indexOf(searchString, position) === position; 30 | }; 31 | } 32 | if (!String.prototype.endsWith) { 33 | String.prototype.endsWith = function (searchString, position) { 34 | var subjectString = this.toString(); 35 | if (position === undefined || position > subjectString.length) { 36 | position = subjectString.length; 37 | } 38 | position -= searchString.length; 39 | var lastIndex = subjectString.indexOf(searchString, position); 40 | return lastIndex !== -1 && lastIndex === position; 41 | }; 42 | } 43 | if (!String.prototype.includes) { 44 | String.prototype.includes = function () { 45 | 'use strict'; 46 | return String.prototype.indexOf.apply(this, arguments) !== -1; 47 | }; 48 | } 49 | if (!String.prototype.format) { 50 | String.prototype.format = function () { 51 | var formatted = this; 52 | for (var i = 0; i < arguments.length; i++) { 53 | var regexp = new RegExp('\\{' + i + '\\}', 'gi'); 54 | formatted = formatted.replace(regexp, arguments[i]); 55 | } 56 | return formatted; 57 | }; 58 | } 59 | 60 | var BrutusinForms = new Object(); 61 | BrutusinForms.messages = { 62 | "validationError": "Validation error", 63 | "required": "This field is **required**", 64 | "invalidValue": "Invalid field value", 65 | "addpropNameExistent": "This property is already present in the object", 66 | "addpropNameRequired": "A name is required", 67 | "minItems": "At least `{0}` items are required", 68 | "maxItems": "At most `{0}` items are allowed", 69 | "pattern": "Value does not match pattern: `{0}`", 70 | "minLength": "Value must be **at least** `{0}` characters long", 71 | "maxLength": "Value must be **at most** `{0}` characters long", 72 | "multipleOf": "Value must be **multiple of** `{0}`", 73 | "minimum": "Value must be **greater or equal than** `{0}`", 74 | "exclusiveMinimum": "Value must be **greater than** `{0}`", 75 | "maximum": "Value must be **lower or equal than** `{0}`", 76 | "exclusiveMaximum": "Value must be **lower than** `{0}`", 77 | "minProperties": "At least `{0}` properties are required", 78 | "maxProperties": "At most `{0}` properties are allowed", 79 | "uniqueItems": "Array items must be unique", 80 | "addItem": "Add item", 81 | "true": "True", 82 | "false": "False" 83 | }; 84 | 85 | /** 86 | * Callback functions to be notified after an HTML element has been rendered (passed as parameter). 87 | * @type type 88 | */ 89 | BrutusinForms.decorators = new Array(); 90 | 91 | BrutusinForms.addDecorator = function (f) { 92 | BrutusinForms.decorators[BrutusinForms.decorators.length] = f; 93 | }; 94 | 95 | BrutusinForms.onResolutionStarted = function (element) { 96 | }; 97 | 98 | BrutusinForms.onResolutionFinished = function (element) { 99 | }; 100 | 101 | BrutusinForms.onValidationError = function (element, message) { 102 | element.focus(); 103 | if (!element.className.includes(" error")) { 104 | element.className += " error"; 105 | } 106 | alert(message); 107 | }; 108 | 109 | BrutusinForms.onValidationSuccess = function (element) { 110 | element.className = element.className.replace(" error", ""); 111 | }; 112 | 113 | /** 114 | * Callback function to be notified after a form has been rendered (passed as parameter). 115 | * @type type 116 | */ 117 | BrutusinForms.postRender = null; 118 | /** 119 | * BrutusinForms instances created in the document 120 | * @type Array 121 | */ 122 | BrutusinForms.instances = new Array(); 123 | /** 124 | * BrutusinForms factory method 125 | * @param {type} schema schema object 126 | * @returns {BrutusinForms.create.obj|Object|Object.create.obj} 127 | */ 128 | BrutusinForms.create = function (schema) { 129 | var SCHEMA_ANY = {"type": "any"}; 130 | var obj = new Object(); 131 | 132 | var schemaMap = new Object(); 133 | var dependencyMap = new Object(); 134 | var renderInfoMap = new Object(); 135 | var container; 136 | var data; 137 | var error; 138 | var initialValue; 139 | var inputCounter = 0; 140 | var root = schema; 141 | var formId = "BrutusinForms#" + BrutusinForms.instances.length; 142 | 143 | renameRequiredPropeties(schema); // required v4 (array) -> requiredProperties 144 | populateSchemaMap("$", schema); 145 | 146 | validateDepencyMapIsAcyclic(); 147 | 148 | var renderers = new Object(); 149 | 150 | renderers["integer"] = function (container, id, parentObject, propertyProvider, value) { 151 | renderers["string"](container, id, parentObject, propertyProvider, value); 152 | }; 153 | 154 | renderers["number"] = function (container, id, parentObject, propertyProvider, value) { 155 | renderers["string"](container, id, parentObject, propertyProvider, value); 156 | }; 157 | 158 | renderers["any"] = function (container, id, parentObject, propertyProvider, value) { 159 | renderers["string"](container, id, parentObject, propertyProvider, value); 160 | }; 161 | 162 | renderers["string"] = function (container, id, parentObject, propertyProvider, value) { 163 | /// TODO change the handler for when there is a 'media' 164 | /// specifier so it becomes a file element. 165 | var schemaId = getSchemaId(id); 166 | var parentId = getParentSchemaId(schemaId); 167 | var s = getSchema(schemaId); 168 | var parentSchema = getSchema(parentId); 169 | var input; 170 | if (s.type === "any") { 171 | input = document.createElement("textarea"); 172 | if (value) { 173 | input.value = JSON.stringify(value, null, 4); 174 | if (s.readOnly) 175 | input.disabled = true; 176 | } 177 | } else if (s.media) { 178 | input = document.createElement("input"); 179 | input.type = "file"; 180 | appendChild(input, option, s); 181 | // XXX TODO, encode the SOB properly. 182 | } else if (s.enum) { 183 | input = document.createElement("select"); 184 | if (!s.required) { 185 | var option = document.createElement("option"); 186 | var textNode = document.createTextNode(""); 187 | option.value = ""; 188 | appendChild(option, textNode, s); 189 | appendChild(input, option, s); 190 | } 191 | var selectedIndex = 0; 192 | for (var i = 0; i < s.enum.length; i++) { 193 | var option = document.createElement("option"); 194 | var textNode = document.createTextNode(s.enum[i]); 195 | option.value = s.enum[i]; 196 | appendChild(option, textNode, s); 197 | appendChild(input, option, s); 198 | if (value && s.enum[i] === value) { 199 | selectedIndex = i; 200 | if (!s.required) { 201 | selectedIndex++; 202 | } 203 | if (s.readOnly) 204 | input.disabled = true; 205 | } 206 | } 207 | if (s.enum.length === 1) 208 | input.selectedIndex = 1; 209 | else 210 | input.selectedIndex = selectedIndex; 211 | } else { 212 | input = document.createElement("input"); 213 | if (s.type === "integer" || s.type === "number") { 214 | input.type = "number"; 215 | input.step = s.step?""+s.step:"any"; 216 | if (typeof value !== "number") { 217 | value = null; 218 | } 219 | } else if (s.format === "date-time") { 220 | try { 221 | input.type = "datetime-local"; 222 | } catch (err) { 223 | // #46, problem in IE11. TODO polyfill? 224 | input.type = "text"; 225 | } 226 | } else if (s.format === "email") { 227 | input.type = "email"; 228 | } else if (s.format === "text") { 229 | input = document.createElement("textarea"); 230 | } else { 231 | input.type = "text"; 232 | } 233 | if (value !== null && typeof value !== "undefined") { 234 | // readOnly? 235 | input.value = value; 236 | if (s.readOnly) 237 | input.disabled = true; 238 | 239 | } 240 | } 241 | input.schema = schemaId; 242 | input.setAttribute("autocorrect", "off"); 243 | 244 | input.getValidationError = function () { 245 | try { 246 | var value = getValue(s, input); 247 | if (value === null) { 248 | if (s.required) { 249 | if (parentSchema && parentSchema.type === "object") { 250 | if (parentSchema.required) { 251 | return BrutusinForms.messages["required"]; 252 | } else { 253 | for (var prop in parentObject) { 254 | if (parentObject[prop] !== null) { 255 | return BrutusinForms.messages["required"]; 256 | } 257 | } 258 | } 259 | } else { 260 | return BrutusinForms.messages["required"]; 261 | } 262 | } 263 | } else { 264 | if (s.pattern && !s.pattern.test(value)) { 265 | return BrutusinForms.messages["pattern"].format(s.pattern.source); 266 | } 267 | if (s.minLength) { 268 | if (!value || s.minLength > value.length) { 269 | return BrutusinForms.messages["minLength"].format(s.minLength); 270 | } 271 | } 272 | if (s.maxLength) { 273 | if (value && s.maxLength < value.length) { 274 | return BrutusinForms.messages["maxLength"].format(s.maxLength); 275 | } 276 | } 277 | } 278 | if (value !== null && !isNaN(value)) { 279 | if (s.multipleOf && value % s.multipleOf !== 0) { 280 | return BrutusinForms.messages["multipleOf"].format(s.multipleOf); 281 | } 282 | if (s.hasOwnProperty("maximum")) { 283 | if (s.exclusiveMaximum && value >= s.maximum) { 284 | return BrutusinForms.messages["exclusiveMaximum"].format(s.maximum); 285 | } else if (!s.exclusiveMaximum && value > s.maximum) { 286 | return BrutusinForms.messages["maximum"].format(s.maximum); 287 | } 288 | } 289 | if (s.hasOwnProperty("minimum")) { 290 | if (s.exclusiveMinimum && value <= s.minimum) { 291 | return BrutusinForms.messages["exclusiveMinimum"].format(s.minimum); 292 | } else if (!s.exclusiveMinimum && value < s.minimum) { 293 | return BrutusinForms.messages["minimum"].format(s.minimum); 294 | } 295 | } 296 | } 297 | } catch (error) { 298 | return BrutusinForms.messages["invalidValue"]; 299 | } 300 | }; 301 | 302 | input.onchange = function () { 303 | var value; 304 | try { 305 | value = getValue(s, input); 306 | } catch (error) { 307 | value = null; 308 | } 309 | if (parentObject) { 310 | parentObject[propertyProvider.getValue()] = value; 311 | } else { 312 | data = value; 313 | } 314 | onDependencyChanged(schemaId, input); 315 | }; 316 | 317 | if (s.description) { 318 | input.title = s.description; 319 | input.placeholder = s.description; 320 | } 321 | // if (s.pattern) { 322 | // input.pattern = s.pattern; 323 | // } 324 | // if (s.required) { 325 | // input.required = true; 326 | // } 327 | // 328 | // if (s.minimum) { 329 | // input.min = s.minimum; 330 | // } 331 | // if (s.maximum) { 332 | // input.max = s.maximum; 333 | // } 334 | input.onchange(); 335 | input.id = getInputId(); 336 | inputCounter++; 337 | appendChild(container, input, s); 338 | return parentObject; 339 | }; 340 | 341 | renderers["boolean"] = function (container, id, parentObject, propertyProvider, value) { 342 | var schemaId = getSchemaId(id); 343 | var s = getSchema(schemaId); 344 | var input; 345 | if (s.required) { 346 | input = document.createElement("input"); 347 | input.type = "checkbox"; 348 | if (value === true) { 349 | input.checked = true; 350 | } 351 | } else { 352 | input = document.createElement("select"); 353 | var emptyOption = document.createElement("option"); 354 | var textEmpty = document.createTextNode(""); 355 | textEmpty.value = ""; 356 | appendChild(emptyOption, textEmpty, s); 357 | appendChild(input, emptyOption, s); 358 | 359 | var optionTrue = document.createElement("option"); 360 | var textTrue = document.createTextNode(BrutusinForms.messages["true"]); 361 | optionTrue.value = "true"; 362 | appendChild(optionTrue, textTrue, s); 363 | appendChild(input, optionTrue, s); 364 | 365 | var optionFalse = document.createElement("option"); 366 | var textFalse = document.createTextNode(BrutusinForms.messages["false"]); 367 | optionFalse.value = "false"; 368 | appendChild(optionFalse, textFalse, s); 369 | appendChild(input, optionFalse, s); 370 | 371 | if (value === true) { 372 | input.selectedIndex = 1; 373 | } else if (value === false) { 374 | input.selectedIndex = 2; 375 | } 376 | } 377 | input.onchange = function () { 378 | if (parentObject) { 379 | parentObject[propertyProvider.getValue()] = getValue(s, input); 380 | } else { 381 | data = getValue(s, input); 382 | } 383 | onDependencyChanged(schemaId, input); 384 | }; 385 | input.schema = schemaId; 386 | input.id = getInputId(); 387 | inputCounter++; 388 | if (s.description) { 389 | input.title = s.description; 390 | } 391 | input.onchange(); 392 | appendChild(container, input, s); 393 | }; 394 | 395 | renderers["oneOf"] = function (container, id, parentObject, propertyProvider, value) { 396 | var schemaId = getSchemaId(id); 397 | var s = getSchema(schemaId); 398 | var input = document.createElement("select"); 399 | var display = document.createElement("div"); 400 | display.innerHTML = ""; 401 | input.type = "select"; 402 | input.schema = schemaId; 403 | var noption = document.createElement("option"); 404 | noption.value = null; 405 | appendChild(input, noption, s); 406 | for (var i = 0; i < s.oneOf.length; i++) { 407 | var option = document.createElement("option"); 408 | var propId = schemaId + "." + i; 409 | var ss = getSchema(propId); 410 | var textNode = document.createTextNode(ss.title); 411 | option.value = s.oneOf[i]; 412 | appendChild(option, textNode, s); 413 | appendChild(input, option, s); 414 | if (value === undefined || value === null) 415 | continue; 416 | if (s.readOnly) 417 | input.disabled = true; 418 | if (value.hasOwnProperty("type")) { 419 | if (ss.hasOwnProperty("properties")) { 420 | if (ss.properties.hasOwnProperty("type")) { 421 | var tryit = getSchema(ss.properties.type); 422 | if (value.type === tryit.enum[0]) { 423 | input.selectedIndex = i + 1; 424 | render(null, display, id + "." + (input.selectedIndex - 1), parentObject, propertyProvider, value); 425 | } 426 | } 427 | } 428 | } 429 | } 430 | input.onchange = function () { 431 | render(null, display, id + "." + (input.selectedIndex - 1), parentObject, propertyProvider, value); 432 | }; 433 | appendChild(container, input, s); 434 | appendChild(container, display, s); 435 | 436 | }; 437 | 438 | renderers["object"] = function (container, id, parentObject, propertyProvider, value) { 439 | 440 | function createStaticPropertyProvider(propname) { 441 | var ret = new Object(); 442 | ret.getValue = function () { 443 | return propname; 444 | }; 445 | ret.onchange = function (oldName) { 446 | }; 447 | return ret; 448 | } 449 | 450 | function addAdditionalProperty(current, table, id, name, value, pattern) { 451 | var schemaId = getSchemaId(id); 452 | var s = getSchema(schemaId); 453 | var tbody = table.tBodies[0]; 454 | var tr = document.createElement("tr"); 455 | var td1 = document.createElement("td"); 456 | td1.className = "add-prop-name"; 457 | var innerTab = document.createElement("table"); 458 | var innerTr = document.createElement("tr"); 459 | var innerTd1 = document.createElement("td"); 460 | var innerTd2 = document.createElement("td"); 461 | var keyForBlank = "$" + Object.keys(current).length + "$"; 462 | var td2 = document.createElement("td"); 463 | td2.className = "prop-value"; 464 | var nameInput = document.createElement("input"); 465 | nameInput.type = "text"; 466 | var regExp; 467 | if (pattern) { 468 | regExp = RegExp(pattern); 469 | } 470 | nameInput.getValidationError = function () { 471 | if (nameInput.previousValue !== nameInput.value) { 472 | if (current.hasOwnProperty(nameInput.value)) { 473 | return BrutusinForms.messages["addpropNameExistent"]; 474 | } 475 | } 476 | if (!nameInput.value) { 477 | return BrutusinForms.messages["addpropNameRequired"]; 478 | } 479 | }; 480 | var pp = createPropertyProvider( 481 | function () { 482 | if (nameInput.value) { 483 | if (regExp) { 484 | if (nameInput.value.search(regExp) !== -1) { 485 | return nameInput.value; 486 | } 487 | } else { 488 | return nameInput.value; 489 | } 490 | } 491 | return keyForBlank; 492 | }, 493 | function (oldPropertyName) { 494 | if (pp.getValue() === oldPropertyName) { 495 | return; 496 | } 497 | if (!oldPropertyName || !current.hasOwnProperty(oldPropertyName)) { 498 | oldPropertyName = keyForBlank; 499 | } 500 | if (current.hasOwnProperty(oldPropertyName) || regExp && pp.getValue().search(regExp) === -1) { 501 | current[pp.getValue()] = current[oldPropertyName]; 502 | delete current[oldPropertyName]; 503 | } 504 | }); 505 | 506 | nameInput.onblur = function () { 507 | if (nameInput.previousValue !== nameInput.value) { 508 | var name = nameInput.value; 509 | var i = 1; 510 | while (nameInput.previousValue !== name && current.hasOwnProperty(name)) { 511 | name = nameInput.value + "(" + i + ")"; 512 | i++; 513 | } 514 | nameInput.value = name; 515 | pp.onchange(nameInput.previousValue); 516 | nameInput.previousValue = nameInput.value; 517 | return; 518 | } 519 | }; 520 | var removeButton = document.createElement("button"); 521 | removeButton.setAttribute('type', 'button'); 522 | removeButton.className = "remove"; 523 | appendChild(removeButton, document.createTextNode("x"), s); 524 | removeButton.onclick = function () { 525 | delete current[nameInput.value]; 526 | table.deleteRow(tr.rowIndex); 527 | nameInput.value = null; 528 | pp.onchange(nameInput.previousValue); 529 | }; 530 | appendChild(innerTd1, nameInput, s); 531 | appendChild(innerTd2, removeButton, s); 532 | appendChild(innerTr, innerTd1, s); 533 | appendChild(innerTr, innerTd2, s); 534 | appendChild(innerTab, innerTr, s); 535 | appendChild(td1, innerTab, s); 536 | 537 | if (pattern !== undefined) { 538 | nameInput.placeholder = pattern; 539 | } 540 | 541 | appendChild(tr, td1, s); 542 | appendChild(tr, td2, s); 543 | appendChild(tbody, tr, s); 544 | appendChild(table, tbody, s); 545 | render(null, td2, id, current, pp, value); 546 | 547 | if (name) { 548 | nameInput.value = name; 549 | nameInput.onblur(); 550 | } 551 | } 552 | 553 | var schemaId = getSchemaId(id); 554 | var s = getSchema(schemaId); 555 | var current = new Object(); 556 | if (!parentObject) { 557 | data = current; 558 | } else { 559 | if (propertyProvider.getValue() || propertyProvider.getValue() === 0) { 560 | parentObject[propertyProvider.getValue()] = current; 561 | } 562 | } 563 | var table = document.createElement("table"); 564 | table.className = "object"; 565 | var tbody = document.createElement("tbody"); 566 | appendChild(table, tbody, s); 567 | var propNum = 0; 568 | if (s.hasOwnProperty("properties")) { 569 | propNum = s.properties.length; 570 | for (var prop in s.properties) { 571 | var tr = document.createElement("tr"); 572 | var td1 = document.createElement("td"); 573 | td1.className = "prop-name"; 574 | var propId = id + "." + prop; 575 | var propSchema = getSchema(getSchemaId(propId)); 576 | var td2 = document.createElement("td"); 577 | td2.className = "prop-value"; 578 | 579 | appendChild(tbody, tr, propSchema); 580 | appendChild(tr, td1, propSchema); 581 | appendChild(tr, td2, propSchema); 582 | var pp = createStaticPropertyProvider(prop); 583 | var propInitialValue = null; 584 | if (value) { 585 | propInitialValue = value[prop]; 586 | } 587 | render(td1, td2, propId, current, pp, propInitialValue); 588 | } 589 | } 590 | var usedProps = []; 591 | if (s.patternProperties || s.additionalProperties) { 592 | var div = document.createElement("div"); 593 | appendChild(div, table, s); 594 | if (s.patternProperties) { 595 | for (var pattern in s.patternProperties) { 596 | var patProps = s.patternProperties[pattern]; 597 | var patdiv = document.createElement("div"); 598 | patdiv.className = "add-pattern-div"; 599 | var addButton = document.createElement("button"); 600 | addButton.setAttribute('type', 'button'); 601 | addButton.pattern = pattern; 602 | addButton.id = id + "[" + pattern + "]"; 603 | addButton.onclick = function () { 604 | addAdditionalProperty(current, table, this.id, undefined, undefined, this.pattern); 605 | }; 606 | if (s.maxProperties || s.minProperties) { 607 | addButton.getValidationError = function () { 608 | if (s.minProperties && propNum + table.rows.length < s.minProperties) { 609 | return BrutusinForms.messages["minProperties"].format(s.minProperties); 610 | } 611 | if (s.maxProperties && propNum + table.rows.length > s.maxProperties) { 612 | return BrutusinForms.messages["maxProperties"].format(s.maxProperties); 613 | } 614 | }; 615 | } 616 | if (patProps.description) { 617 | addButton.title = patProps.description; 618 | } 619 | appendChild(addButton, document.createTextNode("Add " + pattern), s); 620 | appendChild(patdiv, addButton, s); 621 | if (value) { 622 | for (var p in value) { 623 | if (s.properties && s.properties.hasOwnProperty(p)) { 624 | continue; 625 | } 626 | var r = RegExp(pattern); 627 | if (p.search(r) === -1) { 628 | continue; 629 | } 630 | if (usedProps.indexOf(p) !== -1) { 631 | continue; 632 | } 633 | addAdditionalProperty(current, table, id + "[" + pattern + "]", p, value[p], pattern); 634 | usedProps.push(p); 635 | } 636 | } 637 | appendChild(div, patdiv, s); 638 | } 639 | } 640 | if (s.additionalProperties) { 641 | var addPropS = getSchema(s.additionalProperties); 642 | var addButton = document.createElement("button"); 643 | addButton.setAttribute('type', 'button'); 644 | addButton.onclick = function () { 645 | addAdditionalProperty(current, table, id + "[*]", undefined); 646 | }; 647 | if (s.maxProperties || s.minProperties) { 648 | addButton.getValidationError = function () { 649 | if (s.minProperties && propNum + table.rows.length < s.minProperties) { 650 | return BrutusinForms.messages["minProperties"].format(s.minProperties); 651 | } 652 | if (s.maxProperties && propNum + table.rows.length > s.maxProperties) { 653 | return BrutusinForms.messages["maxProperties"].format(s.maxProperties); 654 | } 655 | }; 656 | } 657 | if (addPropS.description) { 658 | addButton.title = addPropS.description; 659 | } 660 | appendChild(addButton, document.createTextNode("Add"), s); 661 | appendChild(div, addButton, s); 662 | if (value) { 663 | for (var p in value) { 664 | if (s.properties && s.properties.hasOwnProperty(p)) { 665 | continue; 666 | } 667 | if (usedProps.indexOf(p) !== -1) { 668 | continue; 669 | } 670 | addAdditionalProperty(current, table, id + "[\"" + prop + "\"]", p, value[p]); 671 | } 672 | } 673 | } 674 | appendChild(container, div, s); 675 | } else { 676 | appendChild(container, table, s); 677 | } 678 | }; 679 | // end of object renderer 680 | renderers["array"] = function (container, id, parentObject, propertyProvider, value) { 681 | function addItem(current, table, id, value, readOnly) { 682 | var schemaId = getSchemaId(id); 683 | var s = getSchema(schemaId); 684 | var tbody = document.createElement("tbody"); 685 | var tr = document.createElement("tr"); 686 | tr.className = "item"; 687 | var td1 = document.createElement("td"); 688 | td1.className = "item-index"; 689 | var td2 = document.createElement("td"); 690 | td2.className = "item-action"; 691 | var td3 = document.createElement("td"); 692 | td3.className = "item-value"; 693 | var removeButton = document.createElement("button"); 694 | removeButton.setAttribute('type', 'button'); 695 | removeButton.className = "remove"; 696 | if (readOnly === true) 697 | removeButton.disabled = true; 698 | appendChild(removeButton, document.createTextNode("x"), s); 699 | var computRowCount = function () { 700 | for (var i = 0; i < table.rows.length; i++) { 701 | var row = table.rows[i]; 702 | row.cells[0].innerHTML = i + 1; 703 | } 704 | }; 705 | removeButton.onclick = function () { 706 | current.splice(tr.rowIndex, 1); 707 | table.deleteRow(tr.rowIndex); 708 | computRowCount(); 709 | }; 710 | appendChild(td2, removeButton, s); 711 | var number = document.createTextNode(table.rows.length + 1); 712 | appendChild(td1, number, s); 713 | appendChild(tr, td1, s); 714 | appendChild(tr, td2, s); 715 | appendChild(tr, td3, s); 716 | appendChild(tbody, tr, s); 717 | appendChild(table, tbody, s); 718 | var pp = createPropertyProvider(function () { 719 | return tr.rowIndex; 720 | }); 721 | render(null, td3, id, current, pp, value); 722 | } 723 | 724 | var schemaId = getSchemaId(id); 725 | var s = getSchema(schemaId); 726 | var itemS = getSchema(s.items); 727 | var current = new Array(); 728 | if (!parentObject) { 729 | data = current; 730 | } else { 731 | if (propertyProvider.getValue() || propertyProvider.getValue() === 0) { 732 | parentObject[propertyProvider.getValue()] = current; 733 | } 734 | } 735 | if (propertyProvider) { 736 | propertyProvider.onchange = function (oldPropertyName) { 737 | delete parentObject[oldPropertyName]; 738 | parentObject[propertyProvider.getValue()] = current; 739 | }; 740 | } 741 | var div = document.createElement("div"); 742 | var table = document.createElement("table"); 743 | table.className = "array"; 744 | appendChild(div, table, s); 745 | appendChild(container, div, s); 746 | var addButton = document.createElement("button"); 747 | if (s.readOnly) 748 | addButton.disabled = true; 749 | addButton.setAttribute('type', 'button'); 750 | addButton.getValidationError = function () { 751 | if (s.minItems && s.minItems > table.rows.length) { 752 | return BrutusinForms.messages["minItems"].format(s.minItems); 753 | } 754 | if (s.maxItems && s.maxItems < table.rows.length) { 755 | return BrutusinForms.messages["maxItems"].format(s.maxItems); 756 | } 757 | if (s.uniqueItems) { 758 | for (var i = 0; i < current.length; i++) { 759 | for (var j = i + 1; j < current.length; j++) { 760 | if (JSON.stringify(current[i]) === JSON.stringify(current[j])) { 761 | return BrutusinForms.messages["uniqueItems"]; 762 | } 763 | } 764 | } 765 | } 766 | }; 767 | addButton.onclick = function () { 768 | addItem(current, table, id + "[#]", null); 769 | }; 770 | if (itemS.description) { 771 | addButton.title = itemS.description; 772 | } 773 | appendChild(addButton, document.createTextNode(BrutusinForms.messages["addItem"]), s); 774 | appendChild(div, table, s); 775 | appendChild(div, addButton, s); 776 | if (value && value instanceof Array) { 777 | for (var i = 0; i < value.length; i++) { 778 | addItem(current, table, id + "[" + i + "]", value[i], s.readOnly); 779 | } 780 | } 781 | appendChild(container, div, s); 782 | }; 783 | // end of array render 784 | /** 785 | * Renders the form inside the the container, with the specified data preloaded 786 | * @param {type} c container 787 | * @param {type} data json data 788 | * @returns {undefined} 789 | */ 790 | obj.render = function (c, data) { 791 | container = c; 792 | initialValue = data; 793 | var form = document.createElement("form"); 794 | form.className = "brutusin-form"; 795 | form.onsubmit = function (event) { 796 | return false; 797 | }; 798 | if (container) { 799 | appendChild(container, form); 800 | } else { 801 | appendChild(document.body, form); 802 | } 803 | if (error) { 804 | var errLabel = document.createElement("label"); 805 | var errNode = document.createTextNode(error); 806 | appendChild(errLabel, errNode); 807 | errLabel.className = "error-message"; 808 | appendChild(form, errLabel); 809 | } else { 810 | render(null, form, "$", null, null); 811 | } 812 | if (dependencyMap.hasOwnProperty("$")) { 813 | onDependencyChanged("$"); 814 | } 815 | if (BrutusinForms.postRender) { 816 | BrutusinForms.postRender(obj); 817 | } 818 | }; 819 | 820 | obj.getRenderingContainer = function () { 821 | return container; 822 | }; 823 | 824 | obj.validate = function () { 825 | return validate(container); 826 | }; 827 | 828 | obj.getData = function () { 829 | function removeEmptiesAndNulls(object, s) { 830 | if (ss === null) { 831 | ss = SCHEMA_ANY; 832 | } 833 | if (s.$ref) { 834 | s = getDefinition(s.$ref); 835 | } 836 | if (object instanceof Array) { 837 | if (object.length === 0) { 838 | return null; 839 | } 840 | var clone = new Array(); 841 | for (var i = 0; i < object.length; i++) { 842 | clone[i] = removeEmptiesAndNulls(object[i], s.items); 843 | } 844 | return clone; 845 | } else if (object === "") { 846 | return null; 847 | } else if (object instanceof Object) { 848 | var clone = new Object(); 849 | var nonEmpty = false; 850 | for (var prop in object) { 851 | if (prop.startsWith("$") && prop.endsWith("$")) { 852 | continue; 853 | } 854 | var ss = null; 855 | if (s.hasOwnProperty("properties") && s.properties.hasOwnProperty(prop)) { 856 | ss = s.properties[prop]; 857 | } 858 | if (ss === null && s.hasOwnProperty("additionalProperties")) { 859 | if (typeof s.additionalProperties === 'object') { 860 | ss = s.additionalProperties; 861 | } 862 | } 863 | if (ss === null && s.hasOwnProperty("patternProperties")) { 864 | for (var p in s.patternProperties) { 865 | var r = RegExp(p); 866 | if (prop.search(r) !== -1) { 867 | ss = s.patternProperties[p]; 868 | break; 869 | } 870 | } 871 | } 872 | var value = removeEmptiesAndNulls(object[prop], ss); 873 | if (value !== null) { 874 | clone[prop] = value; 875 | nonEmpty = true; 876 | } 877 | } 878 | if (nonEmpty || s.required) { 879 | return clone; 880 | } else { 881 | return null; 882 | } 883 | } else { 884 | return object; 885 | } 886 | } 887 | if (!container) { 888 | return null; 889 | } else { 890 | return removeEmptiesAndNulls(data, schema); 891 | } 892 | }; 893 | 894 | BrutusinForms.instances[BrutusinForms.instances.length] = obj; 895 | 896 | return obj; 897 | 898 | function validateDepencyMapIsAcyclic() { 899 | function dfs(visitInfo, stack, id) { 900 | if (stack.hasOwnProperty(id)) { 901 | error = "Schema dependency graph has cycles"; 902 | return; 903 | } 904 | stack[id] = null; 905 | if (visitInfo.hasOwnProperty(id)) { 906 | return; 907 | } 908 | visitInfo[id] = null; 909 | var arr = dependencyMap[id]; 910 | if (arr) { 911 | for (var i = 0; i < arr.length; i++) { 912 | dfs(visitInfo, stack, arr[i]); 913 | } 914 | } 915 | delete stack[id]; 916 | } 917 | var visitInfo = new Object(); 918 | for (var id in dependencyMap) { 919 | if (visitInfo.hasOwnProperty(id)) { 920 | continue; 921 | } 922 | dfs(visitInfo, new Object(), id); 923 | } 924 | } 925 | 926 | function appendChild(parent, child, schema) { 927 | parent.appendChild(child); 928 | for (var i = 0; i < BrutusinForms.decorators.length; i++) { 929 | BrutusinForms.decorators[i](child, schema); 930 | } 931 | } 932 | 933 | function createPseudoSchema(schema) { 934 | var pseudoSchema = new Object(); 935 | for (var p in schema) { 936 | if (p === "items" || p === "properties" || p === "additionalProperties") { 937 | continue; 938 | } 939 | if (p === "pattern") { 940 | pseudoSchema[p] = new RegExp(schema[p]); 941 | } else { 942 | pseudoSchema[p] = schema[p]; 943 | } 944 | 945 | } 946 | return pseudoSchema; 947 | } 948 | 949 | function getDefinition(path) { 950 | var parts = path.split('/'); 951 | var def = root; 952 | for (var p in parts) { 953 | if (p === "0") 954 | continue; 955 | def = def[parts[p]]; 956 | 957 | } 958 | return def; 959 | } 960 | 961 | function containsStr(array, string) { 962 | for (var i = 0; i < array.length; i++) { 963 | if (array[i] == string) { 964 | return true; 965 | } 966 | } 967 | return false; 968 | } 969 | 970 | function renameRequiredPropeties(schema) { 971 | if (!schema) { 972 | return; 973 | } else if (schema.hasOwnProperty("oneOf")) { 974 | for (var i in schema.oneOf) { 975 | renameRequiredPropeties(schema.oneOf[i]); 976 | } 977 | } else if (schema.hasOwnProperty("$ref")) { 978 | var newSchema = getDefinition(schema["$ref"]); 979 | renameRequiredPropeties(newSchema); 980 | } else if (schema.type === "object") { 981 | if (schema.properties) { 982 | if (schema.hasOwnProperty("required")) { 983 | if (Array.isArray(schema.required)) { 984 | schema.requiredProperties = schema.required; 985 | delete schema.required; 986 | } 987 | } 988 | for (var prop in schema.properties) { 989 | renameRequiredPropeties(schema.properties[prop]); 990 | } 991 | } 992 | if (schema.patternProperties) { 993 | for (var pat in schema.patternProperties) { 994 | var s = schema.patternProperties[pat]; 995 | if (s.hasOwnProperty("type") || s.hasOwnProperty("$ref") || s.hasOwnProperty("oneOf")) { 996 | renameRequiredPropeties(schema.patternProperties[pat]); 997 | } 998 | } 999 | } 1000 | if (schema.additionalProperties) { 1001 | if (schema.additionalProperties.hasOwnProperty("type") || schema.additionalProperties.hasOwnProperty("oneOf")) { 1002 | renameRequiredPropeties(schema.additionalProperties); 1003 | 1004 | } 1005 | } 1006 | } else if (schema.type === "array") { 1007 | renameRequiredPropeties(schema.items); 1008 | } 1009 | } 1010 | 1011 | function populateSchemaMap(name, schema) { 1012 | var pseudoSchema = createPseudoSchema(schema); 1013 | pseudoSchema["$id"] = name; 1014 | schemaMap[name] = pseudoSchema; 1015 | 1016 | if (!schema) { 1017 | return; 1018 | } else if (schema.hasOwnProperty("oneOf")) { 1019 | pseudoSchema.oneOf = new Array(); 1020 | pseudoSchema.type = "oneOf"; 1021 | for (var i in schema.oneOf) { 1022 | var childProp = name + "." + i; 1023 | pseudoSchema.oneOf[i] = childProp; 1024 | populateSchemaMap(childProp, schema.oneOf[i]); 1025 | } 1026 | } else if (schema.hasOwnProperty("$ref")) { 1027 | var refSchema = getDefinition(schema["$ref"]); 1028 | if (refSchema) { 1029 | if (schema.hasOwnProperty("title") || schema.hasOwnProperty("description")) { 1030 | var clonedRefSchema = {}; 1031 | for (var prop in refSchema) { 1032 | clonedRefSchema[prop] = refSchema[prop]; 1033 | } 1034 | if (schema.hasOwnProperty("title")) { 1035 | clonedRefSchema.title = schema.title; 1036 | } 1037 | if (schema.hasOwnProperty("description")) { 1038 | clonedRefSchema.description = schema.description; 1039 | } 1040 | refSchema = clonedRefSchema; 1041 | } 1042 | populateSchemaMap(name, refSchema); 1043 | } 1044 | } else if (schema.type === "object") { 1045 | if (schema.properties) { 1046 | pseudoSchema.properties = new Object(); 1047 | for (var prop in schema.properties) { 1048 | var childProp = name + "." + prop; 1049 | pseudoSchema.properties[prop] = childProp; 1050 | var subSchema = schema.properties[prop]; 1051 | if (schema.requiredProperties) { 1052 | if (containsStr(schema.requiredProperties, prop)) { 1053 | subSchema.required = true; 1054 | } else { 1055 | subSchema.required = false; 1056 | } 1057 | } 1058 | populateSchemaMap(childProp, subSchema); 1059 | } 1060 | } 1061 | if (schema.patternProperties) { 1062 | pseudoSchema.patternProperties = new Object(); 1063 | for (var pat in schema.patternProperties) { 1064 | var patChildProp = name + "[" + pat + "]"; 1065 | pseudoSchema.patternProperties[pat] = patChildProp; 1066 | var s = schema.patternProperties[pat]; 1067 | 1068 | if (s.hasOwnProperty("type") || s.hasOwnProperty("$ref") || 1069 | s.hasOwnProperty("oneOf")) { 1070 | populateSchemaMap(patChildProp, schema.patternProperties[pat]); 1071 | } else { 1072 | populateSchemaMap(patChildProp, SCHEMA_ANY); 1073 | } 1074 | } 1075 | } 1076 | if (schema.additionalProperties) { 1077 | var childProp = name + "[*]"; 1078 | pseudoSchema.additionalProperties = childProp; 1079 | if (schema.additionalProperties.hasOwnProperty("type") || 1080 | schema.additionalProperties.hasOwnProperty("oneOf")) { 1081 | populateSchemaMap(childProp, schema.additionalProperties); 1082 | } else { 1083 | populateSchemaMap(childProp, SCHEMA_ANY); 1084 | } 1085 | } 1086 | } else if (schema.type === "array") { 1087 | pseudoSchema.items = name + "[#]"; 1088 | populateSchemaMap(pseudoSchema.items, schema.items); 1089 | } 1090 | if (schema.hasOwnProperty("dependsOn")) { 1091 | if (schema.dependsOn === null) { 1092 | schema.dependsOn = ["$"]; 1093 | } 1094 | var arr = new Array(); 1095 | for (var i = 0; i < schema.dependsOn.length; i++) { 1096 | if (!schema.dependsOn[i]) { 1097 | arr[i] = "$"; 1098 | // Relative cases 1099 | } else if (schema.dependsOn[i].startsWith("$")) { 1100 | arr[i] = schema.dependsOn[i]; 1101 | // Relative cases 1102 | } else if (name.endsWith("]")) { 1103 | arr[i] = name + "." + schema.dependsOn[i]; 1104 | } else { 1105 | arr[i] = name.substring(0, name.lastIndexOf(".")) + "." + schema.dependsOn[i]; 1106 | } 1107 | } 1108 | schemaMap[name].dependsOn = arr; 1109 | for (var i = 0; i < arr.length; i++) { 1110 | var entry = dependencyMap[arr[i]]; 1111 | if (!entry) { 1112 | entry = new Array(); 1113 | dependencyMap[arr[i]] = entry; 1114 | } 1115 | entry[entry.length] = name; 1116 | } 1117 | } 1118 | } 1119 | 1120 | function renderTitle(container, title, schema) { 1121 | if (container) { 1122 | if (title) { 1123 | var titleLabel = document.createElement("label"); 1124 | if (schema.type !== "any" && schema.type !== "object" && schema.type !== "array") { 1125 | titleLabel.htmlFor = getInputId(); 1126 | } 1127 | var titleNode = document.createTextNode(title + ":"); 1128 | appendChild(titleLabel, titleNode, schema); 1129 | if (schema.description) { 1130 | titleLabel.title = schema.description; 1131 | } 1132 | if (schema.required) { 1133 | var sup = document.createElement("sup"); 1134 | appendChild(sup, document.createTextNode("*"), schema); 1135 | appendChild(titleLabel, sup, schema); 1136 | titleLabel.className = "required"; 1137 | } 1138 | appendChild(container, titleLabel, schema); 1139 | } 1140 | } 1141 | } 1142 | 1143 | function getInputId() { 1144 | return formId + "_" + inputCounter; 1145 | } 1146 | 1147 | function validate(element) { 1148 | var ret = true; 1149 | if (element.hasOwnProperty("getValidationError")) { 1150 | var error = element.getValidationError(); 1151 | if (error) { 1152 | BrutusinForms.onValidationError(element, error); 1153 | ret = false; 1154 | } else { 1155 | BrutusinForms.onValidationSuccess(element); 1156 | } 1157 | } 1158 | if (element.childNodes) { 1159 | for (var i = 0; i < element.childNodes.length; i++) { 1160 | if (!validate(element.childNodes[i])) { 1161 | ret = false; 1162 | } 1163 | } 1164 | } 1165 | return ret; 1166 | } 1167 | 1168 | function clear(container) { 1169 | if (container) { 1170 | while (container.firstChild) { 1171 | container.removeChild(container.firstChild); 1172 | } 1173 | } 1174 | } 1175 | 1176 | function render(titleContainer, container, id, parentObject, propertyProvider, value) { 1177 | //console.log(id); 1178 | var schemaId = getSchemaId(id); 1179 | var s = getSchema(schemaId); 1180 | renderInfoMap[schemaId] = new Object(); 1181 | renderInfoMap[schemaId].titleContainer = titleContainer; 1182 | renderInfoMap[schemaId].container = container; 1183 | renderInfoMap[schemaId].parentObject = parentObject; 1184 | renderInfoMap[schemaId].propertyProvider = propertyProvider; 1185 | renderInfoMap[schemaId].value = value; 1186 | clear(titleContainer); 1187 | clear(container); 1188 | //console.log(id,s,value); 1189 | var r = renderers[s.type]; 1190 | if (r && !s.dependsOn) { 1191 | if (s.title) { 1192 | renderTitle(titleContainer, s.title, s); 1193 | } else if (propertyProvider) { 1194 | renderTitle(titleContainer, propertyProvider.getValue(), s); 1195 | } 1196 | if (!value) { 1197 | if (typeof initialValue !== "undefined" && initialValue !== null) { 1198 | value = getInitialValue(id); 1199 | } else { 1200 | value = s.default; 1201 | } 1202 | } 1203 | r(container, id, parentObject, propertyProvider, value); 1204 | } else if (s.$ref) { 1205 | if (obj.schemaResolver) { 1206 | var cb = function (schemas) { 1207 | if (schemas && schemas.hasOwnProperty(id)) { 1208 | if (JSON.stringify(schemaMap[id]) !== JSON.stringify(schemas[id])) { 1209 | cleanSchemaMap(id); 1210 | cleanData(id); 1211 | populateSchemaMap(id, schemas[id]); 1212 | var renderInfo = renderInfoMap[id]; 1213 | if (renderInfo) { 1214 | render(renderInfo.titleContainer, renderInfo.container, id, renderInfo.parentObject, renderInfo.propertyProvider, renderInfo.value); 1215 | } 1216 | } 1217 | } 1218 | BrutusinForms.onResolutionFinished(parentObject); 1219 | }; 1220 | BrutusinForms.onResolutionStarted(parentObject); 1221 | obj.schemaResolver([id], obj.getData(), cb); 1222 | } 1223 | } 1224 | } 1225 | 1226 | /** 1227 | * Used in object additionalProperties and arrays 1228 | * @param {type} getValue 1229 | * @param {type} onchange 1230 | * @returns {Object.create.createPropertyProvider.ret} 1231 | */ 1232 | function createPropertyProvider(getValue, onchange) { 1233 | var ret = new Object(); 1234 | ret.getValue = getValue; 1235 | ret.onchange = onchange; 1236 | return ret; 1237 | } 1238 | 1239 | function getInitialValue(id) { 1240 | var ret; 1241 | try { 1242 | eval("ret = initialValue" + id.substring(1)); 1243 | } catch (e) { 1244 | ret = null; 1245 | } 1246 | return ret; 1247 | } 1248 | 1249 | function getValue(schema, input) { 1250 | if (typeof input.getValue === "function") { 1251 | return input.getValue(); 1252 | } 1253 | var value; 1254 | 1255 | if (input.tagName.toLowerCase() === "select") { 1256 | value = input.options[input.selectedIndex].value; 1257 | } else { 1258 | value = input.value; 1259 | } 1260 | if (value === "") { 1261 | return null; 1262 | } 1263 | if (schema.type === "integer") { 1264 | value = parseInt(value); 1265 | if (!isFinite(value)) { 1266 | value = null; 1267 | } 1268 | } else if (schema.type === "number") { 1269 | value = parseFloat(value); 1270 | if (!isFinite(value)) { 1271 | value = null; 1272 | } 1273 | } else if (schema.type === "boolean") { 1274 | if (input.tagName.toLowerCase() === "input") { 1275 | value = input.checked; 1276 | if (!value) { 1277 | value = false; 1278 | } 1279 | } else if (input.tagName.toLowerCase() === "select") { 1280 | if (input.value === "true") { 1281 | value = true; 1282 | } else if (input.value === "false") { 1283 | value = false; 1284 | } else { 1285 | value = null; 1286 | } 1287 | } 1288 | } else if (schema.type === "any") { 1289 | if (value) { 1290 | eval("value=" + value); 1291 | } 1292 | } 1293 | return value; 1294 | } 1295 | 1296 | function getSchemaId(id) { 1297 | return id.replace(/\["[^"]*"\]/g, "[*]").replace(/\[\d*\]/g, "[#]"); 1298 | } 1299 | 1300 | function getParentSchemaId(id) { 1301 | return id.substring(0, id.lastIndexOf(".")); 1302 | } 1303 | 1304 | function getSchema(schemaId) { 1305 | return schemaMap[schemaId]; 1306 | } 1307 | 1308 | function cleanSchemaMap(schemaId) { 1309 | for (var prop in schemaMap) { 1310 | if (schemaId.startsWith(prop)) { 1311 | delete schemaMap[prop]; 1312 | } 1313 | } 1314 | } 1315 | function cleanData(schemaId) { 1316 | var expression = new Expression(schemaId); 1317 | expression.visit(data, function (data, parent, property) { 1318 | delete parent[property]; 1319 | }); 1320 | } 1321 | 1322 | function onDependencyChanged(name, source) { 1323 | 1324 | var arr = dependencyMap[name]; 1325 | if (!arr || !obj.schemaResolver) { 1326 | return; 1327 | } 1328 | var cb = function (schemas) { 1329 | if (schemas) { 1330 | for (var id in schemas) { 1331 | if (JSON.stringify(schemaMap[id]) !== JSON.stringify(schemas[id])) { 1332 | cleanSchemaMap(id); 1333 | cleanData(id); 1334 | populateSchemaMap(id, schemas[id]); 1335 | var renderInfo = renderInfoMap[id]; 1336 | if (renderInfo) { 1337 | render(renderInfo.titleContainer, renderInfo.container, id, renderInfo.parentObject, renderInfo.propertyProvider, renderInfo.value); 1338 | } 1339 | } 1340 | } 1341 | } 1342 | BrutusinForms.onResolutionFinished(source); 1343 | }; 1344 | BrutusinForms.onResolutionStarted(source); 1345 | obj.schemaResolver(arr, obj.getData(), cb); 1346 | 1347 | 1348 | } 1349 | 1350 | function Expression(exp) { 1351 | if (exp === null || exp.length === 0 || exp === ".") { 1352 | exp = "$"; 1353 | } 1354 | var queue = new Array(); 1355 | var tokens = parseTokens(exp); 1356 | var isInBracket = false; 1357 | var numInBracket = 0; 1358 | var sb = ""; 1359 | for (var i = 0; i < tokens.length; i++) { 1360 | var token = tokens[i]; 1361 | if (token === "[") { 1362 | if (isInBracket) { 1363 | throw ("Error parsing expression '" + exp + "': Nested [ found"); 1364 | } 1365 | isInBracket = true; 1366 | numInBracket = 0; 1367 | sb = sb + token; 1368 | } else if (token === "]") { 1369 | if (!isInBracket) { 1370 | throw ("Error parsing expression '" + exp + "': Unbalanced ] found"); 1371 | } 1372 | isInBracket = false; 1373 | sb = sb + token; 1374 | queue[queue.length] = sb; 1375 | sb = ""; 1376 | } else { 1377 | if (isInBracket) { 1378 | if (numInBracket > 0) { 1379 | throw ("Error parsing expression '" + exp + "': Multiple tokens found inside a bracket"); 1380 | } 1381 | sb = sb + token; 1382 | numInBracket++; 1383 | } else { 1384 | queue[queue.length] = token; 1385 | } 1386 | } 1387 | if (i === tokens.length - 1) { 1388 | if (isInBracket) { 1389 | throw ("Error parsing expression '" + exp + "': Unbalanced [ found"); 1390 | } 1391 | } 1392 | } 1393 | this.exp = exp; 1394 | this.queue = queue; 1395 | this.visit = function (data, visitor) { 1396 | function visit(name, queue, data, parentData, property) { 1397 | if (data == null) { 1398 | return; 1399 | } 1400 | var currentToken = queue.shift(); 1401 | if (currentToken === "$") { 1402 | name = "$"; 1403 | var currentToken = queue.shift(); 1404 | } 1405 | if (!currentToken) { 1406 | visitor(data, parentData, property); 1407 | } else if (Array.isArray(data)) { 1408 | if (!currentToken.startsWith("[")) { 1409 | throw ("Node '" + name + "' is of type array"); 1410 | } 1411 | var element = currentToken.substring(1, currentToken.length - 1); 1412 | if (element.equals("#")) { 1413 | for (var i = 0; i < data.length; i++) { 1414 | var child = data[i]; 1415 | visit(name + currentToken, queue.slice(0), child, data, i); 1416 | visit(name + "[" + i + "]", queue.slice(0), child, data, i); 1417 | } 1418 | } else if (element === "$") { 1419 | var child = data[data.length - 1]; 1420 | visit(name + currentToken, queue.slice(0), child, data, data.length - 1); 1421 | } else { 1422 | var index = parseInt(element); 1423 | if (isNaN(index)) { 1424 | throw ("Element '" + element + "' of node '" + name + "' is not an integer, or the '$' last element symbol, or the wilcard symbol '#'"); 1425 | } 1426 | if (index < 0) { 1427 | throw ("Element '" + element + "' of node '" + name + "' is lower than zero"); 1428 | } 1429 | var child = data[index]; 1430 | visit(name + currentToken, queue.slice(0), child, data, index); 1431 | } 1432 | } else if ("object" === typeof data) { 1433 | if (currentToken === "[*]") { 1434 | for (var p in data) { 1435 | var child = data[p]; 1436 | visit(name + currentToken, queue.slice(0), child, data, p); 1437 | visit(name + "[\"" + p + "\"]", queue.slice(0), child, data, p); 1438 | } 1439 | } else { 1440 | var child; 1441 | if (currentToken.startsWith("[")) { 1442 | var element = currentToken.substring(1, currentToken.length - 1); 1443 | if (element.startsWith("\"") || element.startsWith("'")) { 1444 | element = element.substring(1, element.length() - 1); 1445 | } else { 1446 | throw ("Element '" + element + "' of node '" + name + "' must be a string expression or wilcard '*'"); 1447 | } 1448 | name = name + currentToken; 1449 | child = data[element]; 1450 | } else { 1451 | if (name.length > 0) { 1452 | name = name + "." + currentToken; 1453 | } else { 1454 | name = currentToken; 1455 | } 1456 | child = data[currentToken]; 1457 | } 1458 | visit(name, queue, child, data, currentToken); 1459 | } 1460 | } else if ("boolean" === typeof data 1461 | || "number" === typeof data 1462 | || "string" === typeof data) { 1463 | throw ("Node is leaf but still are tokens remaining: " + currentToken); 1464 | } else { 1465 | throw ("Node type '" + typeof data + "' not supported for index field '" + name + "'"); 1466 | } 1467 | } 1468 | visit(this.exp, this.queue, data); 1469 | }; 1470 | 1471 | function parseTokens(exp) { 1472 | if (exp === null) { 1473 | return null; 1474 | } 1475 | var ret = new Array(); 1476 | var commentChar = null; 1477 | var start = 0; 1478 | for (var i = 0; i < exp.length; i++) { 1479 | if (exp.charAt(i) === '"') { 1480 | if (commentChar === null) { 1481 | commentChar = '"'; 1482 | } else if (commentChar === '"') { 1483 | commentChar = null; 1484 | ret[ret.length] = exp.substring(start, i + 1).trim(); 1485 | start = i + 1; 1486 | } 1487 | } else if (exp.charAt(i) === '\'') { 1488 | if (commentChar === null) { 1489 | commentChar = '\''; 1490 | } else if (commentChar === '\'') { 1491 | commentChar = null; 1492 | ret[ret.length] = exp.substring(start, i + 1).trim(); 1493 | start = i + 1; 1494 | } 1495 | } else if (exp.charAt(i) === '[') { 1496 | if (commentChar === null) { 1497 | if (start !== i) { 1498 | ret[ret.length] = exp.substring(start, i).trim(); 1499 | } 1500 | ret[ret.length] = "["; 1501 | start = i + 1; 1502 | } 1503 | } else if (exp.charAt(i) === ']') { 1504 | if (commentChar === null) { 1505 | if (start !== i) { 1506 | ret[ret.length] = exp.substring(start, i).trim(); 1507 | } 1508 | ret[ret.length] = "]"; 1509 | start = i + 1; 1510 | } 1511 | } else if (exp.charAt(i) === '.') { 1512 | if (commentChar === null) { 1513 | if (start !== i) { 1514 | ret[ret.length] = exp.substring(start, i).trim(); 1515 | } 1516 | start = i + 1; 1517 | } 1518 | } else if (i === exp.length - 1) { 1519 | ret[ret.length] = exp.substring(start, i + 1).trim(); 1520 | } 1521 | } 1522 | return ret; 1523 | } 1524 | } 1525 | }; 1526 | brutusin["json-forms"] = BrutusinForms; 1527 | }()); 1528 | -------------------------------------------------------------------------------- /dist/js/brutusin-json-forms.min.js: -------------------------------------------------------------------------------- 1 | if("undefined"==typeof brutusin)window.brutusin=new Object;else if("object"!=typeof brutusin)throw"brutusin global variable already exists";!function(){String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=t||0,this.indexOf(e,t)===t}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){var r=this.toString();(void 0===t||t>r.length)&&(t=r.length),t-=e.length;var n=r.indexOf(e,t);return-1!==n&&n===t}),String.prototype.includes||(String.prototype.includes=function(){"use strict";return-1!==String.prototype.indexOf.apply(this,arguments)}),String.prototype.format||(String.prototype.format=function(){for(var e=this,t=0;t0)throw"Error parsing expression '"+e+"': Multiple tokens found inside a bracket";o+=u,i++}else r[r.length]=u;if(s===n.length-1&&a)throw"Error parsing expression '"+e+"': Unbalanced [ found"}this.exp=e,this.queue=r,this.visit=function(e,t){function r(e,n,a,i,o){if(null!=a){var s=n.shift();if("$"===s){e="$";var s=n.shift()}if(s)if(Array.isArray(a)){if(!s.startsWith("["))throw"Node '"+e+"' is of type array";var u=s.substring(1,s.length-1);if(u.equals("#"))for(var l=0;lp)throw"Element '"+u+"' of node '"+e+"' is lower than zero";var d=a[p];r(e+s,n.slice(0),d,a,p)}}else{if("object"!=typeof a)throw"boolean"==typeof a||"number"==typeof a||"string"==typeof a?"Node is leaf but still are tokens remaining: "+s:"Node type '"+typeof a+"' not supported for index field '"+e+"'";if("[*]"===s)for(var c in a){var d=a[c];r(e+s,n.slice(0),d,a,c),r(e+'["'+c+'"]',n.slice(0),d,a,c)}else{var d;if(s.startsWith("[")){var u=s.substring(1,s.length-1);if(!u.startsWith('"')&&!u.startsWith("'"))throw"Element '"+u+"' of node '"+e+"' must be a string expression or wilcard '*'";u=u.substring(1,u.length()-1),e+=s,d=a[u]}else e=e.length>0?e+"."+s:s,d=a[s];r(e,n,d,a,s)}}else t(a,i,o)}}r(this.exp,this.queue,e)}}var SCHEMA_ANY={type:"any"},obj=new Object,schemaMap=new Object,dependencyMap=new Object,renderInfoMap=new Object,container,data,error,initialValue,inputCounter=0,root=schema,formId="BrutusinForms#"+BrutusinForms.instances.length;renameRequiredPropeties(schema),populateSchemaMap("$",schema),validateDepencyMapIsAcyclic();var renderers=new Object;return renderers.integer=function(e,t,r,n,a){renderers.string(e,t,r,n,a)},renderers.number=function(e,t,r,n,a){renderers.string(e,t,r,n,a)},renderers.any=function(e,t,r,n,a){renderers.string(e,t,r,n,a)},renderers.string=function(e,t,r,n,a){var i,o=getSchemaId(t),s=getParentSchemaId(o),u=getSchema(o),l=getSchema(s);if("any"===u.type)i=document.createElement("textarea"),a&&(i.value=JSON.stringify(a,null,4),u.readOnly&&(i.disabled=!0));else if(u.media)i=document.createElement("input"),i.type="file",appendChild(i,d,u);else if(u["enum"]){if(i=document.createElement("select"),!u.required){var d=document.createElement("option"),p=document.createTextNode("");d.value="",appendChild(d,p,u),appendChild(i,d,u)}for(var c=0,m=0;me.length))return BrutusinForms.messages.minLength.format(u.minLength);if(u.maxLength&&e&&u.maxLength=u.maximum)return BrutusinForms.messages.exclusiveMaximum.format(u.maximum);if(!u.exclusiveMaximum&&e>u.maximum)return BrutusinForms.messages.maximum.format(u.maximum)}if(u.hasOwnProperty("minimum")){if(u.exclusiveMinimum&&e<=u.minimum)return BrutusinForms.messages.exclusiveMinimum.format(u.minimum);if(!u.exclusiveMinimum&&eu.maxProperties?BrutusinForms.messages.maxProperties.format(u.maxProperties):void 0}),C.description&&(S.title=C.description),appendChild(S,document.createTextNode("Add "+x),u),appendChild(E,S,u),a)for(var I in a)if(!u.properties||!u.properties.hasOwnProperty(I)){var N=RegExp(x);-1!==I.search(N)&&-1===O.indexOf(I)&&(o(l,d,t+"["+x+"]",I,a[I],x),O.push(I))}appendChild(w,E,u)}if(u.additionalProperties){var F=getSchema(u.additionalProperties),S=document.createElement("button");if(S.setAttribute("type","button"),S.onclick=function(){o(l,d,t+"[*]",void 0)},(u.maxProperties||u.minProperties)&&(S.getValidationError=function(){return u.minProperties&&c+d.rows.lengthu.maxProperties?BrutusinForms.messages.maxProperties.format(u.maxProperties):void 0}),F.description&&(S.title=F.description),appendChild(S,document.createTextNode("Add"),u),appendChild(w,S,u),a)for(var I in a)u.properties&&u.properties.hasOwnProperty(I)||-1===O.indexOf(I)&&o(l,d,t+'["'+m+'"]',I,a[I])}appendChild(e,w,u)}else appendChild(e,d,u)},renderers.array=function(e,t,r,n,a){function i(e,t,r,n,a){var i=getSchemaId(r),o=getSchema(i),s=document.createElement("tbody"),u=document.createElement("tr");u.className="item";var l=document.createElement("td");l.className="item-index";var d=document.createElement("td");d.className="item-action";var p=document.createElement("td");p.className="item-value";var c=document.createElement("button");c.setAttribute("type","button"),c.className="remove",a===!0&&(c.disabled=!0),appendChild(c,document.createTextNode("x"),o);var m=function(){for(var e=0;ep.rows.length)return BrutusinForms.messages.minItems.format(s.minItems);if(s.maxItems&&s.maxItems (http://brutusin.org)", 10 | "license": "Apache-2.0", 11 | "dependencies": {}, 12 | "keywords": [ 13 | "form", 14 | "json", 15 | "json-schema", 16 | "schema" 17 | ], 18 | "devDependencies": { 19 | "gulp": "^3.5.6", 20 | "gulp-angular-templatecache": "^1.2.1", 21 | "gulp-concat": "^2.2.0", 22 | "gulp-gh-pages": "^0.5.3", 23 | "gulp-jscs": "^1.1.0", 24 | "gulp-minify-css": "^1.2.1", 25 | "gulp-minify-html": "^0.1.1", 26 | "gulp-protractor": "^1.0.0", 27 | "gulp-rename": "^1.2.0", 28 | "gulp-uglify": "^0.2.1", 29 | "gulp-umd": "^0.1.3", 30 | "rimraf": "^2.5.1" 31 | }, 32 | "licenses": [ 33 | { 34 | "type": "Apache-2.0", 35 | "url": "http://www.apache.org/licenses/LICENSE-2.0" 36 | } 37 | ], 38 | "autoupdate": { 39 | "source": "git", 40 | "target": "git://github.com/brutusin/json-forms.git", 41 | "basePath": "/dist/", 42 | "files": [ 43 | "brutusin-json-forms.min.js", 44 | "brutusin-json-forms.js", 45 | "brutusin-json-forms-bootstrap.js", 46 | "brutusin-json-forms-bootstrap.min.js", 47 | "brutusin-json-forms-jsonsrv.js", 48 | "brutusin-json-forms-jsonsrv.min.js" 49 | ] 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/css/brutusin-json-forms.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 brutusin.org 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * @author Ignacio del Valle Alles idelvall@brutusin.org 17 | */ 18 | .add-pattern-div{ 19 | margin-top: 6px; 20 | } 21 | .loading-layer{ 22 | position: absolute; 23 | top:0px; 24 | left:0px; 25 | z-index : 10; 26 | width: 100%; 27 | height: 100%; 28 | opacity: 0.7; 29 | background-color: white; 30 | } 31 | .loading-icon{ 32 | position: absolute; 33 | top:14px; 34 | left:50%; 35 | z-index : 11; 36 | } 37 | .loading-icon-select{ 38 | position: absolute; 39 | top:14px; 40 | left:50%; 41 | z-index : 11; 42 | } 43 | .loading-icon-checkbox{ 44 | position: absolute; 45 | top:7px; 46 | left:3px; 47 | z-index : 11; 48 | } 49 | .glyphicon-refresh-animate { 50 | animation: spin .7s infinite linear; 51 | -webkit-animation: spin2 .7s infinite linear; 52 | } 53 | 54 | @-webkit-keyframes spin2 { 55 | from { -webkit-transform: rotate(0deg);} 56 | to { -webkit-transform: rotate(360deg);} 57 | } 58 | 59 | @keyframes spin { 60 | from { transform: scale(1) rotate(0deg);} 61 | to { transform: scale(1) rotate(360deg);} 62 | } 63 | form.brutusin-form table, form.brutusin-form input, form.brutusin-form select, form.brutusin-form textarea{ 64 | width: 100% !important; 65 | min-width: 80px; 66 | } 67 | form.brutusin-form input[type=checkbox]{ 68 | width: auto !important; 69 | min-width: auto !important; 70 | } 71 | form.brutusin-form textarea{ 72 | height: 8em; 73 | } 74 | form.brutusin-form table table{ 75 | border-left: solid 1px; 76 | border-color: lightgray; 77 | margin: 4px; 78 | } 79 | form.brutusin-form td { 80 | vertical-align: top; 81 | padding: 4px; 82 | white-space: nowrap; 83 | } 84 | form.brutusin-form td.prop-name { 85 | text-align: right; 86 | } 87 | form.brutusin-form td.add-prop-name table { 88 | text-align: right; 89 | border: none; 90 | } 91 | form.brutusin-form td.add-prop-name table td { 92 | vertical-align: middle; 93 | } 94 | form.brutusin-form td.prop-value { 95 | width: 100%; 96 | text-align: left; 97 | } 98 | form.brutusin-form td.item-index{ 99 | font-size: 0.8em; 100 | color: lightgray; 101 | width: 25px; 102 | text-align: right; 103 | } 104 | form.brutusin-form td.item-action{ 105 | width: 30px; 106 | } 107 | form.brutusin-form .error { 108 | border-color: red; 109 | } 110 | form.brutusin-form .error-message { 111 | color: red; 112 | } 113 | -------------------------------------------------------------------------------- /src/js/addon/brutusin-json-forms-lan-de_DE.js: -------------------------------------------------------------------------------- 1 | if ("undefined" === typeof brutusin || "undefined" === typeof brutusin["json-forms"]) { 2 | throw new Error("brutusin-json-forms-bootstrap.js requires brutusin-json-forms.js"); 3 | } 4 | (function () { 5 | var BrutusinForms = brutusin["json-forms"]; 6 | 7 | BrutusinForms.messages = { 8 | "validationError": "Validierungsfehler", 9 | "required": "Pflichtfeld", 10 | "invalidValue": "Ungültiger Wert", 11 | "addpropNameExistent": "Dieses Attribut existiert bereits", 12 | "addpropNameRequired": "Ein Name ist erforderlich", 13 | "minItems": "Mindestens {0} Elemente werden benötigt", 14 | "maxItems": "Maximal {0} Elemente sind zugelassen", 15 | "pattern": "Dieser Wert stimmt nicht mit dem vorgegebenen Muster überein: {0}", 16 | "minLength": "Mindestlänge: {0} Zeichen", 17 | "maxLength": "Maximale Länge: {0} Zeichen", 18 | "multipleOf": "Der Wert muss ein Vielfaches von {0} sein", 19 | "minimum": "Der Wert muss ≤ {0} sein", 20 | "exclusiveMinimum": "Der Wert muss < {0} sein", 21 | "maximum": "Der Wert muss ≥ {0} sein", 22 | "exclusiveMaximum": "Der Wert muss > {0} sein", 23 | "minProperties": "Mindestens {0} Attribute werden benötigt", 24 | "maxProperties": "Höchstens {0} Attribute sind zugelassen", 25 | "uniqueItems": "Jedes Element darf höchstens einmal vorkommen", 26 | "addItem": "Element hinzufügen", 27 | "true": "Ja", 28 | "false": "Nein" 29 | }; 30 | }()); -------------------------------------------------------------------------------- /src/js/addon/brutusin-json-forms-lan-es_ES.js: -------------------------------------------------------------------------------- 1 | if ("undefined" === typeof brutusin || "undefined" === typeof brutusin["json-forms"]) { 2 | throw new Error("brutusin-json-forms-bootstrap.js requires brutusin-json-forms.js"); 3 | } 4 | (function () { 5 | var BrutusinForms = brutusin["json-forms"]; 6 | 7 | BrutusinForms.messages = { 8 | "validationError": "Error de validación", 9 | "required": "Este campo es **obligatorio**", 10 | "invalidValue": "Valor inválido", 11 | "addpropNameExistent": "Esta propiedad ya existe en el objeto", 12 | "addpropNameRequired": "Un nombre es obligatorio", 13 | "minItems": "Se requiere un mínimo de `{0}` elementos", 14 | "maxItems": "Se admiten a lo sumo `{0}` elementos", 15 | "pattern": "El valor no cumple el patrón: `{0}`", 16 | "minLength": "El valor debe tener **como mínimo** `{0}` caracteres de longitud", 17 | "maxLength": "El valor debe tener **como máximo** `{0}` caracteres de longitud", 18 | "multipleOf": "El valor debe ser **múltiplo de** `{0}`", 19 | "minimum": "El valor debe ser **mayor o igual que** `{0}`", 20 | "exclusiveMinimum": "El valor debe ser **mayor que** `{0}`", 21 | "maximum": "El valor debe ser **menor o igual que** `{0}`", 22 | "exclusiveMaximum": "El valor debe ser **menor que** `{0}`", 23 | "minProperties": "Se requieren como mínimo `{0}` propiedades", 24 | "maxProperties": "Se admiten a lo sumo `{0}` propiedades", 25 | "uniqueItems": "Los elementos del array deben ser diferentes", 26 | "addItem": "Añadir elemento", 27 | "true": "Verdadero", 28 | "false": "Falso" 29 | }; 30 | }()); -------------------------------------------------------------------------------- /src/js/addon/brutusin-json-forms-lan-fr-FR.js: -------------------------------------------------------------------------------- 1 | if ("undefined" === typeof brutusin || "undefined" === typeof brutusin["json-forms"]) { 2 | throw new Error("brutusin-json-forms-bootstrap.js requires brutusin-json-forms.js"); 3 | } 4 | (function () { 5 | var BrutusinForms = brutusin["json-forms"]; 6 | 7 | BrutusinForms.messages = { 8 | "validationError": "Erreur de validation", 9 | "required": "Ce champ est obligatoire", 10 | "invalidValue": "Valeur du champ invalide", 11 | "addpropNameExistent": "Cet propriété est déjà présente dans l'objet", 12 | "addpropNameRequired": "Un nom est obligatoire", 13 | "minItems": "Au moins {0} éléments sont requis", 14 | "maxItems": "Au plus {0} élément sont autorisés", 15 | "pattern": "La valeur n'est pas conforme au patron: {0}", 16 | "minLength": "La valeur doit être au moins de {0} caractères", 17 | "maxLength": "La valeur doit être *au maximum de {0} caractères", 18 | "multipleOf": "La valeur doit être multiple de {0}", 19 | "minimum": "La valeur doit être supérieur ou égale à {0}", 20 | "exclusiveMinimum": "La valeur doit être supérieur à {0}", 21 | "maximum": "La valeur doit inférieur ou égale à{0}", 22 | "exclusiveMaximum": "La valeur doit être inférieur à {0}", 23 | "minProperties": "Au moins {0} propriétés sont obligatoire", 24 | "maxProperties": "Au plus {0} propriétés sont autorisés", 25 | "uniqueItems": "Les éléments du tableaux doivent être unique", 26 | "addItem": "Ajouter un élément", 27 | "true": "Vrai", 28 | "false": "Faux" 29 | }; 30 | }()); -------------------------------------------------------------------------------- /src/js/brutusin-json-forms-bootstrap.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 brutusin.org 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * @author Ignacio del Valle Alles idelvall@brutusin.org 17 | */ 18 | if ("undefined" === typeof brutusin || "undefined" === typeof brutusin["json-forms"]) { 19 | throw new Error("brutusin-json-forms-bootstrap.js requires brutusin-json-forms.js"); 20 | } 21 | if ("undefined" === typeof markdown && window.console) { 22 | console.warn("Include markdown.js (https://github.com/evilstreak/markdown-js) to add markdown support in property description popups"); 23 | } 24 | 25 | if (("undefined" === typeof $ || "undefined" === typeof $.fn || "undefined" === typeof $.fn.selectpicker) && window.console) { 26 | console.warn("Include bootstrap-select.js (https://github.com/silviomoreto/bootstrap-select) to turn native selects into bootstrap components"); 27 | } 28 | 29 | (function () { 30 | var BrutusinForms = brutusin["json-forms"]; 31 | 32 | // Basic bootstrap css 33 | BrutusinForms.addDecorator(function (element, schema) { 34 | if (element.tagName) { 35 | var tagName = element.tagName.toLowerCase(); 36 | if (tagName === "input" && element.type !== "checkbox" || tagName === "textarea") { 37 | element.className += " form-control"; 38 | } else if (tagName === "select") { 39 | element.className += " chosen-select form-control"; 40 | } else if (tagName === "button") { 41 | if (element.className === "remove") { 42 | element.className += " glyphicon glyphicon-remove"; 43 | while (element.firstChild) { 44 | element.removeChild(element.firstChild); 45 | } 46 | } 47 | element.className += " btn btn-primary btn-xs"; 48 | } else if (tagName === "form") { 49 | element.className += " form-inline"; 50 | } 51 | } 52 | }); 53 | 54 | 55 | // Description help icon 56 | BrutusinForms.addDecorator(function (element, schema) { 57 | if (element.tagName) { 58 | var tagName = element.tagName.toLowerCase(); 59 | if (tagName === "label" || tagName === "button") { 60 | if (element.title) { 61 | var helpLink = document.createElement("a"); 62 | helpLink.setAttribute("style", "outline: 0; text-decoration: none; margin-left: 2px;"); 63 | helpLink.setAttribute("tabIndex", -1); 64 | helpLink.className = "glyphicon glyphicon-info-sign" 65 | helpLink.setAttribute("data-toggle", "popover"); 66 | helpLink.setAttribute("data-trigger", "focus"); 67 | if ("undefined" === typeof markdown) { 68 | helpLink.setAttribute("data-content", element.title); 69 | } else { 70 | helpLink.setAttribute("data-content", markdown.toHTML(element.title)); 71 | } 72 | if (schema.title) { 73 | helpLink.title = schema.title; 74 | } else { 75 | helpLink.title = "Help"; 76 | } 77 | $(helpLink).popover({ 78 | placement: 'top', 79 | container: 'body', 80 | html: !("undefined" === typeof markdown) 81 | }); 82 | element.parentNode.appendChild(helpLink); 83 | } 84 | } 85 | } 86 | }); 87 | 88 | // Popover over inputs 89 | //BrutusinForms.addDecorator(function (element, schema) { 90 | //if (element.tagName) { 91 | // if (element.title && (tagName === "input" || tagName === "textarea" || tagName === "select")) { 92 | // element.setAttribute("data-toggle", "tooltip"); 93 | // element.setAttribute("data-trigger", "focus"); 94 | // if ("undefined" === typeof markdown) { 95 | // element.setAttribute("data-content", element.title); 96 | // } else { 97 | // element.setAttribute("data-content", markdown.toHTML(element.title)); 98 | // } 99 | // if (schema.title) { 100 | // element.title = schema.title; 101 | // } else { 102 | // element.title = "Help"; 103 | // } 104 | // $(element).popover({ 105 | // placement: 'top', 106 | // container: 'body', 107 | // html: !("undefined" === typeof markdown) 108 | // }); 109 | // }input 110 | // } 111 | //}); 112 | // Bootstrap select 113 | BrutusinForms.addDecorator(function (element, schema) { 114 | if (element.tagName) { 115 | var tagName = element.tagName.toLowerCase(); 116 | // https://github.com/silviomoreto/bootstrap-select 117 | if (!("undefined" === typeof $ || "undefined" === typeof $.fn || "undefined" === typeof $.fn.selectpicker) && tagName === "select") { 118 | element.title = ""; 119 | element.className += " selectpicker"; 120 | element.setAttribute("data-live-search", true); 121 | $(element).selectpicker(); 122 | } 123 | } 124 | }); 125 | BrutusinForms.bootstrap = new Object(); 126 | // helper button for string (with format) fields 127 | BrutusinForms.bootstrap.addFormatDecorator = function (format, inputType, glyphicon, cb) { 128 | BrutusinForms.addDecorator(function (element, schema) { 129 | if (element.tagName) { 130 | var tagName = element.tagName.toLowerCase(); 131 | if (tagName === "input" && schema.type === "string" && schema.format === format) { 132 | if (inputType) { 133 | element.type = inputType; 134 | } 135 | if (glyphicon) { 136 | var parent = element.parentNode; 137 | var table = document.createElement("table"); 138 | table.setAttribute("style", "border:none;margin:0"); 139 | var tr = document.createElement("tr"); 140 | var td1 = document.createElement("td"); 141 | td1.setAttribute("style", "width:100%; padding:0;padding-right:4px"); 142 | table.appendChild(tr); 143 | tr.appendChild(td1); 144 | parent.removeChild(element); 145 | td1.appendChild(element); 146 | parent.appendChild(table); 147 | var td = document.createElement("td"); 148 | tr.appendChild(td); 149 | td.setAttribute("style", "padding:0"); 150 | var searchButton = document.createElement("button"); 151 | searchButton.className = "btn btn-default glyphicon " + glyphicon; 152 | searchButton.onclick = function () { 153 | cb(element); 154 | }; 155 | td.appendChild(searchButton); 156 | } 157 | } 158 | } 159 | }); 160 | }; 161 | BrutusinForms.bootstrap.showLoading = function (element) { 162 | if (element && element.parentNode) { 163 | var loadingId = element.id + "_loading"; 164 | var loadingLayerId = element.id + "_loading-layer"; 165 | var loading = document.getElementById(loadingId); 166 | var loadingLayer = document.getElementById(loadingLayerId); 167 | if (!loading) { 168 | var tagName = element.tagName.toLowerCase(); 169 | element.parentNode.style.position = "relative"; 170 | loading = document.createElement("span"); 171 | loading.id = loadingId; 172 | loading.className = "glyphicon glyphicon-refresh glyphicon-refresh-animate"; 173 | if (tagName === "select") { 174 | loading.className += " loading-icon-select"; 175 | } else if (element.type === "checkbox") { 176 | loading.className += " loading-icon-checkbox"; 177 | } else { 178 | loading.className += " loading-icon"; 179 | } 180 | element.parentNode.appendChild(loading); 181 | loadingLayer = document.createElement("div"); 182 | loadingLayer.className = "loading-layer"; 183 | loadingLayer.appendChild(document.createTextNode("")); 184 | loadingLayer.id = loadingLayerId; 185 | element.parentNode.appendChild(loadingLayer); 186 | } 187 | loading.style.visibility = "visible"; 188 | loadingLayer.style.visibility = "visible"; 189 | } 190 | } 191 | BrutusinForms.bootstrap.hideLoading = function (element) { 192 | if (element) { 193 | var loadingId = element.id + "_loading"; 194 | var loadingLayerId = element.id + "_loading-layer"; 195 | var loading = document.getElementById(loadingId); 196 | var loadingLayer = document.getElementById(loadingLayerId); 197 | if (loading) { 198 | loading.style.visibility = "hidden"; 199 | } 200 | if (loadingLayer) { 201 | loadingLayer.style.visibility = "hidden"; 202 | } 203 | } 204 | } 205 | 206 | BrutusinForms.onResolutionStarted = BrutusinForms.bootstrap.showLoading; 207 | BrutusinForms.onResolutionFinished = BrutusinForms.bootstrap.hideLoading; 208 | 209 | BrutusinForms.onValidationSuccess = function (element) { 210 | element.parentNode.className = element.parentNode.className.replace(" has-error", ""); 211 | } 212 | BrutusinForms.onValidationError = function (element, message) { 213 | 214 | setTimeout(function () { 215 | var dataToggle = element.getAttribute("data-toggle"); 216 | var dataTrigger = element.getAttribute("data-trigger"); 217 | var dataContent = element.getAttribute("data-content"); 218 | var title = element.title; 219 | element.setAttribute("data-toggle", "popover"); 220 | element.setAttribute("data-trigger", "manual"); 221 | if ("undefined" === typeof markdown) { 222 | element.setAttribute("data-content", message); 223 | } else { 224 | element.setAttribute("data-content", markdown.toHTML(message)); 225 | } 226 | 227 | element.title = BrutusinForms.messages["validationError"]; 228 | if (!element.parentNode.className.includes("has-error")) { 229 | element.parentNode.className += " has-error"; 230 | } 231 | element.focus(); 232 | $(element).popover({ 233 | placement: 'top', 234 | container: 'body', 235 | html: true 236 | }); 237 | $(element).popover("show"); 238 | var onblur = element.onblur; 239 | element.onblur = function (e) { 240 | if (dataToggle) { 241 | $(element).popover('hide'); 242 | element.setAttribute("data-toggle", dataToggle); 243 | element.setAttribute("data-trigger", dataTrigger); 244 | element.setAttribute("data-content", dataContent); 245 | } else { 246 | $(element).popover('destroy'); 247 | element.removeAttribute("data-toggle"); 248 | element.removeAttribute("data-trigger"); 249 | element.removeAttribute("data-content"); 250 | } 251 | 252 | element.onblur = onblur; 253 | element.title = title; 254 | if (onblur) { 255 | onblur(); 256 | } 257 | } 258 | }, 259 | 200); 260 | } 261 | }()); --------------------------------------------------------------------------------