Skip to content

Commit

Permalink
eval with callback
Browse files Browse the repository at this point in the history
  • Loading branch information
bung87 committed Sep 20, 2024
1 parent 218a4a1 commit 8603330
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/crowngui/platforms/macos/webview.nim
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# import strutils, base64
import objc_runtime
import darwin / [app_kit,web_kit, foundation, objc/runtime, core_graphics/cggeometry]
import darwin / [app_kit,web_kit, foundation, objc/runtime, objc/blocks, core_graphics/cggeometry]
# import menu
import types
export types
Expand All @@ -17,6 +17,7 @@ import ./utils
import ./app_utils
import ../../types


{.passl: "-framework Cocoa -framework WebKit".}


Expand Down Expand Up @@ -145,6 +146,37 @@ proc addUserScriptAtDocumentEnd*(w: Webview, js: string): void =
proc eval*(w: Webview, js: string): void {.objcr.} =
[w.priv.webview evaluateJavaScript: @js, completionHandler: nil]

proc eval*[T](w: Webview, js: string, cb: proc(res: T): void): void {.objcr.} =
let bl = proc (res:ID; err:ID) =
let isString = cast[bool]([res isKindOfClass:[NSString class]])
let isNumber = cast[bool]([res isKindOfClass:[NSNumber class]])
let isArray = cast[bool]([res isKindOfClass:[NSArray class]])
let isObj = cast[bool]([res isKindOfClass:[NSDictionary class]])
let isNil = res == nil
if err != nil:
let localStr = cast[NSString]([err valueForKey: "localizedDescription"])
raise newException(CatchableError, $localStr)
when T is string:
if isString:
let str = $cast[NSString](res)
cb(str)
else:
raise newException(ValueError, "type mismatched")
elif T is bool:
if isNumber:
if strcmp([res objCType], @encode(BOOL)) == 0:
let v = cast[bool]([res boolValue])
cb(v)
else:
raise newException(ValueError, "type mismatched")
else:
raise newException(ValueError, "type mismatched")
else:
# TODO:
discard

[w.priv.webview evaluateJavaScript: @js, completionHandler: toBlock(bl)]

proc setTitle*(w: Webview; title: string) {.objcr.} =
[w.priv.window setTitle: @title]

Expand Down

0 comments on commit 8603330

Please sign in to comment.