gopherjs - overlay/overlay.go
1 // Package overlay creates a simple 'window' overlay system for gopherjs
2 package overlay // import "vimagination.zapto.org/gopherjs/overlay"
3
4 import (
5 "honnef.co/go/js/dom"
6 "vimagination.zapto.org/gopherjs/style"
7 "vimagination.zapto.org/gopherjs/xdom"
8 )
9
10 const css = `
11 window, body {
12 width : 100%;
13 margin : 0;
14 overflow-x : hidden;
15 }
16
17 .mw-overlay {
18 position : fixed;
19 top : 0;
20 left : 0;
21 right : 0;
22 bottom : 0;
23 background-color : rgba(0, 0, 0, 0.25);
24 overflow-y : scroll;
25 overflow-x : hidden;
26 }
27
28 .mw-overlay > *:not(.closer) {
29 position : absolute;
30 top : 10px;
31 left : 10px;
32 right : 10px;
33 background-color : #fff;
34 }
35
36 .mw-overlay > .closer {
37 color : #fff;
38 font-family : serif;
39 right : 12px;
40 position : absolute;
41 text-shadow : #000 -1px -1px 0, #000 1px -1px 0, #000 1px 1px 0, #000 -1px 1px 0, #000 -1px 0 0, #000 1px 0 0;
42 top : 10px;
43 transition : color 0.25s;
44 transition-timing-function : ease;
45 user-select : none;
46 z-index : 1;
47 -moz-user-select : none;
48 -webkit-user-select : none;
49 }
50
51 .mw-overlay > .closer:hover {
52 color : #f00;
53 cursor : pointer;
54 }
55
56 * > .mw-overlay:not(:last-of-type) {
57 background-color : transparent;
58 }
59 `
60
61 func init() {
62 style.Add(css)
63 }
64
65 // Overlay is a dom.Element which
66 type Overlay struct {
67 dom.Element
68 onClose []func()
69 }
70
71 // OnClose adds an onClose handler for the overlay
72 func (o *Overlay) OnClose(f func()) {
73 o.onClose = append(o.onClose, f)
74 }
75
76 // Close closes the overlay, and runs any given onClose handle funcs
77 func (o *Overlay) Close() error {
78 p := o.ParentNode()
79 if p != nil {
80 p.RemoveChild(o)
81 for _, f := range o.onClose {
82 f()
83 }
84 }
85 return nil
86 }
87
88 // New wraps a dom.Element in an Overlay
89 func New(e dom.Node) *Overlay {
90 o := &Overlay{Element: xdom.Div()}
91 o.SetAttribute("class", "mw-overlay")
92 c := xdom.Div()
93 c.SetTextContent("X")
94 c.SetAttribute("class", "closer")
95 c.AddEventListener("click", false, func(dom.Event) {
96 o.Close()
97 })
98 o.AppendChild(c)
99 o.AppendChild(e)
100 return o
101 }