query_field.tsx 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import PluginPrism from './slate-plugins/prism';
  2. // import PluginPrism from 'slate-prism';
  3. // import Prism from 'prismjs';
  4. import BracesPlugin from 'app/features/explore/slate-plugins/braces';
  5. import ClearPlugin from 'app/features/explore/slate-plugins/clear';
  6. // Custom plugins (new line on Enter and run on Shift+Enter)
  7. import NewlinePlugin from './slate-plugins/newline';
  8. import RunnerPlugin from './slate-plugins/runner';
  9. import Typeahead from './typeahead';
  10. import { Block, Document, Text, Value } from 'slate';
  11. import { Editor } from 'slate-react';
  12. import Plain from 'slate-plain-serializer';
  13. import ReactDOM from 'react-dom';
  14. import React from 'react';
  15. import _ from 'lodash';
  16. function flattenSuggestions(s) {
  17. return s ? s.reduce((acc, g) => acc.concat(g.items), []) : [];
  18. }
  19. export const makeFragment = text => {
  20. const lines = text.split('\n').map(line =>
  21. Block.create({
  22. type: 'paragraph',
  23. nodes: [Text.create(line)],
  24. })
  25. );
  26. const fragment = Document.create({
  27. nodes: lines,
  28. });
  29. return fragment;
  30. };
  31. export const getInitialValue = query => Value.create({ document: makeFragment(query) });
  32. class Portal extends React.Component<any, any> {
  33. node: any;
  34. constructor(props) {
  35. super(props);
  36. const { index = 0, prefix = 'query' } = props;
  37. this.node = document.createElement('div');
  38. this.node.classList.add(`slate-typeahead`, `slate-typeahead-${prefix}-${index}`);
  39. document.body.appendChild(this.node);
  40. }
  41. componentWillUnmount() {
  42. document.body.removeChild(this.node);
  43. }
  44. render() {
  45. return ReactDOM.createPortal(this.props.children, this.node);
  46. }
  47. }
  48. class QueryField extends React.Component<any, any> {
  49. menuEl: any;
  50. plugins: any;
  51. resetTimer: any;
  52. constructor(props, context) {
  53. super(props, context);
  54. const { prismDefinition = {}, prismLanguage = 'kusto' } = props;
  55. this.plugins = [
  56. BracesPlugin(),
  57. ClearPlugin(),
  58. RunnerPlugin({ handler: props.onPressEnter }),
  59. NewlinePlugin(),
  60. PluginPrism({ definition: prismDefinition, language: prismLanguage }),
  61. ];
  62. this.state = {
  63. labelKeys: {},
  64. labelValues: {},
  65. suggestions: [],
  66. typeaheadIndex: 0,
  67. typeaheadPrefix: '',
  68. value: getInitialValue(props.initialQuery || ''),
  69. };
  70. }
  71. componentDidMount() {
  72. this.updateMenu();
  73. }
  74. componentWillUnmount() {
  75. clearTimeout(this.resetTimer);
  76. }
  77. componentDidUpdate() {
  78. this.updateMenu();
  79. }
  80. onChange = ({ value }) => {
  81. const changed = value.document !== this.state.value.document;
  82. this.setState({ value }, () => {
  83. if (changed) {
  84. this.onChangeQuery();
  85. }
  86. });
  87. window.requestAnimationFrame(this.onTypeahead);
  88. }
  89. request = (url?) => {
  90. if (this.props.request) {
  91. return this.props.request(url);
  92. }
  93. return fetch(url);
  94. }
  95. onChangeQuery = () => {
  96. // Send text change to parent
  97. const { onQueryChange } = this.props;
  98. if (onQueryChange) {
  99. onQueryChange(Plain.serialize(this.state.value));
  100. }
  101. }
  102. onKeyDown = (event, change) => {
  103. const { typeaheadIndex, suggestions } = this.state;
  104. switch (event.key) {
  105. case 'Escape': {
  106. if (this.menuEl) {
  107. event.preventDefault();
  108. event.stopPropagation();
  109. this.resetTypeahead();
  110. return true;
  111. }
  112. break;
  113. }
  114. case ' ': {
  115. if (event.ctrlKey) {
  116. event.preventDefault();
  117. this.onTypeahead();
  118. return true;
  119. }
  120. break;
  121. }
  122. case 'Tab': {
  123. if (this.menuEl) {
  124. // Dont blur input
  125. event.preventDefault();
  126. if (!suggestions || suggestions.length === 0) {
  127. return undefined;
  128. }
  129. // Get the currently selected suggestion
  130. const flattenedSuggestions = flattenSuggestions(suggestions);
  131. const selected = Math.abs(typeaheadIndex);
  132. const selectedIndex = selected % flattenedSuggestions.length || 0;
  133. const suggestion = flattenedSuggestions[selectedIndex];
  134. this.applyTypeahead(change, suggestion);
  135. return true;
  136. }
  137. break;
  138. }
  139. case 'ArrowDown': {
  140. if (this.menuEl) {
  141. // Select next suggestion
  142. event.preventDefault();
  143. this.setState({ typeaheadIndex: typeaheadIndex + 1 });
  144. }
  145. break;
  146. }
  147. case 'ArrowUp': {
  148. if (this.menuEl) {
  149. // Select previous suggestion
  150. event.preventDefault();
  151. this.setState({ typeaheadIndex: Math.max(0, typeaheadIndex - 1) });
  152. }
  153. break;
  154. }
  155. default: {
  156. // console.log('default key', event.key, event.which, event.charCode, event.locale, data.key);
  157. break;
  158. }
  159. }
  160. return undefined;
  161. }
  162. onTypeahead = (change?, item?) => {
  163. return change || this.state.value.change();
  164. }
  165. applyTypeahead(change?, suggestion?): { value: object } { return { value: {} }; }
  166. resetTypeahead = () => {
  167. this.setState({
  168. suggestions: [],
  169. typeaheadIndex: 0,
  170. typeaheadPrefix: '',
  171. typeaheadContext: null,
  172. });
  173. }
  174. handleBlur = () => {
  175. const { onBlur } = this.props;
  176. // If we dont wait here, menu clicks wont work because the menu
  177. // will be gone.
  178. this.resetTimer = setTimeout(this.resetTypeahead, 100);
  179. if (onBlur) {
  180. onBlur();
  181. }
  182. }
  183. handleFocus = () => {
  184. const { onFocus } = this.props;
  185. if (onFocus) {
  186. onFocus();
  187. }
  188. }
  189. onClickItem = item => {
  190. const { suggestions } = this.state;
  191. if (!suggestions || suggestions.length === 0) {
  192. return;
  193. }
  194. // Get the currently selected suggestion
  195. const flattenedSuggestions = flattenSuggestions(suggestions);
  196. const suggestion = _.find(
  197. flattenedSuggestions,
  198. suggestion => suggestion.display === item || suggestion.text === item
  199. );
  200. // Manually triggering change
  201. const change = this.applyTypeahead(this.state.value.change(), suggestion);
  202. this.onChange(change);
  203. }
  204. updateMenu = () => {
  205. const { suggestions } = this.state;
  206. const menu = this.menuEl;
  207. const selection = window.getSelection();
  208. const node = selection.anchorNode;
  209. // No menu, nothing to do
  210. if (!menu) {
  211. return;
  212. }
  213. // No suggestions or blur, remove menu
  214. const hasSuggesstions = suggestions && suggestions.length > 0;
  215. if (!hasSuggesstions) {
  216. menu.removeAttribute('style');
  217. return;
  218. }
  219. // Align menu overlay to editor node
  220. if (node && node.parentElement) {
  221. // Read from DOM
  222. const rect = node.parentElement.getBoundingClientRect();
  223. const scrollX = window.scrollX;
  224. const scrollY = window.scrollY;
  225. // Write DOM
  226. requestAnimationFrame(() => {
  227. menu.style.opacity = 1;
  228. menu.style.top = `${rect.top + scrollY + rect.height + 4}px`;
  229. menu.style.left = `${rect.left + scrollX - 2}px`;
  230. });
  231. }
  232. }
  233. menuRef = el => {
  234. this.menuEl = el;
  235. }
  236. renderMenu = () => {
  237. const { portalPrefix } = this.props;
  238. const { suggestions } = this.state;
  239. const hasSuggesstions = suggestions && suggestions.length > 0;
  240. if (!hasSuggesstions) {
  241. return null;
  242. }
  243. // Guard selectedIndex to be within the length of the suggestions
  244. let selectedIndex = Math.max(this.state.typeaheadIndex, 0);
  245. const flattenedSuggestions = flattenSuggestions(suggestions);
  246. selectedIndex = selectedIndex % flattenedSuggestions.length || 0;
  247. const selectedKeys = (flattenedSuggestions.length > 0 ? [flattenedSuggestions[selectedIndex]] : []).map(
  248. i => (typeof i === 'object' ? i.text : i)
  249. );
  250. // Create typeahead in DOM root so we can later position it absolutely
  251. return (
  252. <Portal prefix={portalPrefix}>
  253. <Typeahead
  254. menuRef={this.menuRef}
  255. selectedItems={selectedKeys}
  256. onClickItem={this.onClickItem}
  257. groupedItems={suggestions}
  258. />
  259. </Portal>
  260. );
  261. }
  262. render() {
  263. return (
  264. <div className="slate-query-field">
  265. {this.renderMenu()}
  266. <Editor
  267. autoCorrect={false}
  268. onBlur={this.handleBlur}
  269. onKeyDown={this.onKeyDown}
  270. onChange={this.onChange}
  271. onFocus={this.handleFocus}
  272. placeholder={this.props.placeholder}
  273. plugins={this.plugins}
  274. spellCheck={false}
  275. value={this.state.value}
  276. />
  277. </div>
  278. );
  279. }
  280. }
  281. export default QueryField;