Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support SVG symbols (DHIS2-14440) #517

Merged
merged 4 commits into from
Jan 9, 2023
Merged
Changes from 2 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
76 changes: 58 additions & 18 deletions src/utils/images.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,64 @@
// Load and add images to map sprite
export const addImages = async (map, images) =>
Promise.all(
images.map(
url =>
new Promise((resolve, reject) => {
map.loadImage(url, (error, img) => {
if (error) {
reject(error)
}
// Only one SVG icon size is currently suppored
const svgWidth = 16
const svgHeight = 16

if (!map.hasImage(url)) {
map.addImage(url, img)
}
const credentials = 'include'

resolve(img)
})
})
// Add image to map sprite if not exist
const addImage = (map, name, img) => {
if (!map.hasImage(name)) {
map.addImage(name, img)
}
}

// Creates image from SVG data URI
const dataUri2image = dataUri =>
new Promise((resolve, reject) => {
const img = new Image(svgWidth, svgHeight)
img.onload = () => resolve(img)
img.onerror = reject
img.src = dataUri
})

// Fetch SVG and convert to Base64 data URI
const fetchSvg = url =>
fetch(url, { credentials })
.then(response => response.text())
.then(
svg => `data:image/svg+xml;charset=utf-8;base64,${window.btoa(svg)}`
)
)
.then(dataUri2image)

// Load and add image to map
const loadImage = map => url =>
new Promise(resolve => {
if (url.endsWith('.svg')) {
fetchSvg(url)
.then(img => {
addImage(map, url, img)
resolve(img)
})
.catch(error => {
console.log('SVG not added', url, error)
resolve()
})
} else {
map.loadImage(url, (error, img) => {
if (error) {
console.log('Image not loaded', url, error)
}
if (img) {
turban marked this conversation as resolved.
Show resolved Hide resolved
addImage(map, url, img)
}
resolve(img)
})
}
})

// Load and add images to map sprite
export const addImages = async (map, images) =>
Promise.all(images.map(loadImage(map)))

// Include cookies for cross-origin image requests
export const transformRequest = (url, resourceType) =>
resourceType === 'Image' ? { url, credentials: 'include' } : null
resourceType === 'Image' ? { url, credentials } : null