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

WIP: flatten ?filters=(...) to ?f=...&f=... #4810

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
9 changes: 8 additions & 1 deletion assets/js/dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { createAppRouter } from './dashboard/router'
import ErrorBoundary from './dashboard/error/error-boundary'
import * as api from './dashboard/api'
import * as timer from './dashboard/util/realtime-update-timer'
import { filtersBackwardsCompatibilityRedirect } from './dashboard/query'
import { filtersBackwardsCompatibilityRedirect, filtersBackwardsCompatibilityRedirect2 } from './dashboard/query'
import SiteContextProvider, {
parseSiteFromDataset
} from './dashboard/site-context'
Expand Down Expand Up @@ -43,6 +43,13 @@ if (container && container.dataset) {
console.error('Error redirecting in a backwards compatible way', e)
}

try {
filtersBackwardsCompatibilityRedirect2(window.location, window.history)
} catch (e) {
console.error('Error redirecting in a backwards compatible way', e)
}


const router = createAppRouter(site)

app = (
Expand Down
19 changes: 19 additions & 0 deletions assets/js/dashboard/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,25 @@ export function filtersBackwardsCompatibilityRedirect(
}
}

// Called once when dashboard is loaded load. Checks whether old filter style is used and if so,
// updates the filters and updates location
export function filtersBackwardsCompatibilityRedirect2(
windowLocation: Location,
windowHistory: History
) {
const searchRecord = parseSearch(windowLocation.search)
const getValue = (k: string) => searchRecord[k]

if (getValue('filters')) {
windowHistory.pushState(
{},
'',
`${windowLocation.pathname}${stringifySearch(searchRecord)}`
)
}
}


// Returns a boolean indicating whether the given query includes a
// non-empty goal filterset containing a single, or multiple revenue
// goals with the same currency. Used to decide whether to render
Expand Down
79 changes: 68 additions & 11 deletions assets/js/dashboard/util/url.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* @format */
import JsonURL from '@jsonurl/jsonurl'
import { PlausibleSite } from '../site-context'
import { Filter } from '../query'

export function apiPath(
site: Pick<PlausibleSite, 'domain'>,
Expand Down Expand Up @@ -72,18 +73,22 @@ export function trimURL(url: string, maxLength: number): string {
}
}

export function encodeURIComponentPermissive(input: string): string {
return (
encodeURIComponent(input)
/* @ts-expect-error API supposedly not present in compilation target */
.replaceAll('%2C', ',')
.replaceAll('%3A', ':')
.replaceAll('%2F', '/')
)
export function encodeURIComponentPermissive(
input: string,
permittedCharacters: string
): string {
return Array.from(permittedCharacters)
.map((character) => [encodeURIComponent(character), character])
.reduce(
(acc, [encodedCharacter, character]) =>
/* @ts-expect-error API supposedly not present in compilation target, but works in major browsers */
acc.replaceAll(encodedCharacter, character),
encodeURIComponent(input)
)
}

export function encodeSearchParamEntry([k, v]: [string, string]): string {
return `${encodeURIComponentPermissive(k)}=${encodeURIComponentPermissive(v)}`
return `${encodeURIComponentPermissive(k, ',:/')}=${encodeURIComponentPermissive(v, ',:/')}`
}

export function isSearchEntryDefined(
Expand All @@ -95,14 +100,45 @@ export function isSearchEntryDefined(
export function stringifySearch(
searchRecord: Record<string, unknown>
): '' | string {
const definedSearchEntries = Object.entries(searchRecord || {})
const { filters, labels, ...rest } = searchRecord || {}
const definedSearchEntries = Object.entries(rest)
.map(stringifySearchEntry)
.filter(isSearchEntryDefined)

const encodedSearchEntries = definedSearchEntries.map(encodeSearchParamEntry)

if (Array.isArray(filters) && filters.length) {
const serializedFilters = filters.map((f) => `f=${serializeFilter(f)}`)
const serializedLabels = Object.entries(labels ?? {}).map(
(entry) => `l=${serializeLabelsEntry(entry)}`
)
return `?${serializedFilters.concat(serializedLabels).concat(encodedSearchEntries).join('&')}`
}

return encodedSearchEntries.length ? `?${encodedSearchEntries.join('&')}` : ''
}
function serializeLabelsEntry([k, v]: [string, string]) {
return `${encodeURIComponentPermissive(k, ':/')},${encodeURIComponentPermissive(v, ':/')}`
}

function parseLabelsEntry(labelString: string) {
return labelString.split(',').map(decodeURIComponent) as string[]
}

function serializeFilter(f: Filter) {
const [operator, dimension, clauses] = f
const serializedFilter = [
operator,
dimension,
...clauses.map((c) => encodeURIComponentPermissive(c.toString(), ':/'))
].join(',')
return serializedFilter
}

function parseFilter(filterString: string) {
const [operator, dimension, ...unparsedClauses] = filterString.split(',')
return [operator, dimension, unparsedClauses.map(decodeURIComponent)]
}

export function stringifySearchEntry([key, value]: [string, unknown]): [
string,
Expand Down Expand Up @@ -148,6 +184,27 @@ export function parseSearchFragment(
export function parseSearch(searchString: string): Record<string, unknown> {
const urlSearchParams = new URLSearchParams(searchString)
const searchRecord: Record<string, unknown> = {}
urlSearchParams.forEach((v, k) => (searchRecord[k] = parseSearchFragment(v)))
const filters: unknown[] = []
const labels: Record<string, string> = {}
urlSearchParams.forEach((v, k) => {
if (k === 'f') {
filters.push(parseFilter(v))
return
}
if (k === 'l') {
const parsedLabel = parseLabelsEntry(v)
labels[parsedLabel[0]] = parsedLabel[1]
return
}

searchRecord[k] = parseSearchFragment(v)
})
if (filters.length) {
return {
...searchRecord,
labels,
filters
}
}
return searchRecord
}
Loading