shortcut-keys.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. (() => {
  2. /**
  3. * 统一管理素材管理的键盘快捷键(复制自 client/js/disk/shortcut-keys.js)
  4. */
  5. class ResourceManagerShortcutKeys {
  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. // 确保 iframe 可以接收键盘事件
  16. window.focus();
  17. console.log('[ShortcutKeys] 快捷键模块已初始化');
  18. }
  19. destroy() {
  20. document.removeEventListener('keydown', this.handleKeyDown);
  21. }
  22. handleKeyDown(e) {
  23. if (this.shouldIgnoreTarget(e.target)) {
  24. return;
  25. }
  26. // Delete
  27. if (e.key === 'Delete') {
  28. console.log('[ShortcutKeys] Delete 键被按下');
  29. console.log('[ShortcutKeys] this.selection:', this.selection);
  30. console.log('[ShortcutKeys] hasSelection:', this.selection ? this.selection.hasSelection() : 'N/A');
  31. if (this.selection && this.selection.hasSelection()) {
  32. console.log('[ShortcutKeys] 有选中项,调用 onDelete');
  33. e.preventDefault();
  34. this.onDelete && this.onDelete();
  35. } else {
  36. console.log('[ShortcutKeys] 没有选中项或 selection 为空');
  37. }
  38. return;
  39. }
  40. // 重命名
  41. if (e.key === 'F2') {
  42. if (this.selection && this.selection.getSelectedCount() === 1) {
  43. e.preventDefault();
  44. this.onRename && this.onRename();
  45. }
  46. return;
  47. }
  48. if (!e.ctrlKey) {
  49. return;
  50. }
  51. const key = e.key.toLowerCase();
  52. switch (key) {
  53. case 'a':
  54. if (this.selection) {
  55. e.preventDefault();
  56. this.selection.selectAll();
  57. }
  58. break;
  59. case 'c':
  60. if (this.selection && this.selection.hasSelection() && this.onCopy) {
  61. e.preventDefault();
  62. this.onCopy();
  63. }
  64. break;
  65. case 'x':
  66. if (this.selection && this.selection.hasSelection() && this.onCut) {
  67. e.preventDefault();
  68. this.onCut();
  69. }
  70. break;
  71. case 'v':
  72. if (this.onPaste) {
  73. e.preventDefault();
  74. Promise.resolve(this.onPaste()).catch((error) => {
  75. console.error('粘贴失败:', error);
  76. });
  77. }
  78. break;
  79. default:
  80. break;
  81. }
  82. }
  83. shouldIgnoreTarget(target) {
  84. if (!target) return false;
  85. const tag = target.tagName;
  86. if (!tag) return false;
  87. if (target.isContentEditable) return true;
  88. return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
  89. }
  90. }
  91. window.ResourceManagerShortcutKeys = ResourceManagerShortcutKeys;
  92. })();