-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbrowser.ts
73 lines (58 loc) · 2.08 KB
/
browser.ts
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { StreamElement, TurboStreamActions } from "@hotwired/turbo"
import { Action } from "@hotwired/turbo/dist/types/core/types"
import { VisitOptions } from "@hotwired/turbo/dist/types/core/drive/visit"
type Visitable = {
visit(location: URL | string, options?: Partial<VisitOptions>): void
}
declare global {
interface Window {
Turbo: Visitable
Turbolinks: Visitable
}
}
export function redirect_to(this: StreamElement) {
const url = this.getAttribute("url") || "/"
const action = (this.getAttribute("action") || "advance") as Action
const turbo = this.getAttribute("turbo") === "true"
if (turbo) {
if (window.Turbo) window.Turbo.visit(url, { action })
if (window.Turbolinks) window.Turbolinks.visit(url, { action })
if (!window.Turbo && !window.Turbolinks) window.location.href = url
} else {
window.location.href = url
}
}
export function reload(this: StreamElement) {
window.location.reload()
}
export function scroll_into_view(this: StreamElement) {
this.targetElements.forEach((element: Element) => element.scrollIntoView())
}
export function set_cookie(this: StreamElement) {
const cookie = this.getAttribute("cookie") || ""
document.cookie = cookie
}
export function set_cookie_item(this: StreamElement) {
console.log("set_cookie_item", this)
}
export function set_focus(this: StreamElement) {
this.targetElements.forEach((element: HTMLElement) => element.focus())
}
export function set_title(this: StreamElement) {
const title = this.getAttribute("title") || ""
let titleElement = document.head.querySelector("title")
if (!titleElement) {
titleElement = document.createElement("title")
document.head.appendChild(titleElement)
}
titleElement.textContent = title
}
export function registerBrowserActions(streamActions: TurboStreamActions) {
streamActions.redirect_to = redirect_to
streamActions.reload = reload
streamActions.scroll_into_view = scroll_into_view
streamActions.set_cookie = set_cookie
streamActions.set_cookie_item = set_cookie_item
streamActions.set_focus = set_focus
streamActions.set_title = set_title
}