├── .gitignore ├── Gruntfile.js ├── LICENSE ├── README.md ├── admin_bundle.go ├── bundle.sh ├── index.html ├── package.json ├── src ├── base.css ├── js │ ├── eventListener.js │ ├── json-client.js │ ├── main.js │ └── syncModel.js ├── jsx │ ├── app.jsx │ ├── channels.jsx │ ├── databases.jsx │ ├── documents.jsx │ ├── editor.jsx │ ├── helpers.jsx │ ├── page.jsx │ ├── sync.jsx │ └── users.jsx ├── logo.png └── vendor │ ├── codemirror-compressed.js │ ├── codemirror.css │ ├── davis.js │ ├── react.js │ └── zepto.min.js └── tests └── test_data.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | assets/ 3 | tmp/ 4 | watchChanged.json 5 | pkg/ 6 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt) { 2 | var watchChanged = {} 3 | if (grunt.file.exists('watchChanged.json')) { 4 | watchChanged = grunt.file.readJSON('watchChanged.json') 5 | } 6 | grunt.initConfig({ 7 | pkg: grunt.file.readJSON('package.json'), 8 | babel : { 9 | // for jshint only 10 | options : { 11 | only : "*.jsx" 12 | }, 13 | dist : { 14 | "tmp/babel.js" : "src/jsx/*" 15 | } 16 | }, 17 | jshint: { 18 | changed : [], 19 | js: ['Gruntfile.js', 'src/js/*.js', 'tests/*.js'], 20 | jsx : ['tmp/jsx/*.js'], 21 | options: { 22 | "browser": true, 23 | "globals": { 24 | "React" : true, 25 | "CodeMirror" : true, 26 | "confirm" : true 27 | }, 28 | "node" : true, 29 | "asi" : true, 30 | "globalstrict": false, 31 | "quotmark": false, 32 | "smarttabs": true, 33 | "trailing": false, 34 | "undef": true, 35 | "unused": false 36 | } 37 | }, 38 | node_tap: { 39 | all: { 40 | options: { 41 | outputType: 'failures', // tap, failures, stats 42 | outputTo: 'console' // or file 43 | // outputFilePath: '/tmp/out.log' // path for output file, 44 | // only makes sense with outputTo 'file' 45 | }, 46 | files: { 47 | 'tests': ['tests/*.js'] 48 | } 49 | }, 50 | changed: { 51 | options: { 52 | outputType: 'tap', // tap, failures, stats 53 | outputTo: 'console' // or file 54 | // outputFilePath: '/tmp/out.log' // path for output file, 55 | // only makes sense with outputTo 'file' 56 | }, 57 | files: { 58 | 'tests': watchChanged.node_tap || [] 59 | } 60 | } 61 | }, 62 | copy: { 63 | assets: { 64 | files: [ 65 | // includes files within path 66 | {expand: true, cwd: 'src/', src: ['*'], dest: 'assets/', filter: 'isFile'}, 67 | 68 | // includes files within path and its sub-directories 69 | {expand: true, cwd: 'src/vendor', src: ['**'], dest: 'assets/vendor'} 70 | 71 | // makes all src relative to cwd 72 | // {expand: true, cwd: 'path/', src: ['**'], dest: 'dest/'}, 73 | 74 | // flattens results to a single level 75 | // {expand: true, flatten: true, src: ['path/**'], dest: 'dest/', filter: 'isFile'} 76 | ] 77 | } 78 | }, 79 | browserify: { 80 | options: { 81 | debug : true, 82 | transform: [ require('babelify').configure({sourceMap : true}) ] 83 | }, 84 | app: { 85 | src: 'src/js/main.js', 86 | dest: 'assets/bundle.js' 87 | } 88 | }, 89 | uglify: { 90 | options: { 91 | mangle: false, 92 | compress : { 93 | unused : false 94 | }, 95 | beautify : { 96 | ascii_only : true 97 | } 98 | }, 99 | assets: { 100 | files: { 101 | 'assets/bundle.min.js': ['assets/bundle.js'], 102 | 'assets/vendor.min.js': ['src/vendor/*.js'] 103 | } 104 | } 105 | }, 106 | imageEmbed: { 107 | dist: { 108 | src: [ "src/base.css" ], 109 | dest: "assets/base.css", 110 | options: { 111 | deleteAfterEncoding : false 112 | } 113 | } 114 | }, 115 | staticinline: { 116 | main: { 117 | files: { 118 | 'assets/index.html': 'index.html', 119 | } 120 | } 121 | }, 122 | watch: { 123 | scripts: { 124 | files: ['Gruntfile.js', 'src/js/*.js'], 125 | tasks: ['jshint:changed', 'default'], 126 | options: { 127 | spawn: false, 128 | }, 129 | }, 130 | jsx: { 131 | files: ['src/jsx/*.jsx'], 132 | tasks: ['jsxhint', 'default'], 133 | options: { 134 | spawn: false, 135 | }, 136 | }, 137 | other : { 138 | files: ['index.html','src/**/*.css', 'src/vendor/**/*'], 139 | tasks: ['default'], 140 | options: { 141 | spawn: false, 142 | }, 143 | }, 144 | tests : { 145 | files: ['tests/*.js'], 146 | tasks: ['jshint:js', 'node_tap:changed', 'default'], 147 | options: { 148 | interrupt: true, 149 | }, 150 | } 151 | } 152 | }) 153 | grunt.loadNpmTasks('grunt-newer'); 154 | grunt.loadNpmTasks('grunt-browserify') 155 | grunt.loadNpmTasks('grunt-babel'); 156 | grunt.loadNpmTasks('grunt-contrib-jshint'); 157 | grunt.loadNpmTasks('grunt-contrib-watch'); 158 | grunt.loadNpmTasks('grunt-contrib-copy'); 159 | grunt.loadNpmTasks('grunt-contrib-uglify'); 160 | grunt.loadNpmTasks('grunt-node-tap'); 161 | grunt.loadNpmTasks('grunt-static-inline'); 162 | grunt.loadNpmTasks("grunt-image-embed"); 163 | 164 | grunt.registerTask('jsxhint', ['babel', 'jshint:jsx']); 165 | grunt.registerTask('default', ['jshint:js', 'jsxhint', 'node_tap:all', 'copy:assets', 'browserify', 'imageEmbed','uglify', 'staticinline']); 166 | 167 | grunt.event.on('watch', function(action, filepath) { 168 | // for (var key in require.cache) {delete require.cache[key];} 169 | grunt.config('jshint.changed', [filepath]); 170 | grunt.file.write("watchChanged.json", JSON.stringify({ 171 | node_tap : [filepath] 172 | })) 173 | grunt.config('node_tap.changed.files.tests', [filepath]); 174 | }); 175 | }; 176 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2017 Couchbase, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **NOTE:** development on this has stopped and moved to the [dev branch](https://github.com/couchbaselabs/sync_gateway_admin_ui/tree/dev) which is a re-write from scratch! 2 | 3 | # Developer Console for Couchbase Sync Gateway 4 | 5 | This is not a standalone project -- it's a submodule of the [Couchbase Sync Gateway][SG]. We are keeping it in a separate repository so that its Git commits and Github issues are separated from the main gateway's, for clarity. In addition, this project is currently in an early development and experimental phase. The resulting dashboard will change drastically in the near future. 6 | 7 | This project contains the Web assets for the Sync Gateway's admin console. To use this interface, launch a Sync Gateway server and visit [http://localhost:4985/_admin/](http://localhost:4985/_admin/) in your browser. (This port is bound to localhost-only by default, so if you want to connect to it from a remote device you may need to create a tunnel or change your gateway config.) 8 | 9 | ## What can you do with it? 10 | 11 | * View and edit your Sync Function code and see what it will do *before* you deploy it 12 | * Browse through all databases and their documents 13 | * View the JSON contents of any document, plus its channel assignments and any channel access it grants 14 | * View the internal `_sync` metadata of any document (useful mostly for troubleshooting the Sync Gateway) 15 | 16 | ## Known Issues 17 | 18 | Currently it tries to load the last 1000 changes into the brower's memory. If you have more than 1000 documents in your database it will only look at the 1000 most recent. In the future we will make this configurable. 19 | 20 | ## Developing / Contributing 21 | 22 | **NOTE:** To use the existing admin UI you don't need to do anything with this repository; it's already built into the Sync Gateway. You only need to follow these instructions if you want to make changes to the admin UI. 23 | 24 | Before you can work on this code, you need [node.js][NODEJS] installed locally. Once you have that, run these commands. 25 | 26 | ```bash 27 | cd src/github.com/couchbaselabs/sync_gateway_admin_ui 28 | npm install -g grunt-cli # you might need to sudo this 29 | npm install -g tap # ditto 30 | npm install 31 | grunt 32 | ``` 33 | 34 | You'll need to run `grunt` every time you change code files. You can also run it continuously with `grunt watch`. 35 | 36 | To point Sync Gateway at the development bundle created by `grunt`, add this line to your Sync Gateway config file at the top level: 37 | 38 | ``` 39 | "adminUI" : "src/github.com/couchbaselabs/sync_gateway_admin_ui/assets/index.html", 40 | ``` 41 | 42 | ## Building for Release 43 | 44 | To release this code for consumption by Sync Gateway's build process, it needs to be packaged as Go code: 45 | 46 | ```bash 47 | go get github.com/jteeuwen/go-bindata 48 | grunt 49 | ./bundle.sh 50 | ``` 51 | 52 | [SG]: https://github.com/couchbase/sync_gateway 53 | [NODEJS]: http://nodejs.org 54 | -------------------------------------------------------------------------------- /bundle.sh: -------------------------------------------------------------------------------- 1 | #/bin/sh 2 | go-bindata -pkg sync_gateway_admin_ui -o admin_bundle.go assets/ && \ 3 | gofmt admin_bundle.go > gofmt_admin_bundle.go && \ 4 | mv gofmt_admin_bundle.go admin_bundle.go -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Couchbase Sync Gateway 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sync-gateway-utils", 3 | "dependencies": { 4 | "coax": "0.4.x", 5 | "underscore": "1.4.4", 6 | "react": "^0.13.3" 7 | }, 8 | "devDependencies": { 9 | "babelify": "^6.1.3", 10 | "browserify": "~4.0.0", 11 | "grunt": "~0.4.2", 12 | "grunt-babel": "^5.0.1", 13 | "grunt-browserify": "~1.3.0", 14 | "grunt-contrib-copy": "~0.5.0", 15 | "grunt-contrib-jshint": "~0.6.3", 16 | "grunt-contrib-uglify": "~0.2.7", 17 | "grunt-contrib-watch": "~0.5.3", 18 | "grunt-image-embed": "~0.3.1", 19 | "grunt-newer": "~0.6.0", 20 | "grunt-node-tap": "~0.1.52", 21 | "grunt-static-inline": "~0.1.2", 22 | "request": "~2.33.0", 23 | "tap": "~0.4.8", 24 | "tape": "~2.3.2" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/base.css: -------------------------------------------------------------------------------- 1 | /* global tags */ 2 | * { 3 | box-sizing: border-box; 4 | } 5 | 6 | body { 7 | background: #fff; 8 | font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;; 9 | font-size: 15px; 10 | margin: 0; 11 | padding: 0; 12 | } 13 | 14 | code { 15 | background-color: #f8f8f8; 16 | border: 1px solid #ddd; 17 | border-radius: 3px; 18 | font-family: "Bitstream Vera Sans Mono", Consolas, Courier, monospace; 19 | font-size: 12px; 20 | margin: 0 2px; 21 | padding: 0px 5px; 22 | } 23 | 24 | h1, h2, h3, h4 { 25 | font-weight: bold; 26 | margin: 0 0 15px; 27 | padding: 0; 28 | } 29 | 30 | h1 { 31 | border-bottom: 1px solid #ddd; 32 | font-size: 2.5em; 33 | font-weight: bold; 34 | margin: 0 0 15px; 35 | padding: 0; 36 | } 37 | 38 | h2 { 39 | border-bottom: 1px solid #eee; 40 | font-size: 2em; 41 | } 42 | 43 | h3 { 44 | font-size: 1.5em; 45 | } 46 | 47 | h4 { 48 | font-size: 1.2em; 49 | } 50 | 51 | p, ul { 52 | margin: 15px 0; 53 | } 54 | 55 | ul { 56 | padding-left: 0; 57 | list-style-type: none; 58 | } 59 | 60 | ul.defaults { 61 | padding-left: 1em; 62 | list-style-type: circle; 63 | } 64 | 65 | a { 66 | color: #4183c4; 67 | /*color: #94651a;*/ 68 | text-decoration: none; 69 | } 70 | 71 | a.active { 72 | font-weight: bold; 73 | } 74 | 75 | a:hover { 76 | /*color: #94651a;*/ 77 | text-decoration: underline; 78 | } 79 | 80 | .clear { 81 | clear:both; 82 | } 83 | 84 | /* layout */ 85 | 86 | #main, #container, #sidebar { 87 | margin:0; 88 | padding:0; 89 | } 90 | 91 | #main { 92 | /* width: 85%; 93 | float: left;*/ 94 | } 95 | 96 | .content { 97 | margin: 1em; 98 | } 99 | 100 | a.logo { 101 | background-image: url(logo.png); 102 | background-size: contain; 103 | background-repeat: no-repeat; 104 | padding-top: 0.2em; 105 | margin:0.2em; 106 | height:0.8em; 107 | width: 2em; 108 | display: block; 109 | float:left; 110 | } 111 | 112 | .NavBar { 113 | font-size: 2em; 114 | border-bottom: 1px solid #ddd; 115 | position: fixed; 116 | top:0; 117 | left: 0; 118 | width: 100%; 119 | /*height:2em;*/ 120 | padding: 0.2em 0.5em; 121 | background: rgba(255, 255, 255, 0.8); 122 | } 123 | .NavBar.preview { 124 | background: rgba(255, 217, 119, 0.8); 125 | /*background: #fff0b7;*/ 126 | } 127 | 128 | 129 | .PreviewToggle { 130 | float: right; 131 | font-size: 50%; 132 | padding: 0.2em 133 | } 134 | 135 | .NavBarWrap { 136 | height: 3em; 137 | } 138 | 139 | /* layout */ 140 | .SyncFunEditor { 141 | /*background: #efe;*/ 142 | width: 100% 143 | } 144 | 145 | 146 | .SyncPreview { 147 | /*background: #bbb;*/ 148 | padding:1em; 149 | float:left; 150 | width: 50%; 151 | min-width: 40em; 152 | } 153 | 154 | .SyncPreview .docs { 155 | width: 33%; 156 | float: left; 157 | padding:1em; 158 | } 159 | 160 | .JSONDoc { 161 | width: 60%; 162 | padding: 0.1em 0.25em; 163 | float:left; 164 | overflow: scroll; 165 | max-height: 24em; 166 | } 167 | 168 | .JSONDoc pre { 169 | background: #f3f3f8; 170 | padding: 0.1em 0.25em; 171 | } 172 | 173 | .DocSyncPreview { 174 | /*clear:left;*/ 175 | padding: 0.1em 0.25em; 176 | } 177 | 178 | .DocSyncPreview .channels, .DocSyncPreview .access { 179 | width: 50%; 180 | float:left; 181 | } 182 | 183 | .channelDocs { 184 | float:left; 185 | width: 30%; 186 | padding: 0.1em 0.25em; 187 | } 188 | 189 | .ChannelAccessList { 190 | padding: 0.1em 0.25em; 191 | margin: 0.25em; 192 | float: left; 193 | } 194 | 195 | 196 | .ChannelGrid>ul { 197 | white-space:nowrap; 198 | overflow-x:scroll; 199 | } 200 | 201 | .ChannelGrid>ul>li { 202 | white-space:normal; 203 | background: #eee; 204 | width: 16em; 205 | margin: .25em; 206 | padding:.25em; 207 | display: inline-flex; 208 | } 209 | 210 | .UserChannels li, .ChannelChanges li { 211 | background: #ddedfd; 212 | margin:.25em; 213 | padding:.25em; 214 | } 215 | 216 | li.isAccess { 217 | background: #fdf5cc; 218 | } 219 | 220 | li.hiddenAccess { 221 | background: #fcccc1; 222 | } 223 | 224 | .UsersForDatabase, .RecentChannels, .ListDocs { 225 | width: 16em; 226 | float: left; 227 | background: #f2f7f7; 228 | margin:.25em; 229 | padding:.25em; 230 | } 231 | 232 | .UsersForDatabase li, .RecentChannels li, .ListDocs li { 233 | margin:0.1em .25em; 234 | padding:0.1em .25em; 235 | } 236 | 237 | .UserInfo { 238 | /*background: #efd;*/ 239 | float: left; 240 | margin:0 1em; 241 | /*width: 60%;*/ 242 | } 243 | 244 | .UserChannels { 245 | float: left; 246 | width: 24em; 247 | padding:0.1em .25em; 248 | } 249 | 250 | .UserDoc { 251 | float: left; 252 | width: 24em; 253 | padding:0.1em .25em; 254 | } 255 | 256 | .DocsInChannel { 257 | margin: 1em; 258 | } 259 | 260 | 261 | .watched { 262 | font-weight: bold; 263 | /*color: #012345;*/ 264 | color: #2463b7; 265 | } 266 | 267 | .SyncFunEditor { 268 | /*padding:0.1em .25em;*/ 269 | } 270 | 271 | .SyncFunctionCode { 272 | float: left; 273 | width:50%; 274 | min-width: 40em; 275 | padding:1em; 276 | /*background: #ebebeb;*/ 277 | } 278 | 279 | .SyncFunctionCodeButtons { 280 | float:right; 281 | padding: 0.25em; 282 | } 283 | 284 | .SyncFunctionCodeEditor { 285 | border:1px solid #aaa; 286 | } 287 | 288 | .SyncFunEditor textarea { 289 | font-size: 1em; 290 | width: 100%; height: 20em; 291 | padding: 0.25em; 292 | background: #fefefe; 293 | } 294 | -------------------------------------------------------------------------------- /src/js/eventListener.js: -------------------------------------------------------------------------------- 1 | // Apache 2.0 License http://www.apache.org/licenses/LICENSE-2.0.html 2 | // Copywrite 2014 Couchbase, Inc. 3 | 4 | module.exports = { 5 | listen : function(emitter, event, handler) { 6 | // console.log("listen", event) 7 | var mixinStateKeyForEvent = "_EventListenerMixinState:"+event; 8 | var sub = this.state[mixinStateKeyForEvent] || {}; 9 | if (sub.event && sub.emitter) { 10 | if (sub.event == event && sub.emitter === emitter) { 11 | // we are already listening, noop 12 | // console.log("EventListenerMixin alreadyListening", sub.event, this) 13 | return; 14 | } else { 15 | // unsubscribe from the existing one 16 | // console.log("EventListenerMixin removeListener", sub.event, this) 17 | sub.emitter.removeListener(sub.event, sub.handler) 18 | } 19 | } 20 | var mixinState = { 21 | emitter : emitter, 22 | event : event, 23 | handler : handler 24 | } 25 | // console.log("EventListenerMixin addListener", event, this, mixinState) 26 | var stateToMerge = {}; 27 | stateToMerge[mixinStateKeyForEvent] = mixinState; 28 | this.setState(stateToMerge); 29 | emitter.on(event, handler) 30 | }, 31 | componentWillUnmount : function() { 32 | // console.log("componentWillUnmount", JSON.stringify(this.state)) 33 | for (var eventKey in this.state) { 34 | var ekps = eventKey.split(":") 35 | if (ekps[0] == "_EventListenerMixinState") { 36 | var sub = this.state[eventKey] 37 | var emitter = sub.emitter 38 | // console.log("EventListenerMixin Unmount removeListener", eventKey, sub, this) 39 | emitter.removeListener(sub.event, sub.handler) 40 | } 41 | } 42 | }, 43 | } 44 | -------------------------------------------------------------------------------- /src/js/json-client.js: -------------------------------------------------------------------------------- 1 | var requestLib = require("request"), 2 | request = requestLib.defaults({ 3 | json:true 4 | }, function(uri, options, callback){ 5 | var params = requestLib.initParams(uri, options, callback); 6 | // console.log("req", params.options) 7 | return requestLib(params.uri, params.options, function(err, res, body){ 8 | // console.log("requestLib", err, res.statusCode, params.uri) 9 | // treat bad status codes as errors 10 | if (!err && res.statusCode >= 400) { 11 | params.callback.apply(this, [res.statusCode, res, body]); 12 | } else { 13 | params.callback.apply(this, arguments); 14 | } 15 | }) 16 | }); 17 | 18 | module.exports = request; 19 | -------------------------------------------------------------------------------- /src/js/main.js: -------------------------------------------------------------------------------- 1 | var app = require("../jsx/app.jsx"); 2 | 3 | app.start(); 4 | -------------------------------------------------------------------------------- /src/js/syncModel.js: -------------------------------------------------------------------------------- 1 | /* 2 | SyncModel creates an in-memory representation of documents flowing 3 | through channels. It also mediates any server access so that UI 4 | components are abtracted from network interactions and the API is 5 | mostly synchronous queries from the UI triggered by SyncModel events. 6 | */ 7 | 8 | /* jshint -W061 */ 9 | /* global syncFun */ 10 | /* global compiledFunction */ 11 | 12 | var events = require('events'), 13 | coax = require("coax"), 14 | util = require("util"); 15 | 16 | var dbStateSingletons = {}; 17 | exports.SyncModelForDatabase = function(dbURL) { 18 | var state = dbStateSingletons[dbURL] 19 | if (!state) { 20 | state = new SyncModel(dbURL) 21 | state.setMaxListeners(100) 22 | dbStateSingletons[dbURL] = state 23 | } 24 | return state 25 | } 26 | 27 | exports.allDBs = function(host, cb){ 28 | coax([host, "_all_dbs"], cb); 29 | } 30 | 31 | exports.createDB = function(host, db, config, cb){ 32 | coax.put([host, db, ""], config, cb); 33 | } 34 | 35 | exports.deleteDB = function(host, db, cb){ 36 | coax.del([host, db, ""], cb); 37 | } 38 | 39 | 40 | function SyncModel(db) { 41 | // setup on / emit / etc 42 | events.EventEmitter.call(this); 43 | 44 | // private state 45 | var previewFun, self=this, client = coax(db), 46 | dbConfig = {}, previewChannels = {}, previewDocs = {}; 47 | 48 | // public state 49 | this.db = db; 50 | this.client = client; 51 | this.workingSet = 1000 52 | this.pageSize = 10 53 | // pubic methods 54 | this.setSyncFunction = function(funCode) { 55 | var oldCode = previewFun && previewFun.code 56 | if (funCode == oldCode) { 57 | return; 58 | } 59 | previewChannels = {}; 60 | previewDocs = {}; 61 | totalChanges = 0 62 | previewFun = compileSyncFunction(funCode) 63 | previewFun.code = funCode 64 | loadChangesHistory() 65 | if (this.deployedSyncFunction() == funCode) { 66 | this.emit("syncReset", "deployed") 67 | } else { 68 | this.emit("syncReset", "preview") 69 | } 70 | } 71 | this.getSyncFunction = function() { 72 | return previewFun.code; 73 | } 74 | this.channelNames = function() { 75 | return Object.keys(previewChannels); 76 | } 77 | this.deployedSyncFunction = function(){ 78 | return dbConfig.sync || "function(doc){\n channel(doc.channels)\n}"; 79 | } 80 | 81 | this.deploySyncFunction = function(code, done) { 82 | var newConfig = {} 83 | for (var k in dbConfig) { 84 | if (dbConfig[k]) { 85 | newConfig[k] = dbConfig[k] 86 | } 87 | } 88 | newConfig.sync = code; 89 | client.del([""]/*[""] to force trailing slash*/,function(err){ 90 | if (err && err.constructor !== SyntaxError) { 91 | return done(err); 92 | } 93 | client.put([""]/*[""] to force trailing slash*/,newConfig, function(err, ok){ 94 | if (err && err.constructor !== SyntaxError) { 95 | return done(err); 96 | } 97 | self.setSyncFunction(code) 98 | done(false, ok) 99 | }) 100 | }) 101 | } 102 | this.channel = function(name) { 103 | var changes = [], revs ={}, chan = previewChannels[name]; 104 | if (!chan) return {name:name, changes:[]}; 105 | var docs = chan.docs; 106 | 107 | for (var id in docs) revs[docs[id]] = id 108 | var rs = Object.keys(revs).sort(function(a, b){ 109 | return parseInt(a, 10) - parseInt(b, 10); 110 | }) 111 | for (var i = rs.length - 1; i >= 0; i--) { 112 | var docid = revs[rs[i]] 113 | changes.push({id:docid, seq:parseInt(rs[i], 10), isAccess : chan.access[docid]}) 114 | } 115 | var result = { 116 | name : name, 117 | changes : changes 118 | } 119 | var accessIds = Object.keys(chan.access); 120 | if (accessIds.length) { 121 | result.access = chan.access 122 | result.hiddenAccessIds = []; 123 | for (i = accessIds.length - 1; i >= 0; i--) { 124 | if (!docs[accessIds[i]]) { 125 | result.hiddenAccessIds.push(accessIds[i]) 126 | } 127 | } 128 | } 129 | return result 130 | } 131 | this.randomAccessDocID = function() { 132 | var chs = this.channelNames() 133 | chs = shuffleArray(chs); 134 | var ch = chs.pop(); 135 | while (ch) { 136 | var chInfo = this.channel(ch) 137 | if (chInfo.access) { 138 | var ids = Object.keys(chInfo.access) 139 | return ids[Math.floor(Math.random()*ids.length)] 140 | } 141 | ch = chs.pop() 142 | } 143 | } 144 | this.randomDocID = function(){ 145 | var chs = this.channelNames() 146 | var ch = chs[Math.floor(Math.random()*chs.length)] 147 | var chInfo = this.channel(ch); 148 | var rIds = chInfo.changes.map(function(c){return c.id}) 149 | return rIds[Math.floor(Math.random()*rIds.length)] 150 | } 151 | this.getDoc = function(id, cb){ 152 | client.get(["_raw", id], function(err, raw) { 153 | if (err) {return cb(err);} 154 | var deployed = raw._sync; 155 | delete raw._sync; 156 | raw._rev = deployed.rev; 157 | raw._id = id; 158 | var previewSet = {} 159 | var preview = runSyncFunction(previewSet, id, raw, 0) 160 | cb(err, raw, transformDeployed(id, deployed), transformPreview(id, preview)) 161 | }); 162 | } 163 | this.saveDoc = function(doc, cb) { 164 | client.put(doc._id, doc, cb) 165 | } 166 | this.allDocs = function(cb) { 167 | client.get("_all_docs", function(err, data) { 168 | var rows = data.rows.map(function(r){ 169 | return {id : r.id, access : previewDocs[r.id]} 170 | }) 171 | cb(err, rows) 172 | }) 173 | } 174 | this.allUsers = function(cb) { 175 | client.get(["_view", "principals", {state:false}], cb); 176 | } 177 | this.userInfo = function(id, cb) { 178 | client.get(["_user", id], cb) 179 | } 180 | 181 | // private implementation 182 | function transformDeployed(id, deployed){ 183 | var access = {}; 184 | for (var user in deployed.access) { 185 | var chans = Object.keys(deployed.access[user]) 186 | for (var i = chans.length - 1; i >= 0; i--) { 187 | var ch = chans[i] 188 | access[ch] = access[ch] || [] 189 | access[ch].push(user) 190 | access[ch] = access[ch].sort() 191 | } 192 | } 193 | return { 194 | access : access, 195 | channels : deployed.channels ? Object.keys(deployed.channels) : [] 196 | } 197 | } 198 | 199 | function transformPreview(id, preview) { 200 | // console.log("preview", preview) 201 | var channelSet = {} 202 | preview.access.forEach(function(acc) { 203 | acc.channels.forEach(function(ch) { 204 | channelSet[ch] = channelSet[ch] || []; 205 | channelSet[ch] = 206 | mergeUsers(channelSet[ch], acc.users); 207 | }) 208 | }) 209 | // console.log("preview.access", channelSet) 210 | return { 211 | access : channelSet, 212 | channels : preview.channels, 213 | reject : preview.reject 214 | }; 215 | } 216 | 217 | function runSyncFunction(channelSet, id, doc, seq) { 218 | // console.log('previewFun', doc) 219 | doc._id = id 220 | var sync = previewFun(doc, false, null) 221 | // console.log('previewFun', doc._id, doc, sync) 222 | if (sync.reject) { 223 | console.error("update rejected by sync function", doc, sync) 224 | return; 225 | } 226 | var changed = {}; 227 | previewDocs[id] = false; 228 | sync.channels.forEach(function(ch) { 229 | channelSet[ch] = channelSet[ch] || {docs : {}, access:{}}; 230 | channelSet[ch].docs[id] = seq; 231 | changed[ch]=true; 232 | }) 233 | sync.access.forEach(function(acc) { 234 | previewDocs[id] = true; 235 | acc.channels.forEach(function(ch){ 236 | changed[ch]=true; 237 | channelSet[ch] = channelSet[ch] || {docs : {}, access:{}}; 238 | channelSet[ch].access[id] = 239 | mergeUsers(channelSet[ch].access[id], acc.users); 240 | }) 241 | }) 242 | sync.changed = changed; 243 | return sync; 244 | } 245 | 246 | function mergeUsers(existing, more) { 247 | var keys = {}; 248 | existing = existing || []; 249 | for (var i = existing.length - 1; i >= 0; i--) { 250 | keys[existing[i]] = true; 251 | } 252 | for (i = more.length - 1; i >= 0; i--) { 253 | keys[more[i]] = true; 254 | } 255 | return Object.keys(keys).sort() 256 | } 257 | 258 | // function disconnect() { 259 | // if (changesRequest) { 260 | // changesRequest.abort(); 261 | // } 262 | // } 263 | this.shutdown = function() { 264 | if (changesRequest) { 265 | changesRequest.destroy(); 266 | } 267 | } 268 | 269 | var changesRequest; 270 | var oldBefore; 271 | function moreHistory(before) { 272 | // console.log("totalChanges", totalChanges, self.workingSet) 273 | if (oldBefore !== before && totalChanges < self.workingSet) { 274 | oldBefore = before; 275 | client.get(["_changes", {since : before, include_docs : true, 276 | limit : self.pageSize}], function(err, data) { 277 | // console.log("history", data) 278 | data.results.forEach(onChange) 279 | self.emit("batch") 280 | moreHistory(data.last_seq) 281 | }) 282 | } 283 | } 284 | 285 | function loadChangesHistory(){ 286 | // get first page 287 | // console.log("loadChangesHistory") 288 | client.get(["_changes", {limit : self.pageSize, include_docs : true}], function(err, data) { 289 | // console.log("history once", data) 290 | data.results.forEach(onChange) 291 | self.emit("batch") 292 | moreHistory(data.last_seq) 293 | 294 | changesRequest = client.changes({since : data.last_seq, include_docs : true}, function(err, data){ 295 | // console.log("change", err, data); 296 | if (!err) 297 | onChange(data) 298 | }) 299 | }) 300 | } 301 | 302 | self.once("batch", function() { 303 | self.connected = true; 304 | self.emit("connected") 305 | }) 306 | self.on("newListener", function(name, fun){ 307 | if (name == "connected" && self.connected) { 308 | fun() 309 | } 310 | }) 311 | 312 | var totalChanges = 0 313 | function onChangeWDoc(ch, doc) { 314 | // console.log("onChangeWDoc", ch, doc) 315 | var seq; 316 | if ("number" !== typeof ch.seq) { 317 | seq = parseInt(ch.seq.split(":")[1], 10) 318 | } else { 319 | seq = ch.seq 320 | } 321 | 322 | ch.doc = doc 323 | totalChanges++; 324 | var sync = runSyncFunction(previewChannels, ch.id, ch.doc, seq) 325 | self.emit("change", ch) 326 | Object.keys(sync.changed).forEach(function(channel) { 327 | self.emit("ch:"+channel); 328 | }) 329 | } 330 | 331 | function onChange(ch) { 332 | if (ch.doc) { 333 | onChangeWDoc(ch, ch.doc) 334 | } else if (ch.id == "_user/") { 335 | // ignore, this is an access control change sequence not a data sequence 336 | } else { 337 | console.log("doc async", ch.id) 338 | // return; 339 | client.get(ch.id, function(err, doc) { 340 | if (err) { 341 | console.error("doc missing", ch.id) 342 | } else { 343 | onChangeWDoc(ch, doc) 344 | } 345 | }) 346 | } 347 | 348 | } 349 | 350 | client.get("_config", function(err, config) { 351 | if (err) throw(err); 352 | dbConfig = config; 353 | self.setSyncFunction(config.sync || "function(doc){\n channel(doc.channels)\n}"); 354 | }) 355 | } 356 | 357 | util.inherits(SyncModel, events.EventEmitter); 358 | 359 | function shuffleArray(array) { 360 | for (var i = array.length - 1; i > 0; i--) { 361 | var j = Math.floor(Math.random() * (i + 1)); 362 | var temp = array[i]; 363 | array[i] = array[j]; 364 | array[j] = temp; 365 | } 366 | return array; 367 | } 368 | 369 | var syncWrapper = function(newDoc, oldDoc, realUserCtx) { 370 | "syncCodeStringHere"; 371 | 372 | var _ = require("underscore"), 373 | log = console.log.bind(console); 374 | 375 | function makeArray(maybeArray) { 376 | if (Array.isArray(maybeArray)) { 377 | return maybeArray; 378 | } else { 379 | return [maybeArray]; 380 | } 381 | } 382 | 383 | function inArray(string, array) { 384 | return array.indexOf(string) != -1; 385 | } 386 | 387 | function anyInArray(any, array) { 388 | for (var i = 0; i < any.length; ++i) { 389 | if (inArray(any[i], array)) 390 | return true; 391 | } 392 | return false; 393 | } 394 | 395 | // Proxy userCtx that allows queries but not direct access to user/roles: 396 | var shouldValidate = (realUserCtx !== null && realUserCtx.name !== null); 397 | 398 | function requireUser(names) { 399 | if (!shouldValidate) return; 400 | names = makeArray(names); 401 | if (!inArray(realUserCtx.name, names)) 402 | throw({forbidden: "wrong user"}); 403 | } 404 | 405 | function requireRole(roles) { 406 | if (!shouldValidate) return; 407 | roles = makeArray(roles); 408 | if (!anyInArray(realUserCtx.roles, roles)) 409 | throw({forbidden: "missing role"}); 410 | } 411 | 412 | function requireAccess(channels) { 413 | if (!shouldValidate) return; 414 | channels = makeArray(channels); 415 | if (!anyInArray(realUserCtx.channels, channels)) 416 | throw({forbidden: "missing channel access"}); 417 | } 418 | var results = { 419 | channels : [], 420 | access : [], 421 | roles : [], 422 | reject : false 423 | }; 424 | function channel(){ 425 | var args = Array.prototype.slice.apply(arguments); 426 | results.channels = Array.prototype.concat.apply(results.channels, args); 427 | } 428 | function access(users, channels){ 429 | results.access.push({ 430 | users : makeArray(users), 431 | channels : makeArray(channels) 432 | }) 433 | } 434 | function role(users, channels){ 435 | results.roles.push({ 436 | users : makeArray(users), 437 | channels : makeArray(channels) 438 | }) 439 | } 440 | 441 | function reject(code, message) { 442 | results.reject = [code, message]; 443 | } 444 | try { 445 | // console.log("syncFun", newDoc) 446 | syncFun(newDoc, oldDoc); 447 | } catch(x) { 448 | if (x.forbidden) 449 | reject(403, x.forbidden); 450 | else if (x.unauthorized) 451 | reject(401, x.unauthorized); 452 | else 453 | throw(x); 454 | } 455 | return results; 456 | }.toString(); 457 | 458 | function compileSyncFunction(syncCode) { 459 | var codeString = "var syncFun = ("+ syncCode+")", 460 | wrappedCode = syncWrapper.replace('"syncCodeStringHere"', function() { return codeString; }), 461 | evalString = "compiledFunction = ("+ wrappedCode+")", 462 | compiledFunction; 463 | eval(evalString); 464 | return compiledFunction; 465 | } 466 | -------------------------------------------------------------------------------- /src/jsx/app.jsx: -------------------------------------------------------------------------------- 1 | /** 2 | * @jsx React.DOM 3 | */ 4 | /* global Davis */ 5 | /* global Zepto */ 6 | 7 | var PageWrap = require("./page.jsx"), 8 | channels = require("./channels.jsx"), 9 | ChannelsWatchPage = channels.ChannelsWatchPage, 10 | ChannelInfoPage = channels.ChannelInfoPage, 11 | SyncPage = require("./sync.jsx").SyncPage, 12 | UsersPage = require("./users.jsx"), 13 | AllDatabases = require("./databases.jsx"), 14 | documents = require("./documents.jsx"), 15 | DocumentsPage = documents.DocumentsPage; 16 | 17 | Davis.$ = Zepto; 18 | 19 | exports.start = function() { 20 | console.info("binding routes") 21 | Davis(function() { 22 | this.settings.generateRequestOnPageLoad = true; 23 | this.settings.handleRouteNotFound = true; 24 | 25 | // global handlers 26 | this.bind("routeNotFound", routeNotFound) 27 | this.bind("lookupRoute", lookupRoute) 28 | 29 | // Bind controllers to URL paths 30 | // 31 | // If you find yourself making big changes here 32 | // (like adding something more than /db/:db) 33 | // think about moving to a full page JSX router 34 | // like Chris describes in a comment here 35 | // http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html 36 | this.scope("/_admin", function() { 37 | this.get('/', drawIndexPage) 38 | this.get('/db/:db', drawDocsPage) 39 | this.get('/db/:db/documents/:id', drawDocsPage) 40 | this.get('/db/:db/sync', drawSyncPage) 41 | this.get('/db/:db/channels', drawChannelWatchPage) 42 | this.get('/db/:db/channels/:id', drawChannelInfoPage) 43 | this.get('/db/:db/users', drawUserPage) 44 | this.get('/db/:db/users/:id', drawUserPage) 45 | // todo this.get('/db/:db/users/:id/channels', userChannelsPage) 46 | }) 47 | }); 48 | } 49 | 50 | function draw(component, container) { 51 | React.render( 52 | component, 53 | container || document.getElementById('container') 54 | ); 55 | } 56 | 57 | /* /_admin/ 58 | The home page, list and create databases. 59 | */ 60 | function drawIndexPage(req) { 61 | draw( 62 | 63 |

Welcome to Couchbase Sync Gateway. You are connected to the admin 64 | port at {location.toString()}

65 | 66 |

Documentation for the Sync Gateway is here. Visit the developer portal for downloads and examples. 67 |

68 |
) 69 | } 70 | 71 | /* /_admin/db/myDatabase 72 | /_admin/db/myDatabase/documents/myDocID 73 | The index page for myDatabase, list and edit documents. 74 | */ 75 | function drawDocsPage(req) { 76 | draw( 77 | 78 | 79 | ); 80 | } 81 | 82 | /* /_admin/db/myDatabase/sync 83 | Sync function editor for myDatabase 84 | */ 85 | function drawSyncPage(req) { 86 | draw( 87 | 88 | 89 | ); 90 | } 91 | 92 | /* /_admin/db/myDatabase/channels 93 | Channel watcher page for myDatabase 94 | */ 95 | function drawChannelWatchPage (req) { 96 | var watch = (req.params.watch && req.params.watch.split(',') || []); 97 | draw( 98 | 99 | 100 | ); 101 | } 102 | 103 | /* 104 | /_admin/db/myDatabase/channels/myChannel 105 | Channel detail page 106 | */ 107 | function drawChannelInfoPage(req) { 108 | draw( 109 | 110 | 111 | ); 112 | } 113 | 114 | 115 | /* /_admin/db/myDatabase/users 116 | /_admin/db/myDatabase/users/userID 117 | List and edit users. 118 | */ 119 | function drawUserPage(req) { 120 | draw( 121 | 122 | 123 | ); 124 | } 125 | 126 | /* 404 handlers 127 | If the 404 is in-app, redirect to the index page. 128 | Otherwise make a server request for the new page. 129 | */ 130 | function routeNotFound(r) { 131 | setTimeout(function(){ // required sleep 132 | window.location = "/_admin/" 133 | },100) 134 | } 135 | function lookupRoute(req) { 136 | if (req.path.indexOf("/_admin") !== 0) { 137 | window.location = req.path; 138 | req.delegateToServer() 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/jsx/channels.jsx: -------------------------------------------------------------------------------- 1 | var helpers = require("./helpers.jsx"), 2 | dbPath = helpers.dbPath, 3 | dbState = helpers.dbState, 4 | docLink = helpers.docLink, 5 | userLink = helpers.userLink, 6 | StateForPropsMixin = helpers.StateForPropsMixin, 7 | EventListenerMixin = helpers.EventListenerMixin; 8 | 9 | function hrefToggleWatchingChannel(db, chName, current) { 10 | var channels = []; 11 | var urlparts = current.split("?"); 12 | var query = urlparts[1] 13 | if (query) { 14 | var parts = query.split(/=|&/) 15 | var watch = parts.indexOf("watch") 16 | if (watch !== -1) { 17 | channels = parts[watch+1].split(','); 18 | } 19 | } 20 | var chIndex = channels.indexOf(chName); 21 | if (chIndex == -1) { 22 | channels.push(chName) 23 | } else { 24 | channels.splice(chIndex, 1) 25 | } 26 | if (channels.length === 0) { 27 | return urlparts[0]; 28 | } else { 29 | return dbPath(db, "channels?watch="+channels.join(',')) 30 | } 31 | } 32 | 33 | exports.ChannelsWatchPage = React.createClass({ 34 | render : function(){ 35 | var channels = this.props.watch; 36 | var db = this.props.db, 37 | title = this.props.title || "Watch Channels"; 38 | // todo use cookies to offer previous watch list if the cookie differs from url param 39 | return ( 40 |
41 |

{title}

42 | 43 | 48 |
49 | ) 50 | } 51 | }) 52 | 53 | exports.ChannelInfoPage = React.createClass({ 54 | mixins : [StateForPropsMixin, EventListenerMixin], 55 | getInitialState: function() { 56 | return {channel: {}}; 57 | }, 58 | channelChanged : function() { 59 | this.setState({ 60 | channel : dbState(this.props.db).channel(this.props.id) 61 | }) 62 | }, 63 | setStateForProps : function(newProps, oldProps) { 64 | if (newProps.db && newProps.id) { 65 | var dbs = dbState(newProps.db) 66 | this.listen(dbs, "ch:"+newProps.id, this.channelChanged) 67 | this.channelChanged() 68 | } 69 | }, 70 | render : function() { 71 | var channel = this.state.channel || {}; 72 | return ( 73 |
74 |

Channel: {this.props.id}

75 |
76 |

Recent Updates

77 | 78 |
79 | 80 |
81 | ) 82 | } 83 | }) 84 | 85 | // smells like AccessList 86 | var ChannelAccessList = React.createClass({ 87 | render : function() { 88 | var db = this.props.db; 89 | var accessList = [] 90 | for (var docid in this.props.access) { 91 | accessList.push({id: docid, users: this.props.access[docid]}) 92 | } 93 | return
94 |

Access

95 |
96 | {accessList.map(function(ch) { 97 | return
{docLink(db, ch.id)}
98 | {ch.users.map(function(who){ 99 | return
{userLink(db, who)}
100 | })}
101 | })} 102 |
103 |
104 | } 105 | }) 106 | 107 | var ChannelChanges = React.createClass({ 108 | mixins : [StateForPropsMixin, EventListenerMixin], 109 | getInitialState: function() { 110 | return {channel: {changes:[]}, db : this.props.db, id : this.props.id}; 111 | }, 112 | channelChanged : function() { 113 | // console.log("channelChanged bug") 114 | this.setState({ 115 | channel : dbState(this.props.db).channel(this.props.id) 116 | }) 117 | }, 118 | setStateForProps : function(newProps, oldProps) { 119 | var dbs = dbState(newProps.db) 120 | this.listen(dbs, "ch:"+newProps.id, this.channelChanged) 121 | this.listen(dbs, "syncReset", this.channelChanged) 122 | this.channelChanged() 123 | }, 124 | render : function() { 125 | // console.log("render channelChanges", this.props.id) 126 | var channel = this.state.channel; 127 | var db = this.state.db, hiddenAccess = ; 128 | if (channel.hiddenAccessIds && channel.hiddenAccessIds.length > 0) { 129 | hiddenAccess = 134 | } 135 | return ( 136 |
137 | {channel.name} 138 | {hiddenAccess} 139 |
144 | ); 145 | } 146 | }) 147 | 148 | var RecentChannels = React.createClass({ 149 | mixins : [StateForPropsMixin, EventListenerMixin], 150 | getInitialState: function() { 151 | return {channelNames: [], db : this.props.db}; 152 | }, 153 | changed : function() { 154 | var oldNames = this.state.channelNames, 155 | newNames = dbState(this.props.db).channelNames() 156 | // console.log("RecentChannels state", newNames) 157 | if (oldNames.sort().join() !== newNames.sort().join()) { 158 | this.setState({ 159 | channelNames : newNames 160 | }) 161 | } 162 | }, 163 | setStateForProps : function(newProps, oldProps) { 164 | var dbs = dbState(newProps.db) 165 | this.listen(dbs, "change", this.changed) 166 | this.changed() 167 | }, 168 | render : function() { 169 | // console.log("render RecentChannels", this.state, this.props) 170 | var watch = this.props.watch || [], 171 | currentLoc = location.toString(), 172 | channelNames = this.state.channelNames, 173 | db = this.state.db; 174 | return (
175 | {channelNames.length} channels. 176 | Select channels to watch updates. raw 177 |
) 187 | } 188 | }); 189 | -------------------------------------------------------------------------------- /src/jsx/databases.jsx: -------------------------------------------------------------------------------- 1 | var syncModel = require("../js/syncModel.js"), 2 | helpers = require("./helpers.jsx"), 3 | dbPath = helpers.dbPath, 4 | dbState = helpers.dbState, 5 | docLink = helpers.docLink, 6 | userLink = helpers.userLink, 7 | StateForPropsMixin = helpers.StateForPropsMixin, 8 | EventListenerMixin = helpers.EventListenerMixin; 9 | 10 | module.exports = React.createClass({ 11 | loadList : function() { 12 | syncModel.allDBs(location.origin, function(err, list) { 13 | if (!err) 14 | this.setState({dbs: list}); 15 | }.bind(this)); 16 | }, 17 | getInitialState: function() { 18 | return {dbs: []}; 19 | }, 20 | componentWillMount: function() { 21 | this.loadList(); 22 | }, 23 | createDatabase : function(e) { 24 | e.preventDefault(); 25 | var db = this.refs.dbName.getDOMNode().value; 26 | var url = this.refs.dbServer.getDOMNode().value; 27 | syncModel.createDB(location.origin, db, { 28 | server : url 29 | }, function(err){ 30 | var message; 31 | if (err && err.constructor !== SyntaxError) { 32 | message = err.message 33 | } else { 34 | message = "Created database: "+db 35 | } 36 | this.refs.dbName.state.value = "" 37 | this.loadList(); 38 | this.setState({message : message}) 39 | }.bind(this)) 40 | }, 41 | render : function() { 42 | var dbs = this.state.dbs; 43 | var title = this.props.title || "Databases" 44 | return (
45 |

{title}

46 | 51 |
52 |

{this.state.message}

53 | 54 |
55 | 56 | 57 |
58 |
); 59 | } 60 | }); 61 | -------------------------------------------------------------------------------- /src/jsx/documents.jsx: -------------------------------------------------------------------------------- 1 | var helpers = require("./helpers.jsx"), 2 | dbPath = helpers.dbPath, 3 | dbState = helpers.dbState, 4 | docLink = helpers.docLink, 5 | userLink = helpers.userLink, 6 | brClear = helpers.brClear, 7 | channelLink = helpers.channelLink, 8 | StateForPropsMixin = helpers.StateForPropsMixin, 9 | EventListenerMixin = helpers.EventListenerMixin, 10 | CodeMirrorEditor = require("./editor.jsx").CodeMirrorEditor; 11 | 12 | var JSONDoc = exports.JSONDoc = React.createClass({ 13 | render : function() { 14 | return
15 |

{ 16 | this.props.id ? {this.props.id+" "} raw : "Loading..."}

17 |

 18 |       {JSON.stringify(this.props.doc, null, 2)}
 19 |       
20 |
; 21 | } 22 | }) 23 | 24 | var EditableJSONDoc = React.createClass({ 25 | render : function(){ 26 | var editor = this.props.docText ? :
; 32 | return
33 |
34 | 35 | 36 |
37 | {editor} 38 |
39 | } 40 | }) 41 | 42 | var DocSyncPreview = exports.DocSyncPreview = React.createClass({ 43 | getDefaultProps : function(){ 44 | return {sync:{channels:[], access:{}}}; 45 | }, 46 | render : function() { 47 | var sync = this.props.sync; 48 | // console.log("sync", sync) 49 | var db = this.props.db; 50 | if (!sync) return
; 51 | var channels = sync.channels; 52 | return
53 |
54 |

Channels

55 |
    56 | {channels.map(function(ch) { 57 | return
  • {channelLink(db, ch)}
  • 58 | })} 59 |
60 |
61 | 62 |
; 63 | } 64 | }) 65 | 66 | // smells like ChannelAccessList 67 | var AccessList = React.createClass({ 68 | render : function() { 69 | var db = this.props.db; 70 | var accessList = [] 71 | for (var ch in this.props.access) { 72 | accessList.push({name: ch, users: this.props.access[ch]}) 73 | } 74 | return
75 |

