Skip to content

Instantly share code, notes, and snippets.

@kinngh
Last active February 20, 2024 01:37
Show Gist options
  • Save kinngh/19d2bee151504f6d8e9a264ae9895368 to your computer and use it in GitHub Desktop.
Save kinngh/19d2bee151504f6d8e9a264ae9895368 to your computer and use it in GitHub Desktop.
AppBridge CDN Modal Wrapper
import { Box } from "@shopify/polaris";
import { useEffect, useRef } from "react";
/**
* @typedef {Object} Action
* @property {string} content
* @property {'critical'} [tone]
* @property {() => void} onAction
*/
/**
* @typedef {Object} ModalProps
* @property {string} title
* @property {boolean} open
* @property {() => void} [onClose]
* @property {React.ReactNode} [children]
* @property {Action} [primaryAction]
* @property {Action} [secondaryAction]
*/
/**
* @param {ModalProps} props The modal component properties.
* @returns {JSX.Element} The modal component.
*/
export default function Modal({
open,
title,
children,
onClose,
primaryAction,
secondaryAction,
}) {
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
const handleHide = () => onClose?.();
ref?.current?.addEventListener("hide", handleHide);
return () => {
ref?.current?.removeEventListener("hide", handleHide);
};
}
}, [onClose]);
useEffect(() => {
if (ref.current) {
if (open) {
ref.current.show();
} else {
ref.current.hide();
}
}
}, [open]);
return (
<ui-modal ref={ref} id="my-modal">
<Box padding="200">
{children}
</Box>
<ui-title-bar title={title ?? ""}>
{primaryAction && (
<button
variant="primary"
tone={primaryAction.tone}
onClick={primaryAction.onAction}
>
{primaryAction.content}
</button>
)}
{secondaryAction && (
<button onClick={secondaryAction.onAction}>
{secondaryAction.content}
</button>
)}
</ui-title-bar>
</ui-modal>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment