UNPKG

@hakit/core

Version:

A collection of React hooks and helpers for Home Assistant to easily communicate with the Home Assistant WebSocket API.

3 lines (2 loc) 2.18 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react"),R=require("./logbook.js");require("lodash");const v=require("../../../index-iGClY3ec.cjs");require("../useLocale/locales/index.js");require("home-assistant-js-websocket");require("../../utils/date.js");require("@iconify/react");const D=require("use-debounce"),L=24,g=(l,o)=>new Date(l.getTime()-o*1e3).getTime()/1e3;function O(l,o){const[b,k]=n.useState(void 0),d=v.useHass(e=>e.connection),[m,i]=n.useState([]),t=n.useRef([]),f=n.useRef(!1),a=n.useRef(void 0),s=n.useMemo(()=>{const e={};return o?.hoursToShow?e.recent=o.hoursToShow*60*60:o?.startTime&&o?.endTime?e.range=[o.startTime,o.endTime]:e.recent=L*60*60,e},[o]),h=n.useCallback(()=>{const e=new Date;if("range"in s)return{now:e,startTime:s.range[0],endTime:s.range[1],purgeBeforePythonTime:void 0};if("recent"in s){const u=g(e,s.recent);return{now:e,startTime:new Date(u*1e3),endTime:new Date(e.getTime()+86400*365*1e3),purgeBeforePythonTime:g(e,s.recent)}}throw new Error("Unexpected time specified")},[s]),w=n.useCallback(e=>t.current?e?t.current.filter(u=>u.when>e):t.current:[],[]),T=n.useCallback(e=>{const u=s&&"recent"in s?g(new Date,s.recent):void 0,r=[...e.events].reverse();if(!t.current.length){t.current=r,i(r);return}if(!r.length)return;const c=w(u);c.length?r[r.length-1].when>c[0].when?(t.current=r.concat(c),i(t.current)):c[c.length-1].when>r[0].when?(t.current=c.concat(r),i(t.current)):(t.current=c.concat(r).sort((E,q)=>q.when-E.when),i(t.current)):(t.current=r,i(r))},[s,w]);n.useEffect(()=>()=>{f.current=!1,t.current=[],i([])},[]);const S=n.useCallback((e,u)=>R.subscribeLogbook(d,c=>{f.current&&T(c)},u.startTime.toISOString(),u.endTime.toISOString(),[e]).catch(c=>{f.current=!1,c instanceof Error&&k(c.message)}),[d,T]),_=D.useDebouncedCallback(async(e,u)=>{if(a.current){const r=await a.current;r&&await r(),a.current=void 0}f.current=!0,a.current=await S(e,u)},100,{leading:!0,trailing:!0});if(n.useEffect(()=>{const e=h();return _(l,e),()=>{f.current=!1,a.current&&a.current()}},[h,_,S,l]),b)throw new Error(b);return n.useMemo(()=>m,[m])}exports.useLogs=O; //# sourceMappingURL=index.js.map