@aarongustafson/pull-to-refresh 1.1.3 → 1.2.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.
@@ -1,5 +1,51 @@
1
1
  import defaultTranslations from './translations.json' with { type: 'json' };
2
2
 
3
+ const messageNames = [
4
+ 'indicator-message',
5
+ 'release-message',
6
+ 'refreshing-message',
7
+ ];
8
+ const sharedConfigurations = new WeakMap();
9
+
10
+ function validateMessage(value) {
11
+ if (typeof value !== 'string' || !value.trim())
12
+ throw new TypeError(
13
+ 'Pull-to-refresh messages must be nonempty strings.',
14
+ );
15
+ }
16
+
17
+ function sharedMessages(document) {
18
+ const scripts = document.querySelectorAll('[data-pull-to-refresh-config]');
19
+ if (scripts.length > 1)
20
+ throw new TypeError(
21
+ 'Use only one pull-to-refresh configuration script per document.',
22
+ );
23
+ if (!scripts.length) return {};
24
+ const script = scripts[0];
25
+ if (
26
+ script.localName !== 'script' ||
27
+ script.type.trim().toLowerCase() !== 'application/json' ||
28
+ script.hasAttribute('src') ||
29
+ script.getAttribute('data-pull-to-refresh-config') !== ''
30
+ )
31
+ throw new TypeError(
32
+ 'Use an inline application/json script with an empty data-pull-to-refresh-config attribute.',
33
+ );
34
+ const text = script.textContent;
35
+ const cached = sharedConfigurations.get(script);
36
+ if (cached?.text === text) return cached.messages;
37
+ const messages = JSON.parse(text);
38
+ if (!messages || typeof messages !== 'object' || Array.isArray(messages))
39
+ throw new TypeError('Pull-to-refresh configuration must be an object.');
40
+ for (const [name, value] of Object.entries(messages)) {
41
+ if (!messageNames.includes(name))
42
+ throw new TypeError(`Unknown pull-to-refresh message: ${name}.`);
43
+ validateMessage(value);
44
+ }
45
+ sharedConfigurations.set(script, { text, messages });
46
+ return messages;
47
+ }
48
+
3
49
  /**
4
50
  * PullToRefreshElement - Web component that enables pull-to-refresh functionality
5
51
  *
@@ -9,6 +55,9 @@ import defaultTranslations from './translations.json' with { type: 'json' };
9
55
  * @attr {string} indicator-text - Text shown when pulling down (default: localized "↓ Pull to refresh")
10
56
  * @attr {string} release-text - Text shown when ready to release (default: localized "↻ Release to refresh")
11
57
  * @attr {string} refreshing-text - Text shown while refreshing (default: localized "⏳ Refreshing...")
58
+ * @attr {string} indicator-message - Complete literal message while pulling; supersedes indicator-text.
59
+ * @attr {string} release-message - Complete literal message beyond the threshold; supersedes release-text.
60
+ * @attr {string} refreshing-message - Complete literal message while refreshing; supersedes refreshing-text.
12
61
  * @attr {string} lang - Language code for localization (falls back to closest [lang], document lang, or 'en')
13
62
  * @attr {boolean} disabled - Disables the pull-to-refresh functionality
14
63
  * @attr {boolean} disable-selection - Disables text selection during pull gesture
@@ -29,8 +78,14 @@ import defaultTranslations from './translations.json' with { type: 'json' };
29
78
  * @cssprop --ptr-transition-duration - Duration of indicator transitions (default: 0.2s)
30
79
  */
