@dile/ui 3.20.1 → 3.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,290 @@
1
+ import { LitElement, html, css } from 'lit';
2
+
3
+ /**
4
+ * # dile-sortable
5
+ *
6
+ * Container that lets the user reorder its children dragging them with the mouse, a finger or
7
+ * the keyboard.
8
+ *
9
+ * The component does NOT move the DOM. It only previews the movement with transforms and, on
10
+ * drop, emits `dile-sortable-change` with the `from` and `to` indexes. The consumer reorders
11
+ * its data and renders again (in Lit, with `repeat()` and a stable key so the children keep
12
+ * their state). The `moveItem(array, from, to)` helper returns the reordered copy.
13
+ *
14
+ * ## Usage
15
+ *
16
+ * ```html
17
+ * <dile-sortable @dile-sortable-change=${this.reorder}>
18
+ * ${repeat(items, (i) => i.id, (i) => html`<my-item .item=${i}></my-item>`)}
19
+ * </dile-sortable>
20
+ * ```
21
+ *
22
+ * Each child must contain a handle marked with `data-sortable-handle`. It can live inside the
23
+ * child's shadow DOM: it is found with `composedPath()`. The handle should have
24
+ * `touch-action: none` (so the gesture doesn't scroll on mobile) and `tabindex="0"` (to move
25
+ * it with the keyboard: Alt+↑ / Alt+↓).
26
+ *
27
+ * While dragging, the child gets the `data-sortable-dragging` attribute, useful to style it
28
+ * from the child itself with `:host([data-sortable-dragging])`.
29
+ *
30
+ * ## Properties
31
+ * - `disabled`: disables reordering.
32
+ *
33
+ * ## Events
34
+ * - `dile-sortable-change`: `detail: { from, to }`.
35
+ *
36
+ * ## CSS custom properties
37
+ * - `--dile-sortable-transition-duration` (150ms)
38
+ * - `--dile-sortable-dragging-shadow` (0 6px 16px rgba(0, 0, 0, 0.18))
39
+ * - `--dile-sortable-dragging-background-color` (unset: the background doesn't change)
40
+ */
41
+
42
+ const AUTOSCROLL_EDGE = 48;
43
+ const AUTOSCROLL_SPEED = 12;
44
+
45
+ export class DileSortable extends LitElement {
46
+ static styles = css`
47
+ :host {
48
+ display: block;
49
+ position: relative;
50
+ }
51
+ :host([dragging]) {
52
+ cursor: grabbing;
53
+ user-select: none;
54
+ -webkit-user-select: none;
55
+ }
56
+ `;
57
+
58
+ static properties = {
59
+ disabled: { type: Boolean },
60
+ dragging: { type: Boolean, reflect: true },
61
+ };
62
+
63
+ constructor() {
64
+ super();
65
+ this.disabled = false;
66
+ this.dragging = false;
67
+ this._drag = null;
68
+ this._onPointerDown = this._onPointerDown.bind(this);
69
+ this._onPointerMove = this._onPointerMove.bind(this);
70
+ this._onPointerUp = this._onPointerUp.bind(this);
71
+ this._onKeyDown = this._onKeyDown.bind(this);
72
+ this._autoScroll = this._autoScroll.bind(this);
73
+ }
74
+
75
+ connectedCallback() {
76
+ super.connectedCallback();
77
+ this.addEventListener('pointerdown', this._onPointerDown);
78
+ this.addEventListener('keydown', this._onKeyDown);
79
+ }
80
+
81
+ disconnectedCallback() {
82
+ super.disconnectedCallback();
83
+ this.removeEventListener('pointerdown', this._onPointerDown);
84
+ this.removeEventListener('keydown', this._onKeyDown);
85
+ this._finishDrag(false);
86
+ }
87
+
88
+ render() {
89
+ return html`<slot></slot>`;
90
+ }
91
+
92
+ get items() {
93
+ return Array.from(this.children);
94
+ }
95
+
96
+ /** Returns the handle and the direct child involved in an event, if any. */
97
+ _resolveTarget(e) {
98
+ const path = e.composedPath();
99
+ const handle = path.find((node) => node instanceof Element && node.hasAttribute('data-sortable-handle'));
100
+ if (!handle) return null;
101
+ const item = path.find((node) => node instanceof Element && node.parentElement === this);
102
+ if (!item) return null;
103
+ return { handle, item };
104
+ }
105
+
106
+ _onPointerDown(e) {
107
+ if (this.disabled || this._drag || !e.isPrimary || e.button !== 0) return;
108
+ const target = this._resolveTarget(e);
109
+ if (!target) return;
110
+ e.preventDefault();
111
+
112
+ const items = this.items;
113
+ const from = items.indexOf(target.item);
114
+ const rects = items.map((item) => item.getBoundingClientRect());
115
+ const draggedRect = rects[from];
116
+ const gap =
117
+ items.length > 1
118
+ ? Math.max(
119
+ 0,
120
+ from > 0 ? draggedRect.top - rects[from - 1].bottom : rects[from + 1].top - draggedRect.bottom,
121
+ )
122
+ : 0;
123
+
124
+ this._drag = {
125
+ pointerId: e.pointerId,
126
+ handle: target.handle,
127
+ item: target.item,
128
+ items,
129
+ rects,
130
+ from,
131
+ to: from,
132
+ startY: e.clientY,
133
+ startScrollY: window.scrollY,
134
+ lastClientY: e.clientY,
135
+ shift: draggedRect.height + gap,
136
+ rafId: null,
137
+ };
138
+
139
+ this.setPointerCapture(e.pointerId);
140
+ this.addEventListener('pointermove', this._onPointerMove);
141
+ this.addEventListener('pointerup', this._onPointerUp);
142
+ this.addEventListener('pointercancel', this._onPointerUp);
143
+
144
+ this.dragging = true;
145
+ const style = getComputedStyle(this);
146
+ const duration = this._transitionDuration(style);
147
+ target.item.setAttribute('data-sortable-dragging', '');
148
+ Object.assign(target.item.style, {
149
+ position: 'relative',
150
+ zIndex: '2',
151
+ transition: 'none',
152
+ boxShadow:
153
+ style.getPropertyValue('--dile-sortable-dragging-shadow').trim() || '0 6px 16px rgba(0, 0, 0, 0.18)',
154
+ });
155
+ const background = style.getPropertyValue('--dile-sortable-dragging-background-color').trim();
156
+ if (background) {
157
+ target.item.style.backgroundColor = background;
158
+ }
159
+ items.forEach((item) => {
160
+ if (item !== target.item) {
161
+ item.style.transition = `transform ${duration}`;
162
+ }
163
+ });
164
+ }
165
+
166
+ _transitionDuration(style = getComputedStyle(this)) {
167
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
168
+ return '0ms';
169
+ }
170
+ return style.getPropertyValue('--dile-sortable-transition-duration').trim() || '150ms';
171
+ }
172
+
173
+ _onPointerMove(e) {
174
+ if (!this._drag || e.pointerId !== this._drag.pointerId) return;
175
+ this._drag.lastClientY = e.clientY;
176
+ this._updatePositions();
177
+ this._scheduleAutoScroll();
178
+ }
179
+
180
+ _updatePositions() {
181
+ const drag = this._drag;
182
+ const dy = drag.lastClientY - drag.startY + (window.scrollY - drag.startScrollY);
183
+ drag.item.style.transform = `translateY(${dy}px)`;
184
+
185
+ const draggedRect = drag.rects[drag.from];
186
+ const center = draggedRect.top + draggedRect.height / 2 + dy;
187
+ // The target position is the number of siblings whose center is above the dragged one.
188
+ const to = drag.rects.filter(
189
+ (rect, index) => index !== drag.from && rect.top + rect.height / 2 < center,
190
+ ).length;
191
+ drag.to = to;
192
+
193
+ drag.items.forEach((item, index) => {
194
+ if (index === drag.from) return;
195
+ let offset = 0;
196
+ if (drag.from < to && index > drag.from && index <= to) offset = -drag.shift;
197
+ if (drag.from > to && index < drag.from && index >= to) offset = drag.shift;
198
+ item.style.transform = offset ? `translateY(${offset}px)` : '';
199
+ });
200
+ }
201
+
202
+ _scheduleAutoScroll() {
203
+ if (this._drag && this._drag.rafId === null) {
204
+ this._drag.rafId = requestAnimationFrame(this._autoScroll);
205
+ }
206
+ }
207
+
208
+ _autoScroll() {
209
+ const drag = this._drag;
210
+ if (!drag) return;
211
+ drag.rafId = null;
212
+ const y = drag.lastClientY;
213
+ let delta = 0;
214
+ if (y < AUTOSCROLL_EDGE) delta = -AUTOSCROLL_SPEED;
215
+ else if (y > window.innerHeight - AUTOSCROLL_EDGE) delta = AUTOSCROLL_SPEED;
216
+ if (!delta) return;
217
+ const before = window.scrollY;
218
+ window.scrollBy(0, delta);
219
+ if (window.scrollY !== before) {
220
+ this._updatePositions();
221
+ this._scheduleAutoScroll();
222
+ }
223
+ }
224
+
225
+ _onPointerUp(e) {
226
+ if (!this._drag || e.pointerId !== this._drag.pointerId) return;
227
+ this._finishDrag(e.type === 'pointerup');
228
+ }
229
+
230
+ _finishDrag(commit) {
231
+ const drag = this._drag;
232
+ if (!drag) return;
233
+ this._drag = null;
234
+ if (drag.rafId !== null) cancelAnimationFrame(drag.rafId);
235
+ if (this.hasPointerCapture?.(drag.pointerId)) {
236
+ this.releasePointerCapture(drag.pointerId);
237
+ }
238
+ this.removeEventListener('pointermove', this._onPointerMove);
239
+ this.removeEventListener('pointerup', this._onPointerUp);
240
+ this.removeEventListener('pointercancel', this._onPointerUp);
241
+ this.dragging = false;
242
+
243
+ drag.item.removeAttribute('data-sortable-dragging');
244
+ drag.items.forEach((item) => {
245
+ item.style.transform = '';
246
+ item.style.transition = '';
247
+ item.style.position = '';
248
+ item.style.zIndex = '';
249
+ item.style.boxShadow = '';
250
+ item.style.backgroundColor = '';
251
+ });
252
+
253
+ if (commit && drag.to !== drag.from) {
254
+ this._emitChange(drag.from, drag.to);
255
+ }
256
+ }
257
+
258
+ _onKeyDown(e) {
259
+ if (this.disabled || this._drag || !e.altKey) return;
260
+ if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
261
+ const target = this._resolveTarget(e);
262
+ if (!target) return;
263
+ const items = this.items;
264
+ const from = items.indexOf(target.item);
265
+ const to = e.key === 'ArrowUp' ? from - 1 : from + 1;
266
+ e.preventDefault();
267
+ if (to < 0 || to >= items.length) return;
268
+ this._emitChange(from, to);
269
+ // The parent renders again and moves the child: give the focus back to the handle.
270
+ requestAnimationFrame(() => target.handle.focus());
271
+ }
272
+
273
+ _emitChange(from, to) {
274
+ this.dispatchEvent(
275
+ new CustomEvent('dile-sortable-change', {
276
+ bubbles: true,
277
+ composed: true,
278
+ detail: { from, to },
279
+ }),
280
+ );
281
+ }
282
+ }
283
+
284
+ /** Returns a copy of the array with the `from` element moved to the `to` position. */
285
+ export function moveItem(array, from, to) {
286
+ const result = [...array];
287
+ const [moved] = result.splice(from, 1);
288
+ result.splice(to, 0, moved);
289
+ return result;
290
+ }
@@ -10,6 +10,10 @@ export class DileTab extends DileSelectableItem(LitElement) {
10
10
  target: { type: String },
11
11
  /** If this tab is in the page tab sequence. dile-tabs keeps it true only on one of its tabs */
12
12
  tabbable: { type: Boolean, attribute: false },
13
+ /** Id of the panel controlled by this tab (resolved in the same DOM scope as the tab) */
14
+ controls: { type: String },
15
+ /** Panel element controlled by this tab. Takes precedence over controls */
16
+ controlsElement: { type: Object, attribute: false },
13
17
  };
