@aarongustafson/pull-to-refresh 1.1.2 → 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.
package/README.md CHANGED
@@ -1,48 +1,38 @@
1
1
  # Pull to Refresh Web Component
2
2
 
3
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)
4
+ [![CI status](https://img.shields.io/github/actions/workflow/status/aarongustafson/pull-to-refresh/ci.yml?branch=main&label=CI)](https://github.com/aarongustafson/pull-to-refresh/actions/workflows/ci.yml)
5
+ [![Minified + gzipped size](https://img.shields.io/bundlejs/size/@aarongustafson/pull-to-refresh?format=minzip&label=min%2Bgzip)](https://bundlejs.com/?q=@aarongustafson/pull-to-refresh)
6
+ [![License](https://img.shields.io/npm/l/@aarongustafson/pull-to-refresh)](https://github.com/aarongustafson/pull-to-refresh/blob/main/LICENSE)
7
+ [![Type definitions](https://img.shields.io/npm/types/@aarongustafson/pull-to-refresh)](https://github.com/aarongustafson/pull-to-refresh/blob/main/pull-to-refresh.d.ts)
5
8
 
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.
9
+ `<pull-to-refresh>` adds a downward pull gesture to scrollable content. At the
10
+ top of its scroll container, pulling past the threshold and releasing fires
11
+ `ptr:refresh`. Your application loads data, updates content, and reports the
12
+ result; the component doesn’t fetch data or reload the page.
7
13
 
8
- ## Demo
14
+ Supply a native Refresh button for keyboard use and a useful no-JavaScript
15
+ alternative. The example below uses a form that reloads the document before
16
+ enhancement or if registration fails. The component doesn’t create a button.
9
17
 
10
- [Live Demo](https://aarongustafson.github.io/pull-to-refresh/demo/) ([Source](./demo/index.html))
18
+ ## Demos
11
19
 
12
- ### Additional Demos
20
+ - [Live demo](https://aarongustafson.github.io/pull-to-refresh/demo/) ([source](./demo/index.html))
21
+ - [esm.sh: manual registration](https://aarongustafson.github.io/pull-to-refresh/demo/esm.html) ([source](./demo/esm.html))
22
+ - [unpkg: automatic registration](https://aarongustafson.github.io/pull-to-refresh/demo/unpkg.html) ([source](./demo/unpkg.html))
13
23
 
14
- - [esm.sh CDN](https://aarongustafson.github.io/pull-to-refresh/demo/esm.html) ([Source](./demo/esm.html)) - Loading from esm.sh
15
- - [unpkg CDN](https://aarongustafson.github.io/pull-to-refresh/demo/unpkg.html) ([Source](./demo/unpkg.html)) - Loading from unpkg
24
+ The live demo covers [a basic handler](https://aarongustafson.github.io/pull-to-refresh/demo/#basic),
25
+ [failure and retry](https://aarongustafson.github.io/pull-to-refresh/demo/#custom-text),
26
+ [selection](https://aarongustafson.github.io/pull-to-refresh/demo/#disable-selection),
27
+ and [translated examples](https://aarongustafson.github.io/pull-to-refresh/demo/#localization).
16
28
 
17
- ## Features
29
+ ## Installation and registration
18
30
 
19
- - **Touch-optimized**: Smooth pull gesture with momentum and feedback
20
- - **Customizable**: Adjust threshold, text, and styling via attributes and CSS custom properties
21
- - **Event-driven**: Rich event API for complete control over the refresh lifecycle
22
- - **Accessible**: Semantic HTML and ARIA-friendly
23
- - **Framework-agnostic**: Works with any framework or vanilla JavaScript
24
- - **Lightweight**: No dependencies, just native Web Components
25
- - **Shadow DOM**: Encapsulated styles that won't leak
26
- - **TypeScript-ready**: Bundled definitions for editors and build tooling
27
-
28
- ## TypeScript & Framework Support
29
-
30
- - Bundled `.d.ts` files describe both `PullToRefreshElement` and `definePullToRefresh`, so modern editors provide autocomplete without extra config.
31
- - Threshold/text/disabled props now reflect to attributes, keeping declarative templates in sync with imperative code.
32
- - `_upgradeProperty` preserves pre-upgrade assignments—handy for SSR, hydration, and framework wrappers.
33
- - Global `HTMLElementTagNameMap` augmentation lets TypeScript understand `document.querySelector('pull-to-refresh')` out of the box.
34
-
35
- ## Quick Start
36
-
37
- ### Installation
38
-
39
- ```bash
31
+ ```sh
40
32
  npm install @aarongustafson/pull-to-refresh
41
33
  ```
42
34
 
43
- ### Usage
44
-
45
- **Option 1: Manual registration**
35
+ The main import exports the class without registering an element:
46
36
 
47
37
  ```javascript
48
38
  import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
@@ -50,14 +40,17 @@ import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
50
40
  customElements.define('pull-to-refresh', PullToRefreshElement);
51
41
  ```
52
42
 
53
- **Option 2: Auto-define (browser environments only)**
43
+ You can register the class under another tag name; update your HTML to match.
44
+
45
+ For automatic registration in a browser, import the guarded helper instead:
54
46
 
55
47
  ```javascript
56
48
  import '@aarongustafson/pull-to-refresh/define.js';
57
- // Registers <pull-to-refresh> when customElements is available
58
49
  ```
59
50
 
60
- Prefer to control when registration happens? Call the helper directly:
51
+ Importing `define.js` also calls `definePullToRefresh()`. The helper skips an
52
+ already registered tag and returns `true` when a registry is available, or
53
+ `false` otherwise. Calling it explicitly doesn’t defer that initial registration:
61
54
 
62
55
  ```javascript
63
56
  import { definePullToRefresh } from '@aarongustafson/pull-to-refresh/define.js';
@@ -65,394 +58,389 @@ import { definePullToRefresh } from '@aarongustafson/pull-to-refresh/define.js';
65
58
  definePullToRefresh();
66
59
  ```
67
60
 
68
- You can also include the guarded script from HTML:
61
+ You can also load `define.js` with a module script:
69
62
 
70
63
  ```html
71
64
  <script
72
- src="./node_modules/@aarongustafson/pull-to-refresh/define.js"
73
65
  type="module"
66
+ src="./node_modules/@aarongustafson/pull-to-refresh/define.js"
74
67
  ></script>
75
68
  ```
76
69
 
77
- ### Basic Example
78
-
79
- ```html
80
- <pull-to-refresh>
81
- <div class="content">
82
- <h1>My Content</h1>
83
- <p>Pull down from the top to refresh!</p>
84
- </div>
85
- </pull-to-refresh>
70
+ The class is also exported from
71
+ `@aarongustafson/pull-to-refresh/pull-to-refresh.js`. Bundled
72
+ [type declarations](./pull-to-refresh.d.ts) describe the public API.
86
73
 
87
- <script type="module">
88
- import '@aarongustafson/pull-to-refresh';
89
-
90
- const ptr = document.querySelector('pull-to-refresh');
91
-
92
- ptr.addEventListener('ptr:refresh', (e) => {
93
- // Perform your refresh logic (fetch data, etc.)
94
- fetch('/api/data')
95
- .then((response) => response.json())
96
- .then((data) => {
97
- // Update your content
98
- updateContent(data);
99
- // Signal completion
100
- e.detail.complete();
101
- });
102
- });
103
- </script>
104
- ```
74
+ ## Basic usage
105
75
 
106
- ## API
107
-
108
- ### Attributes
109
-
110
- | Attribute | Type | Default | Description |
111
- | ------------------- | ------- | ------------- | ------------------------------------------- |
112
- | `threshold` | number | `80` | Distance in pixels to trigger refresh |
113
- | `indicator-text` | string | localized | Text shown when pulling down |
114
- | `release-text` | string | localized | Text shown when ready to release |
115
- | `refreshing-text` | string | localized | Text shown while refreshing |
116
- | `lang` | string | auto-detected | Language code for localization |
117
- | `disabled` | boolean | `false` | Disables pull-to-refresh functionality |
118
- | `disable-selection` | boolean | `false` | Prevents text selection during pull gesture |
119
-
120
- **Note:** The text attributes use automatic localization based on the `lang` attribute or auto-detection. See [Localization](#-localization-i18n) below.
121
-
122
- ### Properties
123
-
124
- All attributes are also available as properties:
125
-
126
- ```javascript
127
- const ptr = document.querySelector('pull-to-refresh');
128
- ptr.threshold = 120;
129
- ptr.indicatorText = 'Swipe down';
130
- ptr.disabled = true;
131
- ```
132
-
133
- ### Events
134
-
135
- | Event | Detail | Description |
136
- | ---------------------- | ------------------------ | ------------------------------- |
137
- | `ptr:pull-start` | `{}` | Fired when pull gesture starts |
138
- | `ptr:pull-move` | `{ distance: number }` | Fired during pull gesture |
139
- | `ptr:pull-end` | `{}` | Fired when pull gesture ends |
140
- | `ptr:refresh` | `{ complete: Function }` | Fired when refresh is triggered |
141
- | `ptr:refresh-complete` | `{}` | Fired when refresh completes |
142
-
143
- **Important**: Call `event.detail.complete()` in your `ptr:refresh` handler to signal completion:
144
-
145
- ```javascript
146
- ptr.addEventListener('ptr:refresh', (e) => {
147
- doAsyncWork().then(() => {
148
- e.detail.complete(); // Call this when done
149
- });
150
- });
151
- ```
152
-
153
- If you don't call `complete()`, the component will auto-complete after 2 seconds.
154
-
155
- ### Slots
156
-
157
- | Slot | Description |
158
- | ----------- | --------------------------------- |
159
- | (default) | Your scrollable content |
160
- | `indicator` | Optional custom indicator element |
161
-
162
- ### CSS Custom Properties
163
-
164
- | Property | Default | Description |
165
- | --------------------------- | ------------ | --------------------------------- |
166
- | `--ptr-indicator-height` | `3.125rem` | Height of the indicator area |
167
- | `--ptr-indicator-bg` | `ButtonFace` | Background color of indicator |
168
- | `--ptr-indicator-color` | `ButtonText` | Text color of indicator |
169
- | `--ptr-indicator-font-size` | `0.875rem` | Font size of indicator text |
170
- | `--ptr-transition-duration` | `0.2s` | Duration of indicator transitions |
171
-
172
- ### Methods
173
-
174
- | Method | Description |
175
- | ------------------- | -------------------------------------------------------------------------------- |
176
- | `completeRefresh()` | Manually complete the refresh (alternative to calling `event.detail.complete()`) |
177
-
178
- ## Examples
179
-
180
- ### Custom Threshold
181
-
182
- ```html
183
- <pull-to-refresh threshold="120">
184
- <div>Content here</div>
185
- </pull-to-refresh>
186
- ```
187
-
188
- ### Localization
189
-
190
- The component automatically detects the language and displays localized text:
76
+ This complete example generates a number locally, so it doesn’t need an API.
77
+ Serve it over HTTP with the installed package at the path shown. Replace the
78
+ delayed update with your application’s work.
191
79
 
192
80
  ```html
193
- <!-- Spanish -->
194
- <pull-to-refresh lang="es">
195
- <div>Contenido aquí</div>
196
- </pull-to-refresh>
197
-
198
- <!-- French -->
199
- <pull-to-refresh lang="fr">
200
- <div>Contenu ici</div>
201
- </pull-to-refresh>
202
-
203
- <!-- Japanese -->
204
- <pull-to-refresh lang="ja">
205
- <div>ここにコンテンツ</div>
81
+ <pull-to-refresh id="refresh-content">
82
+ <h2>Latest number</h2>
83
+ <p>Number: <span id="number">0</span></p>
84
+ <p id="refresh-status" role="status">Ready</p>
85
+ <form id="refresh-form">
86
+ <button type="submit">Refresh</button>
87
+ </form>
206
88
  </pull-to-refresh>
207
- ```
208
89
 
209
- The component supports 16 languages with automatic fallback to English. Language is detected from:
210
-
211
- 1. The element's `lang` attribute
212
- 2. The nearest ancestor's `lang` attribute
213
- 3. The document's `lang` attribute
214
- 4. Default: English
90
+ <script type="module">
91
+ import './node_modules/@aarongustafson/pull-to-refresh/define.js';
215
92
 
216
- You can also register custom translations:
93
+ const component = document.getElementById('refresh-content');
94
+ const number = document.getElementById('number');
95
+ const status = document.getElementById('refresh-status');
96
+ const form = document.getElementById('refresh-form');
97
+ let pending = false;
217
98
 
218
- ```javascript
219
- import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
99
+ form.addEventListener('submit', (event) => {
100
+ event.preventDefault();
101
+ if (!pending) component.triggerRefresh();
102
+ });
220
103
 
221
- PullToRefreshElement.registerTranslations({
222
- 'pt-BR': {
223
- indicator: '↓ Puxe para atualizar',
224
- release: '↻ Solte para atualizar',
225
- refreshing: '⏳ Atualizando...',
226
- },
227
- });
104
+ component.addEventListener('ptr:refresh', async (event) => {
105
+ if (pending) {
106
+ event.detail.complete();
107
+ return;
108
+ }
109
+ pending = true;
110
+ status.textContent = 'Refreshing...';
111
+ try {
112
+ await new Promise((resolve) => setTimeout(resolve, 1500));
113
+ const nextNumber = Math.floor(Math.random() * 1000);
114
+ number.textContent = nextNumber;
115
+ status.textContent = 'Complete! Use Refresh or pull again.';
116
+ } catch {
117
+ status.textContent =
118
+ 'Refresh failed. Your previous number is unchanged. Use Refresh to try again.';
119
+ } finally {
120
+ pending = false;
121
+ event.detail.complete();
122
+ }
123
+ });
124
+ </script>
228
125
  ```
229
126
 
230
- ### Custom Styling
231
-
232
- ```html
233
- <style>
234
- pull-to-refresh {
235
- --ptr-indicator-bg: #102030;
236
- --ptr-indicator-color: #ffffff;
237
- --ptr-indicator-font-size: 1rem;
238
- --ptr-indicator-height: 3.75rem;
239
- }
240
- </style>
127
+ The handler leaves the previous number visible while loading and on failure.
128
+ The button stays available and focus stays where the user left it. Translate
129
+ the button and application status messages alongside your content.
130
+
131
+ For a network update, check `response.ok`, validate the response, and prepare
132
+ the new content before replacing the existing data. Use `textContent` for
133
+ untrusted text. Report failures visibly and provide a retry action.
134
+
135
+ ## Behavior and completion
136
+
137
+ - The host defaults to `height: 100vh`, with an internal vertical scroll
138
+ container. Set the host’s height to fit your layout.
139
+ - A downward movement greater than 5 pixels confirms a pull. Release must
140
+ exceed `threshold` to trigger refresh; matching it exactly isn’t enough.
141
+ - A browser `pointercancel` abandons the pull, restores selection and the
142
+ resting indicator, and emits `ptr:pull-end`. It never starts a refresh or
143
+ emits `ptr:refresh-complete` for the canceled gesture, even beyond threshold.
144
+ - `disabled` removes gesture listeners and resets the indicator. It doesn’t
145
+ disable your button or prevent a direct `triggerRefresh()` call.
146
+ - `disable-selection` suppresses selection on slotted content during a
147
+ confirmed pull. Release removes the `pulling` attribute and restores
148
+ selection styling. Removing `disable-selection` also removes `pulling`.
149
+ - Without upgrade, authored content and forms remain ordinary HTML.
150
+ - On disconnect, the component removes its gesture/scroll listeners and
151
+ clears its timers and interaction state. Pending completion callbacks become
152
+ inactive, without a completion event. It doesn’t cancel your application’s
153
+ work; cancel or guard your own pending updates when removing the component.
154
+
155
+ Call `event.detail.complete()` in `finally` for both success and failure.
156
+ Each callback belongs to the action that supplied it. Repeated calls and
157
+ callbacks from older actions do nothing. `completeRefresh()` instead completes
158
+ whichever action is current. Either path ends that action and fires
159
+ `ptr:refresh-complete` once; neither means the data update succeeded.
160
+
161
+ By default, the component schedules automatic completion **two seconds after
162
+ dispatching `ptr:refresh`**, even when a listener is still working. That timer does not wait
163
+ for a promise returned by your handler. `triggerRefresh()`’s returned promise
164
+ also doesn’t await your work. Keep application loading and outcome messages
165
+ separate from `ptr:refresh-complete`, and guard overlapping work.
166
+
167
+ Set `refresh-timeout="0"` (or `component.refreshTimeout = 0`) to keep the
168
+ interaction refreshing until explicit completion. Always call the event’s
169
+ `complete()` callback in `finally`, and provide application-owned error and
170
+ retry feedback. Removing the component also cancels its interaction, not the
171
+ underlying request. A positive `refresh-timeout` sets a different delay in
172
+ milliseconds. The component captures the delay before dispatching each refresh
173
+ event; changes apply to the next action, not an already running one.
174
+
175
+ ## Attributes and properties
176
+
177
+ Property setters reflect their corresponding attributes. Pre-upgrade property
178
+ assignments are preserved.
179
+
180
+ | Attribute | Property | Default | Behavior |
181
+ | -------------------- | ------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
182
+ | `threshold` | `threshold` | `80` | Pull distance in pixels. Invalid or negative values remove the attribute and restore the default. Attribute reads use integer parsing; the setter rounds valid numbers. |
183
+ | `refresh-timeout` | `refreshTimeout` | `2000` | Automatic completion delay in integer milliseconds, from 0 to 2147483647. Zero requires explicit completion. Changes affect the next action. |
184
+ | `indicator-message` | `indicatorMessage` | `null` | Authored message while pulling; a nonempty value overrides other sources. |
185
+ | `release-message` | `releaseMessage` | `null` | Authored message beyond the threshold. |
186
+ | `refreshing-message` | `refreshingMessage` | `null` | Authored message while the interaction is refreshing. |
187
+ | `indicator-text` | `indicatorText` | Localized | Deprecated override while pulling; retained for migration. |
188
+ | `release-text` | `releaseText` | Localized | Deprecated override beyond the threshold; retained for migration. |
189
+ | `refreshing-text` | `refreshingText` | Localized | Deprecated override while refreshing; retained for migration. |
190
+ | `lang` | `lang` | Inherited or `en` | Language used to select indicator messages. |
191
+ | `disabled` | `disabled` | `false` | Boolean attribute; presence disables gesture listeners. |
192
+ | `disable-selection` | `disableSelection` | `false` | Boolean attribute; presence suppresses selection during a confirmed pull. |
193
+
194
+ The new message properties return the authored attribute value (`string | null`),
195
+ not the resolved message. Assigning a string reflects it to the attribute;
196
+ assigning `null` or `undefined` removes it. Supply nonempty, complete literal
197
+ strings. The component doesn’t interpolate tokens or insert data into messages;
198
+ any braces remain literal text.
199
+ Empty or whitespace-only message values are invalid; remove the attribute to
200
+ use the next source.
201
+
202
+ The legacy `indicatorText`, `releaseText`, and `refreshingText` getters return
203
+ the resolved, last-working effective messages, not their authored attributes.
204
+ Invalid configuration leaves those returned messages unchanged.
205
+ Set legacy text properties to `null` or `undefined` to remove an override.
206
+ Empty legacy text attributes also fall through. Set `threshold` to `null`,
207
+ `undefined`, or `''` to restore its default.
208
+ See [Localization](#localization-i18n) for message precedence and language selection.
209
+
210
+ `refreshTimeout` returns the effective numeric delay. Set it to `null` or
211
+ `undefined` to restore the default. Invalid property assignments throw
212
+ `RangeError` without changing the existing value. Invalid attributes, including
213
+ empty values, log an error and are removed, restoring the default.
214
+
215
+ ## Interaction state
216
+
217
+ `isRefreshing` is an observation-only boolean. It starts as `false`, including
218
+ before connection, and stays false while pulling. An accepted refresh sets it
219
+ to `true` before dispatching `ptr:refresh`. Completion sets it to `false` before
220
+ `ptr:refresh-complete`; disconnect cancels the interaction and sets it to false
221
+ without a completion event. Reconnecting starts idle.
222
+
223
+ This state describes the component’s interaction, not your application’s
224
+ loading, progress, failure, or success. With automatic completion enabled, it
225
+ can become false while your request is still pending. Keep application state
226
+ and error/retry feedback separate.
227
+
228
+ TypeScript declares `isRefreshing` as `readonly`. The existing runtime field
229
+ remains writable for compatibility, but assigning it bypasses timers, indicator
230
+ updates, and events. Use `triggerRefresh()`, `completeRefresh()`, or the event’s
231
+ completion callback instead. The existing `isPulling`, `isPullingConfirmed`,
232
+ `currentY`, and `startY` fields remain untouched implementation details, not
233
+ additional supported state APIs.
234
+
235
+ ## Methods and events
236
+
237
+ | Method | Behavior |
238
+ | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
239
+ | `triggerRefresh()` | Starts a connected, idle interaction and dispatches `ptr:refresh`. Does nothing while disconnected or already refreshing. Works independently of `disabled`; doesn’t wait for application work. |
240
+ | `completeRefresh()` | Ends the current interaction once, resets the indicator, clears the timer, and dispatches `ptr:refresh-complete`. Does nothing when idle. |
241
+ | `refreshMessages(): boolean` | Rereads shared configuration and resolves messages for this connected instance. Returns `false` when disconnected or when configuration is invalid. See [Localization](#localization-i18n). |
242
+ | `PullToRefreshElement.registerTranslations(translations)` | Deprecated. Adds or replaces whole base-language entries for indicator messages. |
243
+
244
+ The established `ptr:*` namespace is retained for compatibility. There are no
245
+ `pull-to-refresh:*` aliases, so one action doesn’t notify two sets of listeners.
246
+ Alternate registration tags use the same event names.
247
+
248
+ All five events are dispatched synchronously on the host with `bubbles: true`,
249
+ `composed: true`, and `cancelable: false`. They support delegation across an
250
+ enclosing shadow root. `preventDefault()` does not stop a pull or refresh.
251
+ Initialization and message/configuration changes do not emit these events.
252
+
253
+ | Event | Detail | Timing and frequency |
254
+ | ---------------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
255
+ | `ptr:pull-start` | `null` | Once when downward movement greater than 5 pixels confirms a pull, before that move updates the indicator. |
256
+ | `ptr:pull-move` | `{ distance: number }` | On each confirmed positive-distance move, after indicator position and text update. Distance is a snapshot in CSS pixels, not a live state object. |
257
+ | `ptr:pull-end` | `null` | When an active pointer ends or is canceled, even if the pull was unconfirmed or below threshold. Pulling is already false; refresh/reset and distance cleanup follow dispatch. Cancellation only resets; it never triggers refresh. |
258
+ | `ptr:refresh` | `{ complete: () => void }` | A gesture or `triggerRefresh()` starts an interaction, after refreshing state and indicator text update. See [completion behavior](#behavior-and-completion). |
259
+ | `ptr:refresh-complete` | `null` | Explicit or automatic completion, after refreshing state is false and the indicator has reset. This is not a data-success notification. |
260
+
261
+ TypeScript infers event details for `addEventListener()` and
262
+ `removeEventListener()`, including when importing only `define.js`. The exported
263
+ `PullToRefreshEventMap`, `PullToRefreshPullMoveDetail`, and
264
+ `PullToRefreshRefreshDetail` types describe the same contract. Native events
265
+ such as `keydown` retain their usual types; application-defined event names
266
+ remain supported.
267
+
268
+ `indicatorHeight` returns the indicator’s current rendered height in CSS pixels
269
+ (zero before rendering or when it has no layout). Gesture positioning measures
270
+ its untransformed layout height once at the start of each pull, not on every
271
+ move, so scaled ancestors don’t distort local CSS offsets. Height changes during a
272
+ pull apply to the next gesture; the resting position follows its CSS height
273
+ automatically, including font-size changes.
241
274
 
242
- <pull-to-refresh>
243
- <div>Content here</div>
244
- </pull-to-refresh>
245
- ```
275
+ ## Localization (i18n)
246
276
 
247
- The indicator defaults to `ButtonText` on `ButtonFace`. Set
248
- `--ptr-indicator-bg` and `--ptr-indicator-color` together; changing one can
249
- make the other unreadable. Custom properties override these defaults and
250
- inherit from the host. A custom slotted indicator supplies its own markup
251
- and styles. Test your complete pair, including nested text, in each supported
252
- scheme and user palette. Automatic forced-color adjustment remains enabled.
253
- The indicator uses different authored or localized messages for pulling,
254
- release, and loading, rather than color alone.
255
-
256
- The demos use `CanvasText` on `Canvas` for reading surfaces and status
257
- messages, `ButtonText` on `ButtonFace` for code and buttons, and
258
- `MarkText` on `Mark` for marked examples. They preserve native keyboard focus.
259
- Each standalone demo includes a native Refresh form: enhancement runs the
260
- existing refresh handler; without JavaScript or a successful module load,
261
- the form reloads the document. The component does not generate a keyboard
262
- button. Supply one for tasks that must not depend on a pull gesture.
263
- Keep existing data visible during loading or failure, provide a readable
264
- error and retry action, and call `event.detail.complete()` when your handler
265
- finishes. Completion reports the end of the interaction, not success.
266
-
267
- Recorded-palette substitution and browser emulation are regression checks,
268
- not proof of native high-contrast repainting or assistive-technology support.
269
- The recorded study’s 19 distinct palettes pass the tested demo pairs; bundled
270
- Ubuntu WebKit has a known dark `ButtonText`/`ButtonFace` contrast limitation
271
- outside that dataset. The browser suite tracks it as a narrowly scoped expected
272
- failure instead of replacing every platform’s native pair.
273
-
274
- ### Custom Messages
277
+ Use message attributes to match your application’s vocabulary before adding
278
+ translations:
275
279
 
276
280
  ```html
277
281
  <pull-to-refresh
278
- indicator-text="⬇ Swipe down"
279
- release-text="🔄 Let go!"
280
- refreshing-text="⏳ Loading..."
282
+ indicator-message="↓ Pull to check for updates"
283
+ release-message="↻ Release to check"
284
+ refreshing-message="⏳ Checking for updates..."
281
285
  >
282
- <div>Content here</div>
286
+ <!-- Your content and native Refresh form -->
283
287
  </pull-to-refresh>
284
288
  ```
285
289
 
286
- ### With Fetch API
290
+ ### Shared document defaults
287
291
 
288
- ```javascript
289
- ptr.addEventListener('ptr:refresh', async (e) => {
290
- try {
291
- const response = await fetch('/api/latest');
292
- const data = await response.json();
293
- renderData(data);
294
- } catch (error) {
295
- console.error('Refresh failed:', error);
296
- } finally {
297
- e.detail.complete();
298
- }
299
- });
300
- ```
301
-
302
- ### Disabled State
292
+ Add one inline JSON script before the components connect to share messages
293
+ throughout that document:
303
294
 
304
295
  ```html
305
- <!-- Disable pull-to-refresh when needed -->
306
- <pull-to-refresh disabled>
307
- <div>No refresh available</div>
308
- </pull-to-refresh>
309
-
310
- <script>
311
- // Or toggle programmatically
312
- ptr.disabled = true;
296
+ <script type="application/json" data-pull-to-refresh-config>
297
+ {
298
+ "indicator-message": "↓ Pull to check for updates",
299
+ "release-message": "↻ Release to check",
300
+ "refreshing-message": "⏳ Checking for updates..."
301
+ }
313
302
  </script>
314
303
  ```
315
304
 
316
- ### Tracking Pull Distance
317
-
318
- ```javascript
319
- ptr.addEventListener('ptr:pull-move', (e) => {
320
- console.log('Pull distance:', e.detail.distance);
321
- // Use this for custom animations, etc.
322
- });
323
- ```
324
-
325
- ## Localization (i18n)
326
-
327
- The component includes built-in translations for **16 languages**:
328
-
329
- | Language | Code | Indicator Text |
330
- | ------------------ | ---- | ---------------------------- |
331
- | English | `en` | ↓ Pull to refresh |
332
- | Chinese (Mandarin) | `zh` | ↓ 下拉刷新 |
333
- | Hindi | `hi` | ↓ रीफ्रेश करने के लिए खींचें |
334
- | Spanish | `es` | ↓ Desliza para actualizar |
335
- | French | `fr` | ↓ Tirez pour actualiser |
336
- | Arabic | `ar` | ↓ اسحب للتحديث |
337
- | Bengali | `bn` | ↓ রিফ্রেশ করতে টানুন |
338
- | Portuguese | `pt` | ↓ Puxe para atualizar |
339
- | Russian | `ru` | ↓ Потяните для обновления |
340
- | Japanese | `ja` | ↓ 引っ張って更新 |
341
- | German | `de` | ↓ Zum Aktualisieren ziehen |
342
- | Punjabi | `pa` | ↓ ਤਾਜ਼ਾ ਕਰਨ ਲਈ ਖਿੱਚੋ |
343
- | Javanese | `jv` | ↓ Tarik kanggo nyegerake |
344
- | Korean | `ko` | ↓ 당겨서 새로고침 |
345
- | Vietnamese | `vi` | ↓ Kéo để làm mới |
346
- | Italian | `it` | ↓ Trascina per aggiornare |
347
-
348
- ### Language Detection
349
-
350
- The component uses a cascading fallback approach:
351
-
352
- 1. Element's `lang` attribute: `&lt;pull-to-refresh lang="es"&gt;`
353
- 2. Nearest ancestor with `lang`: `&lt;div lang="fr"&gt;&lt;pull-to-refresh&gt;`
354
- 3. Document language: `&lt;html lang="de"&gt;`
355
- 4. Default: English (en)
356
-
357
- Regional variants (e.g., `en-US`, `es-MX`, `fr-CA`) automatically fall back to their base language.
358
-
359
- ### Custom Translations
360
-
361
- Register custom translations or override existing ones:
305
+ Keep the `data-pull-to-refresh-config` marker empty. The JSON must be an object
306
+ containing only `indicator-message`, `release-message`, and
307
+ `refreshing-message`; each supplied value
308
+ must be a nonempty string. You can omit keys to use the fallback for those
309
+ messages. Don’t add language dictionaries, scopes, a `src`, or multiple
310
+ configuration scripts. Shared defaults apply regardless of an instance’s
311
+ language; each embedded document needs its own configuration.
312
+
313
+ The component resolves each message separately, in this order:
314
+
315
+ 1. An instance `*-message` attribute containing a valid message
316
+ 2. A nonempty legacy instance `*-text` attribute
317
+ 3. A shared document JSON string
318
+ 4. A registered base-language key
319
+ 5. A bundled base-language key
320
+ 6. The English message
321
+
322
+ After changing the JSON, call `component.refreshMessages()` on each connected
323
+ instance that needs the new messages. The method returns `true` on success.
324
+ It returns `false` when the instance is disconnected. Invalid configuration
325
+ also returns `false`, reports the failure with `console.error`, and retains the
326
+ entire last valid message set without partial updates. If shared or instance
327
+ configuration is invalid on initial connection, the component logs the failure,
328
+ keeps its initial English messages, and still enhances the native content.
329
+ Correct the configuration and call `refreshMessages()` to recover.
330
+ It doesn’t start or complete a refresh, dispatch events, move focus, or change
331
+ interaction state.
332
+
333
+ ### Language fallback and legacy migration
334
+
335
+ Language selection uses the first nonempty value from the element’s `lang`,
336
+ `closest('[lang]')`, the document language, and then `en`. The closest match
337
+ includes the element itself: an empty `lang` on the element or its nearest
338
+ matching ancestor falls through to the document language, not a more distant
339
+ ancestor. The component resolves inherited
340
+ language when it connects; changing an ancestor’s language alone doesn’t update
341
+ an already connected indicator. Changing the element’s `lang` or calling
342
+ `refreshMessages()` resolves the language again.
343
+ Regional codes such as `es-MX` use their base language. Unknown codes fall back
344
+ to English. See [translations.json](./translations.json) for the built-in
345
+ messages and supported codes.
346
+
347
+ The built-in catalogs, `registerTranslations()`, and the existing `*-text`
348
+ attributes and properties are deprecated but retained. They emit no deprecation
349
+ warnings; removal is reserved for a future major version. For new code, use
350
+ instance messages and shared document defaults. Rename `indicator-text`,
351
+ `release-text`, and `refreshing-text` to their `*-message` equivalents, keeping
352
+ the complete strings.
353
+
354
+ If you still use registered catalogs, register them before the elements connect:
362
355
 
363
356
  ```javascript
364
357
  import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
365
358
 
366
- // Add a new language
367
- PullToRefreshElement.registerTranslations({
368
- nl: {
369
- indicator: '↓ Trek om te vernieuwen',
370
- release: '↻ Loslaten om te vernieuwen',
371
- refreshing: '⏳ Vernieuwen...',
372
- },
373
- });
374
-
375
- // Override existing translations
376
359
  PullToRefreshElement.registerTranslations({
377
360
  en: {
378
- indicator: '⬇ Pull down',
379
- release: '🔄 Let go',
380
- refreshing: '⏳ Loading...',
361
+ indicator: '↓ Pull to check for updates',
362
+ release: '↻ Release to check',
363
+ refreshing: '⏳ Checking for updates...',
381
364
  },
382
365
  });
383
- ```
384
-
385
- ### Per-Instance Overrides
386
-
387
- You can always override translations for individual instances:
388
-
389
- ```html
390
- <pull-to-refresh
391
- lang="es"
392
- indicator-text="Custom Spanish text"
393
- release-text="Custom release text"
394
- >
395
- <!-- Content -->
396
- </pull-to-refresh>
397
- ```
398
-
399
- ## Testing
400
-
401
- ```bash
402
- npm test # Run tests in watch mode
403
- npm run test:run # Run tests once
404
- npm run test:ui # Open Vitest UI
405
- npm run test:coverage # Generate coverage report
406
- ```
407
-
408
- ## Development
409
366
 
410
- ```bash
411
- npm install # Install dependencies
412
- npm run setup # Run setup wizard (first time)
413
- npm run lint # Lint code
414
- npm run format # Format code
367
+ customElements.define('pull-to-refresh', PullToRefreshElement);
415
368
  ```
416
369
 
417
- ## Browser Support
418
-
419
- Works in all modern browsers supporting:
370
+ Registration replaces whole base-language entries; it doesn’t merge a new
371
+ entry with the previously registered one. A missing key falls back to the
372
+ bundled base-language key, then English. Register base codes such as `pt`, not
373
+ `pt-BR`, because lookup uses the base code. Registration alone doesn’t redraw
374
+ connected indicators; call `refreshMessages()` after registering to update them.
420
375
 
421
- - Custom Elements v1
422
- - Shadow DOM v1
423
- - ES Modules
424
- - Pointer Events
376
+ Only the indicator messages are translated by the component. Authors translate
377
+ content, buttons, loading messages, errors, and retry instructions. The
378
+ [Spanish, French, and Japanese demos](./demo/index.html#localization) show
379
+ authored instance messages and shared defaults in embedded documents.
425
380
 
426
- For legacy browsers, use appropriate polyfills.
381
+ ## Styling
427
382
 
428
- ## Package Exports
383
+ | Custom property | Default | Purpose |
384
+ | --------------------------- | ------------ | ------------------------------------------------------------- |
385
+ | `--ptr-indicator-height` | `3.125rem` | Indicator area height, measured at the start of each gesture. |
386
+ | `--ptr-indicator-bg` | `ButtonFace` | Indicator background. |
387
+ | `--ptr-indicator-color` | `ButtonText` | Indicator foreground. |
388
+ | `--ptr-indicator-font-size` | `0.875rem` | Indicator text size. |
389
+ | `--ptr-transition-duration` | `0.2s` | Indicator transition duration. |
429
390
 
430
- ```javascript
431
- // Auto-define
432
- import '@aarongustafson/pull-to-refresh';
433
-
434
- // Class only
435
- import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh/pull-to-refresh.js';
391
+ Set foreground and background together:
436
392
 
437
- // Both
438
- import { PullToRefreshElement } from '@aarongustafson/pull-to-refresh';
393
+ ```css
394
+ pull-to-refresh {
395
+ --ptr-indicator-bg: #102030;
396
+ --ptr-indicator-color: #ffffff;
397
+ }
439
398
 
440
- // Manual define script
441
- import '@aarongustafson/pull-to-refresh/define.js';
399
+ @media (prefers-reduced-motion: reduce) {
400
+ pull-to-refresh {
401
+ --ptr-transition-duration: 0s;
402
+ }
403
+ }
442
404
  ```
443
405
 
444
- ## Contributing
406
+ Test the pair in light, dark, and user-selected palettes. Automatic forced-color
407
+ adjustment remains enabled. Messages distinguish pulling, release, and loading
408
+ without relying on color alone.
409
+
410
+ The default slot holds your content. The optional `indicator` slot replaces the
411
+ default message with authored markup and styles; your application must update
412
+ that custom indicator’s state text. There are no exposed CSS parts.
413
+
414
+ ## Accessibility and compatibility
415
+
416
+ The indicator uses `role="status"` with assertive live announcements; the
417
+ component temporarily turns announcements off while resetting it. Supply a
418
+ separate visible application status, preserve existing data on failure, and
419
+ keep a native Refresh action. The gesture alone isn’t a keyboard alternative.
420
+ Test focus, announcements, touch scrolling, and browser pull-to-refresh behavior
421
+ on the devices and assistive technologies your application supports.
422
+
423
+ The runtime uses Custom Elements, Shadow DOM, modules with JSON import
424
+ attributes, and Pointer Events. If registration cannot load, the authored
425
+ content and native form remain available. Browser emulation and the recorded
426
+ palette checks aren’t proof of native high-contrast repainting or screen-reader
427
+ behavior. The browser suite tracks a known Ubuntu WebKit dark
428
+ `ButtonText`/`ButtonFace` contrast limitation as an expected failure.
429
+
430
+ ## Development and testing
431
+
432
+ ```sh
433
+ npm install
434
+ npm run lint
435
+ npm run format
436
+ npm run test:run
437
+ npm run test:browser
438
+ ```
445
439
 
446
- Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
440
+ `npm test` runs watch mode; `npm run test:ui` opens the Vitest UI, and
441
+ `npm run test:coverage` collects coverage. See [CONTRIBUTING.md](./CONTRIBUTING.md)
442
+ for contributor guidance and [the demo guide](./demo/README.md) for ownership.
447
443
 
448
444
  ## License
449
445
 
450
- MIT - See [LICENSE](LICENSE)
451
-
452
- ## Credits
453
-
454
- Created by [Aaron Gustafson](https://github.com/aarongustafson)
455
-
456
- ---
457
-
458
- **Try it out!** Check out the [live demo](https://aarongustafson.github.io/pull-to-refresh/demo/index.html) 🚀
446
+ MIT — see [LICENSE](./LICENSE).