From 32fc0540070cf884e3bac8b05a902b6f10f82323 Mon Sep 17 00:00:00 2001 From: loganhz Date: Sat, 16 Sep 2017 11:08:00 +0800 Subject: [PATCH] Expose metadata field in add service and edit service pages --- .../container/new-edit/component.js | 6 +- .../container/new-edit/template.hbs | 8 + app/components/form-metadata/component.js | 47 +++++ app/components/form-metadata/template.hbs | 10 + app/components/json-editor/component.js | 52 ++++++ app/components/json-editor/template.hbs | 1 + app/styles/_rancher.scss | 1 + app/styles/components/_json-editor.scss | 3 + ember-cli-build.js | 1 + translations/en-us.yaml | 7 + vendor/json-sanitizer/LICENSE.txt | 176 ++++++++++++++++++ vendor/json-sanitizer/NOTICE.txt | 17 ++ vendor/json-sanitizer/json-sanitizer.js | 172 +++++++++++++++++ 13 files changed, 500 insertions(+), 1 deletion(-) create mode 100644 app/components/form-metadata/component.js create mode 100644 app/components/form-metadata/template.hbs create mode 100644 app/components/json-editor/component.js create mode 100644 app/components/json-editor/template.hbs create mode 100644 app/styles/components/_json-editor.scss create mode 100644 vendor/json-sanitizer/LICENSE.txt create mode 100644 vendor/json-sanitizer/NOTICE.txt create mode 100644 vendor/json-sanitizer/json-sanitizer.js diff --git a/app/components/container/new-edit/component.js b/app/components/container/new-edit/component.js index 81c86c6f1..a7d6b56a7 100644 --- a/app/components/container/new-edit/component.js +++ b/app/components/container/new-edit/component.js @@ -39,6 +39,7 @@ export default Ember.Component.extend(NewOrEdit, { imageErrors: null, portErrors: null, stackErrors: null, + metadataErrors: null, actions: { setImage(uuid) { @@ -100,11 +101,13 @@ export default Ember.Component.extend(NewOrEdit, { name: this.get('service.name'), description: this.get('service.description'), scale: this.get('service.scale'), + metadata: this.get('service.metadata') || {}, }); } else { this.setProperties({ name: this.get('launchConfig.name'), description: this.get('launchConfig.description'), + metadata: {}, }); } @@ -192,7 +195,7 @@ export default Ember.Component.extend(NewOrEdit, { errors.pushObjects(this.get('imageErrors')||[]); errors.pushObjects(this.get('portErrors')||[]); errors.pushObjects(this.get('stackErrors')||[]); - + errors.pushObjects(this.get('metadataErrors')||[]); errors = errors.uniq(); @@ -261,6 +264,7 @@ export default Ember.Component.extend(NewOrEdit, { pr = this.get('service').clone(); nameResource = pr; pr.set('launchConfig', lc); + pr.set('metadata', this.get('metadata')) pr.set('scale', this.get('scale')); } else { // Convert the launch config to a container diff --git a/app/components/container/new-edit/template.hbs b/app/components/container/new-edit/template.hbs index 1234d2963..3ebc9f504 100644 --- a/app/components/container/new-edit/template.hbs +++ b/app/components/container/new-edit/template.hbs @@ -154,6 +154,14 @@ {{#if isService}} {{#unless isSidekick}} + {{form-metadata + classNames="accordion-wrapper" + instance=metadata + errors=metadataErrors + expandAll=al.expandAll + expandFn=expandFn + }} + {{container/form-service-links service=service expandAll=al.expandAll diff --git a/app/components/form-metadata/component.js b/app/components/form-metadata/component.js new file mode 100644 index 000000000..cdbb9e6e4 --- /dev/null +++ b/app/components/form-metadata/component.js @@ -0,0 +1,47 @@ +import Ember from 'ember'; +import { STATUS, STATUS_INTL_KEY, classForStatus } from 'ui/components/accordion-list-item/component'; + +export default Ember.Component.extend({ + intl: Ember.inject.service(), + + classNames: ['accordion-wrapper'], + + detailKey: 'formMetadata.detail', + + instance: null, + errors: null, + invalid: false, + + didReceiveAttrs() { + if (!this.get('expandFn')) { + this.set('expandFn', function (item) { + item.toggleProperty('expanded'); + }); + } + }, + + validate: function () { + let intl = this.get('intl'); + if (this.get('invalid')) { + this.set('errors', [intl.t('formMetadata.errors.invalidJSON')]) + } else if (['object', 'null'].indexOf(Ember.typeOf(this.get('instance'))) === -1) { + this.set('errors', [intl.t('formMetadata.errors.topLevelValueInvalid')]); + } else { + this.set('errors', []); + } + }.observes('invalid', 'instance'), + + statusClass: null, + status: function () { + let k; + if (this.get('invalid') || ['object', 'null'].indexOf(Ember.typeOf(this.get('instance'))) === -1) { + k = STATUS.ERROR; + } else if (!Ember.isNone(this.get('instance')) && Object.keys(this.get('instance')).length > 0) { + k = STATUS.CONFIGURED; + } else { + k = STATUS.NOTCONFIGURED; + } + this.set('statusClass', classForStatus(k)); + return this.get('intl').t(`${STATUS_INTL_KEY}.${k}`); + }.property('invalid'), +}); diff --git a/app/components/form-metadata/template.hbs b/app/components/form-metadata/template.hbs new file mode 100644 index 000000000..0bd09e152 --- /dev/null +++ b/app/components/form-metadata/template.hbs @@ -0,0 +1,10 @@ +{{#accordion-list-item + title=(t 'formMetadata.title') + detail=(t detailKey appName=settings.appName) + status=status + statusClass=statusClass + expandAll=expandAll + expand=(action expandFn) +}} + {{json-editor json=instance isInvalid=invalid}} +{{/accordion-list-item}} diff --git a/app/components/json-editor/component.js b/app/components/json-editor/component.js new file mode 100644 index 000000000..a886b74c7 --- /dev/null +++ b/app/components/json-editor/component.js @@ -0,0 +1,52 @@ +import Ember from 'ember'; +import sanitize from 'json-sanitizer'; +import C from 'ui/utils/constants'; + +export default Ember.Component.extend({ + json: {}, + isInvalid: false, + + tagName: 'div', + classNames: ['jsoneditor-component'], + + jsonString: function () { + return JSON.stringify(this.get('json'), undefined, 4); + }.property('json'), + + onChange: function () { + try { + const json = this.parseJSON(this.jsonString) + this.set('json', json); + this.set('isInvalid', false) + } catch (err) { + this.set('isInvalid', true) + } + }.observes('jsonString'), + + parseJSON: function (jsonString) { + try { + return JSON.parse(jsonString); + } catch (err) { + return JSON.parse(sanitize(jsonString)); + } + }, + + focusOut() { + if (!this.get('isInvalid')) { + this.set('jsonString', JSON.stringify(this.get('json'), undefined, 4)); + } + }, + + keyDown: function (event) { + const keyCode = event.which; + if (keyCode === C.KEY.TAB) { + event.preventDefault(); + const el = $(this).get(0).childViews.get(0).element; + const start = el.selectionStart; + const end = el.selectionEnd; + $(el).val($(el).val().substring(0, start) + " " + $(el).val().substring(end)); + el.selectionStart = start + 4; + el.selectionEnd = start + 4; + } + }, +}); diff --git a/app/components/json-editor/template.hbs b/app/components/json-editor/template.hbs new file mode 100644 index 000000000..a678c2972 --- /dev/null +++ b/app/components/json-editor/template.hbs @@ -0,0 +1 @@ +{{schema/input-multiline value=jsonString}} \ No newline at end of file diff --git a/app/styles/_rancher.scss b/app/styles/_rancher.scss index ef05964f6..5428bccbf 100644 --- a/app/styles/_rancher.scss +++ b/app/styles/_rancher.scss @@ -35,6 +35,7 @@ @import "app/styles/components/spark-line"; @import "app/styles/components/tooltip"; @import "app/styles/components/container-shell"; +@import "app/styles/components/json-editor"; @import "app/styles/components/modals"; @import "app/styles/components/catalog-box"; @import "app/styles/components/code"; diff --git a/app/styles/components/_json-editor.scss b/app/styles/components/_json-editor.scss new file mode 100644 index 000000000..e640ed3c7 --- /dev/null +++ b/app/styles/components/_json-editor.scss @@ -0,0 +1,3 @@ +.jsoneditor-component .form-control.text-mono{ + height: 300px; +} diff --git a/ember-cli-build.js b/ember-cli-build.js index bf5295d09..ae62ec6e5 100644 --- a/ember-cli-build.js +++ b/ember-cli-build.js @@ -87,6 +87,7 @@ module.exports = function(defaults) { app.import('bower_components/async/dist/async.js'); app.import('bower_components/position-calculator/dist/position-calculator.js'); app.import('vendor/aws-sdk-ec2.js'); + app.import('vendor/json-sanitizer/json-sanitizer.js'); app.import('bower_components/identicon.js/pnglib.js'); app.import('bower_components/identicon.js/identicon.js'); app.import('bower_components/commonmark/dist/commonmark.js'); diff --git a/translations/en-us.yaml b/translations/en-us.yaml index 6d55d7877..b5e48400a 100644 --- a/translations/en-us.yaml +++ b/translations/en-us.yaml @@ -2167,6 +2167,13 @@ formUserLabels: placeholder: e.g. bar protip: "ProTip: Paste one or more lines of key=value pairs into any key field for easy bulk entry." +formMetadata: + title: Metadata + detail: Configure the metadata for the container. + errors: + invalidJSON: Metadata JSON format is invalid. + topLevelValueInvalid: Metadata JSON top-level value should be an object. + formUpgrade: title: Upgrade Policy detail: Configure how containers are replaced when performing an upgrade. diff --git a/vendor/json-sanitizer/LICENSE.txt b/vendor/json-sanitizer/LICENSE.txt new file mode 100644 index 000000000..ea2712c09 --- /dev/null +++ b/vendor/json-sanitizer/LICENSE.txt @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/vendor/json-sanitizer/NOTICE.txt b/vendor/json-sanitizer/NOTICE.txt new file mode 100644 index 000000000..f65d2291d --- /dev/null +++ b/vendor/json-sanitizer/NOTICE.txt @@ -0,0 +1,17 @@ +JSON Editor +https://github.com/josdejong/jsoneditor + +Copyright (C) 2011-2017 Jos de Jong + + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/json-sanitizer/json-sanitizer.js b/vendor/json-sanitizer/json-sanitizer.js new file mode 100644 index 000000000..9fe173c07 --- /dev/null +++ b/vendor/json-sanitizer/json-sanitizer.js @@ -0,0 +1,172 @@ +/** + * Sanitize a JSON-like string containing. For example changes JavaScript + * notation into JSON notation. + * This function for example changes a string like "{a: 2, 'b': {c: 'd'}" + * into '{"a": 2, "b": {"c": "d"}' + * @param {string} jsString + * @returns {string} json + */ + +(function () { + function generateModule(name, values) { + define(name, [], function () { + 'use strict'; + return values; + }); + } + generateModule('json-sanitizer', { + 'default': function sanitize(jsString) { + // escape all single and double quotes inside strings + var chars = []; + var i = 0; + + //If JSON starts with a function (characters/digits/"_-"), remove this function. + //This is useful for "stripping" JSONP objects to become JSON + //For example: /* some comment */ function_12321321 ( [{"a":"b"}] ); => [{"a":"b"}] + var match = jsString.match(/^\s*(\/\*(.|[\r\n])*?\*\/)?\s*[\da-zA-Z_$]+\s*\(([\s\S]*)\)\s*;?\s*$/); + if (match) { + jsString = match[3]; + } + + // helper functions to get the current/prev/next character + function curr() { return jsString.charAt(i); } + function next() { return jsString.charAt(i + 1); } + function prev() { return jsString.charAt(i - 1); } + + // get the last parsed non-whitespace character + function lastNonWhitespace() { + var p = chars.length - 1; + + while (p >= 0) { + var pp = chars[p]; + if (pp !== ' ' && pp !== '\n' && pp !== '\r' && pp !== '\t') { // non whitespace + return pp; + } + p--; + } + + return ''; + } + + // skip a block comment '/* ... */' + function skipBlockComment() { + i += 2; + while (i < jsString.length && (curr() !== '*' || next() !== '/')) { + i++; + } + i += 2; + } + + // skip a comment '// ...' + function skipComment() { + i += 2; + while (i < jsString.length && (curr() !== '\n')) { + i++; + } + } + + // parse single or double quoted string + function parseString(quote) { + chars.push('"'); + i++; + var c = curr(); + while (i < jsString.length && c !== quote) { + if (c === '"' && prev() !== '\\') { + // unescaped double quote, escape it + chars.push('\\'); + } + + // handle escape character + if (c === '\\') { + i++; + c = curr(); + + // remove the escape character when followed by a single quote ', not needed + if (c !== '\'') { + chars.push('\\'); + } + } + chars.push(c); + + i++; + c = curr(); + } + if (c === quote) { + chars.push('"'); + i++; + } + } + + // parse an unquoted key + function parseKey() { + var specialValues = ['null', 'true', 'false']; + var key = ''; + var c = curr(); + + var regexp = /[a-zA-Z_$\d]/; // letter, number, underscore, dollar character + while (regexp.test(c)) { + key += c; + i++; + c = curr(); + } + + if (specialValues.indexOf(key) === -1) { + chars.push('"' + key + '"'); + } + else { + chars.push(key); + } + } + + // parse an unquoted key + function parseValue() { + var specialValues = ['null', 'true', 'false']; + var key = ''; + var c = curr(); + + while ([',', '}', ']'].indexOf(c) === -1) { + key += c; + i++; + c = curr(); + } + + key = key.trim() + + if (specialValues.indexOf(key) === -1 && !(key + '').match(/^([0-9]+\.)?[0-9]*$/)) { + chars.push('"' + key + '"'); + } + else { + chars.push(key); + } + } + + while (i < jsString.length) { + var c = curr(); + + if (c === '/' && next() === '*') { + skipBlockComment(); + } + else if (c === '/' && next() === '/') { + skipComment(); + } + else if (c === '\'' || c === '"') { + parseString(c); + } + else if (/[a-zA-Z_$]/.test(c) && ['{', ','].indexOf(lastNonWhitespace()) !== -1) { + // an unquoted object key (like a in '{a:2}') + parseKey(); + } + else if (c.trim() !== '' && ['[', '{'].indexOf(c) === -1 && ':' === lastNonWhitespace()) { + // an unquoted object value (like b in '{a:b}') + parseValue(); + } + else { + chars.push(c); + i++; + } + } + + return chars.join(''); + } + }); +})();