Access

76 |
77 | {accessList.map(function(ch) { 78 | return
{channelLink(db, ch.name)}
79 | {ch.users.map(function(who){ 80 | return
{userLink(db, who)}
81 | })}
82 | })} 83 |
84 |
85 | } 86 | }) 87 | 88 | exports.DocumentsPage = React.createClass({ 89 | render : function() { 90 | var db = this.props.db; 91 | var docID = this.props.docID; 92 | return ( 93 |
94 | 95 | {docID && } 96 |
97 | ); 98 | } 99 | }); 100 | 101 | var ListDocs = React.createClass({ 102 | getInitialState: function() { 103 | return {rows: []}; 104 | }, 105 | componentWillMount: function() { 106 | var dbs = dbState(this.props.db) 107 | dbs.on("connected", function() { 108 | dbs.allDocs(function(err, rows){ 109 | this.setState({rows : rows}) 110 | }.bind(this)); 111 | }.bind(this)) 112 | }, 113 | findOrCreateDoc : function(e){ 114 | e.preventDefault() 115 | var id = this.refs.goID.getDOMNode().value 116 | console.log("createDoc", id) 117 | var url = dbPath(this.props.db, "documents/"+id) 118 | document.location = url; 119 | }, 120 | render : function() { 121 | var db = this.props.db; 122 | var rows = this.state.rows; 123 | return
124 | {rows.length} documents, highlighted documents have access control output with the current sync function. 125 |

Load or create document with ID: 126 |

127 |
136 | } 137 | }) 138 | 139 | var DocInfo = React.createClass({ 140 | mixins : [StateForPropsMixin], 141 | getInitialState: function() { 142 | return {deployed : {channels:[], access:{}}, 143 | db : this.props.db, docText : "", loadSeq : 0}; 144 | }, 145 | setDoc : function(id) { 146 | if (!id) return; 147 | dbState(this.props.db).getDoc(id, function(err, doc, deployedSync, previewSync) { 148 | if (err && err.error == "not_found") { 149 | doc = {_id : id} 150 | } else if (err) { 151 | return console.error(err) 152 | } 153 | console.log("getDoc", doc) 154 | this.setState({docID : id, 155 | docText : JSON.stringify(doc, null, 2), 156 | isNewDoc : !doc._rev, 157 | loadSeq : this.state.loadSeq + 1, 158 | deployed : deployedSync, preview : previewSync}) 159 | }.bind(this)) 160 | }, 161 | saveDoc : function(e){ 162 | e.preventDefault(); 163 | if (!(this.state.docText && this.state.docID)) {return;} 164 | var doc = JSON.parse(this.state.docText) 165 | console.log("saveDoc", doc) 166 | dbState(this.props.db).saveDoc(doc, function(err) { 167 | console.log("saved Doc", this.state.docID) 168 | this.setDoc(this.state.docID) 169 | }.bind(this)) 170 | }, 171 | revertDoc : function(e){ 172 | e.preventDefault(); 173 | if (!this.state.docID) return; 174 | this.setDoc(this.state.docID) 175 | }, 176 | bindState: function(name) { 177 | return function(value) { 178 | var newState = {}; 179 | newState[name] = value; 180 | this.setState(newState); 181 | }.bind(this); 182 | }, 183 | setStateForProps : function(props) { 184 | if (props.db && props.docID) { 185 | this.setDoc(props.docID) 186 | } 187 | }, 188 | render : function() { 189 | var newDocMessage; 190 | if (this.state.isNewDoc) { 191 | newDocMessage =

Document with ID "{this.props.docID}" will be created on save.

192 | } 193 | return ( 194 |
195 |

{ 196 | this.state.docID ? {this.state.docID+" "} raw : "Loading..."} 197 |

198 | {newDocMessage} 199 | 200 | 201 | 202 |

Raw document URL

203 |
204 | ); 205 | } 206 | }); 207 | 208 | -------------------------------------------------------------------------------- /src/jsx/editor.jsx: -------------------------------------------------------------------------------- 1 | var IS_MOBILE = ( 2 | navigator.userAgent.match(/Android/i) || 3 | navigator.userAgent.match(/webOS/i) || 4 | navigator.userAgent.match(/iPhone/i)|| 5 | navigator.userAgent.match(/iPad/i) || 6 | navigator.userAgent.match(/iPod/i) || 7 | navigator.userAgent.match(/BlackBerry/i) || 8 | navigator.userAgent.match(/Windows Phone/i) 9 | ); 10 | 11 | exports.CodeMirrorEditor = React.createClass({ 12 | componentDidMount: function(root) { 13 | if (IS_MOBILE) { 14 | return; 15 | } 16 | this.editor = CodeMirror.fromTextArea(this.refs.editor.getDOMNode(), { 17 | mode: this.props.mode, 18 | lineNumbers: true, 19 | matchBrackets: true, 20 | readOnly: this.props.readOnly 21 | }); 22 | // console.log("CodeMirror",this.editor) 23 | this.editor.on('change', this.onChange); 24 | }, 25 | onChange: function(e, change) { 26 | if (change.origin !== "setValue" && this.props.onChange) { 27 | var content = this.editor.getValue(); 28 | this.props.onChange(content); 29 | } 30 | }, 31 | componentWillUpdate : function(newProps) { 32 | // console.log("componentWillUpdate", this.props, newProps) 33 | // don't refill the editor unless we get new external data 34 | // console.log(newProps) 35 | if (this.props.loadSeq !== newProps.loadSeq) { 36 | this.editor.setValue(newProps.codeText) 37 | } 38 | }, 39 | render: function() { 40 | // wrap in a div to fully contain CodeMirror 41 | var editor; 42 | // console.log("editor", this.props) 43 | if (IS_MOBILE) { 44 | editor =
{this.props.codeText}
; 45 | } else { 46 | editor =