Skip to content

Commit

Permalink
Merge pull request #166 from posit-dev/message-on-ready
Browse files Browse the repository at this point in the history
Post message to parent when ready
  • Loading branch information
jcheng5 authored Jul 30, 2024
2 parents b741ce0 + 4115611 commit bcb472b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from "../examples";
import type { PyodideProxyHandle } from "../hooks/usePyodide";
import { initPyodide, initShiny, usePyodide } from "../hooks/usePyodide";
import { useRunOnceOnMount } from "../hooks/useRunOnceOnMount";
import type { WebRProxyHandle } from "../hooks/useWebR";
import { initRShiny, initWebR, useWebR } from "../hooks/useWebR";
import type { ProxyType } from "../pyodide-proxy";
Expand Down Expand Up @@ -329,6 +330,12 @@ export function App({
};
}, [currentFiles, setCurrentFiles, editorMethods]);

useRunOnceOnMount(() => {
if (window.parent === window) return;

window.parent.postMessage({ type: "shinyliveReady" }, "*");
});

const [utilityMethods, setUtilityMethods] = React.useState<UtilityMethods>({
formatCode: async (code: string) => {
return code;
Expand Down
20 changes: 20 additions & 0 deletions src/hooks/useRunOnceOnMount.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import React from "react";

/**
* Executes a callback function only once when the component mounts.
*
* @param {Function} callback - The callback function to be executed on mount.
*/
export function useRunOnceOnMount(callback: () => void) {
// This is needed to prevent the callback from being run twice -- in React
// strict mode, a useEffect will run twice.
const hasRun = React.useRef(false);

React.useEffect(() => {
if (!hasRun.current) {
callback();
hasRun.current = true;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}

0 comments on commit bcb472b

Please sign in to comment.