@hakit/core
Version:
A collection of React hooks and helpers for Home Assistant to easily communicate with the Home Assistant WebSocket API.
99 lines (98 loc) • 3.05 kB
JavaScript
import { useState as _, useRef as d, useMemo as D, useCallback as m, useEffect as k } from "react";
import { subscribeLogbook as R } from "./logbook.js";
import "lodash";
import "../../utils/light/index.js";
import "../useLocale/locales/index.js";
import "../../../index-BfdcdUoC.js";
import "../../HassConnect/HassContext.js";
import "@iconify/react";
import { useStore as x } from "../useStore/index.js";
import "home-assistant-js-websocket";
import { useDebouncedCallback as B } from "use-debounce";
const y = 24, g = (f, i) => new Date(f.getTime() - i * 1e3).getTime() / 1e3;
function z(f, i) {
const [b, L] = _(void 0), l = x((e) => e.connection), [w, s] = _([]), n = d([]), a = d(!1), u = d(void 0), c = D(() => {
const e = {};
return i?.hoursToShow ? e.recent = i.hoursToShow * 60 * 60 : i?.startTime && i?.endTime ? e.range = [i.startTime, i.endTime] : e.recent = y * 60 * 60, e;
}, [i]), 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 = g(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: g(e, c.recent)
};
}
throw new Error("Unexpected time specified");
}, [c]), T = m(
(e) => n.current ? e ? n.current.filter((o) => o.when > e) : n.current : [],
[]
), p = m(
(e) => {
const o = c && "recent" in c ? g(/* @__PURE__ */ new Date(), c.recent) : void 0, r = [...e.events].reverse();
if (!n.current.length) {
n.current = r, s(r);
return;
}
if (!r.length)
return;
const t = T(o);
t.length ? r[r.length - 1].when > // oldest new entry
t[0].when ? (n.current = r.concat(t), s(n.current)) : t[t.length - 1].when > // oldest old entry
r[0].when ? (n.current = t.concat(r), s(n.current)) : (n.current = t.concat(r).sort((O, P) => P.when - O.when), s(n.current)) : (n.current = r, s(r));
},
[c, T]
);
k(() => () => {
a.current = !1, n.current = [], s([]);
}, []);
const S = m(
(e, o) => R(
l,
(t) => {
a.current && p(t);
},
o.startTime.toISOString(),
o.endTime.toISOString(),
[e]
).catch((t) => {
a.current = !1, t instanceof Error && L(t.message);
}),
[l, p]
), E = B(
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 (k(() => {
const e = h();
return E(f, e), () => {
a.current = !1, u.current && u.current();
};
}, [h, E, S, f]), b)
throw new Error(b);
return D(() => w, [w]);
}
export {
z as useLogs
};
//# sourceMappingURL=index.js.map