2016-09-08 21:42:18 +02:00
|
|
|
import React from 'react';
|
2016-09-10 21:29:18 +02:00
|
|
|
import Immutable from 'immutable'
|
|
|
|
import spec from 'mapbox-gl-style-spec/reference/latest.min.js'
|
2016-09-09 18:53:57 +02:00
|
|
|
|
2016-09-10 21:29:18 +02:00
|
|
|
// Standard JSON to Immutable conversion except layers
|
|
|
|
// are stored in an OrderedMap to make lookups id fast
|
|
|
|
// It also ensures that every style has an id and
|
|
|
|
// a created date for future reference
|
|
|
|
function fromJSON(jsonStyle) {
|
2016-12-16 14:49:25 +01:00
|
|
|
if (typeof jsonStyle === 'string' || jsonStyle instanceof String) {
|
|
|
|
jsonStyle = JSON.parse(jsonStyle)
|
|
|
|
}
|
2016-09-10 21:29:18 +02:00
|
|
|
|
2016-12-16 14:49:25 +01:00
|
|
|
return Immutable.Map(Object.keys(jsonStyle).map(key => {
|
|
|
|
const val = jsonStyle[key]
|
|
|
|
if(key === "layers") {
|
|
|
|
return [key, Immutable.OrderedMap(val.map(l => [l.id, Immutable.fromJS(l)]))]
|
|
|
|
} else if(key === "sources" || key === "metadata" || key === "transition") {
|
|
|
|
return [key, Immutable.fromJS(val)]
|
|
|
|
} else {
|
|
|
|
return [key, val]
|
|
|
|
}
|
|
|
|
}))
|
2016-09-10 21:29:18 +02:00
|
|
|
}
|
|
|
|
|
2016-12-16 14:49:25 +01:00
|
|
|
// Empty style is always used if no style could be restored or fetched
|
|
|
|
const emptyStyle = ensureMetadataExists(fromJSON({
|
|
|
|
version: 8,
|
|
|
|
sources: {},
|
|
|
|
layers: [],
|
|
|
|
}))
|
|
|
|
|
2016-09-20 16:49:02 +02:00
|
|
|
function ensureHasId(style) {
|
2016-12-16 14:49:25 +01:00
|
|
|
if(style.has('id')) return style
|
|
|
|
return style.set('id', Math.random().toString(36).substr(2, 9))
|
2016-09-20 16:49:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function ensureHasTimestamp(style) {
|
2016-12-16 14:49:25 +01:00
|
|
|
if(style.has('id')) return style
|
|
|
|
return style.set('created', new Date().toJSON())
|
2016-09-20 16:49:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function ensureMetadataExists(style) {
|
2016-12-16 14:49:25 +01:00
|
|
|
return ensureHasId(ensureHasTimestamp(style))
|
2016-09-20 16:49:02 +02:00
|
|
|
}
|
|
|
|
|
2016-09-10 21:29:18 +02:00
|
|
|
// Turns immutable style back into JSON with the original order of the
|
|
|
|
// layers preserved
|
|
|
|
function toJSON(mapStyle) {
|
2016-12-16 14:49:25 +01:00
|
|
|
const jsonStyle = {}
|
|
|
|
for(let [key, value] of mapStyle.entries()) {
|
|
|
|
if(key === "layers") {
|
|
|
|
jsonStyle[key] = value.toIndexedSeq().toJS()
|
|
|
|
} else if(key === 'sources' || key === "metadata" || key === "transition") {
|
|
|
|
jsonStyle[key] = value.toJS()
|
|
|
|
} else {
|
|
|
|
jsonStyle[key] = value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return jsonStyle
|
2016-09-10 21:29:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export default {
|
2016-12-16 14:49:25 +01:00
|
|
|
toJSON,
|
|
|
|
fromJSON,
|
|
|
|
ensureMetadataExists,
|
|
|
|
emptyStyle,
|
2016-09-10 21:29:18 +02:00
|
|
|
}
|