preact-homeassistant 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +54 -0
- package/dist/index.js +16 -6
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/useResizeObserver.test.tsx +151 -0
- package/src/__tests__/useWidth.test.tsx +110 -0
- package/src/index.ts +6 -0
- package/src/registerPreactCard.tsx +1 -16
- package/src/useResizeObserver.ts +88 -0
- package/src/useWidth.ts +37 -0
package/README.md
CHANGED
|
@@ -171,6 +171,60 @@ const { forecast, status, error, refetch } = useWeatherForecast('weather.home',
|
|
|
171
171
|
Generic hook for fetching data with localStorage caching. The domain-specific
|
|
172
172
|
hooks above are built on this.
|
|
173
173
|
|
|
174
|
+
### `useResizeObserver(ref, callback, deps?)`
|
|
175
|
+
|
|
176
|
+
Observe an element's size via `ResizeObserver`. The callback fires once after
|
|
177
|
+
mount with the current size, on every subsequent resize, and whenever `deps`
|
|
178
|
+
change. The callback is held in a ref, so passing a fresh closure each render
|
|
179
|
+
is safe — the observer is never re-created.
|
|
180
|
+
|
|
181
|
+
```tsx
|
|
182
|
+
const containerRef = useRef<HTMLDivElement>(null);
|
|
183
|
+
|
|
184
|
+
useResizeObserver(
|
|
185
|
+
containerRef,
|
|
186
|
+
({ width, height }) => {
|
|
187
|
+
if (width === 0 || height === 0) return; // optional, consumer's call
|
|
188
|
+
drawChart(canvasRef.current, forecast, width, height);
|
|
189
|
+
},
|
|
190
|
+
[forecast],
|
|
191
|
+
);
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
The callback is suppressed while the element is detached from the document.
|
|
195
|
+
Zero width/height is passed through — many draw routines need to guard
|
|
196
|
+
against zero dimensions (a 0-sized canvas throws `InvalidStateError` on
|
|
197
|
+
`drawImage`; ratios of measurements like `Math.ceil(width / cellSize)`
|
|
198
|
+
produce `Infinity` when a dimension is zero and infinite-loop the next
|
|
199
|
+
`for` they feed into) — but the guard belongs at the call site so the hook
|
|
200
|
+
stays general-purpose.
|
|
201
|
+
|
|
202
|
+
Sizes are read from `offsetWidth` / `offsetHeight` (CSS pixels, includes
|
|
203
|
+
padding and border).
|
|
204
|
+
|
|
205
|
+
### `useWidth(ref)`
|
|
206
|
+
|
|
207
|
+
Stateful sibling to `useResizeObserver` for the JSX path: tracks a
|
|
208
|
+
referenced element's width and re-renders the component when it changes.
|
|
209
|
+
Returns `undefined` until the first non-zero measurement, then a positive
|
|
210
|
+
number that never returns to `undefined` or `0` — transient zero-width
|
|
211
|
+
firings during HA layout transitions (dashboard switch, edit-mode toggle)
|
|
212
|
+
and detached states are silently ignored.
|
|
213
|
+
|
|
214
|
+
```tsx
|
|
215
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
216
|
+
const width = useWidth(ref);
|
|
217
|
+
return (
|
|
218
|
+
<div ref={ref}>
|
|
219
|
+
{width !== undefined && <Chart width={width} />}
|
|
220
|
+
</div>
|
|
221
|
+
);
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Use this when the width needs to appear in JSX (responsive layout, prop to
|
|
225
|
+
a sized child). For imperative use inside a draw callback, prefer
|
|
226
|
+
`useResizeObserver` directly — no state, no extra re-renders.
|
|
227
|
+
|
|
174
228
|
## Styles
|
|
175
229
|
|
|
176
230
|
Styles are registered globally via the `css\`\`` tagged template and
|
package/dist/index.js
CHANGED
|
@@ -329,21 +329,31 @@ function registerPreactCard(options) {
|
|
|
329
329
|
_shadowRoot;
|
|
330
330
|
_hasRendered = false;
|
|
331
331
|
_entityChangeListeners = /* @__PURE__ */ new Map();
|
|
332
|
+
// Pending tree teardown — see disconnectedCallback.
|
|
333
|
+
_unmountTimer;
|
|
332
334
|
constructor() {
|
|
333
335
|
super();
|
|
334
336
|
this._shadowRoot = this.attachShadow({ mode: "open" });
|
|
335
337
|
}
|
|
336
338
|
connectedCallback() {
|
|
339
|
+
if (this._unmountTimer !== void 0) {
|
|
340
|
+
clearTimeout(this._unmountTimer);
|
|
341
|
+
this._unmountTimer = void 0;
|
|
342
|
+
}
|
|
337
343
|
if (this._hass && this._config && !this._hasRendered) {
|
|
338
344
|
this._render();
|
|
339
345
|
}
|
|
340
346
|
}
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
+
disconnectedCallback() {
|
|
348
|
+
if (this._unmountTimer !== void 0) return;
|
|
349
|
+
this._unmountTimer = setTimeout(() => {
|
|
350
|
+
this._unmountTimer = void 0;
|
|
351
|
+
if (this.isConnected) return;
|
|
352
|
+
render(null, this._shadowRoot);
|
|
353
|
+
this._hasRendered = false;
|
|
354
|
+
this._entityChangeListeners.clear();
|
|
355
|
+
}, 100);
|
|
356
|
+
}
|
|
347
357
|
set hass(hass) {
|
|
348
358
|
const prevStates = this._hass?.states;
|
|
349
359
|
this._hass = hass;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/cacheUtils.ts","../src/useCallbackStable.ts","../src/HAContext.tsx","../src/styleRegistry.ts","../src/registerPreactCard.tsx"],"sourcesContent":["const CACHE_PREFIX = 'preact-ha:';\nconst CACHE_EXPIRY_MS = 24 * 60 * 60 * 1000;\n\ninterface CacheEntry<T> {\n data: T;\n timestamp: number;\n}\n\nexport function loadFromCache<T>(key: string): T | undefined {\n try {\n const raw = localStorage.getItem(`${CACHE_PREFIX}${key}`);\n if (!raw) return undefined;\n\n const entry: CacheEntry<T> = JSON.parse(raw);\n if (Date.now() - entry.timestamp > CACHE_EXPIRY_MS) {\n localStorage.removeItem(`${CACHE_PREFIX}${key}`);\n return undefined;\n }\n return entry.data;\n } catch {\n return undefined;\n }\n}\n\nexport function saveToCache<T>(key: string, data: T): void {\n try {\n const entry: CacheEntry<T> = { data, timestamp: Date.now() };\n localStorage.setItem(`${CACHE_PREFIX}${key}`, JSON.stringify(entry));\n } catch (e) {\n console.warn('[preact-homeassistant cache] Failed to save:', e);\n }\n}\n","import { useRef } from 'preact/hooks';\n\n/**\n * Creates a stable callback reference that always calls the latest version of the callback.\n * Unlike useCallback, this never changes identity, so it won't cause re-renders in children.\n *\n * @param callback The callback function to stabilize\n * @returns A stable function reference that always calls the latest callback\n */\nexport function useCallbackStable<T extends (...args: never[]) => unknown>(callback: T): T {\n const callbackRef = useRef<T>(callback);\n\n callbackRef.current = callback;\n\n // Create a stable function reference once\n const stableRef = useRef<T | null>(null);\n if (stableRef.current === null) {\n stableRef.current = ((...args: Parameters<T>) => {\n return callbackRef.current(...args);\n }) as T;\n }\n\n return stableRef.current;\n}\n","import { createContext } from 'preact';\nimport type { ComponentChildren } from 'preact';\nimport { useContext, useEffect, useMemo, useRef, useState } from 'preact/hooks';\n\nimport { loadFromCache, saveToCache } from './cacheUtils';\nimport type {\n CalendarEvent,\n CalendarEventWithSource,\n EntityForId,\n FetchStatus,\n ForecastType,\n HomeAssistant,\n ServicesForId,\n WeatherForecast,\n} from './types';\nimport { useCallbackStable } from './useCallbackStable';\n\ninterface HAStore {\n hass: HomeAssistant | undefined;\n getHass: () => HomeAssistant | undefined;\n subscribeToEntity: (entityId: string, callback: (entity: any) => void) => () => void;\n}\n\nconst HAContext = createContext<HAStore | null>(null);\n\ninterface HAProviderProps {\n hass: HomeAssistant | undefined;\n subscribeToEntity: (entityId: string, callback: (entity: any) => void) => () => void;\n children: ComponentChildren;\n}\n\nexport function HAProvider({ hass, subscribeToEntity, children }: HAProviderProps) {\n const hassRef = useRef(hass);\n hassRef.current = hass;\n\n const getHass = useCallbackStable(() => hassRef.current);\n\n const store = useMemo<HAStore>(\n () => ({\n hass: hassRef.current,\n getHass,\n subscribeToEntity,\n }),\n [getHass, subscribeToEntity],\n );\n\n return <HAContext.Provider value={store}>{children}</HAContext.Provider>;\n}\n\nfunction useHAStore(): HAStore {\n const store = useContext(HAContext);\n if (!store) {\n throw new Error('useEntity/useHass must be used within an HAProvider');\n }\n return store;\n}\n\n/**\n * Subscribe to a specific entity by ID. Re-renders only when that entity changes.\n *\n * Returns a typed entity based on the domain prefix:\n * - 'calendar.xyz' -> CalendarEntity\n * - 'weather.xyz' -> WeatherEntity\n * - 'sun.sun' -> SunEntity\n * - other domains -> HassEntity (fallback)\n */\nexport function useEntity<T extends string>(entityId: T): EntityForId<T> | undefined {\n const store = useHAStore();\n const cacheKey = `entity:${entityId}`;\n\n const [entity, setEntity] = useState<EntityForId<T> | undefined>(() => {\n const current = store.hass?.states[entityId] as EntityForId<T> | undefined;\n if (current) return current;\n return loadFromCache<EntityForId<T>>(cacheKey);\n });\n\n useEffect(() => {\n const unsubscribe = store.subscribeToEntity(entityId, (newEntity) => {\n setEntity(newEntity as EntityForId<T>);\n saveToCache(cacheKey, newEntity);\n });\n return unsubscribe;\n }, [entityId, store.subscribeToEntity, cacheKey]);\n\n return entity;\n}\n\n/**\n * Get access to the full hass object for calling services / accessing config.\n * Does NOT re-render on entity changes. Use useEntity for that.\n */\nexport function useHass(): { getHass: () => HomeAssistant | undefined } {\n const store = useHAStore();\n return { getHass: store.getHass };\n}\n\ntype ServiceCaller<T extends string> = <S extends keyof ServicesForId<T> & string>(\n service: S,\n ...args: ServicesForId<T>[S] extends undefined\n ? []\n : Record<string, never> extends Exclude<ServicesForId<T>[S], undefined>\n ? [data?: ServicesForId<T>[S]]\n : [data: ServicesForId<T>[S]]\n) => Promise<void>;\n\n/**\n * Returns a stable function that calls services on a specific HA entity.\n * The service domain is parsed from the entity ID prefix and `entity_id` is\n * auto-injected into every call. Service names and data shapes are strongly\n * typed via DomainServiceMap when the domain is registered. No-ops if hass\n * is not yet available or the entity ID is empty.\n *\n * const fanService = useService(config.entity); // `fan.${string}`\n * await fanService('turn_off');\n * await fanService('set_percentage', { percentage: 67 });\n */\nexport function useService<T extends string>(entityId: T): ServiceCaller<T> {\n const { getHass } = useHass();\n return useCallbackStable(((service: string, data?: object) => {\n const hass = getHass();\n if (!hass || !entityId.includes('.')) return Promise.resolve();\n const domain = entityId.split('.', 1)[0];\n return hass.callService(domain, service, { entity_id: entityId, ...data });\n }) as ServiceCaller<T>);\n}\n\ninterface UseCachedFetchResult<T> {\n data: T | undefined;\n status: FetchStatus;\n error: Error | undefined;\n refetch: () => void;\n}\n\n/**\n * Generic hook for fetching data with localStorage caching. Returns a cache-aware\n * status string to distinguish cached vs fresh data.\n */\nexport function useCachedFetch<T>(\n cacheKey: string,\n fetcher: () => Promise<T>,\n deps: unknown[],\n): UseCachedFetchResult<T> {\n const [data, setData] = useState<T | undefined>(() => loadFromCache<T>(cacheKey));\n const [isFresh, setIsFresh] = useState(false);\n const [isFetching, setIsFetching] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n\n const fetchIdRef = useRef(0);\n\n const doFetch = useCallbackStable(async () => {\n const fetchId = ++fetchIdRef.current;\n setIsFetching(true);\n setError(undefined);\n\n try {\n const result = await fetcher();\n if (fetchId === fetchIdRef.current) {\n setData(result);\n setIsFresh(true);\n saveToCache(cacheKey, result);\n }\n } catch (err) {\n if (fetchId === fetchIdRef.current) {\n setError(err instanceof Error ? err : new Error(String(err)));\n }\n } finally {\n if (fetchId === fetchIdRef.current) {\n setIsFetching(false);\n }\n }\n });\n\n useEffect(() => {\n doFetch();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n const status: FetchStatus = useMemo(() => {\n if (!data && isFetching) return 'loading';\n if (data && !isFresh && isFetching) return 'cached';\n if (data && isFresh && isFetching) return 'refreshing';\n return 'ready';\n }, [data, isFresh, isFetching]);\n\n return { data, status, error, refetch: doFetch };\n}\n\ninterface UseCalendarEventsResult {\n events: CalendarEvent[] | undefined;\n loading: boolean;\n error: Error | undefined;\n refetch: () => void;\n}\n\n/**\n * Fetch calendar events for a date range from a single calendar.\n */\nexport function useCalendarEvents(\n entityId: `calendar.${string}`,\n options: { start: Date; end: Date },\n): UseCalendarEventsResult {\n const { getHass } = useHass();\n const [events, setEvents] = useState<CalendarEvent[] | undefined>(undefined);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n\n const fetchIdRef = useRef(0);\n\n const fetchEvents = useCallbackStable(async () => {\n const hass = getHass();\n if (!hass?.connection) {\n setError(new Error('Home Assistant connection not available'));\n return;\n }\n\n const fetchId = ++fetchIdRef.current;\n setLoading(true);\n setError(undefined);\n\n try {\n const result = await hass.connection.sendMessagePromise<{\n response: { [entityId: string]: { events: CalendarEvent[] } };\n }>({\n type: 'call_service',\n domain: 'calendar',\n service: 'get_events',\n service_data: {\n start_date_time: options.start.toISOString(),\n end_date_time: options.end.toISOString(),\n },\n target: { entity_id: entityId },\n return_response: true,\n });\n\n if (fetchId === fetchIdRef.current) {\n const entityEvents = result.response?.[entityId]?.events ?? [];\n setEvents(entityEvents);\n setLoading(false);\n }\n } catch (err) {\n if (fetchId === fetchIdRef.current) {\n setError(err instanceof Error ? err : new Error(String(err)));\n setLoading(false);\n }\n }\n });\n\n useEffect(() => {\n fetchEvents();\n }, [entityId, options.start.getTime(), options.end.getTime(), fetchEvents]);\n\n return { events, loading, error, refetch: fetchEvents };\n}\n\ninterface UseMultiCalendarEventsResult {\n events: CalendarEventWithSource[] | undefined;\n status: FetchStatus;\n error: Error | undefined;\n refetch: () => void;\n}\n\n/**\n * Fetch events from multiple calendars for a date range, with localStorage\n * caching. Events are tagged with their source calendar ID.\n */\nexport function useMultiCalendarEvents(\n entityIds: `calendar.${string}`[],\n options: { start: Date; end: Date },\n): UseMultiCalendarEventsResult {\n const store = useHAStore();\n const { getHass } = useHass();\n\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const entityIdsKey = entityIds.join(',');\n const dateRangeKey = `${options.start.getTime()}-${options.end.getTime()}`;\n const cacheKey = `events:${entityIdsKey}:${dateRangeKey}`;\n\n const fetcher = useCallbackStable(async () => {\n const hass = getHass();\n if (!hass?.connection) {\n throw new Error('Home Assistant connection not available');\n }\n\n if (entityIds.length === 0) {\n return [];\n }\n\n const results = await Promise.all(\n entityIds.map(async (entityId) => {\n try {\n const result = await hass.connection.sendMessagePromise<{\n response: { [key: string]: { events: CalendarEvent[] } };\n }>({\n type: 'call_service',\n domain: 'calendar',\n service: 'get_events',\n service_data: {\n start_date_time: options.start.toISOString(),\n end_date_time: options.end.toISOString(),\n },\n target: { entity_id: entityId },\n return_response: true,\n });\n\n const calendarEvents = result.response?.[entityId]?.events ?? [];\n return calendarEvents.map(\n (event): CalendarEventWithSource => ({ ...event, calendarId: entityId }),\n );\n } catch (err) {\n console.error(`Failed to fetch events for ${entityId}:`, err);\n return [];\n }\n }),\n );\n\n return results.flat();\n });\n\n const {\n data: events,\n status,\n error,\n refetch,\n } = useCachedFetch(cacheKey, fetcher, [entityIdsKey, dateRangeKey]);\n\n const debouncedRefetch = useCallbackStable(() => {\n if (debounceTimerRef.current) {\n clearTimeout(debounceTimerRef.current);\n }\n debounceTimerRef.current = setTimeout(() => refetch(), 500);\n });\n\n useEffect(() => {\n const unsubscribes = entityIds.map((entityId) =>\n store.subscribeToEntity(entityId, debouncedRefetch),\n );\n return () => {\n unsubscribes.forEach((unsub) => unsub());\n if (debounceTimerRef.current) {\n clearTimeout(debounceTimerRef.current);\n }\n };\n }, [entityIdsKey, store.subscribeToEntity, debouncedRefetch]);\n\n return { events, status, error, refetch };\n}\n\ninterface UseWeatherForecastResult {\n forecast: WeatherForecast[] | undefined;\n status: FetchStatus;\n error: Error | undefined;\n refetch: () => void;\n}\n\n/**\n * Fetch weather forecast data with localStorage caching. Auto-refetches at the\n * top of each hour and when the underlying entity changes (debounced).\n */\nexport function useWeatherForecast(\n entityId: `weather.${string}`,\n type: ForecastType,\n): UseWeatherForecastResult {\n const store = useHAStore();\n const { getHass } = useHass();\n const cacheKey = `forecast:${entityId}:${type}`;\n\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const hourlyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const fetcher = useCallbackStable(async () => {\n const hass = getHass();\n if (!hass?.connection) {\n throw new Error('Home Assistant connection not available');\n }\n\n const result = await hass.connection.sendMessagePromise<{\n response: { [entityId: string]: { forecast: WeatherForecast[] } };\n }>({\n type: 'call_service',\n domain: 'weather',\n service: 'get_forecasts',\n service_data: { type },\n target: { entity_id: entityId },\n return_response: true,\n });\n\n return result.response?.[entityId]?.forecast ?? [];\n });\n\n const {\n data: forecast,\n status,\n error,\n refetch,\n } = useCachedFetch(cacheKey, fetcher, [entityId, type]);\n\n const debouncedRefetch = useCallbackStable(() => {\n if (debounceTimerRef.current) {\n clearTimeout(debounceTimerRef.current);\n }\n debounceTimerRef.current = setTimeout(() => refetch(), 500);\n });\n\n const scheduleHourlyRefetch = useCallbackStable(() => {\n if (hourlyTimerRef.current) {\n clearTimeout(hourlyTimerRef.current);\n }\n const now = new Date();\n const nextHour = new Date(now);\n nextHour.setHours(now.getHours() + 1, 0, 0, 0);\n const msUntilNextHour = nextHour.getTime() - now.getTime();\n\n hourlyTimerRef.current = setTimeout(() => {\n refetch();\n scheduleHourlyRefetch();\n }, msUntilNextHour);\n });\n\n useEffect(() => {\n scheduleHourlyRefetch();\n }, [entityId, type, scheduleHourlyRefetch]);\n\n useEffect(() => {\n const unsubscribe = store.subscribeToEntity(entityId, debouncedRefetch);\n return () => {\n unsubscribe();\n if (debounceTimerRef.current) {\n clearTimeout(debounceTimerRef.current);\n }\n if (hourlyTimerRef.current) {\n clearTimeout(hourlyTimerRef.current);\n }\n };\n }, [entityId, store.subscribeToEntity, debouncedRefetch]);\n\n return { forecast, status, error, refetch };\n}\n","// Style registry for Shadow DOM injection\n// Each .styles.ts file uses css`` which auto-registers\n\nconst styleRegistry: string[] = [];\n\n/**\n * CSS tagged template literal for syntax highlighting.\n * Automatically registers the styles with the global registry.\n */\nexport const css = (strings: TemplateStringsArray, ...values: unknown[]): string => {\n const result = strings.reduce((acc, str, i) => acc + str + (values[i] ?? ''), '');\n styleRegistry.push(result);\n return result;\n};\n\n/**\n * Register raw CSS string (e.g., from ?inline imports).\n * Only registers if not already present.\n */\nexport function registerRawStyles(styles: string): void {\n if (!styleRegistry.includes(styles)) {\n styleRegistry.push(styles);\n }\n}\n\n/**\n * Get all registered styles for Shadow DOM injection.\n */\nexport function getAllStyles(): string {\n return styleRegistry.join('\\n');\n}\n","import { type ComponentType, render } from 'preact';\nimport { HAProvider } from './HAContext';\nimport { getAllStyles } from './styleRegistry';\nimport type { HomeAssistant } from './types';\n\ninterface RegisterPreactCardOptions<TConfig> {\n type: string;\n name: string;\n description: string;\n Component: ComponentType<{ config: TConfig }>;\n ConfigComponent?: ComponentType<{\n hass: HomeAssistant;\n config: TConfig;\n onConfigChanged: (config: TConfig) => void;\n }>;\n UnconfiguredComponent?: ComponentType<{}>;\n getStubConfig?: () => Partial<TConfig>;\n}\n\ndeclare global {\n interface Window {\n customCards?: Array<{ type: string; name: string; description: string }>;\n }\n}\n\nexport function registerPreactCard<TConfig>(options: RegisterPreactCardOptions<TConfig>) {\n const {\n type,\n name,\n description,\n Component,\n ConfigComponent,\n UnconfiguredComponent,\n getStubConfig,\n } = options;\n\n class HACard extends HTMLElement {\n private _hass?: HomeAssistant;\n private _config?: TConfig;\n private _shadowRoot: ShadowRoot;\n private _hasRendered = false;\n private _entityChangeListeners = new Map<string, Set<(entity: any) => void>>();\n\n constructor() {\n super();\n this._shadowRoot = this.attachShadow({ mode: 'open' });\n }\n\n connectedCallback() {\n // HA disconnects + reconnects the element during edit-mode toggling.\n // Re-rendering on each connect causes Preact to lose its diff anchor and\n // append a duplicate tree, so only render once per attachment cycle.\n if (this._hass && this._config && !this._hasRendered) {\n this._render();\n }\n }\n\n // Intentionally no disconnectedCallback: HA detaches + reattaches the card\n // on edit-mode toggle, but the shadow root (with Preact's tree + effects)\n // travels with the host. Clearing _entityChangeListeners here would orphan\n // the still-mounted components — their useEffect cleanups never run, so\n // they think they're subscribed while the host's map is empty, and entity\n // updates stop reaching the UI.\n\n set hass(hass: HomeAssistant) {\n const prevStates = this._hass?.states;\n this._hass = hass;\n\n for (const [entityId, listeners] of this._entityChangeListeners) {\n const newState = hass.states[entityId];\n const oldState = prevStates?.[entityId];\n if (newState !== oldState) {\n listeners.forEach((listener) => listener(newState));\n }\n }\n\n // Render only when attached. HA may set hass/config before insertion;\n // rendering into a detached shadow root then again on connect duplicates\n // the tree. connectedCallback handles the detached-first-render case.\n if (!prevStates && this._config && this.isConnected) {\n this._render();\n }\n }\n\n setConfig(config: TConfig) {\n this._config = config;\n if (this._hass && this.isConnected) {\n this._render();\n }\n }\n\n private _subscribeToEntity = (entityId: string, callback: (entity: any) => void) => {\n if (!this._entityChangeListeners.has(entityId)) {\n this._entityChangeListeners.set(entityId, new Set());\n }\n this._entityChangeListeners.get(entityId)!.add(callback);\n\n return () => {\n const listeners = this._entityChangeListeners.get(entityId);\n if (listeners) {\n listeners.delete(callback);\n if (listeners.size === 0) {\n this._entityChangeListeners.delete(entityId);\n }\n }\n };\n };\n\n private _render() {\n if (!this._config || !this._hass) {\n if (UnconfiguredComponent) {\n render(<UnconfiguredComponent />, this._shadowRoot);\n }\n return;\n }\n\n render(\n <HAProvider hass={this._hass} subscribeToEntity={this._subscribeToEntity}>\n <style>{getAllStyles()}</style>\n <Component config={this._config} />\n </HAProvider>,\n this._shadowRoot,\n );\n this._hasRendered = true;\n }\n\n static getConfigElement() {\n if (ConfigComponent) {\n return document.createElement(`${type}-editor`);\n }\n return undefined;\n }\n\n static getStubConfig() {\n return getStubConfig?.() ?? {};\n }\n }\n\n customElements.define(type, HACard);\n\n if (ConfigComponent) {\n const EditorComponent = ConfigComponent;\n\n class HACardEditor extends HTMLElement {\n private _hass?: HomeAssistant;\n private _config?: TConfig;\n\n set hass(hass: HomeAssistant) {\n this._hass = hass;\n this._render();\n }\n\n setConfig(config: TConfig) {\n this._config = config;\n this._render();\n }\n\n private _fireConfigChanged = (config: TConfig) => {\n this.dispatchEvent(\n new CustomEvent('config-changed', {\n detail: { config },\n bubbles: true,\n composed: true,\n }),\n );\n };\n\n private _render() {\n if (!this._hass || !this._config) return;\n\n // Render to light DOM so HA's custom elements (ha-select etc.) work.\n render(\n <EditorComponent\n hass={this._hass}\n config={this._config}\n onConfigChanged={this._fireConfigChanged}\n />,\n this,\n );\n }\n }\n\n customElements.define(`${type}-editor`, HACardEditor);\n }\n\n window.customCards = window.customCards || [];\n window.customCards.push({ type, name, description });\n\n console.info(\n `%c ${name.toUpperCase()} %c loaded `,\n 'background: #3b82f6; color: white; font-weight: bold',\n '',\n );\n}\n"],"names":[],"mappings":";;;AAAA,MAAM,eAAe;AACrB,MAAM,kBAAkB,KAAK,KAAK,KAAK;AAOhC,SAAS,cAAiB,KAA4B;AAC3D,MAAI;AACF,UAAM,MAAM,aAAa,QAAQ,GAAG,YAAY,GAAG,GAAG,EAAE;AACxD,QAAI,CAAC,IAAK,QAAO;AAEjB,UAAM,QAAuB,KAAK,MAAM,GAAG;AAC3C,QAAI,KAAK,IAAA,IAAQ,MAAM,YAAY,iBAAiB;AAClD,mBAAa,WAAW,GAAG,YAAY,GAAG,GAAG,EAAE;AAC/C,aAAO;AAAA,IACT;AACA,WAAO,MAAM;AAAA,EACf,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,YAAe,KAAa,MAAe;AACzD,MAAI;AACF,UAAM,QAAuB,EAAE,MAAM,WAAW,KAAK,MAAI;AACzD,iBAAa,QAAQ,GAAG,YAAY,GAAG,GAAG,IAAI,KAAK,UAAU,KAAK,CAAC;AAAA,EACrE,SAAS,GAAG;AACV,YAAQ,KAAK,gDAAgD,CAAC;AAAA,EAChE;AACF;ACtBO,SAAS,kBAA2D,UAAgB;AACzF,QAAM,cAAc,OAAU,QAAQ;AAEtC,cAAY,UAAU;AAGtB,QAAM,YAAY,OAAiB,IAAI;AACvC,MAAI,UAAU,YAAY,MAAM;AAC9B,cAAU,WAAW,IAAI,SAAwB;AAC/C,aAAO,YAAY,QAAQ,GAAG,IAAI;AAAA,IACpC;AAAA,EACF;AAEA,SAAO,UAAU;AACnB;ACAA,MAAM,YAAY,c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AiB;AACzB,aAAK,UAAU;AACf,aAAK,QAAA;AAAA,MACP;AAAA,MAEQ,qBAAqB,CAAC,WAAoB;AAChD,aAAK;AAAA,UACH,IAAI,YAAY,kBAAkB;AAAA,YAChC,QAAQ,EAAE,OAAA;AAAA,YACV,SAAS;AAAA,YACT,UAAU;AAAA,UAAA,CACX;AAAA,QAAA;AAAA,MAEL;AAAA,MAEQ,UAAU;AAChB,YAAI,CAAC,KAAK,SAAS,CAAC,KAAK,QAAS;AAGlC;AAAA,UACE;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,MAAM,KAAK;AAAA,cACX,QAAQ,KAAK;AAAA,cACb,iBAAiB,KAAK;AAAA,YAAA;AAAA,UAAA;AAAA,UAExB;AAAA,QAAA;AAAA,MAEJ;AAAA,IAAA;AAGF,mBAAe,OAAO,GAAG,IAAI,WAAW,YAAY;AAAA,EACtD;AAEA,SAAO,cAAc,OAAO,eAAe,CAAA;AAC3C,SAAO,YAAY,KAAK,EAAE,MAAM,MAAM,aAAa;AAEnD,UAAQ;AAAA,IACN,MAAM,KAAK,YAAA,CAAa;AAAA,IACxB;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/cacheUtils.ts","../src/useCallbackStable.ts","../src/HAContext.tsx","../src/styleRegistry.ts","../src/registerPreactCard.tsx"],"sourcesContent":["const CACHE_PREFIX = 'preact-ha:';\nconst CACHE_EXPIRY_MS = 24 * 60 * 60 * 1000;\n\ninterface CacheEntry<T> {\n data: T;\n timestamp: number;\n}\n\nexport function loadFromCache<T>(key: string): T | undefined {\n try {\n const raw = localStorage.getItem(`${CACHE_PREFIX}${key}`);\n if (!raw) return undefined;\n\n const entry: CacheEntry<T> = JSON.parse(raw);\n if (Date.now() - entry.timestamp > CACHE_EXPIRY_MS) {\n localStorage.removeItem(`${CACHE_PREFIX}${key}`);\n return undefined;\n }\n return entry.data;\n } catch {\n return undefined;\n }\n}\n\nexport function saveToCache<T>(key: string, data: T): void {\n try {\n const entry: CacheEntry<T> = { data, timestamp: Date.now() };\n localStorage.setItem(`${CACHE_PREFIX}${key}`, JSON.stringify(entry));\n } catch (e) {\n console.warn('[preact-homeassistant cache] Failed to save:', e);\n }\n}\n","import { useRef } from 'preact/hooks';\n\n/**\n * Creates a stable callback reference that always calls the latest version of the callback.\n * Unlike useCallback, this never changes identity, so it won't cause re-renders in children.\n *\n * @param callback The callback function to stabilize\n * @returns A stable function reference that always calls the latest callback\n */\nexport function useCallbackStable<T extends (...args: never[]) => unknown>(callback: T): T {\n const callbackRef = useRef<T>(callback);\n\n callbackRef.current = callback;\n\n // Create a stable function reference once\n const stableRef = useRef<T | null>(null);\n if (stableRef.current === null) {\n stableRef.current = ((...args: Parameters<T>) => {\n return callbackRef.current(...args);\n }) as T;\n }\n\n return stableRef.current;\n}\n","import { createContext } from 'preact';\nimport type { ComponentChildren } from 'preact';\nimport { useContext, useEffect, useMemo, useRef, useState } from 'preact/hooks';\n\nimport { loadFromCache, saveToCache } from './cacheUtils';\nimport type {\n CalendarEvent,\n CalendarEventWithSource,\n EntityForId,\n FetchStatus,\n ForecastType,\n HomeAssistant,\n ServicesForId,\n WeatherForecast,\n} from './types';\nimport { useCallbackStable } from './useCallbackStable';\n\ninterface HAStore {\n hass: HomeAssistant | undefined;\n getHass: () => HomeAssistant | undefined;\n subscribeToEntity: (entityId: string, callback: (entity: any) => void) => () => void;\n}\n\nconst HAContext = createContext<HAStore | null>(null);\n\ninterface HAProviderProps {\n hass: HomeAssistant | undefined;\n subscribeToEntity: (entityId: string, callback: (entity: any) => void) => () => void;\n children: ComponentChildren;\n}\n\nexport function HAProvider({ hass, subscribeToEntity, children }: HAProviderProps) {\n const hassRef = useRef(hass);\n hassRef.current = hass;\n\n const getHass = useCallbackStable(() => hassRef.current);\n\n const store = useMemo<HAStore>(\n () => ({\n hass: hassRef.current,\n getHass,\n subscribeToEntity,\n }),\n [getHass, subscribeToEntity],\n );\n\n return <HAContext.Provider value={store}>{children}</HAContext.Provider>;\n}\n\nfunction useHAStore(): HAStore {\n const store = useContext(HAContext);\n if (!store) {\n throw new Error('useEntity/useHass must be used within an HAProvider');\n }\n return store;\n}\n\n/**\n * Subscribe to a specific entity by ID. Re-renders only when that entity changes.\n *\n * Returns a typed entity based on the domain prefix:\n * - 'calendar.xyz' -> CalendarEntity\n * - 'weather.xyz' -> WeatherEntity\n * - 'sun.sun' -> SunEntity\n * - other domains -> HassEntity (fallback)\n */\nexport function useEntity<T extends string>(entityId: T): EntityForId<T> | undefined {\n const store = useHAStore();\n const cacheKey = `entity:${entityId}`;\n\n const [entity, setEntity] = useState<EntityForId<T> | undefined>(() => {\n const current = store.hass?.states[entityId] as EntityForId<T> | undefined;\n if (current) return current;\n return loadFromCache<EntityForId<T>>(cacheKey);\n });\n\n useEffect(() => {\n const unsubscribe = store.subscribeToEntity(entityId, (newEntity) => {\n setEntity(newEntity as EntityForId<T>);\n saveToCache(cacheKey, newEntity);\n });\n return unsubscribe;\n }, [entityId, store.subscribeToEntity, cacheKey]);\n\n return entity;\n}\n\n/**\n * Get access to the full hass object for calling services / accessing config.\n * Does NOT re-render on entity changes. Use useEntity for that.\n */\nexport function useHass(): { getHass: () => HomeAssistant | undefined } {\n const store = useHAStore();\n return { getHass: store.getHass };\n}\n\ntype ServiceCaller<T extends string> = <S extends keyof ServicesForId<T> & string>(\n service: S,\n ...args: ServicesForId<T>[S] extends undefined\n ? []\n : Record<string, never> extends Exclude<ServicesForId<T>[S], undefined>\n ? [data?: ServicesForId<T>[S]]\n : [data: ServicesForId<T>[S]]\n) => Promise<void>;\n\n/**\n * Returns a stable function that calls services on a specific HA entity.\n * The service domain is parsed from the entity ID prefix and `entity_id` is\n * auto-injected into every call. Service names and data shapes are strongly\n * typed via DomainServiceMap when the domain is registered. No-ops if hass\n * is not yet available or the entity ID is empty.\n *\n * const fanService = useService(config.entity); // `fan.${string}`\n * await fanService('turn_off');\n * await fanService('set_percentage', { percentage: 67 });\n */\nexport function useService<T extends string>(entityId: T): ServiceCaller<T> {\n const { getHass } = useHass();\n return useCallbackStable(((service: string, data?: object) => {\n const hass = getHass();\n if (!hass || !entityId.includes('.')) return Promise.resolve();\n const domain = entityId.split('.', 1)[0];\n return hass.callService(domain, service, { entity_id: entityId, ...data });\n }) as ServiceCaller<T>);\n}\n\ninterface UseCachedFetchResult<T> {\n data: T | undefined;\n status: FetchStatus;\n error: Error | undefined;\n refetch: () => void;\n}\n\n/**\n * Generic hook for fetching data with localStorage caching. Returns a cache-aware\n * status string to distinguish cached vs fresh data.\n */\nexport function useCachedFetch<T>(\n cacheKey: string,\n fetcher: () => Promise<T>,\n deps: unknown[],\n): UseCachedFetchResult<T> {\n const [data, setData] = useState<T | undefined>(() => loadFromCache<T>(cacheKey));\n const [isFresh, setIsFresh] = useState(false);\n const [isFetching, setIsFetching] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n\n const fetchIdRef = useRef(0);\n\n const doFetch = useCallbackStable(async () => {\n const fetchId = ++fetchIdRef.current;\n setIsFetching(true);\n setError(undefined);\n\n try {\n const result = await fetcher();\n if (fetchId === fetchIdRef.current) {\n setData(result);\n setIsFresh(true);\n saveToCache(cacheKey, result);\n }\n } catch (err) {\n if (fetchId === fetchIdRef.current) {\n setError(err instanceof Error ? err : new Error(String(err)));\n }\n } finally {\n if (fetchId === fetchIdRef.current) {\n setIsFetching(false);\n }\n }\n });\n\n useEffect(() => {\n doFetch();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n const status: FetchStatus = useMemo(() => {\n if (!data && isFetching) return 'loading';\n if (data && !isFresh && isFetching) return 'cached';\n if (data && isFresh && isFetching) return 'refreshing';\n return 'ready';\n }, [data, isFresh, isFetching]);\n\n return { data, status, error, refetch: doFetch };\n}\n\ninterface UseCalendarEventsResult {\n events: CalendarEvent[] | undefined;\n loading: boolean;\n error: Error | undefined;\n refetch: () => void;\n}\n\n/**\n * Fetch calendar events for a date range from a single calendar.\n */\nexport function useCalendarEvents(\n entityId: `calendar.${string}`,\n options: { start: Date; end: Date },\n): UseCalendarEventsResult {\n const { getHass } = useHass();\n const [events, setEvents] = useState<CalendarEvent[] | undefined>(undefined);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n\n const fetchIdRef = useRef(0);\n\n const fetchEvents = useCallbackStable(async () => {\n const hass = getHass();\n if (!hass?.connection) {\n setError(new Error('Home Assistant connection not available'));\n return;\n }\n\n const fetchId = ++fetchIdRef.current;\n setLoading(true);\n setError(undefined);\n\n try {\n const result = await hass.connection.sendMessagePromise<{\n response: { [entityId: string]: { events: CalendarEvent[] } };\n }>({\n type: 'call_service',\n domain: 'calendar',\n service: 'get_events',\n service_data: {\n start_date_time: options.start.toISOString(),\n end_date_time: options.end.toISOString(),\n },\n target: { entity_id: entityId },\n return_response: true,\n });\n\n if (fetchId === fetchIdRef.current) {\n const entityEvents = result.response?.[entityId]?.events ?? [];\n setEvents(entityEvents);\n setLoading(false);\n }\n } catch (err) {\n if (fetchId === fetchIdRef.current) {\n setError(err instanceof Error ? err : new Error(String(err)));\n setLoading(false);\n }\n }\n });\n\n useEffect(() => {\n fetchEvents();\n }, [entityId, options.start.getTime(), options.end.getTime(), fetchEvents]);\n\n return { events, loading, error, refetch: fetchEvents };\n}\n\ninterface UseMultiCalendarEventsResult {\n events: CalendarEventWithSource[] | undefined;\n status: FetchStatus;\n error: Error | undefined;\n refetch: () => void;\n}\n\n/**\n * Fetch events from multiple calendars for a date range, with localStorage\n * caching. Events are tagged with their source calendar ID.\n */\nexport function useMultiCalendarEvents(\n entityIds: `calendar.${string}`[],\n options: { start: Date; end: Date },\n): UseMultiCalendarEventsResult {\n const store = useHAStore();\n const { getHass } = useHass();\n\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const entityIdsKey = entityIds.join(',');\n const dateRangeKey = `${options.start.getTime()}-${options.end.getTime()}`;\n const cacheKey = `events:${entityIdsKey}:${dateRangeKey}`;\n\n const fetcher = useCallbackStable(async () => {\n const hass = getHass();\n if (!hass?.connection) {\n throw new Error('Home Assistant connection not available');\n }\n\n if (entityIds.length === 0) {\n return [];\n }\n\n const results = await Promise.all(\n entityIds.map(async (entityId) => {\n try {\n const result = await hass.connection.sendMessagePromise<{\n response: { [key: string]: { events: CalendarEvent[] } };\n }>({\n type: 'call_service',\n domain: 'calendar',\n service: 'get_events',\n service_data: {\n start_date_time: options.start.toISOString(),\n end_date_time: options.end.toISOString(),\n },\n target: { entity_id: entityId },\n return_response: true,\n });\n\n const calendarEvents = result.response?.[entityId]?.events ?? [];\n return calendarEvents.map(\n (event): CalendarEventWithSource => ({ ...event, calendarId: entityId }),\n );\n } catch (err) {\n console.error(`Failed to fetch events for ${entityId}:`, err);\n return [];\n }\n }),\n );\n\n return results.flat();\n });\n\n const {\n data: events,\n status,\n error,\n refetch,\n } = useCachedFetch(cacheKey, fetcher, [entityIdsKey, dateRangeKey]);\n\n const debouncedRefetch = useCallbackStable(() => {\n if (debounceTimerRef.current) {\n clearTimeout(debounceTimerRef.current);\n }\n debounceTimerRef.current = setTimeout(() => refetch(), 500);\n });\n\n useEffect(() => {\n const unsubscribes = entityIds.map((entityId) =>\n store.subscribeToEntity(entityId, debouncedRefetch),\n );\n return () => {\n unsubscribes.forEach((unsub) => unsub());\n if (debounceTimerRef.current) {\n clearTimeout(debounceTimerRef.current);\n }\n };\n }, [entityIdsKey, store.subscribeToEntity, debouncedRefetch]);\n\n return { events, status, error, refetch };\n}\n\ninterface UseWeatherForecastResult {\n forecast: WeatherForecast[] | undefined;\n status: FetchStatus;\n error: Error | undefined;\n refetch: () => void;\n}\n\n/**\n * Fetch weather forecast data with localStorage caching. Auto-refetches at the\n * top of each hour and when the underlying entity changes (debounced).\n */\nexport function useWeatherForecast(\n entityId: `weather.${string}`,\n type: ForecastType,\n): UseWeatherForecastResult {\n const store = useHAStore();\n const { getHass } = useHass();\n const cacheKey = `forecast:${entityId}:${type}`;\n\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const hourlyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const fetcher = useCallbackStable(async () => {\n const hass = getHass();\n if (!hass?.connection) {\n throw new Error('Home Assistant connection not available');\n }\n\n const result = await hass.connection.sendMessagePromise<{\n response: { [entityId: string]: { forecast: WeatherForecast[] } };\n }>({\n type: 'call_service',\n domain: 'weather',\n service: 'get_forecasts',\n service_data: { type },\n target: { entity_id: entityId },\n return_response: true,\n });\n\n return result.response?.[entityId]?.forecast ?? [];\n });\n\n const {\n data: forecast,\n status,\n error,\n refetch,\n } = useCachedFetch(cacheKey, fetcher, [entityId, type]);\n\n const debouncedRefetch = useCallbackStable(() => {\n if (debounceTimerRef.current) {\n clearTimeout(debounceTimerRef.current);\n }\n debounceTimerRef.current = setTimeout(() => refetch(), 500);\n });\n\n const scheduleHourlyRefetch = useCallbackStable(() => {\n if (hourlyTimerRef.current) {\n clearTimeout(hourlyTimerRef.current);\n }\n const now = new Date();\n const nextHour = new Date(now);\n nextHour.setHours(now.getHours() + 1, 0, 0, 0);\n const msUntilNextHour = nextHour.getTime() - now.getTime();\n\n hourlyTimerRef.current = setTimeout(() => {\n refetch();\n scheduleHourlyRefetch();\n }, msUntilNextHour);\n });\n\n useEffect(() => {\n scheduleHourlyRefetch();\n }, [entityId, type, scheduleHourlyRefetch]);\n\n useEffect(() => {\n const unsubscribe = store.subscribeToEntity(entityId, debouncedRefetch);\n return () => {\n unsubscribe();\n if (debounceTimerRef.current) {\n clearTimeout(debounceTimerRef.current);\n }\n if (hourlyTimerRef.current) {\n clearTimeout(hourlyTimerRef.current);\n }\n };\n }, [entityId, store.subscribeToEntity, debouncedRefetch]);\n\n return { forecast, status, error, refetch };\n}\n","// Style registry for Shadow DOM injection\n// Each .styles.ts file uses css`` which auto-registers\n\nconst styleRegistry: string[] = [];\n\n/**\n * CSS tagged template literal for syntax highlighting.\n * Automatically registers the styles with the global registry.\n */\nexport const css = (strings: TemplateStringsArray, ...values: unknown[]): string => {\n const result = strings.reduce((acc, str, i) => acc + str + (values[i] ?? ''), '');\n styleRegistry.push(result);\n return result;\n};\n\n/**\n * Register raw CSS string (e.g., from ?inline imports).\n * Only registers if not already present.\n */\nexport function registerRawStyles(styles: string): void {\n if (!styleRegistry.includes(styles)) {\n styleRegistry.push(styles);\n }\n}\n\n/**\n * Get all registered styles for Shadow DOM injection.\n */\nexport function getAllStyles(): string {\n return styleRegistry.join('\\n');\n}\n","import { type ComponentType, render } from 'preact';\nimport { HAProvider } from './HAContext';\nimport { getAllStyles } from './styleRegistry';\nimport type { HomeAssistant } from './types';\n\ninterface RegisterPreactCardOptions<TConfig> {\n type: string;\n name: string;\n description: string;\n Component: ComponentType<{ config: TConfig }>;\n ConfigComponent?: ComponentType<{\n hass: HomeAssistant;\n config: TConfig;\n onConfigChanged: (config: TConfig) => void;\n }>;\n UnconfiguredComponent?: ComponentType<{}>;\n getStubConfig?: () => Partial<TConfig>;\n}\n\ndeclare global {\n interface Window {\n customCards?: Array<{ type: string; name: string; description: string }>;\n }\n}\n\nexport function registerPreactCard<TConfig>(options: RegisterPreactCardOptions<TConfig>) {\n const {\n type,\n name,\n description,\n Component,\n ConfigComponent,\n UnconfiguredComponent,\n getStubConfig,\n } = options;\n\n class HACard extends HTMLElement {\n private _hass?: HomeAssistant;\n private _config?: TConfig;\n private _shadowRoot: ShadowRoot;\n private _hasRendered = false;\n private _entityChangeListeners = new Map<string, Set<(entity: any) => void>>();\n // Pending tree teardown — see disconnectedCallback.\n private _unmountTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor() {\n super();\n this._shadowRoot = this.attachShadow({ mode: 'open' });\n }\n\n connectedCallback() {\n // If a teardown was scheduled by a recent disconnect, cancel it: HA is\n // doing a transient detach/reattach (edit-mode toggle, drag/drop) and\n // the tree is still valid.\n if (this._unmountTimer !== undefined) {\n clearTimeout(this._unmountTimer);\n this._unmountTimer = undefined;\n }\n if (this._hass && this._config && !this._hasRendered) {\n this._render();\n }\n }\n\n disconnectedCallback() {\n // HA disconnects + reconnects the element during edit-mode toggling and\n // drag-and-drop. A reconnect lands within a tick. If we're still\n // detached after a short delay, tear the Preact tree down properly so\n // useEffect cleanups run (e.g. Leaflet's map.remove(), which removes\n // its non-passive touch/wheel listeners from window/document).\n // Leaving the tree mounted on a detached shadow root leaks listeners on\n // every reconnect cycle and eventually locks up the UI.\n if (this._unmountTimer !== undefined) return;\n this._unmountTimer = setTimeout(() => {\n this._unmountTimer = undefined;\n if (this.isConnected) return;\n render(null, this._shadowRoot);\n this._hasRendered = false;\n this._entityChangeListeners.clear();\n }, 100);\n }\n\n set hass(hass: HomeAssistant) {\n const prevStates = this._hass?.states;\n this._hass = hass;\n\n for (const [entityId, listeners] of this._entityChangeListeners) {\n const newState = hass.states[entityId];\n const oldState = prevStates?.[entityId];\n if (newState !== oldState) {\n listeners.forEach((listener) => listener(newState));\n }\n }\n\n // Render only when attached. HA may set hass/config before insertion;\n // rendering into a detached shadow root then again on connect duplicates\n // the tree. connectedCallback handles the detached-first-render case.\n if (!prevStates && this._config && this.isConnected) {\n this._render();\n }\n }\n\n setConfig(config: TConfig) {\n this._config = config;\n if (this._hass && this.isConnected) {\n this._render();\n }\n }\n\n private _subscribeToEntity = (entityId: string, callback: (entity: any) => void) => {\n if (!this._entityChangeListeners.has(entityId)) {\n this._entityChangeListeners.set(entityId, new Set());\n }\n this._entityChangeListeners.get(entityId)!.add(callback);\n\n return () => {\n const listeners = this._entityChangeListeners.get(entityId);\n if (listeners) {\n listeners.delete(callback);\n if (listeners.size === 0) {\n this._entityChangeListeners.delete(entityId);\n }\n }\n };\n };\n\n private _render() {\n if (!this._config || !this._hass) {\n if (UnconfiguredComponent) {\n render(<UnconfiguredComponent />, this._shadowRoot);\n }\n return;\n }\n\n render(\n <HAProvider hass={this._hass} subscribeToEntity={this._subscribeToEntity}>\n <style>{getAllStyles()}</style>\n <Component config={this._config} />\n </HAProvider>,\n this._shadowRoot,\n );\n this._hasRendered = true;\n }\n\n static getConfigElement() {\n if (ConfigComponent) {\n return document.createElement(`${type}-editor`);\n }\n return undefined;\n }\n\n static getStubConfig() {\n return getStubConfig?.() ?? {};\n }\n }\n\n customElements.define(type, HACard);\n\n if (ConfigComponent) {\n const EditorComponent = ConfigComponent;\n\n class HACardEditor extends HTMLElement {\n private _hass?: HomeAssistant;\n private _config?: TConfig;\n\n set hass(hass: HomeAssistant) {\n this._hass = hass;\n this._render();\n }\n\n setConfig(config: TConfig) {\n this._config = config;\n this._render();\n }\n\n private _fireConfigChanged = (config: TConfig) => {\n this.dispatchEvent(\n new CustomEvent('config-changed', {\n detail: { config },\n bubbles: true,\n composed: true,\n }),\n );\n };\n\n private _render() {\n if (!this._hass || !this._config) return;\n\n // Render to light DOM so HA's custom elements (ha-select etc.) work.\n render(\n <EditorComponent\n hass={this._hass}\n config={this._config}\n onConfigChanged={this._fireConfigChanged}\n />,\n this,\n );\n }\n }\n\n customElements.define(`${type}-editor`, HACardEditor);\n }\n\n window.customCards = window.customCards || [];\n window.customCards.push({ type, name, description });\n\n console.info(\n `%c ${name.toUpperCase()} %c loaded `,\n 'background: #3b82f6; color: white; font-weight: bold',\n '',\n );\n}\n"],"names":[],"mappings":";;;AAAA,MAAM,eAAe;AACrB,MAAM,kBAAkB,KAAK,KAAK,KAAK;AAOhC,SAAS,cAAiB,KAA4B;AAC3D,MAAI;AACF,UAAM,MAAM,aAAa,QAAQ,GAAG,YAAY,GAAG,GAAG,EAAE;AACxD,QAAI,CAAC,IAAK,QAAO;AAEjB,UAAM,QAAuB,KAAK,MAAM,GAAG;AAC3C,QAAI,KAAK,IAAA,IAAQ,MAAM,YAAY,iBAAiB;AAClD,mBAAa,WAAW,GAAG,YAAY,GAAG,GAAG,EAAE;AAC/C,aAAO;AAAA,IACT;AACA,WAAO,MAAM;AAAA,EACf,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,YAAe,KAAa,MAAe;AACzD,MAAI;AACF,UAAM,QAAuB,EAAE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;AAAA,MAEJ;AAAA,IAAA;AAGF,mBAAe,OAAO,GAAG,IAAI,WAAW,YAAY;AAAA,EACtD;AAEA,SAAO,cAAc,OAAO,eAAe,CAAA;AAC3C,SAAO,YAAY,KAAK,EAAE,MAAM,MAAM,aAAa;AAEnD,UAAQ;AAAA,IACN,MAAM,KAAK,YAAA,CAAa;AAAA,IACxB;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
package/package.json
CHANGED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { act, render } from '@testing-library/preact';
|
|
2
|
+
import { useRef } from 'preact/hooks';
|
|
3
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
4
|
+
import { type ElementSize, useResizeObserver } from '../useResizeObserver';
|
|
5
|
+
|
|
6
|
+
// jsdom doesn't implement ResizeObserver. Provide a controllable stub so we
|
|
7
|
+
// can drive size changes deterministically.
|
|
8
|
+
type StubObserver = {
|
|
9
|
+
observe: ReturnType<typeof vi.fn>;
|
|
10
|
+
disconnect: ReturnType<typeof vi.fn>;
|
|
11
|
+
trigger: () => void;
|
|
12
|
+
};
|
|
13
|
+
const liveObservers: StubObserver[] = [];
|
|
14
|
+
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
liveObservers.length = 0;
|
|
17
|
+
(globalThis as any).ResizeObserver = class {
|
|
18
|
+
private cb: () => void;
|
|
19
|
+
public observe: any;
|
|
20
|
+
public disconnect: any;
|
|
21
|
+
constructor(cb: () => void) {
|
|
22
|
+
this.cb = cb;
|
|
23
|
+
this.observe = vi.fn();
|
|
24
|
+
this.disconnect = vi.fn(() => {
|
|
25
|
+
const idx = liveObservers.findIndex((o) => o.observe === this.observe);
|
|
26
|
+
if (idx !== -1) liveObservers.splice(idx, 1);
|
|
27
|
+
});
|
|
28
|
+
liveObservers.push({
|
|
29
|
+
observe: this.observe,
|
|
30
|
+
disconnect: this.disconnect,
|
|
31
|
+
trigger: () => this.cb(),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
afterEach(() => {
|
|
38
|
+
(globalThis as any).ResizeObserver = undefined;
|
|
39
|
+
document.body.innerHTML = '';
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
function setSize(el: HTMLElement, width: number, height: number) {
|
|
43
|
+
Object.defineProperty(el, 'offsetWidth', { configurable: true, value: width });
|
|
44
|
+
Object.defineProperty(el, 'offsetHeight', { configurable: true, value: height });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function Probe({
|
|
48
|
+
callback,
|
|
49
|
+
deps,
|
|
50
|
+
initialWidth = 400,
|
|
51
|
+
initialHeight = 80,
|
|
52
|
+
}: {
|
|
53
|
+
callback: (size: ElementSize) => void;
|
|
54
|
+
deps?: unknown[];
|
|
55
|
+
initialWidth?: number;
|
|
56
|
+
initialHeight?: number;
|
|
57
|
+
}) {
|
|
58
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
59
|
+
// Apply size to the element synchronously before useResizeObserver's effect
|
|
60
|
+
// runs by relying on the callback ref pattern: the ref is populated before
|
|
61
|
+
// useEffect fires.
|
|
62
|
+
useResizeObserver(
|
|
63
|
+
ref,
|
|
64
|
+
(size) => {
|
|
65
|
+
callback(size);
|
|
66
|
+
},
|
|
67
|
+
deps,
|
|
68
|
+
);
|
|
69
|
+
return (
|
|
70
|
+
<div
|
|
71
|
+
ref={(el) => {
|
|
72
|
+
if (el) {
|
|
73
|
+
ref.current = el;
|
|
74
|
+
setSize(el, initialWidth, initialHeight);
|
|
75
|
+
}
|
|
76
|
+
}}
|
|
77
|
+
/>
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
describe('useResizeObserver', () => {
|
|
82
|
+
it('fires once with the current size after mount', () => {
|
|
83
|
+
const cb = vi.fn();
|
|
84
|
+
render(<Probe callback={cb} initialWidth={300} initialHeight={150} />);
|
|
85
|
+
act(() => liveObservers[0].trigger());
|
|
86
|
+
expect(cb).toHaveBeenCalledTimes(1);
|
|
87
|
+
expect(cb).toHaveBeenCalledWith({ width: 300, height: 150 });
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('fires again when the element resizes', () => {
|
|
91
|
+
const cb = vi.fn();
|
|
92
|
+
const { container } = render(<Probe callback={cb} />);
|
|
93
|
+
act(() => liveObservers[0].trigger());
|
|
94
|
+
cb.mockClear();
|
|
95
|
+
|
|
96
|
+
const el = container.firstChild as HTMLElement;
|
|
97
|
+
setSize(el, 500, 100);
|
|
98
|
+
act(() => liveObservers[0].trigger());
|
|
99
|
+
|
|
100
|
+
expect(cb).toHaveBeenCalledWith({ width: 500, height: 100 });
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('delivers zero dimensions to the callback (consumer decides)', () => {
|
|
104
|
+
const cb = vi.fn();
|
|
105
|
+
render(<Probe callback={cb} initialWidth={0} initialHeight={80} />);
|
|
106
|
+
act(() => liveObservers[0].trigger());
|
|
107
|
+
expect(cb).toHaveBeenCalledWith({ width: 0, height: 80 });
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('does not fire when the element is detached', () => {
|
|
111
|
+
const cb = vi.fn();
|
|
112
|
+
const { container, unmount } = render(<Probe callback={cb} />);
|
|
113
|
+
const el = container.firstChild as HTMLElement;
|
|
114
|
+
setSize(el, 400, 80);
|
|
115
|
+
|
|
116
|
+
// Detach without unmounting Preact (simulates HA moving the host).
|
|
117
|
+
el.remove();
|
|
118
|
+
act(() => liveObservers[0]?.trigger());
|
|
119
|
+
|
|
120
|
+
expect(cb).not.toHaveBeenCalled();
|
|
121
|
+
unmount();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('re-fires when deps change', () => {
|
|
125
|
+
const cb = vi.fn();
|
|
126
|
+
const { rerender } = render(<Probe callback={cb} deps={[1]} />);
|
|
127
|
+
act(() => liveObservers[0].trigger());
|
|
128
|
+
cb.mockClear();
|
|
129
|
+
|
|
130
|
+
rerender(<Probe callback={cb} deps={[2]} />);
|
|
131
|
+
expect(cb).toHaveBeenCalledWith({ width: 400, height: 80 });
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it('does not re-fire on the mount run of the deps effect', () => {
|
|
135
|
+
// The observer fires once on .observe(). The deps effect's first-mount run
|
|
136
|
+
// must not double-fire with the same dimensions.
|
|
137
|
+
const cb = vi.fn();
|
|
138
|
+
render(<Probe callback={cb} deps={[1]} />);
|
|
139
|
+
act(() => liveObservers[0].trigger());
|
|
140
|
+
expect(cb).toHaveBeenCalledTimes(1);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('disconnects the observer on unmount', () => {
|
|
144
|
+
const cb = vi.fn();
|
|
145
|
+
const { unmount } = render(<Probe callback={cb} />);
|
|
146
|
+
const observer = liveObservers[0];
|
|
147
|
+
expect(observer.disconnect).not.toHaveBeenCalled();
|
|
148
|
+
unmount();
|
|
149
|
+
expect(observer.disconnect).toHaveBeenCalled();
|
|
150
|
+
});
|
|
151
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { act, render } from '@testing-library/preact';
|
|
2
|
+
import { useRef } from 'preact/hooks';
|
|
3
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
4
|
+
import { useWidth } from '../useWidth';
|
|
5
|
+
|
|
6
|
+
// Controllable ResizeObserver stub (same shape as useResizeObserver.test).
|
|
7
|
+
type StubObserver = {
|
|
8
|
+
observe: ReturnType<typeof vi.fn>;
|
|
9
|
+
disconnect: ReturnType<typeof vi.fn>;
|
|
10
|
+
trigger: () => void;
|
|
11
|
+
};
|
|
12
|
+
const liveObservers: StubObserver[] = [];
|
|
13
|
+
|
|
14
|
+
beforeEach(() => {
|
|
15
|
+
liveObservers.length = 0;
|
|
16
|
+
(globalThis as any).ResizeObserver = class {
|
|
17
|
+
private cb: () => void;
|
|
18
|
+
public observe: any;
|
|
19
|
+
public disconnect: any;
|
|
20
|
+
constructor(cb: () => void) {
|
|
21
|
+
this.cb = cb;
|
|
22
|
+
this.observe = vi.fn();
|
|
23
|
+
this.disconnect = vi.fn(() => {
|
|
24
|
+
const idx = liveObservers.findIndex((o) => o.observe === this.observe);
|
|
25
|
+
if (idx !== -1) liveObservers.splice(idx, 1);
|
|
26
|
+
});
|
|
27
|
+
liveObservers.push({
|
|
28
|
+
observe: this.observe,
|
|
29
|
+
disconnect: this.disconnect,
|
|
30
|
+
trigger: () => this.cb(),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
afterEach(() => {
|
|
37
|
+
(globalThis as any).ResizeObserver = undefined;
|
|
38
|
+
document.body.innerHTML = '';
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
function setSize(el: HTMLElement, width: number, height: number) {
|
|
42
|
+
Object.defineProperty(el, 'offsetWidth', { configurable: true, value: width });
|
|
43
|
+
Object.defineProperty(el, 'offsetHeight', { configurable: true, value: height });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let lastWidth: number | undefined;
|
|
47
|
+
|
|
48
|
+
function Probe({ initialWidth = 400 }: { initialWidth?: number }) {
|
|
49
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
50
|
+
lastWidth = useWidth(ref);
|
|
51
|
+
return (
|
|
52
|
+
<div
|
|
53
|
+
ref={(el) => {
|
|
54
|
+
if (el) {
|
|
55
|
+
ref.current = el;
|
|
56
|
+
setSize(el, initialWidth, 80);
|
|
57
|
+
}
|
|
58
|
+
}}
|
|
59
|
+
/>
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
describe('useWidth', () => {
|
|
64
|
+
beforeEach(() => {
|
|
65
|
+
lastWidth = undefined;
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('returns undefined until the first measurement', () => {
|
|
69
|
+
render(<Probe />);
|
|
70
|
+
expect(lastWidth).toBeUndefined();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('returns the observed width after the first non-zero measurement', () => {
|
|
74
|
+
const { container } = render(<Probe initialWidth={400} />);
|
|
75
|
+
act(() => liveObservers[0].trigger());
|
|
76
|
+
expect(lastWidth).toBe(400);
|
|
77
|
+
|
|
78
|
+
const el = container.firstChild as HTMLElement;
|
|
79
|
+
setSize(el, 500, 80);
|
|
80
|
+
act(() => liveObservers[0].trigger());
|
|
81
|
+
expect(lastWidth).toBe(500);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('ignores zero-width measurements (keeps last good value)', () => {
|
|
85
|
+
const { container } = render(<Probe initialWidth={400} />);
|
|
86
|
+
act(() => liveObservers[0].trigger());
|
|
87
|
+
expect(lastWidth).toBe(400);
|
|
88
|
+
|
|
89
|
+
const el = container.firstChild as HTMLElement;
|
|
90
|
+
setSize(el, 0, 80);
|
|
91
|
+
act(() => liveObservers[0].trigger());
|
|
92
|
+
expect(lastWidth).toBe(400);
|
|
93
|
+
|
|
94
|
+
setSize(el, 450, 80);
|
|
95
|
+
act(() => liveObservers[0].trigger());
|
|
96
|
+
expect(lastWidth).toBe(450);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('does not update while the element is detached', () => {
|
|
100
|
+
const { container } = render(<Probe initialWidth={400} />);
|
|
101
|
+
act(() => liveObservers[0].trigger());
|
|
102
|
+
expect(lastWidth).toBe(400);
|
|
103
|
+
|
|
104
|
+
const el = container.firstChild as HTMLElement;
|
|
105
|
+
el.remove();
|
|
106
|
+
setSize(el, 999, 80);
|
|
107
|
+
act(() => liveObservers[0]?.trigger());
|
|
108
|
+
expect(lastWidth).toBe(400);
|
|
109
|
+
});
|
|
110
|
+
});
|
package/src/index.ts
CHANGED
|
@@ -10,6 +10,12 @@ export {
|
|
|
10
10
|
useWeatherForecast,
|
|
11
11
|
} from './HAContext';
|
|
12
12
|
export { useCallbackStable } from './useCallbackStable';
|
|
13
|
+
export {
|
|
14
|
+
useResizeObserver,
|
|
15
|
+
type ElementSize,
|
|
16
|
+
type ResizeCallback,
|
|
17
|
+
} from './useResizeObserver';
|
|
18
|
+
export { useWidth } from './useWidth';
|
|
13
19
|
export { css, registerRawStyles, getAllStyles } from './styleRegistry';
|
|
14
20
|
export { loadFromCache, saveToCache } from './cacheUtils';
|
|
15
21
|
|
|
@@ -38,7 +38,6 @@ export function registerPreactCard<TConfig>(options: RegisterPreactCardOptions<T
|
|
|
38
38
|
private _hass?: HomeAssistant;
|
|
39
39
|
private _config?: TConfig;
|
|
40
40
|
private _shadowRoot: ShadowRoot;
|
|
41
|
-
private _hasRendered = false;
|
|
42
41
|
private _entityChangeListeners = new Map<string, Set<(entity: any) => void>>();
|
|
43
42
|
|
|
44
43
|
constructor() {
|
|
@@ -47,21 +46,11 @@ export function registerPreactCard<TConfig>(options: RegisterPreactCardOptions<T
|
|
|
47
46
|
}
|
|
48
47
|
|
|
49
48
|
connectedCallback() {
|
|
50
|
-
|
|
51
|
-
// Re-rendering on each connect causes Preact to lose its diff anchor and
|
|
52
|
-
// append a duplicate tree, so only render once per attachment cycle.
|
|
53
|
-
if (this._hass && this._config && !this._hasRendered) {
|
|
49
|
+
if (this._hass && this._config) {
|
|
54
50
|
this._render();
|
|
55
51
|
}
|
|
56
52
|
}
|
|
57
53
|
|
|
58
|
-
// Intentionally no disconnectedCallback: HA detaches + reattaches the card
|
|
59
|
-
// on edit-mode toggle, but the shadow root (with Preact's tree + effects)
|
|
60
|
-
// travels with the host. Clearing _entityChangeListeners here would orphan
|
|
61
|
-
// the still-mounted components — their useEffect cleanups never run, so
|
|
62
|
-
// they think they're subscribed while the host's map is empty, and entity
|
|
63
|
-
// updates stop reaching the UI.
|
|
64
|
-
|
|
65
54
|
set hass(hass: HomeAssistant) {
|
|
66
55
|
const prevStates = this._hass?.states;
|
|
67
56
|
this._hass = hass;
|
|
@@ -74,9 +63,6 @@ export function registerPreactCard<TConfig>(options: RegisterPreactCardOptions<T
|
|
|
74
63
|
}
|
|
75
64
|
}
|
|
76
65
|
|
|
77
|
-
// Render only when attached. HA may set hass/config before insertion;
|
|
78
|
-
// rendering into a detached shadow root then again on connect duplicates
|
|
79
|
-
// the tree. connectedCallback handles the detached-first-render case.
|
|
80
66
|
if (!prevStates && this._config && this.isConnected) {
|
|
81
67
|
this._render();
|
|
82
68
|
}
|
|
@@ -121,7 +107,6 @@ export function registerPreactCard<TConfig>(options: RegisterPreactCardOptions<T
|
|
|
121
107
|
</HAProvider>,
|
|
122
108
|
this._shadowRoot,
|
|
123
109
|
);
|
|
124
|
-
this._hasRendered = true;
|
|
125
110
|
}
|
|
126
111
|
|
|
127
112
|
static getConfigElement() {
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { RefObject } from 'preact';
|
|
2
|
+
import { useEffect, useRef } from 'preact/hooks';
|
|
3
|
+
|
|
4
|
+
export interface ElementSize {
|
|
5
|
+
width: number;
|
|
6
|
+
height: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type ResizeCallback = (size: ElementSize) => void;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Observe an element's size via ResizeObserver. The callback fires:
|
|
13
|
+
*
|
|
14
|
+
* 1. Once after mount, with the element's current size.
|
|
15
|
+
* 2. Whenever the element's size changes.
|
|
16
|
+
* 3. Whenever `deps` change, re-firing with the current size — so callers
|
|
17
|
+
* can re-run draws when their inputs change without re-creating the
|
|
18
|
+
* observer.
|
|
19
|
+
*
|
|
20
|
+
* The callback is suppressed only while the element is detached from the
|
|
21
|
+
* document. Zero width/height is delivered to the callback as-is — consumers
|
|
22
|
+
* that need to skip degenerate sizes (e.g. canvas painters where a 0-sized
|
|
23
|
+
* drawImage throws InvalidStateError) should add their own early return.
|
|
24
|
+
*
|
|
25
|
+
* Sizes are read from `offsetWidth` / `offsetHeight` (CSS pixels, includes
|
|
26
|
+
* padding + border). The callback is held in a ref, so passing a fresh
|
|
27
|
+
* function each render is safe — it never re-creates the observer.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* const containerRef = useRef<HTMLDivElement>(null);
|
|
31
|
+
* const canvasRef = useRef<HTMLCanvasElement>(null);
|
|
32
|
+
*
|
|
33
|
+
* useResizeObserver(
|
|
34
|
+
* containerRef,
|
|
35
|
+
* ({ width, height }) => {
|
|
36
|
+
* if (width === 0 || height === 0) return; // optional, consumer's call
|
|
37
|
+
* drawChart(canvasRef.current, forecast, width, height);
|
|
38
|
+
* },
|
|
39
|
+
* [forecast],
|
|
40
|
+
* );
|
|
41
|
+
*/
|
|
42
|
+
export function useResizeObserver<T extends HTMLElement>(
|
|
43
|
+
ref: RefObject<T>,
|
|
44
|
+
callback: ResizeCallback,
|
|
45
|
+
deps: unknown[] = [],
|
|
46
|
+
): void {
|
|
47
|
+
const callbackRef = useRef(callback);
|
|
48
|
+
callbackRef.current = callback;
|
|
49
|
+
|
|
50
|
+
// Set up the observer once per element. ResizeObserver fires once
|
|
51
|
+
// synchronously-ish after `.observe()` with the current size, which
|
|
52
|
+
// covers the initial draw.
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
const element = ref.current;
|
|
55
|
+
if (!element) return;
|
|
56
|
+
|
|
57
|
+
const fire = () => {
|
|
58
|
+
if (!element.isConnected) return;
|
|
59
|
+
callbackRef.current({
|
|
60
|
+
width: element.offsetWidth,
|
|
61
|
+
height: element.offsetHeight,
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const observer = new ResizeObserver(fire);
|
|
66
|
+
observer.observe(element);
|
|
67
|
+
return () => observer.disconnect();
|
|
68
|
+
// ref identity is stable across renders; observer setup runs once.
|
|
69
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
70
|
+
}, []);
|
|
71
|
+
|
|
72
|
+
// Re-fire on dependency change. Skip the first render — the observer's
|
|
73
|
+
// initial `.observe()` fire already delivers the mount-time size.
|
|
74
|
+
const isFirstRun = useRef(true);
|
|
75
|
+
useEffect(() => {
|
|
76
|
+
if (isFirstRun.current) {
|
|
77
|
+
isFirstRun.current = false;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const element = ref.current;
|
|
81
|
+
if (!element || !element.isConnected) return;
|
|
82
|
+
callbackRef.current({
|
|
83
|
+
width: element.offsetWidth,
|
|
84
|
+
height: element.offsetHeight,
|
|
85
|
+
});
|
|
86
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
87
|
+
}, deps);
|
|
88
|
+
}
|
package/src/useWidth.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { RefObject } from 'preact';
|
|
2
|
+
import { useState } from 'preact/hooks';
|
|
3
|
+
import { useResizeObserver } from './useResizeObserver';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Track the current width of a referenced element in CSS pixels.
|
|
7
|
+
*
|
|
8
|
+
* Returns `undefined` until the first non-zero measurement is observed, then
|
|
9
|
+
* a positive number that updates as the element resizes. Once a real width
|
|
10
|
+
* is captured the hook will never report `undefined` or `0` again, even
|
|
11
|
+
* during HA layout transitions (dashboard switch, edit-mode toggle) — the
|
|
12
|
+
* underlying ResizeObserver firings are silently dropped while the element
|
|
13
|
+
* is detached or transiently zero-width, so the component renders with the
|
|
14
|
+
* last good value instead of flashing through a degenerate state.
|
|
15
|
+
*
|
|
16
|
+
* Use this when you need a width value in JSX (responsive layout, prop to a
|
|
17
|
+
* sized child). If you only need the value imperatively inside a draw
|
|
18
|
+
* callback, prefer `useResizeObserver` directly — it doesn't allocate
|
|
19
|
+
* component state or cause re-renders.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* const ref = useRef<HTMLDivElement>(null);
|
|
23
|
+
* const width = useWidth(ref);
|
|
24
|
+
* return (
|
|
25
|
+
* <div ref={ref}>
|
|
26
|
+
* {width !== undefined && <Chart width={width} />}
|
|
27
|
+
* </div>
|
|
28
|
+
* );
|
|
29
|
+
*/
|
|
30
|
+
export function useWidth<T extends HTMLElement>(ref: RefObject<T>): number | undefined {
|
|
31
|
+
const [width, setWidth] = useState<number | undefined>(undefined);
|
|
32
|
+
useResizeObserver(ref, (size) => {
|
|
33
|
+
if (size.width === 0) return;
|
|
34
|
+
setWidth((prev) => (prev === size.width ? prev : size.width));
|
|
35
|
+
});
|
|
36
|
+
return width;
|
|
37
|
+
}
|