Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
SelectTrigger
} from "@/components/ui/select";
import { useBodyStyle } from "@/hooks/useBodyStyle";
import { forwardRef, useEffect, useState } from "react";
import { useOutsideEvent } from "@/hooks/useOutsideEvent";
import React, { forwardRef, useEffect, useRef, useState } from "react";
import { Streamlit } from "streamlit-component-lib";

interface StSelectOptionsProps {
Expand All @@ -16,6 +17,17 @@ interface StSelectOptionsProps {
export const StSelectOptions = forwardRef<HTMLDivElement, StSelectOptionsProps>((props, ref) => {
const { options, value } = props;
const [selectedValue, setSelectedValue] = useState<string>(value);
const contentRef = useRef<HTMLDivElement>(null);

// expose internal ref
useEffect(() => {
if (!ref) return;
if (typeof ref === "function") {
ref(contentRef.current);
} else {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = contentRef.current;
}
}, [ref]);
// useEffect(() => {
// if (ref && typeof ref !== 'function') {
// Streamlit.setFrameHeight(ref.current.offsetHeight + 5);
Expand All @@ -24,6 +36,24 @@ export const StSelectOptions = forwardRef<HTMLDivElement, StSelectOptionsProps>(

useBodyStyle("body { background-color: transparent !important; }")

useOutsideEvent(
"mousedown",
e => {
const el = contentRef.current;
if (!el) return;
if (el.offsetParent === null) {
return;
}
if (!el.contains(e.target as Node)) {
Streamlit.setComponentValue({
value: selectedValue,
open: false,
});
}
},
true
);

useEffect(() => {
setSelectedValue(value);
}, [value]);
Expand All @@ -38,7 +68,7 @@ export const StSelectOptions = forwardRef<HTMLDivElement, StSelectOptionsProps>(
<SelectTrigger className="hidden">
{/* <SelectValue placeholder="Select a fruit" /> */}
</SelectTrigger>
<SelectContent ref={ref}
<SelectContent ref={contentRef}
>
<SelectGroup>
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useEffect } from "react";

export function useOutsideEvent(
eventName: keyof DocumentEventMap,
handler: (event: Event) => void,
enabled = true
) {
useEffect(() => {
if (!enabled) return;
const parentDoc = (() => {
try {
return window.parent.document;
} catch (e) {
return null;
}
})();

document.addEventListener(eventName, handler);
if (parentDoc && parentDoc !== document) {
parentDoc.addEventListener(eventName, handler);
}

return () => {
document.removeEventListener(eventName, handler);
if (parentDoc && parentDoc !== document) {
parentDoc.removeEventListener(eventName, handler);
}
};
}, [eventName, handler, enabled]);
}