@wcstack/timer 1.15.0 → 1.17.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.ja.md +49 -0
- package/README.md +51 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.esm.js +53 -0
- package/dist/index.esm.js.map +1 -1
- package/dist/index.esm.min.js +1 -1
- package/dist/index.esm.min.js.map +1 -1
- package/package.json +1 -1
package/README.ja.md
CHANGED
|
@@ -135,6 +135,55 @@ npm install @wcstack/timer
|
|
|
135
135
|
|
|
136
136
|
イベント委譲を使うため動的に追加された要素でも動作し、`closest()` によりネストした要素(ボタン内のアイコンなど)にも対応します。一致したクリックは `start()` の前に `event.preventDefault()` を呼ぶため、要素の既定動作は抑制されます。既定動作も必要な要素(実際の `<a href>` リンクや form 送信ボタンなど)には `data-timertarget` を付けないでください(キャンセルされます)。
|
|
137
137
|
|
|
138
|
+
## `:state()` による CSS スタイリング
|
|
139
|
+
|
|
140
|
+
`<wcs-timer>` は 1 つの boolean 出力ステートを
|
|
141
|
+
[`ElementInternals` の `CustomStateSet`](https://developer.mozilla.org/ja/docs/Web/API/CustomStateSet)
|
|
142
|
+
に反映します。そのため `data-wcs` バインディングやクラスの手動トグルなしに、CSS の
|
|
143
|
+
`:state()` 疑似クラスで直接スタイリングできます。
|
|
144
|
+
|
|
145
|
+
| ステート | on になる条件 |
|
|
146
|
+
|----------|----------------|
|
|
147
|
+
| `running` | `wcs-timer:running-changed` が `true` で発火(`false` でクリア) |
|
|
148
|
+
|
|
149
|
+
`<wcs-timer>` には `error` イベントが無いため、`error` ステートは反映されません。
|
|
150
|
+
|
|
151
|
+
```css
|
|
152
|
+
wcs-timer:state(running) ~ .indicator { color: green; }
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
属性やクラスと異なり `:state()` は要素の外部から書き込めないため、この出力ステートが
|
|
156
|
+
入力と混同される心配がありません。
|
|
157
|
+
|
|
158
|
+
**対応ブラウザ**(新構文 `:state(x)`): Chrome/Edge 125+、Safari 17.4+、Firefox 126+。
|
|
159
|
+
非対応の環境ではステートが一切 set されないだけです — `:state()` セレクタがマッチしなく
|
|
160
|
+
なりますが、`<wcs-timer>` 自体は通常どおり動作し続けます(graceful degradation・never-throw)。
|
|
161
|
+
|
|
162
|
+
**SSR:** `:state()` は HTML にシリアライズできないため、サーバーレンダリングされた
|
|
163
|
+
マークアップの初期ペイントにはこれらのステートは乗りません(`@wcstack/server` は無改変)。
|
|
164
|
+
ハイドレーション前の見た目を制御したい場合は、代わりに `wcs-timer:not(:defined)` と組み合わせてください。
|
|
165
|
+
|
|
166
|
+
### デバッグ
|
|
167
|
+
|
|
168
|
+
カスタムステートは DevTools の Elements パネルには表示されず、`attachInternals()`
|
|
169
|
+
は同一要素に 2 回呼べないため、コンソールから直接覗く手段がありません。そのための
|
|
170
|
+
デバッグ専用の補助を 2 つ用意しています:
|
|
171
|
+
|
|
172
|
+
- `el.debugStates` — 現在 on になっているステート名の**スナップショット**配列
|
|
173
|
+
(例: `["running"]`)。`wc-bindable` の一部ではなく(バインド対象ではない)、
|
|
174
|
+
形状も契約として保証されません — デバッグ用途にのみ使ってください。
|
|
175
|
+
- `debug-states` 属性(opt-in・既定 OFF)は、ステート変化を要素の
|
|
176
|
+
`data-wcs-state-running` 属性にミラーします。
|
|
177
|
+
Elements パネルを開いておけば、トグルのたびにハイライトされます:
|
|
178
|
+
|
|
179
|
+
```html
|
|
180
|
+
<wcs-timer interval="1000" debug-states></wcs-timer>
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
**CSS は `data-wcs-state-*` ではなく `:state()` に書いてください。** ミラーされた
|
|
184
|
+
属性は、DevTools を開いた状態でステート変化を可視化するためだけのものであり、
|
|
185
|
+
スタイリング用の正式なフックではありません。
|
|
186
|
+
|
|
138
187
|
## 設定
|
|
139
188
|
|
|
140
189
|
`bootstrapTimer()` が `<wcs-timer>` を登録し、必要に応じて既定値を上書きします。部分的な設定を渡せます。
|
package/README.md
CHANGED
|
@@ -142,6 +142,57 @@ If `autoTrigger` is enabled (default), clicking an element carrying `data-timert
|
|
|
142
142
|
|
|
143
143
|
Event delegation is used, so it also works for dynamically added elements, and `closest()` handles nested targets (e.g. an icon inside the button). A matched click calls `event.preventDefault()` before starting the timer, so the element's default action is suppressed — do not put `data-timertarget` on an element whose default action you also want (a real `<a href>` link, a form-submit button), as it will be cancelled.
|
|
144
144
|
|
|
145
|
+
## CSS styling with `:state()`
|
|
146
|
+
|
|
147
|
+
`<wcs-timer>` reflects one boolean output state onto its
|
|
148
|
+
[`ElementInternals` `CustomStateSet`](https://developer.mozilla.org/en-US/docs/Web/API/CustomStateSet),
|
|
149
|
+
so you can style it directly from CSS with the `:state()` pseudo-class — no
|
|
150
|
+
`data-wcs` binding or extra class toggling required.
|
|
151
|
+
|
|
152
|
+
| State | On when |
|
|
153
|
+
|-------|---------|
|
|
154
|
+
| `running` | `wcs-timer:running-changed` fires with `true` (cleared on `false`) |
|
|
155
|
+
|
|
156
|
+
`<wcs-timer>` has no `error` event, so no `error` state is reflected.
|
|
157
|
+
|
|
158
|
+
```css
|
|
159
|
+
wcs-timer:state(running) ~ .indicator { color: green; }
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Unlike attributes or classes, `:state()` cannot be written from outside the
|
|
163
|
+
element, so there is no risk of confusing this output state with an input.
|
|
164
|
+
|
|
165
|
+
**Browser support** (`:state(x)` syntax): Chrome/Edge 125+, Safari 17.4+,
|
|
166
|
+
Firefox 126+. In older browsers the states are simply never set — `:state()`
|
|
167
|
+
selectors never match, but `<wcs-timer>` itself keeps working normally
|
|
168
|
+
(graceful degradation, never-throw).
|
|
169
|
+
|
|
170
|
+
**SSR**: `:state()` cannot be serialized into HTML, so server-rendered markup
|
|
171
|
+
never carries these states on first paint (`@wcstack/server` is unaffected).
|
|
172
|
+
If you need to style the pre-hydration gap, pair your rule with
|
|
173
|
+
`wcs-timer:not(:defined)` instead.
|
|
174
|
+
|
|
175
|
+
### Debugging
|
|
176
|
+
|
|
177
|
+
Custom states are invisible in DevTools' Elements panel and `attachInternals()`
|
|
178
|
+
cannot be called twice, so there is no console way to inspect them directly.
|
|
179
|
+
Two debug-only aids are provided for that:
|
|
180
|
+
|
|
181
|
+
- `el.debugStates` — a **snapshot** array of the currently-on state names
|
|
182
|
+
(e.g. `["running"]`). It is not part of `wc-bindable` (not a bind target)
|
|
183
|
+
and its shape is not a guaranteed contract — use it for debugging only.
|
|
184
|
+
- The `debug-states` attribute (opt-in, default off) mirrors state changes
|
|
185
|
+
onto a `data-wcs-state-running` attribute on the element, so the Elements
|
|
186
|
+
panel highlights it as it toggles:
|
|
187
|
+
|
|
188
|
+
```html
|
|
189
|
+
<wcs-timer interval="1000" debug-states></wcs-timer>
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
**Write your CSS against `:state()`, not `data-wcs-state-*`.** The mirrored
|
|
193
|
+
attribute exists purely to make state changes visible while debugging with
|
|
194
|
+
DevTools open; it is not a supported styling hook.
|
|
195
|
+
|
|
145
196
|
## Configuration
|
|
146
197
|
|
|
147
198
|
`bootstrapTimer()` registers `<wcs-timer>` and optionally overrides defaults. Pass a partial config:
|
package/dist/index.d.ts
CHANGED
|
@@ -159,7 +159,11 @@ declare class Timer extends HTMLElement {
|
|
|
159
159
|
private _core;
|
|
160
160
|
private _trigger;
|
|
161
161
|
private _connectedCallbackPromise;
|
|
162
|
+
private _internals;
|
|
162
163
|
constructor();
|
|
164
|
+
get debugStates(): string[];
|
|
165
|
+
private _initInternals;
|
|
166
|
+
private _wireStates;
|
|
163
167
|
get connectedCallbackPromise(): Promise<void>;
|
|
164
168
|
get interval(): number;
|
|
165
169
|
set interval(value: number);
|
package/dist/index.esm.js
CHANGED
|
@@ -395,9 +395,62 @@ class Timer extends HTMLElement {
|
|
|
395
395
|
_core;
|
|
396
396
|
_trigger = false;
|
|
397
397
|
_connectedCallbackPromise = Promise.resolve();
|
|
398
|
+
_internals = null;
|
|
398
399
|
constructor() {
|
|
399
400
|
super();
|
|
400
401
|
this._core = new TimerCore(this);
|
|
402
|
+
this._internals = this._initInternals();
|
|
403
|
+
this._wireStates({
|
|
404
|
+
"wcs-timer:running-changed": (d) => ({ running: d === true }),
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
// CSS state reflection (:state()) — debug-only snapshot getter. NOT part of
|
|
408
|
+
// wc-bindable (not a bind target); see README "CSS styling with :state()".
|
|
409
|
+
// MUST NOT return the live CustomStateSet (that would let callers write
|
|
410
|
+
// states from outside, defeating the point of :state() being read-only).
|
|
411
|
+
get debugStates() {
|
|
412
|
+
return this._internals ? [...this._internals.states] : [];
|
|
413
|
+
}
|
|
414
|
+
_initInternals() {
|
|
415
|
+
// never-throw (async-io-node-guidelines.md §3.6): attachInternals is absent
|
|
416
|
+
// in happy-dom / older environments, and pre-125 Chromium rejects
|
|
417
|
+
// non-dashed state names from states.add() (probed and discarded here).
|
|
418
|
+
// Either case silently disables reflection — the component still works,
|
|
419
|
+
// it just doesn't expose :state() selectors.
|
|
420
|
+
try {
|
|
421
|
+
if (typeof this.attachInternals !== "function")
|
|
422
|
+
return null;
|
|
423
|
+
const internals = this.attachInternals();
|
|
424
|
+
internals.states.add("wcs-probe");
|
|
425
|
+
internals.states.delete("wcs-probe");
|
|
426
|
+
return internals;
|
|
427
|
+
}
|
|
428
|
+
catch {
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
_wireStates(map) {
|
|
433
|
+
if (this._internals === null)
|
|
434
|
+
return;
|
|
435
|
+
const states = this._internals.states;
|
|
436
|
+
for (const [event, toStates] of Object.entries(map)) {
|
|
437
|
+
this.addEventListener(event, (e) => {
|
|
438
|
+
const debug = this.hasAttribute("debug-states");
|
|
439
|
+
for (const [name, on] of Object.entries(toStates(e.detail))) {
|
|
440
|
+
try {
|
|
441
|
+
if (on) {
|
|
442
|
+
states.add(name);
|
|
443
|
+
}
|
|
444
|
+
else {
|
|
445
|
+
states.delete(name);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
catch { /* never-throw */ }
|
|
449
|
+
if (debug)
|
|
450
|
+
this.toggleAttribute(`data-wcs-state-${name}`, on);
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
}
|
|
401
454
|
}
|
|
402
455
|
// SSR (§4.1/§4.4): the Shell exposes the Core's readiness so a server-side
|
|
403
456
|
// renderer can await the connect-time probe before snapshotting. The timer has
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/config.ts","../src/core/TimerCore.ts","../src/autoTrigger.ts","../src/components/Timer.ts","../src/registerComponents.ts","../src/bootstrapTimer.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n timer: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-timertarget\",\n tagNames: {\n timer: \"wcs-timer\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\n// Internal-only live handle to the mutable config. NOT part of the public API\n// (deliberately absent from exports.ts) — it is exported solely so sibling\n// modules in this package can read current settings cheaply. External consumers\n// must use getConfig() (returns a deep-frozen snapshot) / setConfig(). Mutating\n// this object directly bypasses the frozenConfig cache and is unsupported.\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable } from \"../types.js\";\n\nexport interface TimerStartOptions {\n interval?: number;\n repeat?: number;\n immediate?: boolean;\n}\n\n/**\n * Headless timer primitive. A thin, framework-agnostic wrapper around\n * `setInterval` exposed through the wc-bindable protocol: it streams `tick`\n * (a monotonically increasing counter), `elapsed` (running time in ms) and a\n * `running` flag, and is driven by the `start` / `stop` / `reset` / `pause` /\n * `resume` commands.\n *\n * `tick` and `elapsed` are both surfaced via the single `wcs-timer:tick` event\n * (read through getters, mirroring how FetchCore exposes value/status from one\n * `wcs-fetch:response` event), so an observer that binds either property is\n * notified on every fire.\n */\nexport class TimerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"tick\", event: \"wcs-timer:tick\", getter: (e: Event) => (e as CustomEvent).detail.count },\n { name: \"elapsed\", event: \"wcs-timer:tick\", getter: (e: Event) => (e as CustomEvent).detail.elapsed },\n { name: \"running\", event: \"wcs-timer:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"stop\" },\n { name: \"reset\" },\n { name: \"pause\" },\n { name: \"resume\" },\n ],\n };\n\n private _target: EventTarget;\n private _timerId: ReturnType<typeof setInterval> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and at every async start\n // (start()/resume()). A scheduled callback (setInterval/setTimeout) captures the\n // generation live via `_gen`; a fire that was already queued when the timer was\n // torn down — or superseded by a new run — has a stale gen and MUST NOT mutate\n // state or dispatch on a disposed element. _clearTimer() removes the handle, but\n // the guard is the belt-and-braces defense for a callback already in the queue.\n private _gen = 0;\n // Generation captured for the currently scheduled run, set at each async start\n // (start()/resume()). A scheduled callback compares it against the live `_gen`;\n // a stale callback (dispose() bumped `_gen` after this run was armed) bails.\n private _runGen = 0;\n // SSR (§3.8): the timer does no asynchronous probe, so readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n\n private _tick: number = 0;\n private _running: boolean = false;\n private _paused: boolean = false;\n\n // `_tick` value captured at the start of the current run. `repeat` counts ticks\n // *per run*, so the stop condition compares against this baseline rather than the\n // cumulative `_tick` (which only resets on reset()). Without it, re-starting a\n // completed bounded timer would stop after a single tick.\n private _runStartTick: number = 0;\n\n // Timer configuration (captured on start, reused by pause/resume).\n // `_immediate` is intentionally NOT a field: it is per-run intent consumed\n // entirely within start() (fire once, then schedule), so it lives as a local\n // there rather than lingering as instance state no other method reads.\n private _interval: number = 1000;\n private _repeat: number = 0; // 0 = unlimited\n\n // Elapsed-time bookkeeping. `_accumulatedElapsed` holds the time folded from\n // already-finished running segments; `_segmentStart` is the timestamp the\n // current running segment began (null when not running). The live elapsed is\n // the sum of the two — see _currentElapsed().\n private _accumulatedElapsed: number = 0;\n private _segmentStart: number | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get tick(): number {\n return this._tick;\n }\n\n get elapsed(): number {\n return this._currentElapsed();\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // SSR readiness (§3.8): resolves after the first probe. The timer is\n // command-driven with nothing to probe, so this is an already-resolved promise.\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). The timer is command-driven (start/stop/...) with no\n // ambient subscription to establish, so observe() is an idempotent no-op that\n // resolves once ready (mirroring UploadCore). dispose() tears the timer down —\n // it stops any running interval and bumps the generation so a callback already\n // queued cannot fire onto a torn-down element.\n observe(): Promise<void> {\n return this._ready;\n }\n\n dispose(): void {\n this._gen++;\n this.stop();\n }\n\n // --- State setters with event dispatch ---\n\n private _dispatchTick(): void {\n this._target.dispatchEvent(new CustomEvent(\"wcs-timer:tick\", {\n detail: { count: this._tick, elapsed: this._currentElapsed() },\n bubbles: true,\n }));\n }\n\n private _setRunning(running: boolean): void {\n if (this._running === running) return;\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-timer:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n start(options: TimerStartOptions = {}): void {\n // Idempotent while running: a redundant start() must not stack a second\n // setInterval (which would leak and double the tick rate). Reconfiguring an\n // active timer is done via stop() + start().\n if (this._running) return;\n\n // start() begins a fresh running segment, so clear any lingering pause from a\n // prior pause()-without-resume(). Without this, the timer would run while\n // _paused stayed true, leaving pause() a no-op and letting resume() overwrite\n // the live timer handle (leak + double fire).\n this._paused = false;\n\n // `interval` is persistent configuration: a non-positive / non-finite value\n // (or an omitted option) keeps the previous interval (default 1000ms). The\n // guard rejects values that would turn setInterval into a hot loop and make\n // resume()'s `accumulated % interval` arithmetic produce NaN. The Shell already\n // falls back to 1000 for invalid attributes; this is the backstop for direct\n // Core API callers.\n if (typeof options.interval === \"number\" && Number.isFinite(options.interval) && options.interval > 0) {\n this._interval = options.interval;\n }\n\n // `repeat` / `immediate` are per-run intent, NOT persistent configuration:\n // every start() re-establishes them from the options, defaulting to\n // \"unlimited\" / \"no immediate fire\" when omitted. This keeps a bare start()\n // after a bounded or one-shot run from silently inheriting the old bounds.\n // `repeat` is a field (pause/resume/_fire read it across the run); `immediate`\n // is consumed here and now, so it stays a local.\n this._repeat = (typeof options.repeat === \"number\" && options.repeat > 0) ? options.repeat : 0;\n const immediate = options.immediate === true;\n\n this._setRunning(true);\n this._segmentStart = Date.now();\n // Baseline this run's per-run repeat counting (set after _setRunning so a\n // re-start of a completed bounded timer fires the full N ticks again).\n this._runStartTick = this._tick;\n // Capture this run's generation (§3.4): a scheduled fire that outlives a\n // dispose() (which bumps `_gen`) is then recognised as stale and ignored.\n this._runGen = ++this._gen;\n\n // Fire immediately on start when requested. _fire() may stop the timer (when\n // repeat is reached), so re-check _running before scheduling the interval.\n if (immediate) {\n this._fire();\n }\n if (this._running) {\n this._timerId = setInterval(this._fire, this._interval);\n }\n }\n\n // Swap the tick period of a live timer in place, WITHOUT re-running start().\n // Unlike stop() + start(), this leaves the per-run repeat progress in flight\n // (`_repeat` and its `_runStartTick` baseline) untouched, so a bounded\n // `repeat=\"N\"` run is not re-baselined to fire N more times. It also never goes\n // through start()'s `immediate` path, so an `immediate` timer does not fire an\n // extra tick. Only re-arms the steady interval; pause()/resume() and reset() are\n // unaffected. No-op when not running (interval is then plain config, captured on\n // the next start) or when the new period is non-positive / non-finite (which\n // would turn setInterval into a hot loop and break resume()'s modulo arithmetic).\n changeInterval(interval: number): void {\n if (!this._running) return;\n if (!(typeof interval === \"number\" && Number.isFinite(interval) && interval > 0)) return;\n if (interval === this._interval) return;\n this._interval = interval;\n // Re-arm the steady ticking at the new period. The current period's progress\n // is intentionally discarded (the next tick is a full new interval away),\n // matching the boundary reset of the previous stop()+start() behaviour.\n this._clearTimer();\n this._timerId = setInterval(this._fire, this._interval);\n }\n\n stop(): void {\n this._clearTimer();\n this._foldElapsed();\n this._paused = false;\n this._setRunning(false);\n }\n\n reset(): void {\n this._clearTimer();\n this._paused = false;\n this._tick = 0;\n this._accumulatedElapsed = 0;\n this._segmentStart = null;\n this._setRunning(false);\n // Notify observers that the counter/elapsed have returned to zero.\n this._dispatchTick();\n }\n\n pause(): void {\n // Pause only a live timer; a no-op otherwise so it composes safely with the\n // declarative lifecycle. Unlike stop(), it records `_paused` so resume() can\n // tell an intentional pause from a full stop.\n if (!this._running || this._paused) return;\n this._clearTimer();\n this._foldElapsed();\n this._paused = true;\n this._setRunning(false);\n }\n\n resume(): void {\n if (!this._paused) return;\n this._paused = false;\n this._setRunning(true);\n this._segmentStart = Date.now();\n // New scheduled run after a pause: capture its generation (§3.4) so a\n // post-dispose() boundary/interval callback is recognised as stale.\n this._runGen = ++this._gen;\n // Invariant: `_interval` is fixed at start() and stays constant for the whole\n // pause/resume cycle — changeInterval() only mutates it while *running* (never\n // while paused), so the remainder arithmetic below can safely assume the same\n // period was in effect across the paused segment. Consequence for the Shell:\n // because the live interval-attribute path (attributeChangedCallback ->\n // changeInterval) is gated on `running`, an `interval` change made *while\n // paused* is silently not applied here; it is picked up only on the next\n // start() as plain config. This is by design — see README \"Commands\".\n // Resume seamlessly: a tick fires every `interval` ms of *running* time, so\n // honour the partial period consumed before the pause. Wait only the\n // remainder to the next boundary, then fall back to the steady interval.\n // (`accumulated % interval === 0` — paused exactly on a boundary — yields a\n // full interval, which is correct: the next tick is a whole period away.)\n const remainder = this._interval - (this._accumulatedElapsed % this._interval);\n this._timerId = setTimeout(this._onResumeBoundary, remainder);\n }\n\n // --- Internal ---\n\n private _onResumeBoundary = (): void => {\n // Stale-run guard (§3.4): a resume-boundary timeout that fires after dispose()\n // belongs to a torn-down run — drop it without re-arming the interval.\n if (this._runGen !== this._gen) return;\n this._timerId = null;\n this._fire();\n // _fire() may have auto-stopped the timer (repeat reached); only re-arm the\n // steady interval while still running.\n if (this._running) {\n this._timerId = setInterval(this._fire, this._interval);\n }\n };\n\n private _fire = (): void => {\n // Stale-run guard (§3.4): an interval callback queued before dispose() (which\n // bumps `_gen`) must not tick or dispatch onto a torn-down element.\n if (this._runGen !== this._gen) return;\n this._tick++;\n this._dispatchTick();\n\n // Auto-stop once this run has fired the requested number of ticks (repeat=0\n // runs forever). Counted per-run via `_runStartTick`, so a re-start after a\n // completed bounded run fires N ticks again. `once` is expressed by the Shell\n // as repeat=1.\n if (this._repeat > 0 && (this._tick - this._runStartTick) >= this._repeat) {\n this._clearTimer();\n this._foldElapsed();\n this._setRunning(false);\n }\n };\n\n private _clearTimer(): void {\n if (this._timerId !== null) {\n // `_timerId` may hold a setInterval handle (steady ticking) or a setTimeout\n // handle (the resume remainder). Clear both — per the HTML spec timers\n // share one list and clearTimeout/clearInterval each remove the entry\n // regardless of which call created it.\n clearTimeout(this._timerId);\n clearInterval(this._timerId);\n this._timerId = null;\n }\n }\n\n private _foldElapsed(): void {\n if (this._segmentStart !== null) {\n this._accumulatedElapsed += Date.now() - this._segmentStart;\n this._segmentStart = null;\n }\n }\n\n private _currentElapsed(): number {\n return this._accumulatedElapsed +\n (this._segmentStart !== null ? Date.now() - this._segmentStart : 0);\n }\n}\n","import { config } from \"./config.js\";\nimport type { Timer } from \"./components/Timer.js\";\n\nlet registered = false;\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const timerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!timerId) return;\n\n // Resolve the registered constructor at call time instead of importing Timer\n // as a value. The value import created a components/Timer.ts ⇄ autoTrigger.ts\n // cycle (Timer.connectedCallback() calls registerAutoTrigger()). instanceof\n // against the customElements registry keeps the exact same identity guarantee\n // — only the registered <wcs-timer> class matches — without the import cycle.\n const TimerCtor = customElements.get(config.tagNames.timer);\n const timerElement = document.getElementById(timerId);\n if (!TimerCtor || !(timerElement instanceof TimerCtor)) return;\n\n // Suppress the element's default action so a timer can start without\n // navigating. Intentional: do not attach data-timertarget to an element whose\n // default action you also want (real <a href> link, form-submit button) — it\n // will be cancelled. See README \"Optional DOM Triggering\".\n event.preventDefault();\n (timerElement as Timer).start();\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable } from \"../types.js\";\nimport { TimerCore } from \"../core/TimerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\nexport class Timer extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...TimerCore.wcBindable,\n properties: [\n ...TimerCore.wcBindable.properties,\n { name: \"trigger\", event: \"wcs-timer:trigger-changed\" },\n ],\n // Shell-level settable surface. `attribute` is a purely descriptive hint\n // (per SPEC-extensions.md the binding core does not act on it) naming the\n // mirrored HTML attribute, matching <wcs-geo> / <wcs-debounce>. `trigger` is a\n // momentary command-property with no backing attribute, so it carries no hint\n // (same as those packages). `start` / `stop` / `reset` / `pause` / `resume`\n // commands are inherited from the Core above.\n inputs: [\n { name: \"interval\", attribute: \"interval\" },\n { name: \"once\", attribute: \"once\" },\n { name: \"repeat\", attribute: \"repeat\" },\n { name: \"immediate\", attribute: \"immediate\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"trigger\" },\n ],\n };\n static get observedAttributes(): string[] { return [\"interval\"]; }\n\n private _core: TimerCore;\n private _trigger: boolean = false;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new TimerCore(this);\n }\n\n // SSR (§4.1/§4.4): the Shell exposes the Core's readiness so a server-side\n // renderer can await the connect-time probe before snapshotting. The timer has\n // no async probe (observe() resolves immediately), but the contract is uniform\n // across IO nodes.\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Attribute accessors ---\n\n get interval(): number {\n const attr = this.getAttribute(\"interval\");\n if (attr === null || attr.trim() === \"\") return 1000;\n // Strict parse via Number() (unlike parseInt, \"100px\" -> NaN, not 100),\n // matching <wcs-geo> / <wcs-debounce>. Fall back to the 1000ms default for any\n // invalid period — not only NaN but also 0 / negative values, which would\n // otherwise reach setInterval as a hot loop and break resume()'s modulo\n // arithmetic in the Core.\n const parsed = Number(attr);\n return (Number.isFinite(parsed) && parsed > 0) ? parsed : 1000;\n }\n\n set interval(value: number) {\n this.setAttribute(\"interval\", String(value));\n }\n\n get once(): boolean {\n return this.hasAttribute(\"once\");\n }\n\n set once(value: boolean) {\n if (value) {\n this.setAttribute(\"once\", \"\");\n } else {\n this.removeAttribute(\"once\");\n }\n }\n\n get repeat(): number {\n const attr = this.getAttribute(\"repeat\");\n if (attr === null || attr.trim() === \"\") return 0;\n // Strict parse via Number() (\"3px\" -> NaN, not 3), matching <wcs-geo> /\n // <wcs-debounce>. Normalise any non-positive / non-numeric value to 0\n // (= unlimited), mirroring the `interval` getter. Without this a negative\n // `repeat=\"-3\"` would leak through to start(); harmless today (Core treats\n // `_repeat <= 0` as unlimited) but the asymmetry is a trap.\n const parsed = Number(attr);\n return (Number.isFinite(parsed) && parsed > 0) ? parsed : 0;\n }\n\n set repeat(value: number) {\n this.setAttribute(\"repeat\", String(value));\n }\n\n get immediate(): boolean {\n return this.hasAttribute(\"immediate\");\n }\n\n set immediate(value: boolean) {\n if (value) {\n this.setAttribute(\"immediate\", \"\");\n } else {\n this.removeAttribute(\"immediate\");\n }\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n // --- Core delegated getters ---\n\n get tick(): number {\n return this._core.tick;\n }\n\n get elapsed(): number {\n return this._core.elapsed;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Command property ---\n\n get trigger(): boolean {\n return this._trigger;\n }\n\n set trigger(value: boolean) {\n // Momentary command-property: a false→true write starts the timer. Mirrors\n // the trigger flag on <wcs-fetch> / <wcs-ws>. Prefer the command-token\n // protocol (`command.start: $command.tick`) for state-driven starts; this\n // exists mainly for the DOM click trigger and simple boolean bindings.\n const v = !!value;\n if (v) {\n this._trigger = true;\n this.start();\n this._trigger = false;\n // The `trigger-changed` event reports the momentary flag returning to\n // false, i.e. that the trigger property *changed* — it is deliberately not\n // gated on whether start() actually began a new run. This keeps the\n // wcBindable `trigger` property's change-notification semantics consistent\n // (every false→true write produces exactly one change-back event), even\n // when start() was a no-op because the timer was already running.\n this.dispatchEvent(new CustomEvent(\"wcs-timer:trigger-changed\", {\n detail: false,\n bubbles: true,\n }));\n }\n }\n\n // --- Commands ---\n\n start(): void {\n // `once` is sugar for \"fire exactly one tick\": map it to repeat=1, but let an\n // explicit repeat attribute win when both are present.\n const repeat = this.repeat > 0 ? this.repeat : (this.once ? 1 : 0);\n this._core.start({\n interval: this.interval,\n repeat,\n immediate: this.immediate,\n });\n }\n\n stop(): void {\n this._core.stop();\n }\n\n reset(): void {\n this._core.reset();\n }\n\n pause(): void {\n this._core.pause();\n }\n\n resume(): void {\n this._core.resume();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n // Live interval changes swap the underlying setInterval period in place.\n // `tick` / `elapsed` and the per-run `repeat` progress are preserved — we\n // deliberately do NOT stop()+start(), which would re-run start() and\n // re-evaluate per-run options (re-firing `immediate` and re-baselining\n // `repeat`). `running` alone gates this: swapping the period is orthogonal to\n // *how* the timer was started, so a `manual` timer the user has explicitly\n // started gets live period changes too. A non-running timer needs no swap —\n // its next start() picks up the new attribute as plain config.\n if (name === \"interval\" && oldValue !== newValue && this.isConnected && this.running) {\n this._core.changeInterval(this.interval);\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // Establish monitoring (§3.5). observe() is a no-op that resolves once ready;\n // expose it as connectedCallbackPromise for SSR.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // dispose() stops the timer and bumps the generation so a callback already\n // queued cannot fire onto a disconnected element (§3.5 / §4.4).\n this._core.dispose();\n }\n}\n","import { Timer } from \"./components/Timer.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.timer)) {\n customElements.define(config.tagNames.timer, Timer);\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapTimer(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n"],"names":[],"mappings":"AAUA,MA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,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;QAC9C,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACrD;AACF;;ACHM,SAAU,cAAc,CAAC,UAA4B,EAAA;IACzD,IAAI,UAAU,EAAE;QACd,SAAS,CAAC,UAAU,CAAC;IACvB;AACA,IAAA,kBAAkB,EAAE;AACtB;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/config.ts","../src/core/TimerCore.ts","../src/autoTrigger.ts","../src/components/Timer.ts","../src/registerComponents.ts","../src/bootstrapTimer.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n timer: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-timertarget\",\n tagNames: {\n timer: \"wcs-timer\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\n// Internal-only live handle to the mutable config. NOT part of the public API\n// (deliberately absent from exports.ts) — it is exported solely so sibling\n// modules in this package can read current settings cheaply. External consumers\n// must use getConfig() (returns a deep-frozen snapshot) / setConfig(). Mutating\n// this object directly bypasses the frozenConfig cache and is unsupported.\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable } from \"../types.js\";\n\nexport interface TimerStartOptions {\n interval?: number;\n repeat?: number;\n immediate?: boolean;\n}\n\n/**\n * Headless timer primitive. A thin, framework-agnostic wrapper around\n * `setInterval` exposed through the wc-bindable protocol: it streams `tick`\n * (a monotonically increasing counter), `elapsed` (running time in ms) and a\n * `running` flag, and is driven by the `start` / `stop` / `reset` / `pause` /\n * `resume` commands.\n *\n * `tick` and `elapsed` are both surfaced via the single `wcs-timer:tick` event\n * (read through getters, mirroring how FetchCore exposes value/status from one\n * `wcs-fetch:response` event), so an observer that binds either property is\n * notified on every fire.\n */\nexport class TimerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"tick\", event: \"wcs-timer:tick\", getter: (e: Event) => (e as CustomEvent).detail.count },\n { name: \"elapsed\", event: \"wcs-timer:tick\", getter: (e: Event) => (e as CustomEvent).detail.elapsed },\n { name: \"running\", event: \"wcs-timer:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"stop\" },\n { name: \"reset\" },\n { name: \"pause\" },\n { name: \"resume\" },\n ],\n };\n\n private _target: EventTarget;\n private _timerId: ReturnType<typeof setInterval> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and at every async start\n // (start()/resume()). A scheduled callback (setInterval/setTimeout) captures the\n // generation live via `_gen`; a fire that was already queued when the timer was\n // torn down — or superseded by a new run — has a stale gen and MUST NOT mutate\n // state or dispatch on a disposed element. _clearTimer() removes the handle, but\n // the guard is the belt-and-braces defense for a callback already in the queue.\n private _gen = 0;\n // Generation captured for the currently scheduled run, set at each async start\n // (start()/resume()). A scheduled callback compares it against the live `_gen`;\n // a stale callback (dispose() bumped `_gen` after this run was armed) bails.\n private _runGen = 0;\n // SSR (§3.8): the timer does no asynchronous probe, so readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n\n private _tick: number = 0;\n private _running: boolean = false;\n private _paused: boolean = false;\n\n // `_tick` value captured at the start of the current run. `repeat` counts ticks\n // *per run*, so the stop condition compares against this baseline rather than the\n // cumulative `_tick` (which only resets on reset()). Without it, re-starting a\n // completed bounded timer would stop after a single tick.\n private _runStartTick: number = 0;\n\n // Timer configuration (captured on start, reused by pause/resume).\n // `_immediate` is intentionally NOT a field: it is per-run intent consumed\n // entirely within start() (fire once, then schedule), so it lives as a local\n // there rather than lingering as instance state no other method reads.\n private _interval: number = 1000;\n private _repeat: number = 0; // 0 = unlimited\n\n // Elapsed-time bookkeeping. `_accumulatedElapsed` holds the time folded from\n // already-finished running segments; `_segmentStart` is the timestamp the\n // current running segment began (null when not running). The live elapsed is\n // the sum of the two — see _currentElapsed().\n private _accumulatedElapsed: number = 0;\n private _segmentStart: number | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get tick(): number {\n return this._tick;\n }\n\n get elapsed(): number {\n return this._currentElapsed();\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // SSR readiness (§3.8): resolves after the first probe. The timer is\n // command-driven with nothing to probe, so this is an already-resolved promise.\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). The timer is command-driven (start/stop/...) with no\n // ambient subscription to establish, so observe() is an idempotent no-op that\n // resolves once ready (mirroring UploadCore). dispose() tears the timer down —\n // it stops any running interval and bumps the generation so a callback already\n // queued cannot fire onto a torn-down element.\n observe(): Promise<void> {\n return this._ready;\n }\n\n dispose(): void {\n this._gen++;\n this.stop();\n }\n\n // --- State setters with event dispatch ---\n\n private _dispatchTick(): void {\n this._target.dispatchEvent(new CustomEvent(\"wcs-timer:tick\", {\n detail: { count: this._tick, elapsed: this._currentElapsed() },\n bubbles: true,\n }));\n }\n\n private _setRunning(running: boolean): void {\n if (this._running === running) return;\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-timer:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n start(options: TimerStartOptions = {}): void {\n // Idempotent while running: a redundant start() must not stack a second\n // setInterval (which would leak and double the tick rate). Reconfiguring an\n // active timer is done via stop() + start().\n if (this._running) return;\n\n // start() begins a fresh running segment, so clear any lingering pause from a\n // prior pause()-without-resume(). Without this, the timer would run while\n // _paused stayed true, leaving pause() a no-op and letting resume() overwrite\n // the live timer handle (leak + double fire).\n this._paused = false;\n\n // `interval` is persistent configuration: a non-positive / non-finite value\n // (or an omitted option) keeps the previous interval (default 1000ms). The\n // guard rejects values that would turn setInterval into a hot loop and make\n // resume()'s `accumulated % interval` arithmetic produce NaN. The Shell already\n // falls back to 1000 for invalid attributes; this is the backstop for direct\n // Core API callers.\n if (typeof options.interval === \"number\" && Number.isFinite(options.interval) && options.interval > 0) {\n this._interval = options.interval;\n }\n\n // `repeat` / `immediate` are per-run intent, NOT persistent configuration:\n // every start() re-establishes them from the options, defaulting to\n // \"unlimited\" / \"no immediate fire\" when omitted. This keeps a bare start()\n // after a bounded or one-shot run from silently inheriting the old bounds.\n // `repeat` is a field (pause/resume/_fire read it across the run); `immediate`\n // is consumed here and now, so it stays a local.\n this._repeat = (typeof options.repeat === \"number\" && options.repeat > 0) ? options.repeat : 0;\n const immediate = options.immediate === true;\n\n this._setRunning(true);\n this._segmentStart = Date.now();\n // Baseline this run's per-run repeat counting (set after _setRunning so a\n // re-start of a completed bounded timer fires the full N ticks again).\n this._runStartTick = this._tick;\n // Capture this run's generation (§3.4): a scheduled fire that outlives a\n // dispose() (which bumps `_gen`) is then recognised as stale and ignored.\n this._runGen = ++this._gen;\n\n // Fire immediately on start when requested. _fire() may stop the timer (when\n // repeat is reached), so re-check _running before scheduling the interval.\n if (immediate) {\n this._fire();\n }\n if (this._running) {\n this._timerId = setInterval(this._fire, this._interval);\n }\n }\n\n // Swap the tick period of a live timer in place, WITHOUT re-running start().\n // Unlike stop() + start(), this leaves the per-run repeat progress in flight\n // (`_repeat` and its `_runStartTick` baseline) untouched, so a bounded\n // `repeat=\"N\"` run is not re-baselined to fire N more times. It also never goes\n // through start()'s `immediate` path, so an `immediate` timer does not fire an\n // extra tick. Only re-arms the steady interval; pause()/resume() and reset() are\n // unaffected. No-op when not running (interval is then plain config, captured on\n // the next start) or when the new period is non-positive / non-finite (which\n // would turn setInterval into a hot loop and break resume()'s modulo arithmetic).\n changeInterval(interval: number): void {\n if (!this._running) return;\n if (!(typeof interval === \"number\" && Number.isFinite(interval) && interval > 0)) return;\n if (interval === this._interval) return;\n this._interval = interval;\n // Re-arm the steady ticking at the new period. The current period's progress\n // is intentionally discarded (the next tick is a full new interval away),\n // matching the boundary reset of the previous stop()+start() behaviour.\n this._clearTimer();\n this._timerId = setInterval(this._fire, this._interval);\n }\n\n stop(): void {\n this._clearTimer();\n this._foldElapsed();\n this._paused = false;\n this._setRunning(false);\n }\n\n reset(): void {\n this._clearTimer();\n this._paused = false;\n this._tick = 0;\n this._accumulatedElapsed = 0;\n this._segmentStart = null;\n this._setRunning(false);\n // Notify observers that the counter/elapsed have returned to zero.\n this._dispatchTick();\n }\n\n pause(): void {\n // Pause only a live timer; a no-op otherwise so it composes safely with the\n // declarative lifecycle. Unlike stop(), it records `_paused` so resume() can\n // tell an intentional pause from a full stop.\n if (!this._running || this._paused) return;\n this._clearTimer();\n this._foldElapsed();\n this._paused = true;\n this._setRunning(false);\n }\n\n resume(): void {\n if (!this._paused) return;\n this._paused = false;\n this._setRunning(true);\n this._segmentStart = Date.now();\n // New scheduled run after a pause: capture its generation (§3.4) so a\n // post-dispose() boundary/interval callback is recognised as stale.\n this._runGen = ++this._gen;\n // Invariant: `_interval` is fixed at start() and stays constant for the whole\n // pause/resume cycle — changeInterval() only mutates it while *running* (never\n // while paused), so the remainder arithmetic below can safely assume the same\n // period was in effect across the paused segment. Consequence for the Shell:\n // because the live interval-attribute path (attributeChangedCallback ->\n // changeInterval) is gated on `running`, an `interval` change made *while\n // paused* is silently not applied here; it is picked up only on the next\n // start() as plain config. This is by design — see README \"Commands\".\n // Resume seamlessly: a tick fires every `interval` ms of *running* time, so\n // honour the partial period consumed before the pause. Wait only the\n // remainder to the next boundary, then fall back to the steady interval.\n // (`accumulated % interval === 0` — paused exactly on a boundary — yields a\n // full interval, which is correct: the next tick is a whole period away.)\n const remainder = this._interval - (this._accumulatedElapsed % this._interval);\n this._timerId = setTimeout(this._onResumeBoundary, remainder);\n }\n\n // --- Internal ---\n\n private _onResumeBoundary = (): void => {\n // Stale-run guard (§3.4): a resume-boundary timeout that fires after dispose()\n // belongs to a torn-down run — drop it without re-arming the interval.\n if (this._runGen !== this._gen) return;\n this._timerId = null;\n this._fire();\n // _fire() may have auto-stopped the timer (repeat reached); only re-arm the\n // steady interval while still running.\n if (this._running) {\n this._timerId = setInterval(this._fire, this._interval);\n }\n };\n\n private _fire = (): void => {\n // Stale-run guard (§3.4): an interval callback queued before dispose() (which\n // bumps `_gen`) must not tick or dispatch onto a torn-down element.\n if (this._runGen !== this._gen) return;\n this._tick++;\n this._dispatchTick();\n\n // Auto-stop once this run has fired the requested number of ticks (repeat=0\n // runs forever). Counted per-run via `_runStartTick`, so a re-start after a\n // completed bounded run fires N ticks again. `once` is expressed by the Shell\n // as repeat=1.\n if (this._repeat > 0 && (this._tick - this._runStartTick) >= this._repeat) {\n this._clearTimer();\n this._foldElapsed();\n this._setRunning(false);\n }\n };\n\n private _clearTimer(): void {\n if (this._timerId !== null) {\n // `_timerId` may hold a setInterval handle (steady ticking) or a setTimeout\n // handle (the resume remainder). Clear both — per the HTML spec timers\n // share one list and clearTimeout/clearInterval each remove the entry\n // regardless of which call created it.\n clearTimeout(this._timerId);\n clearInterval(this._timerId);\n this._timerId = null;\n }\n }\n\n private _foldElapsed(): void {\n if (this._segmentStart !== null) {\n this._accumulatedElapsed += Date.now() - this._segmentStart;\n this._segmentStart = null;\n }\n }\n\n private _currentElapsed(): number {\n return this._accumulatedElapsed +\n (this._segmentStart !== null ? Date.now() - this._segmentStart : 0);\n }\n}\n","import { config } from \"./config.js\";\nimport type { Timer } from \"./components/Timer.js\";\n\nlet registered = false;\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const timerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!timerId) return;\n\n // Resolve the registered constructor at call time instead of importing Timer\n // as a value. The value import created a components/Timer.ts ⇄ autoTrigger.ts\n // cycle (Timer.connectedCallback() calls registerAutoTrigger()). instanceof\n // against the customElements registry keeps the exact same identity guarantee\n // — only the registered <wcs-timer> class matches — without the import cycle.\n const TimerCtor = customElements.get(config.tagNames.timer);\n const timerElement = document.getElementById(timerId);\n if (!TimerCtor || !(timerElement instanceof TimerCtor)) return;\n\n // Suppress the element's default action so a timer can start without\n // navigating. Intentional: do not attach data-timertarget to an element whose\n // default action you also want (real <a href> link, form-submit button) — it\n // will be cancelled. See README \"Optional DOM Triggering\".\n event.preventDefault();\n (timerElement as Timer).start();\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable } from \"../types.js\";\nimport { TimerCore } from \"../core/TimerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\nexport class Timer extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...TimerCore.wcBindable,\n properties: [\n ...TimerCore.wcBindable.properties,\n { name: \"trigger\", event: \"wcs-timer:trigger-changed\" },\n ],\n // Shell-level settable surface. `attribute` is a purely descriptive hint\n // (per SPEC-extensions.md the binding core does not act on it) naming the\n // mirrored HTML attribute, matching <wcs-geo> / <wcs-debounce>. `trigger` is a\n // momentary command-property with no backing attribute, so it carries no hint\n // (same as those packages). `start` / `stop` / `reset` / `pause` / `resume`\n // commands are inherited from the Core above.\n inputs: [\n { name: \"interval\", attribute: \"interval\" },\n { name: \"once\", attribute: \"once\" },\n { name: \"repeat\", attribute: \"repeat\" },\n { name: \"immediate\", attribute: \"immediate\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"trigger\" },\n ],\n };\n static get observedAttributes(): string[] { return [\"interval\"]; }\n\n private _core: TimerCore;\n private _trigger: boolean = false;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n private _internals: ElementInternals | null = null;\n\n constructor() {\n super();\n this._core = new TimerCore(this);\n this._internals = this._initInternals();\n this._wireStates({\n \"wcs-timer:running-changed\": (d) => ({ running: d === true }),\n });\n }\n\n // CSS state reflection (:state()) — debug-only snapshot getter. NOT part of\n // wc-bindable (not a bind target); see README \"CSS styling with :state()\".\n // MUST NOT return the live CustomStateSet (that would let callers write\n // states from outside, defeating the point of :state() being read-only).\n get debugStates(): string[] {\n return this._internals ? [...this._internals.states] : [];\n }\n\n private _initInternals(): ElementInternals | null {\n // never-throw (async-io-node-guidelines.md §3.6): attachInternals is absent\n // in happy-dom / older environments, and pre-125 Chromium rejects\n // non-dashed state names from states.add() (probed and discarded here).\n // Either case silently disables reflection — the component still works,\n // it just doesn't expose :state() selectors.\n try {\n if (typeof this.attachInternals !== \"function\") return null;\n const internals = this.attachInternals();\n internals.states.add(\"wcs-probe\");\n internals.states.delete(\"wcs-probe\");\n return internals;\n } catch {\n return null;\n }\n }\n\n private _wireStates(map: Record<string, (detail: any) => Record<string, boolean>>): void {\n if (this._internals === null) return;\n const states = this._internals.states;\n for (const [event, toStates] of Object.entries(map)) {\n this.addEventListener(event, (e) => {\n const debug = this.hasAttribute(\"debug-states\");\n for (const [name, on] of Object.entries(toStates((e as CustomEvent).detail))) {\n try {\n if (on) { states.add(name); } else { states.delete(name); }\n } catch { /* never-throw */ }\n if (debug) this.toggleAttribute(`data-wcs-state-${name}`, on);\n }\n });\n }\n }\n\n // SSR (§4.1/§4.4): the Shell exposes the Core's readiness so a server-side\n // renderer can await the connect-time probe before snapshotting. The timer has\n // no async probe (observe() resolves immediately), but the contract is uniform\n // across IO nodes.\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Attribute accessors ---\n\n get interval(): number {\n const attr = this.getAttribute(\"interval\");\n if (attr === null || attr.trim() === \"\") return 1000;\n // Strict parse via Number() (unlike parseInt, \"100px\" -> NaN, not 100),\n // matching <wcs-geo> / <wcs-debounce>. Fall back to the 1000ms default for any\n // invalid period — not only NaN but also 0 / negative values, which would\n // otherwise reach setInterval as a hot loop and break resume()'s modulo\n // arithmetic in the Core.\n const parsed = Number(attr);\n return (Number.isFinite(parsed) && parsed > 0) ? parsed : 1000;\n }\n\n set interval(value: number) {\n this.setAttribute(\"interval\", String(value));\n }\n\n get once(): boolean {\n return this.hasAttribute(\"once\");\n }\n\n set once(value: boolean) {\n if (value) {\n this.setAttribute(\"once\", \"\");\n } else {\n this.removeAttribute(\"once\");\n }\n }\n\n get repeat(): number {\n const attr = this.getAttribute(\"repeat\");\n if (attr === null || attr.trim() === \"\") return 0;\n // Strict parse via Number() (\"3px\" -> NaN, not 3), matching <wcs-geo> /\n // <wcs-debounce>. Normalise any non-positive / non-numeric value to 0\n // (= unlimited), mirroring the `interval` getter. Without this a negative\n // `repeat=\"-3\"` would leak through to start(); harmless today (Core treats\n // `_repeat <= 0` as unlimited) but the asymmetry is a trap.\n const parsed = Number(attr);\n return (Number.isFinite(parsed) && parsed > 0) ? parsed : 0;\n }\n\n set repeat(value: number) {\n this.setAttribute(\"repeat\", String(value));\n }\n\n get immediate(): boolean {\n return this.hasAttribute(\"immediate\");\n }\n\n set immediate(value: boolean) {\n if (value) {\n this.setAttribute(\"immediate\", \"\");\n } else {\n this.removeAttribute(\"immediate\");\n }\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n // --- Core delegated getters ---\n\n get tick(): number {\n return this._core.tick;\n }\n\n get elapsed(): number {\n return this._core.elapsed;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Command property ---\n\n get trigger(): boolean {\n return this._trigger;\n }\n\n set trigger(value: boolean) {\n // Momentary command-property: a false→true write starts the timer. Mirrors\n // the trigger flag on <wcs-fetch> / <wcs-ws>. Prefer the command-token\n // protocol (`command.start: $command.tick`) for state-driven starts; this\n // exists mainly for the DOM click trigger and simple boolean bindings.\n const v = !!value;\n if (v) {\n this._trigger = true;\n this.start();\n this._trigger = false;\n // The `trigger-changed` event reports the momentary flag returning to\n // false, i.e. that the trigger property *changed* — it is deliberately not\n // gated on whether start() actually began a new run. This keeps the\n // wcBindable `trigger` property's change-notification semantics consistent\n // (every false→true write produces exactly one change-back event), even\n // when start() was a no-op because the timer was already running.\n this.dispatchEvent(new CustomEvent(\"wcs-timer:trigger-changed\", {\n detail: false,\n bubbles: true,\n }));\n }\n }\n\n // --- Commands ---\n\n start(): void {\n // `once` is sugar for \"fire exactly one tick\": map it to repeat=1, but let an\n // explicit repeat attribute win when both are present.\n const repeat = this.repeat > 0 ? this.repeat : (this.once ? 1 : 0);\n this._core.start({\n interval: this.interval,\n repeat,\n immediate: this.immediate,\n });\n }\n\n stop(): void {\n this._core.stop();\n }\n\n reset(): void {\n this._core.reset();\n }\n\n pause(): void {\n this._core.pause();\n }\n\n resume(): void {\n this._core.resume();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n // Live interval changes swap the underlying setInterval period in place.\n // `tick` / `elapsed` and the per-run `repeat` progress are preserved — we\n // deliberately do NOT stop()+start(), which would re-run start() and\n // re-evaluate per-run options (re-firing `immediate` and re-baselining\n // `repeat`). `running` alone gates this: swapping the period is orthogonal to\n // *how* the timer was started, so a `manual` timer the user has explicitly\n // started gets live period changes too. A non-running timer needs no swap —\n // its next start() picks up the new attribute as plain config.\n if (name === \"interval\" && oldValue !== newValue && this.isConnected && this.running) {\n this._core.changeInterval(this.interval);\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // Establish monitoring (§3.5). observe() is a no-op that resolves once ready;\n // expose it as connectedCallbackPromise for SSR.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // dispose() stops the timer and bumps the generation so a callback already\n // queued cannot fire onto a disconnected element (§3.5 / §4.4).\n this._core.dispose();\n }\n}\n","import { Timer } from \"./components/Timer.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.timer)) {\n customElements.define(config.tagNames.timer, Timer);\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapTimer(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n"],"names":[],"mappings":"AAUA,MAAM,OAAO,GAAoB;AAC/B,IAAA,WAAW,EAAE,IAAI;AACjB,IAAA,gBAAgB,EAAE,kBAAkB;AACpC,IAAA,QAAQ,EAAE;AACR,QAAA,KAAK,EAAE,WAAW;AACnB,KAAA;CACF;AAED,SAAS,UAAU,CAAI,GAAM,EAAA;AAC3B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;AACvD,IAAA,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IAClB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,C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;AAChC,IAAA,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;QAC9C,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACrD;AACF;;ACHM,SAAU,cAAc,CAAC,UAA4B,EAAA;IACzD,IAAI,UAAU,EAAE;QACd,SAAS,CAAC,UAAU,CAAC;IACvB;AACA,IAAA,kBAAkB,EAAE;AACtB;;;;"}
|
package/dist/index.esm.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const t={autoTrigger:!0,triggerAttribute:"data-timertarget",tagNames:{timer:"wcs-timer"}};function e(t){if(null===t||"object"!=typeof t)return t;Object.freeze(t);for(const i of Object.keys(t))e(t[i]);return t}function i(t){if(null===t||"object"!=typeof t)return t;const e={};for(const r of Object.keys(t))e[r]=i(t[r]);return e}let r=null;const s=t;function n(){return r||(r=e(i(t))),r}class a extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"tick",event:"wcs-timer:tick",getter:t=>t.detail.count},{name:"elapsed",event:"wcs-timer:tick",getter:t=>t.detail.elapsed},{name:"running",event:"wcs-timer:running-changed"}],commands:[{name:"start"},{name:"stop"},{name:"reset"},{name:"pause"},{name:"resume"}]};_target;_timerId=null;_gen=0;_runGen=0;_ready=Promise.resolve();_tick=0;_running=!1;_paused=!1;_runStartTick=0;_interval=1e3;_repeat=0;_accumulatedElapsed=0;_segmentStart=null;constructor(t){super(),this._target=t??this}get tick(){return this._tick}get elapsed(){return this._currentElapsed()}get running(){return this._running}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stop()}_dispatchTick(){this._target.dispatchEvent(new CustomEvent("wcs-timer:tick",{detail:{count:this._tick,elapsed:this._currentElapsed()},bubbles:!0}))}_setRunning(t){this._running!==t&&(this._running=t,this._target.dispatchEvent(new CustomEvent("wcs-timer:running-changed",{detail:t,bubbles:!0})))}start(t={}){if(this._running)return;this._paused=!1,"number"==typeof t.interval&&Number.isFinite(t.interval)&&t.interval>0&&(this._interval=t.interval),this._repeat="number"==typeof t.repeat&&t.repeat>0?t.repeat:0;const e=!0===t.immediate;this._setRunning(!0),this._segmentStart=Date.now(),this._runStartTick=this._tick,this._runGen=++this._gen,e&&this._fire(),this._running&&(this._timerId=setInterval(this._fire,this._interval))}changeInterval(t){this._running&&"number"==typeof t&&Number.isFinite(t)&&t>0&&t!==this._interval&&(this._interval=t,this._clearTimer(),this._timerId=setInterval(this._fire,this._interval))}stop(){this._clearTimer(),this._foldElapsed(),this._paused=!1,this._setRunning(!1)}reset(){this._clearTimer(),this._paused=!1,this._tick=0,this._accumulatedElapsed=0,this._segmentStart=null,this._setRunning(!1),this._dispatchTick()}pause(){this._running&&!this._paused&&(this._clearTimer(),this._foldElapsed(),this._paused=!0,this._setRunning(!1))}resume(){if(!this._paused)return;this._paused=!1,this._setRunning(!0),this._segmentStart=Date.now(),this._runGen=++this._gen;const t=this._interval-this._accumulatedElapsed%this._interval;this._timerId=setTimeout(this._onResumeBoundary,t)}_onResumeBoundary=()=>{this._runGen===this._gen&&(this._timerId=null,this._fire(),this._running&&(this._timerId=setInterval(this._fire,this._interval)))};_fire=()=>{this._runGen===this._gen&&(this._tick++,this._dispatchTick(),this._repeat>0&&this._tick-this._runStartTick>=this._repeat&&(this._clearTimer(),this._foldElapsed(),this._setRunning(!1)))};_clearTimer(){null!==this._timerId&&(clearTimeout(this._timerId),clearInterval(this._timerId),this._timerId=null)}_foldElapsed(){null!==this._segmentStart&&(this._accumulatedElapsed+=Date.now()-this._segmentStart,this._segmentStart=null)}_currentElapsed(){return this._accumulatedElapsed+(null!==this._segmentStart?Date.now()-this._segmentStart:0)}}let u=!1;function c(t){const e=t.target;if(!(e instanceof Element))return;const i=e.closest(`[${s.triggerAttribute}]`);if(!i)return;const r=i.getAttribute(s.triggerAttribute);if(!r)return;const n=customElements.get(s.tagNames.timer),a=document.getElementById(r);n&&a instanceof n&&(t.preventDefault(),a.start())}class h extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...a.wcBindable,properties:[...a.wcBindable.properties,{name:"trigger",event:"wcs-timer:trigger-changed"}],inputs:[{name:"interval",attribute:"interval"},{name:"once",attribute:"once"},{name:"repeat",attribute:"repeat"},{name:"immediate",attribute:"immediate"},{name:"manual",attribute:"manual"},{name:"trigger"}]};static get observedAttributes(){return["interval"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();constructor(){super(),this._core=new a(this)}get connectedCallbackPromise(){return this._connectedCallbackPromise}get interval(){const t=this.getAttribute("interval");if(null===t||""===t.trim())return 1e3;const e=Number(t);return Number.isFinite(e)&&e>0?e:1e3}set interval(t){this.setAttribute("interval",String(t))}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}get repeat(){const t=this.getAttribute("repeat");if(null===t||""===t.trim())return 0;const e=Number(t);return Number.isFinite(e)&&e>0?e:0}set repeat(t){this.setAttribute("repeat",String(t))}get immediate(){return this.hasAttribute("immediate")}set immediate(t){t?this.setAttribute("immediate",""):this.removeAttribute("immediate")}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get tick(){return this._core.tick}get elapsed(){return this._core.elapsed}get running(){return this._core.running}get trigger(){return this._trigger}set trigger(t){!!t&&(this._trigger=!0,this.start(),this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-timer:trigger-changed",{detail:!1,bubbles:!0})))}start(){const t=this.repeat>0?this.repeat:this.once?1:0;this._core.start({interval:this.interval,repeat:t,immediate:this.immediate})}stop(){this._core.stop()}reset(){this._core.reset()}pause(){this._core.pause()}resume(){this._core.resume()}attributeChangedCallback(t,e,i){"interval"===t&&e!==i&&this.isConnected&&this.running&&this._core.changeInterval(this.interval)}connectedCallback(){this.style.display="none",s.autoTrigger&&(u||(u=!0,document.addEventListener("click",c))),this._connectedCallbackPromise=this._core.observe(),this.manual||this.start()}disconnectedCallback(){this._core.dispose()}}function l(e){var i;e&&("boolean"==typeof(i=e).autoTrigger&&(t.autoTrigger=i.autoTrigger),"string"==typeof i.triggerAttribute&&(t.triggerAttribute=i.triggerAttribute),i.tagNames&&Object.assign(t.tagNames,i.tagNames),r=null),customElements.get(s.tagNames.timer)||customElements.define(s.tagNames.timer,h)}export{a as TimerCore,h as WcsTimer,l as bootstrapTimer,n as getConfig};
|
|
1
|
+
const t={autoTrigger:!0,triggerAttribute:"data-timertarget",tagNames:{timer:"wcs-timer"}};function e(t){if(null===t||"object"!=typeof t)return t;Object.freeze(t);for(const i of Object.keys(t))e(t[i]);return t}function i(t){if(null===t||"object"!=typeof t)return t;const e={};for(const r of Object.keys(t))e[r]=i(t[r]);return e}let r=null;const s=t;function n(){return r||(r=e(i(t))),r}class a extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"tick",event:"wcs-timer:tick",getter:t=>t.detail.count},{name:"elapsed",event:"wcs-timer:tick",getter:t=>t.detail.elapsed},{name:"running",event:"wcs-timer:running-changed"}],commands:[{name:"start"},{name:"stop"},{name:"reset"},{name:"pause"},{name:"resume"}]};_target;_timerId=null;_gen=0;_runGen=0;_ready=Promise.resolve();_tick=0;_running=!1;_paused=!1;_runStartTick=0;_interval=1e3;_repeat=0;_accumulatedElapsed=0;_segmentStart=null;constructor(t){super(),this._target=t??this}get tick(){return this._tick}get elapsed(){return this._currentElapsed()}get running(){return this._running}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stop()}_dispatchTick(){this._target.dispatchEvent(new CustomEvent("wcs-timer:tick",{detail:{count:this._tick,elapsed:this._currentElapsed()},bubbles:!0}))}_setRunning(t){this._running!==t&&(this._running=t,this._target.dispatchEvent(new CustomEvent("wcs-timer:running-changed",{detail:t,bubbles:!0})))}start(t={}){if(this._running)return;this._paused=!1,"number"==typeof t.interval&&Number.isFinite(t.interval)&&t.interval>0&&(this._interval=t.interval),this._repeat="number"==typeof t.repeat&&t.repeat>0?t.repeat:0;const e=!0===t.immediate;this._setRunning(!0),this._segmentStart=Date.now(),this._runStartTick=this._tick,this._runGen=++this._gen,e&&this._fire(),this._running&&(this._timerId=setInterval(this._fire,this._interval))}changeInterval(t){this._running&&"number"==typeof t&&Number.isFinite(t)&&t>0&&t!==this._interval&&(this._interval=t,this._clearTimer(),this._timerId=setInterval(this._fire,this._interval))}stop(){this._clearTimer(),this._foldElapsed(),this._paused=!1,this._setRunning(!1)}reset(){this._clearTimer(),this._paused=!1,this._tick=0,this._accumulatedElapsed=0,this._segmentStart=null,this._setRunning(!1),this._dispatchTick()}pause(){this._running&&!this._paused&&(this._clearTimer(),this._foldElapsed(),this._paused=!0,this._setRunning(!1))}resume(){if(!this._paused)return;this._paused=!1,this._setRunning(!0),this._segmentStart=Date.now(),this._runGen=++this._gen;const t=this._interval-this._accumulatedElapsed%this._interval;this._timerId=setTimeout(this._onResumeBoundary,t)}_onResumeBoundary=()=>{this._runGen===this._gen&&(this._timerId=null,this._fire(),this._running&&(this._timerId=setInterval(this._fire,this._interval)))};_fire=()=>{this._runGen===this._gen&&(this._tick++,this._dispatchTick(),this._repeat>0&&this._tick-this._runStartTick>=this._repeat&&(this._clearTimer(),this._foldElapsed(),this._setRunning(!1)))};_clearTimer(){null!==this._timerId&&(clearTimeout(this._timerId),clearInterval(this._timerId),this._timerId=null)}_foldElapsed(){null!==this._segmentStart&&(this._accumulatedElapsed+=Date.now()-this._segmentStart,this._segmentStart=null)}_currentElapsed(){return this._accumulatedElapsed+(null!==this._segmentStart?Date.now()-this._segmentStart:0)}}let u=!1;function c(t){const e=t.target;if(!(e instanceof Element))return;const i=e.closest(`[${s.triggerAttribute}]`);if(!i)return;const r=i.getAttribute(s.triggerAttribute);if(!r)return;const n=customElements.get(s.tagNames.timer),a=document.getElementById(r);n&&a instanceof n&&(t.preventDefault(),a.start())}class h extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...a.wcBindable,properties:[...a.wcBindable.properties,{name:"trigger",event:"wcs-timer:trigger-changed"}],inputs:[{name:"interval",attribute:"interval"},{name:"once",attribute:"once"},{name:"repeat",attribute:"repeat"},{name:"immediate",attribute:"immediate"},{name:"manual",attribute:"manual"},{name:"trigger"}]};static get observedAttributes(){return["interval"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new a(this),this._internals=this._initInternals(),this._wireStates({"wcs-timer:running-changed":t=>({running:!0===t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[i,r]of Object.entries(t))this.addEventListener(i,t=>{const i=this.hasAttribute("debug-states");for(const[s,n]of Object.entries(r(t.detail))){try{n?e.add(s):e.delete(s)}catch{}i&&this.toggleAttribute(`data-wcs-state-${s}`,n)}})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get interval(){const t=this.getAttribute("interval");if(null===t||""===t.trim())return 1e3;const e=Number(t);return Number.isFinite(e)&&e>0?e:1e3}set interval(t){this.setAttribute("interval",String(t))}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}get repeat(){const t=this.getAttribute("repeat");if(null===t||""===t.trim())return 0;const e=Number(t);return Number.isFinite(e)&&e>0?e:0}set repeat(t){this.setAttribute("repeat",String(t))}get immediate(){return this.hasAttribute("immediate")}set immediate(t){t?this.setAttribute("immediate",""):this.removeAttribute("immediate")}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get tick(){return this._core.tick}get elapsed(){return this._core.elapsed}get running(){return this._core.running}get trigger(){return this._trigger}set trigger(t){!!t&&(this._trigger=!0,this.start(),this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-timer:trigger-changed",{detail:!1,bubbles:!0})))}start(){const t=this.repeat>0?this.repeat:this.once?1:0;this._core.start({interval:this.interval,repeat:t,immediate:this.immediate})}stop(){this._core.stop()}reset(){this._core.reset()}pause(){this._core.pause()}resume(){this._core.resume()}attributeChangedCallback(t,e,i){"interval"===t&&e!==i&&this.isConnected&&this.running&&this._core.changeInterval(this.interval)}connectedCallback(){this.style.display="none",s.autoTrigger&&(u||(u=!0,document.addEventListener("click",c))),this._connectedCallbackPromise=this._core.observe(),this.manual||this.start()}disconnectedCallback(){this._core.dispose()}}function l(e){var i;e&&("boolean"==typeof(i=e).autoTrigger&&(t.autoTrigger=i.autoTrigger),"string"==typeof i.triggerAttribute&&(t.triggerAttribute=i.triggerAttribute),i.tagNames&&Object.assign(t.tagNames,i.tagNames),r=null),customElements.get(s.tagNames.timer)||customElements.define(s.tagNames.timer,h)}export{a as TimerCore,h as WcsTimer,l as bootstrapTimer,n as getConfig};
|
|
2
2
|
//# sourceMappingURL=index.esm.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/core/TimerCore.ts","../src/autoTrigger.ts","../src/components/Timer.ts","../src/bootstrapTimer.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n timer: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-timertarget\",\n tagNames: {\n timer: \"wcs-timer\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\n// Internal-only live handle to the mutable config. NOT part of the public API\n// (deliberately absent from exports.ts) — it is exported solely so sibling\n// modules in this package can read current settings cheaply. External consumers\n// must use getConfig() (returns a deep-frozen snapshot) / setConfig(). Mutating\n// this object directly bypasses the frozenConfig cache and is unsupported.\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable } from \"../types.js\";\n\nexport interface TimerStartOptions {\n interval?: number;\n repeat?: number;\n immediate?: boolean;\n}\n\n/**\n * Headless timer primitive. A thin, framework-agnostic wrapper around\n * `setInterval` exposed through the wc-bindable protocol: it streams `tick`\n * (a monotonically increasing counter), `elapsed` (running time in ms) and a\n * `running` flag, and is driven by the `start` / `stop` / `reset` / `pause` /\n * `resume` commands.\n *\n * `tick` and `elapsed` are both surfaced via the single `wcs-timer:tick` event\n * (read through getters, mirroring how FetchCore exposes value/status from one\n * `wcs-fetch:response` event), so an observer that binds either property is\n * notified on every fire.\n */\nexport class TimerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"tick\", event: \"wcs-timer:tick\", getter: (e: Event) => (e as CustomEvent).detail.count },\n { name: \"elapsed\", event: \"wcs-timer:tick\", getter: (e: Event) => (e as CustomEvent).detail.elapsed },\n { name: \"running\", event: \"wcs-timer:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"stop\" },\n { name: \"reset\" },\n { name: \"pause\" },\n { name: \"resume\" },\n ],\n };\n\n private _target: EventTarget;\n private _timerId: ReturnType<typeof setInterval> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and at every async start\n // (start()/resume()). A scheduled callback (setInterval/setTimeout) captures the\n // generation live via `_gen`; a fire that was already queued when the timer was\n // torn down — or superseded by a new run — has a stale gen and MUST NOT mutate\n // state or dispatch on a disposed element. _clearTimer() removes the handle, but\n // the guard is the belt-and-braces defense for a callback already in the queue.\n private _gen = 0;\n // Generation captured for the currently scheduled run, set at each async start\n // (start()/resume()). A scheduled callback compares it against the live `_gen`;\n // a stale callback (dispose() bumped `_gen` after this run was armed) bails.\n private _runGen = 0;\n // SSR (§3.8): the timer does no asynchronous probe, so readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n\n private _tick: number = 0;\n private _running: boolean = false;\n private _paused: boolean = false;\n\n // `_tick` value captured at the start of the current run. `repeat` counts ticks\n // *per run*, so the stop condition compares against this baseline rather than the\n // cumulative `_tick` (which only resets on reset()). Without it, re-starting a\n // completed bounded timer would stop after a single tick.\n private _runStartTick: number = 0;\n\n // Timer configuration (captured on start, reused by pause/resume).\n // `_immediate` is intentionally NOT a field: it is per-run intent consumed\n // entirely within start() (fire once, then schedule), so it lives as a local\n // there rather than lingering as instance state no other method reads.\n private _interval: number = 1000;\n private _repeat: number = 0; // 0 = unlimited\n\n // Elapsed-time bookkeeping. `_accumulatedElapsed` holds the time folded from\n // already-finished running segments; `_segmentStart` is the timestamp the\n // current running segment began (null when not running). The live elapsed is\n // the sum of the two — see _currentElapsed().\n private _accumulatedElapsed: number = 0;\n private _segmentStart: number | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get tick(): number {\n return this._tick;\n }\n\n get elapsed(): number {\n return this._currentElapsed();\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // SSR readiness (§3.8): resolves after the first probe. The timer is\n // command-driven with nothing to probe, so this is an already-resolved promise.\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). The timer is command-driven (start/stop/...) with no\n // ambient subscription to establish, so observe() is an idempotent no-op that\n // resolves once ready (mirroring UploadCore). dispose() tears the timer down —\n // it stops any running interval and bumps the generation so a callback already\n // queued cannot fire onto a torn-down element.\n observe(): Promise<void> {\n return this._ready;\n }\n\n dispose(): void {\n this._gen++;\n this.stop();\n }\n\n // --- State setters with event dispatch ---\n\n private _dispatchTick(): void {\n this._target.dispatchEvent(new CustomEvent(\"wcs-timer:tick\", {\n detail: { count: this._tick, elapsed: this._currentElapsed() },\n bubbles: true,\n }));\n }\n\n private _setRunning(running: boolean): void {\n if (this._running === running) return;\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-timer:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n start(options: TimerStartOptions = {}): void {\n // Idempotent while running: a redundant start() must not stack a second\n // setInterval (which would leak and double the tick rate). Reconfiguring an\n // active timer is done via stop() + start().\n if (this._running) return;\n\n // start() begins a fresh running segment, so clear any lingering pause from a\n // prior pause()-without-resume(). Without this, the timer would run while\n // _paused stayed true, leaving pause() a no-op and letting resume() overwrite\n // the live timer handle (leak + double fire).\n this._paused = false;\n\n // `interval` is persistent configuration: a non-positive / non-finite value\n // (or an omitted option) keeps the previous interval (default 1000ms). The\n // guard rejects values that would turn setInterval into a hot loop and make\n // resume()'s `accumulated % interval` arithmetic produce NaN. The Shell already\n // falls back to 1000 for invalid attributes; this is the backstop for direct\n // Core API callers.\n if (typeof options.interval === \"number\" && Number.isFinite(options.interval) && options.interval > 0) {\n this._interval = options.interval;\n }\n\n // `repeat` / `immediate` are per-run intent, NOT persistent configuration:\n // every start() re-establishes them from the options, defaulting to\n // \"unlimited\" / \"no immediate fire\" when omitted. This keeps a bare start()\n // after a bounded or one-shot run from silently inheriting the old bounds.\n // `repeat` is a field (pause/resume/_fire read it across the run); `immediate`\n // is consumed here and now, so it stays a local.\n this._repeat = (typeof options.repeat === \"number\" && options.repeat > 0) ? options.repeat : 0;\n const immediate = options.immediate === true;\n\n this._setRunning(true);\n this._segmentStart = Date.now();\n // Baseline this run's per-run repeat counting (set after _setRunning so a\n // re-start of a completed bounded timer fires the full N ticks again).\n this._runStartTick = this._tick;\n // Capture this run's generation (§3.4): a scheduled fire that outlives a\n // dispose() (which bumps `_gen`) is then recognised as stale and ignored.\n this._runGen = ++this._gen;\n\n // Fire immediately on start when requested. _fire() may stop the timer (when\n // repeat is reached), so re-check _running before scheduling the interval.\n if (immediate) {\n this._fire();\n }\n if (this._running) {\n this._timerId = setInterval(this._fire, this._interval);\n }\n }\n\n // Swap the tick period of a live timer in place, WITHOUT re-running start().\n // Unlike stop() + start(), this leaves the per-run repeat progress in flight\n // (`_repeat` and its `_runStartTick` baseline) untouched, so a bounded\n // `repeat=\"N\"` run is not re-baselined to fire N more times. It also never goes\n // through start()'s `immediate` path, so an `immediate` timer does not fire an\n // extra tick. Only re-arms the steady interval; pause()/resume() and reset() are\n // unaffected. No-op when not running (interval is then plain config, captured on\n // the next start) or when the new period is non-positive / non-finite (which\n // would turn setInterval into a hot loop and break resume()'s modulo arithmetic).\n changeInterval(interval: number): void {\n if (!this._running) return;\n if (!(typeof interval === \"number\" && Number.isFinite(interval) && interval > 0)) return;\n if (interval === this._interval) return;\n this._interval = interval;\n // Re-arm the steady ticking at the new period. The current period's progress\n // is intentionally discarded (the next tick is a full new interval away),\n // matching the boundary reset of the previous stop()+start() behaviour.\n this._clearTimer();\n this._timerId = setInterval(this._fire, this._interval);\n }\n\n stop(): void {\n this._clearTimer();\n this._foldElapsed();\n this._paused = false;\n this._setRunning(false);\n }\n\n reset(): void {\n this._clearTimer();\n this._paused = false;\n this._tick = 0;\n this._accumulatedElapsed = 0;\n this._segmentStart = null;\n this._setRunning(false);\n // Notify observers that the counter/elapsed have returned to zero.\n this._dispatchTick();\n }\n\n pause(): void {\n // Pause only a live timer; a no-op otherwise so it composes safely with the\n // declarative lifecycle. Unlike stop(), it records `_paused` so resume() can\n // tell an intentional pause from a full stop.\n if (!this._running || this._paused) return;\n this._clearTimer();\n this._foldElapsed();\n this._paused = true;\n this._setRunning(false);\n }\n\n resume(): void {\n if (!this._paused) return;\n this._paused = false;\n this._setRunning(true);\n this._segmentStart = Date.now();\n // New scheduled run after a pause: capture its generation (§3.4) so a\n // post-dispose() boundary/interval callback is recognised as stale.\n this._runGen = ++this._gen;\n // Invariant: `_interval` is fixed at start() and stays constant for the whole\n // pause/resume cycle — changeInterval() only mutates it while *running* (never\n // while paused), so the remainder arithmetic below can safely assume the same\n // period was in effect across the paused segment. Consequence for the Shell:\n // because the live interval-attribute path (attributeChangedCallback ->\n // changeInterval) is gated on `running`, an `interval` change made *while\n // paused* is silently not applied here; it is picked up only on the next\n // start() as plain config. This is by design — see README \"Commands\".\n // Resume seamlessly: a tick fires every `interval` ms of *running* time, so\n // honour the partial period consumed before the pause. Wait only the\n // remainder to the next boundary, then fall back to the steady interval.\n // (`accumulated % interval === 0` — paused exactly on a boundary — yields a\n // full interval, which is correct: the next tick is a whole period away.)\n const remainder = this._interval - (this._accumulatedElapsed % this._interval);\n this._timerId = setTimeout(this._onResumeBoundary, remainder);\n }\n\n // --- Internal ---\n\n private _onResumeBoundary = (): void => {\n // Stale-run guard (§3.4): a resume-boundary timeout that fires after dispose()\n // belongs to a torn-down run — drop it without re-arming the interval.\n if (this._runGen !== this._gen) return;\n this._timerId = null;\n this._fire();\n // _fire() may have auto-stopped the timer (repeat reached); only re-arm the\n // steady interval while still running.\n if (this._running) {\n this._timerId = setInterval(this._fire, this._interval);\n }\n };\n\n private _fire = (): void => {\n // Stale-run guard (§3.4): an interval callback queued before dispose() (which\n // bumps `_gen`) must not tick or dispatch onto a torn-down element.\n if (this._runGen !== this._gen) return;\n this._tick++;\n this._dispatchTick();\n\n // Auto-stop once this run has fired the requested number of ticks (repeat=0\n // runs forever). Counted per-run via `_runStartTick`, so a re-start after a\n // completed bounded run fires N ticks again. `once` is expressed by the Shell\n // as repeat=1.\n if (this._repeat > 0 && (this._tick - this._runStartTick) >= this._repeat) {\n this._clearTimer();\n this._foldElapsed();\n this._setRunning(false);\n }\n };\n\n private _clearTimer(): void {\n if (this._timerId !== null) {\n // `_timerId` may hold a setInterval handle (steady ticking) or a setTimeout\n // handle (the resume remainder). Clear both — per the HTML spec timers\n // share one list and clearTimeout/clearInterval each remove the entry\n // regardless of which call created it.\n clearTimeout(this._timerId);\n clearInterval(this._timerId);\n this._timerId = null;\n }\n }\n\n private _foldElapsed(): void {\n if (this._segmentStart !== null) {\n this._accumulatedElapsed += Date.now() - this._segmentStart;\n this._segmentStart = null;\n }\n }\n\n private _currentElapsed(): number {\n return this._accumulatedElapsed +\n (this._segmentStart !== null ? Date.now() - this._segmentStart : 0);\n }\n}\n","import { config } from \"./config.js\";\nimport type { Timer } from \"./components/Timer.js\";\n\nlet registered = false;\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const timerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!timerId) return;\n\n // Resolve the registered constructor at call time instead of importing Timer\n // as a value. The value import created a components/Timer.ts ⇄ autoTrigger.ts\n // cycle (Timer.connectedCallback() calls registerAutoTrigger()). instanceof\n // against the customElements registry keeps the exact same identity guarantee\n // — only the registered <wcs-timer> class matches — without the import cycle.\n const TimerCtor = customElements.get(config.tagNames.timer);\n const timerElement = document.getElementById(timerId);\n if (!TimerCtor || !(timerElement instanceof TimerCtor)) return;\n\n // Suppress the element's default action so a timer can start without\n // navigating. Intentional: do not attach data-timertarget to an element whose\n // default action you also want (real <a href> link, form-submit button) — it\n // will be cancelled. See README \"Optional DOM Triggering\".\n event.preventDefault();\n (timerElement as Timer).start();\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable } from \"../types.js\";\nimport { TimerCore } from \"../core/TimerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\nexport class Timer extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...TimerCore.wcBindable,\n properties: [\n ...TimerCore.wcBindable.properties,\n { name: \"trigger\", event: \"wcs-timer:trigger-changed\" },\n ],\n // Shell-level settable surface. `attribute` is a purely descriptive hint\n // (per SPEC-extensions.md the binding core does not act on it) naming the\n // mirrored HTML attribute, matching <wcs-geo> / <wcs-debounce>. `trigger` is a\n // momentary command-property with no backing attribute, so it carries no hint\n // (same as those packages). `start` / `stop` / `reset` / `pause` / `resume`\n // commands are inherited from the Core above.\n inputs: [\n { name: \"interval\", attribute: \"interval\" },\n { name: \"once\", attribute: \"once\" },\n { name: \"repeat\", attribute: \"repeat\" },\n { name: \"immediate\", attribute: \"immediate\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"trigger\" },\n ],\n };\n static get observedAttributes(): string[] { return [\"interval\"]; }\n\n private _core: TimerCore;\n private _trigger: boolean = false;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new TimerCore(this);\n }\n\n // SSR (§4.1/§4.4): the Shell exposes the Core's readiness so a server-side\n // renderer can await the connect-time probe before snapshotting. The timer has\n // no async probe (observe() resolves immediately), but the contract is uniform\n // across IO nodes.\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Attribute accessors ---\n\n get interval(): number {\n const attr = this.getAttribute(\"interval\");\n if (attr === null || attr.trim() === \"\") return 1000;\n // Strict parse via Number() (unlike parseInt, \"100px\" -> NaN, not 100),\n // matching <wcs-geo> / <wcs-debounce>. Fall back to the 1000ms default for any\n // invalid period — not only NaN but also 0 / negative values, which would\n // otherwise reach setInterval as a hot loop and break resume()'s modulo\n // arithmetic in the Core.\n const parsed = Number(attr);\n return (Number.isFinite(parsed) && parsed > 0) ? parsed : 1000;\n }\n\n set interval(value: number) {\n this.setAttribute(\"interval\", String(value));\n }\n\n get once(): boolean {\n return this.hasAttribute(\"once\");\n }\n\n set once(value: boolean) {\n if (value) {\n this.setAttribute(\"once\", \"\");\n } else {\n this.removeAttribute(\"once\");\n }\n }\n\n get repeat(): number {\n const attr = this.getAttribute(\"repeat\");\n if (attr === null || attr.trim() === \"\") return 0;\n // Strict parse via Number() (\"3px\" -> NaN, not 3), matching <wcs-geo> /\n // <wcs-debounce>. Normalise any non-positive / non-numeric value to 0\n // (= unlimited), mirroring the `interval` getter. Without this a negative\n // `repeat=\"-3\"` would leak through to start(); harmless today (Core treats\n // `_repeat <= 0` as unlimited) but the asymmetry is a trap.\n const parsed = Number(attr);\n return (Number.isFinite(parsed) && parsed > 0) ? parsed : 0;\n }\n\n set repeat(value: number) {\n this.setAttribute(\"repeat\", String(value));\n }\n\n get immediate(): boolean {\n return this.hasAttribute(\"immediate\");\n }\n\n set immediate(value: boolean) {\n if (value) {\n this.setAttribute(\"immediate\", \"\");\n } else {\n this.removeAttribute(\"immediate\");\n }\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n // --- Core delegated getters ---\n\n get tick(): number {\n return this._core.tick;\n }\n\n get elapsed(): number {\n return this._core.elapsed;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Command property ---\n\n get trigger(): boolean {\n return this._trigger;\n }\n\n set trigger(value: boolean) {\n // Momentary command-property: a false→true write starts the timer. Mirrors\n // the trigger flag on <wcs-fetch> / <wcs-ws>. Prefer the command-token\n // protocol (`command.start: $command.tick`) for state-driven starts; this\n // exists mainly for the DOM click trigger and simple boolean bindings.\n const v = !!value;\n if (v) {\n this._trigger = true;\n this.start();\n this._trigger = false;\n // The `trigger-changed` event reports the momentary flag returning to\n // false, i.e. that the trigger property *changed* — it is deliberately not\n // gated on whether start() actually began a new run. This keeps the\n // wcBindable `trigger` property's change-notification semantics consistent\n // (every false→true write produces exactly one change-back event), even\n // when start() was a no-op because the timer was already running.\n this.dispatchEvent(new CustomEvent(\"wcs-timer:trigger-changed\", {\n detail: false,\n bubbles: true,\n }));\n }\n }\n\n // --- Commands ---\n\n start(): void {\n // `once` is sugar for \"fire exactly one tick\": map it to repeat=1, but let an\n // explicit repeat attribute win when both are present.\n const repeat = this.repeat > 0 ? this.repeat : (this.once ? 1 : 0);\n this._core.start({\n interval: this.interval,\n repeat,\n immediate: this.immediate,\n });\n }\n\n stop(): void {\n this._core.stop();\n }\n\n reset(): void {\n this._core.reset();\n }\n\n pause(): void {\n this._core.pause();\n }\n\n resume(): void {\n this._core.resume();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n // Live interval changes swap the underlying setInterval period in place.\n // `tick` / `elapsed` and the per-run `repeat` progress are preserved — we\n // deliberately do NOT stop()+start(), which would re-run start() and\n // re-evaluate per-run options (re-firing `immediate` and re-baselining\n // `repeat`). `running` alone gates this: swapping the period is orthogonal to\n // *how* the timer was started, so a `manual` timer the user has explicitly\n // started gets live period changes too. A non-running timer needs no swap —\n // its next start() picks up the new attribute as plain config.\n if (name === \"interval\" && oldValue !== newValue && this.isConnected && this.running) {\n this._core.changeInterval(this.interval);\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // Establish monitoring (§3.5). observe() is a no-op that resolves once ready;\n // expose it as connectedCallbackPromise for SSR.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // dispose() stops the timer and bumps the generation so a callback already\n // queued cannot fire onto a disconnected element (§3.5 / §4.4).\n this._core.dispose();\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapTimer(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { Timer } from \"./components/Timer.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.timer)) {\n customElements.define(config.tagNames.timer, Timer);\n }\n}\n"],"names":["_config","autoTrigger","triggerAttribute","tagNames","timer","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","TimerCore","EventTarget","static","protocol","version","properties","name","event","getter","e","detail","count","elapsed","commands","_target","_timerId","_gen","_runGen","_ready","Promise","resolve","_tick","_running","_paused","_runStartTick","_interval","_repeat","_accumulatedElapsed","_segmentStart","constructor","target","super","this","tick","_currentElapsed","running","ready","observe","dispose","stop","_dispatchTick","dispatchEvent","CustomEvent","bubbles","_setRunning","start","options","interval","Number","isFinite","repeat","immediate","Date","now","_fire","setInterval","changeInterval","_clearTimer","_foldElapsed","reset","pause","resume","remainder","setTimeout","_onResumeBoundary","clearTimeout","clearInterval","registered","handleClick","Element","triggerElement","closest","timerId","getAttribute","TimerCtor","customElements","get","timerElement","document","getElementById","preventDefault","Timer","HTMLElement","wcBindable","inputs","attribute","observedAttributes","_core","_trigger","_connectedCallbackPromise","connectedCallbackPromise","attr","trim","parsed","value","setAttribute","String","once","hasAttribute","removeAttribute","manual","trigger","attributeChangedCallback","oldValue","newValue","isConnected","connectedCallback","style","display","addEventListener","disconnectedCallback","bootstrapTimer","userConfig","partialConfig","assign","define"],"mappings":"AAUA,MAAMA,EAA2B,CAC/BC,aAAa,EACbC,iBAAkB,mBAClBC,SAAU,CACRC,MAAO,cAIX,SAASC,EAAcC,GACrB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpDC,OAAOC,OAAOF,GACd,IAAK,MAAMG,KAAOF,OAAOG,KAAKJ,GAC5BD,EAAYC,EAAgCG,IAE9C,OAAOH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EAAciG,EAAyBC,GASjD,aAATlG,GAAuBiG,IAAaC,GAAYxE,KAAKyE,aAAezE,KAAKG,SAC3EH,KAAKuD,MAAM/B,eAAexB,KAAKe,SAEnC,CAEA,iBAAA2D,GACE1E,KAAK2E,MAAMC,QAAU,OACjB9G,EAAOb,cD9KTkF,IACJA,GAAa,EACbW,SAAS+B,iBAAiB,QAASzC,KCiLjCpC,KAAKyD,0BAA4BzD,KAAKuD,MAAMlD,UACvCL,KAAKoE,QACRpE,KAAKa,OAET,CAEA,oBAAAiE,GAGE9E,KAAKuD,MAAMjD,SACb,EC1NI,SAAUyE,EAAeC,GJgDzB,IAAoBC,EI/CpBD,IJgDqC,kBADjBC,EI9CZD,GJ+Ca/H,cACvBD,EAAQC,YAAcgI,EAAchI,aAEQ,iBAAnCgI,EAAc/H,mBACvBF,EAAQE,iBAAmB+H,EAAc/H,kBAEvC+H,EAAc9H,UAChBI,OAAO2H,OAAOlI,EAAQG,SAAU8H,EAAc9H,UAEhDU,EAAe,MK1DV8E,eAAeC,IAAI9E,EAAOX,SAASC,QACtCuF,eAAewC,OAAOrH,EAAOX,SAASC,MAAO6F,EDIjD"}
|
|
1
|
+
{"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/core/TimerCore.ts","../src/autoTrigger.ts","../src/components/Timer.ts","../src/bootstrapTimer.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n timer: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-timertarget\",\n tagNames: {\n timer: \"wcs-timer\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\n// Internal-only live handle to the mutable config. NOT part of the public API\n// (deliberately absent from exports.ts) — it is exported solely so sibling\n// modules in this package can read current settings cheaply. External consumers\n// must use getConfig() (returns a deep-frozen snapshot) / setConfig(). Mutating\n// this object directly bypasses the frozenConfig cache and is unsupported.\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable } from \"../types.js\";\n\nexport interface TimerStartOptions {\n interval?: number;\n repeat?: number;\n immediate?: boolean;\n}\n\n/**\n * Headless timer primitive. A thin, framework-agnostic wrapper around\n * `setInterval` exposed through the wc-bindable protocol: it streams `tick`\n * (a monotonically increasing counter), `elapsed` (running time in ms) and a\n * `running` flag, and is driven by the `start` / `stop` / `reset` / `pause` /\n * `resume` commands.\n *\n * `tick` and `elapsed` are both surfaced via the single `wcs-timer:tick` event\n * (read through getters, mirroring how FetchCore exposes value/status from one\n * `wcs-fetch:response` event), so an observer that binds either property is\n * notified on every fire.\n */\nexport class TimerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"tick\", event: \"wcs-timer:tick\", getter: (e: Event) => (e as CustomEvent).detail.count },\n { name: \"elapsed\", event: \"wcs-timer:tick\", getter: (e: Event) => (e as CustomEvent).detail.elapsed },\n { name: \"running\", event: \"wcs-timer:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"stop\" },\n { name: \"reset\" },\n { name: \"pause\" },\n { name: \"resume\" },\n ],\n };\n\n private _target: EventTarget;\n private _timerId: ReturnType<typeof setInterval> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and at every async start\n // (start()/resume()). A scheduled callback (setInterval/setTimeout) captures the\n // generation live via `_gen`; a fire that was already queued when the timer was\n // torn down — or superseded by a new run — has a stale gen and MUST NOT mutate\n // state or dispatch on a disposed element. _clearTimer() removes the handle, but\n // the guard is the belt-and-braces defense for a callback already in the queue.\n private _gen = 0;\n // Generation captured for the currently scheduled run, set at each async start\n // (start()/resume()). A scheduled callback compares it against the live `_gen`;\n // a stale callback (dispose() bumped `_gen` after this run was armed) bails.\n private _runGen = 0;\n // SSR (§3.8): the timer does no asynchronous probe, so readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n\n private _tick: number = 0;\n private _running: boolean = false;\n private _paused: boolean = false;\n\n // `_tick` value captured at the start of the current run. `repeat` counts ticks\n // *per run*, so the stop condition compares against this baseline rather than the\n // cumulative `_tick` (which only resets on reset()). Without it, re-starting a\n // completed bounded timer would stop after a single tick.\n private _runStartTick: number = 0;\n\n // Timer configuration (captured on start, reused by pause/resume).\n // `_immediate` is intentionally NOT a field: it is per-run intent consumed\n // entirely within start() (fire once, then schedule), so it lives as a local\n // there rather than lingering as instance state no other method reads.\n private _interval: number = 1000;\n private _repeat: number = 0; // 0 = unlimited\n\n // Elapsed-time bookkeeping. `_accumulatedElapsed` holds the time folded from\n // already-finished running segments; `_segmentStart` is the timestamp the\n // current running segment began (null when not running). The live elapsed is\n // the sum of the two — see _currentElapsed().\n private _accumulatedElapsed: number = 0;\n private _segmentStart: number | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get tick(): number {\n return this._tick;\n }\n\n get elapsed(): number {\n return this._currentElapsed();\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // SSR readiness (§3.8): resolves after the first probe. The timer is\n // command-driven with nothing to probe, so this is an already-resolved promise.\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). The timer is command-driven (start/stop/...) with no\n // ambient subscription to establish, so observe() is an idempotent no-op that\n // resolves once ready (mirroring UploadCore). dispose() tears the timer down —\n // it stops any running interval and bumps the generation so a callback already\n // queued cannot fire onto a torn-down element.\n observe(): Promise<void> {\n return this._ready;\n }\n\n dispose(): void {\n this._gen++;\n this.stop();\n }\n\n // --- State setters with event dispatch ---\n\n private _dispatchTick(): void {\n this._target.dispatchEvent(new CustomEvent(\"wcs-timer:tick\", {\n detail: { count: this._tick, elapsed: this._currentElapsed() },\n bubbles: true,\n }));\n }\n\n private _setRunning(running: boolean): void {\n if (this._running === running) return;\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-timer:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n start(options: TimerStartOptions = {}): void {\n // Idempotent while running: a redundant start() must not stack a second\n // setInterval (which would leak and double the tick rate). Reconfiguring an\n // active timer is done via stop() + start().\n if (this._running) return;\n\n // start() begins a fresh running segment, so clear any lingering pause from a\n // prior pause()-without-resume(). Without this, the timer would run while\n // _paused stayed true, leaving pause() a no-op and letting resume() overwrite\n // the live timer handle (leak + double fire).\n this._paused = false;\n\n // `interval` is persistent configuration: a non-positive / non-finite value\n // (or an omitted option) keeps the previous interval (default 1000ms). The\n // guard rejects values that would turn setInterval into a hot loop and make\n // resume()'s `accumulated % interval` arithmetic produce NaN. The Shell already\n // falls back to 1000 for invalid attributes; this is the backstop for direct\n // Core API callers.\n if (typeof options.interval === \"number\" && Number.isFinite(options.interval) && options.interval > 0) {\n this._interval = options.interval;\n }\n\n // `repeat` / `immediate` are per-run intent, NOT persistent configuration:\n // every start() re-establishes them from the options, defaulting to\n // \"unlimited\" / \"no immediate fire\" when omitted. This keeps a bare start()\n // after a bounded or one-shot run from silently inheriting the old bounds.\n // `repeat` is a field (pause/resume/_fire read it across the run); `immediate`\n // is consumed here and now, so it stays a local.\n this._repeat = (typeof options.repeat === \"number\" && options.repeat > 0) ? options.repeat : 0;\n const immediate = options.immediate === true;\n\n this._setRunning(true);\n this._segmentStart = Date.now();\n // Baseline this run's per-run repeat counting (set after _setRunning so a\n // re-start of a completed bounded timer fires the full N ticks again).\n this._runStartTick = this._tick;\n // Capture this run's generation (§3.4): a scheduled fire that outlives a\n // dispose() (which bumps `_gen`) is then recognised as stale and ignored.\n this._runGen = ++this._gen;\n\n // Fire immediately on start when requested. _fire() may stop the timer (when\n // repeat is reached), so re-check _running before scheduling the interval.\n if (immediate) {\n this._fire();\n }\n if (this._running) {\n this._timerId = setInterval(this._fire, this._interval);\n }\n }\n\n // Swap the tick period of a live timer in place, WITHOUT re-running start().\n // Unlike stop() + start(), this leaves the per-run repeat progress in flight\n // (`_repeat` and its `_runStartTick` baseline) untouched, so a bounded\n // `repeat=\"N\"` run is not re-baselined to fire N more times. It also never goes\n // through start()'s `immediate` path, so an `immediate` timer does not fire an\n // extra tick. Only re-arms the steady interval; pause()/resume() and reset() are\n // unaffected. No-op when not running (interval is then plain config, captured on\n // the next start) or when the new period is non-positive / non-finite (which\n // would turn setInterval into a hot loop and break resume()'s modulo arithmetic).\n changeInterval(interval: number): void {\n if (!this._running) return;\n if (!(typeof interval === \"number\" && Number.isFinite(interval) && interval > 0)) return;\n if (interval === this._interval) return;\n this._interval = interval;\n // Re-arm the steady ticking at the new period. The current period's progress\n // is intentionally discarded (the next tick is a full new interval away),\n // matching the boundary reset of the previous stop()+start() behaviour.\n this._clearTimer();\n this._timerId = setInterval(this._fire, this._interval);\n }\n\n stop(): void {\n this._clearTimer();\n this._foldElapsed();\n this._paused = false;\n this._setRunning(false);\n }\n\n reset(): void {\n this._clearTimer();\n this._paused = false;\n this._tick = 0;\n this._accumulatedElapsed = 0;\n this._segmentStart = null;\n this._setRunning(false);\n // Notify observers that the counter/elapsed have returned to zero.\n this._dispatchTick();\n }\n\n pause(): void {\n // Pause only a live timer; a no-op otherwise so it composes safely with the\n // declarative lifecycle. Unlike stop(), it records `_paused` so resume() can\n // tell an intentional pause from a full stop.\n if (!this._running || this._paused) return;\n this._clearTimer();\n this._foldElapsed();\n this._paused = true;\n this._setRunning(false);\n }\n\n resume(): void {\n if (!this._paused) return;\n this._paused = false;\n this._setRunning(true);\n this._segmentStart = Date.now();\n // New scheduled run after a pause: capture its generation (§3.4) so a\n // post-dispose() boundary/interval callback is recognised as stale.\n this._runGen = ++this._gen;\n // Invariant: `_interval` is fixed at start() and stays constant for the whole\n // pause/resume cycle — changeInterval() only mutates it while *running* (never\n // while paused), so the remainder arithmetic below can safely assume the same\n // period was in effect across the paused segment. Consequence for the Shell:\n // because the live interval-attribute path (attributeChangedCallback ->\n // changeInterval) is gated on `running`, an `interval` change made *while\n // paused* is silently not applied here; it is picked up only on the next\n // start() as plain config. This is by design — see README \"Commands\".\n // Resume seamlessly: a tick fires every `interval` ms of *running* time, so\n // honour the partial period consumed before the pause. Wait only the\n // remainder to the next boundary, then fall back to the steady interval.\n // (`accumulated % interval === 0` — paused exactly on a boundary — yields a\n // full interval, which is correct: the next tick is a whole period away.)\n const remainder = this._interval - (this._accumulatedElapsed % this._interval);\n this._timerId = setTimeout(this._onResumeBoundary, remainder);\n }\n\n // --- Internal ---\n\n private _onResumeBoundary = (): void => {\n // Stale-run guard (§3.4): a resume-boundary timeout that fires after dispose()\n // belongs to a torn-down run — drop it without re-arming the interval.\n if (this._runGen !== this._gen) return;\n this._timerId = null;\n this._fire();\n // _fire() may have auto-stopped the timer (repeat reached); only re-arm the\n // steady interval while still running.\n if (this._running) {\n this._timerId = setInterval(this._fire, this._interval);\n }\n };\n\n private _fire = (): void => {\n // Stale-run guard (§3.4): an interval callback queued before dispose() (which\n // bumps `_gen`) must not tick or dispatch onto a torn-down element.\n if (this._runGen !== this._gen) return;\n this._tick++;\n this._dispatchTick();\n\n // Auto-stop once this run has fired the requested number of ticks (repeat=0\n // runs forever). Counted per-run via `_runStartTick`, so a re-start after a\n // completed bounded run fires N ticks again. `once` is expressed by the Shell\n // as repeat=1.\n if (this._repeat > 0 && (this._tick - this._runStartTick) >= this._repeat) {\n this._clearTimer();\n this._foldElapsed();\n this._setRunning(false);\n }\n };\n\n private _clearTimer(): void {\n if (this._timerId !== null) {\n // `_timerId` may hold a setInterval handle (steady ticking) or a setTimeout\n // handle (the resume remainder). Clear both — per the HTML spec timers\n // share one list and clearTimeout/clearInterval each remove the entry\n // regardless of which call created it.\n clearTimeout(this._timerId);\n clearInterval(this._timerId);\n this._timerId = null;\n }\n }\n\n private _foldElapsed(): void {\n if (this._segmentStart !== null) {\n this._accumulatedElapsed += Date.now() - this._segmentStart;\n this._segmentStart = null;\n }\n }\n\n private _currentElapsed(): number {\n return this._accumulatedElapsed +\n (this._segmentStart !== null ? Date.now() - this._segmentStart : 0);\n }\n}\n","import { config } from \"./config.js\";\nimport type { Timer } from \"./components/Timer.js\";\n\nlet registered = false;\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const timerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!timerId) return;\n\n // Resolve the registered constructor at call time instead of importing Timer\n // as a value. The value import created a components/Timer.ts ⇄ autoTrigger.ts\n // cycle (Timer.connectedCallback() calls registerAutoTrigger()). instanceof\n // against the customElements registry keeps the exact same identity guarantee\n // — only the registered <wcs-timer> class matches — without the import cycle.\n const TimerCtor = customElements.get(config.tagNames.timer);\n const timerElement = document.getElementById(timerId);\n if (!TimerCtor || !(timerElement instanceof TimerCtor)) return;\n\n // Suppress the element's default action so a timer can start without\n // navigating. Intentional: do not attach data-timertarget to an element whose\n // default action you also want (real <a href> link, form-submit button) — it\n // will be cancelled. See README \"Optional DOM Triggering\".\n event.preventDefault();\n (timerElement as Timer).start();\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable } from \"../types.js\";\nimport { TimerCore } from \"../core/TimerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\nexport class Timer extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...TimerCore.wcBindable,\n properties: [\n ...TimerCore.wcBindable.properties,\n { name: \"trigger\", event: \"wcs-timer:trigger-changed\" },\n ],\n // Shell-level settable surface. `attribute` is a purely descriptive hint\n // (per SPEC-extensions.md the binding core does not act on it) naming the\n // mirrored HTML attribute, matching <wcs-geo> / <wcs-debounce>. `trigger` is a\n // momentary command-property with no backing attribute, so it carries no hint\n // (same as those packages). `start` / `stop` / `reset` / `pause` / `resume`\n // commands are inherited from the Core above.\n inputs: [\n { name: \"interval\", attribute: \"interval\" },\n { name: \"once\", attribute: \"once\" },\n { name: \"repeat\", attribute: \"repeat\" },\n { name: \"immediate\", attribute: \"immediate\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"trigger\" },\n ],\n };\n static get observedAttributes(): string[] { return [\"interval\"]; }\n\n private _core: TimerCore;\n private _trigger: boolean = false;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n private _internals: ElementInternals | null = null;\n\n constructor() {\n super();\n this._core = new TimerCore(this);\n this._internals = this._initInternals();\n this._wireStates({\n \"wcs-timer:running-changed\": (d) => ({ running: d === true }),\n });\n }\n\n // CSS state reflection (:state()) — debug-only snapshot getter. NOT part of\n // wc-bindable (not a bind target); see README \"CSS styling with :state()\".\n // MUST NOT return the live CustomStateSet (that would let callers write\n // states from outside, defeating the point of :state() being read-only).\n get debugStates(): string[] {\n return this._internals ? [...this._internals.states] : [];\n }\n\n private _initInternals(): ElementInternals | null {\n // never-throw (async-io-node-guidelines.md §3.6): attachInternals is absent\n // in happy-dom / older environments, and pre-125 Chromium rejects\n // non-dashed state names from states.add() (probed and discarded here).\n // Either case silently disables reflection — the component still works,\n // it just doesn't expose :state() selectors.\n try {\n if (typeof this.attachInternals !== \"function\") return null;\n const internals = this.attachInternals();\n internals.states.add(\"wcs-probe\");\n internals.states.delete(\"wcs-probe\");\n return internals;\n } catch {\n return null;\n }\n }\n\n private _wireStates(map: Record<string, (detail: any) => Record<string, boolean>>): void {\n if (this._internals === null) return;\n const states = this._internals.states;\n for (const [event, toStates] of Object.entries(map)) {\n this.addEventListener(event, (e) => {\n const debug = this.hasAttribute(\"debug-states\");\n for (const [name, on] of Object.entries(toStates((e as CustomEvent).detail))) {\n try {\n if (on) { states.add(name); } else { states.delete(name); }\n } catch { /* never-throw */ }\n if (debug) this.toggleAttribute(`data-wcs-state-${name}`, on);\n }\n });\n }\n }\n\n // SSR (§4.1/§4.4): the Shell exposes the Core's readiness so a server-side\n // renderer can await the connect-time probe before snapshotting. The timer has\n // no async probe (observe() resolves immediately), but the contract is uniform\n // across IO nodes.\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Attribute accessors ---\n\n get interval(): number {\n const attr = this.getAttribute(\"interval\");\n if (attr === null || attr.trim() === \"\") return 1000;\n // Strict parse via Number() (unlike parseInt, \"100px\" -> NaN, not 100),\n // matching <wcs-geo> / <wcs-debounce>. Fall back to the 1000ms default for any\n // invalid period — not only NaN but also 0 / negative values, which would\n // otherwise reach setInterval as a hot loop and break resume()'s modulo\n // arithmetic in the Core.\n const parsed = Number(attr);\n return (Number.isFinite(parsed) && parsed > 0) ? parsed : 1000;\n }\n\n set interval(value: number) {\n this.setAttribute(\"interval\", String(value));\n }\n\n get once(): boolean {\n return this.hasAttribute(\"once\");\n }\n\n set once(value: boolean) {\n if (value) {\n this.setAttribute(\"once\", \"\");\n } else {\n this.removeAttribute(\"once\");\n }\n }\n\n get repeat(): number {\n const attr = this.getAttribute(\"repeat\");\n if (attr === null || attr.trim() === \"\") return 0;\n // Strict parse via Number() (\"3px\" -> NaN, not 3), matching <wcs-geo> /\n // <wcs-debounce>. Normalise any non-positive / non-numeric value to 0\n // (= unlimited), mirroring the `interval` getter. Without this a negative\n // `repeat=\"-3\"` would leak through to start(); harmless today (Core treats\n // `_repeat <= 0` as unlimited) but the asymmetry is a trap.\n const parsed = Number(attr);\n return (Number.isFinite(parsed) && parsed > 0) ? parsed : 0;\n }\n\n set repeat(value: number) {\n this.setAttribute(\"repeat\", String(value));\n }\n\n get immediate(): boolean {\n return this.hasAttribute(\"immediate\");\n }\n\n set immediate(value: boolean) {\n if (value) {\n this.setAttribute(\"immediate\", \"\");\n } else {\n this.removeAttribute(\"immediate\");\n }\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n // --- Core delegated getters ---\n\n get tick(): number {\n return this._core.tick;\n }\n\n get elapsed(): number {\n return this._core.elapsed;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Command property ---\n\n get trigger(): boolean {\n return this._trigger;\n }\n\n set trigger(value: boolean) {\n // Momentary command-property: a false→true write starts the timer. Mirrors\n // the trigger flag on <wcs-fetch> / <wcs-ws>. Prefer the command-token\n // protocol (`command.start: $command.tick`) for state-driven starts; this\n // exists mainly for the DOM click trigger and simple boolean bindings.\n const v = !!value;\n if (v) {\n this._trigger = true;\n this.start();\n this._trigger = false;\n // The `trigger-changed` event reports the momentary flag returning to\n // false, i.e. that the trigger property *changed* — it is deliberately not\n // gated on whether start() actually began a new run. This keeps the\n // wcBindable `trigger` property's change-notification semantics consistent\n // (every false→true write produces exactly one change-back event), even\n // when start() was a no-op because the timer was already running.\n this.dispatchEvent(new CustomEvent(\"wcs-timer:trigger-changed\", {\n detail: false,\n bubbles: true,\n }));\n }\n }\n\n // --- Commands ---\n\n start(): void {\n // `once` is sugar for \"fire exactly one tick\": map it to repeat=1, but let an\n // explicit repeat attribute win when both are present.\n const repeat = this.repeat > 0 ? this.repeat : (this.once ? 1 : 0);\n this._core.start({\n interval: this.interval,\n repeat,\n immediate: this.immediate,\n });\n }\n\n stop(): void {\n this._core.stop();\n }\n\n reset(): void {\n this._core.reset();\n }\n\n pause(): void {\n this._core.pause();\n }\n\n resume(): void {\n this._core.resume();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n // Live interval changes swap the underlying setInterval period in place.\n // `tick` / `elapsed` and the per-run `repeat` progress are preserved — we\n // deliberately do NOT stop()+start(), which would re-run start() and\n // re-evaluate per-run options (re-firing `immediate` and re-baselining\n // `repeat`). `running` alone gates this: swapping the period is orthogonal to\n // *how* the timer was started, so a `manual` timer the user has explicitly\n // started gets live period changes too. A non-running timer needs no swap —\n // its next start() picks up the new attribute as plain config.\n if (name === \"interval\" && oldValue !== newValue && this.isConnected && this.running) {\n this._core.changeInterval(this.interval);\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // Establish monitoring (§3.5). observe() is a no-op that resolves once ready;\n // expose it as connectedCallbackPromise for SSR.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // dispose() stops the timer and bumps the generation so a callback already\n // queued cannot fire onto a disconnected element (§3.5 / §4.4).\n this._core.dispose();\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapTimer(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { Timer } from \"./components/Timer.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.timer)) {\n customElements.define(config.tagNames.timer, Timer);\n }\n}\n"],"names":["_config","autoTrigger","triggerAttribute","tagNames","timer","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","TimerCore","EventTarget","static","protocol","version","properties","name","event","getter","e","detail","count","elapsed","commands","_target","_timerId","_gen","_runGen","_ready","Promise","resolve","_tick","_running","_paused","_runStartTick","_interval","_repeat","_accumulatedElapsed","_segmentStart","constructor","target","super","this","tick","_currentElapsed","running","ready","observe","dispose","stop","_dispatchTick","dispatchEvent","CustomEvent","bubbles","_setRunning","start","options","interval","Number","isFinite","repeat","immediate","Date","now","_fire","setInterval","changeInterval","_clearTimer","_foldElapsed","reset","pause","resume","remainder","setTimeout","_onResumeBoundary","clearTimeout","clearInterval","registered","handleClick","Element","triggerElement","closest","timerId","getAttribute","TimerCtor","customElements","get","timerElement","document","getElementById","preventDefault","Timer","HTMLElement","wcBindable","inputs","attribute","observedAttributes","_core","_trigger","_connectedCallbackPromise","_internals","_initInternals","_wireStates","d","debugStates","states","attachInternals","internals","add","delete","map","toStates","entries","addEventListener","debug","hasAttribute","on","toggleAttribute","connectedCallbackPromise","attr","trim","parsed","value","setAttribute","String","once","removeAttribute","manual","trigger","attributeChangedCallback","oldValue","newValue","isConnected","connectedCallback","style","display","disconnectedCallback","bootstrapTimer","userConfig","partialConfig","assign","define"],"mappings":"AAUA,MAAMA,EAA2B,CAC/BC,aAAa,EACbC,iBAAkB,mBAClBC,SAAU,CACRC,MAAO,cAIX,SAASC,EAAcC,GACrB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpDC,OAAOC,OAAOF,GACd,IAAK,MAAMG,KAAOF,OAAOG,KAAKJ,GAC5BD,EAAYC,EAAgCG,IAE9C,OAAOH,CACT,CAEA,SAASK,EAAaL,GACpB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpD,MAAMM,EAAiC,CAAA,EACvC,IAAK,MAAMH,KAAOF,OAAOG,KAAKJ,GAC5BM,EAAMH,GAAOE,EAAWL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Ac9I,UAChBI,OAAO2I,OAAOlJ,EAAQG,SAAU8I,EAAc9I,UAEhDU,EAAe,MK1DV8E,eAAeC,IAAI9E,EAAOX,SAASC,QACtCuF,eAAewD,OAAOrI,EAAOX,SAASC,MAAO6F,EDIjD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wcstack/timer",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.17.0",
|
|
4
4
|
"description": "Declarative timer component for Web Components. Framework-agnostic interval/timeout primitive via wc-bindable-protocol.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.esm.js",
|