Move expression field to angularjas so that fields line up better.

Change-Id: Idd5ba503e74090c75492bb879fb2c3f473d35cd2
This commit is contained in:
Rob Raymond 2014-10-08 10:53:19 -06:00
parent 44c9d4e48b
commit 7a5c61342e
4 changed files with 33 additions and 53 deletions

View File

@ -15,12 +15,13 @@
# under the License.
import re
import json
from django import forms as django_forms
from django.template.loader import get_template
from django.template import Context
from django.utils import html
from django.utils.translation import ugettext_lazy as _ # noqa
from django.utils.translation import ugettext as _ # noqa
from horizon import exceptions
from horizon import forms
@ -31,57 +32,24 @@ from monitoring.alarmdefs import constants
class ExpressionWidget(forms.Widget):
def __init__(self, initial, attrs):
def __init__(self, initial, attrs=None):
super(ExpressionWidget, self).__init__(attrs)
self.initial = initial
def render(self, name, value, attrs):
final_attrs = self.build_attrs(attrs, name=name)
t = get_template(constants.TEMPLATE_PREFIX + 'expression_field.html')
local_attrs = {'service': ''}
func = json.dumps([('min', _('min')), ('max', _('max')), ('sum', _('sum')),
('count', _('count')), ('avg', _('avg'))])
comparators = [['>', '>'], ['>=', '>='], ['<', '<'], ['<=', '<=']]
local_attrs = {'service': '', 'func': func, 'comparators': comparators}
local_attrs.update(final_attrs)
context = Context(local_attrs)
return t.render(context)
class SimpleExpressionWidget(django_forms.MultiWidget):
def __init__(self, initial, attrs=None):
comparators = [('>', '>'), ('>=', '>='), ('<', '<'), ('<=', '<=')]
func = [('min', _('min')), ('max', _('max')), ('sum', _('sum')),
('count', _('count')), ('avg', _('avg'))]
_widgets = (
django_forms.widgets.Select(attrs=attrs, choices=func),
ExpressionWidget(initial, attrs={}),
django_forms.widgets.Select(attrs=attrs, choices=comparators),
django_forms.widgets.TextInput(),
)
super(SimpleExpressionWidget, self).__init__(_widgets, attrs)
def decompress(self, expr):
if expr:
return re.search('^(\w+)\((.*)\) ([<>=]*) (.*)$', expr).groups()
else:
return [None, None, None, None]
def format_output(self, rendered_widgets):
return ''.join(rendered_widgets)
def value_from_datadict(self, data, files, name):
values = [
widget.value_from_datadict(data, files, name + '_%s' % i)
for i, widget in enumerate(self.widgets)]
try:
expression = '%s(%s) %s %s' % (values[0],
values[1],
values[2],
values[3])
except ValueError:
return ''
else:
return expression
class NotificationField(forms.MultiValueField):
def __init__(self, *args, **kwargs):
super(NotificationField, self).__init__(*args, **kwargs)
@ -166,13 +134,12 @@ class BaseAlarmForm(forms.SelfHandlingForm):
def _init_fields(self, readOnly=False, create=False, initial=None):
required = True
textWidget = None
textAreaWidget = forms.Textarea(attrs={'class': 'large-text-area'})
choiceWidget = forms.Select
if create:
expressionWidget = SimpleExpressionWidget(initial)
expressionWidget = ExpressionWidget(initial)
notificationWidget = NotificationCreateWidget()
else:
expressionWidget = textAreaWidget
expressionWidget = textWidget
notificationWidget = NotificationCreateWidget()
self.fields['name'] = forms.CharField(label=_("Name"),
@ -184,7 +151,7 @@ class BaseAlarmForm(forms.SelfHandlingForm):
widget=expressionWidget)
self.fields['description'] = forms.CharField(label=_("Description"),
required=False,
widget=textAreaWidget)
widget=textWidget)
sev_choices = [("LOW", _("Low")),
("MEDIUM", _("Medium")),
("HIGH", _("High")),

View File

@ -43,18 +43,19 @@ $('#notification_table').on('click', '#remove_notif_button', (function(event){
metricsList = {{ metrics | safe }}
</script>
<style>
#id_expression_0 {
#function {
width: auto;
float: left;
}
#metric-chooser {
width: auto;
float: left;
}
#id_expression_2 {
#comparators {
width: auto;
float: left;
}
#id_expression_3 {
#threshold {
width: auto;
}
</style>

View File

@ -1,10 +1,18 @@
{% load i18n %}
<div ng-controller="alarmEditController" ng-init="init('{{ service }}')">
<input type="hidden" name="{{ name }}" id="dimension"/>
<select id="metric-chooser" class="form-control"
ng-model="currentMetric"
ng-options="metric for metric in metricNames"
ng-change="metricChanged()"></select>
<div style="margin-bottom:5px;">
<select id="function" class="form-control"
ng-model="currentFunction" ng-options="f[0] as f[1] for f in {{func}}"></select>
<select id="metric-chooser" class="form-control"
ng-model="currentMetric"
ng-options="metric for metric in metricNames"
ng-change="metricChanged()">
</select>
<select id="comparators" class="form-control"
ng-model="currentComparator" ng-options="f[0] as f[1] for f in {{comparators}}"></select>
<input type="number" id="threshold" class="form-control" ng-model="currentThreshold"/>
</div>
<tags-input id="dimension-chooser" ng-model="tags"
placeholder="{% trans 'Add a dimension' %}"
add-from-autocomplete-only="true"

View File

@ -34,6 +34,10 @@ angular.module('monitoring.controllers', [])
$scope.metrics = metricsList;
$scope.metricNames = uniqueNames(metricsList, 'name')
$scope.currentMetric = $scope.metricNames[0];
$scope.currentFunction = "max";
$scope.currentComparator = ">";
$scope.currentThreshold = 0;
$scope.tags = [];
$scope.possibleDimensions = function(query) {
var deferred = $q.defer();
var dim = {}
@ -90,7 +94,7 @@ angular.module('monitoring.controllers', [])
}
dim += value['text']
})
return $scope.currentMetric + '{' + dim + '}';
return $scope.currentMetric + '{' + dim + '} ' + $scope.currentComparator + ' ' + $scope.currentThreshold;
}
$scope.init = function(defaultTag) {
if (defaultTag.length > 0) {