All notable changes to CrootJS. Versions are git tags, served by jsDelivr as https://cdn.jsdelivr.net/gh/crootjs/lib@<version>/<module>.js; each is also a GitHub release.
Our own .min.css files, with SRI hashes
croot.min.css, ui.min.css, themes.min.css and icons.min.css are now built by tools/build-min.py with lightningcss (pinned, with source maps) and shipped in the release commit, like .min.js. Up to 0.0.42 jsDelivr minified them on request, so their content could change whenever jsDelivr updated its minifier, and no SRI hash could be published. Same URLs as before..min.css files. Stylesheets with integrity need crossorigin="anonymous". bump-pins.py says so when a .min.css is missing from an older integrity.json.croot.min.css 2.19 vs 2.39 KB, ui.min.css 3.02 vs 3.24 KB, themes.min.css 1.19 vs 1.38 KB, icons.min.css 1.88 vs 2.46 KB. Computed styles of every element (and ::before, ::after, ::marker) on the nine page patterns are identical to the unminified .css in Chromium, Firefox and WebKit, in light and dark mode and with every theme; only the raw text of custom properties differs (--croot-bg: #fff instead of #ffffff).SRI hashes in every release, and bump-pins.py for your own project
integrity.json: the sha384 SRI hash of each .js, .min.js and .css file in the tag, and the modules each module imports (static, and yaml/markdown for openapi). jsDelivr serves tag files byte for byte, so the hashes match what browsers download; .min.css is not included because jsDelivr minifies it itself. The modules are unchanged from 0.0.41.integrity on <link rel="modulepreload"> is enforced only by Chromium; Firefox and Safari still run a changed module loaded by import. All three enforce an import map with an integrity key, which also covers imports inside modules. The docs show how to install it from integrity.js, a classic script loaded first in <head> (Firefox ignores an import map added after module loading started), the one exception to the ES module convention. The landing page uses it.python3 bump-pins.py <version|latest> [folder] bumps every crootjs/lib@x.y.z in .html, .js, .md, .txt and .json files, and fills or updates every integrity next to a CrootJS URL (attributes and import map entries, empty values too) from integrity.json, or from the downloaded files for older versions. Nothing is written when a hash can’t be fetched; modules missing from an import map are reported. Python 3 only, no packages. The docs include a workflow that opens a pull request for each new version.modulepreload lines include integrity.ui.css, themes.css and tabs.js: app components, four themes, and page patterns
@layer croot.ui after croot.css: an app shell whose sidebar is a column on wide screens and a popover drawer on phones (no JavaScript), breadcrumb, tabs, <details> and popover menus, toggletips, .actions, an exclusive accordion (<details name>), skeleton (still with reduced motion), summary numbers (.stats), status badges, avatar, switch (role="switch" checkbox), steps (ol.steps, earlier steps marked done with :has()), button group, empty state, toolbar, scrollable table wrapper, description list (dl.meta, container query), and footer.<html data-croot-theme>: kampus, kertas, kontras, niaga, each in light and dark (following the system or data-theme), every text/background pair at least WCAG AA, no web fonts; about 1.2 KB gzipped. New token --croot-heading-font.initTabs(id): ARIA tabs with roving tabindex, arrow keys (reversed in right-to-left pages), Home/End; returns { select(index), remove() }.<div> and positioned inside the chart: a table ignores width: 1px, so with large type it made phone pages a few pixels too wide.fieldset has min-width: 0, so a file input no longer pushes it off a phone screen.Release commits on the dist branch, modulepreload lists, paused results
.min.js files) are now on the dist branch instead of belonging to no branch; the first one also takes in the 0.0.38 and 0.0.39 release commits. main stays source only. Pin to a tag (@0.0.40) or a dist commit, not to a commit SHA from main: for those jsDelivr minifies on its own and api.min.js imports "./storage.js" again.staleIfError is off), the result has paused: true and cached: false. In 0.0.38 and 0.0.39 it said cached: true, although no data came from the cache.<link rel="modulepreload"> lines; the docs now show the list. Without preloading, every level of imports adds one round trip (about 150 ms on mobile networks); on the landing page preloading moves the first API request about 300 ms earlier.paused?: boolean.api.js: rewrap the getJSON comment; regenerate crootjs.d.ts (0.0.38 shipped a stale comment)
api.js..min.js files that import .min.js, typed api.js options, rate-limit pause for first visitors
.min.js files (and source maps), built with Terser by tools/build-min.py, whose relative imports point to the .min.js of their sibling modules. Up to 0.0.37 jsDelivr minified on request but kept the import paths, so api.min.js imported "./storage.js": a page using api.min.js and storage.min.js loaded two copies of storage (each with its own state), and mapmodel.min.js loaded model3d.js next to a page’s model3d.min.js, so a viewer created through one copy was unknown to the other. 13 modules have relative imports. The .min.js files live only in the tag’s commit; main holds the source. Don’t mix .js and .min.js on one page.getJSON, postJSON, putJSON, deleteJSON, uploadFile and downloadFile have typed options (CrootJS.GetOptions, CrootJS.CacheOptions, CrootJS.RequestOptions, CrootJS.UploadOptions, CrootJS.DownloadOptions), overloads for the options-object and token forms, and a type parameter for data (getJSON<T>(); with cache.select it is inferred). "nofile" is only in uploadFile’s error type and "select" only in getJSON’s.403/429 with Retry-After (or X-RateLimit-Reset when the quota is 0) sends no more requests to that URL until then; the result is that status with data: null, cached: true and a Retry-After header with the seconds left. With stored data and staleIfError the stored data is returned as before; without staleIfError the pause now applies too..min.js files.getJSON cache fixes: callbacks always asynchronous, select errors, rate-limit pause
getJSON is always called after the code that follows the call, also when the data comes from the cache (before, a cache hit called it immediately, so getJSON(url, hideSpinner, { cache }); showSpinner(); left the spinner on). The same for uploadFile without a file (error: "nofile").cache.select is reported as error: "select" with the server’s real status and data: null, logged with console.error, not stored, and not hidden by staleIfError. Before, it was reported as a network failure (status: 0, error: "network").select produced them; after select changes, old entries are ignored instead of being kept alive by 304 answers.staleReason: the failed HTTP status (e.g. 403) or the network failure ("network", "timeout", "offline").staleIfError, a 403 or 429 that says when to retry (Retry-After, or X-RateLimit-Reset when X-RateLimit-Remaining is 0, as GitHub sends) pauses requests until then (at most one hour): the stored data is returned without a request, with stale: true and staleReason set to that status.503 for missing files, so tests no longer expect exactly 404 there.openapi.js: API documentation without Swagger UI, and yaml.js
renderOpenAPI(id, source, options) shows API documentation from an OpenAPI 3.0/3.1 file (YAML or JSON) or object, replacing Swagger UI (about 11 KB gzipped instead of about 460 KB). Operations grouped by tag, filterable, deep-linkable (#operationId), built when first opened; parameters, request bodies, responses, schema trees (local $ref with cycles shown, allOf merged, oneOf/anyOf), and examples from the spec or generated from the schema. Every operation shows ready-to-copy CrootJS code (getJSON, postJSON, putJSON, deleteJSON, uploadFile; fetch for PATCH and other methods) importing api.js from the same jsDelivr version, and a “Try it” form that sends real requests (bearer, OAuth2/OIDC as bearer, apiKey in header or query; tokens in memory only; CORS failures explained). Options tryIt, snippets, server, expand, timeout, texts, onError. Also loadOpenAPI(source, options) → { spec, error, message } and openAPIExample(schema, spec, direction). Markdown descriptions use markdown.js and YAML uses yaml.js, both downloaded only when needed. Swagger 2.0, external $ref files, per-operation servers, webhooks, HTTP basic and cookie apiKey are not supported.parseYAML(text): a small YAML 1.2 parser (core schema) with block and flow collections, quoted and block scalars, comments, anchors and aliases. Unsupported features (<< merge keys, custom tags, complex keys, several documents, duplicate keys, tab indentation) throw a SyntaxError with the line number. Nesting is limited and __proto__ keys can’t change prototypes.getJSON cache: stale data on failure, entries tied to their URL, select
cache.staleIfError: true: when the request after ttl fails (network down, timeout, or a non-2xx status such as 403 when the GitHub API quota is used up), getJSON returns the stored data with its stored status, cached: true and stale: true instead of an error. A request aborted through signal still gives error: "abort". Before, the stored data was there but not used.key for a different URL is ignored instead of being returned until ttl runs out. Entries stored by 0.0.34 and older have no URL, so the first request after upgrading goes to the server once.cache.select: data => subset trims a 2xx answer before it is stored and returned, so localStorage holds only the fields that are used (a GitHub release answer is about 10 KB).304 answer still counts against the unauthenticated GitHub API quota; only ttl saves requests. Cross-origin ETag revalidation needs Access-Control-Expose-Headers: ETag, which api.github.com and jsDelivr send and GitHub Pages and raw.githubusercontent.com don’t. ttl is in seconds, like setLocalWithExpireSecond.stale?: boolean.toast.js is announced by screen readers and readable in dark mode
aria-live="polite" region and error toasts have role="alert", so screen readers announce them (before, nothing was announced). Toasts shown right after the container is created wait 100 ms, in order, so the new live region is picked up first. Colors now come from croot.css (--croot-success, --croot-danger, --croot-warning, --croot-info, text --croot-accent-text), with the croot.css light values as fallback: the old green, red and blue had white text below the WCAG AA contrast of 4.5:1 (3.0, 3.9 and 4.0), and with croot.css the toasts follow dark mode. The <style> is inserted at the start of <head>, so project CSS overrides it without extra specificity. Animation is off with prefers-reduced-motion, and toasts fit screens narrower than 392px.version.json (served at https://croot.js.org/lib/version.json) instead of sending a repository dispatch; docs, examples and the landing page check it every hour and bump their own pins.Dashboard modules (router, table, chart, icons), markdown, QR codes, PWA, and auth.js without third-party scripts
startRouter(routes, options) for single-page apps: hash mode (default, works on GitHub Pages) or history mode with base; patterns like /mahasiswa/:id, ctx.query (URLSearchParams), a notFound view. A view is a function (may be async, returns HTML or a Node), a URL of an HTML fragment, or { html, run }. When the user navigates again before an async view finishes, its ctx.signal is aborted and its result ignored. History mode intercepts internal <a> clicks. After each navigation focus moves to the first <h1>, the title is announced through role="status", and matching nav links get aria-current="page". Returns { navigate, href, current, stop }.createTable(id, options), a replacement for jQuery DataTables: a real <table> from column definitions and rows, sorting per column (aria-sort, Indonesian natural order with Intl.Collator), search, pagination with selectable page size, and a row count announced to screen readers. Cells are always text or Nodes, never HTML. Server mode through source({ page, pageSize, sort, query }) → { rows, total }, with debounced search and late responses dropped.createChart(id, config) → { element, update, remove }, plus niceScale. Round-number axes, Indonesian number format, width follows the container, a palette (--croot-chart-1..8) that keeps 3:1 contrast in croot.css light and dark mode, role="img" with title and description, a data table for screen readers, legend, and tooltips on hover and on keyboard focus.<span class="icon icon-home" aria-hidden="true">. Color follows currentColor, size is 1em; SVG data URIs as mask-image, so they work cross-origin from jsDelivr. In @layer croot.icons.markdownToHTML, renderMarkdown, getMarkdown: a CommonMark/GFM subset (headings, emphasis, strikethrough, code, quotes, nested and task lists, tables, links, images) that is safe by design: all raw HTML is escaped, URLs are limited to http(s), mailto, tel, relative and #anchor, and malicious input runs in linear time. getMarkdown returns a Promise that never rejects.qrSVG, renderQR, qrMatrix: QR codes written from scratch (byte mode, UTF-8, versions 1-40 chosen automatically, levels L/M/Q/H) as a single-path SVG. Output tested identical to python-qrcode at sample sizes from version 1 to 40 at all four levels.registerServiceWorker (Promise that never rejects, https/localhost only, a “new version” notice with reload), onNetworkChange, isStandalone, installButton. serviceworker.js is a classic script for importScripts in an sw.js on your own domain: crootjsServiceWorker({ version, precache, offlinePage, maxEntries, networkTimeout }) with a versioned precache, network-first navigation with cache and offline-page fallback, stale-while-revalidate for own assets, and cache-first for exact-version jsDelivr files. Non-GET requests, page fetch()/XHR and other domains are not touched.qr.js instead of an unversioned Skypack package, and SweetAlert2 (@11, no exact version) is replaced by a native <dialog>. The Google Sign-In login sent the wrong arguments to postJSON (the body was the string "login" and the callback was the cookie value), so it could never log in; fixed. A network failure now shows a message instead of being swallowed. The login token is no longer written to the console. The refresh and mobile login controls are a real <button> and <a>.refreshbutton and loginbutton no longer contain onclick or inline styles; loginbutton no longer has the ##URL## placeholder. Wrap them in your own <button>/<a> (auth.js does).align="center"/"right" on th/td is respected (markdown.js tables use it instead of inline styles).--croot-danger, so it is readable in croot.css dark mode.croot.min.css is minified again
@property rules, so croot.min.css from 0.0.31 was served unminified (about 3.3 KB gzipped instead of 2.1 KB). --croot-gap and --croot-min are now kept from passing down to child elements by resetting them on every element inside the layer, with the same result: a value set on one element doesn’t change nested .grid/.stack spacing..min.js and croot.min.css is requested from jsDelivr once, and any that answers 404 (a stale cache from requests made before the tag existed, as happened with storage.min.js for 0.0.31) is purged and checked again.croot.css: a small, green CSS framework
croot.min.css). Plain HTML looks finished without classes: headings, text, links, code, tables, forms (inputs, selects, fieldsets, aria-invalid), buttons (.secondary, .danger, .ghost, and .button for links), <dialog>, <details>, progress. Layout classes .container, .stack, .cluster, .grid (auto-fitting columns), plus .card, .badge, .alert (.success, .warning, .danger), .nav, .muted, .center, .visually-hidden. Dark mode follows the device or data-theme="light"/"dark" on <html>; colors and spacing are --croot-* variables; prefers-reduced-motion is respected. Everything sits in @layer croot, so a page’s own CSS always wins without !important; --croot-gap and --croot-min are registered as non-inherited so nested layouts keep their own spacing.tools/bump-pins.sh).Uploads with progress, form validation, offline tile cache, vector PMTiles, keyboard drawing, 3D measuring and in-page AR
uploadFile (multipart upload from an input id, File/Blob, FileList or FormData; onProgress, idle timeout, signal, extra data fields) and downloadFile (Blob for 2xx, optional fileName to save), both with the same { status, data, headers, error } result as getJSON and awaitable. New signal option on all JSON functions to cancel a request (error: "abort", no console warning). The older file helpers keep their behavior.handleForm, validateForm, clearFormErrors: messages under each invalid field from the HTML attributes (required, type, minlength, pattern, …) plus custom rules, Indonesian default messages, aria-invalid and aria-describedby, focus on the first invalid field.fillForm(id, data), the counterpart of serializeForm. serializeForm now returns arrays for several checkboxes with the same name and for <select multiple> (previously the last checkbox overwrote the others and only the first selected option was read).element.js: getValueSelect/getTextSelect always threw a TypeError (they now find the <select> by id, or by name), and getValueRadio no longer logs every radio to the console. cookie.js: getCookie decoded twice, so values with ; were cut and values with % threw; names with spaces were never found. url.js: folderPath kept /js/app.min.js unchanged and turned /v1.2/page into /; it now strips only a last segment that contains a dot.cachedTiles(template): every basemap tile that was viewed is kept in Cache Storage and shown when offline; downloadArea for own tile servers (refused for tile.openstreetmap.org, whose policy forbids bulk downloads).language for local place names, custom styles, and sharp overzoom above the file’s max zoom. Attribution from PMTiles metadata is converted from HTML to text.attribution, and one whose url is the OpenStreetMap server gets the OSM attribution automatically.measureModel (distance or angle between points on the model surface) and in-page AR with WebXR: isARSupported, startAR (surface preview, tap to place, real size), and addARButton(..., { webxr: true }). startAR was tested with a simulated WebXR session, not yet on an AR device.api.js options and response headers, storage.js survives blocked storage
Based on feedback from using api.js and storage.js on a static landing page.
getJSON/postJSON/putJSON/deleteJSON send Content-Type: application/json only when there is a body, so a plain getJSON no longer triggers a CORS preflight and works against static hosts. The argument after responseFunction may be an options object { headers, timeout, cache } (the tokenkey, tokenvalue pair still works). Results also carry headers (the response Headers), error ("timeout", "offline" or "network" when status is 0) and cached. cache: { key, ttl } on getJSON keeps successful results in localStorage for ttl seconds, then revalidates with If-None-Match; a 304 returns the stored data with its stored status (200) and cached: true. Failures in every api.js function are logged with console.warn instead of console.log.null, setters return false (true when saved), with one console warning.blob:).PMTiles on servers that break HTTP Range
.pmtiles files and cuts ranges from the compressed bytes, so browsers reject or corrupt the pieces; the 0.0.27 offline example failed live because of it. When a Range request fails or returns the wrong length, the file is now downloaded whole once and read from memory, with a console warning. Covered by a new test that simulates such a server.Address search, offline PMTiles maps, 3D models on the map, skinning, Draco, AR, English docs
searchPlace, reverseGeocode and addSearchControl: place and address search with OpenStreetMap’s Nominatim (rate-limited to 1 request per second, search on Enter only, OSM attribution under the results) or your own server/provider.openPMTiles(url | File): a basemap from one PMTiles v3 raster file, read with HTTP Range requests from a static host, or from a file on the device with no internet. Checked against the official PMTiles sample.addModel: a glTF/GLB model at its coordinates on the map, true to scale in meters, with heading, pitch, click (8 px tolerance) and a minZoom. Re-exports model3d.js.tiles (and labels) also accept an object { getTile(z, x, y) } returning a Blob, URL or null.KHR_draco_mesh_compression, decoded by Google’s official decoder, downloaded only when needed; dracoDecoder option to self-host it).addARButton and getARLink: “Lihat di AR” opens Google Scene Viewer on Android, or AR Quick Look on iPhone/iPad when a .usdz is given.Map drawing, awaitable api.js, tests and type declarations
tests/index.html, open it through any local server or at https://croot.js.org/lib/tests/), run headless in CI on every push and tag.addDrawControl (tool buttons with hints and Selesai/Hapus titik/Batal for touch), startDrawing, editFeature.getJSON, postJSON, putJSON and deleteJSON also return a Promise of the same { status, data }, so they can be awaited (responseFunction may be null). The Promise never rejects; network failure is still status: 0.tools/build-types.py.exportGLB) are no longer counted in triangles and can no longer be clicked. Found by the new tests.3D animation, exploded view and cross-sections
Tools for interactive 3D learning material.
model3dtools.js
getAnimations(id) and playAnimation(id, nameOrIndex, options) play the animations stored in a glTF file (node translation/rotation/scale; STEP, LINEAR and CUBICSPLINE), with play, pause, stop, seek(seconds) and setSpeed. seek works while paused, for a time slider.explodeModel(id, amount, options) pulls parts away from their center like an assembly drawing; amount 0 to 1 works directly from a slider and 0 restores the exact positions.addSection(id, options) slices the model with a plane (axis, position, flip, color) to show the inside; the cut side cannot be clicked, and the cut face is drawn solid.model3d.js - clip plane support in the shader and in picking; fitView accepts an array of part names.
Example: 3D learning material - anatomy of a BTS tower.
3D model viewer without Three.js
model3d.js (new) - a glTF 2.0 viewer (.glb and .gltf) written from scratch, with no Three.js: its own binary GLB parser, matrix math and shaders, on WebGL2 with an automatic WebGL1 fallback. About 14 KB gzipped.
createViewer(id, options) and loadModel(id, url | File | ArrayBuffer, responseFunction) (also awaitable); the camera fits the model automatically.onModelClick reports the part that was clicked, its path in the node tree and the 3D point.getParts, setPartColor, setPartVisible, highlightPart, getPartTransform / setPartTransform (position, Euler or quaternion rotation, scale).fitView, setCameraView, getCameraView, setAutoRotate.BLEND/MASK), double-sided materials, interleaved and sparse accessors, KHR_materials_unlit, KHR_materials_emissive_strength and KHR_mesh_quantization. Draco/meshopt compressed models fail with a clear message.model3dtools.js (new) - addHotspot (HTML labels pinned to a part or point, dimmed when hidden behind the model), enableTransform (translate/rotate/scale gizmo for mouse and touch, Shift snaps rotation to 15°), and exportGLB / downloadGLB (the edited model, with transforms, colors and hidden parts, as a single .glb).
Examples: 3D model viewer and BTS antenna editor.
Right-click context menu for maps
mapcontrol.js - addContextMenu(id, items, options): a right-click menu for GIS actions. It opens on right-click, a 0.5 s touch long-press (also on iPhone) or Menu/Shift+F10 on the focused map. items may be a function (position, feature) => [...] so the menu changes with what is under the pointer. Items support icons, disabled, danger, separators and submenus, plus built-ins "coordinates" (shows and copies lat, lng), "center", "zoom-in" and "zoom-out". Keyboard navigation, ARIA, dark mode, edge flipping and larger touch targets.
map.js - onMapContextMenu(id, fn) for building your own menu. The browser’s menu is only suppressed while a listener exists, and never inside popups or controls. A tap followed by a long-press no longer zooms the map.
mapheat.js - addGridMap returns cellAt(position), for showing a cell’s value in the context menu.
Heatmaps and coverage grids
mapheat.js (new) - heatmaps and coverage grids from point data (GeoJSON points or [lng, lat, value] arrays), drawn on one canvas above the basemap and below addGeoJSON layers.
addHeatmap(id, data, options) - smooth density, blue to red. Options weight, radius or radiusMeters, max (default: highest density in view), scale (linear/sqrt/log), gradient, opacity, legend. 50,000 points redraw in about 15 ms.addGridMap(id, data, options) - points binned into square or hexagon cells (cellSize in screen pixels, or cellMeters fixed on the ground), each colored by the mean/max/min/sum/count of its values through breaks - an nPerf-style signal coverage map. Clicking a cell shows its value and calls onClick(cell). Optional legend.Both return { setData, setOptions, show, hide, remove }.
maptools.js - exportMapImage includes heatmaps and grids in the PNG.
Wider basemap cards
Reported by the NetDet maps team: “OpenStreetMap” was cut in the middle of the word.
mapcontrol.js - basemap cards are 92 px wide by default (thumbnail 72 px), set by one CSS variable, --crootjs-map-card-width. Names wrap between words and only break a word that cannot fit a line by itself.
Picture-card basemap picker
Requested by the NetDet maps team: a basemap picker like the layer picker in Google Maps / nPerf.
mapcontrol.js - addBasemapControl(id, basemaps, { style: "cards" }) shows the active basemap as a picture card; hovering (mouse) or tapping opens a grid of cards. Card images come from a basemap’s thumbnail, or its own tile at thumbnailCenter/thumbnailZoom, with its label tiles on top. Options trigger, columns (at most 2 on screens up to 640 px), keyboard and ARIA support, and dark mode. The default style stays "list".
New setBasemap(id, nameOrIndex) switches through the map’s picker, keeping it in sync and calling onChange.
Boxed labels in PNG export
Reported by the NetDet maps team: labels with a background box were exported as white text without the box.
maptools.js - exportMapImage draws labels and overlay HTML from their computed CSS: background, border, border-radius, padding, multi-line text, opacity and ::before/::after content, each word where the browser laid it out. text-shadow becomes the halo. Cluster bubbles and the location dot are included too.
All map modules - the injected <style> now goes at the start of <head> instead of the end, so page CSS with the same specificity overrides the map’s defaults without !important.
Canvas renderer, measuring, image overlays and PNG export
The rest of the NetDet maps brief: technical and survey maps.
map.js - canvas renderer and simplification - addGeoJSON(..., { renderer: "canvas" }) draws a layer on one canvas instead of one SVG element per shape; style (including dashes), popups, hoverStyle, tooltips, labels and onMapClick still work. 5,600 lines pan/zoom in less than half the time of SVG. simplify applies Douglas-Peucker per zoom level (a 2,000-point line becomes 36 points at zoom 10). New setZoomRange(id, minZoom, maxZoom).
maptools.js (new) - addMeasureControl / measure (distance and area by clicking points), addImageOverlay (georeferenced images by bounds + rotation, or three corners for rotate/scale/skew), and exportMapImage / downloadMapImage (PNG of the basemap, overlays, SVG and canvas layers, labels, markers, measurements, scale bar and attribution).
mapcontrol.js - addCoordinateControl (cursor coordinates, click to pin and copy, format hook for local grids) and addFullscreenButton (Fullscreen API, full-window fallback on iPhone Safari).
geomeasure.js - createAffineTransform(from, to) fits an affine transform from three or more control points (least squares), with inverse and RMS error: CAD grid or image pixels to [lng, lat] and back.
Named layers, labels and basemap switching
Requested by the NetDet maps team, whose app had to work around these.
map.js - basemaps - maxNativeZoom (overzoom: tiles of that level are scaled up instead of left blank), labels (transparent label tiles over the base tiles, for satellite + labels = hybrid), {s}/{r}/{-y} in tile URLs with a subdomains option, and errorTiles for tiles that fail to load. New setTiles(id, tiles, options) swaps the basemap without recreating the map: layers, markers, the open popup and the view stay, and the old tiles stay until the new ones have loaded, so the map never blinks. Attribution reads “CrootJS |
basemap | layer sources” (attributionPrefix: false drops the CrootJS part). |
map.js - named layers, labels, hover - addGeoJSON options name, minZoom/maxZoom, order, visible, attribution, hoverStyle, tooltip, label + labelOptions. Labels sit at the point, the middle of a line or a polygon’s centroid; colliding labels are hidden, top layer first. New showLayer, hideLayer, setLayerStyle, setLayerOrder, removeLayer, getLayers. Styles gain strokeDasharray, lineCap, lineJoin; fitMap padding may be per side.
mapmarker.js - anchor accepts top, left, right and the four corners, plus offset: [dx, dy].
mapcontrol.js - addBasemapControl (radio list calling setTiles) and addLayerControl (checkboxes for named layers), both with a collapsed mode.
Clustering and live tracking
mapcluster.js (new) - addCluster(id, geojson, options?) draws the Point/MultiPoint features of very large datasets as count bubbles that split as the map zooms in. Grid clustering per zoom level, computed lazily, and only clusters in view get DOM elements, so 100,000 points pan smoothly. Options: radius, color, popup, onClick; returns remove().
mapcontrol.js - live tracking - trackUser(id, responseFunction?, options?) watches the position continuously and returns stop(); the callback gets { position, accuracy, speed, heading, timestamp } on every fix (speed m/s and heading degrees may be null), or null once if permission is denied. The map follows the position (options.follow, default true) until the user pans it manually. addTrackButton(id, responseFunction?, options?, corner?) is a toggle button for it.
map.js - onTap - onTap(element, fn) lets an overlay element handle its own tap: the map does not treat it as a map click and does not close the open popup, while a drag that starts on it still pans the map. The cluster bubbles are built on it.
Map add-ons: markers, controls, measuring, routing
Optional map add-ons, 1-2 KB gzipped each. Add-ons reach the map through element.crootjsMap instead of importing map.js, so a page loading map.min.js never gets a second copy.
addMarker: pin, image icon or your own element, with label, popup and dragging (onDragEnd).addScaleBar, locateUser, addLocateButton.getDistance, getLength, getArea, isInside, getFeaturesAt, getNearest, createCircle (same sphere as Turf.js, so the numbers match).findRoute: shortest route along the LineStrings of your own GeoJSON, computed in the browser, with endpoints snapped to the nearest line.map.js gains onMapMove, getMapBounds, mapToPoint / pointToPosition, and addMapControl for your own element in a map corner.
New module: map.js
map.js (new) - a slippy map written from scratch, with no Leaflet.
{z}/{x}/{y} URL, or none) with GeoJSON drawn as SVG on top.createMap / removeMap, addGeoJSON (style and popup options, returns remove()) / clearMap, fitMap / setMapView / getMapView, onMapClick (position and the clicked feature), showPopup / closePopup.[longitude, latitude], the same order as GeoJSON. Popup text is inserted as text, never HTML.geo.js, so a map page needs a single import.New module: geo.js
geo.js (new) - read GeoJSON from a URL or a local file.
getGeoJSON(url, responseFunction, tokenkey?, tokenvalue?) follows getJSON’s { status, data } callback, but sends no headers unless a token is given, so static hosts like raw.githubusercontent.com work without a CORS preflight. GitHub file-page links are rewritten to their raw URL.readGeoJSONFile(id, responseFunction) reads an <input type="file">; parseGeoJSON(input) validates a string or object.properties. Invalid features are skipped and logged instead of failing the whole file.getBBox, getCenter, getPropertyKeys, getCoordinates and toLatLng for summarising data and feeding a map or table.QR login no longer drops late scans
auth.js - QR login no longer drops late scans - when the QR code rotated, the old socket was closed at the same instant, so a scan sent in the last seconds of a cycle reached a session with nothing behind it and the backend answered “session expired”. The old socket now stays open for wauthparam.graceperiod seconds (default 15) so a late scan still logs in.
A dropped connection (flaky network, backgrounded tab, backend redeploy) is now reported: the QR is swapped for a refresh button, rotation stops, and the new optional wauthparam.onconnectionlost callback is called. Also fixes a socket that rotated before its handshake finished and was never closed.
Error callback for insertHTML and renderHTML
Both functions only had a success callback, so after v0.0.10 a failed load no longer hung but the caller still could not detect it. An optional last parameter has been added:
insertHTML(url, id, runFunction, errorFunction)
renderHTML(id, url, callback, errorCallback)
It is called with an Error when the element does not exist, the reply is non-2xx, the network fails, or the request times out. On failure the element is left unchanged and the success callback is not called. Existing three-argument calls keep working and log failures as before.
An exception thrown inside your own success callback is not reported to the error callback, so a bug in your code is not mistaken for a failed load.
Behavior change: insertHTML now treats a non-2xx reply as a failure. It previously injected the server’s error page, a 404 page for example, into the element and then called runFunction as if the load had succeeded. renderHTML already behaved this way.
Docs: https://croot.js.org/docs/api/ and https://croot.js.org/docs/element/
Failure handling for the remaining api.js and element.js requests
v0.0.9 only covered the four JSON functions. Every other network call in the library had the same problem.
postFile, postFileWithHeader, postFileJSON: a network failure was only logged, and JSON.parse threw on a non-JSON reply. Either way the callback never fired. They now call back with null, or {status: 0, data: null} for postFileJSON.getFileBytesWithHeader: on a 200 reply it read response.arrayBuffer() and then discarded it, so the function never delivered file bytes to anyone. It now passes the ArrayBuffer to the callback.getFileWithHeader and getFileBytesWithHeader: a non-JSON error body previously stopped the callback from firing; network failures now call back with {status: 0}.insertHTML: the error message blamed a missing element for every failure, including network errors. The element is now checked before the request.api.js, and to renderHTML/replaceTag in element.js.Docs: https://croot.js.org/docs/api/
getJSON and friends no longer fail silently
getJSON, postJSON, putJSON and deleteJSON swallowed every failure: the .catch only wrote to the console and never called responseFunction, so the caller had no way to know a request had failed. A server that accepted the connection but never replied left the call pending indefinitely, because fetch() has no timeout of its own.
responseFunction is now always called. On a network failure, CORS rejection or timeout it receives {status: 0, data: null}. 0 is never a real HTTP status, so it can be used to tell a failed request apart from a 4xx/5xx reply.data: null.Docs: https://croot.js.org/docs/api/
New module: toast.js, plus serializeForm
toast.js: notifications with no external dependency, as an alternative to loading SweetAlert2 just to show a message. Provides toast(message, type, duration) and the shortcuts toastSuccess, toastError, toastWarning, toastInfo. Each returns a dismiss() function, and duration: 0 keeps the toast until you dismiss it, which suits a loading state. The CSS is injected by the module itself, so there is no separate stylesheet to import.serializeForm(id) in element.js: returns every named form field as one {name: value} object, so getValue() no longer has to be called field by field before postJSON(). Disabled fields and file inputs are skipped; file uploads need postFile/postFileJSON.Docs: https://croot.js.org/docs/toast and https://croot.js.org/docs/element/
New module: debounce.js
Adds debounce.js:
debounce(fn, delay) - runs fn only after the caller stops triggering it, for search-as-you-type and similar input handling.throttle(fn, delay) - runs fn at most once per interval, firing immediately and again at the end of the window so the last call’s arguments are not lost. Useful for scroll, resize and mousemove.Docs: https://croot.js.org/docs/debounce
New module: storage.js
Adds storage.js for localStorage and sessionStorage:
setLocal, setLocalWithExpireDay / Hour / Second, getLocal, deleteLocalsetSession, getSession, deleteSessionValues are serialized with JSON automatically, so objects and arrays can be stored directly. localStorage entries support an optional expiry, which the browser’s own API does not provide; expired entries are removed on read.
Docs: https://croot.js.org/docs/storage
Restores the window.catcher fallback
websocket.js again calls a global window.catcher(message) when no onMessage callback is passed. v0.0.4 replaced that global with an explicit callback parameter, which broke the pattern documented for WhatsAuth. Both styles now work: pass onMessage if you have one, otherwise define window.catcher.
Repairs the library so it actually loads
This release fixes bugs that made parts of the library unusable.
auth.js could not be parsed as an ES module at all: it imported setCookieWithExpireHour from cookie.js and also declared its own copy, which is a SyntaxError. Any page importing it failed to load.config.js imported from whatsauth.js and helper.js, two files that do not exist in this repo, and DefaultSuccesser referenced undefined variables.websocket.js’s openWebSocketSetId always returned undefined because the socket was assigned inside a .then() callback and returned outside it, so sendMessagetoWebSocket/closeWebSocket could never receive a usable socket.IsMobile/isMobile existed twice, and the four JSON functions in api.js were four copies of the same request logic.Breaking: openWebSocketSetId now returns a Promise that resolves with the WebSocket. It previously returned undefined in every case, so no working code can depend on the old behavior.
First releases: element.js, api.js, cookie.js, url.js and the other core helpers, the WhatsAuth QR login (auth.js, WebSocket handling, configuration), and Google Sign-In with SweetAlert2 notifications.