blob: 09da1ec2cc09e8c51ffb0dc11e83faac9381c6dd [file] [log] [blame]
Steven Burrowsf50a1772017-09-14 11:58:15 +01001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17(function () {
18
19 var ks, wss;
20
21 var EditableText = function (el, options) {
22 // constructor
23 this.el = el;
24 this.scope = options.scope;
25 this.options = options;
26
27 this.el.classed('editable clickable', true).on('click', this.onEdit.bind(this));
28 this.editingName = false;
29 };
30
31 EditableText.prototype = {
32
33 bindHandlers: function () {
34 ks.keyBindings({
35 'enter': this.save.bind(this),
36 'esc': [this.cancel.bind(this), 'Close the details panel']
37 });
38 },
39
40 unbindHandlers: function () {
41 ks.unbindKeys();
42
43 if (this.options.keyBindings) {
44 // Reset to original bindings before editable text
45 ks.keyBindings(this.options.keyBindings);
46 }
47 },
48
49 addTextField: function () {
50 return this.el.append('input').classed('name-input', true)
51 .attr('type', 'text')
52 .attr('value', this.scope.panelData.name)[0][0];
53 },
54
55 onEdit: function () {
56 if (!this.editingName) {
57 this.el.classed('editable clickable', false);
58 this.el.text('');
59
60 var el = this.addTextField();
61 el.focus();
62 el.select();
63 this.editingName = true;
64
65 this.bindHandlers();
66
67 ks.enableGlobalKeys(false);
68 }
69 },
70
71 exit: function (name) {
72 this.el.text(name);
73 this.el.classed('editable clickable', true);
74 this.editingName = false;
75 ks.enableGlobalKeys(true);
76 this.unbindHandlers();
77 },
78
79 cancel: function (a, b, ev) {
80
81 if (this.editingName) {
82 this.exit(this.scope.panelData.name);
83 return true;
84 }
85
86 return false;
87 },
88
89 save: function () {
90 var id = this.scope.panelData.id,
91 val,
92 newVal;
93
94 if (this.editingName) {
95 val = this.el.select('input').property('value').trim();
96 newVal = val || id;
97
98 this.exit(newVal);
99 this.scope.panelData.name = newVal;
100 wss.sendEvent(this.options.nameChangeRequest, { id: id, name: val });
101 }
102 },
103 };
104
105
106 angular.module('onosLayer')
107 .factory('EditableTextComponent', [
108
109 'KeyService', 'WebSocketService',
110
111 function (_ks_, _wss_) {
112 ks = _ks_;
113 wss = _wss_;
114
115 return EditableText;
116 },
117 ]);
118
119})();