Skip to content

Commit

Permalink
Merge pull request #24 from Nosto/type-assertions
Browse files Browse the repository at this point in the history
Fix type assertions
  • Loading branch information
timowestnosto committed Mar 5, 2024
2 parents 10512c6 + 862339b commit e2196d4
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 51 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"promise"
],
"rules": {
"promise/prefer-await-to-then": "error"
"promise/prefer-await-to-then": "error",
"@typescript-eslint/consistent-type-assertions": ["error", { "assertionStyle": "never" }]
}
}
8 changes: 5 additions & 3 deletions src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,13 @@ export function log(
) {
const msg = typeof msgOrError === "string" ? msgOrError : undefined
const error = optLevel ? errorOrLevel : !msg ? msgOrError : undefined
const level = (optLevel || (typeof errorOrLevel === "string" ? errorOrLevel : "error")) as LogLevel
// @ts-expect-error type mismatch
const level: LogLevel = (optLevel || (typeof errorOrLevel === "string" ? errorOrLevel : "error"))
if (error) {
getNostoClient().then(api => {
(async () => {
const api = await getNostoClient()
api.captureError(error, "nostoAutocomplete", level)
})
})()
}
console[level](...[msg, error].filter(Boolean))
}
Expand Down
4 changes: 2 additions & 2 deletions src/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ const defaultProductFields = [
* })
* ```
*/
export async function search<State>(
export async function search(
query: InputSearchQueryWithFields,
options?: SearchOptions
) {
Expand All @@ -102,5 +102,5 @@ export async function search<State>(
},
{ redirect, track })

return { query, response } as State
return { query, response }
}
12 changes: 12 additions & 0 deletions src/shims.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
type GaNamespace = {
(): void
getAll(): {
send(type: string, url: string): void
}[]
}

interface Window {
ga?: GaNamespace
gtag?: unknown
google_tag_manager?: unknown
}
9 changes: 3 additions & 6 deletions src/utils/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function findAll<T extends Element>(
} else if (selector instanceof Array) {
return selector
} else if (selector instanceof NodeList) {
return Array.prototype.slice.call(selector) as Element[]
return Array.prototype.slice.call(selector)
}
return Array.prototype.slice.call(document.querySelectorAll(selector))
})()
Expand Down Expand Up @@ -48,14 +48,11 @@ export function parents(target: Selector, selector?: string): Element[] {
)
}

type WithMsMatchesSelector = {
msMatchesSelector?: typeof Element.prototype.matches
}

export function matches(target: Selector, selector: string): boolean {
const matchesFunc =
Element.prototype.matches ||
(Element.prototype as WithMsMatchesSelector).msMatchesSelector ||
// @ts-expect-error proprietary method
Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector
return findAll(target).some(element => matchesFunc.call(element, selector))
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/dropdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ export function createDropdown<State>(

async function init() {
const state = await Promise.resolve(initialState)
await Promise.resolve(render(container, state as State))
await Promise.resolve(render(container, state))

// Without setTimeout React does not have committed DOM changes yet, so we don't have the correct elements.
setTimeout(() => {
Expand Down
45 changes: 17 additions & 28 deletions src/utils/ga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,6 @@ import { AutocompleteConfig, defaultGaConfig } from "../config"

const localStorageKey = "nostoAutocomplete:gaEvent"

type GaNamespace = {
(): void
getAll(): {
send(type: string, url: string): void
}[]
}

export function trackGaPageView(options?: {
delay?: boolean
title?: string
Expand All @@ -21,20 +14,14 @@ export function trackGaPageView(options?: {
location = window.location.href,
} = options || {}

const windowObj = window as {
ga?: GaNamespace
gtag?: unknown
google_tag_manager?: unknown
}

if (delay) {
saveToLocalStorage(title, location)
} else {
if ("gtag" in windowObj && typeof windowObj.gtag === "function") {
if ("gtag" in window && typeof window.gtag === "function") {
const accounts =
"google_tag_manager" in windowObj &&
typeof windowObj.google_tag_manager === "object"
? Object.keys(windowObj.google_tag_manager || []).filter(
"google_tag_manager" in window &&
typeof window.google_tag_manager === "object"
? Object.keys(window.google_tag_manager || []).filter(
e => {
return e.substring(0, 2) == "G-"
}
Expand All @@ -43,28 +30,28 @@ export function trackGaPageView(options?: {

if (accounts.length > 1) {
for (let i = 0; i < accounts.length; i++) {
windowObj.gtag("event", "page_view", {
window.gtag("event", "page_view", {
page_title: title,
page_location: location,
send_to: accounts[i],
})
}
} else {
windowObj.gtag("event", "page_view", {
window.gtag("event", "page_view", {
page_title: title,
page_location: location,
})
}
}
if (
"ga" in windowObj &&
typeof windowObj.ga === "function" &&
"getAll" in windowObj.ga &&
typeof windowObj.ga.getAll === "function"
"ga" in window &&
typeof window.ga === "function" &&
"getAll" in window.ga &&
typeof window.ga.getAll === "function"
) {
try {
const url = new URL(location)
const trackers = windowObj.ga!.getAll()
const trackers = window.ga!.getAll()
if (trackers?.length > 0) {
trackers[0]?.send("pageview", url.pathname + url.search)
}
Expand Down Expand Up @@ -115,15 +102,17 @@ function saveToLocalStorage(title: string, location: string): void {
localStorage.setItem(localStorageKey, JSON.stringify({ title, location }))
}

interface Event {
title: string
location: string
}

function consumeLocalStorageEvent(): void {
const eventString = localStorage.getItem(localStorageKey)
if (typeof eventString === "string") {
localStorage.removeItem(localStorageKey)
try {
const event = JSON.parse(eventString) as {
title: string
location: string
}
const event: Event = JSON.parse(eventString)
trackGaPageView(event)
} catch (e) {
log("Could not consume pageView", e, "warn")
Expand Down
2 changes: 1 addition & 1 deletion src/utils/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function createHistory(size: number) {
)
} catch (err) {
log("Could not get history items.", err, "error")
return [] as Items
return []
}
}

Expand Down
7 changes: 4 additions & 3 deletions src/utils/limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ type Callback<T> = () => PromiseLike<T>

interface Event<T> {
getPromise?: Callback<T>
resolve: (result?: T) => void
resolve: (result: T | PromiseLike<T>) => void
reject: (...args: unknown[]) => void
number: number
}
Expand All @@ -22,12 +22,12 @@ export function createLimiter<T = void>(
function limited(getPromise?: Callback<T>): PromiseLike<T> {
return new Promise<T>((resolve, reject) => {
currentNumber += 1
const event = {
const event: Event<T> = {
getPromise,
resolve,
reject,
number: currentNumber,
} as Event<T>
}
removeOldEvents()
if (events.length < noLimitCount) {
execute(event)
Expand Down Expand Up @@ -82,6 +82,7 @@ export function createLimiter<T = void>(
event.reject(e)
}
} else {
// @ts-expect-error no result given
event.resolve()
}
}
Expand Down
15 changes: 9 additions & 6 deletions src/utils/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,12 @@ export const getStateActions = <State>({
}): StateActions<State> => {
let cancellable: Cancellable<State> | undefined

const fetchState = (value: string, config: AutocompleteConfig<State>) => {
const fetchState = (value: string, config: AutocompleteConfig<State>): PromiseLike<State> => {
if (typeof config.fetch === "function") {
return config.fetch(value)
} else {
return search<State>(
// @ts-expect-error type mismatch
return search(
{
query: value,
...config.fetch,
Expand All @@ -57,14 +58,15 @@ export const getStateActions = <State>({
)
}
}

function getHistoryState(query: string) {

function getHistoryState(query: string): PromiseLike<State> {
// @ts-expect-error type mismatch
return Promise.resolve({
query: {
query,
},
history: history?.getItems()
} as State)
})
}

return {
Expand All @@ -79,7 +81,8 @@ export const getStateActions = <State>({
}

return (
cancellable?.promise ?? Promise.resolve({} as State)
// @ts-expect-error type mismatch
cancellable?.promise ?? Promise.resolve<State>({})
)
},
addHistoryItem: (item: string) => {
Expand Down

0 comments on commit e2196d4

Please sign in to comment.