@hakit/core
Version:
A collection of React hooks and helpers for Home Assistant to easily communicate with the Home Assistant WebSocket API.
97 lines (96 loc) • 2.96 kB
JavaScript
import { useState as _, useRef as g, useMemo as v, useCallback as m, useEffect as D } from "react";
import { subscribeLogbook as P } from "./logbook.js";
import "lodash";
import { X as R } from "../../../index-BDZyTvOW.js";
import "../useLocale/locales/index.js";
import "home-assistant-js-websocket";
import "../../utils/date.js";
import "@iconify/react";
import { useDebouncedCallback as x } from "use-debounce";
const B = 24, b = (f, s) => new Date(f.getTime() - s * 1e3).getTime() / 1e3;
function X(f, s) {
const [d, k] = _(void 0), l = R((e) => e.connection), [w, i] = _([]), t = g([]), a = g(!1), u = g(void 0), c = v(() => {
const e = {};
return s?.hoursToShow ? e.recent = s.hoursToShow * 60 * 60 : s?.startTime && s?.endTime ? e.range = [s.startTime, s.endTime] : e.recent = B * 60 * 60, e;
}, [s]), h = m(() => {
const e = /* @__PURE__ */ new Date();
if ("range" in c)
return {
now: e,
startTime: c.range[0],
endTime: c.range[1],
purgeBeforePythonTime: void 0
};
if ("recent" in c) {
const o = b(e, c.recent);
return {
now: e,
startTime: new Date(o * 1e3),
// end streaming one year from now
endTime: new Date(e.getTime() + 86400 * 365 * 1e3),
purgeBeforePythonTime: b(e, c.recent)
};
}
throw new Error("Unexpected time specified");
}, [c]), T = m(
(e) => t.current ? e ? t.current.filter((o) => o.when > e) : t.current : [],
[]
), p = m(
(e) => {
const o = c && "recent" in c ? b(/* @__PURE__ */ new Date(), c.recent) : void 0, r = [...e.events].reverse();
if (!t.current.length) {
t.current = r, i(r);
return;
}
if (!r.length)
return;
const n = T(o);
n.length ? r[r.length - 1].when > // oldest new entry
n[0].when ? (t.current = r.concat(n), i(t.current)) : n[n.length - 1].when > // oldest old entry
r[0].when ? (t.current = n.concat(r), i(t.current)) : (t.current = n.concat(r).sort((L, O) => O.when - L.when), i(t.current)) : (t.current = r, i(r));
},
[c, T]
);
D(() => () => {
a.current = !1, t.current = [], i([]);
}, []);
const S = m(
(e, o) => P(
l,
(n) => {
a.current && p(n);
},
o.startTime.toISOString(),
o.endTime.toISOString(),
[e]
).catch((n) => {
a.current = !1, n instanceof Error && k(n.message);
}),
[l, p]
), E = x(
async (e, o) => {
if (u.current) {
const r = await u.current;
r && await r(), u.current = void 0;
}
a.current = !0, u.current = await S(e, o);
},
100,
{
leading: !0,
trailing: !0
}
);
if (D(() => {
const e = h();
return E(f, e), () => {
a.current = !1, u.current && u.current();
};
}, [h, E, S, f]), d)
throw new Error(d);
return v(() => w, [w]);
}
export {
X as useLogs
};
//# sourceMappingURL=index.js.map