// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
import capMixin from "./cap-mixin"
import rasterLayerPointMixin from "./raster-layer-point-mixin"
import rasterLayerPolyMixin from "./raster-layer-poly-mixin"
import rasterLayerHeatmapMixin from "./raster-layer-heatmap-mixin"
import rasterLayerLineMixin from "./raster-layer-line-mixin"
import rasterLayerWindBarbMixin from "./raster-layer-windbarb-mixin"
import rasterLayerMesh2dMixin from "./raster-layer-mesh2d-mixin"
import rasterLayerCrossSectionTerrainMixin from "./raster-layer-cross-section-terrain-mixin"
import {
createRasterLayerGetterSetter,
createVegaAttrMixin
} from "../utils/utils-vega"
import { AABox2d, Point2d } from "@heavyai/draw/dist/draw"
import moment from "moment"
import { IMAGE_SIZE_LIMIT } from "../constants/dc-constants"
import { utils } from "../utils/utils"
import { IMAGE_EXTENSIONS } from "../constants/file-types"
const validLayerTypes = [
"points",
"polys",
"heat",
"lines",
"windbarbs",
"mesh2d",
"crossSectionTerrain"
]
const { getImageSize, replaceAsync, parseUrlParts } = utils
const MISSING_HIT_TEST_COLUMN_ERROR =
"$HEAVYAI_ERROR_COLUMN_NOT_FOUND_IN_HIT_TEST_CACHE$"
export default function rasterLayer(layerType) {
const _layerType = layerType
let _dimension = null
let _group = null
let _mandatoryAttributes = []
let _lastFilteredSize = 0
let _layer = capMixin({
setDataAsync(callback) {
// noop.
// This is to appease mixins that require an object initialized with a baseMixin
},
data(callback) {
// noop.
// This is to appease mixins that require an object initialized with a baseMixin
},
filter() {
// noop.
// This is to appease mixins that require an object initialized with a baseMixin
},
_mandatoryAttributes(mandatoryAttributes) {
// needed for layer mixins to control mandatory checks.
if (!arguments.length) {
return _mandatoryAttributes
}
_mandatoryAttributes = mandatoryAttributes
return _layer
}
})
_layer.othersGrouper(false) // TODO(croot): what does othersGrouper in capMixin do exactly?
// Always set to false for now, tho user can override.
if (layerType === "points") {
_layer = rasterLayerPointMixin(_layer)
} else if (layerType === "polys") {
_layer = rasterLayerPolyMixin(_layer)
} else if (/heat/.test(layerType)) {
_layer = rasterLayerHeatmapMixin(_layer)
} else if (layerType === "lines") {
_layer = rasterLayerLineMixin(_layer)
} else if (layerType === "windbarbs") {
_layer = rasterLayerWindBarbMixin(_layer)
} else if (layerType === "mesh2d") {
_layer = rasterLayerMesh2dMixin(_layer)
} else if (layerType === "crossSectionTerrain") {
_layer = rasterLayerCrossSectionTerrainMixin(_layer)
} else {
throw new Error(
'"' +
layerType +
'" is not a valid layer type. The valid layer types are: ' +
validLayerTypes.join(", ")
)
}
let _opacity = 1
// NOTE: builds _layer.defaultFillColor(), _layer.nullFillColor(),
// _layer.fillColorScale(), & _layer.fillColorAttr()
createVegaAttrMixin(_layer, "fillColor", "#22A7F0", "#CACACA", true)
// NOTE: builds _layer.defaultStrokeColor(), _layer.nullStrokeColor(),
// _layer.strokeColorScale(), & _layer.strokeColorAttr()
createVegaAttrMixin(_layer, "strokeColor", "white", "white", true)
// NOTE: builds _layer.defaultStrokeWidth(), _layer.nullStrokeWidth(),
// _layer.strokeWidthScale(), & _layer.strokeWidthAttr()
createVegaAttrMixin(_layer, "strokeWidth", 0, 0, true)
_layer.popupColumns = createRasterLayerGetterSetter(_layer, [])
_layer.popupColumnsMapped = createRasterLayerGetterSetter(_layer, {})
_layer.popupFunction = createRasterLayerGetterSetter(_layer, null)
_layer.popupStyle = createRasterLayerGetterSetter(_layer, {})
_layer.densityAccumulatorEnabled = createRasterLayerGetterSetter(
_layer,
false
)
const _popup_wrap_class = "map-popup-wrap-new"
const _popup_box_class = "map-popup-box-new"
const _popup_item_copy_class = "popup-item-copy"
const _popup_box_item_wrap_class = "map-popup-item-wrap"
const _popup_box_image_class = "map-popup-image"
const _popup_box_item_class = "map-popup-item"
const _popup_item_key_class = "popup-item-key"
const _popup_item_val_class = "popup-item-val"
const _popup_content_attr = "data-copycontent"
const _layerPopups = {}
_layer.layerType = function() {
return _layerType
}
/**
* **mandatory**
*
* Set or get the dimension attribute of a chart. In `dc`, a dimension can be any valid [crossfilter
* dimension](https://github.com/square/crossfilter/wiki/API-Reference#wiki-dimension).
*
* If a value is given, then it will be used as the new dimension. If no value is specified then
* the current dimension will be returned.
* @name dimension
* @memberof dc.baseMixin
* @instance
* @see {@link https://github.com/square/crossfilter/wiki/API-Reference#dimension crossfilter.dimension}
* @example
* var index = crossfilter([]);
* var dimension = index.dimension(dc.pluck('key'));
* chart.dimension(dimension);
* @param {crossfilter.dimension} [dimension]
* @return {crossfilter.dimension}
* @return {dc.baseMixin}
*/
_layer.dimension = function(dimension) {
if (!arguments.length) {
return _dimension
}
_dimension = dimension
return _layer
}
/**
* **mandatory**
*
* Set or get the group attribute of a chart. In `dc` a group is a
* {@link https://github.com/square/crossfilter/wiki/API-Reference#group-map-reduce crossfilter group}.
* Usually the group should be created from the particular dimension associated with the same chart. If a value is
* given, then it will be used as the new group.
*
* If no value specified then the current group will be returned.
* If `name` is specified then it will be used to generate legend label.
* @name group
* @memberof dc.baseMixin
* @instance
* @see {@link https://github.com/square/crossfilter/wiki/API-Reference#group-map-reduce crossfilter.group}
* @example
* var index = crossfilter([]);
* var dimension = index.dimension(dc.pluck('key'));
* chart.dimension(dimension);
* chart.group(dimension.group(crossfilter.reduceSum()));
* @param {crossfilter.group} [group]
* @param {String} [name]
* @return {crossfilter.group}
* @return {dc.baseMixin}
*/
_layer.group = function(group, name) {
if (!arguments.length) {
return _group
}
_group = group
_layer._groupName = name
return _layer
}
_layer.opacity = function(opacity) {
if (!arguments.length) {
return _opacity
}
_opacity = opacity
return _layer
}
function genHeatConfigFromChart(chart, layerName) {
return {
table: _layer.crossfilter().getDataSource(),
width: Math.round(chart.width() * chart._getPixelRatio()),
height: Math.round(chart.height() * chart._getPixelRatio()),
min: chart.conv4326To900913(chart._minCoord),
max: chart.conv4326To900913(chart._maxCoord),
filter: _layer.crossfilter().getFilterString(layerName),
globalFilter: _layer.crossfilter().getGlobalFilterString(),
neLat: chart._maxCoord[1],
zoom: chart.zoom()
}
}
_layer.genVega = function(chart, layerName) {
const cap = _layer.cap()
const group = _layer.group() || {}
let query = ""
if (group.type === "dimension") {
query = group.writeTopQuery(cap, undefined, true)
} else if (group.type === "group") {
query = group.writeTopQuery(cap, undefined, false, true)
}
if (!query.length) {
// throw new Error("Crossfilter group/dimension did not provide a sql query string for layer " + layerName + "." + (groupType.length ? " Group type: " + (group.type || "unknown") + "." : ""))
}
if (_layer.type === "heatmap") {
const vega = _layer._genVega({
...genHeatConfigFromChart(chart, layerName),
layerName
})
return vega
} else {
const vega = _layer._genVega(chart, layerName, group, query)
return vega
}
}
_layer.hasPopupColumns = function() {
const popCols = _layer.popupColumns()
return Boolean(popCols && popCols instanceof Array && popCols.length > 0)
}
// A Utility function to map size or color measure label for custom measure popup
// Label is the same as field most of the case but for custom measures, it could be different
_layer.getMeasureLabel = function(measureRegex) {
let measureBlock = null
if (measureRegex[2] === "color" || measureRegex[2] === "strokeColor") {
measureBlock = _layer.getState().encoding.color
} else if (
measureRegex[2] === "size" ||
measureRegex[2] === "strokeWidth"
) {
measureBlock = _layer.getState().encoding.size
} else if (measureRegex[2] === "x" || measureRegex[2] === "y") {
measureBlock = _layer.getState().encoding[measureRegex[2]]
} else if (measureRegex[2] === "orientation") {
measureBlock = _layer.getState().encoding.orientation
}
if (measureBlock && measureBlock.label) {
return measureBlock.label
}
return measureBlock
}
_layer.getLastFilteredSize = function() {
return _lastFilteredSize
}
_layer.setLastFilteredSize = function(value) {
_lastFilteredSize = value
}
function isMeasureCol(colAttr) {
return (
colAttr === "x" ||
colAttr === "y" ||
colAttr === "color" ||
colAttr === "size" ||
colAttr === "strokeColor" ||
colAttr === "strokeWidth" ||
colAttr === "orientation"
)
}
function addPopupColumnToSet(colAttr, popupColSet) {
// TODO(croot): getProjectOn for groups requires the two arguments,
// dimension.getProjectOn() doesn't have any args.
// Need to come up with a better API for group.getProjectOn()
// and improve the api so that "as key0" are not automatically
// added to those projection statements.
// TODO(croot): performance could be improved here with a better
// data structure, but probably not an issue given the amount
// of popup col attrs to iterate through is small
const dim = _layer.group() || _layer.dimension()
if (
dim ||
_layer.layerType() === "points" ||
_layer.layerType() === "lines" ||
_layer.layerType() === "polys"
) {
const projExprs =
_layer.layerType() === "points" ||
_layer.layerType() === "lines" ||
_layer.layerType() === "polys" ||
_layer.layerType() === ""
? _layer.getProjections()
: dim.getProjectOn(true) // handles the group and dimension case
const regex = /^\s*([\s\S]+)\s+as\s+(\S+)/i
const funcRegex = /^\s*(\S+\s*\(.*\))\s+as\s+(\S+)/i
for (let i = 0; i < projExprs.length; ++i) {
const projExpr = projExprs[i]
let regexRtn = projExpr.match(regex)
if (regexRtn) {
if (regexRtn[2] === colAttr) {
if (isMeasureCol(colAttr)) {
// column selector label is used for layer.popupColumns(), so we need to remove it from popupColSet for color/size or x/y measures
const label = _layer.getMeasureLabel(regexRtn)
popupColSet.delete(regexRtn[1])
popupColSet.delete(label)
} else {
popupColSet.delete(colAttr)
}
colAttr = projExpr
break
}
} else if (
(regexRtn = projExpr.match(funcRegex)) &&
regexRtn[2] === colAttr
) {
popupColSet.delete(colAttr)
colAttr = projExpr
break
} else if (projExpr && projExpr.replace(/^\s+|\s+$/g, "") === colAttr) {
break
}
}
}
return popupColSet.add(colAttr.replace(/\n/g, " "))
}
_layer.getPopupAndRenderColumns = function(chart) {
const popupColsSet = new Set()
const popupCols = _layer.popupColumns()
if (popupCols) {
popupCols.forEach(colAttr => {
addPopupColumnToSet(colAttr, popupColsSet)
})
}
_layer._addRenderAttrsToPopupColumnSet(chart, popupColsSet)
const rtnArray = []
popupColsSet.forEach(colName => {
rtnArray.push(colName)
})
return rtnArray
}
// this function maps hit testing response to popupColumns items
function mapDataViaColumns(data, popupColumns, chart) {
const newData = {}
const columnSet = new Set(popupColumns)
for (const key in data) {
if (columnSet.has(key)) {
// check for missing hit test cache columns and substitute readable message
newData[key] =
data[key] === MISSING_HIT_TEST_COLUMN_ERROR
? "Column Not Found"
: data[key]
data[key] instanceof Date ? moment(data[key]).utc() : data[key]
if (typeof chart.useLonLat === "function" && chart.useLonLat()) {
if (key === "x") {
newData[key] = chart.conv900913To4326X(data[key])
} else if (key === "y") {
newData[key] = chart.conv900913To4326Y(data[key])
}
}
} else {
// check response key is size or measure column which is in popupColumns
const dim = _layer.group() || _layer.dimension()
const projExprs =
_layer.layerType() === "points" ||
_layer.layerType() === "lines" ||
_layer.layerType() === "polys" ||
_layer.layerType() === ""
? _layer.getProjections()
: dim.getProjectOn(true)
const regex = /^\s*([\s\S]+)\s+as\s+(\S+)/i
for (let i = 0; i < projExprs.length; ++i) {
const projExpr = projExprs[i]
const regexRtn = projExpr.match(regex)
// for custom columns, the column label is different than the column value,
// so need to access the measure column label that is passed from immerse here
const label = _layer.getMeasureLabel(regexRtn)
if (columnSet.has(label)) {
newData[label] = data[regexRtn[2]]
}
}
}
}
return newData
}
_layer.areResultsValidForPopup = function(results) {
if (!results) {
return false
}
return _layer._areResultsValidForPopup(results[0])
}
function filenameHasExtension(url = "", extensions) {
const urlParts = parseUrlParts(url)
const hostAndPath = urlParts?.[5]
return extensions.some(ext => hostAndPath?.toLowerCase()?.endsWith(ext))
}
const LinkElement = (href, content) =>
`
${content}
`
async function renderImageOrLink(chart, url, hyperlink, colVal) {
// eslint-disable-next-line no-restricted-syntax
try {
const sizeBytes = await getImageSize(hyperlink)
let urlContent = url
if (sizeBytes > IMAGE_SIZE_LIMIT) {
// eslint-disable-next-line no-console
console.info(
"Image too large to preview, falling back to hyperlink",
hyperlink
)
} else if (!chart.popupImageEnabled || !chart.popupImageEnabled()) {
// eslint-disable-next-line no-console
console.info("Images preview for popups is disabled")
} else {
urlContent = ``
}
return Promise.resolve(LinkElement(hyperlink, urlContent), true)
} catch (e) {
// eslint-disable-next-line no-console
console.warn(
"Error creating image preview from column:",
colVal,
"Error:",
e
)
return Promise.resolve(LinkElement(hyperlink, colVal), true)
}
}
function replaceURL(chart, columnValue) {
const urlRegExpr = /(((https?:\/\/)|(www\.))[^\s^<>'"”`]+)/g
const urlMatch =
typeof columnValue === "string" && columnValue.match(urlRegExpr)
if (urlMatch) {
return replaceAsync(columnValue, urlRegExpr, async url => {
let hyperlink = url
if (!hyperlink.match("^https?://")) {
hyperlink = "http://" + hyperlink
}
if (filenameHasExtension(hyperlink, Object.values(IMAGE_EXTENSIONS))) {
return renderImageOrLink(chart, hyperlink, url, columnValue)
} else {
return Promise.resolve(
columnValue.replace(urlRegExpr, url => LinkElement(hyperlink, url)),
true
)
}
})
} else {
// Return raw column value, no transformation
return Promise.resolve(columnValue)
}
}
async function renderPopupHTML(
chart,
data,
columnOrder,
columnMap,
formatMeasureValue
) {
const formattedColumnPromises = columnOrder.map(key => {
if (typeof data[key] === "undefined") {
return ""
}
const columnKey = columnMap && columnMap[key] ? columnMap[key] : key
const columnKeyTrimmed = columnKey.replace(/.*\((.*)\).*/, "$1")
const columnValue = formatMeasureValue(data[key], columnKeyTrimmed)
return replaceURL(chart, columnValue).then((formattedColumn, isLink) => {
const columnHtml = `