shortcut-keys.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. (() => {
  2. /**
  3. * 统一管理网盘的键盘快捷键
  4. */
  5. class ShortcutKeys {
  6. constructor(options = {}) {
  7. this.selection = options.selection || null;
  8. this.onDelete = options.onDelete || null;
  9. this.onRename = options.onRename || null;
  10. this.onCopy = options.onCopy || null;
  11. this.onCut = options.onCut || null;
  12. this.onPaste = options.onPaste || null;
  13. this.handleKeyDown = this.handleKeyDown.bind(this);
  14. document.addEventListener('keydown', this.handleKeyDown);
  15. }
  16. destroy() {
  17. document.removeEventListener('keydown', this.handleKeyDown);
  18. }
  19. handleKeyDown(e) {
  20. if (this.shouldIgnoreTarget(e.target)) {
  21. return;
  22. }
  23. // Delete
  24. if (e.key === 'Delete') {
  25. if (this.selection && this.selection.hasSelection()) {
  26. e.preventDefault();
  27. this.onDelete && this.onDelete();
  28. }
  29. return;
  30. }
  31. // 重命名
  32. if (e.key === 'F2') {
  33. if (this.selection && this.selection.getSelectedCount() === 1) {
  34. e.preventDefault();
  35. this.onRename && this.onRename();
  36. }
  37. return;
  38. }
  39. if (!e.ctrlKey) {
  40. return;
  41. }
  42. const key = e.key.toLowerCase();
  43. switch (key) {
  44. case 'a':
  45. if (this.selection) {
  46. e.preventDefault();
  47. this.selection.selectAll();
  48. }
  49. break;
  50. case 'c':
  51. if (this.selection && this.selection.hasSelection() && this.onCopy) {
  52. e.preventDefault();
  53. this.onCopy();
  54. }
  55. break;
  56. case 'x':
  57. if (this.selection && this.selection.hasSelection() && this.onCut) {
  58. e.preventDefault();
  59. this.onCut();
  60. }
  61. break;
  62. case 'v':
  63. if (this.onPaste) {
  64. e.preventDefault();
  65. Promise.resolve(this.onPaste()).catch((error) => {
  66. console.error('粘贴失败:', error);
  67. });
  68. }
  69. break;
  70. default:
  71. break;
  72. }
  73. }
  74. shouldIgnoreTarget(target) {
  75. if (!target) return false;
  76. const tag = target.tagName;
  77. if (!tag) return false;
  78. if (target.isContentEditable) return true;
  79. return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
  80. }
  81. }
  82. window.ShortcutKeys = ShortcutKeys;
  83. })();