Skip to content

Commit

Permalink
modal state in url
Browse files Browse the repository at this point in the history
  • Loading branch information
FredericHeem committed Nov 24, 2023
1 parent c8eda76 commit 8293731
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default (context: Context, options = {}) => {

const MyModal = (props: any) => {
const modalEl = Modal(
{ id: "my-dialog", ...props },
{ id: `dialog-${props.color}-${props.variant}`, ...props },
header("Header"),
Content(),
footer(
Expand Down
4 changes: 3 additions & 1 deletion bau-ui/modal/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ declare module "@grucloud/bau-ui/modal" {
type DefaultDesignProps = import("../constants").DefaultDesignProps;
type ComponentOption = import("../bau-ui").ComponentOption;

export type ModalProps = {} & DefaultDesignProps;
export type ModalProps = {
id: string;
} & DefaultDesignProps;

type Component = import("../bau-ui").Component<ModalProps, HTMLDialogElement>;

Expand Down
27 changes: 25 additions & 2 deletions bau-ui/modal/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { toPropsAndChildren } from "@grucloud/bau/bau.js";
import { Colors } from "../constants.js";

export default function (context, options = {}) {
const { bau, css } = context;
const { bau, css, window } = context;
const { dialog, div } = bau.tags;

const colorsToCss = () =>
Expand Down Expand Up @@ -78,8 +78,16 @@ export default function (context, options = {}) {
...children
] = toPropsAndChildren(args);

return dialog(
const dialogEl = dialog(
{
...props,
bauMounted: () => {
const search = new URLSearchParams(window.location.search);
const modalId = search.get("modal");
if (modalId == (props.id ?? "modal")) {
dialogEl.showModal();
}
},
class: classNames(
"modal",
className,
Expand All @@ -92,5 +100,20 @@ export default function (context, options = {}) {
},
div(children)
);

const observer = new MutationObserver((events) => {
const search = new URLSearchParams(window.location.search);
if (events[0].attributeName == "open") {
if (dialogEl.open) {
search.set("modal", dialogEl.id ?? "modal");
} else {
search.delete("modal");
}
window.history.pushState("", "", `?${search.toString()}`);
}
});
observer.observe(dialogEl, { attributes: true });

return dialogEl;
};
}

0 comments on commit 8293731

Please sign in to comment.