one
Version:
One is a React framework for web, iOS, and Android apps.
85 lines (82 loc) • 2.41 kB
JavaScript
import { createContext, useContext, useMemo } from "react";
const ReservedRegionsContext = createContext(null);
function useSnapshot(hook) {
const snapshot = useContext(ReservedRegionsContext);
if (!snapshot) {
throw new Error(`One.${hook} must be used inside One.UI.ReservedRegions.Provider`);
}
return snapshot;
}
function useRegions(options) {
const { regions } = useSnapshot("useReservedRegions");
const kind = options?.kind;
const includeInactive = options?.includeInactive === true;
return useMemo(() => regions.filter((region) => (!kind || region.kind === kind) && (includeInactive || region.isActive)), [
regions,
kind,
includeInactive
]);
}
function useReady() {
return useSnapshot("useReservedRegionsReady").ready;
}
function useSegments() {
const { bounds, ready, regions } = useSnapshot("useWindowSegments");
return useMemo(() => {
if (!ready || !bounds || bounds.width <= 0 || bounds.height <= 0) return [];
return segmentsFor(bounds, regions);
}, [
bounds,
ready,
regions
]);
}
function useSpanning() {
return useSegments().length > 1;
}
function segmentsFor(bounds, regions) {
const edgeTolerance = .5;
let segments = [{
x: 0,
y: 0,
...bounds
}];
for (const region of regions) {
if (region.kind !== "division" || !region.isActive) continue;
const { x, y, width, height } = region.frame;
segments = segments.flatMap((segment) => {
const right = segment.x + segment.width;
const bottom = segment.y + segment.height;
if (y <= segment.y + edgeTolerance && y + height >= bottom - edgeTolerance && x > segment.x && x + width < right) {
return [{
x: segment.x,
y: segment.y,
width: x - segment.x,
height: segment.height
}, {
x: x + width,
y: segment.y,
width: right - x - width,
height: segment.height
}];
}
if (x <= segment.x + edgeTolerance && x + width >= right - edgeTolerance && y > segment.y && y + height < bottom) {
return [{
x: segment.x,
y: segment.y,
width: segment.width,
height: y - segment.y
}, {
x: segment.x,
y: y + height,
width: segment.width,
height: bottom - y - height
}];
}
return [segment];
});
}
return segments.sort((a, b) => a.y - b.y || a.x - b.x);
}
export { ReservedRegionsContext, segmentsFor, useReady, useRegions, useSegments, useSpanning };
//# sourceMappingURL=reservedRegionsContext.mjs.map