dom.go 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100
  1. // Package dom provides GopherJS bindings for the JavaScript DOM APIs.
  2. //
  3. // This package is an in progress effort of providing idiomatic Go
  4. // bindings for the DOM, wrapping the JavaScript DOM APIs. The API is
  5. // neither complete nor frozen yet, but a great amount of the DOM is
  6. // already useable.
  7. //
  8. // While the package tries to be idiomatic Go, it also tries to stick
  9. // closely to the JavaScript APIs, so that one does not need to learn
  10. // a new set of APIs if one is already familiar with it.
  11. //
  12. // One decision that hasn't been made yet is what parts exactly should
  13. // be part of this package. It is, for example, possible that the
  14. // canvas APIs will live in a separate package. On the other hand,
  15. // types such as StorageEvent (the event that gets fired when the
  16. // HTML5 storage area changes) will be part of this package, simply
  17. // due to how the DOM is structured – even if the actual storage APIs
  18. // might live in a separate package. This might require special care
  19. // to avoid circular dependencies.
  20. //
  21. // The documentation for some of the identifiers is based on the
  22. // MDN Web Docs by Mozilla Contributors (https://developer.mozilla.org/en-US/docs/Web/API),
  23. // licensed under CC-BY-SA 2.5 (https://creativecommons.org/licenses/by-sa/2.5/).
  24. //
  25. //
  26. // Getting started
  27. //
  28. // The usual entry point of using the dom package is by using the
  29. // GetWindow() function which will return a Window, from which you can
  30. // get things such as the current Document.
  31. //
  32. //
  33. // Interfaces
  34. //
  35. // The DOM has a big amount of different element and event types, but
  36. // they all follow three interfaces. All functions that work on or
  37. // return generic elements/events will return one of the three
  38. // interfaces Element, HTMLElement or Event. In these interface values
  39. // there will be concrete implementations, such as
  40. // HTMLParagraphElement or FocusEvent. It's also not unusual that
  41. // values of type Element also implement HTMLElement. In all cases,
  42. // type assertions can be used.
  43. //
  44. // Example:
  45. // el := dom.GetWindow().Document().QuerySelector(".some-element")
  46. // htmlEl := el.(dom.HTMLElement)
  47. // pEl := el.(*dom.HTMLParagraphElement)
  48. //
  49. //
  50. // Live collections
  51. //
  52. // Several functions in the JavaScript DOM return "live"
  53. // collections of elements, that is collections that will be
  54. // automatically updated when elements get removed or added to the
  55. // DOM. Our bindings, however, return static slices of elements that,
  56. // once created, will not automatically reflect updates to the DOM.
  57. // This is primarily done so that slices can actually be used, as
  58. // opposed to a form of iterator, but also because we think that
  59. // magically changing data isn't Go's nature and that snapshots of
  60. // state are a lot easier to reason about.
  61. //
  62. // This does not, however, mean that all objects are snapshots.
  63. // Elements, events and generally objects that aren't slices or maps
  64. // are simple wrappers around JavaScript objects, and as such
  65. // attributes as well as method calls will always return the most
  66. // current data. To reflect this behaviour, these bindings use
  67. // pointers to make the semantics clear. Consider the following
  68. // example:
  69. //
  70. // d := dom.GetWindow().Document()
  71. // e1 := d.GetElementByID("my-element")
  72. // e2 := d.GetElementByID("my-element")
  73. //
  74. // e1.Class().SetString("some-class")
  75. // println(e1.Class().String() == e2.Class().String())
  76. //
  77. // The above example will print `true`.
  78. //
  79. //
  80. // DOMTokenList
  81. //
  82. // Some objects in the JS API have two versions of attributes, one
  83. // that returns a string and one that returns a DOMTokenList to ease
  84. // manipulation of string-delimited lists. Some other objects only
  85. // provide DOMTokenList, sometimes DOMSettableTokenList. To simplify
  86. // these bindings, only the DOMTokenList variant will be made
  87. // available, by the type TokenList. In cases where the string
  88. // attribute was the only way to completely replace the value, our
  89. // TokenList will provide Set([]string) and SetString(string) methods,
  90. // which will be able to accomplish the same. Additionally, our
  91. // TokenList will provide methods to convert it to strings and slices.
  92. //
  93. //
  94. // Backwards compatibility
  95. //
  96. // This package has a relatively stable API. However, there will be
  97. // backwards incompatible changes from time to time. This is because
  98. // the package isn't complete yet, as well as because the DOM is a
  99. // moving target, and APIs do change sometimes.
  100. //
  101. // While an attempt is made to reduce changing function signatures to
  102. // a minimum, it can't always be guaranteed. Sometimes mistakes in the
  103. // bindings are found that require changing arguments or return
  104. // values.
  105. //
  106. // Interfaces defined in this package may also change on a
  107. // semi-regular basis, as new methods are added to them. This happens
  108. // because the bindings aren't complete and can never really be, as
  109. // new features are added to the DOM.
  110. //
  111. // If you depend on none of the APIs changing unexpectedly, you're
  112. // advised to vendor this package.
  113. package dom // import "honnef.co/go/js/dom"
  114. import (
  115. "image"
  116. "image/color"
  117. "strings"
  118. "time"
  119. "github.com/gopherjs/gopherjs/js"
  120. )
  121. // toString returns the string representation of o. If o is nil or
  122. // undefined, the empty string will be returned instead.
  123. func toString(o *js.Object) string {
  124. if o == nil || o == js.Undefined {
  125. return ""
  126. }
  127. return o.String()
  128. }
  129. func callRecover(o *js.Object, fn string, args ...interface{}) (err error) {
  130. defer func() {
  131. e := recover()
  132. if e == nil {
  133. return
  134. }
  135. if panicErr, ok := e.(error); ok && panicErr != nil {
  136. err = panicErr
  137. } else {
  138. panic(e)
  139. }
  140. }()
  141. o.Call(fn, args...)
  142. return nil
  143. }
  144. func elementConstructor(o *js.Object) *js.Object {
  145. if n := o.Get("node"); n != js.Undefined {
  146. // Support elements wrapped in Polymer's DOM APIs.
  147. return n.Get("constructor")
  148. }
  149. return o.Get("constructor")
  150. }
  151. func arrayToObjects(o *js.Object) []*js.Object {
  152. var out []*js.Object
  153. for i := 0; i < o.Length(); i++ {
  154. out = append(out, o.Index(i))
  155. }
  156. return out
  157. }
  158. func nodeListToObjects(o *js.Object) []*js.Object {
  159. if o.Get("constructor") == js.Global.Get("Array") {
  160. // Support Polymer's DOM APIs, which uses Arrays instead of
  161. // NodeLists
  162. return arrayToObjects(o)
  163. }
  164. var out []*js.Object
  165. length := o.Get("length").Int()
  166. for i := 0; i < length; i++ {
  167. out = append(out, o.Call("item", i))
  168. }
  169. return out
  170. }
  171. func nodeListToNodes(o *js.Object) []Node {
  172. var out []Node
  173. for _, obj := range nodeListToObjects(o) {
  174. out = append(out, wrapNode(obj))
  175. }
  176. return out
  177. }
  178. func nodeListToElements(o *js.Object) []Element {
  179. var out []Element
  180. for _, obj := range nodeListToObjects(o) {
  181. out = append(out, wrapElement(obj))
  182. }
  183. return out
  184. }
  185. func nodeListToHTMLElements(o *js.Object) []HTMLElement {
  186. var out []HTMLElement
  187. for _, obj := range nodeListToObjects(o) {
  188. out = append(out, wrapHTMLElement(obj))
  189. }
  190. return out
  191. }
  192. func WrapDocument(o *js.Object) Document {
  193. return wrapDocument(o)
  194. }
  195. func WrapDocumentFragment(o *js.Object) DocumentFragment {
  196. return wrapDocumentFragment(o)
  197. }
  198. func WrapNode(o *js.Object) Node {
  199. return wrapNode(o)
  200. }
  201. func WrapElement(o *js.Object) Element {
  202. return wrapElement(o)
  203. }
  204. func WrapHTMLElement(o *js.Object) HTMLElement {
  205. return wrapHTMLElement(o)
  206. }
  207. func wrapDocument(o *js.Object) Document {
  208. switch elementConstructor(o) {
  209. case js.Global.Get("HTMLDocument"):
  210. return &htmlDocument{&document{&BasicNode{o}}}
  211. default:
  212. return &document{&BasicNode{o}}
  213. }
  214. }
  215. func wrapDocumentFragment(o *js.Object) DocumentFragment {
  216. switch elementConstructor(o) {
  217. // TODO: do we have any other stuff we want to check
  218. default:
  219. return &documentFragment{&BasicNode{o}}
  220. }
  221. }
  222. func wrapNode(o *js.Object) Node {
  223. if o == nil || o == js.Undefined {
  224. return nil
  225. }
  226. switch elementConstructor(o) {
  227. // TODO all the non-element cases
  228. case js.Global.Get("Text"):
  229. return &Text{&BasicNode{o}}
  230. default:
  231. return wrapElement(o)
  232. }
  233. }
  234. func wrapElement(o *js.Object) Element {
  235. if o == nil || o == js.Undefined {
  236. return nil
  237. }
  238. switch elementConstructor(o) {
  239. // TODO all the non-HTML cases
  240. default:
  241. return wrapHTMLElement(o)
  242. }
  243. }
  244. func wrapHTMLElement(o *js.Object) HTMLElement {
  245. if o == nil || o == js.Undefined {
  246. return nil
  247. }
  248. el := &BasicHTMLElement{&BasicElement{&BasicNode{o}}}
  249. c := elementConstructor(o)
  250. switch c {
  251. case js.Global.Get("HTMLAnchorElement"):
  252. return &HTMLAnchorElement{BasicHTMLElement: el, URLUtils: &URLUtils{Object: o}}
  253. case js.Global.Get("HTMLAppletElement"):
  254. return &HTMLAppletElement{BasicHTMLElement: el}
  255. case js.Global.Get("HTMLAreaElement"):
  256. return &HTMLAreaElement{BasicHTMLElement: el, URLUtils: &URLUtils{Object: o}}
  257. case js.Global.Get("HTMLAudioElement"):
  258. return &HTMLAudioElement{HTMLMediaElement: &HTMLMediaElement{BasicHTMLElement: el}}
  259. case js.Global.Get("HTMLBaseElement"):
  260. return &HTMLBaseElement{BasicHTMLElement: el}
  261. case js.Global.Get("HTMLBodyElement"):
  262. return &HTMLBodyElement{BasicHTMLElement: el}
  263. case js.Global.Get("HTMLBRElement"):
  264. return &HTMLBRElement{BasicHTMLElement: el}
  265. case js.Global.Get("HTMLButtonElement"):
  266. return &HTMLButtonElement{BasicHTMLElement: el}
  267. case js.Global.Get("HTMLCanvasElement"):
  268. return &HTMLCanvasElement{BasicHTMLElement: el}
  269. case js.Global.Get("HTMLDataElement"):
  270. return &HTMLDataElement{BasicHTMLElement: el}
  271. case js.Global.Get("HTMLDataListElement"):
  272. return &HTMLDataListElement{BasicHTMLElement: el}
  273. case js.Global.Get("HTMLDirectoryElement"):
  274. return &HTMLDirectoryElement{BasicHTMLElement: el}
  275. case js.Global.Get("HTMLDivElement"):
  276. return &HTMLDivElement{BasicHTMLElement: el}
  277. case js.Global.Get("HTMLDListElement"):
  278. return &HTMLDListElement{BasicHTMLElement: el}
  279. case js.Global.Get("HTMLEmbedElement"):
  280. return &HTMLEmbedElement{BasicHTMLElement: el}
  281. case js.Global.Get("HTMLFieldSetElement"):
  282. return &HTMLFieldSetElement{BasicHTMLElement: el}
  283. case js.Global.Get("HTMLFontElement"):
  284. return &HTMLFontElement{BasicHTMLElement: el}
  285. case js.Global.Get("HTMLFormElement"):
  286. return &HTMLFormElement{BasicHTMLElement: el}
  287. case js.Global.Get("HTMLFrameElement"):
  288. return &HTMLFrameElement{BasicHTMLElement: el}
  289. case js.Global.Get("HTMLFrameSetElement"):
  290. return &HTMLFrameSetElement{BasicHTMLElement: el}
  291. case js.Global.Get("HTMLHeadElement"):
  292. return &HTMLHeadElement{BasicHTMLElement: el}
  293. case js.Global.Get("HTMLHeadingElement"):
  294. return &HTMLHeadingElement{BasicHTMLElement: el}
  295. case js.Global.Get("HTMLHtmlElement"):
  296. return &HTMLHtmlElement{BasicHTMLElement: el}
  297. case js.Global.Get("HTMLHRElement"):
  298. return &HTMLHRElement{BasicHTMLElement: el}
  299. case js.Global.Get("HTMLIFrameElement"):
  300. return &HTMLIFrameElement{BasicHTMLElement: el}
  301. case js.Global.Get("HTMLImageElement"):
  302. return &HTMLImageElement{BasicHTMLElement: el}
  303. case js.Global.Get("HTMLInputElement"):
  304. return &HTMLInputElement{BasicHTMLElement: el}
  305. case js.Global.Get("HTMLKeygenElement"):
  306. return &HTMLKeygenElement{BasicHTMLElement: el}
  307. case js.Global.Get("HTMLLabelElement"):
  308. return &HTMLLabelElement{BasicHTMLElement: el}
  309. case js.Global.Get("HTMLLegendElement"):
  310. return &HTMLLegendElement{BasicHTMLElement: el}
  311. case js.Global.Get("HTMLLIElement"):
  312. return &HTMLLIElement{BasicHTMLElement: el}
  313. case js.Global.Get("HTMLLinkElement"):
  314. return &HTMLLinkElement{BasicHTMLElement: el}
  315. case js.Global.Get("HTMLMapElement"):
  316. return &HTMLMapElement{BasicHTMLElement: el}
  317. case js.Global.Get("HTMLMediaElement"):
  318. return &HTMLMediaElement{BasicHTMLElement: el}
  319. case js.Global.Get("HTMLMenuElement"):
  320. return &HTMLMenuElement{BasicHTMLElement: el}
  321. case js.Global.Get("HTMLMetaElement"):
  322. return &HTMLMetaElement{BasicHTMLElement: el}
  323. case js.Global.Get("HTMLMeterElement"):
  324. return &HTMLMeterElement{BasicHTMLElement: el}
  325. case js.Global.Get("HTMLModElement"):
  326. return &HTMLModElement{BasicHTMLElement: el}
  327. case js.Global.Get("HTMLObjectElement"):
  328. return &HTMLObjectElement{BasicHTMLElement: el}
  329. case js.Global.Get("HTMLOListElement"):
  330. return &HTMLOListElement{BasicHTMLElement: el}
  331. case js.Global.Get("HTMLOptGroupElement"):
  332. return &HTMLOptGroupElement{BasicHTMLElement: el}
  333. case js.Global.Get("HTMLOptionElement"):
  334. return &HTMLOptionElement{BasicHTMLElement: el}
  335. case js.Global.Get("HTMLOutputElement"):
  336. return &HTMLOutputElement{BasicHTMLElement: el}
  337. case js.Global.Get("HTMLParagraphElement"):
  338. return &HTMLParagraphElement{BasicHTMLElement: el}
  339. case js.Global.Get("HTMLParamElement"):
  340. return &HTMLParamElement{BasicHTMLElement: el}
  341. case js.Global.Get("HTMLPreElement"):
  342. return &HTMLPreElement{BasicHTMLElement: el}
  343. case js.Global.Get("HTMLProgressElement"):
  344. return &HTMLProgressElement{BasicHTMLElement: el}
  345. case js.Global.Get("HTMLQuoteElement"):
  346. return &HTMLQuoteElement{BasicHTMLElement: el}
  347. case js.Global.Get("HTMLScriptElement"):
  348. return &HTMLScriptElement{BasicHTMLElement: el}
  349. case js.Global.Get("HTMLSelectElement"):
  350. return &HTMLSelectElement{BasicHTMLElement: el}
  351. case js.Global.Get("HTMLSourceElement"):
  352. return &HTMLSourceElement{BasicHTMLElement: el}
  353. case js.Global.Get("HTMLSpanElement"):
  354. return &HTMLSpanElement{BasicHTMLElement: el}
  355. case js.Global.Get("HTMLStyleElement"):
  356. return &HTMLStyleElement{BasicHTMLElement: el}
  357. case js.Global.Get("HTMLTableElement"):
  358. return &HTMLTableElement{BasicHTMLElement: el}
  359. case js.Global.Get("HTMLTableCaptionElement"):
  360. return &HTMLTableCaptionElement{BasicHTMLElement: el}
  361. case js.Global.Get("HTMLTableCellElement"):
  362. return &HTMLTableCellElement{BasicHTMLElement: el}
  363. case js.Global.Get("HTMLTableDataCellElement"):
  364. return &HTMLTableDataCellElement{BasicHTMLElement: el}
  365. case js.Global.Get("HTMLTableHeaderCellElement"):
  366. return &HTMLTableHeaderCellElement{BasicHTMLElement: el}
  367. case js.Global.Get("HTMLTableColElement"):
  368. return &HTMLTableColElement{BasicHTMLElement: el}
  369. case js.Global.Get("HTMLTableRowElement"):
  370. return &HTMLTableRowElement{BasicHTMLElement: el}
  371. case js.Global.Get("HTMLTableSectionElement"):
  372. return &HTMLTableSectionElement{BasicHTMLElement: el}
  373. case js.Global.Get("HTMLTemplateElement"):
  374. return &HTMLTemplateElement{BasicHTMLElement: el}
  375. case js.Global.Get("HTMLTextAreaElement"):
  376. return &HTMLTextAreaElement{BasicHTMLElement: el}
  377. case js.Global.Get("HTMLTimeElement"):
  378. return &HTMLTimeElement{BasicHTMLElement: el}
  379. case js.Global.Get("HTMLTitleElement"):
  380. return &HTMLTitleElement{BasicHTMLElement: el}
  381. case js.Global.Get("HTMLTrackElement"):
  382. return &HTMLTrackElement{BasicHTMLElement: el}
  383. case js.Global.Get("HTMLUListElement"):
  384. return &HTMLUListElement{BasicHTMLElement: el}
  385. case js.Global.Get("HTMLUnknownElement"):
  386. return &HTMLUnknownElement{BasicHTMLElement: el}
  387. case js.Global.Get("HTMLVideoElement"):
  388. return &HTMLVideoElement{HTMLMediaElement: &HTMLMediaElement{BasicHTMLElement: el}}
  389. case js.Global.Get("HTMLElement"):
  390. return el
  391. default:
  392. return el
  393. }
  394. }
  395. func getForm(o *js.Object) *HTMLFormElement {
  396. form := wrapHTMLElement(o.Get("form"))
  397. if form == nil {
  398. return nil
  399. }
  400. return form.(*HTMLFormElement)
  401. }
  402. func getLabels(o *js.Object) []*HTMLLabelElement {
  403. labels := nodeListToElements(o.Get("labels"))
  404. out := make([]*HTMLLabelElement, len(labels))
  405. for i, label := range labels {
  406. out[i] = label.(*HTMLLabelElement)
  407. }
  408. return out
  409. }
  410. func getOptions(o *js.Object, attr string) []*HTMLOptionElement {
  411. options := nodeListToElements(o.Get(attr))
  412. out := make([]*HTMLOptionElement, len(options))
  413. for i, option := range options {
  414. out[i] = option.(*HTMLOptionElement)
  415. }
  416. return out
  417. }
  418. func GetWindow() Window {
  419. return &window{js.Global}
  420. }
  421. type TokenList struct {
  422. dtl *js.Object // the underlying DOMTokenList
  423. o *js.Object // the object to which the DOMTokenList belongs
  424. sa string // the name of the corresponding string attribute, empty if there isn't one
  425. Length int `js:"length"`
  426. }
  427. func (tl *TokenList) Item(idx int) string {
  428. o := tl.dtl.Call("item", idx)
  429. return toString(o)
  430. }
  431. func (tl *TokenList) Contains(token string) bool {
  432. return tl.dtl.Call("contains", token).Bool()
  433. }
  434. func (tl *TokenList) Add(token string) {
  435. tl.dtl.Call("add", token)
  436. }
  437. func (tl *TokenList) Remove(token string) {
  438. tl.dtl.Call("remove", token)
  439. }
  440. func (tl *TokenList) Toggle(token string) {
  441. tl.dtl.Call("toggle", token)
  442. }
  443. func (tl *TokenList) String() string {
  444. if tl.sa != "" {
  445. return tl.o.Get(tl.sa).String()
  446. }
  447. if tl.dtl.Get("constructor") == js.Global.Get("DOMSettableTokenList") {
  448. return tl.dtl.Get("value").String()
  449. }
  450. // We could manually construct the string, but I am not aware of
  451. // any case where we have neither a string attribute nor
  452. // DOMSettableTokenList.
  453. return ""
  454. }
  455. func (tl *TokenList) Slice() []string {
  456. var out []string
  457. length := tl.dtl.Get("length").Int()
  458. for i := 0; i < length; i++ {
  459. out = append(out, tl.dtl.Call("item", i).String())
  460. }
  461. return out
  462. }
  463. // SetString sets the TokenList's value to the space-separated list of
  464. // tokens in s.
  465. func (tl *TokenList) SetString(s string) {
  466. if tl.sa != "" {
  467. tl.o.Set(tl.sa, s)
  468. return
  469. }
  470. if tl.dtl.Get("constructor") == js.Global.Get("DOMSettableTokenList") {
  471. tl.dtl.Set("value", s)
  472. return
  473. }
  474. // This shouldn't be possible
  475. panic("no way to SetString on this TokenList")
  476. }
  477. // Set sets the TokenList's value to the list of tokens in s.
  478. //
  479. // Individual tokens in s shouldn't countain spaces.
  480. func (tl *TokenList) Set(s []string) {
  481. tl.SetString(strings.Join(s, " "))
  482. }
  483. type Document interface {
  484. Node
  485. ParentNode
  486. Async() bool
  487. SetAsync(bool)
  488. Doctype() DocumentType
  489. DocumentElement() Element
  490. DocumentURI() string
  491. Implementation() DOMImplementation
  492. LastStyleSheetSet() string
  493. PreferredStyleSheetSet() string // TODO correct type?
  494. SelectedStyleSheetSet() string // TODO correct type?
  495. StyleSheets() []StyleSheet // TODO s/StyleSheet/Stylesheet/ ?
  496. StyleSheetSets() []StyleSheet // TODO correct type?
  497. AdoptNode(node Node) Node
  498. ImportNode(node Node, deep bool) Node
  499. CreateElement(name string) Element
  500. CreateElementNS(namespace, name string) Element
  501. CreateTextNode(s string) *Text
  502. ElementFromPoint(x, y int) Element
  503. EnableStyleSheetsForSet(name string)
  504. GetElementsByClassName(name string) []Element
  505. GetElementsByTagName(name string) []Element
  506. GetElementsByTagNameNS(ns, name string) []Element
  507. GetElementByID(id string) Element
  508. QuerySelector(sel string) Element
  509. QuerySelectorAll(sel string) []Element
  510. CreateDocumentFragment() DocumentFragment
  511. }
  512. type DocumentFragment interface {
  513. Node
  514. ParentNode
  515. QuerySelector(sel string) Element
  516. QuerySelectorAll(sel string) []Element
  517. GetElementByID(id string) Element
  518. }
  519. type HTMLDocument interface {
  520. Document
  521. ActiveElement() HTMLElement
  522. Body() HTMLElement
  523. Cookie() string
  524. SetCookie(string)
  525. DefaultView() Window
  526. DesignMode() bool
  527. SetDesignMode(bool)
  528. Domain() string
  529. SetDomain(string)
  530. Forms() []*HTMLFormElement
  531. Head() *HTMLHeadElement
  532. Images() []*HTMLImageElement
  533. LastModified() time.Time
  534. Links() []HTMLElement
  535. Location() *Location
  536. Plugins() []*HTMLEmbedElement
  537. ReadyState() string
  538. Referrer() string
  539. Scripts() []*HTMLScriptElement
  540. Title() string
  541. SetTitle(string)
  542. URL() string
  543. // TODO HTMLDocument methods
  544. }
  545. type documentFragment struct {
  546. *BasicNode
  547. }
  548. func (d documentFragment) GetElementByID(id string) Element {
  549. return wrapElement(d.Call("getElementById", id))
  550. }
  551. func (d documentFragment) QuerySelector(sel string) Element {
  552. return (&BasicElement{&BasicNode{d.Object}}).QuerySelector(sel)
  553. }
  554. func (d documentFragment) QuerySelectorAll(sel string) []Element {
  555. return (&BasicElement{&BasicNode{d.Object}}).QuerySelectorAll(sel)
  556. }
  557. type document struct {
  558. *BasicNode
  559. }
  560. type htmlDocument struct {
  561. *document
  562. }
  563. func (d *htmlDocument) ActiveElement() HTMLElement {
  564. return wrapHTMLElement(d.Get("activeElement"))
  565. }
  566. func (d *htmlDocument) Body() HTMLElement {
  567. return wrapHTMLElement(d.Get("body"))
  568. }
  569. func (d *htmlDocument) Cookie() string {
  570. return d.Get("cookie").String()
  571. }
  572. func (d *htmlDocument) SetCookie(s string) {
  573. d.Set("cookie", s)
  574. }
  575. func (d *htmlDocument) DefaultView() Window {
  576. return &window{d.Get("defaultView")}
  577. }
  578. func (d *htmlDocument) DesignMode() bool {
  579. s := d.Get("designMode").String()
  580. return s != "off"
  581. }
  582. func (d *htmlDocument) SetDesignMode(b bool) {
  583. s := "off"
  584. if b {
  585. s = "on"
  586. }
  587. d.Set("designMode", s)
  588. }
  589. func (d *htmlDocument) Domain() string {
  590. return d.Get("domain").String()
  591. }
  592. func (d *htmlDocument) SetDomain(s string) {
  593. d.Set("domain", s)
  594. }
  595. func (d *htmlDocument) Forms() []*HTMLFormElement {
  596. var els []*HTMLFormElement
  597. forms := d.Get("forms")
  598. length := forms.Get("length").Int()
  599. for i := 0; i < length; i++ {
  600. els = append(els, wrapHTMLElement(forms.Call("item", i)).(*HTMLFormElement))
  601. }
  602. return els
  603. }
  604. func (d *htmlDocument) Head() *HTMLHeadElement {
  605. head := wrapElement(d.Get("head"))
  606. if head == nil {
  607. return nil
  608. }
  609. return head.(*HTMLHeadElement)
  610. }
  611. func (d *htmlDocument) Images() []*HTMLImageElement {
  612. var els []*HTMLImageElement
  613. images := d.Get("images")
  614. length := images.Get("length").Int()
  615. for i := 0; i < length; i++ {
  616. els = append(els, wrapHTMLElement(images.Call("item", i)).(*HTMLImageElement))
  617. }
  618. return els
  619. }
  620. func (d *htmlDocument) LastModified() time.Time {
  621. return d.Get("lastModified").Interface().(time.Time)
  622. }
  623. func (d *htmlDocument) Links() []HTMLElement {
  624. var els []HTMLElement
  625. links := d.Get("links")
  626. length := links.Get("length").Int()
  627. for i := 0; i < length; i++ {
  628. els = append(els, wrapHTMLElement(links.Call("item", i)))
  629. }
  630. return els
  631. }
  632. func (d *htmlDocument) Location() *Location {
  633. o := d.Get("location")
  634. return &Location{Object: o, URLUtils: &URLUtils{Object: o}}
  635. }
  636. func (d *htmlDocument) Plugins() []*HTMLEmbedElement {
  637. var els []*HTMLEmbedElement
  638. forms := d.Get("plugins")
  639. length := forms.Get("length").Int()
  640. for i := 0; i < length; i++ {
  641. els = append(els, wrapHTMLElement(forms.Call("item", i)).(*HTMLEmbedElement))
  642. }
  643. return els
  644. }
  645. func (d *htmlDocument) ReadyState() string {
  646. return d.Get("readyState").String()
  647. }
  648. func (d *htmlDocument) Referrer() string {
  649. return d.Get("referrer").String()
  650. }
  651. func (d *htmlDocument) Scripts() []*HTMLScriptElement {
  652. var els []*HTMLScriptElement
  653. forms := d.Get("scripts")
  654. length := forms.Get("length").Int()
  655. for i := 0; i < length; i++ {
  656. els = append(els, wrapHTMLElement(forms.Call("item", i)).(*HTMLScriptElement))
  657. }
  658. return els
  659. }
  660. func (d *htmlDocument) Title() string {
  661. return d.Get("title").String()
  662. }
  663. func (d *htmlDocument) SetTitle(s string) {
  664. d.Set("title", s)
  665. }
  666. func (d *htmlDocument) URL() string {
  667. return d.Get("URL").String()
  668. }
  669. func (d document) Async() bool {
  670. return d.Get("async").Bool()
  671. }
  672. func (d document) SetAsync(b bool) {
  673. d.Set("async", b)
  674. }
  675. func (d document) Doctype() DocumentType {
  676. // FIXME implement
  677. panic("not implemented")
  678. }
  679. func (d document) DocumentElement() Element {
  680. return wrapElement(d.Get("documentElement"))
  681. }
  682. func (d document) DocumentURI() string {
  683. return d.Get("documentURI").String()
  684. }
  685. func (d document) Implementation() DOMImplementation {
  686. // FIXME implement
  687. panic("not implemented")
  688. }
  689. func (d document) LastStyleSheetSet() string {
  690. return d.Get("lastStyleSheetSet").String()
  691. }
  692. func (d document) PreferredStyleSheetSet() string {
  693. return d.Get("preferredStyleSheetSet").String()
  694. }
  695. func (d document) SelectedStyleSheetSet() string {
  696. return d.Get("selectedStyleSheetSet").String()
  697. }
  698. func (d document) StyleSheets() []StyleSheet {
  699. // FIXME implement
  700. panic("not implemented")
  701. }
  702. func (d document) StyleSheetSets() []StyleSheet {
  703. // FIXME implement
  704. panic("not implemented")
  705. }
  706. func (d document) AdoptNode(node Node) Node {
  707. return wrapNode(d.Call("adoptNode", node.Underlying()))
  708. }
  709. func (d document) ImportNode(node Node, deep bool) Node {
  710. return wrapNode(d.Call("importNode", node.Underlying(), deep))
  711. }
  712. func (d document) CreateDocumentFragment() DocumentFragment {
  713. return wrapDocumentFragment(d.Call("createDocumentFragment"))
  714. }
  715. func (d document) CreateElement(name string) Element {
  716. return wrapElement(d.Call("createElement", name))
  717. }
  718. func (d document) CreateElementNS(ns string, name string) Element {
  719. return wrapElement(d.Call("createElementNS", ns, name))
  720. }
  721. func (d document) CreateTextNode(s string) *Text {
  722. return wrapNode(d.Call("createTextNode", s)).(*Text)
  723. }
  724. func (d document) ElementFromPoint(x, y int) Element {
  725. return wrapElement(d.Call("elementFromPoint", x, y))
  726. }
  727. func (d document) EnableStyleSheetsForSet(name string) {
  728. d.Call("enableStyleSheetsForSet", name)
  729. }
  730. func (d document) GetElementsByClassName(name string) []Element {
  731. return (&BasicElement{&BasicNode{d.Object}}).GetElementsByClassName(name)
  732. }
  733. func (d document) GetElementsByTagName(name string) []Element {
  734. return (&BasicElement{&BasicNode{d.Object}}).GetElementsByTagName(name)
  735. }
  736. func (d document) GetElementsByTagNameNS(ns, name string) []Element {
  737. return (&BasicElement{&BasicNode{d.Object}}).GetElementsByTagNameNS(ns, name)
  738. }
  739. func (d document) GetElementByID(id string) Element {
  740. return wrapElement(d.Call("getElementById", id))
  741. }
  742. func (d document) QuerySelector(sel string) Element {
  743. return (&BasicElement{&BasicNode{d.Object}}).QuerySelector(sel)
  744. }
  745. func (d document) QuerySelectorAll(sel string) []Element {
  746. return (&BasicElement{&BasicNode{d.Object}}).QuerySelectorAll(sel)
  747. }
  748. type URLUtils struct {
  749. *js.Object
  750. Href string `js:"href"`
  751. Protocol string `js:"protocol"`
  752. Host string `js:"host"`
  753. Hostname string `js:"hostname"`
  754. Port string `js:"port"`
  755. Pathname string `js:"pathname"`
  756. Search string `js:"search"`
  757. Hash string `js:"hash"`
  758. Username string `js:"username"`
  759. Password string `js:"password"`
  760. Origin string `js:"origin"`
  761. }
  762. // TODO Location methods
  763. type Location struct {
  764. *js.Object
  765. *URLUtils
  766. }
  767. type HTMLElement interface {
  768. Element
  769. GlobalEventHandlers
  770. AccessKey() string
  771. Dataset() map[string]string
  772. SetAccessKey(string)
  773. AccessKeyLabel() string
  774. SetAccessKeyLabel(string)
  775. ContentEditable() string
  776. SetContentEditable(string)
  777. IsContentEditable() bool
  778. Dir() string
  779. SetDir(string)
  780. Draggable() bool
  781. SetDraggable(bool)
  782. Lang() string
  783. SetLang(string)
  784. OffsetHeight() float64
  785. OffsetLeft() float64
  786. OffsetParent() HTMLElement
  787. OffsetTop() float64
  788. OffsetWidth() float64
  789. Style() *CSSStyleDeclaration
  790. Title() string
  791. SetTitle(string)
  792. Blur()
  793. Click()
  794. Focus()
  795. }
  796. type SVGElement interface {
  797. Element
  798. // TODO
  799. }
  800. type GlobalEventHandlers interface{}
  801. type Window interface {
  802. EventTarget
  803. Console() *Console
  804. Document() Document
  805. FrameElement() Element
  806. Location() *Location
  807. Name() string
  808. SetName(string)
  809. InnerHeight() int
  810. InnerWidth() int
  811. Length() int
  812. Opener() Window
  813. OuterHeight() int
  814. OuterWidth() int
  815. ScrollX() int
  816. ScrollY() int
  817. Parent() Window
  818. ScreenX() int
  819. ScreenY() int
  820. ScrollMaxX() int
  821. ScrollMaxY() int
  822. Top() Window
  823. History() History
  824. Navigator() Navigator
  825. Screen() *Screen
  826. Alert(string)
  827. Back()
  828. Blur()
  829. CancelAnimationFrame(int)
  830. ClearInterval(int)
  831. ClearTimeout(int)
  832. Close()
  833. Confirm(string) bool
  834. Focus()
  835. Forward()
  836. GetComputedStyle(el Element, pseudoElt string) *CSSStyleDeclaration
  837. GetSelection() Selection
  838. Home()
  839. MoveBy(dx, dy int)
  840. MoveTo(x, y int)
  841. Open(url, name, features string) Window
  842. OpenDialog(url, name, features string, args []interface{}) Window
  843. PostMessage(message string, target string, transfer []interface{})
  844. Print()
  845. Prompt(prompt string, initial string) string
  846. RequestAnimationFrame(callback func(time.Duration)) int
  847. ResizeBy(dw, dh int)
  848. ResizeTo(w, h int)
  849. Scroll(x, y int)
  850. ScrollBy(dx, dy int)
  851. ScrollByLines(int)
  852. ScrollTo(x, y int)
  853. SetCursor(name string)
  854. SetInterval(fn func(), delay int) int
  855. SetTimeout(fn func(), delay int) int
  856. Stop()
  857. // TODO constructors
  858. }
  859. type window struct {
  860. // TODO EventTarget
  861. *js.Object
  862. }
  863. func (w *window) Console() *Console {
  864. return &Console{w.Get("console")}
  865. }
  866. func (w *window) Document() Document {
  867. return wrapDocument(w.Get("document"))
  868. }
  869. func (w *window) FrameElement() Element {
  870. return wrapElement(w.Get("frameElement"))
  871. }
  872. func (w *window) Location() *Location {
  873. o := w.Get("location")
  874. return &Location{Object: o, URLUtils: &URLUtils{Object: o}}
  875. }
  876. func (w *window) Name() string {
  877. return w.Get("name").String()
  878. }
  879. func (w *window) SetName(s string) {
  880. w.Set("name", s)
  881. }
  882. func (w *window) InnerHeight() int {
  883. return w.Get("innerHeight").Int()
  884. }
  885. func (w *window) InnerWidth() int {
  886. return w.Get("innerWidth").Int()
  887. }
  888. func (w *window) Length() int {
  889. return w.Get("length").Int()
  890. }
  891. func (w *window) Opener() Window {
  892. return &window{w.Get("opener")}
  893. }
  894. func (w *window) OuterHeight() int {
  895. return w.Get("outerHeight").Int()
  896. }
  897. func (w *window) OuterWidth() int {
  898. return w.Get("outerWidth").Int()
  899. }
  900. func (w *window) ScrollX() int {
  901. return w.Get("scrollX").Int()
  902. }
  903. func (w *window) ScrollY() int {
  904. return w.Get("scrollY").Int()
  905. }
  906. func (w *window) Parent() Window {
  907. return &window{w.Get("parent")}
  908. }
  909. func (w *window) ScreenX() int {
  910. return w.Get("screenX").Int()
  911. }
  912. func (w *window) ScreenY() int {
  913. return w.Get("screenY").Int()
  914. }
  915. func (w *window) ScrollMaxX() int {
  916. return w.Get("scrollMaxX").Int()
  917. }
  918. func (w *window) ScrollMaxY() int {
  919. return w.Get("scrollMaxY").Int()
  920. }
  921. func (w *window) Top() Window {
  922. return &window{w.Get("top")}
  923. }
  924. func (w *window) History() History {
  925. // FIXME implement
  926. return nil
  927. }
  928. func (w *window) Navigator() Navigator {
  929. // FIXME implement
  930. panic("not implemented")
  931. }
  932. func (w *window) Screen() *Screen {
  933. return &Screen{Object: w.Get("screen")}
  934. }
  935. func (w *window) Alert(msg string) {
  936. w.Call("alert", msg)
  937. }
  938. func (w *window) Back() {
  939. w.Call("back")
  940. }
  941. func (w *window) Blur() {
  942. w.Call("blur")
  943. }
  944. func (w *window) ClearInterval(id int) {
  945. w.Call("clearInterval", id)
  946. }
  947. func (w *window) ClearTimeout(id int) {
  948. w.Call("clearTimeout", id)
  949. }
  950. func (w *window) Close() {
  951. w.Call("close")
  952. }
  953. func (w *window) Confirm(prompt string) bool {
  954. return w.Call("confirm", prompt).Bool()
  955. }
  956. func (w *window) Focus() {
  957. w.Call("focus")
  958. }
  959. func (w *window) Forward() {
  960. w.Call("forward")
  961. }
  962. // GetComputedStyle returns the values of all CSS properties of an
  963. // element after applying the active stylesheets. pseudoElt specifies
  964. // the pseudo-element to match. For normal elements, it must be the
  965. // empty string.
  966. func (w *window) GetComputedStyle(el Element, pseudoElt string) *CSSStyleDeclaration {
  967. var optArg interface{}
  968. if pseudoElt != "" {
  969. optArg = pseudoElt
  970. }
  971. return &CSSStyleDeclaration{w.Call("getComputedStyle", el.Underlying(), optArg)}
  972. }
  973. func (w *window) GetSelection() Selection {
  974. // FIXME implement
  975. panic("not implemented")
  976. }
  977. func (w *window) Home() {
  978. w.Call("home")
  979. }
  980. func (w *window) MoveBy(dx, dy int) {
  981. w.Call("moveBy", dx, dy)
  982. }
  983. func (w *window) MoveTo(x, y int) {
  984. w.Call("moveTo", x, y)
  985. }
  986. func (w *window) Open(url, name, features string) Window {
  987. return &window{w.Call("open", url, name, features)}
  988. }
  989. func (w *window) OpenDialog(url, name, features string, args []interface{}) Window {
  990. return &window{w.Call("openDialog", url, name, features, args)}
  991. }
  992. func (w *window) PostMessage(message string, target string, transfer []interface{}) {
  993. w.Call("postMessage", message, target, transfer)
  994. }
  995. func (w *window) Print() {
  996. w.Call("print")
  997. }
  998. func (w *window) Prompt(prompt string, initial string) string {
  999. return w.Call("prompt", prompt, initial).String()
  1000. }
  1001. func (w *window) ResizeBy(dw, dh int) {
  1002. w.Call("resizeBy", dw, dh)
  1003. }
  1004. func (w *window) ResizeTo(width, height int) {
  1005. w.Call("resizeTo", width, height)
  1006. }
  1007. func (w *window) Scroll(x, y int) {
  1008. w.Call("scroll", x, y)
  1009. }
  1010. func (w *window) ScrollBy(dx, dy int) {
  1011. w.Call("scrollBy", dx, dy)
  1012. }
  1013. func (w *window) ScrollByLines(i int) {
  1014. w.Call("scrollByLines", i)
  1015. }
  1016. func (w *window) ScrollTo(x, y int) {
  1017. w.Call("scrollTo", x, y)
  1018. }
  1019. func (w *window) SetCursor(name string) {
  1020. w.Call("setCursor", name)
  1021. }
  1022. func (w *window) SetInterval(fn func(), delay int) int {
  1023. return w.Call("setInterval", fn, delay).Int()
  1024. }
  1025. func (w *window) SetTimeout(fn func(), delay int) int {
  1026. return w.Call("setTimeout", fn, delay).Int()
  1027. }
  1028. func (w *window) Stop() {
  1029. w.Call("stop")
  1030. }
  1031. // TODO reuse util.EventTarget
  1032. func (w *window) AddEventListener(typ string, useCapture bool, listener func(Event)) func(o *js.Object) {
  1033. wrapper := func(o *js.Object) { listener(wrapEvent(o)) }
  1034. w.Call("addEventListener", typ, wrapper, useCapture)
  1035. return wrapper
  1036. }
  1037. func (w *window) RemoveEventListener(typ string, useCapture bool, listener func(*js.Object)) {
  1038. w.Call("removeEventListener", typ, listener, useCapture)
  1039. }
  1040. func (w *window) DispatchEvent(event Event) bool {
  1041. return w.Call("dispatchEvent", event).Bool()
  1042. }
  1043. func wrapDOMHighResTimeStamp(o *js.Object) time.Duration {
  1044. return time.Duration(o.Float() * float64(time.Millisecond))
  1045. }
  1046. func (w *window) RequestAnimationFrame(callback func(time.Duration)) int {
  1047. wrapper := func(o *js.Object) { callback(wrapDOMHighResTimeStamp(o)) }
  1048. return w.Call("requestAnimationFrame", wrapper).Int()
  1049. }
  1050. func (w *window) CancelAnimationFrame(requestID int) {
  1051. w.Call("cancelAnimationFrame", requestID)
  1052. }
  1053. // TODO all the other window methods
  1054. type Selection interface {
  1055. // TODO
  1056. }
  1057. type Screen struct {
  1058. *js.Object
  1059. AvailTop int `js:"availTop"`
  1060. AvailLeft int `js:"availLeft"`
  1061. AvailHeight int `js:"availHeight"`
  1062. AvailWidth int `js:"availWidth"`
  1063. ColorDepth int `js:"colorDepth"`
  1064. Height int `js:"height"`
  1065. Left int `js:"left"`
  1066. PixelDepth int `js:"pixelDepth"`
  1067. Top int `js:"top"`
  1068. Width int `js:"width"`
  1069. }
  1070. type Navigator interface {
  1071. NavigatorID
  1072. NavigatorLanguage
  1073. NavigatorOnLine
  1074. NavigatorGeolocation
  1075. // NavigatorPlugins
  1076. // NetworkInformation
  1077. CookieEnabled() bool
  1078. DoNotTrack() string
  1079. RegisterProtocolHandler(protocol, uri, title string)
  1080. }
  1081. type NavigatorID interface {
  1082. AppName() string
  1083. AppVersion() string
  1084. Platform() string
  1085. Product() string
  1086. UserAgent() string
  1087. }
  1088. type NavigatorLanguage interface {
  1089. Language() string
  1090. }
  1091. type NavigatorOnLine interface {
  1092. Online() bool
  1093. }
  1094. type NavigatorGeolocation interface {
  1095. Geolocation() Geolocation
  1096. }
  1097. type Geolocation interface {
  1098. // TODO wrap PositionOptions into something that uses the JS
  1099. // object
  1100. CurrentPosition(success func(Position), err func(PositionError), opts PositionOptions) Position
  1101. WatchPosition(success func(Position), err func(PositionError), opts PositionOptions) int
  1102. ClearWatch(int)
  1103. }
  1104. type PositionError struct {
  1105. *js.Object
  1106. Code int `js:"code"`
  1107. }
  1108. func (err *PositionError) Error() string {
  1109. return err.Call("message").String()
  1110. }
  1111. type PositionOptions struct {
  1112. EnableHighAccuracy bool
  1113. Timeout time.Duration
  1114. MaximumAge time.Duration
  1115. }
  1116. type Position struct {
  1117. Coords *Coordinates
  1118. Timestamp time.Time
  1119. }
  1120. type Coordinates struct {
  1121. *js.Object
  1122. Latitude float64 `js:"latitude"`
  1123. Longitude float64 `js:"longitude"`
  1124. Altitude float64 `js:"altitude"`
  1125. Accuracy float64 `js:"accuracy"`
  1126. AltitudeAccuracy float64 `js:"altitudeAccuracy"`
  1127. Heading float64 `js:"heading"`
  1128. Speed float64 `js:"speed"`
  1129. }
  1130. type History interface {
  1131. Length() int
  1132. State() interface{}
  1133. Back()
  1134. Forward()
  1135. Go(offset int)
  1136. PushState(state interface{}, title string, url string)
  1137. ReplaceState(state interface{}, title string, url string)
  1138. }
  1139. type Console struct {
  1140. *js.Object
  1141. // TODO will replace the js/console package
  1142. }
  1143. type SVGDocument interface{}
  1144. type DocumentType interface{}
  1145. type DOMImplementation interface{}
  1146. type StyleSheet interface{}
  1147. type CSSStyleSheet interface{}
  1148. type Node interface {
  1149. EventTarget
  1150. Underlying() *js.Object
  1151. BaseURI() string
  1152. ChildNodes() []Node
  1153. FirstChild() Node
  1154. LastChild() Node
  1155. NextSibling() Node
  1156. NodeName() string
  1157. NodeType() int
  1158. NodeValue() string
  1159. SetNodeValue(string)
  1160. OwnerDocument() Document
  1161. ParentNode() Node
  1162. ParentElement() Element
  1163. PreviousSibling() Node
  1164. TextContent() string
  1165. SetTextContent(string)
  1166. AppendChild(Node)
  1167. CloneNode(deep bool) Node
  1168. CompareDocumentPosition(Node) int
  1169. Contains(Node) bool
  1170. HasChildNodes() bool
  1171. InsertBefore(which Node, before Node)
  1172. IsDefaultNamespace(string) bool
  1173. IsEqualNode(Node) bool
  1174. LookupPrefix() string
  1175. LookupNamespaceURI(string) string
  1176. Normalize()
  1177. RemoveChild(Node)
  1178. ReplaceChild(newChild, oldChild Node)
  1179. }
  1180. // Type BasicNode implements the Node interface and is embedded by
  1181. // concrete node types and element types.
  1182. type BasicNode struct {
  1183. *js.Object
  1184. }
  1185. func (n *BasicNode) Underlying() *js.Object {
  1186. return n.Object
  1187. }
  1188. func (n *BasicNode) AddEventListener(typ string, useCapture bool, listener func(Event)) func(*js.Object) {
  1189. wrapper := func(o *js.Object) { listener(wrapEvent(o)) }
  1190. n.Call("addEventListener", typ, wrapper, useCapture)
  1191. return wrapper
  1192. }
  1193. func (n *BasicNode) RemoveEventListener(typ string, useCapture bool, listener func(*js.Object)) {
  1194. n.Call("removeEventListener", typ, listener, useCapture)
  1195. }
  1196. func (n *BasicNode) DispatchEvent(event Event) bool {
  1197. return n.Call("dispatchEvent", event).Bool()
  1198. }
  1199. func (n *BasicNode) BaseURI() string {
  1200. return n.Get("baseURI").String()
  1201. }
  1202. func (n *BasicNode) ChildNodes() []Node {
  1203. return nodeListToNodes(n.Get("childNodes"))
  1204. }
  1205. func (n *BasicNode) FirstChild() Node {
  1206. return wrapNode(n.Get("firstChild"))
  1207. }
  1208. func (n *BasicNode) LastChild() Node {
  1209. return wrapNode(n.Get("lastChild"))
  1210. }
  1211. func (n *BasicNode) NextSibling() Node {
  1212. return wrapNode(n.Get("nextSibling"))
  1213. }
  1214. func (n *BasicNode) NodeName() string {
  1215. return n.Get("nodeName").String()
  1216. }
  1217. func (n *BasicNode) NodeType() int {
  1218. return n.Get("nodeType").Int()
  1219. }
  1220. func (n *BasicNode) NodeValue() string {
  1221. return toString(n.Get("nodeValue"))
  1222. }
  1223. func (n *BasicNode) SetNodeValue(s string) {
  1224. n.Set("nodeValue", s)
  1225. }
  1226. func (n *BasicNode) OwnerDocument() Document {
  1227. // FIXME implement
  1228. panic("not implemented")
  1229. }
  1230. func (n *BasicNode) ParentNode() Node {
  1231. return wrapNode(n.Get("parentNode"))
  1232. }
  1233. func (n *BasicNode) ParentElement() Element {
  1234. return wrapElement(n.Get("parentElement"))
  1235. }
  1236. func (n *BasicNode) PreviousSibling() Node {
  1237. return wrapNode(n.Get("previousSibling"))
  1238. }
  1239. func (n *BasicNode) TextContent() string {
  1240. return toString(n.Get("textContent"))
  1241. }
  1242. func (n *BasicNode) SetTextContent(s string) {
  1243. n.Set("textContent", s)
  1244. }
  1245. func (n *BasicNode) AppendChild(newchild Node) {
  1246. n.Call("appendChild", newchild.Underlying())
  1247. }
  1248. func (n *BasicNode) CloneNode(deep bool) Node {
  1249. return wrapNode(n.Call("cloneNode", deep))
  1250. }
  1251. const (
  1252. DocumentPositionDisconnected = 1
  1253. DocumentPositionPreceding = 2
  1254. DocumentPositionFollowing = 4
  1255. DocumentPositionContains = 8
  1256. DocumentPositionContainedBy = 16
  1257. DocumentPositionImplementationSpecific = 32
  1258. )
  1259. func (n *BasicNode) CompareDocumentPosition(other Node) int {
  1260. return n.Call("compareDocumentPosition", other.Underlying()).Int()
  1261. }
  1262. func (n *BasicNode) Contains(other Node) bool {
  1263. return n.Call("contains", other.Underlying()).Bool()
  1264. }
  1265. func (n *BasicNode) HasChildNodes() bool {
  1266. return n.Call("hasChildNodes").Bool()
  1267. }
  1268. func (n *BasicNode) InsertBefore(which Node, before Node) {
  1269. var o interface{}
  1270. if before != nil {
  1271. o = before.Underlying()
  1272. }
  1273. n.Call("insertBefore", which.Underlying(), o)
  1274. }
  1275. func (n *BasicNode) IsDefaultNamespace(s string) bool {
  1276. return n.Call("isDefaultNamespace", s).Bool()
  1277. }
  1278. func (n *BasicNode) IsEqualNode(other Node) bool {
  1279. return n.Call("isEqualNode", other.Underlying()).Bool()
  1280. }
  1281. func (n *BasicNode) LookupPrefix() string {
  1282. return n.Call("lookupPrefix").String()
  1283. }
  1284. func (n *BasicNode) LookupNamespaceURI(s string) string {
  1285. return toString(n.Call("lookupNamespaceURI", s))
  1286. }
  1287. func (n *BasicNode) Normalize() {
  1288. n.Call("normalize")
  1289. }
  1290. func (n *BasicNode) RemoveChild(other Node) {
  1291. n.Call("removeChild", other.Underlying())
  1292. }
  1293. func (n *BasicNode) ReplaceChild(newChild, oldChild Node) {
  1294. n.Call("replaceChild", newChild.Underlying(), oldChild.Underlying())
  1295. }
  1296. type Element interface {
  1297. Node
  1298. ParentNode
  1299. ChildNode
  1300. Attributes() map[string]string
  1301. Class() *TokenList
  1302. Closest(string) Element
  1303. ID() string
  1304. SetID(string)
  1305. TagName() string
  1306. GetAttribute(string) string // TODO can attributes only be strings?
  1307. GetAttributeNS(ns string, name string) string // can attributes only be strings?
  1308. GetBoundingClientRect() ClientRect
  1309. GetElementsByClassName(string) []Element
  1310. GetElementsByTagName(string) []Element
  1311. GetElementsByTagNameNS(ns string, name string) []Element
  1312. HasAttribute(string) bool
  1313. HasAttributeNS(ns string, name string) bool
  1314. Matches(string) bool
  1315. QuerySelector(string) Element
  1316. QuerySelectorAll(string) []Element
  1317. RemoveAttribute(string)
  1318. RemoveAttributeNS(ns string, name string)
  1319. SetAttribute(name string, value string)
  1320. SetAttributeNS(ns string, name string, value string)
  1321. InnerHTML() string
  1322. SetInnerHTML(string)
  1323. OuterHTML() string
  1324. SetOuterHTML(string)
  1325. }
  1326. type ClientRect struct {
  1327. *js.Object
  1328. Height float64 `js:"height"`
  1329. Width float64 `js:"width"`
  1330. Left float64 `js:"left"`
  1331. Right float64 `js:"right"`
  1332. Top float64 `js:"top"`
  1333. Bottom float64 `js:"bottom"`
  1334. }
  1335. type ParentNode interface {
  1336. // No properties/methods that aren't experimental
  1337. }
  1338. type ChildNode interface {
  1339. PreviousElementSibling() Element
  1340. NextElementSibling() Element
  1341. }
  1342. // Type BasicHTMLElement implements the HTMLElement interface and is
  1343. // embedded by concrete HTML element types.
  1344. type BasicHTMLElement struct {
  1345. *BasicElement
  1346. // TODO globalEventHandlers
  1347. }
  1348. func (e *BasicHTMLElement) AccessKey() string {
  1349. return e.Get("accessKey").String()
  1350. }
  1351. func (e *BasicHTMLElement) Dataset() map[string]string {
  1352. o := e.Get("dataset")
  1353. data := map[string]string{}
  1354. keys := js.Keys(o)
  1355. for _, key := range keys {
  1356. data[key] = o.Get(key).String()
  1357. }
  1358. return data
  1359. }
  1360. func (e *BasicHTMLElement) SetAccessKey(s string) {
  1361. e.Set("accessKey", s)
  1362. }
  1363. func (e *BasicHTMLElement) AccessKeyLabel() string {
  1364. return e.Get("accessKeyLabel").String()
  1365. }
  1366. func (e *BasicHTMLElement) SetAccessKeyLabel(s string) {
  1367. e.Set("accessKeyLabel", s)
  1368. }
  1369. func (e *BasicHTMLElement) ContentEditable() string {
  1370. return e.Get("contentEditable").String()
  1371. }
  1372. func (e *BasicHTMLElement) SetContentEditable(s string) {
  1373. e.Set("contentEditable", s)
  1374. }
  1375. func (e *BasicHTMLElement) IsContentEditable() bool {
  1376. return e.Get("isContentEditable").Bool()
  1377. }
  1378. func (e *BasicHTMLElement) Dir() string {
  1379. return e.Get("dir").String()
  1380. }
  1381. func (e *BasicHTMLElement) SetDir(s string) {
  1382. e.Set("dir", s)
  1383. }
  1384. func (e *BasicHTMLElement) Draggable() bool {
  1385. return e.Get("draggable").Bool()
  1386. }
  1387. func (e *BasicHTMLElement) SetDraggable(b bool) {
  1388. e.Set("draggable", b)
  1389. }
  1390. func (e *BasicHTMLElement) Lang() string {
  1391. return e.Get("lang").String()
  1392. }
  1393. func (e *BasicHTMLElement) SetLang(s string) {
  1394. e.Set("lang", s)
  1395. }
  1396. func (e *BasicHTMLElement) OffsetHeight() float64 {
  1397. return e.Get("offsetHeight").Float()
  1398. }
  1399. func (e *BasicHTMLElement) OffsetLeft() float64 {
  1400. return e.Get("offsetLeft").Float()
  1401. }
  1402. func (e *BasicHTMLElement) OffsetParent() HTMLElement {
  1403. return wrapHTMLElement(e.Get("offsetParent"))
  1404. }
  1405. func (e *BasicHTMLElement) OffsetTop() float64 {
  1406. return e.Get("offsetTop").Float()
  1407. }
  1408. func (e *BasicHTMLElement) OffsetWidth() float64 {
  1409. return e.Get("offsetWidth").Float()
  1410. }
  1411. func (e *BasicHTMLElement) Style() *CSSStyleDeclaration {
  1412. return &CSSStyleDeclaration{e.Get("style")}
  1413. }
  1414. func (e *BasicHTMLElement) TabIndex() int {
  1415. return e.Get("tabIndex").Int()
  1416. }
  1417. func (e *BasicHTMLElement) SetTabIndex(i int) {
  1418. e.Set("tabIndex", i)
  1419. }
  1420. func (e *BasicHTMLElement) Title() string {
  1421. return e.Get("title").String()
  1422. }
  1423. func (e *BasicHTMLElement) SetTitle(s string) {
  1424. e.Set("title", s)
  1425. }
  1426. func (e *BasicHTMLElement) Blur() {
  1427. e.Call("blur")
  1428. }
  1429. func (e *BasicHTMLElement) Click() {
  1430. e.Call("click")
  1431. }
  1432. func (e *BasicHTMLElement) Focus() {
  1433. e.Call("focus")
  1434. }
  1435. // Type BasicElement implements the Element interface and is embedded
  1436. // by concrete element types and HTML element types.
  1437. type BasicElement struct {
  1438. *BasicNode
  1439. }
  1440. func (e *BasicElement) Attributes() map[string]string {
  1441. o := e.Get("attributes")
  1442. attrs := map[string]string{}
  1443. length := o.Get("length").Int()
  1444. for i := 0; i < length; i++ {
  1445. item := o.Call("item", i)
  1446. attrs[item.Get("name").String()] = item.Get("value").String()
  1447. }
  1448. return attrs
  1449. }
  1450. func (e *BasicElement) GetBoundingClientRect() ClientRect {
  1451. obj := e.Call("getBoundingClientRect")
  1452. return ClientRect{Object: obj}
  1453. }
  1454. func (e *BasicElement) PreviousElementSibling() Element {
  1455. return wrapElement(e.Get("previousElementSibling"))
  1456. }
  1457. func (e *BasicElement) NextElementSibling() Element {
  1458. return wrapElement(e.Get("nextElementSibling"))
  1459. }
  1460. func (e *BasicElement) Class() *TokenList {
  1461. return &TokenList{dtl: e.Get("classList"), o: e.Object, sa: "className"}
  1462. }
  1463. // SetClass sets the element's className attribute to s. Consider
  1464. // using the Class method instead.
  1465. func (e *BasicElement) SetClass(s string) {
  1466. e.Set("className", s)
  1467. }
  1468. func (e *BasicElement) Closest(s string) Element {
  1469. return wrapElement(e.Call("closest", s))
  1470. }
  1471. func (e *BasicElement) ID() string {
  1472. return e.Get("id").String()
  1473. }
  1474. func (e *BasicElement) SetID(s string) {
  1475. e.Set("id", s)
  1476. }
  1477. func (e *BasicElement) TagName() string {
  1478. return e.Get("tagName").String()
  1479. }
  1480. func (e *BasicElement) GetAttribute(name string) string {
  1481. return toString(e.Call("getAttribute", name))
  1482. }
  1483. func (e *BasicElement) GetAttributeNS(ns string, name string) string {
  1484. return toString(e.Call("getAttributeNS", ns, name))
  1485. }
  1486. func (e *BasicElement) GetElementsByClassName(s string) []Element {
  1487. return nodeListToElements(e.Call("getElementsByClassName", s))
  1488. }
  1489. func (e *BasicElement) GetElementsByTagName(s string) []Element {
  1490. return nodeListToElements(e.Call("getElementsByTagName", s))
  1491. }
  1492. func (e *BasicElement) GetElementsByTagNameNS(ns string, name string) []Element {
  1493. return nodeListToElements(e.Call("getElementsByTagNameNS", ns, name))
  1494. }
  1495. func (e *BasicElement) HasAttribute(s string) bool {
  1496. return e.Call("hasAttribute", s).Bool()
  1497. }
  1498. func (e *BasicElement) HasAttributeNS(ns string, name string) bool {
  1499. return e.Call("hasAttributeNS", ns, name).Bool()
  1500. }
  1501. func (e *BasicElement) Matches(s string) bool {
  1502. return e.Call("matches", s).Bool()
  1503. }
  1504. func (e *BasicElement) QuerySelector(s string) Element {
  1505. return wrapElement(e.Call("querySelector", s))
  1506. }
  1507. func (e *BasicElement) QuerySelectorAll(s string) []Element {
  1508. return nodeListToElements(e.Call("querySelectorAll", s))
  1509. }
  1510. func (e *BasicElement) RemoveAttribute(s string) {
  1511. e.Call("removeAttribute", s)
  1512. }
  1513. func (e *BasicElement) RemoveAttributeNS(ns string, name string) {
  1514. e.Call("removeAttributeNS", ns, name)
  1515. }
  1516. func (e *BasicElement) SetAttribute(name string, value string) {
  1517. e.Call("setAttribute", name, value)
  1518. }
  1519. func (e *BasicElement) SetAttributeNS(ns string, name string, value string) {
  1520. e.Call("setAttributeNS", ns, name, value)
  1521. }
  1522. func (e *BasicElement) InnerHTML() string {
  1523. return e.Get("innerHTML").String()
  1524. }
  1525. func (e *BasicElement) SetInnerHTML(s string) {
  1526. e.Set("innerHTML", s)
  1527. }
  1528. func (e *BasicElement) OuterHTML() string {
  1529. return e.Get("outerHTML").String()
  1530. }
  1531. func (e *BasicElement) SetOuterHTML(s string) {
  1532. e.Set("outerHTML", s)
  1533. }
  1534. type HTMLAnchorElement struct {
  1535. *BasicHTMLElement
  1536. *URLUtils
  1537. HrefLang string `js:"hreflang"`
  1538. Media string `js:"media"`
  1539. TabIndex int `js:"tabIndex"`
  1540. Target string `js:"target"`
  1541. Text string `js:"text"`
  1542. Type string `js:"type"`
  1543. }
  1544. func (e *HTMLAnchorElement) Rel() *TokenList {
  1545. return &TokenList{dtl: e.Get("relList"), o: e.Object, sa: "rel"}
  1546. }
  1547. type HTMLAppletElement struct {
  1548. *BasicHTMLElement
  1549. Alt string `js:"alt"`
  1550. Coords string `js:"coords"`
  1551. HrefLang string `js:"hreflang"`
  1552. Media string `js:"media"`
  1553. Search string `js:"search"`
  1554. Shape string `js:"shape"`
  1555. TabIndex int `js:"tabIndex"`
  1556. Target string `js:"target"`
  1557. Type string `js:"type"`
  1558. }
  1559. func (e *HTMLAppletElement) Rel() *TokenList {
  1560. return &TokenList{dtl: e.Get("relList"), o: e.Object, sa: "rel"}
  1561. }
  1562. type HTMLAreaElement struct {
  1563. *BasicHTMLElement
  1564. *URLUtils
  1565. Alt string `js:"alt"`
  1566. Coords string `js:"coords"`
  1567. HrefLang string `js:"hreflang"`
  1568. Media string `js:"media"`
  1569. Search string `js:"search"`
  1570. Shape string `js:"shape"`
  1571. TabIndex int `js:"tabIndex"`
  1572. Target string `js:"target"`
  1573. Type string `js:"type"`
  1574. }
  1575. func (e *HTMLAreaElement) Rel() *TokenList {
  1576. return &TokenList{dtl: e.Get("relList"), o: e.Object, sa: "rel"}
  1577. }
  1578. type HTMLAudioElement struct{ *HTMLMediaElement }
  1579. type HTMLBRElement struct{ *BasicHTMLElement }
  1580. type HTMLBaseElement struct{ *BasicHTMLElement }
  1581. func (e *HTMLBaseElement) Href() string {
  1582. return e.Get("href").String()
  1583. }
  1584. func (e *HTMLBaseElement) Target() string {
  1585. return e.Get("target").String()
  1586. }
  1587. type HTMLBodyElement struct{ *BasicHTMLElement }
  1588. type HTMLButtonElement struct {
  1589. *BasicHTMLElement
  1590. AutoFocus bool `js:"autofocus"`
  1591. Disabled bool `js:"disabled"`
  1592. FormAction string `js:"formAction"`
  1593. FormEncType string `js:"formEncType"`
  1594. FormMethod string `js:"formMethod"`
  1595. FormNoValidate bool `js:"formNoValidate"`
  1596. FormTarget string `js:"formTarget"`
  1597. Name string `js:"name"`
  1598. TabIndex int `js:"tabIndex"`
  1599. Type string `js:"type"`
  1600. ValidationMessage string `js:"validationMessage"`
  1601. Value string `js:"value"`
  1602. WillValidate bool `js:"willValidate"`
  1603. }
  1604. func (e *HTMLButtonElement) Form() *HTMLFormElement {
  1605. return getForm(e.Object)
  1606. }
  1607. func (e *HTMLButtonElement) Labels() []*HTMLLabelElement {
  1608. return getLabels(e.Object)
  1609. }
  1610. func (e *HTMLButtonElement) Validity() *ValidityState {
  1611. // TODO replace with a field once GopherJS supports that
  1612. return &ValidityState{Object: e.Get("validity")}
  1613. }
  1614. func (e *HTMLButtonElement) CheckValidity() bool {
  1615. return e.Call("checkValidity").Bool()
  1616. }
  1617. func (e *HTMLButtonElement) SetCustomValidity(s string) {
  1618. e.Call("setCustomValidity", s)
  1619. }
  1620. type HTMLCanvasElement struct {
  1621. *BasicHTMLElement
  1622. Height int `js:"height"`
  1623. Width int `js:"width"`
  1624. }
  1625. type CanvasRenderingContext2D struct {
  1626. *js.Object
  1627. // Colors, Styles, and Shadows
  1628. FillStyle string `js:"fillStyle"`
  1629. StrokeStyle string `js:"strokeStyle"`
  1630. ShadowColor string `js:"shadowColor"`
  1631. ShadowBlur int `js:"shadowBlur"`
  1632. ShadowOffsetX int `js:"shadowOffsetX"`
  1633. ShadowOffsetY int `js:"shadowOffsetY"`
  1634. // Line Styles
  1635. LineCap string `js:"lineCap"`
  1636. LineJoin string `js:"lineJoin"`
  1637. LineWidth int `js:"lineWidth"`
  1638. MiterLimit int `js:"miterLimit"`
  1639. // Text
  1640. Font string `js:"font"`
  1641. TextAlign string `js:"textAlign"`
  1642. TextBaseline string `js:"textBaseline"`
  1643. // Compositing
  1644. GlobalAlpha float64 `js:"globalAlpha"`
  1645. GlobalCompositeOperation string `js:"globalCompositeOperation"`
  1646. }
  1647. type ImageData struct {
  1648. *js.Object
  1649. Width int `js:"width"`
  1650. Height int `js:"height"`
  1651. Data *js.Object `js:"data"`
  1652. }
  1653. func (m *ImageData) ColorModel() color.Model { return color.NRGBAModel }
  1654. func (m *ImageData) Bounds() image.Rectangle {
  1655. return image.Rect(0, 0, m.Width, m.Height)
  1656. }
  1657. func (m *ImageData) At(x, y int) color.Color {
  1658. return m.NRGBAAt(x, y)
  1659. }
  1660. func (m *ImageData) NRGBAAt(x, y int) color.NRGBA {
  1661. if x < 0 || x >= m.Width ||
  1662. y < 0 || y >= m.Height {
  1663. return color.NRGBA{}
  1664. }
  1665. i := (y*m.Width + x) * 4
  1666. return color.NRGBA{
  1667. R: uint8(m.Data.Index(i + 0).Int()),
  1668. G: uint8(m.Data.Index(i + 1).Int()),
  1669. B: uint8(m.Data.Index(i + 2).Int()),
  1670. A: uint8(m.Data.Index(i + 3).Int()),
  1671. }
  1672. }
  1673. func (m *ImageData) Set(x, y int, c color.Color) {
  1674. if x < 0 || x >= m.Width ||
  1675. y < 0 || y >= m.Height {
  1676. return
  1677. }
  1678. c1 := color.NRGBAModel.Convert(c).(color.NRGBA)
  1679. i := (y*m.Width + x) * 4
  1680. m.Data.SetIndex(i+0, c1.R)
  1681. m.Data.SetIndex(i+1, c1.G)
  1682. m.Data.SetIndex(i+2, c1.B)
  1683. m.Data.SetIndex(i+3, c1.A)
  1684. }
  1685. func (m *ImageData) SetNRGBA(x, y int, c color.NRGBA) {
  1686. if x < 0 || x >= m.Width ||
  1687. y < 0 || y >= m.Height {
  1688. return
  1689. }
  1690. i := (y*m.Width + x) * 4
  1691. m.Data.SetIndex(i+0, c.R)
  1692. m.Data.SetIndex(i+1, c.G)
  1693. m.Data.SetIndex(i+2, c.B)
  1694. m.Data.SetIndex(i+3, c.A)
  1695. }
  1696. // CanvasGradient represents an opaque object describing a gradient.
  1697. // It is returned by the methods CanvasRenderingContext2D.CreateLinearGradient
  1698. // or CanvasRenderingContext2D.CreateRadialGradient.
  1699. //
  1700. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient.
  1701. type CanvasGradient struct {
  1702. *js.Object
  1703. }
  1704. // AddColorStop adds a new stop, defined by an offset and a color, to the gradient.
  1705. // It panics with *js.Error if the offset is not between 0 and 1, or if the color
  1706. // can't be parsed as a CSS <color>.
  1707. //
  1708. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient/addColorStop.
  1709. func (cg *CanvasGradient) AddColorStop(offset float64, color string) {
  1710. cg.Call("addColorStop", offset, color)
  1711. }
  1712. // CanvasPattern represents an opaque object describing a pattern.
  1713. // It is based on an image, a canvas or a video, created by the
  1714. // CanvasRenderingContext2D.CreatePattern method.
  1715. //
  1716. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasPattern.
  1717. type CanvasPattern struct {
  1718. *js.Object
  1719. }
  1720. type TextMetrics struct {
  1721. *js.Object
  1722. Width float64 `js:"width"`
  1723. ActualBoundingBoxLeft float64 `js:"actualBoundingBoxLeft"`
  1724. ActualBoundingBoxRight float64 `js:"actualBoundingBoxRight"`
  1725. FontBoundingBoxAscent float64 `js:"fontBoundingBoxAscent"`
  1726. FontBoundingBoxDescent float64 `js:"fontBoundingBoxDescent"`
  1727. ActualBoundingBoxAscent float64 `js:"actualBoundingBoxAscent"`
  1728. ActualBoundingBoxDescent float64 `js:"actualBoundingBoxDescent"`
  1729. EmHeightAscent float64 `js:"emHeightAscent"`
  1730. EmHeightDescent float64 `js:"emHeightDescent"`
  1731. HangingBaseline float64 `js:"hangingBaseline"`
  1732. AlphabeticBaseline float64 `js:"alphabeticBaseline"`
  1733. IdeographicBaseline float64 `js:"ideographicBaseline"`
  1734. }
  1735. // Creating canvas 2d context
  1736. func (e *HTMLCanvasElement) GetContext2d() *CanvasRenderingContext2D {
  1737. ctx := e.GetContext("2d")
  1738. return &CanvasRenderingContext2D{Object: ctx}
  1739. }
  1740. func (e *HTMLCanvasElement) GetContext(param string) *js.Object {
  1741. return e.Call("getContext", param)
  1742. }
  1743. // Drawing Rectangles
  1744. func (ctx *CanvasRenderingContext2D) ClearRect(x, y, width, height float64) {
  1745. ctx.Call("clearRect", x, y, width, height)
  1746. }
  1747. func (ctx *CanvasRenderingContext2D) FillRect(x, y, width, height float64) {
  1748. ctx.Call("fillRect", x, y, width, height)
  1749. }
  1750. func (ctx *CanvasRenderingContext2D) StrokeRect(x, y, width, height float64) {
  1751. ctx.Call("strokeRect", x, y, width, height)
  1752. }
  1753. // Drawing Text
  1754. // FillText fills a given text at the given (x, y) position.
  1755. // If the optional maxWidth parameter is not -1,
  1756. // the text will be scaled to fit that width.
  1757. func (ctx *CanvasRenderingContext2D) FillText(text string, x, y, maxWidth float64) {
  1758. if maxWidth == -1 {
  1759. ctx.Call("fillText", text, x, y)
  1760. return
  1761. }
  1762. ctx.Call("fillText", text, x, y, maxWidth)
  1763. }
  1764. // StrokeText strokes a given text at the given (x, y) position.
  1765. // If the optional maxWidth parameter is not -1,
  1766. // the text will be scaled to fit that width.
  1767. func (ctx *CanvasRenderingContext2D) StrokeText(text string, x, y, maxWidth float64) {
  1768. if maxWidth == -1 {
  1769. ctx.Call("strokeText", text, x, y)
  1770. return
  1771. }
  1772. ctx.Call("strokeText", text, x, y, maxWidth)
  1773. }
  1774. func (ctx *CanvasRenderingContext2D) MeasureText(text string) *TextMetrics {
  1775. textMetrics := ctx.Call("measureText", text)
  1776. return &TextMetrics{Object: textMetrics}
  1777. }
  1778. // Line styles
  1779. func (ctx *CanvasRenderingContext2D) GetLineDash() []float64 {
  1780. var dashes []float64
  1781. for _, dash := range ctx.Call("getLineDash").Interface().([]interface{}) {
  1782. dashes = append(dashes, dash.(float64))
  1783. }
  1784. return dashes
  1785. }
  1786. func (ctx *CanvasRenderingContext2D) SetLineDash(dashes []float64) {
  1787. ctx.Call("setLineDash", dashes)
  1788. }
  1789. // Gradients and patterns
  1790. // CreateLinearGradient creates a linear gradient along the line given
  1791. // by the coordinates represented by the parameters.
  1792. //
  1793. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient.
  1794. func (ctx *CanvasRenderingContext2D) CreateLinearGradient(x0, y0, x1, y1 float64) *CanvasGradient {
  1795. return &CanvasGradient{Object: ctx.Call("createLinearGradient", x0, y0, x1, y1)}
  1796. }
  1797. // CreateRadialGradient creates a radial gradient given by the coordinates of the two circles
  1798. // represented by the parameters.
  1799. //
  1800. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createRadialGradient.
  1801. func (ctx *CanvasRenderingContext2D) CreateRadialGradient(x0, y0, r0, x1, y1, r1 float64) *CanvasGradient {
  1802. return &CanvasGradient{Object: ctx.Call("createRadialGradient", x0, y0, r0, x1, y1, r1)}
  1803. }
  1804. // CreatePattern creates a pattern using the specified image (a CanvasImageSource).
  1805. // It repeats the source in the directions specified by the repetition argument.
  1806. //
  1807. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createPattern.
  1808. func (ctx *CanvasRenderingContext2D) CreatePattern(image Element, repetition string) *CanvasPattern {
  1809. return &CanvasPattern{Object: ctx.Call("createPattern", image, repetition)}
  1810. }
  1811. // Paths
  1812. func (ctx *CanvasRenderingContext2D) BeginPath() {
  1813. ctx.Call("beginPath")
  1814. }
  1815. func (ctx *CanvasRenderingContext2D) ClosePath() {
  1816. ctx.Call("closePath")
  1817. }
  1818. func (ctx *CanvasRenderingContext2D) MoveTo(x, y float64) {
  1819. ctx.Call("moveTo", x, y)
  1820. }
  1821. func (ctx *CanvasRenderingContext2D) LineTo(x, y float64) {
  1822. ctx.Call("lineTo", x, y)
  1823. }
  1824. func (ctx *CanvasRenderingContext2D) BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float64) {
  1825. ctx.Call("bezierCurveTo", cp1x, cp1y, cp2x, cp2y, x, y)
  1826. }
  1827. func (ctx *CanvasRenderingContext2D) QuadraticCurveTo(cpx, cpy, x, y float64) {
  1828. ctx.Call("quadraticCurveTo", cpx, cpy, x, y)
  1829. }
  1830. func (ctx *CanvasRenderingContext2D) Arc(x, y, r, sAngle, eAngle float64, counterclockwise bool) {
  1831. ctx.Call("arc", x, y, r, sAngle, eAngle, counterclockwise)
  1832. }
  1833. func (ctx *CanvasRenderingContext2D) ArcTo(x1, y1, x2, y2, r float64) {
  1834. ctx.Call("arcTo", x1, y1, x2, y2, r)
  1835. }
  1836. func (ctx *CanvasRenderingContext2D) Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle float64, anticlockwise bool) {
  1837. ctx.Call("ellipse", x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
  1838. }
  1839. func (ctx *CanvasRenderingContext2D) Rect(x, y, width, height float64) {
  1840. ctx.Call("rect", x, y, width, height)
  1841. }
  1842. // Drawing paths
  1843. func (ctx *CanvasRenderingContext2D) Fill() {
  1844. ctx.Call("fill")
  1845. }
  1846. func (ctx *CanvasRenderingContext2D) Stroke() {
  1847. ctx.Call("stroke")
  1848. }
  1849. func (ctx *CanvasRenderingContext2D) DrawFocusIfNeeded(element HTMLElement, path *js.Object) {
  1850. ctx.Call("drawFocusIfNeeded", element, path)
  1851. }
  1852. func (ctx *CanvasRenderingContext2D) ScrollPathIntoView(path *js.Object) {
  1853. ctx.Call("scrollPathIntoView", path)
  1854. }
  1855. func (ctx *CanvasRenderingContext2D) Clip() {
  1856. ctx.Call("clip")
  1857. }
  1858. func (ctx *CanvasRenderingContext2D) IsPointInPath(x, y float64) bool {
  1859. return ctx.Call("isPointInPath", x, y).Bool()
  1860. }
  1861. func (ctx *CanvasRenderingContext2D) IsPointInStroke(path *js.Object, x, y float64) bool {
  1862. return ctx.Call("isPointInStroke", path, x, y).Bool()
  1863. }
  1864. // Transformations
  1865. func (ctx *CanvasRenderingContext2D) Rotate(angle float64) {
  1866. ctx.Call("rotate", angle)
  1867. }
  1868. func (ctx *CanvasRenderingContext2D) Scale(scaleWidth, scaleHeight float64) {
  1869. ctx.Call("scale", scaleWidth, scaleHeight)
  1870. }
  1871. func (ctx *CanvasRenderingContext2D) Translate(x, y float64) {
  1872. ctx.Call("translate", x, y)
  1873. }
  1874. func (ctx *CanvasRenderingContext2D) Transform(a, b, c, d, e, f float64) {
  1875. ctx.Call("transform", a, b, c, d, e, f)
  1876. }
  1877. func (ctx *CanvasRenderingContext2D) SetTransform(a, b, c, d, e, f float64) {
  1878. ctx.Call("setTransform", a, b, c, d, e, f)
  1879. }
  1880. func (ctx *CanvasRenderingContext2D) ResetTransform() {
  1881. ctx.Call("resetTransform")
  1882. }
  1883. // Drawing images
  1884. func (ctx *CanvasRenderingContext2D) DrawImage(image Element, dx, dy float64) {
  1885. ctx.Call("drawImage", image, dx, dy)
  1886. }
  1887. func (ctx *CanvasRenderingContext2D) DrawImageWithDst(image Element, dx, dy, dWidth, dHeight float64) {
  1888. ctx.Call("drawImage", image, dx, dy, dWidth, dHeight)
  1889. }
  1890. func (ctx *CanvasRenderingContext2D) DrawImageWithSrcAndDst(image Element, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight float64) {
  1891. ctx.Call("drawImage", image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
  1892. }
  1893. // Pixel manipulation
  1894. func (ctx *CanvasRenderingContext2D) CreateImageData(width, height int) *ImageData {
  1895. return &ImageData{Object: ctx.Call("createImageData", width, height)}
  1896. }
  1897. func (ctx *CanvasRenderingContext2D) GetImageData(sx, sy, sw, sh int) *ImageData {
  1898. return &ImageData{Object: ctx.Call("getImageData", sx, sy, sw, sh)}
  1899. }
  1900. func (ctx *CanvasRenderingContext2D) PutImageData(imageData *ImageData, dx, dy float64) {
  1901. ctx.Call("putImageData", imageData, dx, dy)
  1902. }
  1903. func (ctx *CanvasRenderingContext2D) PutImageDataDirty(imageData *ImageData, dx, dy float64, dirtyX, dirtyY, dirtyWidth, dirtyHeight int) {
  1904. ctx.Call("putImageData", imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight)
  1905. }
  1906. // State
  1907. func (ctx *CanvasRenderingContext2D) Save() {
  1908. ctx.Call("save")
  1909. }
  1910. func (ctx *CanvasRenderingContext2D) Restore() {
  1911. ctx.Call("restore")
  1912. }
  1913. // TODO Hit regions:
  1914. // addHitRegion
  1915. // removeHitRegion
  1916. // clearHitRegions
  1917. type HTMLDListElement struct{ *BasicHTMLElement }
  1918. type HTMLDataElement struct {
  1919. *BasicHTMLElement
  1920. Value string `js:"value"`
  1921. }
  1922. type HTMLDataListElement struct{ *BasicHTMLElement }
  1923. func (e *HTMLDataListElement) Options() []*HTMLOptionElement {
  1924. return getOptions(e.Object, "options")
  1925. }
  1926. type HTMLDirectoryElement struct{ *BasicHTMLElement }
  1927. type HTMLDivElement struct{ *BasicHTMLElement }
  1928. type HTMLEmbedElement struct {
  1929. *BasicHTMLElement
  1930. Src string `js:"src"`
  1931. Type string `js:"type"`
  1932. Width string `js:"width"`
  1933. }
  1934. type HTMLFieldSetElement struct {
  1935. *BasicHTMLElement
  1936. Disabled bool `js:"disabled"`
  1937. Name string `js:"name"`
  1938. Type string `js:"type"`
  1939. ValidationMessage string `js:"validationMessage"`
  1940. WillValidate bool `js:"willValidate"`
  1941. }
  1942. func (e *HTMLFieldSetElement) Elements() []HTMLElement {
  1943. return nodeListToHTMLElements(e.Get("elements"))
  1944. }
  1945. func (e *HTMLFieldSetElement) Form() *HTMLFormElement {
  1946. return getForm(e.Object)
  1947. }
  1948. func (e *HTMLFieldSetElement) Validity() *ValidityState {
  1949. // TODO replace with a field once GopherJS supports that
  1950. return &ValidityState{Object: e.Get("validity")}
  1951. }
  1952. func (e *HTMLFieldSetElement) CheckValidity() bool {
  1953. return e.Call("checkValidity").Bool()
  1954. }
  1955. func (e *HTMLFieldSetElement) SetCustomValidity(s string) {
  1956. e.Call("setCustomValidity", s)
  1957. }
  1958. type HTMLFontElement struct{ *BasicHTMLElement }
  1959. type HTMLFormElement struct {
  1960. *BasicHTMLElement
  1961. AcceptCharset string `js:"acceptCharset"`
  1962. Action string `js:"action"`
  1963. Autocomplete string `js:"autocomplete"`
  1964. Encoding string `js:"encoding"`
  1965. Enctype string `js:"enctype"`
  1966. Length int `js:"length"`
  1967. Method string `js:"method"`
  1968. Name string `js:"name"`
  1969. NoValidate bool `js:"noValidate"`
  1970. Target string `js:"target"`
  1971. }
  1972. func (e *HTMLFormElement) Elements() []HTMLElement {
  1973. return nodeListToHTMLElements(e.Get("elements"))
  1974. }
  1975. func (e *HTMLFormElement) CheckValidity() bool {
  1976. return e.Call("checkValidity").Bool()
  1977. }
  1978. func (e *HTMLFormElement) Submit() {
  1979. e.Call("submit")
  1980. }
  1981. func (e *HTMLFormElement) Reset() {
  1982. e.Call("reset")
  1983. }
  1984. func (e *HTMLFormElement) Item(index int) HTMLElement {
  1985. return wrapHTMLElement(e.Call("item", index))
  1986. }
  1987. func (e *HTMLFormElement) NamedItem(name string) HTMLElement {
  1988. return wrapHTMLElement(e.Call("namedItem", name))
  1989. }
  1990. type HTMLFrameElement struct{ *BasicHTMLElement }
  1991. type HTMLFrameSetElement struct{ *BasicHTMLElement }
  1992. type HTMLHRElement struct{ *BasicHTMLElement }
  1993. type HTMLHeadElement struct{ *BasicHTMLElement }
  1994. type HTMLHeadingElement struct{ *BasicHTMLElement }
  1995. type HTMLHtmlElement struct{ *BasicHTMLElement }
  1996. type HTMLIFrameElement struct {
  1997. *BasicHTMLElement
  1998. Width string `js:"width"`
  1999. Height string `js:"height"`
  2000. Name string `js:"name"`
  2001. Src string `js:"src"`
  2002. SrcDoc string `js:"srcdoc"`
  2003. Seamless bool `js:"seamless"`
  2004. // TODO sandbox attribute
  2005. }
  2006. func (e *HTMLIFrameElement) ContentDocument() Document {
  2007. return wrapDocument(e.Get("contentDocument"))
  2008. }
  2009. func (e *HTMLIFrameElement) ContentWindow() Window {
  2010. return &window{e.Get("contentWindow")}
  2011. }
  2012. type HTMLImageElement struct {
  2013. *BasicHTMLElement
  2014. Complete bool `js:"complete"`
  2015. CrossOrigin string `js:"crossOrigin"`
  2016. Height int `js:"height"`
  2017. IsMap bool `js:"isMap"`
  2018. NaturalHeight int `js:"naturalHeight"`
  2019. NaturalWidth int `js:"naturalWidth"`
  2020. Src string `js:"src"`
  2021. UseMap string `js:"useMap"`
  2022. Width int `js:"width"`
  2023. // TODO constructor
  2024. }
  2025. type HTMLInputElement struct {
  2026. *BasicHTMLElement
  2027. Accept string `js:"accept"`
  2028. Alt string `js:"alt"`
  2029. Autocomplete string `js:"autocomplete"`
  2030. Autofocus bool `js:"autofocus"`
  2031. Checked bool `js:"checked"`
  2032. DefaultChecked bool `js:"defaultChecked"`
  2033. DefaultValue string `js:"defaultValue"`
  2034. DirName string `js:"dirName"`
  2035. Disabled bool `js:"disabled"`
  2036. FormAction string `js:"formAction"`
  2037. FormEncType string `js:"formEncType"`
  2038. FormMethod string `js:"formMethod"`
  2039. FormNoValidate bool `js:"formNoValidate"`
  2040. FormTarget string `js:"formTarget"`
  2041. Height string `js:"height"`
  2042. Indeterminate bool `js:"indeterminate"`
  2043. Max string `js:"max"`
  2044. MaxLength int `js:"maxLength"`
  2045. Min string `js:"min"`
  2046. Multiple bool `js:"multiple"`
  2047. Name string `js:"name"`
  2048. Pattern string `js:"pattern"`
  2049. Placeholder string `js:"placeholder"`
  2050. ReadOnly bool `js:"readOnly"`
  2051. Required bool `js:"required"`
  2052. SelectionDirection string `js:"selectionDirection"`
  2053. SelectionEnd int `js:"selectionEnd"`
  2054. SelectionStart int `js:"selectionStart"`
  2055. Size int `js:"size"`
  2056. Src string `js:"src"`
  2057. Step string `js:"step"`
  2058. TabIndex int `js:"tabIndex"`
  2059. Type string `js:"type"`
  2060. ValidationMessage string `js:"validationMessage"`
  2061. Value string `js:"value"`
  2062. ValueAsDate time.Time `js:"valueAsDate"`
  2063. ValueAsNumber float64 `js:"valueAsNumber"`
  2064. Width string `js:"width"`
  2065. WillValidate bool `js:"willValidate"`
  2066. }
  2067. // File represents files as can be obtained from file choosers or drag
  2068. // and drop. The dom package does not define any methods on File nor
  2069. // does it provide access to the blob or a way to read it.
  2070. type File struct {
  2071. *js.Object
  2072. }
  2073. func (e *HTMLInputElement) Files() []*File {
  2074. files := e.Get("files")
  2075. out := make([]*File, files.Get("length").Int())
  2076. for i := range out {
  2077. out[i] = &File{files.Call("item", i)}
  2078. }
  2079. return out
  2080. }
  2081. func (e *HTMLInputElement) List() *HTMLDataListElement {
  2082. list := wrapHTMLElement(e.Get("list"))
  2083. if list == nil {
  2084. return nil
  2085. }
  2086. return list.(*HTMLDataListElement)
  2087. }
  2088. func (e *HTMLInputElement) Labels() []*HTMLLabelElement {
  2089. return getLabels(e.Object)
  2090. }
  2091. func (e *HTMLInputElement) Form() *HTMLFormElement {
  2092. return getForm(e.Object)
  2093. }
  2094. func (e *HTMLInputElement) Validity() *ValidityState {
  2095. // TODO replace with a field once GopherJS supports that
  2096. return &ValidityState{Object: e.Get("validity")}
  2097. }
  2098. func (e *HTMLInputElement) CheckValidity() bool {
  2099. return e.Call("checkValidity").Bool()
  2100. }
  2101. func (e *HTMLInputElement) SetCustomValidity(s string) {
  2102. e.Call("setCustomValidity", s)
  2103. }
  2104. func (e *HTMLInputElement) Select() {
  2105. e.Call("select")
  2106. }
  2107. func (e *HTMLInputElement) SetSelectionRange(start, end int, direction string) {
  2108. e.Call("setSelectionRange", start, end, direction)
  2109. }
  2110. func (e *HTMLInputElement) StepDown(n int) error {
  2111. return callRecover(e.Object, "stepDown", n)
  2112. }
  2113. func (e *HTMLInputElement) StepUp(n int) error {
  2114. return callRecover(e.Object, "stepUp", n)
  2115. }
  2116. type HTMLKeygenElement struct {
  2117. *BasicHTMLElement
  2118. Autofocus bool `js:"autofocus"`
  2119. Challenge string `js:"challenge"`
  2120. Disabled bool `js:"disabled"`
  2121. Keytype string `js:"keytype"`
  2122. Name string `js:"name"`
  2123. Type string `js:"type"`
  2124. ValidationMessage string `js:"validationMessage"`
  2125. WillValidate bool `js:"willValidate"`
  2126. }
  2127. func (e *HTMLKeygenElement) Form() *HTMLFormElement {
  2128. return getForm(e.Object)
  2129. }
  2130. func (e *HTMLKeygenElement) Labels() []*HTMLLabelElement {
  2131. return getLabels(e.Object)
  2132. }
  2133. func (e *HTMLKeygenElement) Validity() *ValidityState {
  2134. // TODO replace with a field once GopherJS supports that
  2135. return &ValidityState{Object: e.Get("validity")}
  2136. }
  2137. func (e *HTMLKeygenElement) CheckValidity() bool {
  2138. return e.Call("checkValidity").Bool()
  2139. }
  2140. func (e *HTMLKeygenElement) SetCustomValidity(s string) {
  2141. e.Call("setCustomValidity", s)
  2142. }
  2143. type HTMLLIElement struct {
  2144. *BasicHTMLElement
  2145. Value int `js:"value"`
  2146. }
  2147. type HTMLLabelElement struct {
  2148. *BasicHTMLElement
  2149. For string `js:"htmlFor"`
  2150. }
  2151. func (e *HTMLLabelElement) Control() HTMLElement {
  2152. return wrapHTMLElement(e.Get("control"))
  2153. }
  2154. func (e *HTMLLabelElement) Form() *HTMLFormElement {
  2155. return getForm(e.Object)
  2156. }
  2157. type HTMLLegendElement struct{ *BasicHTMLElement }
  2158. func (e *HTMLLegendElement) Form() *HTMLFormElement {
  2159. return getForm(e.Object)
  2160. }
  2161. type HTMLLinkElement struct {
  2162. *BasicHTMLElement
  2163. Disabled bool `js:"disabled"`
  2164. Href string `js:"href"`
  2165. HrefLang string `js:"hrefLang"`
  2166. Media string `js:"media"`
  2167. Type string `js:"type"`
  2168. }
  2169. func (e *HTMLLinkElement) Rel() *TokenList {
  2170. return &TokenList{dtl: e.Get("relList"), o: e.Object, sa: "rel"}
  2171. }
  2172. func (e *HTMLLinkElement) Sizes() *TokenList {
  2173. return &TokenList{dtl: e.Get("sizes"), o: e.Object}
  2174. }
  2175. func (e *HTMLLinkElement) Sheet() StyleSheet {
  2176. // FIXME implement
  2177. panic("not implemented")
  2178. }
  2179. type HTMLMapElement struct {
  2180. *BasicHTMLElement
  2181. Name string `js:"name"`
  2182. }
  2183. func (e *HTMLMapElement) Areas() []*HTMLAreaElement {
  2184. areas := nodeListToElements(e.Get("areas"))
  2185. out := make([]*HTMLAreaElement, len(areas))
  2186. for i, area := range areas {
  2187. out[i] = area.(*HTMLAreaElement)
  2188. }
  2189. return out
  2190. }
  2191. func (e *HTMLMapElement) Images() []HTMLElement {
  2192. return nodeListToHTMLElements(e.Get("areas"))
  2193. }
  2194. type HTMLMediaElement struct {
  2195. *BasicHTMLElement
  2196. Paused bool `js:"paused"`
  2197. }
  2198. func (e *HTMLMediaElement) Play() {
  2199. e.Call("play")
  2200. }
  2201. func (e *HTMLMediaElement) Pause() {
  2202. e.Call("pause")
  2203. }
  2204. type HTMLMenuElement struct{ *BasicHTMLElement }
  2205. type HTMLMetaElement struct {
  2206. *BasicHTMLElement
  2207. Content string `js:"content"`
  2208. HTTPEquiv string `js:"httpEquiv"`
  2209. Name string `js:"name"`
  2210. }
  2211. type HTMLMeterElement struct {
  2212. *BasicHTMLElement
  2213. High float64 `js:"high"`
  2214. Low float64 `js:"low"`
  2215. Max float64 `js:"max"`
  2216. Min float64 `js:"min"`
  2217. Optimum float64 `js:"optimum"`
  2218. }
  2219. func (e HTMLMeterElement) Labels() []*HTMLLabelElement {
  2220. return getLabels(e.Object)
  2221. }
  2222. type HTMLModElement struct {
  2223. *BasicHTMLElement
  2224. Cite string `js:"cite"`
  2225. DateTime string `js:"dateTime"`
  2226. }
  2227. type HTMLOListElement struct {
  2228. *BasicHTMLElement
  2229. Reversed bool `js:"reversed"`
  2230. Start int `js:"start"`
  2231. Type string `js:"type"`
  2232. }
  2233. type HTMLObjectElement struct {
  2234. *BasicHTMLElement
  2235. Data string `js:"data"`
  2236. Height string `js:"height"`
  2237. Name string `js:"name"`
  2238. TabIndex int `js:"tabIndex"`
  2239. Type string `js:"type"`
  2240. TypeMustMatch bool `js:"typeMustMatch"`
  2241. UseMap string `js:"useMap"`
  2242. ValidationMessage string `js:"validationMessage"`
  2243. With string `js:"with"`
  2244. WillValidate bool `js:"willValidate"`
  2245. }
  2246. func (e *HTMLObjectElement) Form() *HTMLFormElement {
  2247. return getForm(e.Object)
  2248. }
  2249. func (e *HTMLObjectElement) ContentDocument() Document {
  2250. return wrapDocument(e.Get("contentDocument"))
  2251. }
  2252. func (e *HTMLObjectElement) ContentWindow() Window {
  2253. return &window{e.Get("contentWindow")}
  2254. }
  2255. func (e *HTMLObjectElement) Validity() *ValidityState {
  2256. // TODO replace with a field once GopherJS supports that
  2257. return &ValidityState{Object: e.Get("validity")}
  2258. }
  2259. func (e *HTMLObjectElement) CheckValidity() bool {
  2260. return e.Call("checkValidity").Bool()
  2261. }
  2262. func (e *HTMLObjectElement) SetCustomValidity(s string) {
  2263. e.Call("setCustomValidity", s)
  2264. }
  2265. type HTMLOptGroupElement struct {
  2266. *BasicHTMLElement
  2267. Disabled bool `js:"disabled"`
  2268. Label string `js:"label"`
  2269. }
  2270. type HTMLOptionElement struct {
  2271. *BasicHTMLElement
  2272. DefaultSelected bool `js:"defaultSelected"`
  2273. Disabled bool `js:"disabled"`
  2274. Index int `js:"index"`
  2275. Label string `js:"label"`
  2276. Selected bool `js:"selected"`
  2277. Text string `js:"text"`
  2278. Value string `js:"value"`
  2279. }
  2280. func (e *HTMLOptionElement) Form() *HTMLFormElement {
  2281. return getForm(e.Object)
  2282. }
  2283. type HTMLOutputElement struct {
  2284. *BasicHTMLElement
  2285. DefaultValue string `js:"defaultValue"`
  2286. Name string `js:"name"`
  2287. Type string `js:"type"`
  2288. ValidationMessage string `js:"validationMessage"`
  2289. Value string `js:"value"`
  2290. WillValidate bool `js:"willValidate"`
  2291. }
  2292. func (e *HTMLOutputElement) Form() *HTMLFormElement {
  2293. return getForm(e.Object)
  2294. }
  2295. func (e *HTMLOutputElement) Labels() []*HTMLLabelElement {
  2296. return getLabels(e.Object)
  2297. }
  2298. func (e *HTMLOutputElement) Validity() *ValidityState {
  2299. // TODO replace with a field once GopherJS supports that
  2300. return &ValidityState{Object: e.Get("validity")}
  2301. }
  2302. func (e *HTMLOutputElement) For() *TokenList {
  2303. return &TokenList{dtl: e.Get("htmlFor"), o: e.Object}
  2304. }
  2305. func (e *HTMLOutputElement) CheckValidity() bool {
  2306. return e.Call("checkValidity").Bool()
  2307. }
  2308. func (e *HTMLOutputElement) SetCustomValidity(s string) {
  2309. e.Call("setCustomValidity", s)
  2310. }
  2311. type HTMLParagraphElement struct{ *BasicHTMLElement }
  2312. type HTMLParamElement struct {
  2313. *BasicHTMLElement
  2314. Name string `js:"name"`
  2315. Value string `js:"value"`
  2316. }
  2317. type HTMLPreElement struct{ *BasicHTMLElement }
  2318. type HTMLProgressElement struct {
  2319. *BasicHTMLElement
  2320. Max float64 `js:"max"`
  2321. Position float64 `js:"position"`
  2322. Value float64 `js:"value"`
  2323. }
  2324. func (e HTMLProgressElement) Labels() []*HTMLLabelElement {
  2325. return getLabels(e.Object)
  2326. }
  2327. type HTMLQuoteElement struct {
  2328. *BasicHTMLElement
  2329. Cite string `js:"cite"`
  2330. }
  2331. type HTMLScriptElement struct {
  2332. *BasicHTMLElement
  2333. Type string `js:"type"`
  2334. Src string `js:"src"`
  2335. Charset string `js:"charset"`
  2336. Async bool `js:"async"`
  2337. Defer bool `js:"defer"`
  2338. Text string `js:"text"`
  2339. }
  2340. type HTMLSelectElement struct {
  2341. *BasicHTMLElement
  2342. Autofocus bool `js:"autofocus"`
  2343. Disabled bool `js:"disabled"`
  2344. Length int `js:"length"`
  2345. Multiple bool `js:"multiple"`
  2346. Name string `js:"name"`
  2347. Required bool `js:"required"`
  2348. SelectedIndex int `js:"selectedIndex"`
  2349. Size int `js:"size"`
  2350. Type string `js:"type"`
  2351. ValidationMessage string `js:"validationMessage"`
  2352. Value string `js:"value"`
  2353. WillValidate bool `js:"willValidate"`
  2354. }
  2355. func (e *HTMLSelectElement) Labels() []*HTMLLabelElement {
  2356. return getLabels(e.Object)
  2357. }
  2358. func (e *HTMLSelectElement) Form() *HTMLFormElement {
  2359. return getForm(e.Object)
  2360. }
  2361. func (e *HTMLSelectElement) Options() []*HTMLOptionElement {
  2362. return getOptions(e.Object, "options")
  2363. }
  2364. func (e *HTMLSelectElement) SelectedOptions() []*HTMLOptionElement {
  2365. return getOptions(e.Object, "selectedOptions")
  2366. }
  2367. func (e *HTMLSelectElement) Item(index int) *HTMLOptionElement {
  2368. el := wrapHTMLElement(e.Call("item", index))
  2369. if el == nil {
  2370. return nil
  2371. }
  2372. return el.(*HTMLOptionElement)
  2373. }
  2374. func (e *HTMLSelectElement) NamedItem(name string) *HTMLOptionElement {
  2375. el := wrapHTMLElement(e.Call("namedItem", name))
  2376. if el == nil {
  2377. return nil
  2378. }
  2379. return el.(*HTMLOptionElement)
  2380. }
  2381. // TODO(dominikh): Not implementing Add or Remove for now. For one,
  2382. // Add with "before" behaves weird when dealing with optgroups. Also,
  2383. // there's already InsertBefore and RemoveChild which can be used
  2384. // instead.
  2385. func (e *HTMLSelectElement) Validity() *ValidityState {
  2386. return &ValidityState{Object: e.Get("validity")}
  2387. }
  2388. func (e *HTMLSelectElement) CheckValidity() bool {
  2389. return e.Call("checkValidity").Bool()
  2390. }
  2391. func (e *HTMLSelectElement) SetCustomValidity(s string) {
  2392. e.Call("setCustomValidity", s)
  2393. }
  2394. type HTMLSourceElement struct {
  2395. *BasicHTMLElement
  2396. Media string `js:"media"`
  2397. Src string `js:"src"`
  2398. Type string `js:"type"`
  2399. }
  2400. type HTMLSpanElement struct{ *BasicHTMLElement }
  2401. type HTMLStyleElement struct{ *BasicHTMLElement }
  2402. type HTMLTableCaptionElement struct{ *BasicHTMLElement }
  2403. type HTMLTableCellElement struct {
  2404. *BasicHTMLElement
  2405. ColSpan int `js:"colSpan"`
  2406. RowSpan int `js:"rowSpan"`
  2407. CellIndex int `js:"cellIndex"`
  2408. // TODO headers
  2409. }
  2410. type HTMLTableColElement struct {
  2411. *BasicHTMLElement
  2412. Span int `js:"span"`
  2413. }
  2414. type HTMLTableDataCellElement struct{ *BasicHTMLElement }
  2415. type HTMLTableElement struct{ *BasicHTMLElement }
  2416. type HTMLTableHeaderCellElement struct {
  2417. *BasicHTMLElement
  2418. Abbr string `js:"abbr"`
  2419. Scope string `js:"scope"`
  2420. }
  2421. type HTMLTableRowElement struct {
  2422. *BasicHTMLElement
  2423. RowIndex int `js:"rowIndex"`
  2424. SectionRowIndex int `js:"sectionRowIndex"`
  2425. }
  2426. func (e *HTMLTableRowElement) Cells() []*HTMLTableCellElement {
  2427. cells := nodeListToElements(e.Get("cells"))
  2428. out := make([]*HTMLTableCellElement, len(cells))
  2429. for i, cell := range cells {
  2430. out[i] = cell.(*HTMLTableCellElement)
  2431. }
  2432. return out
  2433. }
  2434. func (e *HTMLTableRowElement) InsertCell(index int) *HTMLTableCellElement {
  2435. return wrapHTMLElement(e.Call("insertCell", index)).(*HTMLTableCellElement)
  2436. }
  2437. func (e *HTMLTableRowElement) DeleteCell(index int) {
  2438. // FIXME exception handling/check that index is in bounds
  2439. e.Call("deleteCell", index)
  2440. }
  2441. type HTMLTableSectionElement struct{ *BasicHTMLElement }
  2442. func (e *HTMLTableSectionElement) Rows() []*HTMLTableRowElement {
  2443. rows := nodeListToElements(e.Get("rows"))
  2444. out := make([]*HTMLTableRowElement, len(rows))
  2445. for i, row := range rows {
  2446. out[i] = row.(*HTMLTableRowElement)
  2447. }
  2448. return out
  2449. }
  2450. func (e *HTMLTableSectionElement) DeleteRow(index int) {
  2451. // FIXME exception handling/check that index is in bounds
  2452. e.Call("deleteRow", index)
  2453. }
  2454. func (e *HTMLTableSectionElement) InsertRow(index int) *HTMLTableRowElement {
  2455. return wrapHTMLElement(e.Call("insertRow", index)).(*HTMLTableRowElement)
  2456. }
  2457. type HTMLTemplateElement struct{ *BasicHTMLElement }
  2458. func (e *HTMLTemplateElement) Content() DocumentFragment {
  2459. return wrapDocumentFragment(e.Get("content"))
  2460. }
  2461. type HTMLTextAreaElement struct {
  2462. *BasicHTMLElement
  2463. Autocomplete string `js:"autocomplete"`
  2464. Autofocus bool `js:"autofocus"`
  2465. Cols int `js:"cols"`
  2466. DefaultValue string `js:"defaultValue"`
  2467. DirName string `js:"dirName"`
  2468. Disabled bool `js:"disabled"`
  2469. MaxLength int `js:"maxLength"`
  2470. Name string `js:"name"`
  2471. Placeholder string `js:"placeholder"`
  2472. ReadOnly bool `js:"readOnly"`
  2473. Required bool `js:"required"`
  2474. Rows int `js:"rows"`
  2475. SelectionDirection string `js:"selectionDirection"`
  2476. SelectionStart int `js:"selectionStart"`
  2477. SelectionEnd int `js:"selectionEnd"`
  2478. TabIndex int `js:"tabIndex"`
  2479. TextLength int `js:"textLength"`
  2480. Type string `js:"type"`
  2481. ValidationMessage string `js:"validationMessage"`
  2482. Value string `js:"value"`
  2483. WillValidate bool `js:"willValidate"`
  2484. Wrap string `js:"wrap"`
  2485. }
  2486. func (e *HTMLTextAreaElement) Form() *HTMLFormElement {
  2487. return getForm(e.Object)
  2488. }
  2489. func (e *HTMLTextAreaElement) Labels() []*HTMLLabelElement {
  2490. return getLabels(e.Object)
  2491. }
  2492. func (e *HTMLTextAreaElement) Validity() *ValidityState {
  2493. // TODO replace with a field once GopherJS supports that
  2494. return &ValidityState{Object: e.Get("validity")}
  2495. }
  2496. func (e *HTMLTextAreaElement) CheckValidity() bool {
  2497. return e.Call("checkValidity").Bool()
  2498. }
  2499. func (e *HTMLTextAreaElement) SetCustomValidity(s string) {
  2500. e.Call("setCustomValidity", s)
  2501. }
  2502. func (e *HTMLTextAreaElement) Select() {
  2503. e.Call("select")
  2504. }
  2505. func (e *HTMLTextAreaElement) SetSelectionRange(start, end int, direction string) {
  2506. e.Call("setSelectionRange", start, end, direction)
  2507. }
  2508. type HTMLTimeElement struct {
  2509. *BasicHTMLElement
  2510. DateTime string `js:"dateTime"`
  2511. }
  2512. type HTMLTitleElement struct {
  2513. *BasicHTMLElement
  2514. Text string `js:"text"`
  2515. }
  2516. // TextTrack represents text track data for <track> elements. It does
  2517. // not currently provide any methods or attributes and it hasn't been
  2518. // decided yet whether they will be added to this package or a
  2519. // separate package.
  2520. type TextTrack struct{ *js.Object }
  2521. type HTMLTrackElement struct {
  2522. *BasicHTMLElement
  2523. Kind string `js:"kind"`
  2524. Src string `js:"src"`
  2525. Srclang string `js:"srclang"`
  2526. Label string `js:"label"`
  2527. Default bool `js:"default"`
  2528. ReadyState int `js:"readyState"`
  2529. }
  2530. func (e *HTMLTrackElement) Track() *TextTrack {
  2531. return &TextTrack{e.Get("track")}
  2532. }
  2533. type HTMLUListElement struct{ *BasicHTMLElement }
  2534. type HTMLUnknownElement struct{ *BasicHTMLElement }
  2535. type HTMLVideoElement struct{ *HTMLMediaElement }
  2536. type ValidityState struct {
  2537. *js.Object
  2538. CustomError bool `js:"customError"`
  2539. PatternMismatch bool `js:"patternMismatch"`
  2540. RangeOverflow bool `js:"rangeOverflow"`
  2541. RangeUnderflow bool `js:"rangeUnderflow"`
  2542. StepMismatch bool `js:"stepMismatch"`
  2543. TooLong bool `js:"tooLong"`
  2544. TypeMismatch bool `js:"typeMismatch"`
  2545. Valid bool `js:"valid"`
  2546. ValueMissing bool `js:"valueMissing"`
  2547. }
  2548. type CSSStyleDeclaration struct{ *js.Object }
  2549. func (css *CSSStyleDeclaration) ToMap() map[string]string {
  2550. m := make(map[string]string)
  2551. N := css.Get("length").Int()
  2552. for i := 0; i < N; i++ {
  2553. name := css.Call("item", i).String()
  2554. value := css.Call("getPropertyValue", name).String()
  2555. m[name] = value
  2556. }
  2557. return m
  2558. }
  2559. func (css *CSSStyleDeclaration) RemoveProperty(name string) {
  2560. css.Call("removeProperty", name)
  2561. }
  2562. func (css *CSSStyleDeclaration) GetPropertyValue(name string) string {
  2563. return toString(css.Call("getPropertyValue", name))
  2564. }
  2565. func (css *CSSStyleDeclaration) GetPropertyPriority(name string) string {
  2566. return toString(css.Call("getPropertyPriority", name))
  2567. }
  2568. func (css *CSSStyleDeclaration) SetProperty(name, value, priority string) {
  2569. css.Call("setProperty", name, value, priority)
  2570. }
  2571. func (css *CSSStyleDeclaration) Index(idx int) string {
  2572. return css.Call("index", idx).String()
  2573. }
  2574. func (css *CSSStyleDeclaration) Length() int {
  2575. return css.Get("length").Int()
  2576. }
  2577. type Text struct {
  2578. *BasicNode
  2579. }