Skip to content

Commit

Permalink
feat(google): define json-text directive to handle view
Browse files Browse the repository at this point in the history
  • Loading branch information
edgarulg committed Oct 18, 2024
1 parent bda1b59 commit 264b9c5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,7 @@
<b>{{ $ctrl.valueLabel }}</b>
</td>
<td>
<textarea
class="form-control input input-sm"
ng-model="$ctrl.formatValueForDisplay[$index]"
rows="4"
ng-change="$ctrl.onValueChange($index)"
></textarea>
<textarea json-text class="form-control input input-sm" ng-model="pair.value" rows="4"></textarea>
</td>
<td>
<div class="form-control-static">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,22 @@ export const CORE_FORMS_MAPOBJECTEDITOR_MAPOBJECTEDITOR_COMPONENT = 'spinnaker.c
export const name = CORE_FORMS_MAPOBJECTEDITOR_MAPOBJECTEDITOR_COMPONENT; // for backwards compatibility
angular
.module(CORE_FORMS_MAPOBJECTEDITOR_MAPOBJECTEDITOR_COMPONENT, [CORE_VALIDATION_VALIDATEUNIQUE_DIRECTIVE])
.directive('jsonText', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
function into(input) {
return JSON.parse(input);
}
function out(data) {
return JSON.stringify(data);
}
ngModel.$parsers.push(into);
ngModel.$formatters.push(out);
},
};
})
.component('mapObjectEditor', {
bindings: {
model: '=',
Expand Down Expand Up @@ -41,24 +57,6 @@ angular
this.onChange();
};

this.onValueChange = (index) => {
const formattedValue = this.formattedValues[index];

// Parse the JSON if it looks like an object or array, otherwise leave it as a string
try {
this.backingModel[index].value = JSON.parse(formattedValue);
} catch (e) {
this.backingModel[index].value = formattedValue; // Not JSON, so treat it as a string
}

// Sync changes with the model
this.synchronize();
};

this.formatValueForDisplay = (value) => {
return typeof value === 'object' ? JSON.stringify(value, null, 2) : value;
};

// Clears existing values from model, then replaces them
this.synchronize = () => {
if (this.isParameterized) {
Expand Down Expand Up @@ -106,8 +104,6 @@ angular
this.backingModel.push({ key: key, value: this.model[key] });
});
}

this.formattedValues = this.backingModel.map((pair) => this.formatValueForDisplay(pair.value));
};

$scope.$watch(() => JSON.stringify(this.backingModel), this.synchronize);
Expand Down

0 comments on commit 264b9c5

Please sign in to comment.