@aarongustafson/pull-to-refresh 0.0.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aaron Gustafson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,395 @@
1
+ # Pull to Refresh Web Component
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@aarongustafson/pull-to-refresh.svg)](https://www.npmjs.com/package/@aarongustafson/pull-to-refresh)
4
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/aarongustafson/pull-to-refresh/ci.yml?branch=main)](https://github.com/aarongustafson/pull-to-refresh/actions)
5
+
6
+ A lightweight, customizable Web Component that adds pull-to-refresh functionality to your web applications. Perfect for mobile-first experiences and progressive web apps.
7
+
8
+ ## Features
9
+
10
+ - **Touch-optimized**: Smooth pull gesture with momentum and feedback
11
+ - **Customizable**: Adjust threshold, text, and styling via attributes and CSS custom properties
12
+ - **Event-driven**: Rich event API for complete control over the refresh lifecycle
13
+ - **Accessible**: Semantic HTML and ARIA-friendly
14
+ - **Framework-agnostic**: Works with any framework or vanilla JavaScript
15
+ - **Lightweight**: No dependencies, just native Web Components
16
+ - **Shadow DOM**: Encapsulated styles that won't leak
17
+
18
+ ## Quick Start
19
+
20
+ ### Installation
21
+
22
+ ```bash
23
+ npm install @aarongustafson/pull-to-refresh
24
+ ```
25
+
26
+ ### Usage
27
+
28
+ **Option 1: Auto-define (easiest)**
29
+ ```javascript
30
+ import '@aarongustafson/pull-to-refresh';
31
+ ```
32
+
33
+ **Option 2: Manual registration**
34
+ ```javascript
35
+ import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh/pull-to-refresh.js';
36
+ customElements.define('pull-to-refresh', PullToRefreshElement);
37
+ ```
38
+
39
+ **Option 3: Both (class + auto-define)**
40
+ ```javascript
41
+ import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
42
+ // Element is registered AND class is available
43
+ ```
44
+
45
+ ### Basic Example
46
+
47
+ ```html
48
+ <pull-to-refresh>
49
+ <div class="content">
50
+ <h1>My Content</h1>
51
+ <p>Pull down from the top to refresh!</p>
52
+ </div>
53
+ </pull-to-refresh>
54
+
55
+ <script type="module">
56
+ import '@aarongustafson/pull-to-refresh';
57
+
58
+ const ptr = document.querySelector('pull-to-refresh');
59
+
60
+ ptr.addEventListener('ptr:refresh', (e) => {
61
+ // Perform your refresh logic (fetch data, etc.)
62
+ fetch('/api/data')
63
+ .then(response => response.json())
64
+ .then(data => {
65
+ // Update your content
66
+ updateContent(data);
67
+ // Signal completion
68
+ e.detail.complete();
69
+ });
70
+ });
71
+ </script>
72
+ ```
73
+
74
+ ## API
75
+
76
+ ### Attributes
77
+
78
+ | Attribute | Type | Default | Description |
79
+ |-----------|------|---------|-------------|
80
+ | `threshold` | number | `80` | Distance in pixels to trigger refresh |
81
+ | `indicator-text` | string | localized | Text shown when pulling down |
82
+ | `release-text` | string | localized | Text shown when ready to release |
83
+ | `refreshing-text` | string | localized | Text shown while refreshing |
84
+ | `lang` | string | auto-detected | Language code for localization |
85
+ | `disabled` | boolean | `false` | Disables pull-to-refresh functionality |
86
+ | `disable-selection` | boolean | `false` | Prevents text selection during pull gesture |
87
+
88
+ **Note:** The text attributes use automatic localization based on the `lang` attribute or auto-detection. See [Localization](#-localization-i18n) below.
89
+
90
+ ### Properties
91
+
92
+ All attributes are also available as properties:
93
+
94
+ ```javascript
95
+ const ptr = document.querySelector('pull-to-refresh');
96
+ ptr.threshold = 120;
97
+ ptr.indicatorText = 'Swipe down';
98
+ ptr.disabled = true;
99
+ ```
100
+
101
+ ### Events
102
+
103
+ | Event | Detail | Description |
104
+ |-------|--------|-------------|
105
+ | `ptr:pull-start` | `{}` | Fired when pull gesture starts |
106
+ | `ptr:pull-move` | `{ distance: number }` | Fired during pull gesture |
107
+ | `ptr:pull-end` | `{}` | Fired when pull gesture ends |
108
+ | `ptr:refresh` | `{ complete: Function }` | Fired when refresh is triggered |
109
+ | `ptr:refresh-complete` | `{}` | Fired when refresh completes |
110
+
111
+ **Important**: Call `event.detail.complete()` in your `ptr:refresh` handler to signal completion:
112
+
113
+ ```javascript
114
+ ptr.addEventListener('ptr:refresh', (e) => {
115
+ doAsyncWork().then(() => {
116
+ e.detail.complete(); // Call this when done
117
+ });
118
+ });
119
+ ```
120
+
121
+ If you don't call `complete()`, the component will auto-complete after 2 seconds.
122
+
123
+ ### Slots
124
+
125
+ | Slot | Description |
126
+ |------|-------------|
127
+ | (default) | Your scrollable content |
128
+ | `indicator` | Optional custom indicator element |
129
+
130
+ ### CSS Custom Properties
131
+
132
+ | Property | Default | Description |
133
+ |----------|---------|-------------|
134
+ | `--ptr-indicator-height` | `3.125rem` | Height of the indicator area |
135
+ | `--ptr-indicator-bg` | `ButtonFace` | Background color of indicator |
136
+ | `--ptr-indicator-color` | `ButtonText` | Text color of indicator |
137
+ | `--ptr-indicator-font-size` | `0.875rem` | Font size of indicator text |
138
+ | `--ptr-transition-duration` | `0.2s` | Duration of indicator transitions |
139
+
140
+ ### Methods
141
+
142
+ | Method | Description |
143
+ |--------|-------------|
144
+ | `completeRefresh()` | Manually complete the refresh (alternative to calling `event.detail.complete()`) |
145
+
146
+ ## Examples
147
+
148
+ ### Custom Threshold
149
+
150
+ ```html
151
+ <pull-to-refresh threshold="120">
152
+ <div>Content here</div>
153
+ </pull-to-refresh>
154
+ ```
155
+
156
+ ### Localization
157
+
158
+ The component automatically detects the language and displays localized text:
159
+
160
+ ```html
161
+ <!-- Spanish -->
162
+ <pull-to-refresh lang="es">
163
+ <div>Contenido aquí</div>
164
+ </pull-to-refresh>
165
+
166
+ <!-- French -->
167
+ <pull-to-refresh lang="fr">
168
+ <div>Contenu ici</div>
169
+ </pull-to-refresh>
170
+
171
+ <!-- Japanese -->
172
+ <pull-to-refresh lang="ja">
173
+ <div>ここにコンテンツ</div>
174
+ </pull-to-refresh>
175
+ ```
176
+
177
+ The component supports 16 languages with automatic fallback to English. Language is detected from:
178
+ 1. The element's `lang` attribute
179
+ 2. The nearest ancestor's `lang` attribute
180
+ 3. The document's `lang` attribute
181
+ 4. Default: English
182
+
183
+ You can also register custom translations:
184
+
185
+ ```javascript
186
+ import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
187
+
188
+ PullToRefreshElement.registerTranslations({
189
+ 'pt-BR': {
190
+ indicator: '↓ Puxe para atualizar',
191
+ release: '↻ Solte para atualizar',
192
+ refreshing: '⏳ Atualizando...'
193
+ }
194
+ });
195
+ ```
196
+
197
+ ### Custom Styling
198
+
199
+ ```html
200
+ <style>
201
+ pull-to-refresh {
202
+ --ptr-indicator-bg: #f0f0f0;
203
+ --ptr-indicator-color: #1976d2;
204
+ --ptr-indicator-font-size: 1rem;
205
+ --ptr-indicator-height: 3.75rem;
206
+ }
207
+ </style>
208
+
209
+ <pull-to-refresh>
210
+ <div>Content here</div>
211
+ </pull-to-refresh>
212
+ ```
213
+
214
+ ### Custom Messages
215
+
216
+ ```html
217
+ <pull-to-refresh
218
+ indicator-text="⬇ Swipe down"
219
+ release-text="🔄 Let go!"
220
+ refreshing-text="⏳ Loading...">
221
+ <div>Content here</div>
222
+ </pull-to-refresh>
223
+ ```
224
+
225
+ ### With Fetch API
226
+
227
+ ```javascript
228
+ ptr.addEventListener('ptr:refresh', async (e) => {
229
+ try {
230
+ const response = await fetch('/api/latest');
231
+ const data = await response.json();
232
+ renderData(data);
233
+ } catch (error) {
234
+ console.error('Refresh failed:', error);
235
+ } finally {
236
+ e.detail.complete();
237
+ }
238
+ });
239
+ ```
240
+
241
+ ### Disabled State
242
+
243
+ ```html
244
+ <!-- Disable pull-to-refresh when needed -->
245
+ <pull-to-refresh disabled>
246
+ <div>No refresh available</div>
247
+ </pull-to-refresh>
248
+
249
+ <script>
250
+ // Or toggle programmatically
251
+ ptr.disabled = true;
252
+ </script>
253
+ ```
254
+
255
+ ### Tracking Pull Distance
256
+
257
+ ```javascript
258
+ ptr.addEventListener('ptr:pull-move', (e) => {
259
+ console.log('Pull distance:', e.detail.distance);
260
+ // Use this for custom animations, etc.
261
+ });
262
+ ```
263
+
264
+ ## Localization (i18n)
265
+
266
+ The component includes built-in translations for **16 languages**:
267
+
268
+ | Language | Code | Indicator Text |
269
+ |----------|------|----------------|
270
+ | English | `en` | ↓ Pull to refresh |
271
+ | Chinese (Mandarin) | `zh` | ↓ 下拉刷新 |
272
+ | Hindi | `hi` | ↓ रीफ्रेश करने के लिए खींचें |
273
+ | Spanish | `es` | ↓ Desliza para actualizar |
274
+ | French | `fr` | ↓ Tirez pour actualiser |
275
+ | Arabic | `ar` | ↓ اسحب للتحديث |
276
+ | Bengali | `bn` | ↓ রিফ্রেশ করতে টানুন |
277
+ | Portuguese | `pt` | ↓ Puxe para atualizar |
278
+ | Russian | `ru` | ↓ Потяните для обновления |
279
+ | Japanese | `ja` | ↓ 引っ張って更新 |
280
+ | German | `de` | ↓ Zum Aktualisieren ziehen |
281
+ | Punjabi | `pa` | ↓ ਤਾਜ਼ਾ ਕਰਨ ਲਈ ਖਿੱਚੋ |
282
+ | Javanese | `jv` | ↓ Tarik kanggo nyegerake |
283
+ | Korean | `ko` | ↓ 당겨서 새로고침 |
284
+ | Vietnamese | `vi` | ↓ Kéo để làm mới |
285
+ | Italian | `it` | ↓ Trascina per aggiornare |
286
+
287
+ ### Language Detection
288
+
289
+ The component uses a cascading fallback approach:
290
+
291
+ 1. Element's `lang` attribute: `&lt;pull-to-refresh lang="es"&gt;`
292
+ 2. Nearest ancestor with `lang`: `&lt;div lang="fr"&gt;&lt;pull-to-refresh&gt;`
293
+ 3. Document language: `&lt;html lang="de"&gt;`
294
+ 4. Default: English (en)
295
+
296
+ Regional variants (e.g., `en-US`, `es-MX`, `fr-CA`) automatically fall back to their base language.
297
+
298
+ ### Custom Translations
299
+
300
+ Register custom translations or override existing ones:
301
+
302
+ ```javascript
303
+ import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
304
+
305
+ // Add a new language
306
+ PullToRefreshElement.registerTranslations({
307
+ 'nl': {
308
+ indicator: '↓ Trek om te vernieuwen',
309
+ release: '↻ Loslaten om te vernieuwen',
310
+ refreshing: '⏳ Vernieuwen...'
311
+ }
312
+ });
313
+
314
+ // Override existing translations
315
+ PullToRefreshElement.registerTranslations({
316
+ 'en': {
317
+ indicator: '⬇ Pull down',
318
+ release: '🔄 Let go',
319
+ refreshing: '⏳ Loading...'
320
+ }
321
+ });
322
+ ```
323
+
324
+ ### Per-Instance Overrides
325
+
326
+ You can always override translations for individual instances:
327
+
328
+ ```html
329
+ <pull-to-refresh
330
+ lang="es"
331
+ indicator-text="Custom Spanish text"
332
+ release-text="Custom release text">
333
+ <!-- Content -->
334
+ </pull-to-refresh>
335
+ ```
336
+
337
+ ## Testing
338
+
339
+ ```bash
340
+ npm test # Run tests in watch mode
341
+ npm run test:run # Run tests once
342
+ npm run test:ui # Open Vitest UI
343
+ npm run test:coverage # Generate coverage report
344
+ ```
345
+
346
+ ## Development
347
+
348
+ ```bash
349
+ npm install # Install dependencies
350
+ npm run setup # Run setup wizard (first time)
351
+ npm run lint # Lint code
352
+ npm run format # Format code
353
+ ```
354
+
355
+ ## Browser Support
356
+
357
+ Works in all modern browsers supporting:
358
+ - Custom Elements v1
359
+ - Shadow DOM v1
360
+ - ES Modules
361
+ - Pointer Events
362
+
363
+ For legacy browsers, use appropriate polyfills.
364
+
365
+ ## Package Exports
366
+
367
+ ```javascript
368
+ // Auto-define
369
+ import '@aarongustafson/pull-to-refresh';
370
+
371
+ // Class only
372
+ import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh/pull-to-refresh.js';
373
+
374
+ // Both
375
+ import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
376
+
377
+ // Manual define script
378
+ import '@aarongustafson/pull-to-refresh/define.js';
379
+ ```
380
+
381
+ ## Contributing
382
+
383
+ Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
384
+
385
+ ## License
386
+
387
+ MIT - See [LICENSE](LICENSE)
388
+
389
+ ## Credits
390
+
391
+ Created by [Aaron Gustafson](https://github.com/aarongustafson)
392
+
393
+ ---
394
+
395
+ **Try it out!** Check out the [live demo](demo/index.html) 🚀
@@ -0,0 +1,35 @@
1
+ {
2
+ "schemaVersion": "1.0.0",
3
+ "readme": "",
4
+ "modules": [
5
+ {
6
+ "kind": "javascript-module",
7
+ "path": "pull-to-refresh.js",
8
+ "declarations": [
9
+ {
10
+ "kind": "class",
11
+ "description": "Refreshes the current document or runs a specific JavaScript function when pulling down on the page",
12
+ "name": "PullToRefreshElement",
13
+ "members": [],
14
+ "events": [],
15
+ "attributes": [],
16
+ "superclass": {
17
+ "name": "HTMLElement"
18
+ },
19
+ "tagName": "pull-to-refresh",
20
+ "customElement": true
21
+ }
22
+ ],
23
+ "exports": [
24
+ {
25
+ "kind": "js",
26
+ "name": "PullToRefreshElement",
27
+ "declaration": {
28
+ "name": "PullToRefreshElement",
29
+ "module": "pull-to-refresh.js"
30
+ }
31
+ }
32
+ ]
33
+ }
34
+ ]
35
+ }
package/define.js ADDED
@@ -0,0 +1,3 @@
1
+ import { PullToRefreshElement } from './pull-to-refresh.js';
2
+
3
+ customElements.define('pull-to-refresh', PullToRefreshElement);
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { PullToRefreshElement } from './pull-to-refresh.js';
2
+ import './define.js';
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@aarongustafson/pull-to-refresh",
3
+ "version": "0.0.2",
4
+ "description": "Refreshes the current document or runs a specific JavaScript function when pulling down on the page",
5
+ "keywords": [
6
+ "html",
7
+ "custom element",
8
+ "web component"
9
+ ],
10
+ "author": "Aaron Gustafson <aaron@easy-designs.net> (https://www.aaron-gustafson.com/)",
11
+ "license": "MIT",
12
+ "homepage": "https://github.com/aarongustafson/pull-to-refresh#readme",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/aarongustafson/pull-to-refresh.git"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/aarongustafson/pull-to-refresh/issues"
19
+ },
20
+ "type": "module",
21
+ "main": "index.js",
22
+ "module": "pull-to-refresh.js",
23
+ "customElements": "custom-elements.json",
24
+ "exports": {
25
+ ".": {
26
+ "import": "./index.js"
27
+ },
28
+ "./pull-to-refresh.js": {
29
+ "import": "./pull-to-refresh.js"
30
+ },
31
+ "./define.js": {
32
+ "import": "./define.js"
33
+ },
34
+ "./custom-elements.json": "./custom-elements.json"
35
+ },
36
+ "files": [
37
+ "pull-to-refresh.js",
38
+ "define.js",
39
+ "index.js",
40
+ "translations.json",
41
+ "custom-elements.json",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "engines": {
46
+ "node": ">=14.0.0"
47
+ },
48
+ "scripts": {
49
+ "setup": "node scripts/setup.js",
50
+ "test": "vitest",
51
+ "test:ui": "vitest --ui",
52
+ "test:run": "vitest run",
53
+ "test:coverage": "vitest run --coverage",
54
+ "lint": "npm run lint:eslint && npm run lint:prettier",
55
+ "format": "npm run format:eslint && npm run format:prettier",
56
+ "lint:eslint": "eslint .",
57
+ "format:eslint": "eslint . --fix",
58
+ "lint:prettier": "prettier \"**/*.js\" --check --ignore-path .gitignore",
59
+ "format:prettier": "prettier \"**/*.js\" --write --ignore-path .gitignore"
60
+ },
61
+ "devDependencies": {
62
+ "@open-wc/eslint-config": "^13.0.0",
63
+ "@testing-library/dom": "^10.4.1",
64
+ "@testing-library/user-event": "^14.6.1",
65
+ "@vitest/coverage-v8": "^4.0.10",
66
+ "@vitest/ui": "^4.0.10",
67
+ "eslint": "^9.39.1",
68
+ "eslint-config-prettier": "^10.1.8",
69
+ "happy-dom": "^20.0.10",
70
+ "prettier": "^3.6.2",
71
+ "vitest": "^4.0.10"
72
+ },
73
+ "publishConfig": {
74
+ "access": "public"
75
+ }
76
+ }
@@ -0,0 +1,531 @@
1
+ import defaultTranslations from './translations.json' with { type: 'json' };
2
+
3
+ /**
4
+ * PullToRefreshElement - Refreshes the current document or runs a specific JavaScript function when pulling down on the page
5
+ *
6
+ * @element pull-to-refresh
7
+ *
8
+ * @attr {number} threshold - Distance in pixels to trigger refresh (default: 80)
9
+ * @attr {string} indicator-text - Text shown when pulling down (default: localized "↓ Pull to refresh")
10
+ * @attr {string} release-text - Text shown when ready to release (default: localized "↻ Release to refresh")
11
+ * @attr {string} refreshing-text - Text shown while refreshing (default: localized "⏳ Refreshing...")
12
+ * @attr {string} lang - Language code for localization (falls back to closest [lang], document lang, or 'en')
13
+ * @attr {boolean} disabled - Disables the pull-to-refresh functionality
14
+ * @attr {boolean} disable-selection - Disables text selection during pull gesture
15
+ *
16
+ * @fires ptr:pull-start - Fired when pull gesture starts
17
+ * @fires ptr:pull-move - Fired during pull gesture, contains { distance } in detail
18
+ * @fires ptr:pull-end - Fired when pull gesture ends
19
+ * @fires ptr:refresh - Fired when refresh is triggered
20
+ * @fires ptr:refresh-complete - Fired when refresh completes
21
+ *
22
+ * @slot - Default slot for content
23
+ * @slot indicator - Optional custom indicator element
24
+ *
25
+ * @cssprop --ptr-indicator-height - Height of the indicator area (default: 3.125rem)
26
+ * @cssprop --ptr-indicator-bg - Background color of the indicator (default: ButtonFace)
27
+ * @cssprop --ptr-indicator-color - Text color of the indicator (default: ButtonText)
28
+ * @cssprop --ptr-indicator-font-size - Font size of the indicator text (default: 0.875rem)
29
+ * @cssprop --ptr-transition-duration - Duration of indicator transitions (default: 0.2s)
30
+ */
31
+ export class PullToRefreshElement extends HTMLElement {
32
+ static customTranslations = {};
33
+
34
+ static registerTranslations(translations) {
35
+ this.customTranslations = {
36
+ ...this.customTranslations,
37
+ ...translations,
38
+ };
39
+ }
40
+
41
+ static get observedAttributes() {
42
+ return [
43
+ 'threshold',
44
+ 'indicator-text',
45
+ 'release-text',
46
+ 'refreshing-text',
47
+ 'lang',
48
+ 'disabled',
49
+ 'disable-selection',
50
+ ];
51
+ }
52
+
53
+ static styles = `
54
+ :host {
55
+ display: block;
56
+ position: relative;
57
+ height: 100vh;
58
+ overflow: hidden;
59
+ }
60
+
61
+ :host([pulling][disable-selection]) ::slotted(*) {
62
+ user-select: none;
63
+ -webkit-user-select: none;
64
+ }
65
+
66
+ .ptr-container {
67
+ height: 100%;
68
+ overflow-y: auto;
69
+ -webkit-overflow-scrolling: touch;
70
+ position: relative;
71
+ }
72
+
73
+ .ptr-indicator {
74
+ position: absolute;
75
+ top: 0;
76
+ left: 0;
77
+ right: 0;
78
+ height: var(--ptr-indicator-height, 3.125rem);
79
+ display: flex;
80
+ align-items: center;
81
+ justify-content: center;
82
+ background: var(--ptr-indicator-bg, ButtonFace);
83
+ color: var(--ptr-indicator-color, ButtonText);
84
+ font-size: var(--ptr-indicator-font-size, 0.875rem);
85
+ transform: translateY(-3.125rem);
86
+ transition: transform var(--ptr-transition-duration, 0.2s) ease;
87
+ z-index: 1000;
88
+ user-select: none;
89
+ -webkit-user-select: none;
90
+ }
91
+
92
+ .ptr-indicator.active {
93
+ /* Active state can be styled via CSS parts or custom properties */
94
+ }
95
+
96
+ .ptr-content {
97
+ position: relative;
98
+ }
99
+
100
+ :host([disabled]) .ptr-container {
101
+ touch-action: auto;
102
+ }
103
+ `;
104
+
105
+ constructor() {
106
+ super();
107
+ this.attachShadow({ mode: 'open' });
108
+
109
+ // State management
110
+ this.startY = 0;
111
+ this.currentY = 0;
112
+ this.isPulling = false;
113
+ this.isPullingConfirmed = false;
114
+ this.isRefreshing = false;
115
+
116
+ // Cached DOM references (set after render)
117
+ this._container = null;
118
+ this._indicator = null;
119
+
120
+ // Language detection
121
+ this.__lang =
122
+ this.getAttribute('lang') ||
123
+ this.closest('[lang]')?.getAttribute('lang') ||
124
+ document.documentElement.lang ||
125
+ 'en';
126
+
127
+ // Bind event handlers
128
+ this.handleStart = this.handleStart.bind(this);
129
+ this.handleMove = this.handleMove.bind(this);
130
+ this.handleEnd = this.handleEnd.bind(this);
131
+ this.handleScroll = this.handleScroll.bind(this);
132
+ }
133
+
134
+ connectedCallback() {
135
+ this.render();
136
+ this.setupEventListeners();
137
+ }
138
+
139
+ disconnectedCallback() {
140
+ this.removeEventListeners();
141
+ }
142
+
143
+ attributeChangedCallback(name, oldValue, newValue) {
144
+ if (oldValue !== newValue) {
145
+ if (name === 'lang') {
146
+ this.__lang = newValue || 'en';
147
+ this.updateIndicatorText();
148
+ }
149
+ if (name === 'disabled') {
150
+ if (this.disabled) {
151
+ this.removeEventListeners();
152
+ } else {
153
+ this.setupEventListeners();
154
+ }
155
+ }
156
+ this.updateIndicatorText();
157
+ }
158
+ }
159
+
160
+ __getTranslations() {
161
+ // Merge default and custom translations (custom takes precedence)
162
+ const allTranslations = {
163
+ ...defaultTranslations,
164
+ ...PullToRefreshElement.customTranslations,
165
+ };
166
+
167
+ // Get base language code (e.g., 'en-US' -> 'en')
168
+ const langCode = this.__lang.split('-')[0];
169
+ return allTranslations[langCode] || allTranslations.en;
170
+ }
171
+
172
+ setupEventListeners() {
173
+ if (this.disabled) return;
174
+
175
+ this.addEventListener('pointerdown', this.handleStart, {
176
+ passive: true,
177
+ });
178
+ this.addEventListener('pointermove', this.handleMove, {
179
+ passive: false,
180
+ });
181
+ this.addEventListener('pointerup', this.handleEnd);
182
+ this.addEventListener('pointercancel', this.handleEnd);
183
+
184
+ const container = this.shadowRoot.querySelector('.ptr-container');
185
+ if (container) {
186
+ container.addEventListener('scroll', this.handleScroll);
187
+ }
188
+ }
189
+
190
+ removeEventListeners() {
191
+ this.removeEventListener('pointerdown', this.handleStart);
192
+ this.removeEventListener('pointermove', this.handleMove);
193
+ this.removeEventListener('pointerup', this.handleEnd);
194
+ this.removeEventListener('pointercancel', this.handleEnd);
195
+
196
+ if (!this._container) return;
197
+
198
+ this._container.removeEventListener('scroll', this.handleScroll);
199
+ }
200
+
201
+ handleStart(e) {
202
+ console.log('[PTR] handleStart', {
203
+ type: e.type,
204
+ pointerId: e.pointerId,
205
+ pointerType: e.pointerType,
206
+ clientY: e.clientY,
207
+ target: e.target,
208
+ });
209
+ if (
210
+ this._container.scrollTop === 0 &&
211
+ !this.isRefreshing &&
212
+ !this.disabled
213
+ ) {
214
+ console.log('[PTR] Starting pull (pending direction confirmation)');
215
+ this.isPulling = true;
216
+ this.isPullingConfirmed = false;
217
+ this.startY = e.clientY;
218
+ } else {
219
+ console.log('[PTR] Not starting pull', {
220
+ scrollTop: this._container.scrollTop,
221
+ isRefreshing: this.isRefreshing,
222
+ disabled: this.disabled,
223
+ });
224
+ }
225
+ }
226
+
227
+ handleMove(e) {
228
+ if (!this.isPulling) return;
229
+
230
+ const deltaY = e.clientY - this.startY;
231
+
232
+ console.log('[PTR] handleMove', {
233
+ clientY: e.clientY,
234
+ startY: this.startY,
235
+ delta: deltaY,
236
+ isPullingConfirmed: this.isPullingConfirmed,
237
+ });
238
+
239
+ // If direction not yet confirmed, check if user is pulling down
240
+ if (!this.isPullingConfirmed) {
241
+ // Need some movement to determine direction (at least 5px)
242
+ if (Math.abs(deltaY) > 5) {
243
+ if (deltaY < 0) {
244
+ // Upward pull - cancel the gesture
245
+ console.log('[PTR] Upward pull detected, canceling');
246
+ this.isPulling = false;
247
+ return;
248
+ } else {
249
+ // Downward pull - confirm and proceed
250
+ console.log('[PTR] Downward pull confirmed');
251
+ this.isPullingConfirmed = true;
252
+
253
+ // Prevent text selection during pull if disable-selection is set
254
+ if (this.disableSelection) {
255
+ this.setAttribute('pulling', '');
256
+ }
257
+
258
+ this.dispatchEvent(
259
+ new CustomEvent('ptr:pull-start', {
260
+ bubbles: true,
261
+ composed: true,
262
+ }),
263
+ );
264
+ }
265
+ } else {
266
+ // Not enough movement yet
267
+ return;
268
+ }
269
+ }
270
+
271
+ this.currentY = deltaY;
272
+
273
+ if (this.currentY > 0) {
274
+ e.preventDefault(); // Prevent scroll bounce
275
+
276
+ const indicatorHeight = this.indicatorHeight;
277
+ const translateY = Math.min(
278
+ this.currentY - indicatorHeight,
279
+ indicatorHeight,
280
+ );
281
+
282
+ this._indicator.style.transform = `translateY(${translateY}px)`;
283
+
284
+ if (this.currentY > this.threshold) {
285
+ this._indicator.textContent = this.releaseText;
286
+ this._indicator.classList.add('active');
287
+ } else {
288
+ this._indicator.textContent = this.indicatorText;
289
+ this._indicator.classList.remove('active');
290
+ }
291
+
292
+ this.dispatchEvent(
293
+ new CustomEvent('ptr:pull-move', {
294
+ bubbles: true,
295
+ composed: true,
296
+ detail: { distance: this.currentY },
297
+ }),
298
+ );
299
+ }
300
+ }
301
+
302
+ handleEnd() {
303
+ console.log('[PTR] handleEnd', {
304
+ isPulling: this.isPulling,
305
+ currentY: this.currentY,
306
+ threshold: this.threshold,
307
+ });
308
+ if (!this.isPulling) return;
309
+
310
+ this.isPulling = false;
311
+
312
+ // Re-enable text selection if it was disabled
313
+ this.removeAttribute('pulling');
314
+
315
+ this.dispatchEvent(
316
+ new CustomEvent('ptr:pull-end', {
317
+ bubbles: true,
318
+ composed: true,
319
+ }),
320
+ );
321
+
322
+ // Only trigger refresh if pulled down (positive currentY) past threshold
323
+ if (this.currentY > 0 && this.currentY > this.threshold) {
324
+ this.triggerRefresh();
325
+ } else {
326
+ this.resetIndicator();
327
+ }
328
+
329
+ // Reset currentY after handling the gesture
330
+ this.currentY = 0;
331
+ }
332
+
333
+ handleScroll() {
334
+ if (this._container.scrollTop > 0 && !this.isRefreshing) {
335
+ this.resetIndicator();
336
+ }
337
+ }
338
+
339
+ async triggerRefresh() {
340
+ console.log('[PTR] triggerRefresh called');
341
+ this.isRefreshing = true;
342
+ this._indicator.textContent = this.refreshingText;
343
+ this._indicator.classList.add('active');
344
+
345
+ const refreshEvent = new CustomEvent('ptr:refresh', {
346
+ bubbles: true,
347
+ composed: true,
348
+ detail: {
349
+ complete: () => this.completeRefresh(),
350
+ },
351
+ });
352
+
353
+ this.dispatchEvent(refreshEvent);
354
+
355
+ // If no listener calls complete(), auto-complete after a delay
356
+ setTimeout(() => {
357
+ if (this.isRefreshing) {
358
+ this.completeRefresh();
359
+ }
360
+ }, 2000);
361
+ }
362
+
363
+ completeRefresh() {
364
+ this.isRefreshing = false;
365
+ this.resetIndicator();
366
+
367
+ this.dispatchEvent(
368
+ new CustomEvent('ptr:refresh-complete', {
369
+ bubbles: true,
370
+ composed: true,
371
+ }),
372
+ );
373
+ }
374
+
375
+ resetIndicator() {
376
+ if (!this._indicator) return;
377
+
378
+ // Temporarily disable announcements during reset
379
+ this._indicator.setAttribute('aria-live', 'off');
380
+
381
+ this._indicator.style.transform = `translateY(${-this.indicatorHeight}px)`;
382
+ this._indicator.classList.remove('active');
383
+ this._indicator.textContent = this.indicatorText;
384
+
385
+ // Re-enable announcements after text is updated
386
+ // Use setTimeout to ensure the text change happens first
387
+ setTimeout(() => {
388
+ this._indicator.setAttribute('aria-live', 'assertive');
389
+ }, 0);
390
+ }
391
+
392
+ updateIndicatorText() {
393
+ if (!this._indicator || this.isPulling || this.isRefreshing) return;
394
+
395
+ this._indicator.textContent = this.indicatorText;
396
+ }
397
+
398
+ get threshold() {
399
+ return parseInt(this.getAttribute('threshold')) || 80;
400
+ }
401
+
402
+ set threshold(value) {
403
+ this.setAttribute('threshold', value);
404
+ }
405
+
406
+ get indicatorText() {
407
+ const t = this.__getTranslations();
408
+ return this.getAttribute('indicator-text') || t.indicator;
409
+ }
410
+
411
+ set indicatorText(value) {
412
+ this.setAttribute('indicator-text', value);
413
+ }
414
+
415
+ get releaseText() {
416
+ const t = this.__getTranslations();
417
+ return this.getAttribute('release-text') || t.release;
418
+ }
419
+
420
+ set releaseText(value) {
421
+ this.setAttribute('release-text', value);
422
+ }
423
+
424
+ get refreshingText() {
425
+ const t = this.__getTranslations();
426
+ return this.getAttribute('refreshing-text') || t.refreshing;
427
+ }
428
+
429
+ set refreshingText(value) {
430
+ this.setAttribute('refreshing-text', value);
431
+ }
432
+
433
+ get disabled() {
434
+ return this.hasAttribute('disabled');
435
+ }
436
+
437
+ set disabled(value) {
438
+ if (value) {
439
+ this.setAttribute('disabled', '');
440
+ } else {
441
+ this.removeAttribute('disabled');
442
+ }
443
+ }
444
+
445
+ get disableSelection() {
446
+ return this.hasAttribute('disable-selection');
447
+ }
448
+
449
+ set disableSelection(value) {
450
+ if (value) {
451
+ this.setAttribute('disable-selection', '');
452
+ } else {
453
+ this.removeAttribute('disable-selection');
454
+ }
455
+ }
456
+
457
+ // eslint-disable-next-line class-methods-use-this
458
+ get indicatorHeight() {
459
+ return 50; // 3.125rem in pixels (assuming 16px base)
460
+ }
461
+
462
+ static styles = `
463
+ :host {
464
+ display: block;
465
+ position: relative;
466
+ height: 100vh;
467
+ overflow: hidden;
468
+ }
469
+
470
+ :host([pulling][disable-selection]) ::slotted(*) {
471
+ user-select: none;
472
+ -webkit-user-select: none;
473
+ }
474
+
475
+ .ptr-container {
476
+ height: 100%;
477
+ overflow-y: auto;
478
+ -webkit-overflow-scrolling: touch;
479
+ position: relative;
480
+ }
481
+
482
+ .ptr-indicator {
483
+ position: absolute;
484
+ top: 0;
485
+ left: 0;
486
+ right: 0;
487
+ height: var(--ptr-indicator-height, 3.125rem);
488
+ display: flex;
489
+ align-items: center;
490
+ justify-content: center;
491
+ background: var(--ptr-indicator-bg, ButtonFace);
492
+ color: var(--ptr-indicator-color, ButtonText);
493
+ font-size: var(--ptr-indicator-font-size, 0.875rem);
494
+ transform: translateY(-3.125rem);
495
+ transition: transform var(--ptr-transition-duration, 0.2s) ease;
496
+ z-index: 1000;
497
+ user-select: none;
498
+ -webkit-user-select: none;
499
+ }
500
+
501
+ .ptr-indicator.active {
502
+ /* Active state can be styled via CSS parts or custom properties */
503
+ }
504
+
505
+ .ptr-content {
506
+ position: relative;
507
+ }
508
+
509
+ :host([disabled]) .ptr-container {
510
+ touch-action: auto;
511
+ }
512
+ `;
513
+
514
+ render() {
515
+ this.shadowRoot.innerHTML = `
516
+ <style>${PullToRefreshElement.styles}</style>
517
+ <div class="ptr-container">
518
+ <div class="ptr-indicator" role="status" aria-live="assertive">
519
+ <slot name="indicator">${this.indicatorText}</slot>
520
+ </div>
521
+ <div class="ptr-content">
522
+ <slot></slot>
523
+ </div>
524
+ </div>
525
+ `;
526
+
527
+ // Cache DOM references for efficiency
528
+ this._container = this.shadowRoot.querySelector('.ptr-container');
529
+ this._indicator = this.shadowRoot.querySelector('.ptr-indicator');
530
+ }
531
+ }
@@ -0,0 +1,82 @@
1
+ {
2
+ "en": {
3
+ "indicator": "↓ Pull to refresh",
4
+ "release": "↻ Release to refresh",
5
+ "refreshing": "⏳ Refreshing..."
6
+ },
7
+ "zh": {
8
+ "indicator": "↓ 下拉刷新",
9
+ "release": "↻ 释放刷新",
10
+ "refreshing": "⏳ 刷新中..."
11
+ },
12
+ "hi": {
13
+ "indicator": "↓ रीफ्रेश करने के लिए खींचें",
14
+ "release": "↻ रीफ्रेश करने के लिए छोड़ें",
15
+ "refreshing": "⏳ रीफ्रेश हो रहा है..."
16
+ },
17
+ "es": {
18
+ "indicator": "↓ Desliza para actualizar",
19
+ "release": "↻ Suelta para actualizar",
20
+ "refreshing": "⏳ Actualizando..."
21
+ },
22
+ "fr": {
23
+ "indicator": "↓ Tirez pour actualiser",
24
+ "release": "↻ Relâchez pour actualiser",
25
+ "refreshing": "⏳ Actualisation..."
26
+ },
27
+ "ar": {
28
+ "indicator": "↓ اسحب للتحديث",
29
+ "release": "↻ حرر للتحديث",
30
+ "refreshing": "⏳ جارٍ التحديث..."
31
+ },
32
+ "bn": {
33
+ "indicator": "↓ রিফ্রেশ করতে টানুন",
34
+ "release": "↻ রিফ্রেশ করতে ছেড়ে দিন",
35
+ "refreshing": "⏳ রিফ্রেশ হচ্ছে..."
36
+ },
37
+ "pt": {
38
+ "indicator": "↓ Puxe para atualizar",
39
+ "release": "↻ Solte para atualizar",
40
+ "refreshing": "⏳ Atualizando..."
41
+ },
42
+ "ru": {
43
+ "indicator": "↓ Потяните для обновления",
44
+ "release": "↻ Отпустите для обновления",
45
+ "refreshing": "⏳ Обновление..."
46
+ },
47
+ "ja": {
48
+ "indicator": "↓ 引っ張って更新",
49
+ "release": "↻ 離して更新",
50
+ "refreshing": "⏳ 更新中..."
51
+ },
52
+ "de": {
53
+ "indicator": "↓ Zum Aktualisieren ziehen",
54
+ "release": "↻ Zum Aktualisieren loslassen",
55
+ "refreshing": "⏳ Wird aktualisiert..."
56
+ },
57
+ "pa": {
58
+ "indicator": "↓ ਤਾਜ਼ਾ ਕਰਨ ਲਈ ਖਿੱਚੋ",
59
+ "release": "↻ ਤਾਜ਼ਾ ਕਰਨ ਲਈ ਛੱਡੋ",
60
+ "refreshing": "⏳ ਤਾਜ਼ਾ ਹੋ ਰਿਹਾ ਹੈ..."
61
+ },
62
+ "jv": {
63
+ "indicator": "↓ Tarik kanggo nyegerake",
64
+ "release": "↻ Selehake kanggo nyegerake",
65
+ "refreshing": "⏳ Lagi nyegerake..."
66
+ },
67
+ "ko": {
68
+ "indicator": "↓ 당겨서 새로고침",
69
+ "release": "↻ 놓아서 새로고침",
70
+ "refreshing": "⏳ 새로고침 중..."
71
+ },
72
+ "vi": {
73
+ "indicator": "↓ Kéo để làm mới",
74
+ "release": "↻ Thả để làm mới",
75
+ "refreshing": "⏳ Đang làm mới..."
76
+ },
77
+ "it": {
78
+ "indicator": "↓ Trascina per aggiornare",
79
+ "release": "↻ Rilascia per aggiornare",
80
+ "refreshing": "⏳ Aggiornamento..."
81
+ }
82
+ }