live-parser.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. const liveParsers = document.querySelectorAll('.live-parser-container');
  17. function stringify(obj) {
  18. return JSON.stringify(obj, null, 2);
  19. }
  20. liveParsers.forEach(parserEl => {
  21. const scriptsContainer = parserEl.querySelector('.parser-scripts-container');
  22. const msg = parserEl.querySelector('.live-message');
  23. const select = parserEl.querySelector('select');
  24. const [queryText, jsonText] = parserEl.querySelectorAll('textarea');
  25. const parseQuery = () => {
  26. const parser = window[select.value];
  27. if (parser) {
  28. msg.innerHTML = 'Parser ready';
  29. const beforeCursor = queryText.value + ' ';
  30. const afterCursor = '';
  31. const debug = false;
  32. const parsedObj = parser.parseSql(beforeCursor, afterCursor, debug);
  33. jsonText.value = stringify(parsedObj);
  34. } else {
  35. msg.innerHTML = 'Parser not loaded!';
  36. }
  37. };
  38. const loadParser = () => {
  39. const parser = window[select.value];
  40. if (parser) {
  41. parseQuery();
  42. } else {
  43. const parserFile = `/js/gethue/parsers/${select.value}.js`;
  44. const parserScript = document.createElement('script');
  45. parserScript.setAttribute('type', 'text/javascript');
  46. parserScript.setAttribute('src', parserFile);
  47. parserScript.addEventListener('load', parseQuery);
  48. parserScript.addEventListener('error', () => (msg.innerHTML = 'Parser loading failed!'));
  49. msg.innerHTML = 'Loading parser...';
  50. scriptsContainer.appendChild(parserScript);
  51. }
  52. };
  53. loadParser();
  54. select.onchange = loadParser;
  55. queryText.onkeyup = parseQuery;
  56. });