cleanup karax project for public consumption
This commit is contained in:
parent
b22567d9e0
commit
b9aa077513
17 changed files with 577 additions and 20 deletions
564
src/dom.nim
Normal file
564
src/dom.nim
Normal file
|
|
@ -0,0 +1,564 @@
|
|||
#
|
||||
#
|
||||
# Nim's Runtime Library
|
||||
# (c) Copyright 2012 Andreas Rumpf
|
||||
#
|
||||
# See the file "copying.txt", included in this
|
||||
# distribution, for details about the copyright.
|
||||
#
|
||||
|
||||
## Declaration of the Document Object Model for the `JavaScript backend
|
||||
## <backends.html#the-javascript-target>`_.
|
||||
|
||||
when not defined(js) and not defined(Nimdoc):
|
||||
{.error: "This module only works on the JavaScript platform".}
|
||||
|
||||
type
|
||||
EventTarget* = ref EventTargetObj
|
||||
EventTargetObj {.importc.} = object of RootObj
|
||||
onabort*: proc (event: Event) {.nimcall.}
|
||||
onblur*: proc (event: Event) {.nimcall.}
|
||||
onchange*: proc (event: Event) {.nimcall.}
|
||||
onclick*: proc (event: Event) {.nimcall.}
|
||||
ondblclick*: proc (event: Event) {.nimcall.}
|
||||
onerror*: proc (event: Event) {.nimcall.}
|
||||
onfocus*: proc (event: Event) {.nimcall.}
|
||||
onkeydown*: proc (event: Event) {.nimcall.}
|
||||
onkeypress*: proc (event: Event) {.nimcall.}
|
||||
onkeyup*: proc (event: Event) {.nimcall.}
|
||||
onload*: proc (event: Event) {.nimcall.}
|
||||
onmousedown*: proc (event: Event) {.nimcall.}
|
||||
onmousemove*: proc (event: Event) {.nimcall.}
|
||||
onmouseout*: proc (event: Event) {.nimcall.}
|
||||
onmouseover*: proc (event: Event) {.nimcall.}
|
||||
onmouseup*: proc (event: Event) {.nimcall.}
|
||||
onreset*: proc (event: Event) {.nimcall.}
|
||||
onselect*: proc (event: Event) {.nimcall.}
|
||||
onsubmit*: proc (event: Event) {.nimcall.}
|
||||
onunload*: proc (event: Event) {.nimcall.}
|
||||
|
||||
Window* = ref WindowObj
|
||||
WindowObj {.importc.} = object of EventTargetObj
|
||||
document*: Document
|
||||
event*: Event
|
||||
history*: History
|
||||
location*: Location
|
||||
closed*: bool
|
||||
defaultStatus*: cstring
|
||||
innerHeight*, innerWidth*: int
|
||||
locationbar*: ref TLocationBar
|
||||
menubar*: ref TMenuBar
|
||||
name*: cstring
|
||||
outerHeight*, outerWidth*: int
|
||||
pageXOffset*, pageYOffset*: int
|
||||
personalbar*: ref TPersonalBar
|
||||
scrollbars*: ref TScrollBars
|
||||
statusbar*: ref TStatusBar
|
||||
status*: cstring
|
||||
toolbar*: ref TToolBar
|
||||
frames*: seq[TFrame]
|
||||
|
||||
Frame* = ref FrameObj
|
||||
FrameObj {.importc.} = object of WindowObj
|
||||
|
||||
ClassList* = ref ClassListObj
|
||||
ClassListObj {.importc.} = object of RootObj
|
||||
|
||||
NodeType* = enum
|
||||
ElementNode = 1,
|
||||
AttributeNode,
|
||||
TextNode,
|
||||
CDATANode,
|
||||
EntityRefNode,
|
||||
EntityNode,
|
||||
ProcessingInstructionNode,
|
||||
CommentNode,
|
||||
DocumentNode,
|
||||
DocumentTypeNode,
|
||||
DocumentFragmentNode,
|
||||
NotationNode
|
||||
|
||||
Node* = ref NodeObj
|
||||
NodeObj {.importc.} = object of EventTargetObj
|
||||
attributes*: seq[Node]
|
||||
childNodes*: seq[Node]
|
||||
children*: seq[Node]
|
||||
data*: cstring
|
||||
firstChild*: Node
|
||||
lastChild*: Node
|
||||
nextSibling*: Node
|
||||
nodeName*: cstring
|
||||
nodeType*: NodeType
|
||||
nodeValue*: cstring
|
||||
parentNode*: Node
|
||||
previousSibling*: Node
|
||||
innerHTML*: cstring
|
||||
style*: Style
|
||||
|
||||
Document* = ref DocumentObj
|
||||
DocumentObj {.importc.} = object of NodeObj
|
||||
alinkColor*: cstring
|
||||
bgColor*: cstring
|
||||
body*: Element
|
||||
charset*: cstring
|
||||
cookie*: cstring
|
||||
defaultCharset*: cstring
|
||||
fgColor*: cstring
|
||||
head*: Element
|
||||
lastModified*: cstring
|
||||
linkColor*: cstring
|
||||
referrer*: cstring
|
||||
title*: cstring
|
||||
URL*: cstring
|
||||
vlinkColor*: cstring
|
||||
anchors*: seq[AnchorElement]
|
||||
forms*: seq[FormElement]
|
||||
images*: seq[ImageElement]
|
||||
applets*: seq[Element]
|
||||
embeds*: seq[EmbedElement]
|
||||
links*: seq[LinkElement]
|
||||
|
||||
Element* = ref ElementObj
|
||||
ElementObj {.importc.} = object of NodeObj
|
||||
classList*: Classlist
|
||||
checked*: bool
|
||||
defaultChecked*: bool
|
||||
defaultValue*: cstring
|
||||
disabled*: bool
|
||||
form*: FormElement
|
||||
name*: cstring
|
||||
readOnly*: bool
|
||||
options*: seq[OptionElement]
|
||||
|
||||
# https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
|
||||
HtmlElement* = ref object of Element
|
||||
contentEditable*: string
|
||||
isContentEditable*: bool
|
||||
dir*: string
|
||||
offsetHeight*: int
|
||||
offsetWidth*: int
|
||||
offsetLeft*: int
|
||||
offsetTop*: int
|
||||
|
||||
LinkElement* = ref LinkObj
|
||||
LinkObj {.importc.} = object of ElementObj
|
||||
target*: cstring
|
||||
text*: cstring
|
||||
x*: int
|
||||
y*: int
|
||||
|
||||
EmbedElement* = ref EmbedObj
|
||||
EmbedObj {.importc.} = object of ElementObj
|
||||
height*: int
|
||||
hspace*: int
|
||||
src*: cstring
|
||||
width*: int
|
||||
`type`*: cstring
|
||||
vspace*: int
|
||||
|
||||
AnchorElement* = ref AnchorObj
|
||||
AnchorObj {.importc.} = object of ElementObj
|
||||
text*: cstring
|
||||
x*, y*: int
|
||||
|
||||
OptionElement* = ref OptionObj
|
||||
OptionObj {.importc.} = object of ElementObj
|
||||
defaultSelected*: bool
|
||||
selected*: bool
|
||||
selectedIndex*: int
|
||||
text*: cstring
|
||||
value*: cstring
|
||||
|
||||
FormElement* = ref FormObj
|
||||
FormObj {.importc.} = object of ElementObj
|
||||
action*: cstring
|
||||
encoding*: cstring
|
||||
`method`*: cstring
|
||||
target*: cstring
|
||||
elements*: seq[Element]
|
||||
|
||||
ImageElement* = ref ImageObj
|
||||
ImageObj {.importc.} = object of ElementObj
|
||||
border*: int
|
||||
complete*: bool
|
||||
height*: int
|
||||
hspace*: int
|
||||
lowsrc*: cstring
|
||||
src*: cstring
|
||||
vspace*: int
|
||||
width*: int
|
||||
|
||||
Style = ref StyleObj
|
||||
StyleObj {.importc.} = object of RootObj
|
||||
background*: cstring
|
||||
backgroundAttachment*: cstring
|
||||
backgroundColor*: cstring
|
||||
backgroundImage*: cstring
|
||||
backgroundPosition*: cstring
|
||||
backgroundRepeat*: cstring
|
||||
border*: cstring
|
||||
borderBottom*: cstring
|
||||
borderBottomColor*: cstring
|
||||
borderBottomStyle*: cstring
|
||||
borderBottomWidth*: cstring
|
||||
borderColor*: cstring
|
||||
borderLeft*: cstring
|
||||
borderLeftColor*: cstring
|
||||
borderLeftStyle*: cstring
|
||||
borderLeftWidth*: cstring
|
||||
borderRight*: cstring
|
||||
borderRightColor*: cstring
|
||||
borderRightStyle*: cstring
|
||||
borderRightWidth*: cstring
|
||||
borderStyle*: cstring
|
||||
borderTop*: cstring
|
||||
borderTopColor*: cstring
|
||||
borderTopStyle*: cstring
|
||||
borderTopWidth*: cstring
|
||||
borderWidth*: cstring
|
||||
bottom*: cstring
|
||||
captionSide*: cstring
|
||||
clear*: cstring
|
||||
clip*: cstring
|
||||
color*: cstring
|
||||
cursor*: cstring
|
||||
direction*: cstring
|
||||
display*: cstring
|
||||
emptyCells*: cstring
|
||||
cssFloat*: cstring
|
||||
font*: cstring
|
||||
fontFamily*: cstring
|
||||
fontSize*: cstring
|
||||
fontStretch*: cstring
|
||||
fontStyle*: cstring
|
||||
fontVariant*: cstring
|
||||
fontWeight*: cstring
|
||||
height*: cstring
|
||||
left*: cstring
|
||||
letterSpacing*: cstring
|
||||
lineHeight*: cstring
|
||||
listStyle*: cstring
|
||||
listStyleImage*: cstring
|
||||
listStylePosition*: cstring
|
||||
listStyleType*: cstring
|
||||
margin*: cstring
|
||||
marginBottom*: cstring
|
||||
marginLeft*: cstring
|
||||
marginRight*: cstring
|
||||
marginTop*: cstring
|
||||
maxHeight*: cstring
|
||||
maxWidth*: cstring
|
||||
minHeight*: cstring
|
||||
minWidth*: cstring
|
||||
overflow*: cstring
|
||||
padding*: cstring
|
||||
paddingBottom*: cstring
|
||||
paddingLeft*: cstring
|
||||
paddingRight*: cstring
|
||||
paddingTop*: cstring
|
||||
pageBreakAfter*: cstring
|
||||
pageBreakBefore*: cstring
|
||||
position*: cstring
|
||||
right*: cstring
|
||||
scrollbar3dLightColor*: cstring
|
||||
scrollbarArrowColor*: cstring
|
||||
scrollbarBaseColor*: cstring
|
||||
scrollbarDarkshadowColor*: cstring
|
||||
scrollbarFaceColor*: cstring
|
||||
scrollbarHighlightColor*: cstring
|
||||
scrollbarShadowColor*: cstring
|
||||
scrollbarTrackColor*: cstring
|
||||
tableLayout*: cstring
|
||||
textAlign*: cstring
|
||||
textDecoration*: cstring
|
||||
textIndent*: cstring
|
||||
textTransform*: cstring
|
||||
top*: cstring
|
||||
verticalAlign*: cstring
|
||||
visibility*: cstring
|
||||
width*: cstring
|
||||
wordSpacing*: cstring
|
||||
zIndex*: int
|
||||
|
||||
# TODO: A lot of the fields in Event belong to a more specific type of event.
|
||||
# TODO: Should we clean this up?
|
||||
Event* = ref EventObj
|
||||
EventObj {.importc.} = object of RootObj
|
||||
target*: Node
|
||||
altKey*, ctrlKey*, shiftKey*: bool
|
||||
button*: int
|
||||
clientX*, clientY*: int
|
||||
keyCode*: int
|
||||
layerX*, layerY*: int
|
||||
modifiers*: int
|
||||
ALT_MASK*, CONTROL_MASK*, SHIFT_MASK*, META_MASK*: int
|
||||
offsetX*, offsetY*: int
|
||||
pageX*, pageY*: int
|
||||
screenX*, screenY*: int
|
||||
which*: int
|
||||
`type`*: cstring
|
||||
x*, y*: int
|
||||
ABORT*: int
|
||||
BLUR*: int
|
||||
CHANGE*: int
|
||||
CLICK*: int
|
||||
DBLCLICK*: int
|
||||
DRAGDROP*: int
|
||||
ERROR*: int
|
||||
FOCUS*: int
|
||||
KEYDOWN*: int
|
||||
KEYPRESS*: int
|
||||
KEYUP*: int
|
||||
LOAD*: int
|
||||
MOUSEDOWN*: int
|
||||
MOUSEMOVE*: int
|
||||
MOUSEOUT*: int
|
||||
MOUSEOVER*: int
|
||||
MOUSEUP*: int
|
||||
MOVE*: int
|
||||
RESET*: int
|
||||
RESIZE*: int
|
||||
SELECT*: int
|
||||
SUBMIT*: int
|
||||
UNLOAD*: int
|
||||
|
||||
TouchList* {.importc.} = ref object of RootObj
|
||||
length*: int
|
||||
|
||||
TouchEvent* {.importc.} = ref object of Event
|
||||
changedTouches*, targetTouches*, touches*: TouchList
|
||||
|
||||
Touch* {.importc.} = ref object of RootObj
|
||||
identifier*: int
|
||||
screenX*, screenY*, clientX*, clientY*, pageX*, pageY*: int
|
||||
target*: Element
|
||||
radiusX*, radiusY*: int
|
||||
rotationAngle*: int
|
||||
force*: float
|
||||
|
||||
Location* = ref LocationObj
|
||||
LocationObj {.importc.} = object of RootObj
|
||||
hash*: cstring
|
||||
host*: cstring
|
||||
hostname*: cstring
|
||||
href*: cstring
|
||||
pathname*: cstring
|
||||
port*: cstring
|
||||
protocol*: cstring
|
||||
search*: cstring
|
||||
|
||||
History* = ref HistoryObj
|
||||
HistoryObj {.importc.} = object of RootObj
|
||||
length*: int
|
||||
|
||||
Navigator* = ref NavigatorObj
|
||||
NavigatorObj {.importc.} = object of RootObj
|
||||
appCodeName*: cstring
|
||||
appName*: cstring
|
||||
appVersion*: cstring
|
||||
cookieEnabled*: bool
|
||||
language*: cstring
|
||||
platform*: cstring
|
||||
userAgent*: cstring
|
||||
mimeTypes*: seq[ref TMimeType]
|
||||
|
||||
TPlugin* {.importc.} = object of RootObj
|
||||
description*: cstring
|
||||
filename*: cstring
|
||||
name*: cstring
|
||||
|
||||
TMimeType* {.importc.} = object of RootObj
|
||||
description*: cstring
|
||||
enabledPlugin*: ref TPlugin
|
||||
suffixes*: seq[cstring]
|
||||
`type`*: cstring
|
||||
|
||||
TLocationBar* {.importc.} = object of RootObj
|
||||
visible*: bool
|
||||
TMenuBar* = TLocationBar
|
||||
TPersonalBar* = TLocationBar
|
||||
TScrollBars* = TLocationBar
|
||||
TToolBar* = TLocationBar
|
||||
TStatusBar* = TLocationBar
|
||||
|
||||
Screen = ref ScreenObj
|
||||
ScreenObj {.importc.} = object of RootObj
|
||||
availHeight*: int
|
||||
availWidth*: int
|
||||
colorDepth*: int
|
||||
height*: int
|
||||
pixelDepth*: int
|
||||
width*: int
|
||||
|
||||
TTimeOut* {.importc.} = object of RootObj
|
||||
TInterval* {.importc.} = object of RootObj
|
||||
|
||||
{.push importcpp.}
|
||||
|
||||
# EventTarget "methods"
|
||||
proc addEventListener*(et: EventTarget, ev: cstring, cb: proc(ev: Event), useCapture: bool = false)
|
||||
|
||||
# Window "methods"
|
||||
proc alert*(w: Window, msg: cstring)
|
||||
proc back*(w: Window)
|
||||
proc blur*(w: Window)
|
||||
proc captureEvents*(w: Window, eventMask: int) {.deprecated.}
|
||||
proc clearInterval*(w: Window, interval: ref TInterval)
|
||||
proc clearTimeout*(w: Window, timeout: ref TTimeOut)
|
||||
proc close*(w: Window)
|
||||
proc confirm*(w: Window, msg: cstring): bool
|
||||
proc disableExternalCapture*(w: Window)
|
||||
proc enableExternalCapture*(w: Window)
|
||||
proc find*(w: Window, text: cstring, caseSensitive = false,
|
||||
backwards = false)
|
||||
proc focus*(w: Window)
|
||||
proc forward*(w: Window)
|
||||
proc handleEvent*(w: Window, e: Event)
|
||||
proc home*(w: Window)
|
||||
proc moveBy*(w: Window, x, y: int)
|
||||
proc moveTo*(w: Window, x, y: int)
|
||||
proc open*(w: Window, uri, windowname: cstring,
|
||||
properties: cstring = nil): Window
|
||||
proc print*(w: Window)
|
||||
proc prompt*(w: Window, text, default: cstring): cstring
|
||||
proc releaseEvents*(w: Window, eventMask: int) {.deprecated.}
|
||||
proc resizeBy*(w: Window, x, y: int)
|
||||
proc resizeTo*(w: Window, x, y: int)
|
||||
proc routeEvent*(w: Window, event: Event)
|
||||
proc scrollBy*(w: Window, x, y: int)
|
||||
proc scrollTo*(w: Window, x, y: int)
|
||||
proc setInterval*(w: Window, code: cstring, pause: int): ref TInterval
|
||||
proc setInterval*(w: Window, function: proc (), pause: int): ref TInterval
|
||||
proc setTimeout*(w: Window, code: cstring, pause: int): ref TTimeOut
|
||||
proc setTimeout*(w: Window, function: proc (), pause: int): ref TInterval
|
||||
proc stop*(w: Window)
|
||||
proc requestAnimationFrame*(w: Window, function: proc (time: float)): int
|
||||
proc cancelAnimationFrame*(w: Window, id: int)
|
||||
|
||||
# Node "methods"
|
||||
proc appendChild*(n, child: Node)
|
||||
proc appendData*(n: Node, data: cstring)
|
||||
proc cloneNode*(n: Node, copyContent: bool): Node
|
||||
proc deleteData*(n: Node, start, len: int)
|
||||
proc getAttribute*(n: Node, attr: cstring): cstring
|
||||
proc getAttributeNode*(n: Node, attr: cstring): Node
|
||||
proc hasChildNodes*(n: Node): bool
|
||||
proc insertBefore*(n, newNode, before: Node)
|
||||
proc insertData*(n: Node, position: int, data: cstring)
|
||||
proc removeAttribute*(n: Node, attr: cstring)
|
||||
proc removeAttributeNode*(n, attr: Node)
|
||||
proc removeChild*(n, child: Node)
|
||||
proc replaceChild*(n, newNode, oldNode: Node)
|
||||
proc replaceData*(n: Node, start, len: int, text: cstring)
|
||||
proc scrollIntoView*(n: Node)
|
||||
proc setAttribute*(n: Node, name, value: cstring)
|
||||
proc setAttributeNode*(n: Node, attr: Node)
|
||||
|
||||
# Document "methods"
|
||||
proc captureEvents*(d: Document, eventMask: int) {.deprecated.}
|
||||
proc createAttribute*(d: Document, identifier: cstring): Node
|
||||
proc createElement*(d: Document, identifier: cstring): Element
|
||||
proc createTextNode*(d: Document, identifier: cstring): Node
|
||||
proc getElementById*(d: Document, id: cstring): Element
|
||||
proc getElementsByName*(d: Document, name: cstring): seq[Element]
|
||||
proc getElementsByTagName*(d: Document, name: cstring): seq[Element]
|
||||
proc getElementsByClassName*(d: Document, name: cstring): seq[Element]
|
||||
proc getSelection*(d: Document): cstring
|
||||
proc handleEvent*(d: Document, event: Event)
|
||||
proc open*(d: Document)
|
||||
proc releaseEvents*(d: Document, eventMask: int) {.deprecated.}
|
||||
proc routeEvent*(d: Document, event: Event)
|
||||
proc write*(d: Document, text: cstring)
|
||||
proc writeln*(d: Document, text: cstring)
|
||||
|
||||
# Element "methods"
|
||||
proc blur*(e: Element)
|
||||
proc click*(e: Element)
|
||||
proc focus*(e: Node)
|
||||
proc handleEvent*(e: Element, event: Event)
|
||||
proc select*(e: Element)
|
||||
proc getElementsByTagName*(e: Element, name: cstring): seq[Element]
|
||||
proc getElementsByClassName*(e: Element, name: cstring): seq[Element]
|
||||
|
||||
# FormElement "methods"
|
||||
proc reset*(f: FormElement)
|
||||
proc submit*(f: FormElement)
|
||||
|
||||
# EmbedElement "methods"
|
||||
proc play*(e: EmbedElement)
|
||||
proc stop*(e: EmbedElement)
|
||||
|
||||
# Location "methods"
|
||||
proc reload*(loc: Location)
|
||||
proc replace*(loc: Location, s: cstring)
|
||||
|
||||
# History "methods"
|
||||
proc back*(h: History)
|
||||
proc forward*(h: History)
|
||||
proc go*(h: History, pagesToJump: int)
|
||||
|
||||
# Navigator "methods"
|
||||
proc javaEnabled*(h: Navigator): bool
|
||||
|
||||
# ClassList "methods"
|
||||
proc add*(c: ClassList, class: cstring)
|
||||
proc remove*(c: ClassList, class: cstring)
|
||||
proc contains*(c: ClassList, class: cstring):bool
|
||||
proc toggle*(c: ClassList, class: cstring)
|
||||
|
||||
# Style "methods"
|
||||
proc getAttribute*(s: Style, attr: cstring, caseSensitive=false): cstring
|
||||
proc removeAttribute*(s: Style, attr: cstring, caseSensitive=false)
|
||||
proc setAttribute*(s: Style, attr, value: cstring, caseSensitive=false)
|
||||
|
||||
# Event "methods"
|
||||
proc preventDefault*(ev: Event)
|
||||
|
||||
# TouchEvent "methods"
|
||||
proc identifiedTouch*(list: TouchList): Touch
|
||||
proc item*(list: TouchList, i: int): Touch
|
||||
|
||||
{.pop.}
|
||||
|
||||
var
|
||||
window* {.importc, nodecl.}: Window
|
||||
document* {.importc, nodecl.}: Document
|
||||
navigator* {.importc, nodecl.}: Navigator
|
||||
screen* {.importc, nodecl.}: Screen
|
||||
|
||||
proc decodeURI*(uri: cstring): cstring {.importc, nodecl.}
|
||||
proc encodeURI*(uri: cstring): cstring {.importc, nodecl.}
|
||||
|
||||
proc escape*(uri: cstring): cstring {.importc, nodecl.}
|
||||
proc unescape*(uri: cstring): cstring {.importc, nodecl.}
|
||||
|
||||
proc decodeURIComponent*(uri: cstring): cstring {.importc, nodecl.}
|
||||
proc encodeURIComponent*(uri: cstring): cstring {.importc, nodecl.}
|
||||
proc isFinite*(x: BiggestFloat): bool {.importc, nodecl.}
|
||||
proc isNaN*(x: BiggestFloat): bool {.importc, nodecl.}
|
||||
proc parseFloat*(s: cstring): BiggestFloat {.importc, nodecl.}
|
||||
proc parseInt*(s: cstring): int {.importc, nodecl.}
|
||||
proc parseInt*(s: cstring, radix: int):int {.importc, nodecl.}
|
||||
|
||||
|
||||
type
|
||||
TEventHandlers* {.deprecated.} = EventTargetObj
|
||||
TWindow* {.deprecated.} = WindowObj
|
||||
TFrame* {.deprecated.} = FrameObj
|
||||
TNode* {.deprecated.} = NodeObj
|
||||
TDocument* {.deprecated.} = DocumentObj
|
||||
TElement* {.deprecated.} = ElementObj
|
||||
TLink* {.deprecated.} = LinkObj
|
||||
TEmbed* {.deprecated.} = EmbedObj
|
||||
TAnchor* {.deprecated.} = AnchorObj
|
||||
TOption* {.deprecated.} = OptionObj
|
||||
TForm* {.deprecated.} = FormObj
|
||||
TImage* {.deprecated.} = ImageObj
|
||||
TNodeType* {.deprecated.} = NodeType
|
||||
TEvent* {.deprecated.} = EventObj
|
||||
TLocation* {.deprecated.} = LocationObj
|
||||
THistory* {.deprecated.} = HistoryObj
|
||||
TNavigator* {.deprecated.} = NavigatorObj
|
||||
TStyle* {.deprecated.} = StyleObj
|
||||
TScreen* {.deprecated.} = ScreenObj
|
||||
TApplet* {.importc, deprecated.} = object of RootObj
|
||||
13
src/jdict.nim
Normal file
13
src/jdict.nim
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
|
||||
type
|
||||
JDict*[K, V] = ref object
|
||||
|
||||
proc `[]`*[K, V](d: JDict[K, V], k: K): V {.importcpp: "#[#]".}
|
||||
proc `[]=`*[K, V](d: JDict[K, V], k: K, v: V) {.importcpp: "#[#] = #".}
|
||||
|
||||
proc newJDict*[K, V](): JDict[K, V] {.importcpp: "{@}".}
|
||||
|
||||
proc contains*[K, V](d: JDict[K, V], k: K): bool {.importcpp: "#.hasOwnProperty(#)".}
|
||||
|
||||
proc del*[K, V](d: JDict[K, V], k: K) {.importcpp: "delete #[#]".}
|
||||
|
||||
23
src/jstrutils.nim
Normal file
23
src/jstrutils.nim
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# cstring handling utilities for performance
|
||||
|
||||
proc split*(s, sep: cstring): seq[cstring] {.importcpp, nodecl.}
|
||||
|
||||
proc split*(s, sep: cstring; max: int): seq[cstring] {.importcpp, nodecl.}
|
||||
|
||||
proc startsWith*(a, b: cstring): bool {.importcpp: "startsWith", nodecl.}
|
||||
proc contains*(a, b: cstring): bool {.importcpp: "(#.indexOf(#)>=0)", nodecl.}
|
||||
proc substr*(s: cstring; start: int): cstring {.importcpp: "substr", nodecl.}
|
||||
proc substr*(s: cstring; start, length: int): cstring {.importcpp: "substr", nodecl.}
|
||||
|
||||
#proc len*(s: cstring): int {.importcpp: "#.length", nodecl.}
|
||||
proc `&`*(a, b: cstring): cstring {.importcpp: "(# + #)", nodecl.}
|
||||
proc toCstr*(s: int): cstring {.importcpp: "((#)+'')", nodecl.}
|
||||
proc `&`*(s: int): cstring {.importcpp: "((#)+'')", nodecl.}
|
||||
proc `&`*(s: bool): cstring {.importcpp: "((#)+'')", nodecl.}
|
||||
|
||||
proc `&`*(s: cstring): cstring {.importcpp: "(#)", nodecl.}
|
||||
|
||||
proc isInt*(s: cstring): bool {.asmNoStackFrame.} =
|
||||
asm """
|
||||
return s.match(/^[0-9]+$/);
|
||||
"""
|
||||
523
src/karax.nim
Normal file
523
src/karax.nim
Normal file
|
|
@ -0,0 +1,523 @@
|
|||
# Simple lib to write JS UIs
|
||||
|
||||
import dom, vdom, jstrutils
|
||||
|
||||
export dom.Event, dom.cloneNode, dom
|
||||
|
||||
proc len(x: Node): int {.importcpp: "#.childNodes.length".}
|
||||
proc `[]`(x: Node; idx: int): Element {.importcpp: "#.childNodes[#]".}
|
||||
|
||||
proc kout*[T](x: T) {.importc: "console.log", varargs.}
|
||||
## the preferred way of debugging karax applications.
|
||||
|
||||
proc id*(e: Node): cstring {.importcpp: "#.id", nodecl.}
|
||||
proc `id=`*(e: Node; x: cstring) {.importcpp: "#.id = #", nodecl.}
|
||||
proc class*(e: Node): cstring {.importcpp: "#.className", nodecl.}
|
||||
proc `class=`*(e: Node; v: cstring) {.importcpp: "#.className = #", nodecl.}
|
||||
|
||||
proc value*(e: Node): cstring {.importcpp: "#.value", nodecl.}
|
||||
proc `value=`*(e: Node; v: cstring) {.importcpp: "#.value = #", nodecl.}
|
||||
|
||||
proc `disabled=`*(e: Node; v: bool) {.importcpp: "#.disabled = #", nodecl.}
|
||||
|
||||
proc getElementsByClass*(e: Node; name: cstring): seq[Node] {.
|
||||
importcpp: "#.getElementsByClassName(#)", nodecl.}
|
||||
|
||||
proc hasProp(e: Node; prop: cstring): bool {.importcpp: "(#.hasOwnProperty(#))".}
|
||||
proc rawkey(e: Node): VKey {.importcpp: "#.karaxKey", nodecl.}
|
||||
proc key*(e: Node): VKey =
|
||||
if e.hasProp"karaxKey": result = e.rawkey
|
||||
else: result = -1
|
||||
proc `key=`*(e: Node; x: VKey) {.importcpp: "#.karaxKey = #", nodecl.}
|
||||
|
||||
type
|
||||
BoundingRect {.importc.} = object
|
||||
top, bottom, left, right: int
|
||||
|
||||
proc getBoundingClientRect(e: Node): BoundingRect {.
|
||||
importcpp: "getBoundingClientRect", nodecl.}
|
||||
proc clientHeight(): int {.
|
||||
importcpp: "(window.innerHeight || document.documentElement.clientHeight)@", nodecl}
|
||||
proc clientWidth(): int {.
|
||||
importcpp: "(window.innerWidth || document.documentElement.clientWidth)@", nodecl}
|
||||
|
||||
when false:
|
||||
proc pageYOffset(): int {.
|
||||
importcpp: "(window.pageYOffset)@", nodecl}
|
||||
proc pageXOffset(): int {.
|
||||
importcpp: "(window.pageXOffset)@", nodecl}
|
||||
|
||||
type
|
||||
Timeout* = ref object
|
||||
|
||||
var
|
||||
document* {.importc.}: Document
|
||||
toFocus: Node
|
||||
toFocusV: VNode
|
||||
|
||||
proc setFocus*(n: VNode) =
|
||||
toFocusV = n
|
||||
|
||||
proc isElementInViewport(el: Node; h: var int): bool =
|
||||
let rect = el.getBoundingClientRect()
|
||||
h = rect.bottom - rect.top
|
||||
result = rect.top >= 0 and rect.left >= 0 and
|
||||
rect.bottom <= clientHeight() and
|
||||
rect.right <= clientWidth()
|
||||
|
||||
proc vnodeToDom(n: VNode): Node =
|
||||
if n.kind == VNodeKind.text:
|
||||
result = document.createTextNode(n.text)
|
||||
elif n.kind == VNodeKind.thunk:
|
||||
return vnodeToDom(n.callThunk)
|
||||
else:
|
||||
result = document.createElement(toTag[n.kind])
|
||||
for k in n:
|
||||
appendChild(result, vnodeToDom(k))
|
||||
# text is mapped to 'value':
|
||||
if n.text != nil:
|
||||
result.value = n.text
|
||||
if n.id != nil:
|
||||
result.id = n.id
|
||||
if n.class != nil:
|
||||
result.class = n.class
|
||||
if n.key >= 0:
|
||||
result.key = n.key
|
||||
for k, v in attrs(n):
|
||||
if v != nil:
|
||||
result.setAttribute(k, v)
|
||||
let myn = n
|
||||
for e, h in items(n.events):
|
||||
proc wrapper(): proc (ev: Event) =
|
||||
let hh = h
|
||||
result = proc (ev: Event) =
|
||||
assert myn != nil
|
||||
hh(ev, myn)
|
||||
result.addEventListener(toEventName[e], wrapper())
|
||||
if n == toFocusV and toFocus.isNil:
|
||||
toFocus = result
|
||||
|
||||
proc same(n: VNode, e: Node): bool =
|
||||
if toTag[n.kind] == e.nodename:
|
||||
result = true
|
||||
if n.kind != VNodeKind.text:
|
||||
if e.len != n.len: return false
|
||||
for i in 0 ..< n.len:
|
||||
if not same(n[i], e[i]): return false
|
||||
|
||||
var
|
||||
dorender: proc (): VNode {.closure.}
|
||||
drawTimeout: Timeout
|
||||
currentTree: VNode
|
||||
|
||||
proc setRenderer*(renderer: proc (): VNode) =
|
||||
dorender = renderer
|
||||
|
||||
proc setTimeout*(action: proc(); ms: int): Timeout {.importc, nodecl.}
|
||||
proc clearTimeout*(t: Timeout) {.importc, nodecl.}
|
||||
#proc targetElem*(e: Event): Element = cast[Element](e.target)
|
||||
|
||||
proc getElementById*(id: cstring): Element {.importc: "document.getElementById", nodecl.}
|
||||
|
||||
#proc getElementsByClassName*(cls: cstring): seq[Element] {.importc:
|
||||
# "document.getElementsByClassName", nodecl.}
|
||||
|
||||
proc textContent(e: Node): cstring {.
|
||||
importcpp: "#.textContent", nodecl.}
|
||||
|
||||
proc replaceById(id: cstring; newTree: Node) =
|
||||
let x = document.getElementById(id)
|
||||
x.parentNode.replaceChild(newTree, x)
|
||||
#newTree.id = id
|
||||
|
||||
proc equals(a, b: VNode): bool =
|
||||
if a.kind != b.kind: return false
|
||||
if a.id != b.id: return false
|
||||
if a.key != b.key: return false
|
||||
if a.kind == VNodeKind.text:
|
||||
if a.text != b.text: return false
|
||||
elif a.kind == VNodeKind.thunk:
|
||||
if a.thunk != b.thunk: return false
|
||||
if a.len != b.len: return false
|
||||
for i in 0..<a.len:
|
||||
if not equals(a[i], b[i]): return false
|
||||
if not sameAttrs(a, b): return false
|
||||
if a.class != b.class: return false
|
||||
# XXX test event listeners here?
|
||||
# --> maybe give nodes a hash?
|
||||
return true
|
||||
|
||||
proc equalsTree(a, b: VNode): bool =
|
||||
if not a.validHash:
|
||||
a.calcHash()
|
||||
if not b.validHash:
|
||||
b.calcHash()
|
||||
return a.hash == b.hash
|
||||
|
||||
proc updateElement(parent, current: Node, newNode, oldNode: VNode) =
|
||||
if not equals(newNode, oldNode):
|
||||
let n = vnodeToDom(newNode)
|
||||
if parent == nil:
|
||||
replaceById("ROOT", n)
|
||||
else:
|
||||
parent.replaceChild(n, current)
|
||||
elif newNode.kind != VNodeKind.text:
|
||||
let newLength = newNode.len
|
||||
var oldLength = oldNode.len
|
||||
let minLength = min(newLength, oldLength)
|
||||
assert oldNode.kind == newNode.kind
|
||||
when defined(simpleDiff):
|
||||
for i in 0..min(newLength, oldLength)-1:
|
||||
updateElement(current, current[i], newNode[i], oldNode[i])
|
||||
if newLength > oldLength:
|
||||
for i in oldLength..newLength-1:
|
||||
current.appendChild(vnodeToDom(newNode[i]))
|
||||
elif oldLength > newLength:
|
||||
for i in countdown(oldLength-1, newLength):
|
||||
current.removeChild(current.lastChild)
|
||||
else:
|
||||
var commonPrefix = 0
|
||||
while commonPrefix < minLength and equalsTree(newNode[commonPrefix], oldNode[commonPrefix]):
|
||||
inc commonPrefix
|
||||
|
||||
var oldPos = oldLength - 1
|
||||
var newPos = newLength - 1
|
||||
while oldPos >= commonPrefix and newPos >= commonPrefix and equalsTree(newNode[newPos], oldNode[oldPos]):
|
||||
dec oldPos
|
||||
dec newPos
|
||||
|
||||
var pos = min(oldPos, newPos) + 1
|
||||
for i in commonPrefix..pos-1:
|
||||
updateElement(current, current.childNodes[i],
|
||||
newNode[i],
|
||||
oldNode[i])
|
||||
|
||||
var nextChildPos = oldPos + 1
|
||||
while pos <= newPos:
|
||||
if nextChildPos == oldLength:
|
||||
current.appendChild(vnodeToDom(newNode[pos]))
|
||||
else:
|
||||
current.insertBefore(vnodeToDom(newNode[pos]), current.childNodes[nextChildPos])
|
||||
# added new Node, so old state of VDOM have one more Node
|
||||
inc oldLength
|
||||
inc pos
|
||||
inc nextChildPos
|
||||
|
||||
for i in 0..oldPos-pos:
|
||||
current.removeChild(current.childNodes[pos])
|
||||
|
||||
|
||||
proc dodraw() =
|
||||
let newtree = dorender()
|
||||
newtree.id = "ROOT"
|
||||
toFocus = nil
|
||||
if currentTree == nil:
|
||||
currentTree = newtree
|
||||
let asdom = vnodeToDom currentTree
|
||||
replaceById("ROOT", asdom)
|
||||
else:
|
||||
let olddom = document.getElementById("ROOT")
|
||||
updateElement(nil, olddom, newtree, currentTree)
|
||||
#assert same(newtree, document.getElementById("ROOT"))
|
||||
currentTree = newtree
|
||||
# now that it's part of the DOM, give it the focus:
|
||||
if toFocus != nil:
|
||||
toFocus.focus()
|
||||
|
||||
proc visibleKeys(e: Node; a, b: var VKey; h, count: var int) =
|
||||
# we only care about nodes that have a key:
|
||||
var hh = 0
|
||||
# do not recurse if there is a 'key' field already:
|
||||
if e.key >= 0:
|
||||
if isElementInViewport(e, hh):
|
||||
inc count
|
||||
inc h, hh
|
||||
a = min(a, e.key)
|
||||
b = max(b, e.key)
|
||||
else:
|
||||
for i in 0..<e.len:
|
||||
visibleKeys(e[i], a, b, h, count)
|
||||
|
||||
proc reqFrame(callback: proc()) {.importc: "window.requestAnimationFrame".}
|
||||
|
||||
proc redraw*() =
|
||||
# we buffer redraw requests:
|
||||
when false:
|
||||
if drawTimeout != nil:
|
||||
clearTimeout(drawTimeout)
|
||||
drawTimeout = setTimeout(dodraw, 30)
|
||||
elif true:
|
||||
reqFrame(dodraw)
|
||||
else:
|
||||
dodraw()
|
||||
|
||||
proc init*() =
|
||||
reqFrame(dodraw)
|
||||
|
||||
#proc prepend*(parent, kid: Element) =
|
||||
# parent.insertBefore(kid, parent.firstChild)
|
||||
# prependChild(parent, kid)
|
||||
|
||||
proc suffix*(s, prefix: cstring): cstring =
|
||||
if s.startsWith(prefix):
|
||||
result = s.substr(prefix.len)
|
||||
else:
|
||||
kout(cstring"bug! " & s & cstring" does not start with " & prefix)
|
||||
|
||||
proc suffixAsInt*(s, prefix: cstring): int = parseInt(suffix(s, prefix))
|
||||
|
||||
proc scrollTop*(e: Node): int {.importcpp: "#.scrollTop", nodecl.}
|
||||
proc offsetHeight*(e: Node): int {.importcpp: "#.offsetHeight", nodecl.}
|
||||
proc offsetTop*(e: Node): int {.importcpp: "#.offsetTop", nodecl.}
|
||||
|
||||
template onImpl(s) {.dirty.} =
|
||||
proc wrapper(ev: Event; n: VNode) =
|
||||
action(ev, n)
|
||||
redraw()
|
||||
addEventListener(e, s, wrapper)
|
||||
|
||||
proc setOnclick*(e: VNode; action: EventHandler) =
|
||||
onImpl EventKind.onclick
|
||||
|
||||
proc setOnDblclick*(e: VNode; action: EventHandler) =
|
||||
onImpl EventKind.ondblclick
|
||||
|
||||
proc setOnfocuslost*(e: VNode; action: EventHandler) =
|
||||
onImpl EventKind.onblur
|
||||
|
||||
proc setOnchanged*(e: VNode; action: EventHandler) =
|
||||
onImpl EventKind.onchange
|
||||
|
||||
proc setOnscroll*(e: VNode; action: EventHandler) =
|
||||
onImpl EventKind.onscroll
|
||||
|
||||
#proc ceil(f: float): int {.importc: "Math.ceil", nodecl.}
|
||||
|
||||
proc setOnscroll*(action: proc(min, max: VKey; diff: int)) =
|
||||
var oldY = window.pageYOffset
|
||||
|
||||
proc wrapper(ev: Event) =
|
||||
let dir = window.pageYOffset - oldY
|
||||
if dir == 0: return
|
||||
|
||||
var a = VKey high(int)
|
||||
var b = VKey 0
|
||||
var h, count: int
|
||||
document.visibleKeys(a, b, h, count)
|
||||
let avgh = h / count
|
||||
let diff = toInt(dir.float / avgh)
|
||||
if diff != 0:
|
||||
oldY = window.pageYOffset
|
||||
action(a, b, diff)
|
||||
redraw()
|
||||
|
||||
document.addEventListener("scroll", wrapper)
|
||||
|
||||
proc setOnHashChange*(action: proc (hashPart: cstring)) =
|
||||
var onhashChange {.importc: "window.onhashchange".}: proc()
|
||||
var hashPart {.importc: "window.location.hash".}: cstring
|
||||
proc wrapper() =
|
||||
action(hashPart)
|
||||
redraw()
|
||||
onhashchange = wrapper
|
||||
|
||||
var
|
||||
linkCounter: int
|
||||
|
||||
proc link*(id: int): VNode =
|
||||
result = newVNode(VNodeKind.anchor)
|
||||
result.setAttr("href", "#")
|
||||
inc linkCounter
|
||||
result.setAttr("id", $linkCounter & ":" & $id)
|
||||
|
||||
proc link*(action: EventHandler): VNode =
|
||||
result = newVNode(VNodeKind.anchor)
|
||||
result.setAttr("href", "#")
|
||||
result.setOnclick action
|
||||
|
||||
when false:
|
||||
proc button*(caption: cstring; action: EventHandler; disabled=false): VNode =
|
||||
result = newVNode(VNodeKind.button)
|
||||
result.add text(caption)
|
||||
if action != nil:
|
||||
result.setOnClick action
|
||||
if disabled:
|
||||
result.setAttr("disabled", "true")
|
||||
|
||||
proc select*(choices: openarray[cstring]): VNode =
|
||||
result = newVNode(VNodeKind.select)
|
||||
var i = 0
|
||||
for c in choices:
|
||||
result.add tree(VNodeKind.option, [(cstring"value", toCstr(i))], text(c))
|
||||
inc i
|
||||
|
||||
proc select*(choices: openarray[(int, cstring)]): VNode =
|
||||
result = newVNode(VNodeKind.select)
|
||||
for c in choices:
|
||||
result.add tree(VNodeKind.option, [(cstring"value", toCstr(c[0]))], text(c[1]))
|
||||
|
||||
var radioCounter: int
|
||||
|
||||
proc radio*(choices: openarray[(int, cstring)]): VNode =
|
||||
result = newVNode(VNodeKind.fieldset)
|
||||
var i = 0
|
||||
inc radioCounter
|
||||
for c in choices:
|
||||
let id = cstring"radio_" & c[1] & toCstr(i)
|
||||
var kid = tree(VNodeKind.input, [(cstring"type", cstring"radio"),
|
||||
(cstring"id", id), (cstring"name", cstring"radio" & toCStr(radioCounter)),
|
||||
(cstring"value", toCStr(c[0]))])
|
||||
if i == 0:
|
||||
kid.setAttr(cstring"checked", cstring"checked")
|
||||
var lab = tree(VNodeKind.label, [(cstring"for", id)], text(c[1]))
|
||||
kid.add lab
|
||||
result.add kid
|
||||
inc i
|
||||
|
||||
proc tag*(kind: VNodeKind; id=cstring(nil), class=cstring(nil)): VNode =
|
||||
result = newVNode(kind)
|
||||
result.id = id
|
||||
result.class = class
|
||||
|
||||
proc tdiv*(id=cstring(nil), class=cstring(nil)): VNode = tag(VNodeKind.tdiv, id, class)
|
||||
proc span*(id=cstring(nil), class=cstring(nil)): VNode = tag(VNodeKind.span, id, class)
|
||||
|
||||
proc valueAsInt*(e: Node): int = parseInt(e.value)
|
||||
|
||||
proc th*(s: cstring): VNode =
|
||||
result = newVNode(VNodeKind.th)
|
||||
result.add text(s)
|
||||
|
||||
proc td*(s: string): VNode =
|
||||
result = newVNode(VNodeKind.td)
|
||||
result.add text(s)
|
||||
|
||||
proc td*(s: VNode): VNode =
|
||||
result = newVNode(VNodeKind.td)
|
||||
result.add s
|
||||
|
||||
proc td*(class: cstring; s: VNode): VNode =
|
||||
result = newVNode(VNodeKind.td)
|
||||
result.add s
|
||||
result.class = class
|
||||
|
||||
proc table*(class=cstring(nil), kids: varargs[VNode]): VNode =
|
||||
result = tag(VNodeKind.table, nil, class)
|
||||
for k in kids: result.add k
|
||||
|
||||
proc tr*(kids: varargs[VNode]): VNode =
|
||||
result = newVNode(VNodeKind.tr)
|
||||
for k in kids:
|
||||
if k.kind in {VNodeKind.td, VNodeKind.th}:
|
||||
result.add k
|
||||
else:
|
||||
result.add td(k)
|
||||
|
||||
proc getAttr(e: Node; key: cstring): cstring {.
|
||||
importcpp: "#.getAttribute(#)", nodecl.}
|
||||
|
||||
template nativeValue(ev): cstring = cast[Element](ev.target).value
|
||||
template setNativeValue(ev, val) = cast[Element](ev.target).value = val
|
||||
|
||||
template keyeventBody() =
|
||||
n.value = nativeValue(ev)
|
||||
action(ev, n)
|
||||
setNativeValue(ev, n.value)
|
||||
redraw()
|
||||
|
||||
proc realtimeInput*(val: cstring; action: EventHandler): VNode =
|
||||
#let oldElem = getElementById(id)
|
||||
#if oldElem != nil: return oldElem
|
||||
#let newVal = if oldElem.isNil: val else: $oldElem.value
|
||||
var timer: Timeout
|
||||
proc onkeyup(ev: Event; n: VNode) =
|
||||
proc wrapper() = keyeventBody()
|
||||
|
||||
if timer != nil: clearTimeout(timer)
|
||||
timer = setTimeout(wrapper, 400)
|
||||
result = tree(VNodeKind.input, [(cstring"type", cstring"text")])
|
||||
result.value = val
|
||||
result.addEventListener(EventKind.onkeyup, onkeyup)
|
||||
|
||||
proc enterInput*(id, val: cstring; action: EventHandler): VNode =
|
||||
#let oldElem = getElementById(id)
|
||||
#if oldElem != nil: return oldElem
|
||||
#let newVal = if oldElem.isNil: val else: $oldElem.value
|
||||
proc onkeyup(ev: Event; n: VNode) =
|
||||
if ev.keyCode == 13: keyeventBody()
|
||||
|
||||
result = tree(VNodeKind.input, [(cstring"type", cstring"text")])
|
||||
result.id = id
|
||||
result.value = val
|
||||
result.addEventListener(EventKind.onkeyup, onkeyup)
|
||||
|
||||
proc setOnEnter*(n: VNode; action: EventHandler) =
|
||||
proc onkeyup(ev: Event; n: VNode) =
|
||||
if ev.keyCode == 13: keyeventBody()
|
||||
n.addEventListener(EventKind.onkeyup, onkeyup)
|
||||
|
||||
proc ajax(meth, url: cstring; headers: openarray[(cstring, cstring)];
|
||||
data: cstring;
|
||||
cont: proc (httpStatus: int; response: cstring)) =
|
||||
proc setRequestHeader(a, b: cstring) {.importc: "ajax.setRequestHeader".}
|
||||
{.emit: """
|
||||
var ajax = new XMLHttpRequest();
|
||||
ajax.open(`meth`,`url`,true);""".}
|
||||
for a, b in items(headers):
|
||||
setRequestHeader(a, b)
|
||||
{.emit: """
|
||||
ajax.onreadystatechange = function(){
|
||||
if(this.readyState == 4){
|
||||
if(this.status == 200){
|
||||
`cont`(this.status, this.responseText);
|
||||
} else {
|
||||
`cont`(this.status, this.statusText);
|
||||
}
|
||||
}
|
||||
}
|
||||
ajax.send(`data`);
|
||||
""".}
|
||||
|
||||
proc ajaxPut*(url: string; headers: openarray[(cstring, cstring)];
|
||||
data: cstring;
|
||||
cont: proc (httpStatus: int, response: cstring)) =
|
||||
ajax("PUT", url, headers, data, cont)
|
||||
|
||||
proc ajaxGet*(url: string; headers: openarray[(cstring, cstring)];
|
||||
cont: proc (httpStatus: int, response: cstring)) =
|
||||
ajax("GET", url, headers, nil, cont)
|
||||
|
||||
{.push stackTrace:off.}
|
||||
|
||||
proc setupErrorHandler*(useAlert=false) =
|
||||
## Installs an error handler that transforms native JS unhandled
|
||||
## exceptions into Nim based stack traces. If `useAlert` is false,
|
||||
## the error message is put into the console, otherwise `alert`
|
||||
## is called.
|
||||
proc stackTraceAsCstring(): cstring = cstring(getStackTrace())
|
||||
{.emit: """
|
||||
window.onerror = function(msg, url, line, col, error) {
|
||||
var x = "Error: " + msg + "\n" + `stackTraceAsCstring`()
|
||||
if (`useAlert`)
|
||||
alert(x);
|
||||
else
|
||||
console.log(x);
|
||||
var suppressErrorAlert = true;
|
||||
return suppressErrorAlert;
|
||||
};""".}
|
||||
|
||||
{.pop.}
|
||||
|
||||
when false:
|
||||
var plugins {.exportc.}: seq[(string, proc())] = @[]
|
||||
|
||||
proc onInput(val: cstring) =
|
||||
kout val
|
||||
if val == "dyn":
|
||||
let body = getElementById("body")
|
||||
body.prepend(tree("script", [("type", "text/javascript"), ("src", "nimcache/dyn.js")]))
|
||||
redraw()
|
||||
kout(plugins.len)
|
||||
if plugins.len > 0:
|
||||
plugins[0][1]()
|
||||
|
||||
113
src/karaxdsl.nim
Normal file
113
src/karaxdsl.nim
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
|
||||
import macros, karax, vdom
|
||||
from strutils import startsWith, toLowerAscii
|
||||
|
||||
const
|
||||
StmtContext = ["kout", "inc", "echo", "dec", "!"]
|
||||
SpecialAttrs = ["id", "class", "value", "key"]
|
||||
|
||||
proc getName(n: NimNode): string =
|
||||
case n.kind
|
||||
of nnkIdent:
|
||||
result = $n.ident
|
||||
of nnkAccQuoted:
|
||||
result = ""
|
||||
for i in 0..<n.len:
|
||||
result.add getName(n[i])
|
||||
of nnkStrLit..nnkTripleStrLit:
|
||||
result = n.strVal
|
||||
else:
|
||||
#echo repr n
|
||||
expectKind(n, nnkIdent)
|
||||
|
||||
proc newDotAsgn(tmp: NimNode, key: string, x: NimNode): NimNode =
|
||||
result = newTree(nnkAsgn, newDotExpr(tmp, newIdentNode key), x)
|
||||
|
||||
proc isTag(s: string): bool =
|
||||
for i in VNodeKind.low.succ..VNodeKind.high:
|
||||
if $i == s: return true
|
||||
|
||||
proc tcall2(n, tmpContext: NimNode): NimNode =
|
||||
# we need to distinguish statement and expression contexts:
|
||||
# every call statement 's' needs to be transformed to 'dest.add s'.
|
||||
# If expressions need to be distinguished from if statements. Since
|
||||
# we know we start in a statement context, it's pretty simple to
|
||||
# figure out expression contexts: In calls everything is an expression
|
||||
# (except for the last child of the macros we consider here),
|
||||
# lets, consts, types can be considered as expressions
|
||||
# case is complex, calls are assumed to produce a value.
|
||||
case n.kind
|
||||
of nnkLiterals, nnkIdent, nnkSym, nnkDotExpr, nnkBracketExpr:
|
||||
if tmpContext != nil:
|
||||
result = newCall(bindSym"add", tmpContext, n)
|
||||
else:
|
||||
result = n
|
||||
of nnkForStmt, nnkIfExpr, nnkElifExpr, nnkElseExpr,
|
||||
nnkOfBranch, nnkElifBranch, nnkExceptBranch, nnkElse,
|
||||
nnkConstDef, nnkWhileStmt, nnkIdentDefs, nnkVarTuple:
|
||||
# recurse for the last son:
|
||||
result = copyNimTree(n)
|
||||
let L = n.len
|
||||
assert n.len == result.len
|
||||
if L > 0:
|
||||
result[L-1] = tcall2(result[L-1], tmpContext)
|
||||
of nnkStmtList, nnkStmtListExpr, nnkWhenStmt, nnkIfStmt, nnkCaseStmt,
|
||||
nnkTryStmt, nnkFinally:
|
||||
# recurse for every child:
|
||||
result = copyNimNode(n)
|
||||
for x in n:
|
||||
result.add tcall2(x, tmpContext)
|
||||
of nnkVarSection, nnkLetSection, nnkConstSection:
|
||||
result = n
|
||||
of nnkCallKinds:
|
||||
let op = getName(n[0])
|
||||
if isTag(op):
|
||||
let tmp = genSym(nskLet, "tmp")
|
||||
result = newTree(
|
||||
if tmpContext == nil: nnkStmtListExpr else: nnkStmtList,
|
||||
newLetStmt(tmp, newCall(bindSym"tree", newDotExpr(bindSym"VNodeKind", n[0]))))
|
||||
for i in 1 ..< n.len:
|
||||
# named parameters are transformed into attributes or events:
|
||||
let x = n[i]
|
||||
if x.kind == nnkExprEqExpr:
|
||||
let key = getName x[0]
|
||||
if key.startsWith("on"):
|
||||
result.add newCall(!("set" & key), tmp, x[1])
|
||||
elif key in SpecialAttrs:
|
||||
result.add newDotAsgn(tmp, key, x[1])
|
||||
else:
|
||||
result.add newCall(bindSym"setAttr", tmp, newLit(key), x[1])
|
||||
elif x.kind == nnkIdent:
|
||||
result.add newCall(x, tmp)
|
||||
else:
|
||||
result.add tcall2(x, tmp)
|
||||
if tmpContext == nil:
|
||||
result.add tmp
|
||||
else:
|
||||
result.add newCall(bindSym"add", tmpContext, tmp)
|
||||
elif tmpContext != nil and op notin StmtContext:
|
||||
result = newCall(bindSym"add", tmpContext, n)
|
||||
elif op == "!" and n.len == 2:
|
||||
result = n[1]
|
||||
else:
|
||||
result = n
|
||||
else:
|
||||
result = n
|
||||
|
||||
macro buildHtml*(tag, children: untyped): VNode =
|
||||
expectKind children, nnkDo
|
||||
var call: NimNode
|
||||
if tag.kind in nnkCallKinds:
|
||||
call = tag
|
||||
else:
|
||||
call = newCall(tag)
|
||||
call.add body(children)
|
||||
result = tcall2(call, nil)
|
||||
when defined(debugKaraxDsl):
|
||||
echo repr result
|
||||
|
||||
macro buildHtml*(children: untyped): VNode =
|
||||
expectKind children, nnkDo
|
||||
result = tcall2(body(children), nil)
|
||||
when defined(debugKaraxDsl):
|
||||
echo repr result
|
||||
182
src/vdom.nim
Normal file
182
src/vdom.nim
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
# Virtual DOM implementation
|
||||
|
||||
from dom import Event
|
||||
import shash
|
||||
|
||||
type
|
||||
VNodeKind* {.pure.} = enum
|
||||
text, int, bool, thunk,
|
||||
anchor,
|
||||
tdiv,
|
||||
table, tr, td, th, thead, tbody,
|
||||
link, span, label, br, select, option,
|
||||
fieldset, input, button, ul, li, section, header, footer,
|
||||
h1, h2, h3, h4, h5, strong
|
||||
|
||||
const
|
||||
toTag*: array[VNodeKind, cstring] = [
|
||||
cstring"#text", "#int", "#bool", "#thunk", "A", "DIV", "TABLE", "TR", "TD",
|
||||
"TH", "THEAD",
|
||||
"TBODY", "LINK",
|
||||
"SPAN", "LABEL", "BR", "SELECT", "OPTION", "FIELDSET", "INPUT", "BUTTON", "UL",
|
||||
"LI", "SECTION", "HEADER", "FOOTER", "H1", "H2", "H3", "H4", "H5", "STRONG"
|
||||
]
|
||||
|
||||
type
|
||||
EventKind* {.pure.} = enum
|
||||
onclick, ondblclick, onkeyup, onkeydown, onkeypressed, onblur, onchange, onscroll
|
||||
|
||||
const
|
||||
toEventName*: array[EventKind, cstring] = [
|
||||
cstring"click", "dblclick", "keyup", "keydown", "keypressed", "blur",
|
||||
"change", "scroll"
|
||||
]
|
||||
|
||||
type
|
||||
EventHandler* = proc (ev: Event; target: VNode) {.closure.}
|
||||
VKey* = int
|
||||
VNode* = ref object
|
||||
kind*: VNodeKind
|
||||
key*: VKey
|
||||
id*, class*, text*: cstring
|
||||
kids: seq[VNode]
|
||||
# even index: key, odd index: value; done this way for memory efficiency:
|
||||
attrs: seq[cstring]
|
||||
events*: seq[(EventKind, EventHandler)]
|
||||
thunk*: proc (args: seq[VNode]): VNode
|
||||
hash*: Hash
|
||||
validHash*: bool
|
||||
|
||||
proc value*(n: VNode): cstring = n.text
|
||||
proc `value=`*(n: VNode; v: cstring) = n.text = v
|
||||
|
||||
proc intValue*(n: VNode): int = n.key
|
||||
proc vn*(i: int): VNode = VNode(kind: VNodeKind.int, key: i)
|
||||
proc vn*(b: bool): VNode = VNode(kind: VNodeKind.int, key: ord(b))
|
||||
proc vn*(x: cstring): VNode = VNode(kind: VNodeKind.text, key: -1, text: x)
|
||||
|
||||
proc callThunk*(n: VNode): VNode =
|
||||
assert n.kind == VNodeKind.thunk
|
||||
result = n.thunk(n.kids)
|
||||
|
||||
proc thunk*(cb: proc(args: seq[VNode]): VNode; args: varargs[VNode, vn]): VNode =
|
||||
VNode(kind: VNodeKind.thunk, thunk: cb, kids: @args)
|
||||
|
||||
proc eq*(a, b: VNode): bool =
|
||||
if a.kind != b.kind: return false
|
||||
if a.id != b.id: return false
|
||||
if a.class != b.class: return false
|
||||
if a.kind != VNodeKind.text:
|
||||
if a.kids.len != b.kids.len: return false
|
||||
for i in 0..<a.kids.len:
|
||||
if not eq(a.kids[i], b.kids[i]): return false
|
||||
else:
|
||||
if a.text != b.text: return false
|
||||
if a.attrs.len != b.attrs.len: return false
|
||||
for i in 0..<a.attrs.len:
|
||||
if a.attrs[i] != b.attrs[i]: return false
|
||||
result = true
|
||||
|
||||
proc setAttr*(n: VNode; key: cstring; val: cstring = "") =
|
||||
if n.attrs.isNil:
|
||||
n.attrs = @[key, val]
|
||||
else:
|
||||
for i in countup(0, n.attrs.len-2, 2):
|
||||
if n.attrs[i] == key:
|
||||
n.attrs[i+1] = val
|
||||
return
|
||||
n.attrs.add key
|
||||
n.attrs.add val
|
||||
|
||||
proc getAttr*(n: VNode; key: cstring): cstring =
|
||||
for i in countup(0, n.attrs.len-2, 2):
|
||||
if n.attrs[i] == key: return n.attrs[i+1]
|
||||
|
||||
proc len*(x: VNode): int = x.kids.len
|
||||
proc `[]`*(x: VNode; idx: int): VNode = x.kids[idx]
|
||||
proc add*(parent, kid: VNode) = parent.kids.add kid
|
||||
proc newVNode*(kind: VNodeKind): VNode = VNode(kind: kind, key: -1)
|
||||
|
||||
proc tree*(kind: VNodeKind; kids: varargs[VNode]): VNode =
|
||||
result = newVNode(kind)
|
||||
for k in kids: result.add k
|
||||
|
||||
proc tree*(kind: VNodeKind; attrs: openarray[(cstring, cstring)];
|
||||
kids: varargs[VNode]): VNode =
|
||||
result = tree(kind, kids)
|
||||
for a in attrs: result.setAttr(a[0], a[1])
|
||||
|
||||
proc text*(s: string): VNode = VNode(kind: VNodeKind.text, text: cstring(s), key: -1)
|
||||
proc text*(s: cstring): VNode = VNode(kind: VNodeKind.text, text: s, key: -1)
|
||||
|
||||
iterator items*(n: VNode): VNode =
|
||||
for i in 0..<n.kids.len: yield n.kids[i]
|
||||
|
||||
iterator attrs*(n: VNode): (cstring, cstring) =
|
||||
for i in countup(0, n.attrs.len-2, 2):
|
||||
yield (n.attrs[i], n.attrs[i+1])
|
||||
|
||||
proc sameAttrs*(a, b: VNode): bool =
|
||||
if a.attrs.len == b.attrs.len:
|
||||
result = true
|
||||
for i in 0 ..< a.attrs.len:
|
||||
if a.attrs[i] != b.attrs[i]: return false
|
||||
|
||||
proc addEventListener*(n: VNode; event: EventKind; handler: EventHandler) =
|
||||
n.events.add((event, handler))
|
||||
|
||||
template toStringAttr(field) =
|
||||
if n.field != nil:
|
||||
result.add " " & astToStr(field) & " = " & $n.field
|
||||
|
||||
proc toString*(n: VNode; result: var string; indent: int) =
|
||||
for i in 1..indent: result.add ' '
|
||||
if result.len > 0: result.add '\L'
|
||||
result.add "<" & $n.kind
|
||||
toStringAttr(id)
|
||||
toStringAttr(class)
|
||||
for k, v in attrs(n):
|
||||
result.add " " & $k & " = " & $v
|
||||
result.add ">\L"
|
||||
if n.kind == VNodeKind.text:
|
||||
result.add n.text
|
||||
else:
|
||||
if n.text != nil:
|
||||
result.add " value = "
|
||||
result.add n.text
|
||||
for child in items(n):
|
||||
toString(child, result, indent+2)
|
||||
for i in 1..indent: result.add ' '
|
||||
result.add "\L</" & $n.kind & ">"
|
||||
|
||||
proc calcHash*(n: VNode) =
|
||||
if n.validHash: return
|
||||
n.validHash = true
|
||||
var h: Hash = ord n.kind
|
||||
if n.id != nil:
|
||||
h &= "id"
|
||||
h &= n.id
|
||||
if n.class != nil:
|
||||
h &= "class"
|
||||
h &= n.class
|
||||
if n.key >= 0:
|
||||
h &= "k"
|
||||
h &= n.key
|
||||
for k, v in attrs(n):
|
||||
h &= " "
|
||||
h &= k
|
||||
h &= "="
|
||||
h &= v
|
||||
if n.kind == VNodeKind.text or n.text != nil:
|
||||
h &= "t"
|
||||
h &= n.text
|
||||
else:
|
||||
for child in items(n):
|
||||
calcHash(child)
|
||||
h &= child.hash
|
||||
n.hash = h
|
||||
|
||||
proc `$`*(n: VNode): cstring =
|
||||
var res = ""
|
||||
toString(n, res, 0)
|
||||
result = cstring(res)
|
||||
Loading…
Add table
Add a link
Reference in a new issue