Welcome to mirror list, hosted at ThFree Co, Russian Federation.

aTableSortable.html « component « html « web - github.com/MHSanaei/3x-ui.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fdbc247ea5143bc8ad0f11e57f0e9fec24979079 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
{{define "component/sortableTableTrigger"}}
<a-icon type="drag" class="sortable-icon"
        role="button" tabindex="0"
        :aria-label="ariaLabel"
        @pointerdown="onPointerDown"
        @keydown="onKeyDown" />
{{end}}

{{define "component/aTableSortable"}}
<script>
  /**
   * Sortable a-table — drag-to-reorder rows using Pointer Events.
   *
   * Why a rewrite:
   * - Old impl set `draggable: true` on every row, which (a) broke text
   *   selection inside cells, (b) let HTML5 start a drag from anywhere on
   *   the row even when the state machine wasn't primed, producing
   *   "phantom drags" that didn't reorder anything.
   * - HTML5 drag has no touch support on most mobile browsers and no
   *   keyboard fallback at all.
   * - The drag-image hack cloned the entire table — slow on big lists.
   *
   * New design:
   * - Only the explicit drag handle initiates a drag, via Pointer Events
   *   (one API for mouse + touch + pen). Rows are not draggable.
   * - During drag, `data-source` is reordered live: the source row visually
   *   slides into the target slot and other rows shift around it. The live
   *   reorder IS the visual feedback — no separate floating preview.
   * - On commit, emits `onsort(sourceIndex, targetIndex)` — same event name
   *   and signature as before, so existing call sites stay unchanged.
   * - Keyboard support: the handle is focusable; ArrowUp / ArrowDown move
   *   the row by one; Escape cancels a pointer-drag in progress.
   */
  const ROW_CLASS = 'sortable-row';

  Vue.component('a-table-sortable', {
    data() {
      return {
        // null when idle. While dragging:
        //   { sourceIndex, targetIndex, pointerId, sourceKey }
        drag: null,
      };
    },
    props: {
      'data-source': { type: undefined, required: false },
      'customRow':   { type: undefined, required: false },
      'row-key':     { type: undefined, required: false },
    },
    inheritAttrs: false,
    provide() {
      const sortable = {};
      // Methods exposed to the trigger child via inject. Defined as getters
      // so `this` binds to the component instance, not the plain object.
      Object.defineProperty(sortable, 'startDrag', {
        enumerable: true,
        get: () => this.startDrag,
      });
      Object.defineProperty(sortable, 'moveByKeyboard', {
        enumerable: true,
        get: () => this.moveByKeyboard,
      });
      return { sortable };
    },
    beforeDestroy() {
      this.detachPointerListeners();
    },
    methods: {
      isDragging() { return this.drag !== null; },
      // Resolve the row key for a record. Used to identify the source row
      // even after data-source is reordered live during drag.
      keyOf(record, fallback) {
        const rk = this.rowKey;
        if (typeof rk === 'function') return rk(record);
        if (typeof rk === 'string')   return record && record[rk];
        return fallback;
      },
      startDrag(e, sourceIndex) {
        // Primary button only (mouse left / first touch).
        if (e.button != null && e.button !== 0) return;
        e.preventDefault();
        const record = this.dataSource && this.dataSource[sourceIndex];
        this.drag = {
          sourceIndex,
          targetIndex: sourceIndex,
          pointerId: e.pointerId,
          sourceKey: this.keyOf(record, sourceIndex),
        };
        // Capture the pointer so move/up keep firing even if the cursor leaves
        // the icon. Try/catch because some older browsers throw on capture.
        if (e.target && typeof e.target.setPointerCapture === 'function' && e.pointerId != null) {
          try { e.target.setPointerCapture(e.pointerId); } catch (_) {}
        }
        this.attachPointerListeners();
      },
      attachPointerListeners() {
        this._onMove   = (ev) => this.onPointerMove(ev);
        this._onUp     = (ev) => this.onPointerUp(ev);
        this._onCancel = (ev) => this.cancelDrag(ev);
        document.addEventListener('pointermove',   this._onMove,   true);
        document.addEventListener('pointerup',     this._onUp,     true);
        document.addEventListener('pointercancel', this._onCancel, true);
        document.addEventListener('keydown',       this._onCancel, true);
      },
      detachPointerListeners() {
        if (!this._onMove) return;
        document.removeEventListener('pointermove',   this._onMove,   true);
        document.removeEventListener('pointerup',     this._onUp,     true);
        document.removeEventListener('pointercancel', this._onCancel, true);
        document.removeEventListener('keydown',       this._onCancel, true);
        this._onMove = this._onUp = this._onCancel = null;
      },
      onPointerMove(e) {
        if (!this.drag) return;
        if (this.drag.pointerId != null && e.pointerId !== this.drag.pointerId) return;
        // Hit-test: find which row the pointer Y is inside (or closest to).
        const rows = this.$el.querySelectorAll('tr.' + ROW_CLASS);
        if (!rows.length) return;
        const y = e.clientY;
        const firstRect = rows[0].getBoundingClientRect();
        const lastRect  = rows[rows.length - 1].getBoundingClientRect();
        let target = this.drag.targetIndex;
        if (y < firstRect.top) {
          target = 0;
        } else if (y > lastRect.bottom) {
          target = rows.length - 1;
        } else {
          for (let i = 0; i < rows.length; i++) {
            const rect = rows[i].getBoundingClientRect();
            if (y >= rect.top && y <= rect.bottom) {
              target = i;
              break;
            }
          }
        }
        if (target !== this.drag.targetIndex) {
          this.drag = Object.assign({}, this.drag, { targetIndex: target });
        }
      },
      onPointerUp(e) {
        if (!this.drag) return;
        if (this.drag.pointerId != null && e.pointerId !== this.drag.pointerId) return;
        this.commitDrag();
      },
      commitDrag() {
        const d = this.drag;
        this.detachPointerListeners();
        this.drag = null;
        if (d && d.sourceIndex !== d.targetIndex) {
          this.$emit('onsort', d.sourceIndex, d.targetIndex);
        }
      },
      cancelDrag(e) {
        // Triggered by pointercancel and keydown handlers. For keydown, only
        // act on Escape; otherwise let the event flow to other listeners.
        if (e && e.type === 'keydown' && e.key !== 'Escape') return;
        this.detachPointerListeners();
        this.drag = null;
      },
      // Keyboard reorder: commit immediately by emitting onsort. No "preview"
      // state needed since the move is one row up or down.
      moveByKeyboard(direction, sourceIndex) {
        const target = sourceIndex + direction;
        if (target < 0 || target >= (this.dataSource || []).length) return;
        this.$emit('onsort', sourceIndex, target);
      },
      customRowRender(record, index) {
        const parent = (typeof this.customRow === 'function')
          ? (this.customRow(record, index) || {})
          : {};
        const d = this.drag;
        const isSource = d && this.keyOf(record, index) === d.sourceKey;
        return Object.assign({}, parent, {
          // CRITICAL: no `draggable: true`. Drag is initiated only by the
          // handle icon. Leaves text-selection on cells working normally.
          attrs: Object.assign({}, parent.attrs || {}),
          class: Object.assign({}, parent.class || {}, {
            [ROW_CLASS]: true,
            'sortable-source-row': !!isSource,
          }),
        });
      },
    },
    computed: {
      // Render-data: dataSource with the source row spliced into targetIndex.
      // When idle or when target equals source, returns the original list
      // unchanged so Ant Design's table treats this as a stable reference.
      records() {
        const d = this.drag;
        if (!d || d.sourceIndex === d.targetIndex) return this.dataSource;
        const list = (this.dataSource || []).slice();
        const [item] = list.splice(d.sourceIndex, 1);
        list.splice(d.targetIndex, 0, item);
        return list;
      },
    },
    render(h) {
      return h('a-table', {
        class: { 'sortable-table': true, 'sortable-table-dragging': this.isDragging() },
        props: Object.assign({}, this.$attrs, {
          'data-source': this.records,
          'row-key': this.rowKey,
          customRow: (record, index) => this.customRowRender(record, index),
          locale: {
            filterConfirm: `{{ i18n "confirm" }}`,
            filterReset:   `{{ i18n "reset" }}`,
            emptyText:     `{{ i18n "noData" }}`,
          },
        }),
        on: this.$listeners,
        scopedSlots: this.$scopedSlots,
      }, this.$slots.default);
    },
  });

  Vue.component('a-table-sort-trigger', {
    template: `{{template "component/sortableTableTrigger" .}}`,
    props: {
      'item-index': { type: undefined, required: false },
    },
    inject: ['sortable'],
    computed: {
      ariaLabel() {
        // Localised label is overkill for an internal a11y string; English is
        // fine here and matches screen-reader expectations across locales.
        return 'Drag to reorder row ' + (((this.itemIndex == null ? 0 : this.itemIndex) + 1));
      },
    },
    methods: {
      onPointerDown(e) {
        if (this.sortable && this.sortable.startDrag) {
          this.sortable.startDrag(e, this.itemIndex);
        }
      },
      onKeyDown(e) {
        if (!this.sortable || !this.sortable.moveByKeyboard) return;
        if (e.key === 'ArrowUp') {
          e.preventDefault();
          this.sortable.moveByKeyboard(-1, this.itemIndex);
        } else if (e.key === 'ArrowDown') {
          e.preventDefault();
          this.sortable.moveByKeyboard(+1, this.itemIndex);
        }
      },
    },
  });
