Advertisement
optimista

TagsArea 1 Whole

Sep 13th, 2018
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Fragment } from 'react'
  2. import Caret from './caret'
  3. import Tag from './tag'
  4.  
  5. class TagsArea extends React.Component {
  6.     constructor(props) {
  7.         super(props);
  8.        
  9.         this.state = {
  10.             cp: 0, // Caret Position
  11.             tags: [
  12.                 { id: 1, content: "Banana" },
  13.                 { id: 2, content: "Tea" },
  14.                 { id: 3, content: "Coffee" },
  15.                 { id: 4, content: "Mobile" }
  16.             ]
  17.         }  
  18.  
  19.         this.handleCaretKeyDown = this.handleCaretKeyDown.bind(this);
  20.     }
  21.  
  22.     handleCaretKeyDown(e) {
  23.         const { cp, tags } = this.state; let s;
  24.  
  25.         switch(e.key) {
  26.             case "ArrowLeft": if (cp > 0) s = { cp: cp - 1 }; break;
  27.             case "ArrowRight": if(cp < tags.length) s = { cp: cp + 1 }; break;
  28.             case "Backspace": if(cp > 0) s = { cp: cp - 1, tags: tags.filter((_, i) => i !== cp - 1) }; break;
  29.             case "Delete": if(cp < tags.length) s = { tags: tags.filter((_, i) => i !== cp) }; break;
  30.             case " ": console.log("Shift: ", e.shiftKey); break;
  31.             default: break;
  32.         }
  33.         // On arrow right has to save tag if not empty
  34.         // On arroe left has to save tag if not empty
  35.         // On click on tag - set cursor either left or right
  36.         // 1.
  37.         // On enter has to submit tags
  38.         // On space enters new tag
  39.         // 2. On enter ends the tag
  40.        
  41.         this.setState(s);
  42.     }
  43.  
  44.     render() {
  45.         const { cp, tags } = this.state,
  46.               caretProps = { onKeyDown: this.handleCaretKeyDown };
  47.  
  48.         return [...tags, null].map((n, i) =>
  49.             <Fragment key={i}>
  50.                 { cp === i && <Caret {...caretProps} /> }                
  51.                 { i < tags.length && <Tag node={n} /> }
  52.             </Fragment>
  53.         )
  54.     }
  55. }
  56.  
  57. export default TagsArea
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement