Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor(soup-view): split preferences from entry state (Phase 3) (#3535)

gbirman3564bdfab93e
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
index 8324e70035..6c7a8b0bf3 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
@@ -218,7 +218,10 @@ export const SoupViewContextProvider: FlowComponent<
};
const [searchPaused, setSearchPaused] = createSignal(false);
- const [assigneeFilter, setAssigneeFilter] = createSignal<string[]>([]);
+ const [assigneeFilter, setAssigneeFilter] = useEntryState<string[]>(
+ 'soup.assigneeFilter',
+ { default: [] }
+ );
const [activeTab, setActiveTab] = useEntryState<string | undefined>(
'soup.tab',
{ default: undefined }
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
index 05a830a187..ee686a85e0 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
@@ -23,10 +23,7 @@ import { useFilterRefinements } from '@app/component/next-soup/soup-view/filters
import { MaybeSoupEntityActionDrawerManager } from '@app/component/next-soup/soup-view/SoupEntityActionDrawerManager';
import type { SystemSortOption } from '@app/component/next-soup/soup-view/sort-options';
import { SoupEntityContextMenu } from '@app/component/next-soup/soup-view/soup-entity-context-menu';
-import {
- activeSoupViewCounts,
- soupViewCacheKey,
-} from '@app/component/next-soup/soup-view/soup-view-cache-key';
+import { activeSoupViewCounts } from '@app/component/next-soup/soup-view/soup-view-cache-key';
import {
SoupViewContextProvider,
useSoupView,
@@ -62,9 +59,9 @@ import {
SplitHeaderRight,
} from '@app/component/split-layout/components/SplitHeader';
import { SplitPanelContext } from '@app/component/split-layout/context';
-import { useNavigationCause } from '@app/component/split-layout/entry-state';
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import { isListViewID, type ListView } from '@app/constants/list-views';
+import { usePreference } from '@app/preferences/use-preference';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import { EmailPermissionsBanner } from '@core/component/EmailPermissionsBanner';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
@@ -107,7 +104,6 @@ import {
refetchSoupEntity,
} from '@queries/soup/normalized-cache';
import { debounce } from '@solid-primitives/scheduled';
-import { makePersisted } from '@solid-primitives/storage';
import { Button, cn, Layer, Tooltip } from '@ui';
import {
type Accessor,
@@ -124,7 +120,6 @@ import {
Show,
Suspense,
Switch,
- untrack,
} from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import { Dynamic } from 'solid-js/web';
@@ -289,20 +284,6 @@ const useSoupNotificationInvalidators = () => {
);
};
-type PersistedSoupViewState = {
- version?: number;
- activeTab: string | undefined;
- filters: SetPredicatesInput<string>;
- queryFilters: Partial<QueryState>;
- sort: SystemSortOption[];
- previewEntity: string | undefined;
- assigneeFilter: string[];
- groupBy: string | undefined;
- collapsedGroups: string[];
-};
-
-const PERSISTED_STATE_VERSION = 8;
-
const listStateCache = new Map<
string,
{
@@ -324,8 +305,6 @@ interface SoupViewProps {
* exists for this view.
*/
initialGroupBy?: string;
- /** Ignore localStorage on mount and use the supplied `initial*` values. */
- skipPersistedState?: boolean;
disableLocalSearch?: boolean;
/**
* Client-side entities to merge into the soup results. Useful for entity
@@ -561,7 +540,6 @@ export const SoupView = (props: SoupViewProps) => {
<SoupViewList
initialClientFilters={props.initialClientFilters}
initialGroupBy={props.initialGroupBy}
- skipPersistedState={props.skipPersistedState}
onScrollOffsetBaseline={resetFloatingButtonScrollTracking}
onScrollOffsetChange={handleSoupScrollOffsetChange}
/>
@@ -603,7 +581,6 @@ interface SoupViewListProps {
scopeId?: string;
initialClientFilters?: SetPredicatesInput<string>;
initialGroupBy?: string;
- skipPersistedState?: boolean;
onScrollOffsetBaseline?: (offset: number) => void;
onScrollOffsetChange?: (offset: number) => void;
}
@@ -616,14 +593,11 @@ export const SoupViewList = (props: SoupViewListProps) => {
rows,
searchText,
setSearchText,
- queryFilters,
featuredIds,
isSearchServiceLoading,
isLocalSearchSettling,
activeTab,
setActiveTab,
- assigneeFilter,
- setAssigneeFilter,
} = useSoupView();
const { hasActiveRefinements, resetToTabDefaults } = useFilterRefinements();
@@ -894,10 +868,10 @@ export const SoupViewList = (props: SoupViewListProps) => {
const isProjectList = panel.handle.content().type === 'project';
const contentId = panel.handle.content().id;
- // If another SoupViewList with the same contentId is already mounted (e.g.
- // same view open in two splits), disable all persistence for this instance
+ // Maintained for the channel/email/call sub-filters in
+ // search-filter-controls.tsx, which check duplicate-instance status via
+ // this counter.
const prevCount = activeSoupViewCounts.get(contentId) ?? 0;
- const isDuplicate = prevCount > 0;
activeSoupViewCounts.set(contentId, prevCount + 1);
onCleanup(() => {
const count = activeSoupViewCounts.get(contentId) ?? 1;
@@ -905,114 +879,87 @@ export const SoupViewList = (props: SoupViewListProps) => {
else activeSoupViewCounts.set(contentId, count - 1);
});
- const persistenceDisabled = isProjectList || isDuplicate;
-
- // On back/forward navigation, filters were already restored from per-entry
- // state during SoupViewContextProvider's body — don't let the cross-session
- // localStorage hack overwrite them on this mount.
- const navCause = useNavigationCause();
- const skipFiltersOnMount =
- navCause() === 'history-back' || navCause() === 'history-forward';
+ const cacheKey = `soup-view-${panel.handle.id}-${contentId}${previewPanel ? '-preview' : ''}`;
- const [persistedState, setPersistedState] = makePersisted(
- createSignal<PersistedSoupViewState>(),
- { name: soupViewCacheKey(contentId) }
+ // Cross-session, view-kind-scoped user preferences. Each has its own
+ // localStorage key under `macro:pref:soup:{contentId}:*`.
+ const [sortPref, setSortPref] = usePreference<string[]>(
+ `macro:pref:soup:${contentId}:sort`,
+ { default: [] }
+ );
+ const [groupByPref, setGroupByPref] = usePreference<string | undefined>(
+ `macro:pref:soup:${contentId}:groupBy`,
+ { default: undefined }
);
- const cacheKey = `soup-view-${panel.handle.id}-${contentId}${previewPanel ? '-preview' : ''}`;
-
- // Restore previewEntity synchronously so the first-render effect sees the
- // correct value and avoids a transient window where previewEntity is undefined.
- const initialPersistedState =
- !persistenceDisabled && !props.skipPersistedState
- ? untrack(persistedState)
- : null;
- soup.setPreviewEntity(initialPersistedState?.previewEntity);
+ // Preview-pane open state is transient per history entry: captured into
+ // per-entry state on nav-away and restored on back/forward. Read
+ // synchronously in the body so the first render sees the correct value
+ // and we avoid a transient flash where the pane is closed.
+ const persistedPreview = panel.handle.currentEntryState()?.['soup.preview'] as
+ | string
+ | undefined;
+ soup.setPreviewEntity(persistedPreview);
+ const previewCaptorTeardown = panel.handle.registerEntryStateCaptor(
+ 'soup.preview',
+ () => soup.previewEntity()
+ );
+ onCleanup(previewCaptorTeardown);
+
+ // Which groups are collapsed is also per-entry state: captured on nav-away
+ // and restored on back/forward.
+ const persistedCollapsedGroups = panel.handle.currentEntryState()?.[
+ 'soup.collapsedGroups'
+ ] as string[] | undefined;
+ const collapsedCaptorTeardown = panel.handle.registerEntryStateCaptor(
+ 'soup.collapsedGroups',
+ () => [...soup.grouping.collapsedGroups()]
+ );
+ onCleanup(collapsedCaptorTeardown);
- // Set initial state
onMount(() => {
- if (initialPersistedState) {
- const isStale =
- (initialPersistedState.version ?? 0) < PERSISTED_STATE_VERSION;
- const applied =
- isStale &&
- isListViewID(contentId) &&
- initialPersistedState.activeTab &&
- applyTabPreset(contentId, initialPersistedState.activeTab);
- if (!applied) {
- batch(() => {
- if (!skipFiltersOnMount) {
- soup.predicates.set(
- isStale
- ? (props.initialClientFilters ?? {})
- : initialPersistedState.filters
- );
- const persistedFilterData = isStale
- ? {}
- : (initialPersistedState.queryFilters ?? {});
- queryFilters.replace({
- include: persistedFilterData.include,
- exclude: persistedFilterData.exclude,
- emailView: persistedFilterData.emailView,
- });
- }
- if (!skipFiltersOnMount && isListViewID(contentId)) {
- const tab =
- initialPersistedState.activeTab ??
- VIEW_TAB_PRESETS[contentId].default;
- if (tab) {
- setActiveTab(tab);
- }
- }
- });
- }
- batch(() => {
- soup.sort.setAll(initialPersistedState.sort ?? []);
- setAssigneeFilter(initialPersistedState.assigneeFilter ?? []);
- soup.grouping.setActiveGroupId(initialPersistedState.groupBy);
- soup.grouping.collapseAll(initialPersistedState.collapsedGroups ?? []);
- });
- } else {
- if (!skipFiltersOnMount && props.initialClientFilters) {
- soup.predicates.set(props.initialClientFilters);
+ batch(() => {
+ const savedSort = sortPref();
+ if (savedSort.length > 0) {
+ soup.sort.setAll(savedSort as SystemSortOption[]);
}
// soup state is shared at the SplitPanel level, so a prior view in the
// same split (e.g. tasks) may have left grouping state behind. Always
- // reset to this view's initial grouping, even when undefined.
- batch(() => {
- soup.grouping.setActiveGroupId(props.initialGroupBy);
- soup.grouping.collapseAll([]);
- });
- // Set default tab for list views when no persisted state exists
- if (!skipFiltersOnMount && isListViewID(contentId)) {
+ // reset to this view's saved or initial grouping, even when undefined.
+ soup.grouping.setActiveGroupId(groupByPref() ?? props.initialGroupBy);
+ soup.grouping.collapseAll(persistedCollapsedGroups ?? []);
+
+ // Apply view-supplied client filters only when per-entry state didn't
+ // already populate them in SoupViewContextProvider.
+ const hasEntryFilters =
+ panel.handle.currentEntryState()?.['search.predicates'] !== undefined;
+ if (!hasEntryFilters && props.initialClientFilters) {
+ soup.predicates.set(props.initialClientFilters);
+ }
+
+ // Default tab for list views; entry state already restored it via
+ // `useEntryState` in SoupViewContextProvider when applicable.
+ if (isListViewID(contentId) && activeTab() === undefined) {
const defaultTab = VIEW_TAB_PRESETS[contentId].default;
- if (defaultTab) {
- setActiveTab(defaultTab);
- }
+ if (defaultTab) setActiveTab(defaultTab);
}
- }
+ });
});
+ // Bridge live soup state back to preferences. `defer: true` skips the
+ // initial run on mount, so we only write when the user actually changes
+ // something.
createEffect(
on(
- () =>
- ({
- version: PERSISTED_STATE_VERSION,
- activeTab: activeTab(),
- filters: {
- and: [...soup.predicates.andIds()],
- or: [...soup.predicates.orIds()],
- },
- queryFilters: JSON.parse(JSON.stringify(queryFilters.state)),
- sort: soup.sort.active().map((s) => s.id),
- previewEntity: soup.previewEntity(),
- assigneeFilter: assigneeFilter(),
- groupBy: soup.grouping.activeGroupId(),
- collapsedGroups: [...soup.grouping.collapsedGroups()],
- }) satisfies PersistedSoupViewState,
- (state) => {
- if (!persistenceDisabled) setPersistedState(state);
- },
+ () => soup.sort.active().map((s) => s.id),
+ (ids) => setSortPref(ids),
+ { defer: true }
+ )
+ );
+ createEffect(
+ on(
+ () => soup.grouping.activeGroupId(),
+ (id) => setGroupByPref(id),
{ defer: true }
)
);
@@ -1034,9 +981,7 @@ export const SoupViewList = (props: SoupViewListProps) => {
if (restored || isProjectList) return;
restored = true;
- const cached = props.skipPersistedState
- ? undefined
- : listStateCache.get(cacheKey);
+ const cached = listStateCache.get(cacheKey);
if (cached) {
setSearchText(cached.searchText);
soup.focus.set(cached.focus);
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsx
index 91543f0945..fbbb464e57 100644
--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx
+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx
@@ -265,10 +265,6 @@ registerComponent(
withAuth((params: SearchComponentParams = {}) => {
usePageViewTracking('search');
const preset = getViewPreset('search');
- const hasExplicitParams =
- params.initialQuery !== undefined ||
- params.initialFilters !== undefined ||
- params.initialClientFilters !== undefined;
return (
<SoupView
viewName="Search"
@@ -277,7 +273,6 @@ registerComponent(
params.initialClientFilters ?? preset?.clientFilters
}
initialSearchText={params.initialQuery}
- skipPersistedState={hasExplicitParams}
/>
);
})
diff --git a/js/app/packages/app/preferences/use-preference.ts b/js/app/packages/app/preferences/use-preference.ts
new file mode 100644
index 0000000000..af3ccf3c44
--- /dev/null
+++ b/js/app/packages/app/preferences/use-preference.ts
@@ -0,0 +1,25 @@
+import { makePersisted } from '@solid-primitives/storage';
+import { type Accessor, createSignal, type Setter } from 'solid-js';
+
+export type UsePreferenceOptions<T> = {
+ /** Value used when no saved preference exists yet. */
+ default: T;
+};
+
+/**
+ * Cross-session user preference, persisted to localStorage by `key`.
+ *
+ * Use for sticky, view-kind-scoped settings the user has chosen once and
+ * expects to apply on every visit (e.g. how a view is sorted or grouped).
+ * For state that should travel with a specific history entry instead, use
+ * `useEntryState`.
+ */
+export function usePreference<T>(
+ key: string,
+ options: UsePreferenceOptions<T>
+): [Accessor<T>, Setter<T>] {
+ const [signal, setSignal] = makePersisted(createSignal<T>(options.default), {
+ name: key,
+ });
+ return [signal, setSignal];
+}