</script>

<style>
  /* Drag handle — focusable, keyboard-accessible, touch-friendly hit area.
     `touch-action: none` is critical: it tells the browser not to interpret
     touch on the icon as a scroll/zoom gesture, so pointermove fires for
     drag-tracking. Without it, mobile browsers eat the pointer events. */
  .sortable-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: grab;
    padding: 6px;
    border-radius: 6px;
    color: rgba(255, 255, 255, 0.5);
    transition: background-color 0.15s ease, color 0.15s ease;
    user-select: none;
    touch-action: none;
  }
  .sortable-icon:hover {
    color: rgba(255, 255, 255, 0.85);
    background: rgba(255, 255, 255, 0.06);
  }
  .sortable-icon:active { cursor: grabbing; }
  .sortable-icon:focus-visible {
    outline: 2px solid #008771;
    outline-offset: 2px;
  }

  .light .sortable-icon { color: rgba(0, 0, 0, 0.45); }
  .light .sortable-icon:hover {
    color: rgba(0, 0, 0, 0.85);
    background: rgba(0, 0, 0, 0.05);
  }

  /* While dragging: the source row gets a soft green wash so the user can
     track which row is being moved. Other rows transition smoothly as the
     data-source is reordered. */
  .sortable-table-dragging .sortable-source-row > td {
    background: rgba(0, 135, 113, 0.10) !important;
    transition: background-color 0.18s ease;
  }
  .sortable-table-dragging .sortable-source-row .routing-index,
  .sortable-table-dragging .sortable-source-row .outbound-index {
    opacity: 0.45;
  }
  .sortable-table-dragging .sortable-row > td {
    transition: background-color 0.18s ease;
  }
  /* Disable text selection across the whole table while a drag is in
     progress — selection during drag is never useful and looks broken. */
  .sortable-table-dragging,
  .sortable-table-dragging * {
    user-select: none;
  }
</style>
{{end}}