diff options
| author | bptato <nincsnevem662@gmail.com> | 2024-11-15 17:06:53 +0100 |
|---|---|---|
| committer | bptato <nincsnevem662@gmail.com> | 2024-11-15 17:06:53 +0100 |
| commit | def4ceccfb77afd74b1dd1273b66d036b766fd5f (patch) | |
| tree | 8fb976f0ebe632029afe2ee9542d31b88e4f23d1 /src/js | |
| parent | fd10019d8b8a1b5dcb0026521fa8f5f072c3a10a (diff) | |
| download | chawan-def4ceccfb77afd74b1dd1273b66d036b766fd5f.tar.gz | |
js: reorganize modules, update docs
most of it has already been moved to monoucha, and the rest fits better
in other directories.
also, move urimethodmap to config
Diffstat (limited to 'src/js')
| -rw-r--r-- | src/js/console.nim | 84 | ||||
| -rw-r--r-- | src/js/domexception.nim | 55 | ||||
| -rw-r--r-- | src/js/encoding.nim | 100 | ||||
| -rw-r--r-- | src/js/intl.nim | 66 | ||||
| -rw-r--r-- | src/js/jscolor.nim | 56 | ||||
| -rw-r--r-- | src/js/jsmodule.nim | 27 | ||||
| -rw-r--r-- | src/js/timeout.nim | 137 |
7 files changed, 0 insertions, 525 deletions
diff --git a/src/js/console.nim b/src/js/console.nim deleted file mode 100644 index 755910a5..00000000 --- a/src/js/console.nim +++ /dev/null @@ -1,84 +0,0 @@ -import io/dynstream -import monoucha/fromjs -import monoucha/javascript -import types/opt - -type Console* = ref object - err*: DynStream - clearFun: proc() - showFun: proc() - hideFun: proc() - -jsDestructor(Console) - -proc newConsole*(err: DynStream; clearFun: proc() = nil; showFun: proc() = nil; - hideFun: proc() = nil): Console = - return Console( - err: err, - clearFun: clearFun, - showFun: showFun, - hideFun: hideFun - ) - -proc log*(console: Console; ss: varargs[string]) = - var buf = "" - for i, s in ss: - buf &= s - if i != ss.high: - buf &= ' ' - buf &= '\n' - console.err.write(buf) - -proc error*(console: Console; ss: varargs[string]) = - console.log(ss) - -proc log*(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void] - {.jsfunc.} = - var buf = "" - for i, val in ss: - var res: string - ?ctx.fromJS(val, res) - buf &= res - if i != ss.high: - buf &= ' ' - buf &= '\n' - console.err.write(buf) - ok() - -proc clear(console: Console) {.jsfunc.} = - if console.clearFun != nil: - console.clearFun() - -# For now, these are the same as log(). -proc debug(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void] - {.jsfunc.} = - return log(ctx, console, ss) - -proc error(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void] - {.jsfunc.} = - return log(ctx, console, ss) - -proc info(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void] - {.jsfunc.} = - return log(ctx, console, ss) - -proc warn(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void] - {.jsfunc.} = - return log(ctx, console, ss) - -proc show(console: Console) {.jsfunc.} = - if console.showFun != nil: - console.showFun() - -proc hide(console: Console) {.jsfunc.} = - if console.hideFun != nil: - console.hideFun() - -proc addConsoleModule*(ctx: JSContext) = - #TODO console should not have a prototype - # "For historical reasons, console is lowercased." - ctx.registerType(Console, nointerface = true, name = "console") - -proc writeException*(ctx: JSContext; s: DynStream) = - s.write(ctx.getExceptionMsg()) - s.sflush() diff --git a/src/js/domexception.nim b/src/js/domexception.nim deleted file mode 100644 index d07e88f4..00000000 --- a/src/js/domexception.nim +++ /dev/null @@ -1,55 +0,0 @@ -import monoucha/javascript -import monoucha/jserror -import monoucha/quickjs -import types/opt - -const NamesTable = { - "IndexSizeError": 1u16, - "HierarchyRequestError": 3u16, - "WrongDocumentError": 4u16, - "InvalidCharacterError": 5u16, - "NoModificationAllowedError": 7u16, - "NotFoundError": 8u16, - "NotSupportedError": 9u16, - "InUseAttributeError": 10u16, - "InvalidStateError": 11u16, - "SyntaxError": 12u16, - "InvalidModificationError": 13u16, - "NamespaceError": 14u16, - "InvalidAccessError": 15u16, - "TypeMismatchError": 17u16, - "SecurityError": 18u16, - "NetworkError": 19u16, - "AbortError": 20u16, - "URLMismatchError": 21u16, - "QuotaExceededError": 22u16, - "TimeoutError": 23u16, - "InvalidNodeTypeError": 24u16, - "DataCloneError": 25u16 -} - -type - DOMException* = ref object of JSError - name* {.jsget.}: string - code {.jsget.}: uint16 - - DOMResult*[T] = Result[T, DOMException] - -jsDestructor(DOMException) - -proc newDOMException*(message = ""; name = "Error"): DOMException {.jsctor.} = - let ex = DOMException(e: jeDOMException, name: name, message: message) - for it in NamesTable: - if it[0] == name: - ex.code = it[1] - break - return ex - -template errDOMException*(message, name: string): untyped = - err(newDOMException(message, name)) - -func message0(this: DOMException): string {.jsfget: "message".} = - return this.message - -proc addDOMExceptionModule*(ctx: JSContext) = - ctx.registerType(DOMException, JS_CLASS_ERROR, errid = opt(jeDOMException)) diff --git a/src/js/encoding.nim b/src/js/encoding.nim deleted file mode 100644 index 7aae5eb2..00000000 --- a/src/js/encoding.nim +++ /dev/null @@ -1,100 +0,0 @@ -import chagashi/charset -import chagashi/decoder -import monoucha/javascript -import monoucha/jserror -import monoucha/jstypes -import monoucha/quickjs -import types/opt - -type - JSTextEncoder = ref object - - JSTextDecoder = ref object - encoding: Charset - ignoreBOM {.jsget.}: bool - errorMode: DecoderErrorMode - stream: bool - bomSeen: bool - tdctx: TextDecoderContext - -jsDestructor(JSTextDecoder) -jsDestructor(JSTextEncoder) - -type TextDecoderOptions = object of JSDict - fatal {.jsdefault.}: bool - ignoreBOM {.jsdefault.}: bool - -func newJSTextDecoder(label = "utf-8"; options = TextDecoderOptions()): - JSResult[JSTextDecoder] {.jsctor.} = - let encoding = getCharset(label) - if encoding in {CHARSET_UNKNOWN, CHARSET_REPLACEMENT}: - return errRangeError("Invalid encoding label") - let errorMode = if options.fatal: demFatal else: demReplacement - return ok(JSTextDecoder( - ignoreBOM: options.ignoreBOM, - errorMode: errorMode, - tdctx: initTextDecoderContext(encoding, errorMode), - encoding: encoding - )) - -func fatal(this: JSTextDecoder): bool {.jsfget.} = - return this.errorMode == demFatal - -type TextDecodeOptions = object of JSDict - stream {.jsdefault.}: bool - -#TODO AllowSharedBufferSource -proc decode(ctx: JSContext; this: JSTextDecoder; - input = none(JSArrayBufferView); options = TextDecodeOptions()): JSValue - {.jsfunc.} = - if not this.stream: - this.tdctx = initTextDecoderContext(this.encoding, this.errorMode) - this.bomSeen = false - this.stream = options.stream - if input.isSome: - let input = input.get - let H = int(input.abuf.len) - 1 - var oq = "" - let stream = this.stream - for chunk in this.tdctx.decode(input.abuf.p.toOpenArray(0, H), not stream): - oq &= chunk - if this.tdctx.failed: - this.tdctx.failed = false - return JS_ThrowTypeError(ctx, "failed to decode string") - return JS_NewStringLen(ctx, cstring(oq), csize_t(oq.len)) - return JS_NewString(ctx, "") - -func jencoding(this: JSTextDecoder): string {.jsfget: "encoding".} = - return $this.encoding - -func newTextEncoder(): JSTextEncoder {.jsctor.} = - return JSTextEncoder() - -func jencoding(this: JSTextEncoder): string {.jsfget: "encoding".} = - return "utf-8" - -proc dealloc_wrap(rt: JSRuntime; opaque, p: pointer) {.cdecl.} = - dealloc(p) - -proc encode(this: JSTextEncoder; input = ""): JSUint8Array {.jsfunc.} = - # we have to validate input first :/ - #TODO it is possible to do less copies here... - var input = input.toValidUTF8() - let buf = cast[ptr UncheckedArray[uint8]](alloc(input.len)) - copyMem(buf, addr input[0], input.len) - let abuf = JSArrayBuffer( - p: buf, - len: csize_t(input.len), - dealloc: dealloc_wrap - ) - return JSUint8Array( - abuf: abuf, - offset: 0, - nmemb: csize_t(input.len) - ) - -#TODO encodeInto - -proc addEncodingModule*(ctx: JSContext) = - ctx.registerType(JSTextDecoder, name = "TextDecoder") - ctx.registerType(JSTextEncoder, name = "TextEncoder") diff --git a/src/js/intl.nim b/src/js/intl.nim deleted file mode 100644 index b980fb90..00000000 --- a/src/js/intl.nim +++ /dev/null @@ -1,66 +0,0 @@ -# Very minimal Intl module... TODO make it more complete - -import monoucha/javascript -import monoucha/jstypes -import monoucha/quickjs -import monoucha/tojs - -type - NumberFormat = ref object - - PluralRules = ref object - - PRResolvedOptions = object of JSDict - locale: string - -jsDestructor(NumberFormat) -jsDestructor(PluralRules) - -#TODO ...yeah -proc newNumberFormat(name: string = "en-US"; options = none(JSValue)): - NumberFormat {.jsctor.} = - return NumberFormat() - -#TODO -proc newPluralRules(): PluralRules {.jsctor.} = - return PluralRules() - -proc resolvedOptions(this: PluralRules): PRResolvedOptions {.jsfunc.} = - return PRResolvedOptions( - locale: "en-US" - ) - -#TODO: this should accept string/BigInt too -proc format(nf: NumberFormat; num: float64): string {.jsfunc.} = - let s = $num - var i = 0 - var L = s.len - for k in countdown(s.high, 0): - if s[k] == '.': - L = k - break - if L mod 3 != 0: - while i < L mod 3: - result &= s[i] - inc i - if i < L: - result &= ',' - let j = i - while i < L: - if j != i and i mod 3 == j: - result &= ',' - result &= s[i] - inc i - if i + 1 < s.len and s[i] == '.': - if not (s[i + 1] == '0' and s.len == i + 2): - while i < s.len: - result &= s[i] - inc i - -proc addIntlModule*(ctx: JSContext) = - let global = JS_GetGlobalObject(ctx) - let intl = JS_NewObject(ctx) - ctx.registerType(NumberFormat, namespace = intl) - ctx.registerType(PluralRules, namespace = intl) - ctx.defineProperty(global, "Intl", intl) - JS_FreeValue(ctx, global) diff --git a/src/js/jscolor.nim b/src/js/jscolor.nim deleted file mode 100644 index 20f04b0a..00000000 --- a/src/js/jscolor.nim +++ /dev/null @@ -1,56 +0,0 @@ -import std/strutils - -import monoucha/fromjs -import monoucha/javascript -import monoucha/quickjs -import monoucha/tojs -import types/color -import types/opt -import utils/twtstr - -func parseLegacyColor*(s: string): Result[RGBColor, cstring] = - if s == "": - return err(cstring"color value must not be the empty string") - let s = s.strip(chars = AsciiWhitespace).toLowerAscii() - if s == "transparent": - return err(cstring"color must not be transparent") - return ok(parseLegacyColor0(s)) - -proc toJS*(ctx: JSContext; rgb: RGBColor): JSValue = - var res = "#" - res.pushHex(rgb.r) - res.pushHex(rgb.g) - res.pushHex(rgb.b) - return toJS(ctx, res) - -proc fromJS*(ctx: JSContext; val: JSValue; res: var RGBColor): Err[void] = - var s: string - ?ctx.fromJS(val, s) - let x = parseLegacyColor(s) - if x.isNone: - JS_ThrowTypeError(ctx, x.error) - return err() - res = x.get - return ok() - -proc toJS*(ctx: JSContext; rgba: ARGBColor): JSValue = - var res = "#" - res.pushHex(rgba.r) - res.pushHex(rgba.g) - res.pushHex(rgba.b) - res.pushHex(rgba.a) - return toJS(ctx, res) - -proc fromJS*(ctx: JSContext; val: JSValue; res: var ARGBColor): Err[void] = - if JS_IsNumber(val): - # as hex - ?ctx.fromJS(val, uint32(res)) - return ok() - # parse - var s: string - ?ctx.fromJS(val, s) - if (let x = parseARGBColor(s); x.isSome): - res = x.get - return ok() - JS_ThrowTypeError(ctx, "unrecognized color") - return err() diff --git a/src/js/jsmodule.nim b/src/js/jsmodule.nim deleted file mode 100644 index cdb836e6..00000000 --- a/src/js/jsmodule.nim +++ /dev/null @@ -1,27 +0,0 @@ -import monoucha/constcharp -import monoucha/javascript -import monoucha/quickjs -import monoucha/tojs - -proc setImportMeta(ctx: JSContext; funcVal: JSValue; isMain: bool) = - let m = cast[JSModuleDef](JS_VALUE_GET_PTR(funcVal)) - let moduleNameAtom = JS_GetModuleName(ctx, m) - let metaObj = JS_GetImportMeta(ctx, m) - definePropertyCWE(ctx, metaObj, "url", JS_AtomToValue(ctx, moduleNameAtom)) - definePropertyCWE(ctx, metaObj, "main", isMain) - JS_FreeValue(ctx, metaObj) - JS_FreeAtom(ctx, moduleNameAtom) - -proc finishLoadModule*(ctx: JSContext; f: string; name: cstring): JSModuleDef = - let funcVal = compileModule(ctx, f, $name) - if JS_IsException(funcVal): - return nil - setImportMeta(ctx, funcVal, false) - # "the module is already referenced, so we must free it" - # idk how this works, so for now let's just do what qjs does - result = cast[JSModuleDef](JS_VALUE_GET_PTR(funcVal)) - JS_FreeValue(ctx, funcVal) - -proc normalizeModuleName*(ctx: JSContext; base_name, name: cstringConst; - opaque: pointer): cstring {.cdecl.} = - return js_strdup(ctx, cstring(name)) diff --git a/src/js/timeout.nim b/src/js/timeout.nim deleted file mode 100644 index 6c905836..00000000 --- a/src/js/timeout.nim +++ /dev/null @@ -1,137 +0,0 @@ -import std/algorithm -import std/times - -import io/dynstream -import js/console -import monoucha/fromjs -import monoucha/javascript -import monoucha/jsutils -import types/opt - -type - TimeoutType* = enum - ttTimeout = "setTimeout handler" - ttInterval = "setInterval handler" - - TimeoutEntry = ref object - t: TimeoutType - id: int32 - val: JSValue - args: seq[JSValue] - expires: int64 - timeout: int32 - dead: bool - - EvalJSFree* = proc(opaque: RootRef; src, file: string) {.nimcall.} - - TimeoutState* = ref object - timeoutid: int32 - sorted: bool - timeouts: seq[TimeoutEntry] - jsctx: JSContext - evalJSFree: EvalJSFree - opaque: RootRef - -func newTimeoutState*(jsctx: JSContext; evalJSFree: EvalJSFree; - opaque: RootRef): TimeoutState = - return TimeoutState( - jsctx: jsctx, - evalJSFree: evalJSFree, - opaque: opaque, - sorted: true - ) - -func empty*(state: TimeoutState): bool = - return state.timeouts.len == 0 - -proc clearTimeout0(state: var TimeoutState; i: int) = - let entry = state.timeouts[i] - JS_FreeValue(state.jsctx, entry.val) - for arg in entry.args: - JS_FreeValue(state.jsctx, arg) - state.timeouts.del(i) - if state.timeouts.len != i: # only set if we del'd in the middle - state.sorted = false - -proc clearTimeout*(state: var TimeoutState; id: int32) = - for entry in state.timeouts: - if entry.id == id: - entry.dead = true - break - -proc getUnixMillis*(): int64 = - let now = getTime() - return now.toUnix() * 1000 + now.nanosecond div 1_000_000 - -proc setTimeout*(state: var TimeoutState; t: TimeoutType; handler: JSValue; - timeout: int32; args: openArray[JSValue]): int32 = - let id = state.timeoutid - inc state.timeoutid - let entry = TimeoutEntry( - t: t, - id: id, - val: JS_DupValue(state.jsctx, handler), - expires: getUnixMillis() + int64(timeout), - timeout: timeout - ) - for arg in args: - entry.args.add(JS_DupValue(state.jsctx, arg)) - state.timeouts.add(entry) - state.sorted = false - return id - -proc runEntry(state: var TimeoutState; entry: TimeoutEntry; err: DynStream) = - if JS_IsFunction(state.jsctx, entry.val): - let ret = JS_Call(state.jsctx, entry.val, JS_UNDEFINED, - cint(entry.args.len), entry.args.toJSValueArray()) - if JS_IsException(ret): - state.jsctx.writeException(err) - JS_FreeValue(state.jsctx, ret) - else: - var s: string - if state.jsctx.fromJS(entry.val, s).isSome: - state.evalJSFree(state.opaque, s, $entry.t) - -# for poll -proc sortAndGetTimeout*(state: var TimeoutState): cint = - if state.timeouts.len == 0: - return -1 - if not state.sorted: - state.timeouts.sort(proc(a, b: TimeoutEntry): int = - cmp(a.expires, b.expires), order = Descending) - state.sorted = true - let now = getUnixMillis() - return cint(max(state.timeouts[^1].expires - now, -1)) - -proc run*(state: var TimeoutState; err: DynStream): bool = - let now = getUnixMillis() - var found = false - var H = state.timeouts.high - for i in countdown(H, 0): - if state.timeouts[i].expires > now: - break - let entry = state.timeouts[i] - if entry.dead: - continue - state.runEntry(entry, err) - found = true - case entry.t - of ttTimeout: - entry.dead = true - of ttInterval: - entry.expires = now + entry.timeout - state.sorted = false - # we can't just delete timeouts in the above loop, because the JS - # timeout handler may clear them in an arbitrary order - H = state.timeouts.high - for i in countdown(H, 0): - if state.timeouts[i].dead: - state.clearTimeout0(i) - return found - -proc clearAll*(state: var TimeoutState) = - for entry in state.timeouts: - JS_FreeValue(state.jsctx, entry.val) - for arg in entry.args: - JS_FreeValue(state.jsctx, arg) - state.timeouts.setLen(0) |