14
18
  }
15
19
 
@@ -130,6 +134,23 @@ export class DileTab extends DileSelectableItem(LitElement) {
130
134
  }
131
135
  }
132
136
 
137
+ updated(changedProperties) {
138
+ super.updated?.(changedProperties);
139
+ this._updateAriaControls();
140
+ }
141
+
142
+ // The element with role="tab" lives in this shadow root, so an aria-controls IDREF
143
+ // can't reach the panel. ARIA element reflection can point to elements in an ancestor scope.
144
+ _updateAriaControls() {
145
+ const tab = this.shadowRoot?.querySelector('.tab');
146
+ if (!tab || !('ariaControlsElements' in Element.prototype)) {
147
+ return;
148
+ }
149
+ const panel = this.controlsElement
150
+ ?? (this.controls ? this.getRootNode().getElementById?.(this.controls) : null);
151
+ tab.ariaControlsElements = panel ? [panel] : null;
152
+ }
153
+
133
154
  focus(options) {
134
155
  this.shadowRoot?.querySelector('.tab')?.focus(options);
135
156
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dile/ui",
3
- "version": "3.20.1",
3
+ "version": "3.21.0",
4
4
  "description": "UI Core components from dile-components.",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -28,5 +28,5 @@
28
28
  "publishConfig": {
29
29
  "access": "public"
30
30
  },
31
- "gitHead": "2312fc5bacc0b5499c99cd25be6ae3509fd026c1"
31
+ "gitHead": "425f1cf93f61a2703365205c699b8a6fc64e538d"
32
32
  }