') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Better mapbox trace / layout-layer *below* by etpinard · Pull Request #4058 · plotly/plotly.js · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/plots/mapbox/constants.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,8 @@ module.exports = {
}]
},

controlContainerClassName: 'mapboxgl-control-container',
traceLayerPrefix: 'plotly-trace-layer-',
layoutLayerPrefix: 'plotly-layout-layer-',

wrongVersionErrorMsg: [
'Your custom plotly.js bundle is not using the correct mapbox-gl version',
Expand Down
59 changes: 41 additions & 18 deletions src/plots/mapbox/layers.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,15 +10,16 @@

var Lib = require('../../lib');
var convertTextOpts = require('./convert_text_opts');
var constants = require('./constants');

function MapboxLayer(mapbox, index) {
this.mapbox = mapbox;
this.map = mapbox.map;
function MapboxLayer(subplot, index) {
this.subplot = subplot;

this.uid = mapbox.uid + '-' + 'layer' + index;
this.uid = subplot.uid + '-' + index;
this.index = index;

this.idSource = this.uid + '-source';
this.idLayer = this.uid + '-layer';
this.idSource = 'source-' + this.uid;
this.idLayer = constants.layoutLayerPrefix + this.uid;

// some state variable to check if a remove/add step is needed
this.sourceType = null;
Expand DownExpand Up@@ -65,12 +66,12 @@ proto.needsNewSource = function(opts) {
proto.needsNewLayer = function(opts) {
return (
this.layerType !== opts.type ||
this.below !== opts.below
this.below !== this.subplot.belowLookup['layout-' + this.index]
);
};

proto.updateSource = function(opts) {
var map = this.map;
var map = this.subplot.map;

if(map.getSource(this.idSource)) map.removeSource(this.idSource);

Expand All@@ -85,14 +86,33 @@ proto.updateSource = function(opts) {
};

proto.updateLayer = function(opts) {
var map = this.map;
var subplot = this.subplot;
var convertedOpts = convertOpts(opts);

var below = this.subplot.belowLookup['layout-' + this.index];
var _below;

if(below === 'traces') {
var mapLayers = subplot.getMapLayers();

// find id of first plotly trace layer
for(var i = 0; i < mapLayers.length; i++) {
var layerId = mapLayers[i].id;
if(typeof layerId === 'string' &&
layerId.indexOf(constants.traceLayerPrefix) === 0
) {
_below = layerId;
break;
}
}
} else {
_below = below;
}

this.removeLayer();
this.layerType = opts.type;

if(isVisible(opts)) {
map.addLayer({
subplot.addLayer({
id: this.idLayer,
source: this.idSource,
'source-layer': opts.sourcelayer || '',
Expand All@@ -101,27 +121,30 @@ proto.updateLayer = function(opts) {
maxzoom: opts.maxzoom,
layout: convertedOpts.layout,
paint: convertedOpts.paint
}, opts.below);
}, _below);
}

this.layerType = opts.type;
this.below = below;
};

proto.updateStyle = function(opts) {
if(isVisible(opts)) {
var convertedOpts = convertOpts(opts);
this.mapbox.setOptions(this.idLayer, 'setLayoutProperty', convertedOpts.layout);
this.mapbox.setOptions(this.idLayer, 'setPaintProperty', convertedOpts.paint);
this.subplot.setOptions(this.idLayer, 'setLayoutProperty', convertedOpts.layout);
this.subplot.setOptions(this.idLayer, 'setPaintProperty', convertedOpts.paint);
}
};

proto.removeLayer = function() {
var map = this.map;
var map = this.subplot.map;
if(map.getLayer(this.idLayer)) {
map.removeLayer(this.idLayer);
}
};

proto.dispose = function() {
var map = this.map;
var map = this.subplot.map;
map.removeLayer(this.idLayer);
map.removeSource(this.idSource);
};
Expand DownExpand Up@@ -222,8 +245,8 @@ function convertSourceOpts(opts) {
return sourceOpts;
}

module.exports = function createMapboxLayer(mapbox, index, opts) {
var mapboxLayer = new MapboxLayer(mapbox, index);
module.exports = function createMapboxLayer(subplot, index, opts) {
var mapboxLayer = new MapboxLayer(subplot, index);

mapboxLayer.update(opts);

Expand Down
1 change: 0 additions & 1 deletion src/plots/mapbox/layout_attributes.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -158,7 +158,6 @@ var attrs = module.exports = overrideAll({
// attributes shared between all types
below: {
valType: 'string',
dflt: '',
role: 'info',
description: [
'Determines if the layer will be inserted',
Expand Down
122 changes: 122 additions & 0 deletions src/plots/mapbox/mapbox.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,7 @@ function Mapbox(gd, id) {
this.styleObj = null;
this.traceHash = {};
this.layerList = [];
this.belowLookup = {};
}

var proto = Mapbox.prototype;
Expand DownExpand Up@@ -126,6 +127,7 @@ proto.createMap = function(calcData, fullLayout, resolve, reject) {
promises = promises.concat(self.fetchMapData(calcData, fullLayout));

Promise.all(promises).then(function() {
self.fillBelowLookup(calcData, fullLayout);
self.updateData(calcData);
self.updateLayout(fullLayout);
self.resolveOnRender(resolve);
Expand DownExpand Up@@ -191,12 +193,94 @@ proto.updateMap = function(calcData, fullLayout, resolve, reject) {
promises = promises.concat(self.fetchMapData(calcData, fullLayout));

Promise.all(promises).then(function() {
self.fillBelowLookup(calcData, fullLayout);
self.updateData(calcData);
self.updateLayout(fullLayout);
self.resolveOnRender(resolve);
}).catch(reject);
};

proto.fillBelowLookup = function(calcData, fullLayout) {
var opts = fullLayout[this.id];
var layers = opts.layers;
var i, val;

var belowLookup = this.belowLookup = {};
var hasTraceAtTop = false;

for(i = 0; i < calcData.length; i++) {
var trace = calcData[i][0].trace;
var _module = trace._module;

if(typeof trace.below === 'string') {
val = trace.below;
} else if(_module.getBelow) {
// 'smart' default that depend the map's base layers
val = _module.getBelow(trace, this);
}

if(val === '') {
hasTraceAtTop = true;
}

belowLookup['trace-' + trace.uid] = val || '';
}

for(i = 0; i < layers.length; i++) {
var item = layers[i];

if(typeof item.below === 'string') {
val = item.below;
} else if(hasTraceAtTop) {
// if one or more trace(s) set `below:''` and
// layers[i].below is unset,
// place layer below traces
val = 'traces';
} else {
val = '';
}

belowLookup['layout-' + i] = val;
}

// N.B. If multiple layers have the 'below' value,
// we must clear the stashed 'below' field in order
// to make `traceHash[k].update()` and `layerList[i].update()`
// remove/add the all those layers to have preserve
// the correct layer ordering
var val2list = {};
var k, id;

for(k in belowLookup) {
val = belowLookup[k];
if(val2list[val]) {
val2list[val].push(k);
} else {
val2list[val] = [k];
}
}

for(val in val2list) {
var list = val2list[val];
if(list.length > 1) {
for(i = 0; i < list.length; i++) {
k = list[i];
if(k.indexOf('trace-') === 0) {
id = k.split('trace-')[1];
if(this.traceHash[id]) {
this.traceHash[id].below = null;
}
} else if(k.indexOf('layout-') === 0) {
id = k.split('layout-')[1];
if(this.layerList[id]) {
this.layerList[id].below = null;
}
}
}
}
}
};

var traceType2orderIndex = {
choroplethmapbox: 0,
densitymapbox: 1,
Expand All@@ -207,6 +291,10 @@ proto.updateData = function(calcData) {
var traceHash = this.traceHash;
var traceObj, trace, i, j;

// Need to sort here by trace type here,
// in case traces with different `type` have the same
// below value, but sorting we ensure that
// e.g. choroplethmapbox traces will be below scattermapbox traces
var calcDataSorted = calcData.slice().sort(function(a, b) {
return (
traceType2orderIndex[a[0].trace.type] -
Expand DownExpand Up@@ -598,6 +686,40 @@ proto.setOptions = function(id, methodName, opts) {
}
};

proto.getMapLayers = function() {
return this.map.getStyle().layers;
};

// convenience wrapper that first check in 'below' references
// a layer that exist and then add the layer to the map,
proto.addLayer = function(opts, below) {
var map = this.map;

if(typeof below === 'string') {
if(below === '') {
map.addLayer(opts, below);
return;
}

var mapLayers = this.getMapLayers();
for(var i = 0; i < mapLayers.length; i++) {
if(below === mapLayers[i].id) {
map.addLayer(opts, below);
return;
}
}

Lib.warn([
'Trying to add layer with *below* value',
below,
'referencing a layer that does not exist',
'or that does not yet exist.'
].join(' '));
}

map.addLayer(opts);
};

// convenience method to project a [lon, lat] array to pixel coords
proto.project = function(v) {
return this.map.project(new mapboxgl.LngLat(v[0], v[1]));
Expand Down
1 change: 0 additions & 1 deletion src/traces/choroplethmapbox/convert.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,6 @@ function convert(calcTrace) {
line.layout.visibility = 'visible';

opts.geojson = {type: 'FeatureCollection', features: featuresOut};
opts.below = trace.below;

convertOnSelect(calcTrace);

Expand Down
24 changes: 24 additions & 0 deletions src/traces/choroplethmapbox/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,30 @@ module.exports = {
}
},

getBelow: function(trace, subplot) {
var mapLayers = subplot.getMapLayers();

// find layer just above top-most "water" layer
// that is not a plotly layer
for(var i = mapLayers.length - 2; i >= 0; i--) {
var layerId = mapLayers[i].id;

if(typeof layerId === 'string' &&
layerId.indexOf('water') === 0
) {
for(var j = i + 1; j < mapLayers.length; j++) {
layerId = mapLayers[j].id;

if(typeof layerId === 'string' &&
layerId.indexOf('plotly-') === -1
) {
return layerId;
}
}
}
}
},

moduleType: 'trace',
name: 'choroplethmapbox',
basePlotModule: require('../../plots/mapbox'),
Expand Down
Loading