1// Copyright (c) 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5function attachListeners() {
6  var radioEls = document.querySelectorAll('input[type="radio"]');
7  for (var i = 0; i < radioEls.length; ++i) {
8    radioEls[i].addEventListener('click', onRadioClicked);
9  }
10
11  // Wire up the 'click' event for each function's button.
12  var functionEls = document.querySelectorAll('.function');
13  for (var i = 0; i < functionEls.length; ++i) {
14    var functionEl = functionEls[i];
15    var id = functionEl.getAttribute('id');
16    var buttonEl = functionEl.querySelector('button');
17
18    // The function name matches the element id.
19    var func = window[id + 'ButtonClicked'];
20    buttonEl.addEventListener('click', func);
21  }
22}
23
24function onRadioClicked(e) {
25  var divId = this.id.slice(5);  // skip "radio"
26  var functionEls = document.querySelectorAll('.function');
27  for (var i = 0; i < functionEls.length; ++i) {
28    var visible = functionEls[i].id === divId;
29    if (functionEls[i].id === divId)
30      functionEls[i].removeAttribute('hidden');
31    else
32      functionEls[i].setAttribute('hidden', '');
33  }
34}
35
36function getButtonClicked(e) {
37  var key = document.getElementById('getKey').value;
38  common.naclModule.postMessage({cmd: 'Get', key: key});
39}
40
41function setButtonClicked(e) {
42  var key = document.getElementById('setKey').value;
43  var valueString = document.getElementById('setValue').value;
44  var value;
45  try {
46    value = JSON.parse(valueString);
47  } catch (e) {
48    common.logMessage('Error parsing value: ' + e);
49    return;
50  }
51
52  common.naclModule.postMessage({cmd: 'Set', key: key, value: value});
53}
54
55function deleteButtonClicked(e) {
56  var key = document.getElementById('deleteKey').value;
57  common.naclModule.postMessage({cmd: 'Delete', key: key});
58}
59
60function getkeysButtonClicked(e) {
61  common.naclModule.postMessage({cmd: 'GetKeys'});
62}
63
64function haskeyButtonClicked(e) {
65  var key = document.getElementById('haskeyKey').value;
66  common.naclModule.postMessage({cmd: 'HasKey', key: key});
67}
68
69// Called by the common.js module.
70function handleMessage(message_event) {
71  var msg = message_event.data;
72
73  var cmd = msg.cmd;
74  var result = msg.result;
75  var newDict = msg.dict;
76
77  // cmd will be empty when the module first loads and sends the contents of
78  // its dictionary.
79  //
80  // Note that cmd is a String object, not a primitive, so the comparison cmd
81  // !== '' will always fail.
82  if (cmd != '') {
83    common.logMessage(
84        'Function ' + cmd + ' returned ' + JSON.stringify(result));
85  }
86
87  var dictEl = document.getElementById('dict');
88  dictEl.textContent = JSON.stringify(newDict, null, '  ');
89}
90