live-parser.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. if (parser.parseSql) {
  33. const parsedObj = parser.parseSql(beforeCursor, afterCursor, debug);
  34. jsonText.value = stringify(parsedObj);
  35. } else if (parser.parseSyntax) {
  36. const parsedObj = parser.parseSyntax(beforeCursor.trim(), afterCursor);
  37. jsonText.value = stringify(parsedObj);
  38. } else {
  39. jsonText.value = '';
  40. msg.innerHTML = 'Invalid parser!';
  41. }
  42. } else {
  43. msg.innerHTML = 'Parser not loaded!';
  44. }
  45. };
  46. const loadParser = () => {
  47. const parser = window[select.value];
  48. if (parser) {
  49. parseQuery();
  50. } else {
  51. const parserFile = `/js/gethue/parsers/${select.value}.js`;
  52. const parserScript = document.createElement('script');
  53. parserScript.setAttribute('type', 'text/javascript');
  54. parserScript.setAttribute('src', parserFile);
  55. parserScript.addEventListener('load', parseQuery);
  56. parserScript.addEventListener('error', () => (msg.innerHTML = 'Parser loading failed!'));
  57. msg.innerHTML = 'Loading parser...';
  58. scriptsContainer.appendChild(parserScript);
  59. }
  60. };
  61. loadParser();
  62. select.onchange = loadParser;
  63. queryText.onkeyup = parseQuery;
  64. });