File size: 1,468 Bytes
2609fac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {RenderData, Streamlit} from "streamlit-component-lib"

const targetWindow: Window = window.parent || window
const targetDocument = targetWindow.document

let lastValue: string | null = null

interface AddCookieSpec {
    value: string
    expires_at: string
    path: string
}

interface DeleteCookieSpec {
    value: null
    path: string
}

type CookieSpec = AddCookieSpec | DeleteCookieSpec

function onRender(event: Event): void {
    const data = (event as CustomEvent<RenderData>).detail

    saveCookies(data.args["queue"])

    const newValue = targetDocument.cookie
    if (lastValue !== newValue && !data.args.saveOnly) {
        Streamlit.setComponentValue(newValue)
        lastValue = newValue
    }
}

Streamlit.events.addEventListener(Streamlit.RENDER_EVENT, onRender)
Streamlit.setComponentReady()
Streamlit.setFrameHeight(0)


function saveCookies(queue: { [k in string]: CookieSpec }) {
    Object.keys(queue).forEach((name) => {
        const spec = queue[name]
        if (spec.value === null)
            targetDocument.cookie = `${encodeURIComponent(name)}=; max-age=0; path=${encodeURIComponent(spec.path)}`
        else {
            const date = new Date(spec.expires_at)
            targetDocument.cookie = (
                `${encodeURIComponent(name)}=${encodeURIComponent(spec.value)};` +
                ` expires=${date.toUTCString()};` +
                ` path=${encodeURIComponent(spec.path)};`
            )
        }
    })
}