Skip to content

Commit

Permalink
Merge pull request #14 from jaulz/fix/use-badge-v2
Browse files Browse the repository at this point in the history
fix: support Badgin API version 2
  • Loading branch information
jaulz authored Jan 24, 2020
2 parents e637d0d + f6666f4 commit c26e0e6
Showing 1 changed file with 35 additions and 8 deletions.
43 changes: 35 additions & 8 deletions src/badging.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { Value } from './index'
import isPositiveNumber from './isPositiveNumber'

// The actual API can be tracked here: https://github.com/wicg/badging/
// Most likely it will change to: navigator.setAppBadge and navigator.clearAppBadge
// Most likely it will eventually change to: navigator.setAppBadge and navigator.clearAppBadge
declare global {
interface Window {
ExperimentalBadge?: {
set: (value?: number) => void
clear: () => void
}
}

interface Navigator {
setExperimentalAppBadge?: (value?: number) => void
clearExperimentalAppBadge?: () => void
}
}

let warnedBefore = false
Expand All @@ -19,7 +23,7 @@ const warn = () => {
}

// We will only warn the user if the Badging API is not available at all
if ('ExperimentalBadge' in window) {
if ('ExperimentalBadge' in window || 'setExperimentalAppBadge' in navigator) {
return
}

Expand All @@ -34,6 +38,19 @@ const current: { mediaQuery: MediaQueryList | null; value: Value } = {
value: 0,
}

function isVersion1Available() {
return 'ExperimentalBadge' in window && !!window.ExperimentalBadge
}

function isVersion2Available() {
return (
'setExperimentalAppBadge' in navigator &&
!!navigator.setExperimentalAppBadge &&
'clearExperimentalAppBadge' in navigator &&
!!navigator.clearExperimentalAppBadge
)
}

export function isAvailable() {
if (!current.mediaQuery) {
current.mediaQuery = window.matchMedia('(display-mode: standalone)')
Expand All @@ -46,8 +63,7 @@ export function isAvailable() {

return (
current.mediaQuery.matches &&
'ExperimentalBadge' in window &&
!!window.ExperimentalBadge
(isVersion1Available() || isVersion2Available())
)
}

Expand All @@ -61,14 +77,25 @@ export function set(value: Value) {

// Sets the badge to contents (an integer), or to "flag" if contents is omitted. If contents is 0, clears the badge for the matching app(s).
// See details here: https://github.com/WICG/badging/blob/master/explainer.md#the-api
window.ExperimentalBadge!.set(value)
return true
if (isVersion1Available()) {
window.ExperimentalBadge!.set(value)
return true
} else if (isVersion2Available()) {
navigator.setExperimentalAppBadge!(value)
return true
}

return false
}

export function clear() {
if (!isAvailable()) {
return
}

window.ExperimentalBadge!.clear()
if (isVersion1Available()) {
window.ExperimentalBadge!.clear()
} else if (isVersion2Available()) {
navigator.clearExperimentalAppBadge!()
}
}

0 comments on commit c26e0e6

Please sign in to comment.