Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Allow creating and editing limited views (#5925)
Artur Pataf2766e099fe2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3449d20d48..d8c61efdf1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ All notable changes to this project will be documented in this file.### Added- A visitor percentage breakdown is now shown on all reports, both on the dashboard and in the detailed breakdown+- Shared links can now be limited to a particular segment of the data### Removeddiff --git a/assets/js/dashboard.tsx b/assets/js/dashboard.tsxindex c4451df210..b0871d6873 100644--- a/assets/js/dashboard.tsx+++ b/assets/js/dashboard.tsx@@ -7,7 +7,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 { redirectForLegacyParams } from './dashboard/util/url-search-params'+import { maybeDoFERedirect } from './dashboard/util/url-search-params'import SiteContextProvider, {parseSiteFromDataset} from './dashboard/site-context'@@ -19,6 +19,8 @@ import {SomethingWentWrongMessage} from './dashboard/error/something-went-wrong'import {+ getLimitedToSegment,+ parseLimitedToSegmentId,parsePreloadedSegments,SegmentsContextProvider} from './dashboard/filtering/segments-context'@@ -39,8 +41,15 @@ if (container && container.dataset) {api.setSharedLinkAuth(sharedLinkAuth)}+ const limitedToSegmentId = parseLimitedToSegmentId(container.dataset)+ const preloadedSegments = parsePreloadedSegments(container.dataset)+ const limitedToSegment = getLimitedToSegment(+ limitedToSegmentId,+ preloadedSegments+ )+try {- redirectForLegacyParams(window.location, window.history)+ maybeDoFERedirect(window.location, window.history, limitedToSegment)} catch (e) {console.error('Error redirecting in a backwards compatible way', e)}@@ -83,7 +92,8 @@ if (container && container.dataset) {}><SegmentsContextProvider- preloadedSegments={parsePreloadedSegments(container.dataset)}+ limitedToSegment={limitedToSegment}+ preloadedSegments={preloadedSegments}><RouterProvider router={router} /></SegmentsContextProvider>diff --git a/assets/js/dashboard/components/error-panel.tsx b/assets/js/dashboard/components/error-panel.tsxindex f010aacc60..1ad5c68e82 100644--- a/assets/js/dashboard/components/error-panel.tsx+++ b/assets/js/dashboard/components/error-panel.tsx@@ -1,4 +1,4 @@-import React from 'react'+import React, { ReactNode } from 'react'import classNames from 'classnames'import {ArrowPathIcon,@@ -12,7 +12,7 @@ export const ErrorPanel = ({onClose,onRetry}: {- errorMessage: string+ errorMessage: ReactNodeclassName?: stringonClose?: () => voidonRetry?: () => voiddiff --git a/assets/js/dashboard/filtering/segments-context.test.tsx b/assets/js/dashboard/filtering/segments-context.test.tsxindex 01889aa5d3..3925e6d39b 100644--- a/assets/js/dashboard/filtering/segments-context.test.tsx+++ b/assets/js/dashboard/filtering/segments-context.test.tsx@@ -35,6 +35,7 @@ describe('SegmentsContext functions', () => {test('deleteOne works', () => {render(<SegmentsContextProvider+ limitedToSegment={null}preloadedSegments={[segmentOpenSource, segmentAPAC]}><TestComponent />@@ -51,7 +52,10 @@ describe('SegmentsContext functions', () => {test('addOne adds to head of list', async () => {render(- <SegmentsContextProvider preloadedSegments={[segmentAPAC]}>+ <SegmentsContextProvider+ limitedToSegment={null}+ preloadedSegments={[segmentAPAC]}+ ><TestComponent /></SegmentsContextProvider>)@@ -68,6 +72,7 @@ describe('SegmentsContext functions', () => {test('updateOne works: updated segment is at head of list', () => {render(<SegmentsContextProvider+ limitedToSegment={null}preloadedSegments={[segmentOpenSource, segmentAPAC]}><TestComponent />diff --git a/assets/js/dashboard/filtering/segments-context.tsx b/assets/js/dashboard/filtering/segments-context.tsxindex cbc15233e3..aacebb4bda 100644--- a/assets/js/dashboard/filtering/segments-context.tsx+++ b/assets/js/dashboard/filtering/segments-context.tsx@@ -17,17 +17,33 @@ export function parsePreloadedSegments(dataset: DOMStringMap): SavedSegments {return JSON.parse(dataset.segments!).map(handleSegmentResponse)}+export function parseLimitedToSegmentId(dataset: DOMStringMap): number | null {+ return JSON.parse(dataset.limitedToSegmentId!)+}++export function getLimitedToSegment(+ limitedToSegmentId: number | null,+ preloadedSegments: SavedSegments+): Pick<SavedSegment, 'id' | 'name'> | null {+ if (limitedToSegmentId !== null) {+ return preloadedSegments.find((s) => s.id === limitedToSegmentId) ?? null+ }+ return null+}+type ChangeSegmentState = (segment: (SavedSegment | SavedSegmentPublic) & { segment_data: SegmentData }) => voidconst initialValue: {segments: SavedSegments+ limitedToSegment: Pick<SavedSegment, 'id' | 'name'> | nullupdateOne: ChangeSegmentStateaddOne: ChangeSegmentStateremoveOne: ChangeSegmentState} = {segments: [],+ limitedToSegment: null,updateOne: () => {},addOne: () => {},removeOne: () => {}@@ -41,9 +57,11 @@ export const useSegmentsContext = () => {export const SegmentsContextProvider = ({preloadedSegments,+ limitedToSegment,children}: {preloadedSegments: SavedSegments+ limitedToSegment: Pick<SavedSegment, 'id' | 'name'> | nullchildren: ReactNode}) => {const [segments, setSegments] = useState(preloadedSegments)@@ -73,7 +91,13 @@ export const SegmentsContextProvider = ({return (<SegmentsContext.Provider- value={{ segments, removeOne, updateOne, addOne }}+ value={{+ segments,+ limitedToSegment,+ removeOne,+ updateOne,+ addOne+ }}>{children}</SegmentsContext.Provider>diff --git a/assets/js/dashboard/filtering/segments.test.ts b/assets/js/dashboard/filtering/segments.test.tsindex e896ac3d02..932d9eb79f 100644--- a/assets/js/dashboard/filtering/segments.test.ts+++ b/assets/js/dashboard/filtering/segments.test.ts@@ -1,7 +1,7 @@import { remapToApiFilters } from '../util/filters'import {formatSegmentIdAsLabelKey,- getSearchToApplySingleSegmentFilter,+ getSearchToSetSegmentFilter,getSegmentNamePlaceholder,isSegmentIdLabelKey,parseApiSegmentData,@@ -64,9 +64,57 @@ describe(`${parseApiSegmentData.name}`, () => {})})-describe(`${getSearchToApplySingleSegmentFilter.name}`, () => {- test('generated search function applies single segment correctly', () => {- const searchFunction = getSearchToApplySingleSegmentFilter({+describe(`${getSearchToSetSegmentFilter.name}`, () => {+ test('generated search function omits other filters segment correctly', () => {+ const searchFunction = getSearchToSetSegmentFilter(+ {+ name: 'APAC',+ id: 500+ },+ { omitAllOtherFilters: true }+ )+ const existingSearch = {+ date: '2025-02-10',+ filters: [+ ['is', 'country', ['US']],+ ['is', 'page', ['/blog']]+ ],+ labels: { US: 'United States' }+ }+ expect(searchFunction(existingSearch)).toEqual({+ date: '2025-02-10',+ filters: [['is', 'segment', [500]]],+ labels: { 'segment-500': 'APAC' }+ })+ })++ test('generated search function replaces existing segment filter correctly', () => {+ const searchFunction = getSearchToSetSegmentFilter({+ name: 'APAC',+ id: 500+ })+ const existingSearch = {+ date: '2025-02-10',+ filters: [+ ['is', 'segment', [100]],+ ['is', 'country', ['US']],+ ['is', 'page', ['/blog']]+ ],+ labels: { US: 'United States', 'segment-100': 'Scandinavia' }+ }+ expect(searchFunction(existingSearch)).toEqual({+ date: '2025-02-10',+ filters: [+ ['is', 'segment', [500]],+ ['is', 'country', ['US']],+ ['is', 'page', ['/blog']]+ ],+ labels: { US: 'United States', 'segment-500': 'APAC' }+ })+ })++ test('generated search function sets new segment filter correctly', () => {+ const searchFunction = getSearchToSetSegmentFilter({name: 'APAC',id: 500})@@ -80,8 +128,12 @@ describe(`${getSearchToApplySingleSegmentFilter.name}`, () => {}expect(searchFunction(existingSearch)).toEqual({date: '2025-02-10',- filters: [['is', 'segment', [500]]],- labels: { 'segment-500': 'APAC' }+ filters: [+ ['is', 'segment', [500]],+ ['is', 'country', ['US']],+ ['is', 'page', ['/blog']]+ ],+ labels: { US: 'United States', 'segment-500': 'APAC' }})})})@@ -187,7 +239,6 @@ describe(`${canExpandSegment.name}`, () => {it.each([[Role.admin], [Role.editor], [Role.owner]])('allows expanding site segment if the user is logged in and in the role %p',(role) => {- const site = { siteSegmentsAvailable: true }const user: UserContextValue = {loggedIn: true,role,@@ -197,8 +248,7 @@ describe(`${canExpandSegment.name}`, () => {expect(canExpandSegment({segment: { id: 1, owner_id: 1, type: SegmentType.site },- user,- site+ user})).toBe(true)}@@ -213,42 +263,11 @@ describe(`${canExpandSegment.name}`, () => {role: Role.owner,id: 111,team: { identifier: null, hasConsolidatedView: false }- },- site: { siteSegmentsAvailable: true }+ }})).toBe(true)})- it('forbids expanding site segment if site segments are not available', () => {- expect(- canExpandSegment({- segment: { id: 1, owner_id: 1, type: SegmentType.site },- user: {- loggedIn: true,- role: Role.owner,- id: 1,- team: { identifier: null, hasConsolidatedView: false }- },- site: { siteSegmentsAvailable: false }- })- ).toBe(false)- })-- it('forbids public role from expanding site segments', () => {- expect(- canExpandSegment({- segment: { id: 1, owner_id: null, type: SegmentType.site },- user: {- loggedIn: false,- role: Role.public,- id: null,- team: { identifier: null, hasConsolidatedView: false }- },- site: { siteSegmentsAvailable: false }- })- ).toBe(false)- })-it.each([[Role.viewer],[Role.billing],@@ -267,14 +286,13 @@ describe(`${canExpandSegment.name}`, () => {expect(canExpandSegment({segment: { id: 1, owner_id: 1, type: SegmentType.personal },- user,- site: { siteSegmentsAvailable: false }+ user})).toBe(true)})- it('forbids expanding personal segment of other users', () => {+ it('forbids even site owners from expanding the personal segment of other users', () => {expect(canExpandSegment({segment: { id: 2, owner_id: 222, type: SegmentType.personal },@@ -283,24 +301,25 @@ describe(`${canExpandSegment.name}`, () => {role: Role.owner,id: 111,team: { identifier: null, hasConsolidatedView: false }- },- site: { siteSegmentsAvailable: false }+ }})).toBe(false)})- it('forbids public role from expanding personal segments', () => {- expect(- canExpandSegment({- segment: { id: 1, owner_id: 1, type: SegmentType.personal },- user: {- loggedIn: false,- role: Role.public,- id: null,- team: { identifier: null, hasConsolidatedView: false }- },- site: { siteSegmentsAvailable: false }- })- ).toBe(false)- })+ it.each([[SegmentType.personal, SegmentType.site]])(+ 'forbids public role from expanding %s segments',+ (segmentType) => {+ expect(+ canExpandSegment({+ segment: { id: 1, owner_id: 1, type: segmentType },+ user: {+ loggedIn: false,+ role: Role.public,+ id: null,+ team: { identifier: null, hasConsolidatedView: false }+ }+ })+ ).toBe(false)+ }+ )})diff --git a/assets/js/dashboard/filtering/segments.ts b/assets/js/dashboard/filtering/segments.tsindex c1516138a8..ff3e324cd3 100644--- a/assets/js/dashboard/filtering/segments.ts+++ b/assets/js/dashboard/filtering/segments.ts@@ -115,16 +115,44 @@ export const parseApiSegmentData = ({...rest})-export function getSearchToApplySingleSegmentFilter(- segment: Pick<SavedSegment, 'id' | 'name'>+export function getSearchToRemoveSegmentFilter(): Required<AppNavigationTarget>['search'] {+ return (searchRecord) => {+ const updatedFilters = (+ (Array.isArray(searchRecord.filters)+ ? searchRecord.filters+ : []) as Filter[]+ ).filter((f) => !isSegmentFilter(f))+ const currentLabels = searchRecord.labels ?? {}+ return {+ ...searchRecord,+ filters: updatedFilters,+ labels: cleanLabels(updatedFilters, currentLabels)+ }+ }+}++export function getSearchToSetSegmentFilter(+ segment: Pick<SavedSegment, 'id' | 'name'>,+ options: { omitAllOtherFilters?: boolean } = {}): Required<AppNavigationTarget>['search'] {- return (search) => {- const filters = [['is', 'segment', [segment.id]]]- const labels = cleanLabels(filters, {}, 'segment', {+ return (searchRecord) => {+ const otherFilters = (+ (Array.isArray(searchRecord.filters)+ ? searchRecord.filters+ : []) as Filter[]+ ).filter((f) => !isSegmentFilter(f))+ const currentLabels = searchRecord.labels ?? {}++ const filters = [+ ['is', 'segment', [segment.id]],+ ...(options.omitAllOtherFilters ? [] : otherFilters)+ ]++ const labels = cleanLabels(filters, currentLabels, 'segment', {[formatSegmentIdAsLabelKey(segment.id)]: segment.name})return {- ...search,+ ...searchRecord,filters,labels}@@ -160,16 +188,13 @@ export function resolveFilters(export function canExpandSegment({segment,- site,user}: {segment: Pick<SavedSegment, 'id' | 'owner_id' | 'type'>- site: Pick<PlausibleSite, 'siteSegmentsAvailable'>user: UserContextValue}) {if (segment.type === SegmentType.site &&- site.siteSegmentsAvailable &&user.loggedIn &&ROLES_WITH_MAYBE_SITE_SEGMENTS.includes(user.role)) {@@ -213,6 +238,23 @@ export function isListableSegment({return false}+export function canSeeSegmentDetails({ user }: { user: UserContextValue }) {+ return user.loggedIn && user.role !== Role.public+}++export function canRemoveFilter(+ filter: Filter,+ limitedToSegment: Pick<SavedSegment, 'id' | 'name'> | null+) {+ if (isSegmentFilter(filter) && limitedToSegment) {+ const [_operation, _dimension, clauses] = filter+ return (+ clauses.length === 1 && String(limitedToSegment.id) === String(clauses[1])+ )+ }+ return true+}+export function findAppliedSegmentFilter({ filters }: { filters: Filter[] }) {const segmentFilter = filters.find(isSegmentFilter)if (!segmentFilter) {diff --git a/assets/js/dashboard/nav-menu/filter-menu.tsx b/assets/js/dashboard/nav-menu/filter-menu.tsxindex 12fa7c9997..ba1c6178a7 100644--- a/assets/js/dashboard/nav-menu/filter-menu.tsx+++ b/assets/js/dashboard/nav-menu/filter-menu.tsx@@ -11,6 +11,7 @@ import { popover, BlurMenuButtonOnEscape } from '../components/popover'import classNames from 'classnames'import { AppNavigationLink } from '../navigation/use-app-navigate'import { SearchableSegmentsSection } from './segments/searchable-segments-section'+import { useSegmentsContext } from '../filtering/segments-context'export function getFilterListItems({propsAvailable@@ -49,6 +50,7 @@ const FilterMenuItems = ({ closeDropdown }: { closeDropdown: () => void }) => {const columns = useMemo(() => getFilterListItems(site), [site])const buttonRef = useRef<HTMLButtonElement>(null)const panelRef = useRef<HTMLDivElement>(null)+ const { limitedToSegment } = useSegmentsContext()return (<>@@ -107,10 +109,12 @@ const FilterMenuItems = ({ closeDropdown }: { closeDropdown: () => void }) => {</div>))}</div>- <SearchableSegmentsSection- closeList={closeDropdown}- tooltipContainerRef={panelRef}- />+ {limitedToSegment === null && (+ <SearchableSegmentsSection+ closeList={closeDropdown}+ tooltipContainerRef={panelRef}+ />+ )}</Popover.Panel></Transition></>diff --git a/assets/js/dashboard/nav-menu/filter-pills-list.tsx b/assets/js/dashboard/nav-menu/filter-pills-list.tsxindex 6ca03290aa..307eae994e 100644--- a/assets/js/dashboard/nav-menu/filter-pills-list.tsx+++ b/assets/js/dashboard/nav-menu/filter-pills-list.tsx@@ -10,6 +10,8 @@ import { styledFilterText, plainFilterText } from '../util/filter-text'import { useAppNavigate } from '../navigation/use-app-navigate'import classNames from 'classnames'import { filterRoute } from '../router'+import { canRemoveFilter } from '../filtering/segments'+import { useSegmentsContext } from '../filtering/segments-context'export const PILL_X_GAP_PX = 16export const PILL_Y_GAP_PX = 8@@ -48,6 +50,7 @@ export const AppliedFilterPillsList = React.forwardRef<AppliedFilterPillsListProps>(({ className, style, slice, direction, pillClassName }, ref) => {const { query } = useQueryContext()+ const { limitedToSegment } = useSegmentsContext()const navigate = useAppNavigate()const renderableFilters =@@ -82,19 +85,21 @@ export const AppliedFilterPillsList = React.forwardRef<]}},- onRemoveClick: () => {- const newFilters = query.filters.filter(- (_, i) => i !== index + indexAdjustment- )+ onRemoveClick: canRemoveFilter(filter, limitedToSegment)+ ? () => {+ const newFilters = query.filters.filter(+ (_, i) => i !== index + indexAdjustment+ )- navigate({- search: (search) => ({- ...search,- filters: newFilters,- labels: cleanLabels(newFilters, query.labels)- })- })- }+ navigate({+ search: (searchRecord) => ({+ ...searchRecord,+ filters: newFilters,+ labels: cleanLabels(newFilters, query.labels)+ })+ })+ }+ : undefined}}))}className={className}diff --git a/assets/js/dashboard/nav-menu/segments/searchable-segments-section.tsx b/assets/js/dashboard/nav-menu/segments/searchable-segments-section.tsxindex fbbaaf2168..810553a420 100644--- a/assets/js/dashboard/nav-menu/segments/searchable-segments-section.tsx+++ b/assets/js/dashboard/nav-menu/segments/searchable-segments-section.tsx@@ -2,14 +2,12 @@ import React, { RefObject } from 'react'import { useQueryContext } from '../../query-context'import { useSiteContext } from '../../site-context'import {- formatSegmentIdAsLabelKey,- isSegmentFilter,SavedSegmentPublic,SavedSegment,SEGMENT_TYPE_LABELS,- isListableSegment+ isListableSegment,+ getSearchToSetSegmentFilter} from '../../filtering/segments'-import { cleanLabels } from '../../util/filters'import classNames from 'classnames'import { Tooltip } from '../../util/tooltip'import { SegmentAuthorship } from '../../segments/segment-authorship'@@ -170,26 +168,12 @@ const SegmentLink = ({}: Pick<SavedSegment, 'id' | 'name'> & {closeList: () => void}) => {- const { query } = useQueryContext()-return (<AppNavigationLinkclassName={linkClassName}key={id}onClick={closeList}- search={(search) => {- const otherFilters = query.filters.filter((f) => !isSegmentFilter(f))-- const updatedFilters = [['is', 'segment', [id]], ...otherFilters]-- return {- ...search,- filters: updatedFilters,- labels: cleanLabels(updatedFilters, query.labels, 'segment', {- [formatSegmentIdAsLabelKey(id)]: name- })- }- }}+ search={getSearchToSetSegmentFilter({ id, name })}><div className="truncate">{name}</div></AppNavigationLink>diff --git a/assets/js/dashboard/navigation/use-app-navigate.tsx b/assets/js/dashboard/navigation/use-app-navigate.tsxindex c8342c9d6c..c3d171ac81 100644--- a/assets/js/dashboard/navigation/use-app-navigate.tsx+++ b/assets/js/dashboard/navigation/use-app-navigate.tsx@@ -9,6 +9,8 @@ import {LinkProps} from 'react-router-dom'import { parseSearch, stringifySearch } from '../util/url-search-params'+import { useSegmentsContext } from '../filtering/segments-context'+import { getSearchToSetSegmentFilter } from '../filtering/segments'export type AppNavigationTarget = {/**@@ -24,7 +26,7 @@ export type AppNavigationTarget = {* - `(s) => s` preserves current search value,* - `(s) => ({ ...s, calendar: !s.calendar })` toggles the value for calendar search parameter,* - `() => ({ page: 5 })` sets the search to `?page=5`,- * - `undefined` empties the search+ * - `undefined` empties the search, except for the enforced segment*/search?: (search: Record<string, unknown>) => Record<string, unknown>}@@ -44,11 +46,24 @@ const getNavigateToOptions = (export const useGetNavigateOptions = () => {const location = useLocation()+ const { limitedToSegment } = useSegmentsContext()+const getToOptions = useCallback(({ path, params, search }: AppNavigationTarget) => {- return getNavigateToOptions(location.search, { path, params, search })+ const wrappedSearch: typeof search = (searchRecord) => {+ const updatedSearchRecord =+ typeof search === 'function' ? search(searchRecord) : searchRecord+ return limitedToSegment+ ? getSearchToSetSegmentFilter(limitedToSegment)(updatedSearchRecord)+ : updatedSearchRecord+ }+ return getNavigateToOptions(location.search, {+ path,+ params,+ search: wrappedSearch+ })},- [location.search]+ [location.search, limitedToSegment])return getToOptions}diff --git a/assets/js/dashboard/segments/routeless-segment-modals.tsx b/assets/js/dashboard/segments/routeless-segment-modals.tsxindex 024a9d4b8f..6541b5d93a 100644--- a/assets/js/dashboard/segments/routeless-segment-modals.tsx+++ b/assets/js/dashboard/segments/routeless-segment-modals.tsx@@ -5,7 +5,7 @@ import {UpdateSegmentModal} from './segment-modals'import {- getSearchToApplySingleSegmentFilter,+ getSearchToSetSegmentFilter,getSegmentNamePlaceholder,handleSegmentResponse,SavedSegment,@@ -67,7 +67,9 @@ export const RoutelessSegmentModals = () => {updateOne(segment)queryClient.invalidateQueries({ queryKey: ['segments'] })navigate({- search: getSearchToApplySingleSegmentFilter(segment),+ search: getSearchToSetSegmentFilter(segment, {+ omitAllOtherFilters: true+ }),state: {expandedSegment: null}@@ -104,7 +106,9 @@ export const RoutelessSegmentModals = () => {addOne(segment)queryClient.invalidateQueries({ queryKey: ['segments'] })navigate({- search: getSearchToApplySingleSegmentFilter(segment),+ search: getSearchToSetSegmentFilter(segment, {+ omitAllOtherFilters: true+ }),state: {expandedSegment: null}diff --git a/assets/js/dashboard/segments/segment-modals.test.tsx b/assets/js/dashboard/segments/segment-modals.test.tsxindex 92535aaad7..a22160928e 100644--- a/assets/js/dashboard/segments/segment-modals.test.tsx+++ b/assets/js/dashboard/segments/segment-modals.test.tsx@@ -4,6 +4,7 @@ import { SegmentModal } from './segment-modals'import { TestContextProviders } from '../../../test-utils/app-context-providers'import {SavedSegment,+ SavedSegmentPublic,SavedSegments,SegmentData,SegmentType@@ -18,7 +19,7 @@ beforeEach(() => {})describe('Segment details modal - errors', () => {- const anySiteSegment: SavedSegment & { segment_data: SegmentData } = {+ const anySegment: SavedSegment & { segment_data: SegmentData } = {id: 1,type: SegmentType.site,owner_id: 1,@@ -33,7 +34,7 @@ describe('Segment details modal - errors', () => {}const anyPersonalSegment: SavedSegment & { segment_data: SegmentData } = {- ...anySiteSegment,+ ...anySegment,id: 2,type: SegmentType.personal}@@ -48,7 +49,7 @@ describe('Segment details modal - errors', () => {}[] = [{case: 'segment is not in list',- segments: [anyPersonalSegment, anySiteSegment],+ segments: [anyPersonalSegment, anySegment],segmentId: 202020,user: {loggedIn: true,@@ -81,12 +82,125 @@ describe('Segment details modal - errors', () => {})describe('Segment details modal - other cases', () => {- it('displays site segment correctly', () => {- const anySiteSegment: SavedSegment & { segment_data: SegmentData } = {+ it.each([+ [SegmentType.site, 'Site segment'],+ [SegmentType.personal, 'Personal segment']+ ])(+ 'displays segment with type %s correctly for logged in user',+ (segmentType, expectedSegmentTypeText) => {+ const user: UserContextValue = {+ loggedIn: true,+ role: Role.editor,+ id: 1,+ team: { identifier: null, hasConsolidatedView: false }+ }+ const anySegment: SavedSegment & { segment_data: SegmentData } = {+ id: 100,+ type: segmentType,+ owner_id: user.id,+ owner_name: 'Jane Smith',+ name: 'Blog or About',+ segment_data: {+ filters: [['is', 'page', ['/blog', '/about']]],+ labels: {}+ },+ inserted_at: '2025-03-13T13:00:00',+ updated_at: '2025-03-13T16:00:00'+ }++ render(<SegmentModal id={anySegment.id} />, {+ wrapper: (props) => (+ <TestContextProviders+ user={user}+ preloaded={{+ segments: [anySegment]+ }}+ siteOptions={{ siteSegmentsAvailable: true }}+ {...props}+ />+ )+ })+ expect(screen.getByText(anySegment.name)).toBeVisible()+ expect(screen.getByText(expectedSegmentTypeText)).toBeVisible()++ expect(screen.getByText('Filters in segment')).toBeVisible()+ expect(screen.getByTitle('Page is /blog or /about')).toBeVisible()++ expect(+ screen.getByText(`Last updated at 13 Mar by ${anySegment.owner_name}`)+ ).toBeVisible()+ expect(screen.getByText(`Created at 13 Mar`)).toBeVisible()++ expect(screen.getByText('Edit segment')).toBeVisible()+ expect(screen.getByText('Remove filter')).toBeVisible()+ }+ )++ it.each([+ [SegmentType.site, 'Site segment'],+ [SegmentType.personal, 'Personal segment']+ ])(+ 'displays segment with type %s correctly for public role',+ (segmentType, expectedSegmentTypeText) => {+ const user: UserContextValue = {+ loggedIn: false,+ role: Role.public,+ id: null,+ team: { identifier: null, hasConsolidatedView: false }+ }+ const anySegment: SavedSegment & { segment_data: SegmentData } = {+ id: 100,+ type: segmentType,+ owner_id: null,+ owner_name: null,+ name: 'Blog or About',+ segment_data: {+ filters: [['is', 'page', ['/blog', '/about']]],+ labels: {}+ },+ inserted_at: '2025-03-13T13:00:00',+ updated_at: '2025-03-13T16:00:00'+ }++ render(<SegmentModal id={anySegment.id} />, {+ wrapper: (props) => (+ <TestContextProviders+ user={user}+ preloaded={{+ segments: [anySegment]+ }}+ siteOptions={{ siteSegmentsAvailable: true }}+ {...props}+ />+ )+ })+ expect(screen.getByText(anySegment.name)).toBeVisible()+ expect(screen.getByText(expectedSegmentTypeText)).toBeVisible()++ expect(screen.getByText('Filters in segment')).toBeVisible()+ expect(screen.getByTitle('Page is /blog or /about')).toBeVisible()++ expect(screen.getByText(`Last updated at 13 Mar`)).toBeVisible()+ expect(screen.queryByText('by ')).toBeNull() // no segment author is shown to public role+ expect(screen.getByText(`Created at 13 Mar`)).toBeVisible()++ expect(screen.getByText('Remove filter')).toBeVisible()+ expect(screen.queryByText('Edit segment')).toBeNull()+ }+ )++ it('allows elevated roles to expand site segments even if site segments are not available on their plan (to update type to personal segment)', () => {+ const user: UserContextValue = {+ loggedIn: true,+ role: Role.owner,+ id: 1,+ team: { identifier: null, hasConsolidatedView: false }+ }+ const anySegment: SavedSegmentPublic & { segment_data: SegmentData } = {id: 100,type: SegmentType.site,- owner_id: 100100,- owner_name: 'Test User',+ owner_id: null,+ owner_name: null,name: 'Blog or About',segment_data: {filters: [['is', 'page', ['/blog', '/about']]],@@ -96,35 +210,77 @@ describe('Segment details modal - other cases', () => {updated_at: '2025-03-13T16:00:00'}- render(<SegmentModal id={anySiteSegment.id} />, {+ render(<SegmentModal id={anySegment.id} />, {wrapper: (props) => (<TestContextProviders- user={{- loggedIn: true,- role: Role.editor,- id: 1,- team: { identifier: null, hasConsolidatedView: false }- }}+ user={user}preloaded={{- segments: [anySiteSegment]+ segments: [anySegment]}}- siteOptions={{ siteSegmentsAvailable: true }}+ siteOptions={{ siteSegmentsAvailable: false }}{...props}/>)})- expect(screen.getByText(anySiteSegment.name)).toBeVisible()+ expect(screen.getByText(anySegment.name)).toBeVisible()expect(screen.getByText('Site segment')).toBeVisible()expect(screen.getByText('Filters in segment')).toBeVisible()expect(screen.getByTitle('Page is /blog or /about')).toBeVisible()expect(- screen.getByText(`Last updated at 13 Mar by ${anySiteSegment.owner_name}`)+ screen.getByText(`Last updated at 13 Mar by (Removed User)`)).toBeVisible()expect(screen.getByText(`Created at 13 Mar`)).toBeVisible()- expect(screen.getByText('Edit segment')).toBeVisible()expect(screen.getByText('Remove filter')).toBeVisible()+ expect(screen.getByText('Edit segment')).toBeVisible()+ })++ it('does not display clear filter button if the dashboard is limited to this segment', () => {+ const user: UserContextValue = {+ loggedIn: false,+ role: Role.public,+ id: null,+ team: { identifier: null, hasConsolidatedView: false }+ }+ const anySegment: SavedSegmentPublic & { segment_data: SegmentData } = {+ id: 100,+ type: SegmentType.site,+ owner_id: null,+ owner_name: null,+ name: 'Blog or About',+ segment_data: {+ filters: [['is', 'page', ['/blog', '/about']]],+ labels: {}+ },+ inserted_at: '2025-03-13T13:00:00',+ updated_at: '2025-03-13T16:00:00'+ }++ render(<SegmentModal id={anySegment.id} />, {+ wrapper: (props) => (+ <TestContextProviders+ user={user}+ preloaded={{+ segments: [anySegment]+ }}+ limitedToSegment={anySegment}+ siteOptions={{ siteSegmentsAvailable: true }}+ {...props}+ />+ )+ })+ expect(screen.getByText(anySegment.name)).toBeVisible()+ expect(screen.getByText('Site segment')).toBeVisible()++ expect(screen.getByText('Filters in segment')).toBeVisible()+ expect(screen.getByTitle('Page is /blog or /about')).toBeVisible()++ expect(screen.getByText(`Last updated at 13 Mar`)).toBeVisible()+ expect(screen.getByText(`Created at 13 Mar`)).toBeVisible()++ expect(screen.queryByText('Remove filter')).toBeNull()+ expect(screen.queryByText('Edit segment')).toBeNull()})})diff --git a/assets/js/dashboard/segments/segment-modals.tsx b/assets/js/dashboard/segments/segment-modals.tsxindex 1261a24a0c..92c18f1b69 100644--- a/assets/js/dashboard/segments/segment-modals.tsx+++ b/assets/js/dashboard/segments/segment-modals.tsx@@ -1,24 +1,26 @@import React, { ReactNode, useCallback, useState } from 'react'import ModalWithRouting from '../stats/modals/modal'import {+ canRemoveFilter,+ getSearchToRemoveSegmentFilter,canExpandSegment,- isSegmentFilter,SavedSegment,SEGMENT_TYPE_LABELS,SegmentData,SegmentType} from '../filtering/segments'-import { useQueryContext } from '../query-context'-import { AppNavigationLink } from '../navigation/use-app-navigate'-import { cleanLabels } from '../util/filters'+import {+ AppNavigationLink,+ useAppNavigate+} from '../navigation/use-app-navigate'import { plainFilterText, styledFilterText } from '../util/filter-text'import { rootRoute } from '../router'import { FilterPillsList } from '../nav-menu/filter-pills-list'import classNames from 'classnames'import { SegmentAuthorship } from './segment-authorship'import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'-import { MutationStatus } from '@tanstack/react-query'-import { ApiError } from '../api'+import { MutationStatus, useQuery } from '@tanstack/react-query'+import { ApiError, get } from '../api'import { ErrorPanel } from '../components/error-panel'import { useSegmentsContext } from '../filtering/segments-context'import { Role, UserContextValue, useUserContext } from '../user-context'@@ -42,7 +44,8 @@ const primaryNeutralButtonClassName = 'button !px-3'const primaryNegativeButtonClassName = classNames('button !px-3.5',- 'items-center !bg-red-500 dark:!bg-red-500 hover:!bg-red-600 dark:hover:!bg-red-700 whitespace-nowrap'+ 'items-center !bg-red-500 dark:!bg-red-500 hover:!bg-red-600 dark:hover:!bg-red-700 whitespace-nowrap',+ 'disabled:!bg-red-400 disabled:cursor-not-allowed')const secondaryButtonClassName = classNames(@@ -105,7 +108,7 @@ export const CreateSegmentModal = ({return (<SegmentActionModal onClose={onClose}>- <FormTitle>Create segment</FormTitle>+ <FormTitle className="mb-8">Create segment</FormTitle><SegmentNameInputvalue={name}onChange={setName}@@ -143,6 +146,12 @@ export const CreateSegmentModal = ({)}+function getLinksDeleteNotice(links: string[]) {+ return links.length === 1+ ? 'This segment is used in a shared link. To delete it, you also need to delete the shared link.'+ : `This segment is used in ${links.length} shared links. To delete it, you also need to delete the shared links.`+}+export const DeleteSegmentModal = ({onClose,onSave,@@ -155,22 +164,77 @@ export const DeleteSegmentModal = ({onSave: (input: Pick<SavedSegment, 'id'>) => voidsegment: SavedSegment & { segment_data?: SegmentData }} & ApiRequestProps) => {+ const site = useSiteContext()+ const [confirmed, setConfirmed] = useState(false)++ const linksQuery = useQuery({+ queryKey: [segment.id],+ queryFn: async () => {+ const response: string[] = await get(+ `/api/${encodeURIComponent(site.domain)}/segments/${segment.id}/shared-links`+ )+ return response+ }+ })++ const deleteDisabled =+ status === 'pending' ||+ linksQuery.status !== 'success' ||+ (!!linksQuery.data?.length && !confirmed)+return (<SegmentActionModal onClose={onClose}>- <FormTitle>+ <FormTitle className="mb-4">Delete {SEGMENT_TYPE_LABELS[segment.type].toLowerCase()}<span className="break-all">{` "${segment.name}"?`}</span></FormTitle>+ {linksQuery.status === 'pending' && (+ <div className="loading sm">+ <div />+ </div>+ )}+ {linksQuery.status === 'success' && !!linksQuery.data?.length && (+ <ErrorPanel+ errorMessage={+ <span className="break-normal">+ {getLinksDeleteNotice(linksQuery.data)}+ </span>+ }+ />+ )}+ {linksQuery.status === 'error' && (+ <ErrorPanel+ errorMessage="Error loading related shared links"+ onRetry={linksQuery.refetch}+ />+ )}{!!segment.segment_data && (- <FiltersInSegment segment_data={segment.segment_data} />+ <div className="mt-4">+ <FiltersInSegment segment_data={segment.segment_data} />+ </div>+ )}+ {!!linksQuery.data?.length && (+ <>+ <div className="mt-4">+ <RelatedSharedLinks sharedLinks={linksQuery.data} />+ </div>+ <div className="mt-4">+ <Checkbox+ id="confirm"+ checked={confirmed}+ onChange={(e) => setConfirmed(e.currentTarget.checked)}+ >+ Yes, delete the associated shared links+ </Checkbox>+ </div>+ </>)}-<ButtonsRow><buttonclassName={primaryNegativeButtonClassName}- disabled={status === 'pending'}+ disabled={deleteDisabled}onClick={- status === 'pending'+ deleteDisabled? () => {}: () => {onSave({ id: segment.id })@@ -198,8 +262,39 @@ export const DeleteSegmentModal = ({)}-const FormTitle = ({ children }: { children?: ReactNode }) => (- <h1 className="text-lg font-medium text-gray-900 dark:text-gray-100 leading-7 mb-8">+const RelatedSharedLinks = ({ sharedLinks }: { sharedLinks: string[] }) => {+ return (+ <>+ <SecondaryTitle>Shared links</SecondaryTitle>+ <div className="mt-2">+ <FilterPillsList+ className="flex-wrap"+ direction="horizontal"+ pills={sharedLinks.map((name) => ({+ className: 'dark:!shadow-gray-950/60',+ plainText: name,+ children: name,+ interactive: false+ }))}+ />+ </div>+ </>+ )+}++const FormTitle = ({+ className,+ children+}: {+ className?: string+ children?: ReactNode+}) => (+ <h1+ className={classNames(+ 'text-lg font-medium text-gray-900 dark:text-gray-100 leading-7',+ className+ )}+ >{children}</h1>)@@ -412,7 +507,7 @@ export const UpdateSegmentModal = ({return (<SegmentActionModal onClose={onClose}>- <FormTitle>Update segment</FormTitle>+ <FormTitle className="mb-8">Update segment</FormTitle><SegmentNameInputvalue={name}onChange={setName}@@ -453,7 +548,7 @@ export const UpdateSegmentModal = ({const FiltersInSegment = ({ segment_data }: { segment_data: SegmentData }) => {return (<>- <h2 className="font-bold dark:text-gray-100">Filters in segment</h2>+ <SecondaryTitle>Filters in segment</SecondaryTitle><div className="mt-2"><FilterPillsListclassName="flex-wrap"@@ -470,6 +565,37 @@ const FiltersInSegment = ({ segment_data }: { segment_data: SegmentData }) => {)}+const SecondaryTitle = ({ children }: { children: ReactNode }) => (+ <h2 className="font-bold dark:text-gray-100">{children}</h2>+)++/** Keep this component styled the same as checkboxes in PlausibleWeb.Live.Installation.Instructions */+const Checkbox = ({+ id,+ checked,+ onChange,+ children+}: React.DetailedHTMLProps<+ React.InputHTMLAttributes<HTMLInputElement>,+ HTMLInputElement+>) => {+ return (+ <label+ className="text-sm block font-medium dark:text-gray-100 font-normal gap-x-2 flex flex-inline items-center justify-start"+ htmlFor={id}+ >+ <input+ className="block size-5 rounded-sm dark:bg-gray-600 border-gray-300 dark:border-gray-600 text-indigo-600"+ id={id}+ type="checkbox"+ checked={checked}+ onChange={onChange}+ />+ {children}+ </label>+ )+}+const Placeholder = ({children,placeholder@@ -495,10 +621,9 @@ const hasSiteSegmentPermission = (user: UserContextValue) => {}export const SegmentModal = ({ id }: { id: SavedSegment['id'] }) => {- const site = useSiteContext()const user = useUserContext()- const { query } = useQueryContext()- const { segments } = useSegmentsContext()+ const { segments, limitedToSegment } = useSegmentsContext()+ const navigate = useAppNavigate()const segment = segments.find((s) => String(s.id) === String(id))@@ -512,6 +637,11 @@ export const SegmentModal = ({ id }: { id: SavedSegment['id'] }) => {const data = !error ? segment : null+ const showClearButton = canRemoveFilter(+ ['is', 'segment', [id]],+ limitedToSegment+ )+return (<ModalWithRouting maxWidth="460px"><div className="dark:text-gray-100 mb-8">@@ -540,7 +670,7 @@ export const SegmentModal = ({ id }: { id: SavedSegment['id'] }) => {/><div className="mt-4"><ButtonsRow>- {canExpandSegment({ segment: data, site, user }) && (+ {canExpandSegment({ segment: data, user }) && (<AppNavigationLinkclassName={primaryNeutralButtonClassName}path={rootRoute.path}@@ -557,27 +687,19 @@ export const SegmentModal = ({ id }: { id: SavedSegment['id'] }) => {</AppNavigationLink>)}- <AppNavigationLink- className={removeFilterButtonClassname}- path={rootRoute.path}- search={(s) => {- const nonSegmentFilters = query.filters.filter(- (f) => !isSegmentFilter(f)- )- return {- ...s,- filters: nonSegmentFilters,- labels: cleanLabels(- nonSegmentFilters,- query.labels,- 'segment',- {}- )+ {showClearButton && (+ <button+ className={removeFilterButtonClassname}+ onClick={() =>+ navigate({+ path: rootRoute.path,+ search: getSearchToRemoveSegmentFilter()+ })}- }}- >- Remove filter- </AppNavigationLink>+ >+ Remove filter+ </button>+ )}</ButtonsRow></div></>diff --git a/assets/js/dashboard/stats/graph/line-graph.js b/assets/js/dashboard/stats/graph/line-graph.jsindex ef45b2fa4a..4b10e73409 100644--- a/assets/js/dashboard/stats/graph/line-graph.js+++ b/assets/js/dashboard/stats/graph/line-graph.js@@ -247,11 +247,11 @@ class LineGraph extends React.Component {if (this.props.graphData.interval === 'month') {this.props.navigate({- search: (search) => ({ ...search, period: 'month', date })+ search: (searchRecord) => ({ ...searchRecord, period: 'month', date })})} else if (this.props.graphData.interval === 'day') {this.props.navigate({- search: (search) => ({ ...search, period: 'day', date })+ search: (searchRecord) => ({ ...searchRecord, period: 'day', date })})}}diff --git a/assets/js/dashboard/stats/locations/map.tsx b/assets/js/dashboard/stats/locations/map.tsxindex 593a5747d8..5ef90cf0dd 100644--- a/assets/js/dashboard/stats/locations/map.tsx+++ b/assets/js/dashboard/stats/locations/map.tsx@@ -106,7 +106,9 @@ const WorldMap = ({[country.code]: country.name})onCountrySelect()- navigate({ search: (search) => ({ ...search, filters, labels }) })+ navigate({+ search: (searchRecord) => ({ ...searchRecord, filters, labels })+ })}},[navigate, query, dataByCountryCode, onCountrySelect]diff --git a/assets/js/dashboard/stats/modals/filter-modal.js b/assets/js/dashboard/stats/modals/filter-modal.jsindex ba40bfc039..71d6c8a495 100644--- a/assets/js/dashboard/stats/modals/filter-modal.js+++ b/assets/js/dashboard/stats/modals/filter-modal.js@@ -120,8 +120,8 @@ class FilterModal extends React.Component {selectFiltersAndCloseModal(filters) {this.props.navigate({path: rootRoute.path,- search: (search) => ({- ...search,+ search: (searchRecord) => ({+ ...searchRecord,filters: filters,labels: cleanLabels(filters, this.state.labelState)}),diff --git a/assets/js/dashboard/util/url-search-params.test.ts b/assets/js/dashboard/util/url-search-params.test.tsindex 91ecbb6b28..6f99dfa4c1 100644--- a/assets/js/dashboard/util/url-search-params.test.ts+++ b/assets/js/dashboard/util/url-search-params.test.ts@@ -1,8 +1,9 @@import { Filter } from '../query'import {encodeURIComponentPermissive,+ getSearchWithEnforcedSegment,isSearchEntryDefined,- getRedirectTarget,+ maybeGetLatestReadableSearch,parseFilter,parseLabelsEntry,parseSearch,@@ -206,61 +207,55 @@ describe(`${stringifySearch.name}`, () => {})})-describe(`${getRedirectTarget.name}`, () => {+describe(`${maybeGetLatestReadableSearch.name}`, () => {it.each([[''],['?auth=_Y6YOjUl2beUJF_XzG1hk&theme=light&background=%23ee00ee'],['?keybindHint=Escape&with_imported=true'],['?f=is,page,/blog/:category/:article-name&date=2024-10-10&period=day'],['?f=is,country,US&l=US,United%20States']- ])('for modern search %p returns null', (search) => {- expect(- getRedirectTarget({- pathname: '/example.com%2Fdeep%2Fpath',- search- } as Location)- ).toBeNull()+ ])('for modern search string %p returns null', (search) => {+ expect(maybeGetLatestReadableSearch(search)).toBeNull()})- it('returns updated URL for jsonurl style filters (v2), and running the updated value through the function again returns null (no redirect loop)', () => {- const pathname = '/'+ it('returns updated search string for jsonurl style filters (v2), and running the updated value through the function again returns null (no redirect loop)', () => {const search ='?filters=((is,exit_page,(/plausible.io)),(is,source,(Brave)),(is,city,(993800)))&labels=(993800:Johannesburg)'const expectedUpdatedSearch ='?f=is,exit_page,/plausible.io&f=is,source,Brave&f=is,city,993800&l=993800,Johannesburg&r=v2'- expect(- getRedirectTarget({- pathname,- search- } as Location)- ).toEqual(`${pathname}${expectedUpdatedSearch}`)- expect(- getRedirectTarget({- pathname,- search: expectedUpdatedSearch- } as Location)- ).toBeNull()+ expect(maybeGetLatestReadableSearch(search)).toEqual(expectedUpdatedSearch)+ expect(maybeGetLatestReadableSearch(expectedUpdatedSearch)).toBeNull()})it.each([['?page=/docs', '?f=is,page,/docs&r=v1'],- ['?page=%C3%AA&embed=true', '?f=is,page,%C3%AA&embed=true&r=v1']+ ['?page=%C3%AA&embed=true', '?f=is,page,%C3%AA&embed=true&r=v1'],+ [+ '?page=/|/foo&goal=~Signup&source=!Facebook|Instagram',+ '?f=is,page,/,/foo&f=contains,goal,Signup&f=is_not,source,Facebook,Instagram&r=v1'+ ]])(- 'returns updated URL v1 style filter %s, and running the updated value through the function again returns null (no redirect loop)',+ 'returns updated search string v1 style filter %s, and running the updated value through the function again returns null (no redirect loop)',(searchString, expectedSearchString) => {- const pathname = '/'- expect(- getRedirectTarget({- pathname,- search: searchString- } as Location)- ).toEqual(`${pathname}${expectedSearchString}`)- expect(- getRedirectTarget({- pathname,- search: expectedSearchString- } as Location)- ).toBeNull()+ expect(maybeGetLatestReadableSearch(searchString)).toEqual(+ expectedSearchString+ )+ expect(maybeGetLatestReadableSearch(expectedSearchString)).toBeNull()})})++describe(`${getSearchWithEnforcedSegment.name}`, () => {+ it('adds enforced segment appropriately, and running the updated value through the function again returns the same value', () => {+ const segment = { id: 100, name: 'Eastern Europe' }+ const search = '?auth=foo&embed=true'+ const expectedUpdatedSearch =+ '?f=is,segment,100&l=segment-100,Eastern%20Europe&auth=foo&embed=true'+ expect(getSearchWithEnforcedSegment(search, segment)).toEqual(+ expectedUpdatedSearch+ )+ expect(+ getSearchWithEnforcedSegment(expectedUpdatedSearch, segment)+ ).toEqual(expectedUpdatedSearch)+ })+})diff --git a/assets/js/dashboard/util/url-search-params.ts b/assets/js/dashboard/util/url-search-params.tsindex be8ce5d9a0..ab9bbfa996 100644--- a/assets/js/dashboard/util/url-search-params.ts+++ b/assets/js/dashboard/util/url-search-params.ts@@ -1,3 +1,7 @@+import {+ getSearchToSetSegmentFilter,+ SavedSegment+} from '../filtering/segments'import { Filter, FilterClauseLabels } from '../query'import { v1 } from './url-search-params-v1'import { v2 } from './url-search-params-v2'@@ -230,8 +234,10 @@ function isAlreadyRedirected(searchParams: URLSearchParams) {The purpose of this function is to redirect users from one of the previous versions to the current version,so previous dashboard links still work.*/-export function getRedirectTarget(windowLocation: Location): null | string {- const searchParams = new URLSearchParams(windowLocation.search)+export function maybeGetLatestReadableSearch(+ searchString: string+): null | string {+ const searchParams = new URLSearchParams(searchString)if (isAlreadyRedirected(searchParams)) {return null}@@ -244,24 +250,64 @@ export function getRedirectTarget(windowLocation: Location): null | string {const isV1 = v1.isV1(searchParams)if (isV2) {- return `${windowLocation.pathname}${stringifySearch({ ...v2.parseSearch(windowLocation.search), [REDIRECTED_SEARCH_PARAM_NAME]: 'v2' })}`+ return stringifySearch({+ ...v2.parseSearch(searchString),+ [REDIRECTED_SEARCH_PARAM_NAME]: 'v2'+ })}if (isV1) {- return `${windowLocation.pathname}${stringifySearch({ ...v1.parseSearch(windowLocation.search), [REDIRECTED_SEARCH_PARAM_NAME]: 'v1' })}`+ return stringifySearch({+ ...v1.parseSearch(searchString),+ [REDIRECTED_SEARCH_PARAM_NAME]: 'v1'+ })}return null}+/**+ * It's possible to set a particular segment to be always applied on the data on dashboards accessed with a shared link.+ * This function ensures that the particular segment filter is set to the URL string on initial page load.+ * Other functions ensure that it can't be removed.+ */+export function getSearchWithEnforcedSegment(+ searchString: string,+ enforcedSegment: Pick<SavedSegment, 'id' | 'name'>+): string {+ const searchRecord = parseSearch(searchString)+ return stringifySearch(+ getSearchToSetSegmentFilter(enforcedSegment)(searchRecord)+ )+}+/** Called once before React app mounts. If legacy url search params are present, does a redirect to new format. */-export function redirectForLegacyParams(+export function maybeDoFERedirect(windowLocation: Location,- windowHistory: History+ windowHistory: History,+ enforcedSegment: Pick<SavedSegment, 'id' | 'name'> | null) {- const redirectTargetURL = getRedirectTarget(windowLocation)- if (redirectTargetURL === null) {+ const originalSearchString = windowLocation.search++ let updatedSearchString = maybeGetLatestReadableSearch(originalSearchString)++ if (enforcedSegment) {+ updatedSearchString = getSearchWithEnforcedSegment(+ updatedSearchString ?? originalSearchString,+ enforcedSegment+ )+ }++ if (+ updatedSearchString === null ||+ updatedSearchString === originalSearchString+ ) {return}- windowHistory.pushState({}, '', redirectTargetURL)++ windowHistory.pushState(+ {},+ '',+ `${windowLocation.pathname}${updatedSearchString}`+ )}diff --git a/assets/test-utils/app-context-providers.tsx b/assets/test-utils/app-context-providers.tsxindex 17f4bf4b3b..d5e059a112 100644--- a/assets/test-utils/app-context-providers.tsx+++ b/assets/test-utils/app-context-providers.tsx@@ -12,7 +12,7 @@ import QueryContextProvider from '../js/dashboard/query-context'import { getRouterBasepath } from '../js/dashboard/router'import { RoutelessModalsContextProvider } from '../js/dashboard/navigation/routeless-modals-context'import { SegmentsContextProvider } from '../js/dashboard/filtering/segments-context'-import { SavedSegments } from '../js/dashboard/filtering/segments'+import { SavedSegment, SavedSegments } from '../js/dashboard/filtering/segments'type TestContextProvidersProps = {children: ReactNode@@ -20,6 +20,7 @@ type TestContextProvidersProps = {siteOptions?: Partial<PlausibleSite>user?: UserContextValuepreloaded?: { segments?: SavedSegments }+ limitedToSegment?: SavedSegment | null}export const DEFAULT_SITE: PlausibleSite = {@@ -51,6 +52,7 @@ export const TestContextProviders = ({routerProps,siteOptions,preloaded,+ limitedToSegment,user}: TestContextProvidersProps) => {const site = { ...DEFAULT_SITE, ...siteOptions }@@ -78,7 +80,10 @@ export const TestContextProviders = ({}}>- <SegmentsContextProvider preloadedSegments={preloaded?.segments ?? []}>+ <SegmentsContextProvider+ limitedToSegment={limitedToSegment ?? null}+ preloadedSegments={preloaded?.segments ?? []}+ ><MemoryRouterbasename={getRouterBasepath(site)}initialEntries={defaultInitialEntries}diff --git a/lib/plausible/segments/segments.ex b/lib/plausible/segments/segments.exindex 290364fe44..0072c1002f 100644--- a/lib/plausible/segments/segments.ex+++ b/lib/plausible/segments/segments.ex@@ -70,6 +70,63 @@ defmodule Plausible.Segments do{:ok, Repo.all(query)}end+ def search_by_name(%Plausible.Site{} = site, input) do+ type = :site+ fields = [:id, :name]++ input_empty? = is_nil(input) or (is_binary(input) and String.trim(input) == "")++ base_query =+ from(segment in Segment,+ where: segment.site_id == ^site.id,+ where: segment.type == ^type,+ limit: 20+ )++ query =+ if input_empty? do+ from([segment] in base_query,+ select: ^fields,+ order_by: [desc: segment.updated_at]+ )+ else+ from([segment] in base_query,+ select: %{+ id: segment.id,+ name: segment.name,+ match_rank:+ fragment(+ "CASE+ WHEN lower(?) = lower(?) THEN 0 -- exact match+ WHEN lower(?) LIKE lower(?) || '%' THEN 1 -- starts with+ WHEN lower(?) LIKE '% ' || lower(?) || '%' THEN 2 -- after a space+ WHEN lower(?) ILIKE ? THEN 3 -- anywhere+ END AS match_rank",+ segment.name,+ ^input,+ segment.name,+ ^input,+ segment.name,+ ^input,+ segment.name,+ ^"%#{input}%"+ ),+ pos:+ fragment(+ "position(lower(?) IN lower(?)) AS pos",+ ^input,+ segment.name+ ),+ len_diff: fragment("abs(length(?) - length(?)) AS len_diff", segment.name, ^input)+ },+ where: fragment("? ilike ?", segment.name, ^"%#{input}%"),+ order_by: fragment("match_rank asc, pos asc, len_diff asc, updated_at desc")+ )+ end++ {:ok, Repo.all(query)}+ end+@spec get_one(pos_integer(), Plausible.Site.t(), atom(), pos_integer() | nil) ::{:ok, Segment.t()}| error_not_enough_permissions()@@ -281,6 +338,33 @@ defmodule Plausible.Segments doendend+ def get_related_shared_links(+ _site,+ _site_role,+ nil+ ) do+ {:error, :segment_not_found}+ end++ def get_related_shared_links(+ %Plausible.Site{} = site,+ site_role,+ segment_id+ ) do+ if site_role in roles_with_personal_segments() do+ {:ok,+ Repo.all(+ from(shared_link in Plausible.Site.SharedLink,+ select: [:name],+ where: shared_link.segment_id == ^segment_id,+ where: shared_link.site_id == ^site.id+ )+ )}+ else+ {:error, :not_enough_permissions}+ end+ end+@spec do_get_one(pos_integer(), pos_integer(), pos_integer() | nil) ::Segment.t() | nildefp do_get_one(user_id, site_id, segment_id)diff --git a/lib/plausible/site/shared_link.ex b/lib/plausible/site/shared_link.exindex 2a2c2cf7f2..ba540c7128 100644--- a/lib/plausible/site/shared_link.ex+++ b/lib/plausible/site/shared_link.ex@@ -10,17 +10,19 @@ defmodule Plausible.Site.SharedLink dofield :slug, :stringfield :password_hash, :stringfield :password, :string, virtual: true+ belongs_to :segment, Plausible.Segments.Segmenttimestamps()enddef changeset(link, attrs \\ %{}, opts \\ []) dolink- |> cast(attrs, [:slug, :password, :name])+ |> cast(attrs, [:slug, :password, :name, :segment_id])|> validate_required([:slug, :name])|> validate_special_name(opts)|> unique_constraint(:slug)|> unique_constraint(:name, name: :shared_links_site_id_name_index)+ |> foreign_key_constraint(:segment_id)|> hash_password()end@@ -48,4 +50,9 @@ defmodule Plausible.Site.SharedLink dodef password_protected?(%__MODULE__{password_hash: hash}) when not is_nil(hash), do: truedef password_protected?(%__MODULE__{}), do: false++ def limited_to_segment?(%__MODULE__{segment_id: segment_id}) when is_integer(segment_id),+ do: true++ def limited_to_segment?(%__MODULE__{}), do: falseenddiff --git a/lib/plausible/sites.ex b/lib/plausible/sites.exindex f0f04d1f5d..98b0ffb709 100644--- a/lib/plausible/sites.ex+++ b/lib/plausible/sites.ex@@ -415,6 +415,8 @@ defmodule Plausible.Sites dodef create_shared_link(site, name, opts \\ []) dopassword = Keyword.get(opts, :password)+ segment_id = Keyword.get(opts, :segment_id)+site = Plausible.Repo.preload(site, :team)skip_feature_check? = Keyword.get(opts, :skip_feature_check?, false)@@ -423,7 +425,7 @@ defmodule Plausible.Sites doelse%SharedLink{site_id: site.id, slug: Nanoid.generate()}|> SharedLink.changeset(- %{name: name, password: password},+ %{name: name, password: password, segment_id: segment_id},Keyword.take(opts, [:skip_special_name_check?]))|> Repo.insert()diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.exindex a1aac36cdf..696195bdca 100644--- a/lib/plausible_web/components/generic.ex+++ b/lib/plausible_web/components/generic.ex@@ -393,7 +393,7 @@ defmodule PlausibleWeb.Components.Generic do~H"""<.linkclass={[- "inline-flex items-center gap-x-0.5",+ "inline-flex items-center gap-x-1",@class]}href={@href}@@ -403,7 +403,7 @@ defmodule PlausibleWeb.Components.Generic do{@rest}>{render_slot(@inner_block)}- <Heroicons.arrow_top_right_on_square class={["opacity-60", @icon_class]} />+ <Heroicons.arrow_top_right_on_square class={["stroke-2", @icon_class]} /></.link>"""else@@ -444,6 +444,18 @@ defmodule PlausibleWeb.Components.Generic doattr(:rest, :global)+ @doc """+ Renders toggle input.+ Needs `:js_active_var` that controls toggle state.+ Set this outside this component with `x-data="{ <variable name>: <initial state> }"`.++ ### Examples+ ```+ <div x-data="{ showGoals: false }>+ <.toggle_switch id="show_goals" js_active_var="showGoals" />+ </div>+ ```+ """def toggle_switch(assigns) do~H"""<button@@ -471,6 +483,54 @@ defmodule PlausibleWeb.Components.Generic do"""end+ attr :id, :string, required: true+ attr :js_active_var, :string, required: true+ attr :id_suffix, :string, default: ""+ attr :disabled, :boolean, default: false+ attr :label, :string, required: true+ attr :help_text, :string, default: nil+ attr :show_help_text_only_when_active?, :boolean, default: false+ attr :mt?, :boolean, default: true++ attr(:rest, :global)++ @doc """+ Renders toggle input with a label. Clicking the label also toggles the toggle.+ Needs `:js_active_var` that controls toggle state.+ Set this outside this component with `x-data="{ <variable name>: <initial state> }"`+ Can be configured to always show a description of the field / help text `:help_text`,+ or only show the help text when the toggle is activated `:show_help_text_only_when_active?`.+ """+ def toggle_field(assigns) do+ ~H"""+ <div class={["flex items-start justify-between gap-5 w-full", @mt? && "mt-6"]}>+ <div class="flex-1">+ <span+ x-on:click={"#{@js_active_var} = !#{@js_active_var}"}+ class="text-sm font-medium text-gray-900 dark:text-gray-100 cursor-pointer"+ >+ {@label}+ </span>+ <p+ :if={@help_text}+ class="text-gray-500 dark:text-gray-400 text-sm text-pretty"+ x-show={if @show_help_text_only_when_active?, do: @js_active_var, else: "true"}+ x-cloak={@show_help_text_only_when_active?}+ >+ {@help_text}+ </p>+ </div>+ <PlausibleWeb.Components.Generic.toggle_switch+ id={@id}+ id_suffix={@id_suffix}+ js_active_var={@js_active_var}+ disabled={@disabled}+ {@rest}+ />+ </div>+ """+ end+def settings_tiles(assigns) do~H"""<div class="text-gray-900 leading-5 dark:text-gray-100">@@ -683,9 +743,9 @@ defmodule PlausibleWeb.Components.Generic doif String.contains?(classes, "text-sm") orString.contains?(classes, "text-xs") do- ["w-3 h-3"]+ ["size-3"]else- ["w-4 h-4"]+ ["size-4"]endend@@ -791,15 +851,19 @@ defmodule PlausibleWeb.Components.Generic do~H"""<td- class={[- @height,- "text-sm px-6 py-4 first:pl-0 last:pr-0 whitespace-nowrap",- @truncate && "truncate",- @max_width,- @actions && "flex text-right justify-end",- @hide_on_mobile && "hidden md:table-cell",- @class- ]}+ class={+ [+ @height,+ "text-sm px-6 py-4 first:pl-0 last:pr-0 whitespace-nowrap",+ # allow tooltips overflow cells vertically+ "overflow-visible",+ @truncate && "truncate",+ @max_width,+ @actions && "flex text-right justify-end",+ @hide_on_mobile && "hidden md:table-cell",+ @class+ ]+ }{@rest}><div :if={@actions} class="flex gap-1">diff --git a/lib/plausible_web/controllers/api/internal/segments_controller.ex b/lib/plausible_web/controllers/api/internal/segments_controller.exindex c7962ba6b8..21d873a66a 100644--- a/lib/plausible_web/controllers/api/internal/segments_controller.ex+++ b/lib/plausible_web/controllers/api/internal/segments_controller.ex@@ -100,6 +100,33 @@ defmodule PlausibleWeb.Api.Internal.SegmentsController dodef delete(%Plug.Conn{} = conn, _params), do: invalid_request(conn)+ def get_related_shared_links(+ %Plug.Conn{+ assigns: %{+ site: site,+ current_user: %{id: _user_id},+ site_role: site_role+ }+ } =+ conn,+ %{} = params+ ) do+ segment_id = normalize_segment_id_param(params["segment_id"])++ case Segments.get_related_shared_links(site, site_role, segment_id) do+ {:error, :not_enough_permissions} ->+ H.not_enough_permissions(conn, "Not enough permissions to get related shared links")++ {:error, :segment_not_found} ->+ segment_not_found(conn, params["segment_id"])++ {:ok, shared_links} ->+ json(conn, shared_links |> Enum.map(& &1.name))+ end+ end++ def get_related_shared_links(%Plug.Conn{} = conn, _params), do: invalid_request(conn)+@spec normalize_segment_id_param(any()) :: nil | pos_integer()defp normalize_segment_id_param(input) docase Integer.parse(input) dodiff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.exindex 318690d22d..ed3b7f930f 100644--- a/lib/plausible_web/controllers/api/stats_controller.ex+++ b/lib/plausible_web/controllers/api/stats_controller.ex@@ -14,6 +14,7 @@ defmodule PlausibleWeb.Api.StatsController do@not_set "(not set)"plug(:date_validation_plug)+ plug(:validate_required_filters_plug when action not in [:current_visitors])@doc """Returns a time-series based on given parameters.@@ -1615,6 +1616,43 @@ defmodule PlausibleWeb.Api.StatsController doendend+ defp validate_required_filters_plug(+ %Plug.Conn{assigns: %{shared_link: %Plausible.Site.SharedLink{segment_id: segment_id}}} =+ conn,+ _opts+ )+ when is_integer(segment_id) do+ case ensure_expected_segment_filter_present(conn.params, segment_id) do+ :ok ->+ conn++ :error ->+ bad_request(+ conn,+ "The first filter must be for the segment with id #{segment_id}"+ )+ end+ end++ defp validate_required_filters_plug(conn, _opts), do: conn++ defp ensure_expected_segment_filter_present(+ %{"filters" => filters} = _params,+ expected_segment_id+ ) do+ case JSON.decode!(filters) do+ [["is", "segment", [segment_id]] | _other_filters] when segment_id == expected_segment_id ->+ :ok++ _ ->+ :error+ end+ end++ defp ensure_expected_segment_filter_present(_params, _expected_segment_id) do+ :error+ end+defp parse_date_params(params) doparams|> Map.take(["from", "to", "date"])diff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.exindex 94f0c9a2e4..a69c15d3f1 100644--- a/lib/plausible_web/controllers/stats_controller.ex+++ b/lib/plausible_web/controllers/stats_controller.ex@@ -101,6 +101,7 @@ defmodule PlausibleWeb.StatsController doconsolidated_view?: consolidated_view?,consolidated_view_available?: consolidated_view_available?,team_identifier: team_identifier,+ limited_to_segment_id: nil,connect_live_socket: PlausibleWeb.Live.Dashboard.enabled?(site))@@ -405,12 +406,34 @@ defmodule PlausibleWeb.StatsController donot Teams.locked?(shared_link.site.team) ->current_user = conn.assigns[:current_user]site_role = get_fallback_site_role(conn)- shared_link = Plausible.Repo.preload(shared_link, site: :owners)+ shared_link = Plausible.Repo.preload(shared_link, :segment, site: [:owners])stats_start_date = Plausible.Sites.stats_start_date(shared_link.site)flags = get_flags(current_user, shared_link.site)- {:ok, segments} = Plausible.Segments.get_all_for_site(shared_link.site, site_role)+ limited_to_segment_id =+ if Plausible.Site.SharedLink.limited_to_segment?(shared_link) do+ shared_link.segment.id+ else+ nil+ end++ segments =+ if is_nil(limited_to_segment_id) do+ {:ok, segments} = Plausible.Segments.get_all_for_site(shared_link.site, site_role)+ segments+ else+ shared_link.segment+ |> Map.take([+ :id,+ :name,+ :type,+ :inserted_at,+ :updated_at,+ :segment_data+ ])+ |> List.wrap()+ endembedded? = conn.params["embed"] == "true"@@ -444,7 +467,8 @@ defmodule PlausibleWeb.StatsController do# no shared links for consolidated viewsconsolidated_view?: false,consolidated_view_available?: false,- team_identifier: team_identifier+ team_identifier: team_identifier,+ limited_to_segment_id: limited_to_segment_id)endenddiff --git a/lib/plausible_web/live/components/form.ex b/lib/plausible_web/live/components/form.exindex 04d463ac22..0a637312d0 100644--- a/lib/plausible_web/live/components/form.ex+++ b/lib/plausible_web/live/components/form.ex@@ -74,8 +74,14 @@ defmodule PlausibleWeb.Live.Components.Form dodef input(%{type: "select"} = assigns) do~H"""- <div class={@mt? && "mt-4"}>- <.label for={@id} class={if @help_text, do: "mb-0.5", else: "mb-1.5"}>{@label}</.label>+ <div class={@mt? && "mt-6"}>+ <.label+ :if={@label != nil and @label != ""}+ for={@id}+ class={if @help_text, do: "mb-0.5", else: "mb-1.5"}+ >+ {@label}+ </.label><p :if={@help_text} class="text-gray-500 dark:text-gray-400 mb-2 text-sm">{@help_text}@@ -138,7 +144,7 @@ defmodule PlausibleWeb.Live.Components.Form do<span:if={@help_text || @help_content != []}- class="text-gray-500 dark:text-gray-400 mb-2 text-sm"+ class="text-gray-500 dark:text-gray-400 mb-2 text-sm text-pretty">{@help_text}{render_slot(@help_content)}@@ -150,7 +156,7 @@ defmodule PlausibleWeb.Live.Components.Form dodef input(%{type: "textarea"} = assigns) do~H"""- <div class={@mt? && "mt-4"}>+ <div class={@mt? && "mt-6"}><.label class="mb-1.5" for={@id}>{@label}</.label><textareaid={@id}@@ -176,7 +182,7 @@ defmodule PlausibleWeb.Live.Components.Form doassigns = assign(assigns, :errors, errors)~H"""- <div class={@mt? && "mt-4"}>+ <div class={@mt? && "mt-6"}><.label:if={@label != nil and @label != ""}for={@id}diff --git a/lib/plausible_web/live/shared_link_settings.ex b/lib/plausible_web/live/shared_link_settings.exindex 3b923fc565..97839539d0 100644--- a/lib/plausible_web/live/shared_link_settings.ex+++ b/lib/plausible_web/live/shared_link_settings.ex@@ -119,9 +119,35 @@ defmodule PlausibleWeb.Live.SharedLinkSettings do</:thead><:tbody :let={link}><.td truncate hide_on_mobile>- {link.name}- <Heroicons.lock_closed :if={link.password_hash} class="feather ml-2 mb-0.5" />- <Heroicons.lock_open :if={!link.password_hash} class="feather ml-2 mb-0.5" />+ <div class="flex items-center">+ {link.name}+ <.tooltip+ :if={Plausible.Site.SharedLink.password_protected?(link)}+ enabled?={true}+ centered?={true}+ >+ <:tooltip_content>+ Password protected+ </:tooltip_content>+ <Heroicons.lock_closed class="feather ml-2 mb-0.5" />+ </.tooltip>+ <.tooltip+ :if={!Plausible.Site.SharedLink.password_protected?(link)}+ enabled?={true}+ centered?={true}+ >+ <:tooltip_content>+ No password protection+ </:tooltip_content>+ <Heroicons.lock_open class="feather ml-2 mb-0.5" />+ </.tooltip>+ <.tooltip :if={link.segment_id} enabled?={true} centered?={true}>+ <:tooltip_content>+ Limited to segment of data+ </:tooltip_content>+ <Heroicons.eye_slash class="feather ml-1" />+ </.tooltip>+ </div></.td><.td><.input_with_clipboard@@ -158,7 +184,10 @@ defmodule PlausibleWeb.Live.SharedLinkSettings doenddef handle_event("edit-shared-link", %{"slug" => slug}, socket) do- shared_link = Plausible.Repo.get_by(Plausible.Site.SharedLink, slug: slug)+ shared_link =+ Plausible.Site.SharedLink+ |> Plausible.Repo.get_by(slug: slug)+ |> Plausible.Repo.preload(:segment)socket =socket |> assign(form_shared_link: shared_link) |> Modal.open("shared-links-form-modal")diff --git a/lib/plausible_web/live/shared_link_settings/form.ex b/lib/plausible_web/live/shared_link_settings/form.exindex e4ff0effc5..0adf0c1c43 100644--- a/lib/plausible_web/live/shared_link_settings/form.ex+++ b/lib/plausible_web/live/shared_link_settings/form.ex@@ -6,6 +6,7 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.Form douse Plausiblealias Plausible.Sites+ alias PlausibleWeb.Live.Components.ComboBoxdef update(assigns, socket) doform =@@ -43,6 +44,39 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.Form do<.input field={f[:name]} label="Name" required="required" autocomplete="off" />+ <div+ x-data={"{ limitViewEnabled: #{not is_nil(f[:segment_id].value)} }"}+ x-effect="+ const input = document.getElementById('submit-segment_id');+ if (input) {+ if (!limitViewEnabled) {+ input.value = '';+ }+ }+ "+ class="flex flex-col gap-y-2"+ >+ <PlausibleWeb.Components.Generic.toggle_field+ id="limit-view"+ js_active_var="limitViewEnabled"+ label="Limit to segment"+ help_text="Restrict this link to a segment of the data."+ />+ <div x-show="limitViewEnabled" x-cloak>+ <.live_component+ id="segment_id"+ submit_name="shared_link[segment_id]"+ module={ComboBox}+ suggest_fun={fn input, _ -> get_segment_suggestions(assigns.site, input) end}+ selected={+ @shared_link.segment_id &&+ {@shared_link.segment.id, @shared_link.segment.name}+ }+ />+ <.learn_more />+ </div>+ </div>+<.button type="submit" class="w-full">Update shared link</.button>@@ -55,13 +89,68 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.Form do<.form :let={f} for={@form} phx-submit="save-shared-link" phx-target={@myself}><.title>New shared link</.title><.input field={f[:name]} label="Name" required="required" autocomplete="off" />- <.input- field={f[:password]}- label="Password (optional)"- help_text="Store the password securely, as it can't be viewed again."- type="password"- autocomplete="new-password"- />++ <div+ x-data="{ passwordProtectEnabled: false }"+ x-effect={"+ const input = document.getElementById('#{f[:password].id}');+ if (input) {+ if (passwordProtectEnabled) {+ setTimeout(() => input.focus(), 50);+ } else {+ input.value = '';+ }+ }+ "}+ class="flex flex-col gap-y-2"+ >+ <PlausibleWeb.Components.Generic.toggle_field+ id="password-protect"+ js_active_var="passwordProtectEnabled"+ label="Password protect"+ help_text="Keep this password safe. You won't be able to see it again."+ show_help_text_only_when_active?={true}+ />+ <div x-show="passwordProtectEnabled" x-cloak>+ <.input+ field={f[:password]}+ type="password"+ placeholder="Enter password"+ autocomplete="new-password"+ mt?={false}+ />+ </div>+ </div>++ <div+ x-data={"{ limitViewEnabled: #{not is_nil(f[:segment_id].value)} }"}+ x-effect="+ const input = document.getElementById('submit-segment_id');+ if (input) {+ if (!limitViewEnabled) {+ input.value = '';+ }+ }+ "+ class="flex flex-col gap-y-2"+ >+ <PlausibleWeb.Components.Generic.toggle_field+ id="limit-view"+ js_active_var="limitViewEnabled"+ label="Limit to segment"+ help_text="Restrict this link to a segment of the data."+ />+ <div x-show="limitViewEnabled" x-cloak>+ <.live_component+ id="segment_id"+ submit_name="shared_link[segment_id]"+ module={ComboBox}+ suggest_fun={fn input, _ -> get_segment_suggestions(assigns.site, input) end}+ selected={nil}+ />+ <.learn_more />+ </div>+ </div><.button type="submit" class="w-full">Create shared link</.button>@@ -69,13 +158,32 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.Form do"""end+ defp learn_more(assigns),+ do: ~H"""+ <div class="mt-1">+ <PlausibleWeb.Components.Generic.unstyled_link+ href="https://plausible.io/docs/filters-segments#how-to-save-a-segment"+ new_tab+ class="text-xs text-indigo-600 dark:text-indigo-400"+ >+ Learn about segments+ </PlausibleWeb.Components.Generic.unstyled_link>+ </div>+ """++ defp get_segment_suggestions(site, input) do+ {:ok, segments} = Plausible.Segments.search_by_name(site, input)+ Enum.map(segments, &{&1.id, &1.name})+ end+def handle_event("save-shared-link",%{"shared_link" => shared_link_params},%{assigns: %{shared_link: nil}} = socket) docase Sites.create_shared_link(socket.assigns.site, shared_link_params["name"],- password: shared_link_params["password"]+ password: shared_link_params["password"],+ segment_id: shared_link_params["segment_id"]) do{:ok, shared_link} ->socket = socket.assigns.on_save_shared_link.(shared_link, socket)@@ -98,7 +206,11 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.Form do%{"shared_link" => shared_link_params},%{assigns: %{shared_link: %Plausible.Site.SharedLink{} = shared_link}} = socket) do- changeset = Plausible.Site.SharedLink.changeset(shared_link, shared_link_params)+ changeset =+ Plausible.Site.SharedLink.changeset(+ shared_link,+ shared_link_params+ )case Plausible.Repo.update(changeset) do{:ok, updated_shared_link} ->diff --git a/lib/plausible_web/plugs/authorize_site_access.ex b/lib/plausible_web/plugs/authorize_site_access.exindex 063df8258d..970e2883b5 100644--- a/lib/plausible_web/plugs/authorize_site_access.ex+++ b/lib/plausible_web/plugs/authorize_site_access.ex@@ -118,7 +118,7 @@ defmodule PlausibleWeb.Plugs.AuthorizeSiteAccess doteam: [:owners, subscription: Teams.last_subscription_query()]])- conn = merge_assigns(conn, site: site, site_role: role)+ conn = merge_assigns(conn, site: site, site_role: role, shared_link: shared_link)# Switch current team if user is a team member in itconn =diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.exindex ef561ea0f5..bafaa080d8 100644--- a/lib/plausible_web/router.ex+++ b/lib/plausible_web/router.ex@@ -306,6 +306,7 @@ defmodule PlausibleWeb.Router dopost "/", SegmentsController, :createpatch "/:segment_id", SegmentsController, :updatedelete "/:segment_id", SegmentsController, :delete+ get "/:segment_id/shared-links", SegmentsController, :get_related_shared_linksendenddiff --git a/lib/plausible_web/templates/stats/stats.html.heex b/lib/plausible_web/templates/stats/stats.html.heexindex 429a050590..0c698cc9b0 100644--- a/lib/plausible_web/templates/stats/stats.html.heex+++ b/lib/plausible_web/templates/stats/stats.html.heex@@ -52,6 +52,7 @@data-is-consolidated-view={Jason.encode!(@consolidated_view?)}data-consolidated-view-available={Jason.encode!(@consolidated_view_available?)}data-team-identifier={@team_identifier}+ data-limited-to-segment-id={Jason.encode!(@limited_to_segment_id)}></div><%= if PlausibleWeb.Live.Dashboard.enabled?(@site) do %>diff --git a/test/plausible/segments/segments_test.exs b/test/plausible/segments/segments_test.exsindex 4fc53ac01b..52bd61f2d3 100644--- a/test/plausible/segments/segments_test.exs+++ b/test/plausible/segments/segments_test.exs@@ -1,4 +1,154 @@defmodule Plausible.SegmentsTest douse ExUnit.Case+ use Plausible.DataCase, async: truedoctest Plausible.Segments, import: true+ alias Plausible.Segments.Segment++ setup [:create_user, :create_site]++ describe("searching segments by name") do+ for input <- [nil, "", " ", "\n", " \t"] do+ test "empty search input #{inspect(input)} yields site segments ordered by updated_at",+ %{+ site: site+ } do+ other_site = new_site()++ segment_scandinavia =+ insert(:segment,+ name: "Scandinavia",+ site: site,+ type: :site,+ updated_at: "2025-12-01T12:00:00"+ )++ segment_apac =+ insert(:segment,+ name: "APAC",+ site: site,+ type: :site,+ updated_at: "2025-12-01T10:00:00"+ )++ _segment_other_site = insert(:segment, name: "any", site: other_site, type: :site)+ _segment_personal = insert(:segment, name: "My segment", site: site, type: :personal)++ assert {:ok,+ [+ list_all_result(segment_scandinavia),+ list_all_result(segment_apac)+ ]} ==+ Plausible.Segments.search_by_name(site, unquote(input))+ end+ end++ for input <- ["", "emea"] do+ test "search input #{inspect(input)} returns a maximum of 20 segments", %{site: site} do+ insert_list(100, :segment,+ name: "EMEA",+ site: site,+ type: :site+ )++ assert {:ok, segments} = Plausible.Segments.search_by_name(site, unquote(input))++ assert 20 == length(segments)+ end+ end++ test "search input \"A\" yields correctly ranked segments", %{+ site: site+ } do+ segment_scandinavia =+ insert(:segment,+ name: "Scandinavia",+ site: site,+ type: :site,+ updated_at: "2025-12-01T12:00:00"+ )++ segment_scandinavia_latest =+ insert(:segment,+ name: segment_scandinavia.name,+ site: site,+ type: :site,+ updated_at: "2025-12-01T13:00:00"+ )++ segment_scandinavia_longer_name =+ insert(:segment,+ name: "#{segment_scandinavia.name} (but longer)",+ site: site,+ type: :site,+ updated_at: "2025-12-01T12:00:00"+ )++ segment_a =+ insert(:segment,+ name: "A",+ site: site,+ type: :site,+ updated_at: "2025-12-01T10:00:00"+ )++ segment_apac =+ insert(:segment,+ name: "APAC",+ site: site,+ type: :site,+ updated_at: "2025-12-01T10:00:00"+ )++ segment_apac_copy =+ insert(:segment,+ name: "Copy of APAC",+ site: site,+ type: :site,+ updated_at: "2025-12-01T10:00:00"+ )++ _segment_personal = insert(:segment, name: "My segment", site: site, type: :personal)++ assert_matches {:ok,+ [+ # ranked here because it exactly matches input+ %{+ name: ^segment_a.name,+ id: ^segment_a.id+ },+ # ranked here because it starts with the input+ %{+ name: ^segment_apac.name,+ id: ^segment_apac.id+ },+ # ranked here because it has a substring starting with a space and the input+ %{+ name: ^segment_apac_copy.name,+ id: ^segment_apac_copy.id+ },+ # ranked over next one (that has the same name) because it's been updated more lately+ %{+ name: ^segment_scandinavia_latest.name,+ id: ^segment_scandinavia_latest.id+ },+ # ranked over next one because it has a shorter name+ %{+ name: ^segment_scandinavia.name,+ id: ^segment_scandinavia.id+ },+ %{+ name: ^segment_scandinavia_longer_name.name,+ id: ^segment_scandinavia_longer_name.id+ }+ ]} =+ Plausible.Segments.search_by_name(site, "A")+ end++ defp list_all_result(segment) do+ Plausible.Repo.load(Segment, %{+ name: segment.name,+ id: segment.id+ })+ end+ endenddiff --git a/test/plausible_web/controllers/api/internal_controller/segments_controller_test.exs b/test/plausible_web/controllers/api/internal_controller/segments_controller_test.exsindex 1bd7ad7d2a..5549ecdfb5 100644--- a/test/plausible_web/controllers/api/internal_controller/segments_controller_test.exs+++ b/test/plausible_web/controllers/api/internal_controller/segments_controller_test.exs@@ -468,6 +468,63 @@ defmodule PlausibleWeb.Api.Internal.SegmentsControllerTest doendend+ test "deleting a segment deletes the shared links linked to it", %{+ conn: conn,+ site: site,+ user: user+ } do+ segment =+ insert(:segment,+ site: site,+ owner: user,+ name: "any",+ type: :personal,+ segment_data: %{"filters" => [["is", "event:goal", ["Signup"]]]}+ )++ other_segment =+ insert(:segment,+ site: site,+ owner: user,+ name: "other",+ type: :site,+ segment_data: %{"filters" => [["is", "event:goal", ["Signup"]]]}+ )++ shared_links_with_segments =+ insert_list(3, :shared_link,+ site: site,+ segment_id: segment.id+ )++ shared_link_with_other_segment =+ insert(:shared_link, site: site, name: "Gamma", segment_id: other_segment.id)++ shared_link_with_no_segment = insert(:shared_link, site: site, name: "Delta")++ response =+ delete(conn, "/api/#{site.domain}/segments/#{segment.id}")+ |> json_response(200)++ assert %{+ "owner_id" => user.id,+ "owner_name" => user.name,+ "id" => segment.id,+ "name" => segment.name,+ "segment_data" => segment.segment_data,+ "type" => "#{segment.type}",+ "inserted_at" => Calendar.strftime(segment.inserted_at, "%Y-%m-%dT%H:%M:%S"),+ "updated_at" => Calendar.strftime(segment.updated_at, "%Y-%m-%dT%H:%M:%S")+ } == response++ assert Repo.reload(shared_link_with_other_segment)+ assert Repo.reload(shared_link_with_no_segment)++ for link <- shared_links_with_segments do+ refute Repo.reload(link)+ end+ end+test "site owner can delete a site segment owned by someone else, even if it contains a non-existing goal",%{conn: conn, site: site} doother_user = add_guest(site, role: :editor)@@ -500,6 +557,106 @@ defmodule PlausibleWeb.Api.Internal.SegmentsControllerTest doendend+ describe "GET /api/:domain/segments/:segment_id/shared-links" do+ setup [:create_user, :create_site, :log_in]++ for %{role: role} <- [+ %{role: :viewer},+ %{role: :editor},+ %{role: :admin},+ %{role: :billing},+ %{role: :owner}+ ] do+ test "#{role} can get related shared links for a segment", %{+ conn: conn,+ site: site+ } do+ user = add_member(site.team, role: unquote(role))++ segment = insert(:segment, site: site, name: "Test Segment", type: :site, owner: user)++ insert(:shared_link, site: site, name: "Shared Link 1", segment_id: segment.id)+ insert(:shared_link, site: site, name: "Shared Link 2", segment_id: segment.id)++ # Create a shared link for a different segment to ensure filtering works+ other_segment = insert(:segment, site: site, name: "Other Segment", type: :personal)+ insert(:shared_link, site: site, name: "Other Shared Link", segment_id: other_segment.id)++ # Create a shared link with no segment+ insert(:shared_link, site: site, name: "No Segment Link", segment_id: nil)++ response =+ get(conn, "/api/#{site.domain}/segments/#{segment.id}/shared-links")+ |> json_response(200)++ assert response == ["Shared Link 1", "Shared Link 2"]+ end+ end++ test "returns empty list when no shared links are related to the segment", %{+ conn: conn,+ user: user,+ site: site+ } do+ segment = insert(:segment, site: site, name: "Test Segment", type: :personal, owner: user)++ response =+ get(conn, "/api/#{site.domain}/segments/#{segment.id}/shared-links")+ |> json_response(200)++ assert response == []+ end++ test "returns empty list when giving a segment ID that doesn't exist", %{+ conn: conn,+ site: site+ } do+ response =+ get(conn, "/api/#{site.domain}/segments/9999999/shared-links")+ |> json_response(200)++ assert response == []+ end++ test "returns empty list when requesting with the segment_id of another site", %{+ conn: conn,+ site: site+ } do+ other_site = new_site()+ other_site_segment = insert(:segment, site: other_site, name: "Test Segment")++ insert(:shared_link,+ site: other_site,+ name: "Link",+ segment_id: other_site_segment.id+ )++ response =+ get(conn, "/api/#{site.domain}/segments/#{other_site_segment.id}/shared-links")+ |> json_response(200)++ assert response == []+ end++ test "returns 404 for invalid segment_id", %{conn: conn, site: site} do+ conn = get(conn, "/api/#{site.domain}/segments/invalid/shared-links")++ assert %{"error" => "Segment not found with ID \"invalid\""} ==+ json_response(conn, 404)+ end++ test "returns 403 when looking at a public site", %{conn: conn} do+ public_site = new_site(public: true)+ segment = insert(:segment, site: public_site, name: "segment", type: :site)++ conn =+ get(conn, "/api/#{public_site.domain}/segments/#{segment.id}/shared-links")++ assert %{"error" => "Not enough permissions to get related shared links"} ==+ json_response(conn, 403)+ end+ end+defp verify_segment_in_db(segment) douncomparable_keys = [:__meta__, :site]diff --git a/test/plausible_web/controllers/api/stats_controller/authorization_test.exs b/test/plausible_web/controllers/api/stats_controller/authorization_test.exsindex 7457658b75..9c0917f3d1 100644--- a/test/plausible_web/controllers/api/stats_controller/authorization_test.exs+++ b/test/plausible_web/controllers/api/stats_controller/authorization_test.exs@@ -107,6 +107,61 @@ defmodule PlausibleWeb.Api.StatsController.AuthorizationTest doendend+ describe "Filter validation for limited view shared links" do+ test "returns 400 for limited view shared link if there are no filters", %{conn: conn} do+ site = new_site()++ segment = insert(:segment, site: site, type: :site, name: "Scandinavia")++ link =+ insert(:shared_link, site: site, segment: segment)++ conn = get(conn, "/api/stats/#{site.domain}/top-stats?auth=#{link.slug}")++ assert json_response(conn, 400) == %{+ "error" => "The first filter must be for the segment with id #{segment.id}"+ }+ end++ test "returns 400 for limited view shared link if the segment filter is not for the right segment",+ %{conn: conn} do+ site = new_site()++ segment = insert(:segment, site: site, type: :site, name: "Scandinavia")++ link =+ insert(:shared_link, site: site, segment: segment)++ conn =+ get(+ conn,+ "/api/stats/#{site.domain}/top-stats?auth=#{link.slug}&filters=#{JSON.encode!([["is", "segment", [segment.id + 1]]])}"+ )++ assert json_response(conn, 400) == %{+ "error" => "The first filter must be for the segment with id #{segment.id}"+ }+ end++ test "returns 200 for limited view shared link if the required segment is present, permits other filters to be applied",+ %{conn: conn} do+ site = new_site()++ segment = insert(:segment, site: site, type: :site, name: "Scandinavia")++ link =+ insert(:shared_link, site: site, segment: segment)++ conn =+ get(+ conn,+ "/api/stats/#{site.domain}/top-stats?auth=#{link.slug}&filters=#{JSON.encode!([["is", "segment", [segment.id]], ["is", "event:page", ["/docs"]]])}"+ )++ assert json_response(conn, 200)+ end+ end+describe "API authorization - as logged in user" dosetup [:create_user, :log_in]diff --git a/test/plausible_web/controllers/stats_controller_test.exs b/test/plausible_web/controllers/stats_controller_test.exsindex eb9fe48401..788ad54f98 100644--- a/test/plausible_web/controllers/stats_controller_test.exs+++ b/test/plausible_web/controllers/stats_controller_test.exs@@ -1330,9 +1330,10 @@ defmodule PlausibleWeb.StatsControllerTest doassert response(conn, 200) =~ "Enter password"end- test "logs anonymous user in straight away if the link is not password-protected", %{- conn: conn- } do+ test "if the shared link is not protected with a password, passes user immediately to dashboard",+ %{+ conn: conn+ } dosite = new_site(domain: "test-site.com")link = insert(:shared_link, site: site)@@ -1344,7 +1345,34 @@ defmodule PlausibleWeb.StatsControllerTest doassert text_of_attr(resp, @react_container, "data-current-user-role") == "public"end- test "footer and header are shown when accessing public dashboard", %{+ test "if the shared link is limited to a segment, only that segment is stuffed into data-segments",+ %{+ conn: conn+ } do+ site = new_site(domain: "test-site.com")+ emea_site_segment = insert(:segment, name: "EMEA", site: site, type: :site)+ apac_site_segment = insert(:segment, name: "APAC", site: site, type: :site)+ link = insert(:shared_link, site: site, segment: emea_site_segment)++ conn = get(conn, "/share/test-site.com/?auth=#{link.slug}")+ resp = html_response(conn, 200)+ assert resp =~ "stats-react-container"++ assert text_of_attr(resp, @react_container, "data-limited-to-segment-id") ==+ "#{emea_site_segment.id}"++ assert text_of_attr(resp, @react_container, "data-segments") ==+ emea_site_segment+ |> Map.take([:id, :name, :type, :inserted_at, :updated_at, :segment_data])+ |> List.wrap()+ |> JSON.encode!()++ refute resp =~ apac_site_segment.name++ assert text_of_attr(resp, @react_container, "data-current-user-role") == "public"+ end++ test "footer and header are shown when accessing shared link dashboard", %{conn: conn} dosite = new_site(domain: "test-site.com")diff --git a/test/plausible_web/live/shared_link_settings/form_test.exs b/test/plausible_web/live/shared_link_settings/form_test.exsindex e6e889c99c..04b5a8063d 100644--- a/test/plausible_web/live/shared_link_settings/form_test.exs+++ b/test/plausible_web/live/shared_link_settings/form_test.exs@@ -20,9 +20,19 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.FormTest dohtml = render(lv)assert html =~ "New shared link"+ assert html =~ "Password protect"+ assert html =~ "Limit to segment"+ assert element_exists?(html, ~s|button[role="switch"]#password-protect-|)+ assert element_exists?(html, ~s|button[role="switch"]#limit-view-|)assert element_exists?(html, ~s|input[name="shared_link[name]"]|)assert element_exists?(html, ~s|input[name="shared_link[password]"][type="password"]|)+ assert element_exists?(html, ~s|input[name="shared_link[segment_id]"]|)assert element_exists?(html, ~s|button[type="submit"]|)++ assert element_exists?(+ html,+ ~s|a[href="https://plausible.io/docs/filters-segments#how-to-save-a-segment"]|+ )endtest "renders error on empty submission", %{conn: conn, session: session} do@@ -56,6 +66,31 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.FormTest dorefute shared_link.password_hashend+ test "creates a shared link limited to segment", %{conn: conn, site: site, session: session} do+ segment = insert(:segment, type: :site, site: site, name: "Scandinavia")+ lv = get_liveview(conn, session)++ lv |> element("button#add-shared-link-button") |> render_click()++ lv+ |> find_form()+ |> render_submit(%{shared_link: %{name: "Limited to Scandinavia", segment_id: segment.id}})++ html = render(lv)+ assert html =~ "Limited to Scandinavia"+ assert html =~ "Shared link saved"++ shared_link =+ Plausible.Repo.get_by(Plausible.Site.SharedLink,+ name: "Limited to Scandinavia",+ site_id: site.id,+ segment_id: segment.id+ )++ assert shared_link+ refute shared_link.password_hash+ end+test "creates a shared link with password", %{conn: conn, site: site, session: session} dolv = get_liveview(conn, session)refute render(lv) =~ "Protected Link"@@ -77,12 +112,50 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.FormTest doassert shared_link.password_hashend- test "renders form fields for editing a shared link", %{+ test "renders form fields for editing a shared link (not limited to segment, not protected)",+ %{+ conn: conn,+ site: site,+ session: session+ } do+ shared_link = insert(:shared_link, site: site, name: "Existing Link")++ lv = get_liveview(conn, session)++ lv+ |> element(~s/button[phx-click="edit-shared-link"][phx-value-slug="#{shared_link.slug}"]/)+ |> render_click()++ html = render(lv)+ assert html =~ "Edit shared link"+ assert element_exists?(html, ~s|input[name="shared_link[name]"]|)+ assert html =~ ~s|value="#{shared_link.name}"|+ refute html =~ "Password protect"+ assert html =~ "Limit to segment"+ refute element_exists?(html, ~s|button#password-protect-[role="switch"]|)+ refute element_exists?(html, ~s|input[name="shared_link[password]"][type="password"]|)+ assert element_exists?(html, ~s|input[name="shared_link[segment_id]"][value=""]|)++ assert element_exists?(+ html,+ ~s|a[href="https://plausible.io/docs/filters-segments#how-to-save-a-segment"]|+ )+ end++ test "renders form fields for editing a shared link (limited to segment, protected)", %{conn: conn,site: site,session: session} do- shared_link = insert(:shared_link, site: site, name: "Existing Link")+ segment = insert(:segment, type: :site, site: site, name: "Scandinavia")++ shared_link =+ insert(:shared_link,+ site: site,+ name: "Existing Link",+ segment: segment,+ password: "secret123"+ )lv = get_liveview(conn, session)@@ -94,6 +167,17 @@ defmodule PlausibleWeb.Live.SharedLinkSettings.FormTest doassert html =~ "Edit shared link"assert element_exists?(html, ~s|input[name="shared_link[name]"]|)assert html =~ ~s|value="#{shared_link.name}"|+ refute html =~ "Password protect"+ assert html =~ "Limit to segment"+ assert element_exists?(html, ~s|input[name="shared_link[segment_id]"]|)+ refute element_exists?(html, ~s|input[name="shared_link[password]"][type="password"]|)++ assert element_exists?(+ html,+ ~s|input[name="shared_link[segment_id]"][value="#{segment.id}"]|+ )++ assert html =~ ~s|value="#{segment.name}"|endtest "updates a shared link name", %{conn: conn, site: site, session: session} dodiff --git a/test/support/factory.ex b/test/support/factory.exindex 55366971b6..5396ee4475 100644--- a/test/support/factory.ex+++ b/test/support/factory.ex@@ -232,9 +232,12 @@ defmodule Plausible.Factory doenddef shared_link_factory do+ slug = Nanoid.generate()+ name = "Link - #{slug}"+%Plausible.Site.SharedLink{- name: "Link name",- slug: Nanoid.generate()+ name: name,+ slug: slug}end