events.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* @flow */
  2. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/
  3. const simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/
  4. // keyCode aliases
  5. const keyCodes: { [key: string]: number | Array<number> } = {
  6. esc: 27,
  7. tab: 9,
  8. enter: 13,
  9. space: 32,
  10. up: 38,
  11. left: 37,
  12. right: 39,
  13. down: 40,
  14. 'delete': [8, 46]
  15. }
  16. const modifierCode: { [key: string]: string } = {
  17. stop: '$event.stopPropagation();',
  18. prevent: '$event.preventDefault();',
  19. self: 'if($event.target !== $event.currentTarget)return;',
  20. ctrl: 'if(!$event.ctrlKey)return;',
  21. shift: 'if(!$event.shiftKey)return;',
  22. alt: 'if(!$event.altKey)return;',
  23. meta: 'if(!$event.metaKey)return;'
  24. }
  25. export function genHandlers (events: ASTElementHandlers, native?: boolean): string {
  26. let res = native ? 'nativeOn:{' : 'on:{'
  27. for (const name in events) {
  28. res += `"${name}":${genHandler(name, events[name])},`
  29. }
  30. return res.slice(0, -1) + '}'
  31. }
  32. function genHandler (
  33. name: string,
  34. handler: ASTElementHandler | Array<ASTElementHandler>
  35. ): string {
  36. if (!handler) {
  37. return 'function(){}'
  38. } else if (Array.isArray(handler)) {
  39. return `[${handler.map(handler => genHandler(name, handler)).join(',')}]`
  40. } else if (!handler.modifiers) {
  41. return fnExpRE.test(handler.value) || simplePathRE.test(handler.value)
  42. ? handler.value
  43. : `function($event){${handler.value}}`
  44. } else {
  45. let code = ''
  46. const keys = []
  47. for (const key in handler.modifiers) {
  48. if (modifierCode[key]) {
  49. code += modifierCode[key]
  50. } else {
  51. keys.push(key)
  52. }
  53. }
  54. if (keys.length) {
  55. code = genKeyFilter(keys) + code
  56. }
  57. const handlerCode = simplePathRE.test(handler.value)
  58. ? handler.value + '($event)'
  59. : handler.value
  60. return 'function($event){' + code + handlerCode + '}'
  61. }
  62. }
  63. function genKeyFilter (keys: Array<string>): string {
  64. return `if(${keys.map(genFilterCode).join('&&')})return;`
  65. }
  66. function genFilterCode (key: string): string {
  67. const keyVal = parseInt(key, 10)
  68. if (keyVal) {
  69. return `$event.keyCode!==${keyVal}`
  70. }
  71. const alias = keyCodes[key]
  72. return `_k($event.keyCode,${JSON.stringify(key)}${alias ? ',' + JSON.stringify(alias) : ''})`
  73. }