Source

tools/hooks/useEmbedded.ts

//
// useEmbedded custom hook
//

import { useJcuConfig } from '../../services'

/**
Custom Hook for determining if the app is "embedded" or not.

Embedded means you're displaying minimal headers and footers,
in a manner suitable for this app to be included in an iframe
within a parent page.

By default, apps are never "embedded" (even if they are in an
iframe). To be considered embedded, your app needs to set the
`config.application.embedded` value to either `"always"`, in
which case the app will be "embedded") or `"auto"`, in which
case the app will be "embedded" when it is inside a frame or
iframe, and non-embedded if it is not.

The default value for `config.application.embedded` is
`"never"`.

```
import { useEmbedded } from '@jcu/spark'

export default function MyComponent() {

    const embed = useEmbedded()

    if (embed) {
        return <b>I'm in an iframe with hardly any headers!</b>
    } else {
        return <i>Normal headers for me.</i>
    }
}
```

Application headers and footers automatically adapt to
embedded-ness; you might like to use this hook to switch your
app's `shape` prop from the default `COLUMN` shape, which
constrains your content to a centered, reasonable width column,
to the `WIDECOLUMN` shape, which uses the full width of the
app's viewport.

```
import {JcuApp, Shape, useEmbedded} from '@jcu/spark'
// ...

function App() {
    const embed = useEmbedded()
    return (
        <JcuApp
            title="Useful app"
            shape={embed ? Shape.WIDECOLUMN : Shape.COLUMN}
        >
            <p>
                This para will horizontally fill an iframe, but
                be normal when it's in its own tab.
                This para will horizontally fill an iframe, but
                be normal when it's in its own tab.
                This para will horizontally fill an iframe, but
                be normal when it's in its own tab.
            </p>
        </JcuApp>
    )
```
@category Hooks
*/

export function useEmbedded(): boolean {

    const config = useJcuConfig()

    // read application.embedded from config (always, never, auto)
    const cfgEmbedded = config.application?.embedded || 'never'

    // we're embedded if config says "always", or if config
    // says "auto" and we're in an iframe
    return (
        cfgEmbedded === 'always'  ||
        (cfgEmbedded === 'auto' && window.parent !== window)
    )
}