31
80
  export class PullToRefreshElement extends HTMLElement {
81
+ #pullIndicatorHeight = 0;
82
+ #messages = { ...defaultTranslations.en };
83
+ #refreshAction = null;
84
+
85
+ /** @deprecated Prefer authored instance/shared messages. Removal is reserved for a future major release. */
32
86
  static customTranslations = {};
33
87
 
88
+ /** @deprecated Prefer authored instance/shared messages. Removal is reserved for a future major release. */
34
89
  static registerTranslations(translations) {
35
90
  this.customTranslations = {
36
91
  ...this.customTranslations,
@@ -41,12 +96,14 @@ export class PullToRefreshElement extends HTMLElement {
41
96
  static get observedAttributes() {
42
97
  return [
43
98
  'threshold',
99
+ 'refresh-timeout',
44
100
  'indicator-text',
45
101
  'release-text',
46
102
  'refreshing-text',
47
103
  'lang',
48
104
  'disabled',
49
105
  'disable-selection',
106
+ ...messageNames,
50
107
  ];
51
108
  }
52
109
 
@@ -59,6 +116,7 @@ export class PullToRefreshElement extends HTMLElement {
59
116
  this.currentY = 0;
60
117
  this.isPulling = false;
61
118
  this.isPullingConfirmed = false;
119
+ /** Component interaction state. Observe only; transition through refresh commands. */
62
120
  this.isRefreshing = false;
63
121
  this.__listenersAttached = false;
64
122
  this.__refreshTimeoutId = null;
@@ -87,13 +145,18 @@ export class PullToRefreshElement extends HTMLElement {
87
145
 
88
146
  connectedCallback() {
89
147
  this.__upgradeProperty('threshold');
148
+ this.__upgradeProperty('refreshTimeout');
90
149
  this.__upgradeProperty('indicatorText');
91
150
  this.__upgradeProperty('releaseText');
92
151
  this.__upgradeProperty('refreshingText');
152
+ this.__upgradeProperty('indicatorMessage');
153
+ this.__upgradeProperty('releaseMessage');
154
+ this.__upgradeProperty('refreshingMessage');
93
155
  this.__upgradeProperty('disabled');
94
156
  this.__upgradeProperty('disableSelection');
95
157
  this.__upgradeProperty('lang');
96
158
  this.__lang = this.__resolveLang();
159
+ this.__readMessages();
97
160
 
98
161
  this.render();
99
162
  this.setupEventListeners();
@@ -103,6 +166,13 @@ export class PullToRefreshElement extends HTMLElement {
103
166
  this.removeEventListeners();
104
167
  this.__clearRefreshTimeout();
105
168
  this.__clearAriaLiveResetTimeout();
169
+ this.#refreshAction = null;
170
+ this.isRefreshing = false;
171
+ this.isPulling = false;
172
+ this.isPullingConfirmed = false;
173
+ this.currentY = 0;
174
+ this.startY = 0;
175
+ this.removeAttribute('pulling');
106
176
  }
107
177
 
108
178
  attributeChangedCallback(name, oldValue, newValue) {
@@ -111,14 +181,29 @@ export class PullToRefreshElement extends HTMLElement {
111
181
  }
112
182
 
113
183
  switch (name) {
114
- case 'lang':
115
- this.__lang = this.__resolveLang();
116
- this.updateIndicatorText({ force: true });
184
+ case 'refresh-timeout':
185
+ if (
186
+ newValue !== null &&
187
+ (newValue.trim() === '' ||
188
+ !Number.isInteger(Number(newValue)) ||
189
+ Number(newValue) < 0 ||
190
+ Number(newValue) > 2147483647)
191
+ ) {
192
+ console.error(
193
+ 'pull-to-refresh: refresh-timeout must be an integer from 0 to 2147483647 milliseconds.',
194
+ );
195
+ this.removeAttribute('refresh-timeout');
196
+ }
117
197
  break;
198
+ case 'lang':
118
199
  case 'indicator-text':
119
200
  case 'release-text':
120
201
  case 'refreshing-text':
121
- this.updateIndicatorText({ force: true });
202
+ case 'indicator-message':
203
+ case 'release-message':
204
+ case 'refreshing-message':
205
+ if (this._indicatorTextEl && this.__readMessages())
206
+ this.updateIndicatorText({ force: true });
122
207
  break;
123
208
  case 'threshold': {
124
209
  if (newValue !== null) {
@@ -151,15 +236,45 @@ export class PullToRefreshElement extends HTMLElement {
151
236
  }
152
237
 
153
238
  __getTranslations() {
154
- // Merge default and custom translations (custom takes precedence)
155
- const allTranslations = {
156
- ...defaultTranslations,
157
- ...PullToRefreshElement.customTranslations,
158
- };
159
-
160
239
  // Get base language code (e.g., 'en-US' -> 'en')
161
240
  const langCode = this.__lang.split('-')[0];
162
- return allTranslations[langCode] || allTranslations.en;
241
+ return {
242
+ ...defaultTranslations.en,
243
+ ...this.constructor.customTranslations.en,
244
+ ...defaultTranslations[langCode],
245
+ ...this.constructor.customTranslations[langCode],
246
+ };
247
+ }
248
+
249
+ __readMessages() {
250
+ try {
251
+ const shared = sharedMessages(this.ownerDocument);
252
+ this.__lang = this.__resolveLang();
253
+ const translations = this.__getTranslations();
254
+ const messages = {};
255
+ for (const name of messageNames) {
256
+ const key = name.replace('-message', '');
257
+ const value =
258
+ this.getAttribute(name) ??
259
+ (this.getAttribute(`${key}-text`) ||
260
+ shared[name] ||
261
+ translations[key]);
262
+ validateMessage(value);
263
+ messages[key] = value;
264
+ }
265
+ this.#messages = messages;
266
+ return true;
267
+ } catch (error) {
268
+ console.error('pull-to-refresh could not refresh messages:', error);
269
+ return false;
270
+ }
271
+ }
272
+
273
+ refreshMessages() {
274
+ if (!this.isConnected) return false;
275
+ if (!this.__readMessages()) return false;
276
+ this.updateIndicatorText({ force: true });
277
+ return true;
163
278
  }
164
279
 
165
280
  setupEventListeners() {
@@ -249,9 +364,11 @@ export class PullToRefreshElement extends HTMLElement {
249
364
  !this.isRefreshing &&
250
365
  !this.disabled
251
366
  ) {
367
+ this.#pullIndicatorHeight = this._indicator?.offsetHeight ?? 0;
252
368
  this.isPulling = true;
253
369
  this.isPullingConfirmed = false;
254
370
  this.startY = e.clientY;
371
+ this.currentY = 0;
255
372
  }
256
373
  }
257
374
 
@@ -283,6 +400,7 @@ export class PullToRefreshElement extends HTMLElement {
283
400
  composed: true,
284
401
  }),
285
402
  );
403
+ if (!this.isConnected || !this.isPulling) return;
286
404
  }
287
405
  } else {
288
406
  // Not enough movement yet
@@ -297,7 +415,7 @@ export class PullToRefreshElement extends HTMLElement {
297
415
  e.preventDefault(); // Prevent scroll bounce
298
416
  }
299
417
 
300
- const indicatorHeight = this.indicatorHeight;
418
+ const indicatorHeight = this.#pullIndicatorHeight;
301
419
  const translateY = Math.min(
302
420
  this.currentY - indicatorHeight,
303
421
  indicatorHeight,
@@ -323,10 +441,11 @@ export class PullToRefreshElement extends HTMLElement {
323
441
  }
324
442
  }
325
443
 
326
- handleEnd() {
444
+ handleEnd(e) {
327
445
  if (!this.isPulling) return;
328
446
 
329
447
  this.isPulling = false;
448
+ this.isPullingConfirmed = false;
330
449
 
331
450
  // Re-enable text selection if it was disabled
332
451
  this.removeAttribute('pulling');
@@ -337,9 +456,13 @@ export class PullToRefreshElement extends HTMLElement {
337
456
  composed: true,
338
457
  }),
339
458
  );
459
+ if (!this.isConnected) return;
340
460
 
341
- // Only trigger refresh if pulled down (positive currentY) past threshold
342
- if (this.currentY > 0 && this.currentY > this.threshold) {
461
+ if (
462
+ e?.type !== 'pointercancel' &&
463
+ this.currentY > 0 &&
464
+ this.currentY > this.threshold
465
+ ) {
343
466
  this.triggerRefresh();
344
467
  } else {
345
468
  this.resetIndicator();
@@ -356,9 +479,12 @@ export class PullToRefreshElement extends HTMLElement {
356
479
  }
357
480
 
358
481
  async triggerRefresh() {
359
- if (this.isRefreshing) {
482
+ if (!this.isConnected || this.isRefreshing) {
360
483
  return;
361
484
  }
485
+ const action = {};
486
+ const timeout = this.refreshTimeout;
487
+ this.#refreshAction = action;
362
488
  this.isRefreshing = true;
363
489
  this.__updateIndicatorTextForState();
364
490
  if (this._indicator) {
@@ -369,21 +495,27 @@ export class PullToRefreshElement extends HTMLElement {
369
495
  bubbles: true,
370
496
  composed: true,
371
497
  detail: {
372
- complete: () => this.completeRefresh(),
498
+ complete: () => this.__completeRefresh(action),
373
499
  },
374
500
  });
375
501
 
376
502
  this.dispatchEvent(refreshEvent);
377
503
 
378
- // If no listener calls complete(), auto-complete after a delay
379
- this.__refreshTimeoutId = setTimeout(() => {
380
- if (this.isRefreshing) {
381
- this.completeRefresh();
382
- }
383
- }, 2000);
504
+ if (timeout > 0 && this.#refreshAction === action) {
505
+ this.__refreshTimeoutId = setTimeout(
506
+ () => this.__completeRefresh(action),
507
+ timeout,
508
+ );
509
+ }
384
510
  }
385
511
 
386
512
  completeRefresh() {
513
+ this.__completeRefresh(this.#refreshAction);
514
+ }
515
+
516
+ __completeRefresh(action) {
517
+ if (action === null || this.#refreshAction !== action) return;
518
+ this.#refreshAction = null;
387
519
  this.isRefreshing = false;
388
520
  this.resetIndicator();
389
521
  this.__clearRefreshTimeout();
@@ -402,7 +534,7 @@ export class PullToRefreshElement extends HTMLElement {
402
534
  // Temporarily disable announcements during reset
403
535
  this._indicator.setAttribute('aria-live', 'off');
404
536
 
405
- this._indicator.style.transform = `translateY(${-this.indicatorHeight}px)`;
537
+ this._indicator.style.transform = 'translateY(-100%)';
406
538
  this._indicator.classList.remove('active');
407
539
  this.__updateIndicatorTextForState();
408
540
 
@@ -431,6 +563,24 @@ export class PullToRefreshElement extends HTMLElement {
431
563
  return Number.isFinite(parsed) ? parsed : 80;
432
564
  }
433
565
 
566
+ /** Automatic completion delay in milliseconds; zero requires explicit completion. */
567
+ get refreshTimeout() {
568
+ return Number(this.getAttribute('refresh-timeout') ?? 2000);
569
+ }
570
+
571
+ set refreshTimeout(value) {
572
+ if (value === null || value === undefined) {
573
+ this.removeAttribute('refresh-timeout');
574
+ return;
575
+ }
576
+ if (!Number.isInteger(value) || value < 0 || value > 2147483647) {
577
+ throw new RangeError(
578
+ 'refreshTimeout must be an integer from 0 to 2147483647 milliseconds.',
579
+ );
580
+ }
581
+ this.setAttribute('refresh-timeout', String(value));
582
+ }
583
+
434
584
  set threshold(value) {
435
585
  if (value === null || value === undefined || value === '') {
436
586
  this.removeAttribute('threshold');
@@ -444,9 +594,36 @@ export class PullToRefreshElement extends HTMLElement {
444
594
  this.setAttribute('threshold', String(Math.round(numericValue)));
445
595
  }
446
596
 
597
+ get indicatorMessage() {
598
+ return this.getAttribute('indicator-message');
599
+ }
600
+
601
+ set indicatorMessage(value) {
602
+ if (value == null) this.removeAttribute('indicator-message');
603
+ else this.setAttribute('indicator-message', value);
604
+ }
605
+
606
+ get releaseMessage() {
607
+ return this.getAttribute('release-message');
608
+ }
609
+
610
+ set releaseMessage(value) {
611
+ if (value == null) this.removeAttribute('release-message');
612
+ else this.setAttribute('release-message', value);
613
+ }
614
+
615
+ get refreshingMessage() {
616
+ return this.getAttribute('refreshing-message');
617
+ }
618
+
619
+ set refreshingMessage(value) {
620
+ if (value == null) this.removeAttribute('refreshing-message');
621
+ else this.setAttribute('refreshing-message', value);
622
+ }
623
+
624
+ /** @deprecated Use indicatorMessage or shared JSON messages. */
447
625
  get indicatorText() {
448
- const t = this.__getTranslations();
449
- return this.getAttribute('indicator-text') || t.indicator;
626
+ return this.#messages.indicator;
450
627
  }
451
628
 
452
629
  set indicatorText(value) {
@@ -457,9 +634,9 @@ export class PullToRefreshElement extends HTMLElement {
457
634
  this.setAttribute('indicator-text', value);
458
635
  }
459
636
 
637
+ /** @deprecated Use releaseMessage or shared JSON messages. */
460
638
  get releaseText() {
461
- const t = this.__getTranslations();
462
- return this.getAttribute('release-text') || t.release;
639
+ return this.#messages.release;
463
640
  }
464
641
 
465
642
  set releaseText(value) {
@@ -470,9 +647,9 @@ export class PullToRefreshElement extends HTMLElement {
470
647
  this.setAttribute('release-text', value);
471
648
  }
472
649
 
650
+ /** @deprecated Use refreshingMessage or shared JSON messages. */
473
651
  get refreshingText() {
474
- const t = this.__getTranslations();
475
- return this.getAttribute('refreshing-text') || t.refreshing;
652
+ return this.#messages.refreshing;
476
653
  }
477
654
 
478
655
  set refreshingText(value) {
@@ -507,9 +684,8 @@ export class PullToRefreshElement extends HTMLElement {
507
684
  }
508
685
  }
509
686
 
510
- // eslint-disable-next-line class-methods-use-this
511
687
  get indicatorHeight() {
512
- return 50; // 3.125rem in pixels (assuming 16px base)
688
+ return this._indicator?.getBoundingClientRect().height ?? 0;
513
689
  }
514
690
 
515
691
  static styles = `
@@ -544,7 +720,7 @@ export class PullToRefreshElement extends HTMLElement {
544
720
  background: var(--ptr-indicator-bg, ButtonFace);
545
721
  color: var(--ptr-indicator-color, ButtonText);
546
722
  font-size: var(--ptr-indicator-font-size, 0.875rem);
547
- transform: translateY(-3.125rem);
723
+ transform: translateY(-100%);
548
724
  transition: transform var(--ptr-transition-duration, 0.2s) ease;
549
725
  z-index: 1000;
550
726
  user-select: none;
@@ -570,7 +746,7 @@ export class PullToRefreshElement extends HTMLElement {
570
746
  <div class="ptr-container">
571
747
  <div class="ptr-indicator" role="status" aria-live="assertive">
572
748
  <slot name="indicator">
573
- <span class="ptr-indicator-text">${this.indicatorText}</span>
749
+ <span class="ptr-indicator-text"></span>
574
750
  </slot>
575
751
  </div>
576
752
  <div class="ptr-content">
@@ -592,7 +768,7 @@ export class PullToRefreshElement extends HTMLElement {
592
768
  return (
593
769
  this.getAttribute('lang') ||
594
770
  this.closest('[lang]')?.getAttribute('lang') ||
595
- document.documentElement.lang ||
771
+ this.ownerDocument.documentElement.lang ||
596
772
  'en'
597
773
  );
598
774
  }