react-konva-utils
Version:
Useful components and hooks for react-konva
56 lines (55 loc) • 2.27 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Portal = void 0;
const react_1 = __importDefault(require("react"));
const react_konva_1 = require("react-konva");
// make a portal implementation
const Portal = ({ selector, enabled, children }) => {
// "selector" is a string to find another container to insert all internals
// if can be like ".top-layer" or "#overlay-group"
const outer = react_1.default.useRef(null);
const inner = react_1.default.useRef(null);
const safeRef = react_1.default.useRef(null);
const shouldMove = enabled !== null && enabled !== void 0 ? enabled : true;
react_1.default.useLayoutEffect(() => {
if (!outer.current || !inner.current) {
return;
}
safeRef.current = inner.current;
const stage = outer.current.getStage();
const newContainer = stage.findOne(selector);
if (shouldMove && newContainer) {
inner.current.moveTo(newContainer);
}
else {
inner.current.moveTo(outer.current);
}
// manually redraw layers
const outerLayer = outer.current.getLayer();
if (!outerLayer)
return;
outerLayer.batchDraw();
if (newContainer) {
const newContainerLayer = newContainer.getLayer();
if (!newContainerLayer)
return;
newContainerLayer.batchDraw();
}
}, [selector, shouldMove]);
react_1.default.useEffect(() => {
return () => {
var _a;
// manually destroy
(_a = safeRef.current) === null || _a === void 0 ? void 0 : _a.destroy();
};
}, []);
// for smooth movement we will have to use two group
// outer - is main container, will be placed on old position
// inner - that we will move into another container
return (react_1.default.createElement(react_konva_1.Group, { name: "_outer_portal", ref: outer },
react_1.default.createElement(react_konva_1.Group, { name: "_inner_portal", ref: inner }, children)));
};
exports.Portal = Portal;