Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(new-layout): new tasks view (#6175)
dev-rbc3226b276796
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex caf7ea2780..4bf7823555 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -15,6 +15,7 @@ import { SoupView } from '@app/features/next-soup/soup-view/soup-view';import { useRecentViewFlag } from '@app/features/next-soup/use-recent-view-flag';import { ReminderEditorSplit } from '@app/features/reminders/ReminderEditorSplit';import { SettingsPanelComponentWrapper } from '@app/features/settings/Settings';+import { TasksView } from '@app/features/tasks-view/tasks-view';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { useFeatureFlag, usePosthog } from '@app/lib/analytics/posthog';import { globalSplitManager } from '@app/signal/splitLayout';@@ -423,25 +424,37 @@ registerComponent(}));-registerComponent(- 'tasks',- withAuth(() => {- usePageViewTracking('tasks');- const user = useUserContext();- const preset = getViewPreset('tasks', undefined, {- userId: user.userId(),- isTeamAdmin: false,- });- return (- <SoupView- viewName="Tasks"- initialFilters={preset?.filters}- initialClientFilters={preset?.clientFilters}- initialGroupBy={preset?.groupBy}- />- );- })-);+function LegacyTasksView() {+ const user = useUserContext();+ const preset = getViewPreset('tasks', undefined, {+ userId: user.userId(),+ isTeamAdmin: false,+ });++ return (+ <SoupView+ viewName="Tasks"+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}+ initialGroupBy={preset?.groupBy}+ />+ );+}++function RegisteredTasksView() {+ usePageViewTracking('tasks');+ const newAppViews = useNewAppViews();++ return (+ <Show when={newAppViews.ready()} fallback={<LoadingBlock />}>+ <Show when={newAppViews.enabled()} fallback={<LegacyTasksView />}>+ <TasksView />+ </Show>+ </Show>+ );+}++registerComponent('tasks', withAuth(RegisteredTasksView));function LegacyChannelsView() {const preset = getViewPreset('channels');diff --git a/apps/web/src/components/view-shell/ViewShell.tsx b/apps/web/src/components/view-shell/ViewShell.tsxindex 873baea106..02b580ddce 100644--- a/apps/web/src/components/view-shell/ViewShell.tsx+++ b/apps/web/src/components/view-shell/ViewShell.tsx@@ -271,6 +271,27 @@ function Root(props: ViewShellRootProps) {function Aside(props: JSX.HTMLAttributes<HTMLDivElement>) {const [local, rest] = splitProps(props, ['children', 'class']);const ws = useViewShellInternal();+ const redistributionPreferredSize = () => {+ const layout = ws.aside.layout();+ if (layout.preserveDuringResize !== false) return layout.width;++ const shellWidth = ws.width();+ const mainLayout = ws.main.layout();+ if (+ shellWidth === undefined ||+ mainLayout.preferredWidth === undefined ||+ ws.detail.placement() === 'inline'+ ) {+ return layout.width;+ }++ const availableForAside =+ shellWidth -+ RESIZE_GUTTER -+ Math.max(mainLayout.preferredWidth, mainLayout.min);++ return Math.min(layout.width, Math.max(layout.min, availableForAside));+ };return (<Resize.Panel@@ -278,7 +299,7 @@ function Aside(props: JSX.HTMLAttributes<HTMLDivElement>) {index={0}minSize={ws.aside.layout().min}maxSize={ws.aside.layout().max}- redistributionPreferredSize={ws.aside.layout().width}+ redistributionPreferredSize={redistributionPreferredSize()}target={{ kind: 'px', px: ws.aside.layout().width }}collapsed={() => ws.aside.isCollapsed()}>diff --git a/apps/web/src/components/view-shell/view-shell-layout.ts b/apps/web/src/components/view-shell/view-shell-layout.tsindex 5c556d0c6a..974434957e 100644--- a/apps/web/src/components/view-shell/view-shell-layout.ts+++ b/apps/web/src/components/view-shell/view-shell-layout.ts@@ -8,6 +8,11 @@ export type AsideLayout = {width: number;min: number;max: number;+ /**+ * Whether automatic container resizing should preserve `width`.+ * Set to false with a main `preferredWidth` to let the aside yield first.+ */+ preserveDuringResize?: boolean;};export const DEFAULT_ASIDE_LAYOUT: AsideLayout = {@@ -20,6 +25,11 @@ export type MainLayout = {width?: number;min: number;max?: number;+ /**+ * Soft width protected while a yielding aside shrinks toward its minimum.+ * Unlike `min`, this does not prevent Main from shrinking when space runs out.+ */+ preferredWidth?: number;};export const DEFAULT_MAIN_LAYOUT: MainLayout = {diff --git a/apps/web/src/features/tasks-view/components/TasksControls.tsx b/apps/web/src/features/tasks-view/components/TasksControls.tsxnew file mode 100644index 0000000000..9cc9b4c7d1--- /dev/null+++ b/apps/web/src/features/tasks-view/components/TasksControls.tsx@@ -0,0 +1,200 @@+import {+ ListFilterDropdown,+ type ListFilterGroup,+ ListGroupDropdown,+ ListSortDropdown,+ useViewControlHotkeys,+} from '@app/components/view-shell';+import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';+import { PreviewButton } from '@components/app/split-layout/components/PreviewButton';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { UserIcon } from '@core/component/UserIcon';+import { useUserId } from '@core/context/user';+import { idToDisplayName } from '@core/user/util';+import { PropertyValueIcon } from '@property/component/propertyValue';+import { TagDot } from '@property/tags/TagDot';+import { useTagSets } from '@property/tags/tag-sets-context';+import { useContacts } from '@queries/contacts/contacts';+import { createMemo, Show } from 'solid-js';+import { TASK_GROUP_OPTIONS, TASK_SORT_OPTIONS } from '../constants';+import {+ TASK_PRIORITY_OPTIONS,+ TASK_STATUS_OPTIONS,+} from '../filters/task-facets';+import { useTasksView } from '../tasks-view-context';++type TaskFilterGroupId =+ | 'status'+ | 'priority'+ | 'assignees'+ | 'created-by'+ | 'tags';++export function TasksControls() {+ const panel = useSplitPanelOrThrow();+ const { state, setFacets, setPrimarySort, setState } = useTasksView();+ const contacts = useContacts();+ const currentUserId = useUserId();+ const tagSets = useTagSets();+ let filterControl: HTMLDivElement | undefined;+ let sortControl: HTMLDivElement | undefined;++ useViewControlHotkeys({+ scopeId: panel.splitHotkeyScope,+ enabled: panel.isPanelActive,+ filter: {+ description: 'Filter tasks',+ run: () => {+ const trigger = filterControl?.querySelector('button');+ trigger?.click();++ return trigger !== null && trigger !== undefined;+ },+ },+ sort: {+ description: 'Sort tasks',+ run: () => {+ const trigger = sortControl?.querySelector('button');+ trigger?.click();++ return trigger !== null && trigger !== undefined;+ },+ },+ });++ const primarySort = () => state.sort[0]?.id ?? 'updated_at';+ const activeFilterCount = createMemo(() =>+ Object.values(state.facets).reduce(+ (count, optionIds) => count + optionIds.length,+ 0+ )+ );++ const peopleOptions = createMemo(() => {+ const people = [...contacts()];+ const me = currentUserId();+ if (me && !people.some((person) => person.id === me)) {+ people.unshift({ id: me, email: '', name: idToDisplayName(me) });+ }++ return people.map((person) => ({+ id: person.id,+ label:+ person.id === me+ ? person.name+ ? `${person.name} (me)`+ : 'Me'+ : person.name || person.id,+ icon: () => (+ <UserIcon+ id={person.id}+ size="sm"+ class="size-3.5"+ suppressClick+ showTooltip={false}+ />+ ),+ }));+ });++ const filterGroups = createMemo(+ (): ListFilterGroup<TaskFilterGroupId, string>[] => [+ {+ id: 'status',+ label: 'Status',+ options: TASK_STATUS_OPTIONS.map((option) => ({+ ...option,+ icon: () => (+ <PropertyValueIcon+ optionId={option.propertyOptionId}+ class="size-3.5"+ />+ ),+ })),+ },+ {+ id: 'priority',+ label: 'Priority',+ options: TASK_PRIORITY_OPTIONS.map((option) => ({+ ...option,+ icon: () => (+ <PropertyValueIcon+ optionId={option.propertyOptionId}+ class="size-3.5"+ />+ ),+ })),+ },+ {+ id: 'assignees',+ label: 'Assignees',+ options: peopleOptions(),+ },+ {+ id: 'created-by',+ label: 'Created by',+ options: peopleOptions(),+ },+ {+ id: 'tags',+ label: 'Tags',+ options: tagSets().flatMap((set) =>+ set.options.map((option) => ({+ id: option.id,+ label:+ option.value.type === 'string' ? option.value.value : option.id,+ icon: () => <TagDot color={option.color ?? undefined} />,+ }))+ ),+ },+ ]+ );++ return (+ <div class="flex min-w-0 shrink-0 items-center justify-end gap-2 @max-[720px]/view-shell:gap-1">+ <div ref={(element) => (sortControl = element)}>+ <ListSortDropdown+ label="Sort tasks"+ value={primarySort()}+ options={TASK_SORT_OPTIONS}+ onChange={setPrimarySort}+ />+ </div>+ <ListGroupDropdown+ label="Group tasks"+ value={state.groupBy}+ options={TASK_GROUP_OPTIONS}+ onChange={(groupBy) => setState('groupBy', groupBy)}+ />+ <div+ ref={(element) => (filterControl = element)}+ class="relative shrink-0"+ >+ <ListFilterDropdown+ label="Filter tasks"+ groups={filterGroups()}+ isSelected={(groupId, optionId) =>+ (state.facets[groupId] ?? []).includes(optionId)+ }+ onSelectionChange={(groupId, optionId, selected) => {+ const update = selected+ ? addUnique(optionId)+ : removeValue(optionId);++ setFacets({+ ...state.facets,+ [groupId]: update(state.facets[groupId]),+ });+ }}+ onClear={() => setFacets({})}+ />+ <Show when={activeFilterCount() > 0}>+ <span class="absolute -top-0.5 right-0 flex size-4 translate-x-1/2 items-center justify-center rounded-full bg-accent text-xxs font-medium leading-none text-surface">+ {activeFilterCount()}+ </span>+ </Show>+ </div>+ <PreviewButton iconOnly class="rounded-lg" />+ </div>+ );+}diff --git a/apps/web/src/features/tasks-view/components/TasksHeader.tsx b/apps/web/src/features/tasks-view/components/TasksHeader.tsxnew file mode 100644index 0000000000..b4af95c2e1--- /dev/null+++ b/apps/web/src/features/tasks-view/components/TasksHeader.tsx@@ -0,0 +1,95 @@+import { SearchBar, useViewControlHotkeys } from '@app/components/view-shell';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { SplitPanel } from '@components/app/split-panel';+import MenuIcon from '@phosphor/list.svg';+import PlusIcon from '@phosphor/plus.svg';+import { Button, Dropdown } from '@ui';+import { createSignal } from 'solid-js';+import { useTasksView } from '../tasks-view-context';+import { TasksControls } from './TasksControls';+import { TasksNavigation } from './TasksSidebar';++export function TasksHeader() {+ const panel = useSplitPanelOrThrow();+ const layout = useSplitLayout();+ const { state, setState } = useTasksView();+ const [navigationOpen, setNavigationOpen] = createSignal(false);+ let searchInput: HTMLInputElement | undefined;++ useViewControlHotkeys({+ scopeId: panel.splitHotkeyScope,+ enabled: panel.isPanelActive,+ search: {+ description: 'Search tasks',+ run: () => {+ searchInput?.focus();+ searchInput?.select();+ return true;+ },+ },+ });++ const createTask = () => {+ layout.popoverSplit({ type: 'component', id: 'task-compose' });+ };++ return (+ <div class="flex min-w-0 flex-col">+ <SplitPanel.ControlGroup class="hidden px-2 pb-2 @max-[720px]/view-shell:flex">+ <SplitPanel.CloseButton />+ <SplitPanel.BackButton />+ <SplitPanel.ForwardButton />+ </SplitPanel.ControlGroup>++ <div class="mb-4 hidden min-w-0 items-center gap-2 @max-[720px]/view-shell:flex">+ <Dropdown+ open={navigationOpen()}+ onOpenChange={setNavigationOpen}+ placement="bottom-start"+ >+ <Dropdown.Trigger+ variant="ghost"+ size="sm"+ square+ class="size-8 shrink-0 rounded-full"+ aria-label="Open Tasks navigation"+ >+ <MenuIcon class="size-4" />+ </Dropdown.Trigger>+ <Dropdown.Content class="w-72 rounded-2xl p-2">+ <div class="rounded-xl bg-menu">+ <TasksNavigation onNavigate={() => setNavigationOpen(false)} />+ </div>+ </Dropdown.Content>+ </Dropdown>+ <h1 class="min-w-0 truncate text-xl font-semibold tracking-[-0.03em] text-ink">+ Tasks+ </h1>+ <Button+ type="button"+ variant="cta"+ size="md"+ class="ml-auto rounded-lg px-3"+ onClick={createTask}+ >+ <PlusIcon class="size-4 shrink-0" />+ New+ </Button>+ </div>++ <div class="flex min-w-0 items-center justify-between gap-3">+ <SearchBar+ ref={(element) => (searchInput = element)}+ label="Search tasks"+ value={state.search}+ hotkey="cmd+f"+ onValueChange={(search) => setState('search', search)}+ placeholder="Search tasks"+ class="max-w-md flex-1"+ />+ <TasksControls />+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/tasks-view/components/TasksSidebar.tsx b/apps/web/src/features/tasks-view/components/TasksSidebar.tsxnew file mode 100644index 0000000000..74635010ad--- /dev/null+++ b/apps/web/src/features/tasks-view/components/TasksSidebar.tsx@@ -0,0 +1,162 @@+import {+ CollapsibleSection,+ useViewTabHotkeys,+ ViewSidebar,+} from '@app/components/view-shell';+import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { SplitPanel } from '@components/app/split-panel';+import { EntityIcon } from '@core/component/EntityIcon';+import NoteIcon from '@phosphor/note-pencil.svg';+import PlusIcon from '@phosphor/plus.svg';+import UsersIcon from '@phosphor/users-three.svg';+import { useCurrentTeamQuery } from '@queries/team/teams';+import { Button } from '@ui';+import { For } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import {+ PERSONAL_TASK_TABS,+ type TaskTabItem,+ TEAM_TASK_TABS,+} from '../constants';+import { useTasksView } from '../tasks-view-context';++function TaskIcon(props: { class?: string }) {+ return (+ <EntityIcon+ targetType="task"+ size="fill"+ theme="monochrome"+ class={props.class}+ />+ );+}++const TAB_ICONS = {+ 'my-tasks': TaskIcon,+ 'created-by-me': NoteIcon,+ 'team-tasks': TaskIcon,+} as const;++function Tab(props: {+ item: TaskTabItem;+ onNavigate?: () => void;+ class?: string;+}) {+ const { state, setTab } = useTasksView();++ return (+ <ViewSidebar.Item+ active={state.tab === props.item.id}+ class={props.class}+ onClick={() => {+ setTab(props.item.id);+ props.onNavigate?.();+ }}+ >+ <Dynamic+ component={TAB_ICONS[props.item.id]}+ aria-hidden="true"+ class="size-4 shrink-0"+ />+ <span class="truncate">{props.item.label}</span>+ </ViewSidebar.Item>+ );+}++export function TasksNavigation(props: { onNavigate?: () => void }) {+ const { state, setState } = useTasksView();+ const team = useCurrentTeamQuery();+ const teamName = () => team.data?.team.name ?? 'Team';+ const isTeamExpanded = () =>+ !state.collapsedSidebarSectionIds.includes('team');+ const setTeamExpanded = (expanded: boolean) =>+ setState(+ 'collapsedSidebarSectionIds',+ expanded ? removeValue('team') : addUnique('team')+ );++ return (+ <div class="flex flex-col gap-3">+ <ViewSidebar.Nav aria-label="Personal task tabs">+ <For each={PERSONAL_TASK_TABS}>+ {(item) => <Tab item={item} onNavigate={props.onNavigate} />}+ </For>+ </ViewSidebar.Nav>++ <CollapsibleSection.Root+ open={isTeamExpanded()}+ onOpenChange={setTeamExpanded}+ >+ <CollapsibleSection.Trigger>+ <UsersIcon aria-hidden="true" class="size-4 shrink-0" />+ <span class="truncate">{teamName()}</span>+ <CollapsibleSection.Indicator />+ </CollapsibleSection.Trigger>+ <CollapsibleSection.Content>+ <ViewSidebar.Nav aria-label={`${teamName()} task tabs`}>+ <For each={TEAM_TASK_TABS}>+ {(item) => (+ <Tab+ item={item}+ onNavigate={props.onNavigate}+ class="pl-8 pr-3"+ />+ )}+ </For>+ </ViewSidebar.Nav>+ </CollapsibleSection.Content>+ </CollapsibleSection.Root>+ </div>+ );+}++export function TasksSidebar() {+ const layout = useSplitLayout();+ const panel = useSplitPanelOrThrow();+ const { state, setTab } = useTasksView();++ useViewTabHotkeys({+ scopeId: panel.splitHotkeyScope,+ enabled: panel.isPanelActive,+ ids: () => [...PERSONAL_TASK_TABS, ...TEAM_TASK_TABS].map((tab) => tab.id),+ activeId: () => state.tab,+ setActiveId: setTab,+ });++ const createTask = () => {+ layout.popoverSplit({ type: 'component', id: 'task-compose' });+ };++ return (+ <ViewSidebar.Root+ aria-label="Tasks navigation"+ class="gap-4 border-r-0 pt-2"+ >+ <SplitPanel.ControlGroup>+ <SplitPanel.CloseButton />+ <SplitPanel.BackButton />+ <SplitPanel.ForwardButton />+ </SplitPanel.ControlGroup>++ <ViewSidebar.Header>+ <ViewSidebar.Title>Tasks</ViewSidebar.Title>+ <Button+ type="button"+ variant="cta"+ size="md"+ class="rounded-lg px-3"+ onClick={createTask}+ >+ <PlusIcon class="size-4 shrink-0" />+ New+ </Button>+ </ViewSidebar.Header>++ <ViewSidebar.Content class="pt-1">+ <TasksNavigation />+ </ViewSidebar.Content>+ </ViewSidebar.Root>+ );+}diff --git a/apps/web/src/features/tasks-view/components/task-list/ListPropertyValue.tsx b/apps/web/src/features/tasks-view/components/task-list/ListPropertyValue.tsxnew file mode 100644index 0000000000..38ea297a20--- /dev/null+++ b/apps/web/src/features/tasks-view/components/task-list/ListPropertyValue.tsx@@ -0,0 +1,119 @@+import { useMaybeBlockId } from '@core/block';+import CircleDashedEmpty from '@phosphor/circle-dashed.svg';+import { Property } from '@property';+import { usePropertiesContext } from '@property/context/PropertiesContext';+import type { Property as PropertyType } from '@property/types';+import { getEntityValues, hasValue } from '@property/utils';+import { Layer } from '@ui';+import { Match, Show, Switch } from 'solid-js';++/**+ * Tasks-owned adaptation of the established Soup task property cell.+ * It remains local so this view does not depend on legacy Soup orchestration.+ */+export function ListPropertyValue(props: { property: PropertyType }) {+ const context = usePropertiesContext();+ const blockId = useMaybeBlockId();+ const isUserEntity = () =>+ props.property.valueType === 'ENTITY' &&+ props.property.specificEntityType === 'USER';+ const userCount = () => {+ if (!isUserEntity()) return 0;+ return getEntityValues(props.property).length;+ };+ const isEmpty = () => !hasValue(props.property);+ const isInlineType = () =>+ props.property.valueType === 'STRING' ||+ props.property.valueType === 'NUMBER' ||+ props.property.valueType === 'BOOLEAN' ||+ props.property.valueType === 'LINK';++ if (isInlineType()) {+ return (+ <Property.Root+ property={props.property}+ canEdit={context.canEdit}+ onSave={context.saveHandler.saveProperty}+ onRefresh={context.onRefresh}+ >+ <Property.Tooltip property={props.property}>+ <Layer depth={2}>+ <div+ role="presentation"+ class="list-property-cell w-full max-w-full min-w-0 overflow-hidden rounded-full text-left hover:bg-surface/50 @max-[840px]/u-list:hidden"+ onClick={(event) => event.stopPropagation()}+ >+ <Property.InlineEditor />+ </div>+ </Layer>+ </Property.Tooltip>+ </Property.Root>+ );+ }++ return (+ <Property.Root+ property={props.property}+ canEdit={context.canEdit}+ onSave={context.saveHandler.saveProperty}+ onRefresh={context.onRefresh}+ >+ <Property.Tooltip property={props.property}>+ <Layer depth={2}>+ <Property.EditTrigger class="list-property-cell inline-flex w-full max-w-full min-w-0 items-center gap-1 overflow-hidden rounded-full px-2 py-1.5 text-left leading-tight hover:bg-surface/50 @max-[840px]/u-list:px-1">+ <Show+ when={!isEmpty()}+ fallback={+ <>+ <CircleDashedEmpty class="size-3 shrink-0 opacity-50 @max-[840px]/u-list:size-4" />+ <span class="min-w-0 flex-1 truncate opacity-50 @max-[840px]/u-list:hidden">+ {props.property.displayName}+ </span>+ </>+ }+ >+ <Switch+ fallback={+ <Property.Icon+ property={props.property}+ class="size-3 shrink-0 @max-[840px]/u-list:size-4"+ />+ }+ >+ <Match when={userCount() > 1}>+ <div class="@max-[840px]/u-list:hidden">+ <Property.UserStack+ property={props.property}+ maxUsers={2}+ />+ </div>+ <div class="hidden @max-[840px]/u-list:flex">+ <Property.UserStack+ property={props.property}+ maxUsers={1}+ avatarClass="@max-[840px]/u-list:size-5"+ />+ </div>+ </Match>+ <Match when={isUserEntity()}>+ <Property.Icon+ property={props.property}+ class="@max-[840px]/u-list:size-5"+ />+ </Match>+ </Switch>+ <Property.Text+ property={props.property}+ class="min-w-0 max-w-full flex-1 @max-[840px]/u-list:hidden"+ />+ </Show>+ <Property.Caret class="@max-[840px]/u-list:hidden" />+ </Property.EditTrigger>+ </Layer>+ </Property.Tooltip>+ <Property.PopoverEditor+ entitySelfFilter={{ entityType: context.entityType, blockId }}+ />+ </Property.Root>+ );+}diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsxnew file mode 100644index 0000000000..ba3087a436--- /dev/null+++ b/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx@@ -0,0 +1,242 @@+import { UserIcon } from '@core/component/UserIcon';+import { getDisplayNameParts, tryMacroId } from '@core/user';+import {+ Entity,+ isProjectContainedEntity,+ MultiSelectCheckbox,+ ProjectBreadCrumb,+ type TaskEntityWithProperties,+ UnreadIndicator,+} from '@entity';+import {+ CreatedByBadgeSmall,+ SharedBadgeSmall,+} from '@entity/components/Badges';+import type { LayoutProps } from '@entity/composed/list-entity/shared';+import { soupPropertyToProperty } from '@entity/extractors-property';+import { Modals } from '@property/component/modal';+import {+ PropertiesProvider,+ type PropertySaveHandler,+} from '@property/context/PropertiesContext';+import { EntityRowTags } from '@property/tags';+import type { Property, PropertyApiValues } from '@property/types';+import { useUserId } from '@queries/auth';+import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';+import { EntityType } from '@service-properties/generated/schemas/entityType';+import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';+import { cn } from '@ui/utils/classname';+import { createMemo, For, Show, Suspense } from 'solid-js';+import { ListPropertyValue } from './ListPropertyValue';+import {+ TASK_GRID_COLUMNS,+ TASK_GRID_TEMPLATE_AREAS_WIDE,+ TASK_GRID_TEMPLATE_AREAS_WIDE_NO_INDICATOR,+ TASK_GRID_TEMPLATE_COLUMNS_WIDE,+ TASK_GRID_TEMPLATE_COLUMNS_WIDE_NO_INDICATOR,+ type TaskGridColumn,+} from './task-grid-template';++const EPOCH = new Date(0).toISOString();++/**+ * Build a placeholder Property for a column when the entity doesn't yet have+ * the property attached. Lets the editor open and create the property on save.+ */+function buildStubProperty(col: TaskGridColumn): Property {+ const stubSoup: SoupProperty = {+ id: col.defId,+ definition: {+ id: col.defId,+ display_name: col.label,+ data_type: col.dataType,+ is_metadata: false,+ is_multi_select: col.isMultiSelect,+ is_system: true,+ owner: { scope: 'system' },+ specific_entity_type: col.specificEntityType,+ created_at: EPOCH,+ updated_at: EPOCH,+ },+ };+ return soupPropertyToProperty(stubSoup);+}++type TaskGridLayoutProps = Omit<LayoutProps, 'entity'> & {+ entity: TaskEntityWithProperties;+};++export function TaskGridLayout(props: TaskGridLayoutProps) {+ const currentId = useUserId();+ const entity = () => props.entity;+ const isShared = () => props.entity.ownerId !== currentId();++ // Get owner's first name for the Created By column+ const ownerDisplayName = () =>+ isShared()+ ? getDisplayNameParts(tryMacroId(props.entity.ownerId)).firstName ||+ 'Unknown'+ : 'Me';++ const propertyMap = createMemo(() => {+ const map = new Map<string, Property>();+ for (const sp of entity().properties ?? []) {+ try {+ const property = soupPropertyToProperty(sp);+ map.set(property.propertyDefinitionId, property);+ } catch (error) {+ console.warn('Skipping property with unsupported type', error);+ }+ }+ return map;+ });++ const properties = createMemo(() => Array.from(propertyMap().values()));++ const saveMutation = useBulkSaveEntityPropertiesMutation();++ const saveOne = (property: Property, apiValues: PropertyApiValues) =>+ saveMutation.mutateAsync({+ properties: [+ {+ entityId: props.entity.id,+ entityType: EntityType.TASK,+ property,+ apiValues,+ },+ ],+ });++ const saveHandler: PropertySaveHandler = {+ saveProperty: (property, value) => saveOne(property, value),+ saveDate: (property, date) =>+ saveOne(property, { valueType: 'DATE', value: date }),+ };++ return (+ <PropertiesProvider+ entityId={props.entity.id}+ entityType={EntityType.TASK}+ canEdit={true}+ properties={properties}+ onRefresh={() => {}}+ onPropertyAdded={() => {}}+ onPropertyDeleted={() => {}}+ saveHandler={saveHandler}+ >+ <Entity.Layout+ class={cn(+ 'task-grid-row w-full min-h-[inherit] items-center text-sm px-2',+ 'gap-2 grid grid-rows-[1fr]'+ )}+ style={{+ 'grid-template-columns': props.hideCheckbox+ ? TASK_GRID_TEMPLATE_COLUMNS_WIDE_NO_INDICATOR+ : TASK_GRID_TEMPLATE_COLUMNS_WIDE,+ 'grid-template-areas': props.hideCheckbox+ ? TASK_GRID_TEMPLATE_AREAS_WIDE_NO_INDICATOR+ : TASK_GRID_TEMPLATE_AREAS_WIDE,+ }}+ >+ <Show when={!props.hideCheckbox}>+ <Entity.Slot placement="indicator" class="relative size-full group">+ <div class="absolute inset-0 grid place-items-center group-hover:opacity-0">+ <UnreadIndicator active={props.unread} />+ </div>+ <div+ class={cn(+ 'absolute inset-0 grid place-items-center opacity-0 group-hover:opacity-100',+ {+ 'opacity-100': props.checked,+ }+ )}+ >+ <MultiSelectCheckbox+ checked={props.checked}+ onChecked={props.onChecked}+ />+ </div>+ </Entity.Slot>+ </Show>++ <Entity.Slot+ placement="content"+ class="ph-no-capture font-medium truncate items-center gap-2 flex min-w-0"+ >+ <div class="size-4 shrink-0">+ <Entity.Icon+ entity={props.entity}+ streamState={props.streamState}+ />+ </div>+ <span class="truncate min-w-0">+ <Entity.Title entity={props.entity} />+ </span>+ <Show when={isProjectContainedEntity(props.entity) && props.entity}>+ {(entity) => (+ <span class="ph-no-capture text-ink text-xs shrink-0 truncate border border-edge-muted px-2 rounded-sm py-0.5">+ <ProjectBreadCrumb+ entity={entity()}+ onClick={props.onProjectClick}+ />+ </span>+ )}+ </Show>+ {/* Show shared badges on narrow/medium containers, hide on wide (>1220px) */}+ <Show when={isShared()}>+ {/* Narrow: "shared this with you" tooltip */}+ <span class="@min-[841px]/u-list:hidden">+ <SharedBadgeSmall ownerId={props.entity.ownerId} />+ </span>+ {/* Medium (841px-1220px): "Created by" tooltip */}+ <span class="hidden @min-[841px]/u-list:inline @min-[1221px]/u-list:hidden">+ <CreatedByBadgeSmall ownerId={props.entity.ownerId} />+ </span>+ </Show>+ <EntityRowTags+ entityId={props.entity.id}+ entityType={EntityType.TASK}+ properties={entity().properties}+ class="ml-auto"+ />+ </Entity.Slot>++ <For each={TASK_GRID_COLUMNS}>+ {(col) => (+ <Entity.Slot+ placement={col.id}+ class="flex items-center min-w-0 text-xs ph-no-capture @container/slot @max-[840px]/u-list:justify-center"+ >+ <ListPropertyValue+ property={+ propertyMap().get(col.defId) ?? buildStubProperty(col)+ }+ />+ </Entity.Slot>+ )}+ </For>++ {/* Created By column - only shown on wide containers (>1220px) */}+ <Entity.Slot+ placement="createdBy"+ class="hidden @min-[1221px]/u-list:flex items-center gap-1.5 min-w-0 overflow-hidden text-xs ph-no-capture"+ >+ <UserIcon id={props.entity.ownerId} size="sm" showTooltip={true} />+ <span class="truncate text-ink-muted">{ownerDisplayName()}</span>+ </Entity.Slot>++ <Entity.Slot+ placement="timestamp"+ class="text-xs text-right text-ink-extra-muted font-light"+ >+ <Show when={!props.hasNotifications}>+ <Entity.Timestamp entity={props.entity} />+ </Show>+ </Entity.Slot>+ </Entity.Layout>+ <Suspense>+ <Modals />+ </Suspense>+ </PropertiesProvider>+ );+}diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsxnew file mode 100644index 0000000000..06e5fb3d5a--- /dev/null+++ b/apps/web/src/features/tasks-view/components/task-list/TaskGroupHeader.tsx@@ -0,0 +1,127 @@+import type { SoupGroupHeaderRow } from '@app/features/soup';+import { UserIcon } from '@core/component/UserIcon';+import { getDisplayName, tryMacroId } from '@core/user';+import { getPropertyOptionLabel } from '@entity';+import CaretRightIcon from '@phosphor/caret-right.svg';+import CircleDashedIcon from '@phosphor/circle-dashed.svg';+import FolderIcon from '@phosphor/folder-simple.svg';+import { PROPERTY_OPTION_IDS } from '@property';+import { PropertyValueIcon } from '@property/component/propertyValue';+import { cn, Layer, Surface } from '@ui';+import { createMemo, Match, Show, Switch } from 'solid-js';+import type { TaskGroupBy } from '../../types';++const STATUS_GROUP_HEADER_TINTS: Record<string, string> = {+ [PROPERTY_OPTION_IDS.STATUS.NOT_STARTED]:+ 'bg-task/5 border-task/10 data-highlighted:bg-task/10 hover:bg-task/10',+ [PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS]:+ 'bg-alert/5 border-alert/10 data-highlighted:bg-alert/10 hover:bg-alert/10',+ [PROPERTY_OPTION_IDS.STATUS.IN_REVIEW]:+ 'bg-note/5 border-note/10 data-highlighted:bg-note/10 hover:bg-note/10',+ [PROPERTY_OPTION_IDS.STATUS.COMPLETED]:+ 'bg-accent/5 border-accent/10 data-highlighted:bg-accent/10 hover:bg-accent/10',+ [PROPERTY_OPTION_IDS.STATUS.CANCELED]:+ 'bg-ink/5 border-ink/10 data-highlighted:bg-ink/10 hover:bg-ink/10',+};++export function TaskGroupHeader(props: {+ row: SoupGroupHeaderRow;+ groupBy: TaskGroupBy;+ expanded: boolean;+ focused: boolean;+ onToggle: () => void;+ onFocus: () => void;+}) {+ const label = createMemo(() => {+ if (!props.row.groupId) return props.row.label || 'Not set';++ if (props.groupBy === 'status' || props.groupBy === 'priority') {+ return getPropertyOptionLabel(props.row.groupId) ?? props.row.label;+ }++ if (props.groupBy === 'assignee') {+ const assigneeId = tryMacroId(props.row.groupId);+ if (!assigneeId) return props.row.label;+ return (+ getDisplayName(assigneeId, { emailFallback: 'local-part' }) ||+ props.row.label+ );+ }++ return props.row.label;+ });+ const statusTint = createMemo(() =>+ props.groupBy === 'status'+ ? STATUS_GROUP_HEADER_TINTS[props.row.groupId]+ : undefined+ );++ return (+ <div id={props.row.id} role="row">+ <div role="gridcell" aria-colspan={7}>+ <Surface+ depth={3}+ hideBorder+ data-highlighted={props.focused || undefined}+ class={cn(+ 'group/header mx-1 my-0.5 h-auto w-[calc(100%-0.5rem)] rounded-lg border border-edge-muted text-ink-muted hover:bg-active',+ statusTint(),+ props.focused && 'bg-active'+ )}+ >+ <button+ type="button"+ tabIndex={-1}+ class="flex w-full items-center gap-2.5 rounded-[inherit] px-2 py-1.5 text-left text-xs font-semibold tracking-tight"+ aria-expanded={props.expanded}+ onMouseMove={props.onFocus}+ onClick={props.onToggle}+ >+ <Layer depth={3}>+ <span class="flex size-4.5 items-center justify-center rounded-xs group-hover/header:bg-ink/5">+ <CaretRightIcon+ class={cn(+ 'size-2.5 transition-transform',+ props.expanded && 'rotate-90'+ )}+ />+ </span>+ </Layer>+ <Switch>+ <Match when={!props.row.groupId}>+ <CircleDashedIcon class="size-3.5 text-ink-extra-muted" />+ </Match>+ <Match+ when={+ props.groupBy === 'status' || props.groupBy === 'priority'+ }+ >+ <PropertyValueIcon+ optionId={props.row.groupId}+ class="size-3.5"+ />+ </Match>+ <Match when={props.groupBy === 'assignee'}>+ <UserIcon+ id={props.row.groupId}+ size="sm"+ suppressClick+ showTooltip={false}+ />+ </Match>+ <Match when={props.groupBy === 'project'}>+ <FolderIcon class="size-3.5 shrink-0" />+ </Match>+ </Switch>+ <span class="truncate">{label()}</span>+ <Show when={props.row.count !== undefined}>+ <span class="shrink-0 rounded-full bg-ink/10 px-1.5 py-px text-xs font-medium tabular-nums text-ink-extra-muted">+ {props.row.count}+ </span>+ </Show>+ </button>+ </Surface>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsxnew file mode 100644index 0000000000..147bbd5206--- /dev/null+++ b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx@@ -0,0 +1,710 @@+import {+ createListController,+ type ListActivation,+ listOwnedSlotName,+ useListInteractions,+} from '@app/components/list';+import {+ resolveEntityActionViewContext,+ toEntityActionListState,+ useEntityActionHotkeys,+} from '@app/features/next-soup/actions';+import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';+import {+ MaybeSoupEntityActionDrawerManager,+ SoupEntityContextMenu,+ useSoupListNavigationHotkeys,+} from '@app/features/soup';+import { makePersistedState } from '@app/lib/persistence';+import {+ addUnique,+ removeValue,+ toggleValue,+} from '@app/lib/signals/store-array-updaters';+import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';+import {+ useSplitPanelOrThrow,+ withSplitPanelOwner,+} from '@components/app/split-layout/layoutUtils';+import { useUserId } from '@core/context/user';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import {+ type EntityData,+ EntitySelectionToolbar,+ getTaskStatusOptionId,+ ListLayoutProvider,+ type TaskEntityWithProperties,+} from '@entity';+import { useListLayout } from '@entity/composed/list-entity/shared';+import { soupPropertyToProperty } from '@entity/extractors-property';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import SpinnerIcon from '@phosphor/spinner.svg';+import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property';+import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';+import { useTagsQuery } from '@queries/properties/tags';+import { EntityType } from '@service-properties/generated/schemas/entityType';+import { Button, cn, Surface } from '@ui';+import {+ createEffect,+ createMemo,+ createSignal,+ Match,+ type Setter,+ Show,+ Suspense,+ Switch,+} from 'solid-js';+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';+import {+ createTasksListEntryStorage,+ DEFAULT_TASKS_LIST_STATE,+ type TasksListStateSnapshot,+} from '../../persistence';+import {+ type TasksDataSourceItem,+ useTasksDataSource,+} from '../../queries/use-tasks-query';+import { useTasksView } from '../../tasks-view-context';+import { TaskGroupHeader } from './TaskGroupHeader';+import { TaskListEntity } from './TaskListEntity';+import { TaskListHeader } from './TaskListHeader';+import './task-list.css';++function ResponsiveTaskListHeader() {+ const layout = useListLayout();++ return (+ <Show when={(layout?.isWide() ?? true) && !isTouchDevice()}>+ <TaskListHeader />+ </Show>+ );+}++const getStatusProperty = (task: TaskEntityWithProperties) => {+ const status = task.properties?.find(+ (property) => property.definition.id === SYSTEM_PROPERTY_IDS.STATUS+ );+ if (!status) return undefined;+ try {+ return soupPropertyToProperty(status);+ } catch {+ return undefined;+ }+};++type TasksListActivationMetadata = {+ event?: MouseEvent;+ newSplit?: boolean;+};++export function TaskList() {+ const panel = useSplitPanelOrThrow();+ const { state, setState } = useTasksView();+ const userId = useUserId();+ const isGroupExpanded = (groupId: string) =>+ !state.collapsedGroupIds.includes(groupId);+ const setGroupExpanded = (groupId: string, expanded: boolean) =>+ setState(+ 'collapsedGroupIds',+ expanded ? removeValue(groupId) : addUnique(groupId)+ );+ const toggleGroup = (groupId: string) =>+ setState('collapsedGroupIds', toggleValue(groupId));++ const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () => {+ const tagsQuery = useTagsQuery();++ return useTasksDataSource(state, {+ userId,+ tagSets: () => tagsQuery.data ?? [],+ isGroupExpanded,+ });+ });++ function openEntity(+ entity: EntityData,+ options: {+ openInNewSplit?: boolean;+ replacePreview?: boolean;+ mergeHistory?: boolean;+ } = {}+ ) {+ void openEntityInSplitFromUnifiedList(entity, {+ splitHandle: panel.handle,+ referredFrom: 'tasks',+ ...options,+ });+ }++ function onActivate({+ item,+ metadata,+ }: ListActivation<TasksDataSourceItem, TasksListActivationMetadata>) {+ if (item.kind === 'group-header') {+ toggleGroup(item.groupId);++ return;+ }++ if (item.kind === 'load-more' && item.groupId !== undefined) {+ const focusIndex = list.items.indexOf(item.id);+ void source.loadMoreGroup(item.groupId).then(() => {+ if (list.focus.requestedKey() !== item.id) return;++ list.focus.restore(item.id, {+ fallback: 'nearest',+ nearestIndex: focusIndex,+ retainUnavailable: false,+ });+ });++ return;+ }++ if (item.kind !== 'entity') return;++ const sourceRow = source+ .items()+ .find((row) => row.kind === 'entity' && row.id === item.id);++ if (sourceRow?.kind !== 'entity') return;++ const newSplit =+ metadata?.newSplit === true || metadata?.event?.shiftKey === true;++ openEntity(sourceRow.entity, {+ openInNewSplit: newSplit,+ replacePreview: metadata?.event?.altKey === true && !newSplit,+ });+ }++ const list = withSplitPanelOwner(listOwnedSlotName('controller'), () =>+ createListController<TasksDataSourceItem, TasksListActivationMetadata>({+ items: source.items,+ getKey: (row) => row.id,+ selection: {+ getKey: (row) => (row.kind === 'entity' ? row.entity.id : row.id),+ },+ isNavigable: (row) => row.kind !== 'section-header',+ isSelectable: (row) => row.kind === 'entity',+ onActivate,+ })+ );++ withSplitPanelOwner(listOwnedSlotName('navigation-hotkeys'), () => {+ useSoupListNavigationHotkeys({+ splitHotkeyScope: panel.splitHotkeyScope,+ viewId: 'tasks',+ dataSource: source,+ controller: list,+ handle: panel.handle,+ openEntityInSplit: (task, options) => {+ openEntity(task, {+ mergeHistory: options.mergeHistory,+ });+ },+ });+ });++ const entityActionViewContext = () =>+ resolveEntityActionViewContext({+ activeListView: panel.handle.content().id,+ activeTab: state.tab,+ });+ const [viewport, setViewport] = createSignal<HTMLDivElement>();+ const [grid, setGrid] = createSignal<HTMLDivElement>();+ const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();++ let scrollOffset = DEFAULT_TASKS_LIST_STATE.scrollOffset;+ const readListState = (): TasksListStateSnapshot => ({+ focusKey: list.focus.requestedKey(),+ scrollOffset: virtualizer()?.scrollOffset ?? scrollOffset,+ });++ const applyListState: Setter<TasksListStateSnapshot> = (next) => {+ const current = readListState();+ const value = typeof next === 'function' ? next(current) : next;++ if (value.focusKey !== current.focusKey) {+ list.focus.restore(value.focusKey, { reason: 'restore' });+ }++ scrollOffset = value.scrollOffset;+ if (value.scrollOffset !== current.scrollOffset) {+ virtualizer()?.scrollTo(value.scrollOffset);+ }++ return value;+ };+ const [, setPersistedListState] = makePersistedState(+ [readListState, applyListState],+ { storages: createTasksListEntryStorage(panel.handle) }+ );++ const visibleRows = source.items;+ const tasksById = createMemo(() => {+ const tasks = new Map<string, TaskEntityWithProperties>();+ for (const row of visibleRows()) {+ if (row.kind === 'entity') tasks.set(row.entity.id, row.entity);+ }+ return tasks;+ });+ const saveProperties = useBulkSaveEntityPropertiesMutation();+ const canCompleteTask = (taskId: string) => {+ const task = tasksById().get(taskId);+ if (!task || saveProperties.isPending) return false;+ return (+ getTaskStatusOptionId(task) !== PROPERTY_OPTION_IDS.STATUS.COMPLETED &&+ getStatusProperty(task) !== undefined+ );+ };+ const completeTask = (taskId: string) => {+ const task = tasksById().get(taskId);+ if (!task) return;+ const property = getStatusProperty(task);+ if (!property) return;+ saveProperties.mutate({+ properties: [+ {+ entityId: task.id,+ entityType: EntityType.TASK,+ property,+ apiValues: {+ valueType: 'SELECT_STRING',+ values: [PROPERTY_OPTION_IDS.STATUS.COMPLETED],+ },+ },+ ],+ });+ };++ const selectedTasks = createMemo(() =>+ list.selection+ .items()+ .flatMap((row) => (row.kind === 'entity' ? [row.entity] : []))+ );++ const focusedTask = () => {+ const row = list.focus.result()?.item;+ return row?.kind === 'entity' ? row.entity : undefined;+ };++ const actionState = toEntityActionListState({+ controller: list,+ getEntity: (row) => (row.kind === 'entity' ? row.entity : undefined),+ onFocus: (target) => {+ if (target) {+ virtualizer()?.scrollToIndex(target.index, { align: 'nearest' });+ }++ grid()?.focus();+ },+ });++ const listInteractions = useListInteractions({+ controller: list,+ scopeId: panel.splitHotkeyScope,+ scrollHandle: virtualizer,+ enabled: panel.isPanelActive,+ navigation: {+ onNavigate: (event) => {+ const row = event.result?.item;+ if (row?.kind === 'entity' && panel.handle.isControllerSplit()) {+ openEntity(row.entity, {+ mergeHistory: true,+ });+ }++ if (event.kind !== 'move' || event.direction !== 1) return;+ if (source.isLoadingMore() || !source.hasMore()) {+ return;+ }++ const distanceFromEnd = event.result+ ? list.items.count() - event.result.index - 1+ : 0;+ if (distanceFromEnd > 3) return;++ void source.loadMore();+ },+ },+ activation: {+ createMetadata: (intent) => ({ newSplit: intent === 'alternate' }),+ alternateDescription: 'Open in new split',+ },+ disclosure: {+ getKey: (row) =>+ row.kind === 'section-header' ? undefined : row.groupId,+ isExpanded: isGroupExpanded,+ setExpanded: setGroupExpanded,+ getFocusKey: (groupId) =>+ visibleRows().find(+ (row) => row.kind === 'group-header' && row.groupId === groupId+ )?.id,+ },+ });++ useEntityActionHotkeys({+ scopeId: panel.splitHotkeyScope,+ list: actionState,+ selectedEntities: selectedTasks,+ focusedEntity: focusedTask,+ restoreFocus: () => grid()?.focus(),+ viewContext: entityActionViewContext,+ splitHandle: panel.handle,+ condition: panel.isPanelActive,+ });++ let restoredScroll = false;+ function registerVirtualizer(handle?: VirtualizerHandle) {+ setVirtualizer(handle);+ if (!handle || restoredScroll) return;++ handle.scrollTo(scrollOffset);+ restoredScroll = true;+ }++ let activeTab = state.tab;+ createEffect(() => {+ const nextTab = state.tab;+ if (nextTab === activeTab) return;++ activeTab = nextTab;+ listInteractions.selection.clear();+ list.focus.clear({ reason: 'programmatic' });+ panel.handle.resetPreview();+ setPersistedListState((current) => ({ ...current, scrollOffset: 0 }));+ });++ createEffect(() => {+ visibleRows();+ if (source.isLoading()) return;+ if (list.focus.result()) return;++ const restored = list.focus.restore(list.focus.requestedKey(), {+ retainUnavailable: false,+ });+ if (restored) return;+ if (isTouchDevice()) return;+ if (panel.handle.isControllerSplit()) {+ panel.handle.resetPreview();+ return;+ }++ list.focus.first({+ isNavigable: (row) => row.kind === 'entity',+ reason: 'restore',+ });+ });++ function checkNearEnd() {+ const handle = virtualizer();+ if (!handle) return;++ if (!source.hasMore()) return;++ const distance =+ handle.scrollSize - handle.scrollOffset - handle.viewportSize;+ if (distance >= 300 || source.isLoadingMore()) return;++ void source.loadMore();+ }++ const emptyMessage = () => {+ if (state.search.trim()) return 'No tasks match this search.';++ return 'No tasks in this view.';+ };++ return (+ <MaybeSoupEntityActionDrawerManager>+ <Surface+ depth={2}+ ref={setGrid}+ role="grid"+ aria-label="Tasks"+ aria-multiselectable="true"+ aria-activedescendant={list.focus.key()}+ tabIndex={0}+ class="@container/u-list flex min-h-0 min-w-0 flex-col rounded-2xl p-2 outline-none"+ >+ <ListLayoutProvider ref={grid}>+ <ResponsiveTaskListHeader />+ <SwipableRowProvider+ container={viewport}+ canSwipeLeft={canCompleteTask}+ canSwipeRight={() => false}+ onSwipeLeft={completeTask}+ triggerBehavior="spring-back"+ >+ <Switch>+ <Match when={source.isLoading()}>+ <div class="grid min-h-0 flex-1 place-items-center text-ink-muted">+ <SpinnerIcon class="size-5 animate-spin" />+ </div>+ </Match>++ <Match when={source.error()}>+ <div class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted">+ <span>Tasks couldn’t be loaded.</span>+ <Button+ variant="outline"+ size="sm"+ class="rounded-lg"+ onClick={() => void source.refresh()}+ >+ Try again+ </Button>+ </div>+ </Match>++ <Match when={visibleRows().length === 0}>+ <div class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted">+ <span>{emptyMessage()}</span>+ <Show when={source.hasMore()}>+ <Button+ variant="outline"+ size="sm"+ class="rounded-lg"+ disabled={source.isLoadingMore()}+ onClick={() => void source.loadMore()}+ >+ <Show+ when={source.isLoadingMore()}+ fallback="Search more results"+ >+ <SpinnerIcon class="size-3 animate-spin" />+ Searching+ </Show>+ </Button>+ </Show>+ </div>+ </Match>++ <Match when={true}>+ <div+ ref={setViewport}+ class="min-h-0 flex-1 overflow-auto overscroll-none"+ >+ <Suspense>+ <Virtualizer+ ref={registerVirtualizer}+ data={visibleRows()}+ scrollRef={viewport()}+ bufferSize={240}+ itemSize={44}+ keepMounted={+ list.focus.index() >= 0+ ? [list.focus.index()]+ : undefined+ }+ onScroll={checkNearEnd}+ >+ {(row) => (+ <div>+ <Switch>+ <Match+ when={+ row.kind === 'group-header' ? row : undefined+ }+ >+ {(group) => (+ <TaskGroupHeader+ row={group()}+ groupBy={state.groupBy}+ expanded={isGroupExpanded(group().groupId)}+ focused={list.focus.key() === group().id}+ onFocus={() =>+ list.focus.set(group().id, {+ reason: 'hover',+ })+ }+ onToggle={() =>+ list.activate.key(group().id, {+ reason: 'pointer',+ })+ }+ />+ )}+ </Match>+ <Match when={row.kind === 'entity' && row}>+ {(entityRow) => (+ <SoupEntityContextMenu+ entity={entityRow().entity}+ list={actionState}+ selectedEntities={selectedTasks}+ viewContext={entityActionViewContext()}+ onOpenChange={(open) => {+ if (!open) return;+ list.focus.set(entityRow().id, {+ reason: 'pointer',+ force: true,+ });+ list.selection.setAnchor(entityRow().id);+ }}+ >+ <TaskListEntity+ rowId={entityRow().id}+ entity={entityRow().entity}+ highlighted={+ list.focus.key() === entityRow().id+ }+ checked={list.selection.isSelected(+ entityRow().id+ )}+ onMouseMove={() =>+ list.focus.set(entityRow().id, {+ reason: 'hover',+ })+ }+ onClick={(event) => {+ if (+ event.metaKey ||+ event.ctrlKey ||+ (isTouchDevice() &&+ list.selection.count() > 0)+ ) {+ listInteractions.selection.toggle(+ entityRow().id+ );++ return;+ }++ list.activate.key(entityRow().id, {+ reason: 'pointer',+ metadata: { event },+ });+ }}+ onProjectClick={(project, event) => {+ const openInNewSplit = event.shiftKey;++ openEntity(project, {+ openInNewSplit,+ replacePreview:+ event.altKey && !openInNewSplit,+ });+ }}+ onChecked={(selected, shiftKey) =>+ listInteractions.selection.set(+ entityRow().id,+ selected,+ { range: shiftKey }+ )+ }+ entityRowConfig={{+ swipeLeftColor: 'bg-success',+ swipeLeftRevealedComponent: (+ <CheckIcon class="size-8 text-surface" />+ ),+ }}+ />+ </SoupEntityContextMenu>+ )}+ </Match>+ <Match+ when={+ row.kind === 'section-header' ? row : undefined+ }+ >+ {(section) => (+ <div id={section().id} role="row">+ <div+ role="gridcell"+ aria-colspan={7}+ class="flex h-8 items-end px-3 pb-1 text-xs font-semibold text-ink-extra-muted"+ >+ {section().label}+ </div>+ </div>+ )}+ </Match>+ <Match+ when={row.kind === 'load-more' ? row : undefined}+ >+ {(loadMore) => {+ const highlighted = () =>+ list.focus.key() === loadMore().id;+ const buttonClass = () =>+ cn({+ 'bg-surface': !highlighted(),+ 'border-transparent': highlighted(),+ });+ const activate = () => {+ if (loadMore().isLoading) return;+ list.activate.key(loadMore().id, {+ reason: 'pointer',+ });+ };++ return (+ <div id={loadMore().id} role="row">+ <div+ role="gridcell"+ aria-colspan={7}+ aria-busy={loadMore().isLoading}+ onMouseMove={() =>+ list.focus.set(loadMore().id, {+ reason: 'hover',+ })+ }+ onClick={activate}+ class={cn(+ 'my-1 flex min-h-9 items-center justify-center rounded',+ highlighted()+ ? 'mx-1 w-[calc(100%-0.5rem)] bg-active/60'+ : 'mx-auto'+ )}+ >+ <Show+ when={!loadMore().isLoading}+ fallback={+ <Button+ variant="outline"+ size="sm"+ depth={2}+ class={buttonClass()}+ disabled+ >+ <SpinnerIcon class="size-3 animate-spin" />+ Loading...+ </Button>+ }+ >+ <Button+ variant="outline"+ size="sm"+ depth={2}+ class={buttonClass()}+ >+ <CaretDownIcon class="size-2.5" />+ Load More+ </Button>+ </Show>+ </div>+ </div>+ );+ }}+ </Match>+ </Switch>+ </div>+ )}+ </Virtualizer>+ </Suspense>+ </div>+ </Match>+ </Switch>+ </SwipableRowProvider>+ <Show when={selectedTasks().length > 0}>+ <EntitySelectionToolbar+ selected={selectedTasks()}+ onClear={listInteractions.selection.clear}+ analyticsSource="tasks_view_selection_toolbar"+ />+ </Show>+ </ListLayoutProvider>+ </Surface>+ </MaybeSoupEntityActionDrawerManager>+ );+}diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskListEntity.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskListEntity.tsxnew file mode 100644index 0000000000..3a16717e61--- /dev/null+++ b/apps/web/src/features/tasks-view/components/task-list/TaskListEntity.tsx@@ -0,0 +1,202 @@+import '@entity/composed/ListEntity.css';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ SwipableRow,+ SwipableRowContext,+} from '@components/app/mobile/SwipableRow';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';+import { isMobile } from '@core/mobile/isMobile';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import {+ createEntityDraggable,+ Entity,+ filterNotDoneNotifications,+ filterValidNotifications,+ isWithNotification,+ type TaskEntityWithProperties,+ unreadFilterFn,+ useIsShared,+} from '@entity';+import { NarrowLayout } from '@entity/composed/list-entity/narrow-layout';+import {+ type BaseListEntityProps,+ hasSearchContentHits,+ useCharacterCount,+ useListLayout,+} from '@entity/composed/list-entity/shared';+import type { EntityRowConfig } from '@entity/extractors-notification';+import {+ BULK_DOCUMENT_WAKEUP_FEATURE_FLAG,+ enqueueDocumentWakeup,+ isWakeableDocument,+} from '@queries/preview';+import {+ getStreamState,+ subscribeToStreamState,+} from '@service-connection/stream-events';+import { mergeRefs } from '@solid-primitives/refs';+import { cn } from '@ui/utils/classname';+import {+ createEffect,+ createSignal,+ type JSX,+ Match,+ Show,+ Switch,+ useContext,+} from 'solid-js';+import { TaskGridLayout } from './TaskGridLayout';++type TaskListEntityProps = Omit<BaseListEntityProps, 'entity'> & {+ entity: TaskEntityWithProperties;+ rowId?: string;+ showUnrollNotifications?: boolean;+};++function MaybeEntityRow(props: {+ entityId: string;+ children: JSX.Element;+ config?: EntityRowConfig;+}) {+ const ctx = useContext(SwipableRowContext);+ return (+ <Show when={isMobile() && ctx} fallback={props.children}>+ <SwipableRow+ id={props.entityId}+ swipeLeftColor={props.config?.swipeLeftColor}+ swipeLeftRevealedComponent={props.config?.swipeLeftRevealedComponent}+ swipeRightColor={props.config?.swipeRightColor}+ swipeRightRevealedComponent={props.config?.swipeRightRevealedComponent}+ >+ {props.children}+ </SwipableRow>+ </Show>+ );+}++/**+ * Task-specific list entity that renders properties (Status, Priority,+ * Assignees, Due Date) in fixed-width grid columns so they line up+ * vertically across rows in a list.+ */+export function TaskListEntity(props: TaskListEntityProps) {+ const unread = () => unreadFilterFn(props.entity);+ const isShared = useIsShared(props.entity);+ const bulkWakeupEnabled = useFeatureFlag(BULK_DOCUMENT_WAKEUP_FEATURE_FLAG);++ createEffect(() => {+ if (!bulkWakeupEnabled().enabled) return;+ if (!isWakeableDocument(props.entity)) return;++ enqueueDocumentWakeup(props.entity);+ });++ subscribeToStreamState(props.entity.id, props.entity.type);+ const streamState = getStreamState(props.entity.id);++ const hasNotifications = () => {+ if (!isWithNotification(props.entity)) return false;+ return (+ filterNotDoneNotifications(+ filterValidNotifications(props.entity.notifications?.())+ ).length > 0+ );+ };++ const [snippetContainerRef, setSnippetContainerRef] = createSignal<+ HTMLElement | undefined+ >();+ const chars = useCharacterCount(snippetContainerRef);++ const showHitSnippet = () =>+ !props.hideContentHits && hasSearchContentHits(props.entity);++ const showContentHits = () => showHitSnippet();++ const layoutProps = () => ({+ entity: props.entity,+ checked: props.checked,+ hideCheckbox: props.hideCheckbox,+ onChecked: props.onChecked,+ unread: unread(),+ isShared: isShared(),+ hasNotifications: hasNotifications(),+ showHitSnippet: showHitSnippet(),+ streamState: streamState(),+ setSnippetContainerRef,+ chars: chars(),+ onProjectClick: props.onProjectClick,+ });++ const draggable = createEntityDraggable({+ entity: props.entity,+ splitId: useSplitPanel()?.handle?.id,+ });++ const isWide = useListLayout()?.isWide ?? (() => true);++ return (+ <Entity.Root+ id={props.rowId}+ role={props.rowId ? 'row' : undefined}+ aria-selected={props.rowId ? props.checked : undefined}+ tabIndex={props.rowId ? -1 : undefined}+ entity={props.entity}+ onClick={(e) => {+ if (e.metaKey && props.onChecked) {+ props.onChecked(!props.checked, e.shiftKey);+ return;+ }+ props.onClick?.(e);+ }}+ ref={mergeRefs(props.ref, draggable)}+ class={cn(+ 'soup-list-entity @container/entity w-[calc(100%-0.5rem)] mr-1 relative group/narrow flex flex-col py-0.5 rounded-lg',+ {+ 'min-h-10 mx-1': !isMobile(),+ 'bg-list-selected': props.checked,+ 'bg-list-selected-highlighted':+ props.checked && props.highlighted && !isTouchDevice(),+ 'bg-list-highlighted':+ props.highlighted && !props.checked && !isTouchDevice(),+ 'hover:bg-list-hover':+ !props.highlighted && !props.checked && !isTouchDevice(),+ }+ )}+ onMouseMove={props.onMouseMove}+ >+ <Switch>+ <Match when={isWide()}>+ <MaybeEntityRow+ entityId={props.entity.id}+ config={props.entityRowConfig}+ >+ <TaskGridLayout {...layoutProps()} />+ </MaybeEntityRow>+ </Match>+ <Match when={true}>+ <MaybeEntityRow+ entityId={props.entity.id}+ config={props.entityRowConfig}+ >+ <NarrowLayout {...layoutProps()} />+ </MaybeEntityRow>+ </Match>+ </Switch>++ <Show when={showContentHits()}>+ <div class="flex gap-2 w-full h-full items-center text-sm px-2 pb-1 -mt-2 min-w-0">+ <div+ class={cn('min-w-0 flex-1 overflow-hidden ml-4 @lg/entity:ml-6')}+ >+ <Entity.Search.ContentHits+ entity={props.entity}+ onClick={props.onContentHitClick}+ visibleCount={0}+ />+ </div>+ </div>+ </Show>+ </Entity.Root>+ );+}diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskListHeader.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskListHeader.tsxnew file mode 100644index 0000000000..a36a284ce5--- /dev/null+++ b/apps/web/src/features/tasks-view/components/task-list/TaskListHeader.tsx@@ -0,0 +1,94 @@+import ArrowDownIcon from '@phosphor/arrow-down.svg';+import { cn } from '@ui';+import { Show } from 'solid-js';+import { useTasksView } from '../../tasks-view-context';+import type { TaskSortId } from '../../types';+import {+ TASK_GRID_TEMPLATE_AREAS_WIDE,+ TASK_GRID_TEMPLATE_COLUMNS_WIDE,+} from './task-grid-template';++function SortableHeader(props: {+ label: string;+ area: string;+ sortId?: TaskSortId;+ align?: 'start' | 'end';+ class?: string;+}) {+ const { state, setPrimarySort } = useTasksView();+ const active = () => state.sort[0]?.id === props.sortId;+ const reversed = () => active() && state.sort[0]?.reversed === true;+ const alignment = () => {+ if (props.align === 'end') return 'justify-end';+ return 'justify-start';+ };++ return (+ <div+ role="columnheader"+ class={cn('flex min-w-0 items-center', alignment(), props.class)}+ style={{ 'grid-area': props.area }}+ >+ <Show+ when={props.sortId}+ fallback={<span class="truncate">{props.label}</span>}+ >+ {(sortId) => (+ <button+ type="button"+ data-blocks-navigation+ class={cn(+ 'flex h-full min-w-0 items-center gap-1 text-ink-extra-muted hover:text-ink',+ active() && 'text-ink'+ )}+ onClick={() => setPrimarySort(sortId())}+ >+ <span class="truncate">{props.label}</span>+ <ArrowDownIcon+ class={cn(+ 'size-3 shrink-0 transition-transform',+ reversed() && 'rotate-180'+ )}+ />+ </button>+ )}+ </Show>+ </div>+ );+}++export function TaskListHeader() {+ return (+ <div+ role="row"+ class="task-grid-row grid h-10 w-full shrink-0 items-center gap-2 bg-surface px-3 text-xs font-medium text-ink-extra-muted"+ style={{+ 'grid-template-columns': TASK_GRID_TEMPLATE_COLUMNS_WIDE,+ 'grid-template-areas': TASK_GRID_TEMPLATE_AREAS_WIDE,+ }}+ >+ <span role="columnheader" style={{ 'grid-area': 'indicator' }} />+ <span+ role="columnheader"+ class="truncate"+ style={{ 'grid-area': 'content' }}+ >+ Task+ </span>+ <SortableHeader label="Status" area="status" />+ <SortableHeader label="Priority" area="priority" />+ <SortableHeader label="Assignees" area="assignees" />+ <SortableHeader+ label="Created By"+ area="createdBy"+ class="@max-[1220px]/u-list:hidden"+ />+ <SortableHeader+ label="Updated"+ area="timestamp"+ sortId="updated_at"+ align="end"+ />+ </div>+ );+}diff --git a/apps/web/src/features/tasks-view/components/task-list/task-grid-template.ts b/apps/web/src/features/tasks-view/components/task-list/task-grid-template.tsnew file mode 100644index 0000000000..eedc2300ff--- /dev/null+++ b/apps/web/src/features/tasks-view/components/task-list/task-grid-template.ts@@ -0,0 +1,60 @@+import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import { DataType } from '@service-storage/generated/schemas/dataType';+import { EntityType } from '@service-storage/generated/schemas/entityType';++export const TASK_GRID_COLUMNS = [+ {+ id: 'status',+ label: 'Status',+ defId: SYSTEM_PROPERTY_IDS.STATUS,+ dataType: DataType.SELECT_STRING,+ isMultiSelect: false,+ specificEntityType: null,+ sortKey: 'status',+ width: 'var(--task-col-status, 7rem)',+ },+ {+ id: 'priority',+ label: 'Priority',+ defId: SYSTEM_PROPERTY_IDS.PRIORITY,+ dataType: DataType.SELECT_STRING,+ isMultiSelect: false,+ specificEntityType: null,+ sortKey: 'priority',+ width: 'var(--task-col-priority, 7rem)',+ },+ {+ id: 'assignees',+ label: 'Assignees',+ defId: SYSTEM_PROPERTY_IDS.ASSIGNEES,+ dataType: DataType.ENTITY,+ isMultiSelect: true,+ specificEntityType: EntityType.USER,+ width: 'var(--task-col-assignees, 7rem)',+ },+] as const;++/** Width for the "Created By" column - only shown on wide containers */+const CREATED_BY_COLUMN_WIDTH = 'var(--task-col-created-by, 7rem)';++export type TaskGridColumn = (typeof TASK_GRID_COLUMNS)[number];++/** Grid template for wide containers (includes Created By column) */+export const TASK_GRID_TEMPLATE_COLUMNS_WIDE = `1rem minmax(0, 100%) ${TASK_GRID_COLUMNS.map(+ (c) => c.width+).join(' ')} ${CREATED_BY_COLUMN_WIDTH} var(--task-col-timestamp, 5rem)`;++/** Wide template without the leading indicator (checkbox) column. */+export const TASK_GRID_TEMPLATE_COLUMNS_WIDE_NO_INDICATOR = `minmax(0, 100%) ${TASK_GRID_COLUMNS.map(+ (c) => c.width+).join(' ')} ${CREATED_BY_COLUMN_WIDTH} var(--task-col-timestamp, 5rem)`;++/** Grid template areas for wide containers (includes Created By column) */+export const TASK_GRID_TEMPLATE_AREAS_WIDE = `"indicator content ${TASK_GRID_COLUMNS.map(+ (c) => c.id+).join(' ')} createdBy timestamp"`;++/** Wide template areas without the leading indicator (checkbox) column. */+export const TASK_GRID_TEMPLATE_AREAS_WIDE_NO_INDICATOR = `"content ${TASK_GRID_COLUMNS.map(+ (c) => c.id+).join(' ')} createdBy timestamp"`;diff --git a/apps/web/src/features/tasks-view/components/task-list/task-list.css b/apps/web/src/features/tasks-view/components/task-list/task-list.cssnew file mode 100644index 0000000000..5739b2bc22--- /dev/null+++ b/apps/web/src/features/tasks-view/components/task-list/task-list.css@@ -0,0 +1,25 @@+.task-grid-row {+ --task-col-status: 7.25rem;+ --task-col-priority: 7rem;+ --task-col-assignees: 9rem;+ --task-col-created-by: 7rem;+ --task-col-timestamp: 5rem;+}++/* Medium containers: hide Created By column */+@container u-list (max-width: 1220px) {+ .task-grid-row {+ --task-col-created-by: 0rem;+ }+}++/* Narrow containers: collapse property columns to icons */+@container u-list (max-width: 840px) {+ .task-grid-row {+ --task-col-status: 2rem;+ --task-col-priority: 2rem;+ --task-col-assignees: 3rem;+ --task-col-created-by: 0rem;+ --task-col-timestamp: 5rem;+ }+}diff --git a/apps/web/src/features/tasks-view/constants.ts b/apps/web/src/features/tasks-view/constants.tsnew file mode 100644index 0000000000..a009785c85--- /dev/null+++ b/apps/web/src/features/tasks-view/constants.ts@@ -0,0 +1,75 @@+import type { SortDefinition } from '@app/features/soup';+import { compareDateDesc } from '@core/util/date';+import type { TaskEntityWithProperties } from '@entity';+import type { TaskGroupBy, TaskSortId, TaskTab } from './types';++export type TaskTabItem = {+ id: TaskTab;+ label: string;+};++export const PERSONAL_TASK_TABS: TaskTabItem[] = [+ { id: 'my-tasks', label: 'My tasks' },+ { id: 'created-by-me', label: 'Created by me' },+];++export const TEAM_TASK_TABS: TaskTabItem[] = [+ { id: 'team-tasks', label: 'Team tasks' },+];++export const TASK_DEFAULT_GROUP_BY: Record<TaskTab, TaskGroupBy> = {+ 'my-tasks': 'priority',+ 'created-by-me': 'status',+ 'team-tasks': 'priority',+};++export const TASK_GROUP_OPTIONS: {+ id: TaskGroupBy;+ label: string;+}[] = [+ { id: 'none', label: 'None' },+ { id: 'status', label: 'Status' },+ { id: 'priority', label: 'Priority' },+ { id: 'assignee', label: 'Assignee' },+ { id: 'project', label: 'Project' },+ { id: 'date', label: 'Date' },+];++export const TASK_SORT_DEFINITIONS: SortDefinition<+ TaskEntityWithProperties,+ TaskSortId+>[] = [+ {+ id: 'updated_at',+ compare: (left, right) =>+ compareDateDesc(+ left.sortTs ?? left.updatedAt,+ right.sortTs ?? right.updatedAt+ ),+ },+ {+ id: 'created_at',+ compare: (left, right) =>+ compareDateDesc(+ left.sortTs ?? left.createdAt,+ right.sortTs ?? right.createdAt+ ),+ },+ {+ id: 'viewed_at',+ compare: (left, right) =>+ compareDateDesc(+ left.sortTs ?? left.viewedAt,+ right.sortTs ?? right.viewedAt+ ),+ },+];++export const TASK_SORT_OPTIONS: {+ id: TaskSortId;+ label: string;+}[] = [+ { id: 'viewed_at', label: 'Viewed' },+ { id: 'updated_at', label: 'Updated' },+ { id: 'created_at', label: 'Created' },+];diff --git a/apps/web/src/features/tasks-view/filters/task-facets.ts b/apps/web/src/features/tasks-view/filters/task-facets.tsnew file mode 100644index 0000000000..b8bbfe404d--- /dev/null+++ b/apps/web/src/features/tasks-view/filters/task-facets.ts@@ -0,0 +1,174 @@+import {+ clause,+ type Facet,+ type FacetClause,+ type FacetOption,+ type FacetSelection,+ resolveFacetOption,+} from '@app/features/soup';+import type { TaskEntityWithProperties } from '@entity/types/entity';+import {+ getTaskAssigneeIds,+ getTaskPriorityOptionId,+ getTaskStatusOptionId,+} from '@entity/utils/task-properties';+import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';++export type TaskFacetContext = {+ tagPropertyDefinitionByOptionId: ReadonlyMap<string, string>;+};++export const EMPTY_TASK_FACET_CONTEXT: TaskFacetContext = {+ tagPropertyDefinitionByOptionId: new Map(),+};++export type TaskFacetOption = FacetOption<+ TaskEntityWithProperties,+ TaskFacetContext+> & {+ label?: string;+ propertyDefinitionId?: string;+ propertyOptionId?: string;+ propertyEntityId?: string;+};++type TaskPropertyFacetOption = TaskFacetOption & {+ label: string;+ propertyDefinitionId: string;+ propertyOptionId: string;+};++const propertyClause = (+ propertyDefinitionId: string,+ type: 'select' | 'entity',+ value: string+): FacetClause => ({+ propf: clause.eq('properties', {+ propertyId: propertyDefinitionId,+ type,+ value,+ }),+});++const statusOption = (+ id: string,+ label: string,+ propertyOptionId: string+): TaskPropertyFacetOption => ({+ id,+ label,+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.STATUS,+ propertyOptionId,+ clause: propertyClause(+ SYSTEM_PROPERTY_IDS.STATUS,+ 'select',+ propertyOptionId+ ),+ predicate: (task) => getTaskStatusOptionId(task) === propertyOptionId,+});++const priorityOption = (+ id: string,+ label: string,+ propertyOptionId: string+): TaskPropertyFacetOption => ({+ id,+ label,+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.PRIORITY,+ propertyOptionId,+ clause: propertyClause(+ SYSTEM_PROPERTY_IDS.PRIORITY,+ 'select',+ propertyOptionId+ ),+ predicate: (task) => getTaskPriorityOptionId(task) === propertyOptionId,+});++const assigneeOption = (id: string): TaskFacetOption => ({+ id,+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.ASSIGNEES,+ propertyEntityId: id,+ clause: propertyClause(SYSTEM_PROPERTY_IDS.ASSIGNEES, 'entity', id),+ predicate: (task) => getTaskAssigneeIds(task).includes(id),+});++const creatorOption = (id: string): TaskFacetOption => ({+ id,+ clause: { df: clause.eq('documentOwnerId', id) },+ predicate: (task) => task.ownerId === id,+});++const taskHasSelectOption = (+ task: TaskEntityWithProperties,+ optionId: string+) =>+ task.properties?.some(+ (property) =>+ property.value?.type === 'SelectOption' &&+ property.value.value.includes(optionId)+ ) ?? false;++const tagOption = (+ id: string,+ context: TaskFacetContext+): TaskFacetOption | undefined => {+ const propertyDefinitionId = context.tagPropertyDefinitionByOptionId.get(id);+ if (!propertyDefinitionId) return undefined;++ return {+ id,+ propertyDefinitionId,+ propertyOptionId: id,+ clause: propertyClause(propertyDefinitionId, 'select', id),+ predicate: (task) => taskHasSelectOption(task, id),+ };+};++export const TASK_STATUS_OPTIONS = [+ statusOption(+ 'not-started',+ 'Not started',+ PROPERTY_OPTION_IDS.STATUS.NOT_STARTED+ ),+ statusOption(+ 'in-progress',+ 'In progress',+ PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS+ ),+ statusOption('in-review', 'In review', PROPERTY_OPTION_IDS.STATUS.IN_REVIEW),+ statusOption('completed', 'Completed', PROPERTY_OPTION_IDS.STATUS.COMPLETED),+ statusOption('canceled', 'Canceled', PROPERTY_OPTION_IDS.STATUS.CANCELED),+];++export const TASK_PRIORITY_OPTIONS = [+ priorityOption('urgent', 'Urgent', PROPERTY_OPTION_IDS.PRIORITY.URGENT),+ priorityOption('high', 'High', PROPERTY_OPTION_IDS.PRIORITY.HIGH),+ priorityOption('medium', 'Medium', PROPERTY_OPTION_IDS.PRIORITY.MEDIUM),+ priorityOption('low', 'Low', PROPERTY_OPTION_IDS.PRIORITY.LOW),+];++export const TASK_FACETS: Facet<+ TaskEntityWithProperties,+ TaskFacetContext,+ TaskFacetOption+>[] = [+ { id: 'status', mode: 'or', options: TASK_STATUS_OPTIONS },+ { id: 'priority', mode: 'or', options: TASK_PRIORITY_OPTIONS },+ { id: 'assignees', mode: 'or', options: assigneeOption },+ { id: 'created-by', mode: 'or', options: creatorOption },+ { id: 'tags', mode: 'or', options: tagOption },+];++export const DEFAULT_TASK_FACET_SELECTION: FacetSelection = {+ status: ['in-progress', 'in-review', 'not-started'],+};++export const getTaskFacetOption = (+ facetId: string,+ optionId: string,+ context: TaskFacetContext+): TaskFacetOption | undefined => {+ const facet = TASK_FACETS.find((candidate) => candidate.id === facetId);+ if (!facet) return undefined;+ return resolveFacetOption(facet, optionId, context);+};diff --git a/apps/web/src/features/tasks-view/filters/task-predicates.ts b/apps/web/src/features/tasks-view/filters/task-predicates.tsnew file mode 100644index 0000000000..ed66d540be--- /dev/null+++ b/apps/web/src/features/tasks-view/filters/task-predicates.ts@@ -0,0 +1,46 @@+import { testFacets } from '@app/features/soup';+import { getTaskAssigneeIds, type TaskEntityWithProperties } from '@entity';+import type { TaskTab } from '../types';+import {+ EMPTY_TASK_FACET_CONTEXT,+ TASK_FACETS,+ type TaskFacetContext,+} from './task-facets';++export type TaskViewContext = {+ tab: TaskTab;+ userId: string | undefined;+ facets: Record<string, string[]>;+ facetContext?: TaskFacetContext;+};++export function taskMatchesTab(+ task: TaskEntityWithProperties,+ tab: TaskTab,+ userId: string | undefined+) {+ switch (tab) {+ case 'my-tasks':+ if (!userId) return false;+ return getTaskAssigneeIds(task).includes(userId);+ case 'created-by-me':+ if (!userId) return false;+ return task.ownerId === userId;+ case 'team-tasks':+ return true;+ }+}++export function taskMatchesView(+ task: TaskEntityWithProperties,+ context: TaskViewContext+) {+ if (!taskMatchesTab(task, context.tab, context.userId)) return false;++ return testFacets(+ context.facets,+ TASK_FACETS,+ task,+ context.facetContext ?? EMPTY_TASK_FACET_CONTEXT+ );+}diff --git a/apps/web/src/features/tasks-view/persistence.ts b/apps/web/src/features/tasks-view/persistence.tsnew file mode 100644index 0000000000..67a2718ed3--- /dev/null+++ b/apps/web/src/features/tasks-view/persistence.ts@@ -0,0 +1,233 @@+import { normalizeFacetSelection } from '@app/features/soup';+import type {+ MakePersistedStateOptions,+ PersistenceStorage,+} from '@app/lib/persistence';+import {+ createEntryPersistenceStorage,+ type EntryPersistenceHandle,+} from '@components/app/split-layout/entry-persistence';+import { createUserScopedStorage } from '@core/util/userScopedStorage';+import type { Accessor } from 'solid-js';+import { z } from 'zod';+import { DEFAULT_TASK_FACET_SELECTION } from './filters/task-facets';+import type { TasksViewState } from './types';++export const TASKS_ENTRY_STATE_KEY = 'tasks.view';+export const TASKS_LIST_ENTRY_STATE_KEY = 'tasks.listState';++const taskTabSchema = z+ .enum(['my-tasks', 'created-by-me', 'team-tasks'])+ .catch('my-tasks');++const taskGroupBySchema = z.enum([+ 'none',+ 'status',+ 'priority',+ 'assignee',+ 'project',+ 'date',+]);++const taskSortSchema = z.array(+ z.object({+ id: z.enum(['updated_at', 'created_at', 'viewed_at']),+ reversed: z.boolean().optional(),+ })+);++const taskFacetsSchema = z.record(z.string(), z.array(z.string()));++const tasksEntryStateSchemaWithDefaults = z.object({+ version: z.literal(1).default(1),+ tab: taskTabSchema.default('my-tasks'),+ search: z.string().default(''),+ groupBy: taskGroupBySchema.default('priority'),+ sort: taskSortSchema.default([{ id: 'updated_at' }]),+ facets: taskFacetsSchema.default(+ normalizeFacetSelection(DEFAULT_TASK_FACET_SELECTION)+ ),+ collapsedGroupIds: z.array(z.string()).default([]),+});++type TasksEntryState = z.infer<typeof tasksEntryStateSchemaWithDefaults>;++const DEFAULT_TASKS_ENTRY_STATE: TasksEntryState =+ tasksEntryStateSchemaWithDefaults.parse({});+const tasksEntryStateSchema = tasksEntryStateSchemaWithDefaults.catch(+ DEFAULT_TASKS_ENTRY_STATE+);++const tasksPreferencesSchemaWithDefaults = z.object({+ version: z.literal(1).default(1),+ collapsedSidebarSectionIds: z.array(z.string()).default([]),+});++type TasksPreferences = z.infer<typeof tasksPreferencesSchemaWithDefaults>;++const DEFAULT_TASKS_PREFERENCES: TasksPreferences =+ tasksPreferencesSchemaWithDefaults.parse({});+const tasksPreferencesSchema = tasksPreferencesSchemaWithDefaults.catch(+ DEFAULT_TASKS_PREFERENCES+);++const tasksListStateSchemaWithDefaults = z.object({+ version: z.literal(1).default(1),+ focusKey: z.string().optional(),+ scrollOffset: z.number().finite().default(0),+});++type TasksListEntryState = z.infer<typeof tasksListStateSchemaWithDefaults>;++const DEFAULT_TASKS_LIST_ENTRY_STATE: TasksListEntryState =+ tasksListStateSchemaWithDefaults.parse({});+const tasksListStateSchema = tasksListStateSchemaWithDefaults.catch(+ DEFAULT_TASKS_LIST_ENTRY_STATE+);++export type TasksListStateSnapshot = {+ focusKey: TasksListEntryState['focusKey'];+ scrollOffset: TasksListEntryState['scrollOffset'];+};++export const DEFAULT_TASKS_LIST_STATE: TasksListStateSnapshot = {+ focusKey: DEFAULT_TASKS_LIST_ENTRY_STATE.focusKey,+ scrollOffset: DEFAULT_TASKS_LIST_ENTRY_STATE.scrollOffset,+};++function selectEntryState(state: TasksViewState): TasksEntryState {+ return {+ version: 1,+ tab: state.tab,+ search: state.search,+ groupBy: state.groupBy,+ sort: state.sort.map((item) => ({ ...item })),+ facets: normalizeFacetSelection(state.facets),+ collapsedGroupIds: [...state.collapsedGroupIds],+ };+}++function createTasksEntryStorage(options: {+ handle: EntryPersistenceHandle;+ restore: boolean;+}): PersistenceStorage<TasksViewState> {+ return createEntryPersistenceStorage({+ handle: options.handle,+ key: TASKS_ENTRY_STATE_KEY,+ restore: (current, stored) => {+ if (!options.restore) return undefined;++ const restored = tasksEntryStateSchema.parse(stored);+ return {+ ...current,+ tab: restored.tab,+ search: restored.search,+ groupBy: restored.groupBy,+ sort: restored.sort.map((item) => ({ ...item })),+ facets: normalizeFacetSelection(restored.facets),+ collapsedGroupIds: [...restored.collapsedGroupIds],+ };+ },+ select: selectEntryState,+ });+}++export function createTasksListEntryStorage(+ handle: EntryPersistenceHandle+): PersistenceStorage<TasksListStateSnapshot> {+ return createEntryPersistenceStorage({+ handle,+ key: TASKS_LIST_ENTRY_STATE_KEY,+ restore: (current, stored) => {+ const restored = tasksListStateSchema.parse(stored);++ return {+ ...current,+ focusKey: restored.focusKey,+ scrollOffset: restored.scrollOffset,+ };+ },+ select: (state): TasksListEntryState => ({+ version: 1,+ ...(state.focusKey === undefined ? {} : { focusKey: state.focusKey }),+ scrollOffset: state.scrollOffset,+ }),+ });+}++const preferencesStorage = createUserScopedStorage(+ 'macro:tasks:preferences:v1'+);++function createTasksPreferencesStorage(options: {+ userId: Accessor<string | undefined>;+ restore: boolean;+}): PersistenceStorage<TasksViewState> {+ let previous: string | undefined;++ const serialize = (state: TasksViewState): string =>+ JSON.stringify({+ version: 1,+ collapsedSidebarSectionIds: [...state.collapsedSidebarSectionIds],+ } satisfies TasksPreferences);++ return {+ restore: (current) => {+ if (!options.restore) return undefined;++ const userId = options.userId();+ if (!userId) return undefined;++ const raw = preferencesStorage.read(userId);+ if (raw === null) return undefined;++ try {+ const parsed = tasksPreferencesSchema.parse(JSON.parse(raw));+ return {+ ...current,+ collapsedSidebarSectionIds: [...parsed.collapsedSidebarSectionIds],+ };+ } catch {+ return undefined;+ }+ },+ initialize: (current) => {+ previous = serialize(current);+ },+ write: (current) => {+ const userId = options.userId();+ if (!userId) return;++ const serialized = serialize(current);+ if (serialized === previous) return;++ previous = serialized;+ preferencesStorage.write(userId, serialized);+ },+ };+}++export type CreateTasksViewPersistenceOptions = {+ handle: EntryPersistenceHandle;+ userId: Accessor<string | undefined>;+ restoreEntryState?: boolean;+ restorePreferences?: boolean;+};++/** Persists Tasks navigation and user-level sidebar preferences. */+export function createTasksViewPersistence(+ options: CreateTasksViewPersistenceOptions+): MakePersistedStateOptions<TasksViewState> {+ return {+ storages: [+ createTasksPreferencesStorage({+ userId: options.userId,+ restore: options.restorePreferences ?? true,+ }),+ createTasksEntryStorage({+ handle: options.handle,+ restore: options.restoreEntryState ?? true,+ }),+ ],+ };+}diff --git a/apps/web/src/features/tasks-view/queries/task-query.ts b/apps/web/src/features/tasks-view/queries/task-query.tsnew file mode 100644index 0000000000..cd71c68328--- /dev/null+++ b/apps/web/src/features/tasks-view/queries/task-query.ts@@ -0,0 +1,151 @@+import {+ type BackendAstNode,+ combine,+ compileFacets,+ type FacetSelection,+ literal,+ NIL_UUID,+ type SortSelection,+} from '@app/features/soup';+import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import type { GroupByField } from '@queries/soup/grouped/types';+import type { SoupAstBody, SoupAstItemsQueryArgs } from '@queries/soup/items';+import {+ EMPTY_TASK_FACET_CONTEXT,+ TASK_FACETS,+ type TaskFacetContext,+} from '../filters/task-facets';+import type { TaskGroupBy, TaskSortId, TaskTab } from '../types';++type TaskAst = BackendAstNode;++const entityPropertyLiteral = (+ definitionId: string,+ entityId: string+): TaskAst => ({+ l: { pd: definitionId, v: { er: entityId } },+});++const documentScope = (tab: TaskTab, userId: string | undefined): TaskAst => {+ const task = literal('dst', 'task');+ if ((tab === 'my-tasks' || tab === 'created-by-me') && !userId) {+ return literal('id', NIL_UUID);+ }+ if (tab === 'created-by-me') {+ return { '&': [task, literal('o', userId)] };+ }++ return task;+};++const propertyScope = (+ tab: TaskTab,+ userId: string | undefined,+ compiledFacets: TaskAst | undefined+): TaskAst | undefined => {+ const groups: TaskAst[] = [];+ if (compiledFacets) groups.push(compiledFacets);++ if (tab === 'my-tasks' && userId) {+ groups.push(entityPropertyLiteral(SYSTEM_PROPERTY_IDS.ASSIGNEES, userId));+ }++ return combine('&', groups);+};++const nonTaskTargets = {+ calf: literal('id', NIL_UUID),+ callf: literal('CallId', NIL_UUID),+ ccf: literal('id', NIL_UUID),+ cf: literal('cid', NIL_UUID),+ chanf: literal('ChannelId', NIL_UUID),+ cthf: literal('ThreadId', NIL_UUID),+ ef: literal('ThreadId', NIL_UUID),+ fef: literal('id', NIL_UUID),+ pf: literal('pid', NIL_UUID),+};++export const taskGroupByField = (+ groupBy: TaskGroupBy+): GroupByField | undefined => {+ switch (groupBy) {+ case 'none':+ return undefined;+ case 'date':+ return { type: 'date' };+ case 'project':+ return { type: 'project' };+ case 'status':+ return {+ type: 'property',+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.STATUS,+ };+ case 'priority':+ return {+ type: 'property',+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.PRIORITY,+ };+ case 'assignee':+ return {+ type: 'property',+ propertyDefinitionId: SYSTEM_PROPERTY_IDS.ASSIGNEES,+ };+ }+};++export type BuildTaskQueryOptions = {+ tab: TaskTab;+ userId: string | undefined;+ facets: FacetSelection;+ facetContext?: TaskFacetContext;+ groupBy: TaskGroupBy;+ sort: SortSelection<TaskSortId>[];+};++/** Builds the concrete Soup AST used only by the production Tasks view. */+export function buildTaskQuery(+ options: BuildTaskQueryOptions+): SoupAstItemsQueryArgs {+ const primarySort = options.sort[0];+ const serverSort = primarySort?.id ?? 'updated_at';++ let sortDirection: 'asc' | 'desc' = 'desc';++ if (primarySort?.reversed) sortDirection = 'asc';++ const compiledFacets = compileFacets(+ options.facets,+ TASK_FACETS,+ options.facetContext ?? EMPTY_TASK_FACET_CONTEXT+ );++ const properties = propertyScope(+ options.tab,+ options.userId,+ compiledFacets.propf+ );++ const taskDocuments = documentScope(options.tab, options.userId);++ const documents = compiledFacets.df+ ? { '&': [taskDocuments, compiledFacets.df] }+ : taskDocuments;++ const body: SoupAstBody = {+ ...nonTaskTargets,+ df: documents,+ };++ if (properties) body.propf = properties;++ return {+ params: {+ expand: true,+ limit: 100,+ sort_method: serverSort,+ sort_direction: sortDirection,+ },+ body,+ groupBy: taskGroupByField(options.groupBy),+ };+}diff --git a/apps/web/src/features/tasks-view/queries/task-search.ts b/apps/web/src/features/tasks-view/queries/task-search.tsnew file mode 100644index 0000000000..4fc1acba48--- /dev/null+++ b/apps/web/src/features/tasks-view/queries/task-search.ts@@ -0,0 +1,126 @@+import {+ type FacetSelection,+ NIL_UUID,+ type SoupSearchMatchType,+} from '@app/features/soup';+import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import type { SearchSoupQueryArgs } from '@queries/soup/search';+import type {+ EntityFilters,+ PropertyFilter as SearchPropertyFilter,+} from '@service-search/generated/models';+import {+ EMPTY_TASK_FACET_CONTEXT,+ getTaskFacetOption,+ type TaskFacetContext,+} from '../filters/task-facets';+import type { TaskTab } from '../types';++const nonTaskFilters: EntityFilters = {+ calendar_event_filters: { calendar_event_ids: [NIL_UUID] },+ call_filters: { call_ids: [NIL_UUID] },+ channel_filters: { channel_ids: [NIL_UUID] },+ channel_thread_filters: { thread_ids: [NIL_UUID] },+ chat_filters: { chat_ids: [NIL_UUID] },+ crm_company_filters: { company_ids: [NIL_UUID] },+ email_filters: { email_thread_ids: [NIL_UUID] },+ foreign_entity_filters: { ids: [NIL_UUID] },+ project_filters: { project_ids: [NIL_UUID] },+ reminder_filters: { ids: [NIL_UUID] },+};++const selectedCreators = (+ selection: FacetSelection,+ tab: TaskTab,+ userId: string | undefined+): string[] | undefined => {+ const selected = [...new Set(selection['created-by'] ?? [])];+ if (tab !== 'created-by-me') {+ return selected.length > 0 ? selected : undefined;+ }+ if (!userId) return [NIL_UUID];+ if (selected.length > 0 && !selected.includes(userId)) return [NIL_UUID];+ return [userId];+};++const selectedPropertyFilters = (+ selection: FacetSelection,+ context: TaskFacetContext+): SearchPropertyFilter[] =>+ Object.entries(selection).flatMap(([facetId, optionIds]) => {+ if (facetId === 'created-by' || facetId === 'tags') return [];++ const resolved = optionIds.flatMap((optionId) => {+ const option = getTaskFacetOption(facetId, optionId, context);+ return option ? [option] : [];+ });+ const propertyDefinitionId = resolved[0]?.propertyDefinitionId;+ if (!propertyDefinitionId) return [];++ const optionIdsForProperty = resolved.flatMap((option) =>+ option.propertyOptionId ? [option.propertyOptionId] : []+ );+ const entityIdsForProperty = resolved.flatMap((option) =>+ option.propertyEntityId ? [option.propertyEntityId] : []+ );++ return [+ {+ property_definition_id: propertyDefinitionId,+ entity_type: 'TASK',+ ...(optionIdsForProperty.length > 0+ ? { option_ids: optionIdsForProperty }+ : {}),+ ...(entityIdsForProperty.length > 0+ ? { entity_ids: entityIdsForProperty }+ : {}),+ },+ ];+ });++export function buildTaskSearchRequest(options: {+ query: string;+ matchType: SoupSearchMatchType;+ tab: TaskTab;+ userId: string | undefined;+ facets: FacetSelection;+ facetContext?: TaskFacetContext;+}): SearchSoupQueryArgs {+ const propertyFilters = selectedPropertyFilters(+ options.facets,+ options.facetContext ?? EMPTY_TASK_FACET_CONTEXT+ );++ if (options.tab === 'my-tasks') {+ propertyFilters.push({+ property_definition_id: SYSTEM_PROPERTY_IDS.ASSIGNEES,+ entity_type: 'TASK',+ entity_ids: [options.userId ?? NIL_UUID],+ });+ }++ const owners = selectedCreators(options.facets, options.tab, options.userId);+ const tagOptionIds = [...new Set(options.facets.tags ?? [])];++ return {+ params: { cursor: null, page_size: 100 },+ body: {+ query: options.query,+ match_type: options.matchType,+ search_on: 'name_content',+ filters: {+ ...nonTaskFilters,+ document_filters: {+ sub_types: ['task'],+ ...(owners ? { owners } : {}),+ },+ ...(propertyFilters.length > 0+ ? { property_filters: propertyFilters }+ : {}),+ ...(tagOptionIds.length > 0+ ? { tag_option_ids: tagOptionIds, tag_filter_mode: 'any' }+ : {}),+ },+ },+ };+}diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.tsnew file mode 100644index 0000000000..906d932b6f--- /dev/null+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.ts@@ -0,0 +1,314 @@+import type { ListDataSource } from '@app/components/list';+import {+ buildFlatSoupRows,+ buildGroupedSoupRows,+ createSearchState,+ deduplicateSoupEntities,+ isSoupRowVisible,+ type SoupGroup,+ type SoupRow,+ sortItems,+ useSearchContext,+} from '@app/features/soup';+import {+ type EntityData,+ isTaskEntity,+ type TaskEntityWithProperties,+} from '@entity';+import { createGroupedSoupQueries } from '@queries/soup/grouped/create-grouped-soup-queries';+import { useSoupAstItemsQuery } from '@queries/soup/items';+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';+import { type Accessor, createMemo } from 'solid-js';+import { TASK_SORT_DEFINITIONS } from '../constants';+import type { TaskFacetContext } from '../filters/task-facets';+import {+ type TaskViewContext,+ taskMatchesView,+} from '../filters/task-predicates';+import type { TasksViewState } from '../types';+import { buildTaskQuery } from './task-query';+import { buildTaskSearchRequest } from './task-search';++export type TasksDataSourceInput = Pick<+ TasksViewState,+ 'tab' | 'search' | 'groupBy' | 'sort' | 'facets'+>;++export type UseTasksDataSourceOptions = {+ userId: Accessor<string | undefined>;+ tagSets: Accessor<readonly TagSetResponse[]>;+ isGroupExpanded: (groupId: string) => boolean;+};++export type TasksDataSourceItem = SoupRow<TaskEntityWithProperties>;++export type TasksDataSource = ListDataSource<TasksDataSourceItem> & {+ loadMoreGroup: (groupId: string) => Promise<void>;+};++type TaskGroupContinuationReader = {+ entities: (groupId: string) => TaskEntityWithProperties[];+ hasMore: (groupId: string) => boolean;+ isLoading: (groupId: string) => boolean;+ loadMore: (groupId: string) => Promise<void>;+};++/** Query, service search, and row assembly owned by the production Tasks view. */+export function useTasksDataSource(+ state: TasksDataSourceInput,+ options: UseTasksDataSourceOptions+): TasksDataSource {+ const facetContext = createMemo((): TaskFacetContext => {+ const tagPropertyDefinitionByOptionId = new Map<string, string>();+ for (const set of options.tagSets()) {+ for (const option of set.options) {+ tagPropertyDefinitionByOptionId.set(+ option.id,+ option.propertyDefinitionId+ );+ }+ }+ return { tagPropertyDefinitionByOptionId };+ });++ const facetOptionsReady = () =>+ (state.facets.tags ?? []).every((id) =>+ facetContext().tagPropertyDefinitionByOptionId.has(id)+ );++ const queryArgs = () =>+ buildTaskQuery({+ tab: state.tab,+ userId: options.userId(),+ facets: state.facets,+ facetContext: facetContext(),+ groupBy: state.groupBy,+ sort: state.sort,+ });++ const query = useSoupAstItemsQuery(queryArgs, () => ({+ enabled: facetOptionsReady(),+ }));++ const viewContext = (): TaskViewContext => ({+ tab: state.tab,+ userId: options.userId(),+ facets: state.facets,+ facetContext: facetContext(),+ });++ const transformEntities = (entities: EntityData[]) => {+ const selected: TaskEntityWithProperties[] = [];+ const context = viewContext();+ for (const entity of entities) {+ if (!isTaskEntity(entity)) continue;+ if (!taskMatchesView(entity, context)) continue;++ selected.push(entity);+ }+ return selected;+ };++ const baseTasks = createMemo<TaskEntityWithProperties[]>((previous) => {+ if (query.isLoading) return previous;+ if (query.isPlaceholderData && previous.length > 0) return previous;++ return sortItems(+ transformEntities(query.data?.entities ?? []),+ state.sort,+ TASK_SORT_DEFINITIONS+ );+ }, []);++ const { entityPool } = useSearchContext();+ const localPool = createMemo(() => {+ if (!state.search.trim()) return [];+ const pool = entityPool();+ const matchingIds = new Set(+ transformEntities(pool.map((item) => item.data)).map(+ (entity) => entity.id+ )+ );+ return pool.filter((item) => matchingIds.has(item.data.id));+ });++ const search = createSearchState({+ text: () => state.search,+ localPool,+ enabled: facetOptionsReady,+ buildRequest: ({ query, matchType }) =>+ buildTaskSearchRequest({+ query,+ matchType,+ tab: state.tab,+ userId: options.userId(),+ facets: state.facets,+ facetContext: facetContext(),+ }),+ });++ const groupedQueries = createGroupedSoupQueries({+ initialPage: createMemo(() => {+ if (search.isSearching() || query.isLoading || query.isPlaceholderData) {+ return;+ }++ const groups = query.data?.groups;+ const items = query.data?.itemsById;+ if (!groups || !items) return;+ return { groups, items };+ }),+ groupByField: () => queryArgs().groupBy,+ soupParams: () => queryArgs().params,+ soupBody: () => queryArgs().body,+ transport: () => query.transport,+ queryOptions: () => ({+ enabled: !search.isSearching() && facetOptionsReady(),+ }),+ });++ const groupQueryFor = (groupKey: string) =>+ groupedQueries.map().get(groupKey);++ const continuations: TaskGroupContinuationReader = {+ entities: (groupKey) =>+ (groupQueryFor(groupKey)?.data()?.entities ?? []).flatMap((entity) =>+ isTaskEntity(entity) ? [entity] : []+ ),+ hasMore: (groupKey) => groupQueryFor(groupKey)?.hasNextPage() ?? false,+ isLoading: (groupKey) =>+ groupQueryFor(groupKey)?.isFetchingNextPage() ?? false,+ loadMore: async (groupKey) => {+ await groupQueryFor(groupKey)?.fetchNextPage();+ },+ };++ const tasks = createMemo<TaskEntityWithProperties[]>((previous) => {+ if (!search.isSearching()) return baseTasks();++ const results = transformEntities(search.data());+ if (+ results.length === 0 &&+ previous.length > 0 &&+ search.isLocalSearchSettling()+ ) {+ return previous;+ }+ return results;+ }, []);++ const rows = createMemo<SoupRow<TaskEntityWithProperties>[]>((previous) => {+ if (+ !search.isSearching() &&+ (query.isLoading || (query.isPlaceholderData && previous.length > 0))+ ) {+ return previous;+ }++ const groups = search.isSearching() ? undefined : query.data?.groups;+ const currentTasks = tasks();+ if (!groups || state.groupBy === 'none') {+ return buildFlatSoupRows(currentTasks);+ }++ const tasksById = new Map(currentTasks.map((task) => [task.id, task]));+ const taskGroups: SoupGroup<TaskEntityWithProperties>[] = [];++ for (const group of groups) {+ const initialTasks = group.itemIds.flatMap((id) => {+ const task = tasksById.get(id);+ return task ? [task] : [];+ });+ const continuationTasks = continuations+ .entities(group.key)+ .filter((task) => taskMatchesView(task, viewContext()));+ const entities = sortItems(+ deduplicateSoupEntities([...initialTasks, ...continuationTasks]),+ state.sort,+ TASK_SORT_DEFINITIONS+ );+ const taskGroup: SoupGroup<TaskEntityWithProperties> = {+ id: group.key,+ label: group.label,+ entities,+ count: group.totalCount,+ };++ if (continuations.hasMore(group.key)) {+ taskGroup.loadMore = {+ scopeId: `tasks:${group.key}`,+ isLoading: continuations.isLoading(group.key),+ };+ }++ taskGroups.push(taskGroup);+ }++ return buildGroupedSoupRows(taskGroups);+ }, []);++ const items = createMemo(() =>+ rows().filter((row) => isSoupRowVisible(row, options.isGroupExpanded))+ );++ const usesServiceSearch = search.usesServiceSearch;++ const isLoading = () => {+ if (!search.isSearching()) {+ return query.isLoading && rows().length === 0;+ }+ if (tasks().length > 0) return false;+ if (usesServiceSearch()) return search.isLoading();+ return query.isLoading;+ };++ const isFetching = () => {+ if (search.isSettling()) return true;+ if (usesServiceSearch()) return search.isFetching();+ return query.isFetching;+ };++ const error = () => {+ if (!usesServiceSearch()) return query.error ?? undefined;+ return search.error();+ };++ const hasMore = () => {+ if (usesServiceSearch()) return search.hasNextPage();+ return query.hasNextPage;+ };++ const isLoadingMore = () => {+ if (usesServiceSearch()) return search.isFetchingNextPage();+ return query.isFetchingNextPage;+ };++ const loadMore = async () => {+ if (usesServiceSearch()) {+ await search.fetchNextPage();+ return;+ }+ await query.fetchNextPage();+ };++ const refresh = async () => {+ if (usesServiceSearch()) {+ await search.refetch();+ return;+ }+ groupedQueries.resetToInitialPage();+ await query.refresh();+ };++ return {+ items,+ isLoading,+ isFetching,+ error,+ hasMore,+ isLoadingMore,+ loadMoreGroup: continuations.loadMore,+ loadMore,+ refresh,+ } satisfies TasksDataSource;+}diff --git a/apps/web/src/features/tasks-view/tasks-view-context.tsx b/apps/web/src/features/tasks-view/tasks-view-context.tsxnew file mode 100644index 0000000000..c1001c8d9a--- /dev/null+++ b/apps/web/src/features/tasks-view/tasks-view-context.tsx@@ -0,0 +1,101 @@+import { normalizeFacetSelection } from '@app/features/soup';+import { makePersistedState } from '@app/lib/persistence';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { createAssertedContextProvider } from '@core/context/createContext';+import { useUserId } from '@core/context/user';+import type { ContextProviderProps } from '@solid-primitives/context';+import {+ createStore,+ produce,+ reconcile,+ type SetStoreFunction,+ type Store,+} from 'solid-js/store';+import { TASK_DEFAULT_GROUP_BY } from './constants';+import { DEFAULT_TASK_FACET_SELECTION } from './filters/task-facets';+import { createTasksViewPersistence } from './persistence';+import type {+ TaskSortId,+ TasksViewState,+ TasksViewStateOptions,+ TaskTab,+} from './types';++type TasksViewProviderProps = ContextProviderProps & {+ initialState?: TasksViewStateOptions;+};++export type TasksViewContext = {+ state: Store<TasksViewState>;+ setState: SetStoreFunction<TasksViewState>;+ setTab: (tab: TaskTab) => void;+ setFacets: (facets: TasksViewState['facets']) => void;+ setPrimarySort: (id: TaskSortId) => void;+};++export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<+ TasksViewContext,+ TasksViewProviderProps+>('TasksView', (props) => {+ const panel = useSplitPanelOrThrow();+ const userId = useUserId();++ const initial = props.initialState ?? {};+ const initialTab = initial.tab ?? 'my-tasks';++ const [state, setState] = makePersistedState(+ createStore<TasksViewState>({+ tab: initialTab,+ search: initial.search ?? '',+ groupBy: initial.groupBy ?? TASK_DEFAULT_GROUP_BY[initialTab],+ sort: (initial.sort ?? [{ id: 'updated_at' }]).map((item) => ({+ ...item,+ })),+ facets: normalizeFacetSelection(+ initial.facets ?? DEFAULT_TASK_FACET_SELECTION+ ),+ collapsedGroupIds: [...(initial.collapsedGroupIds ?? [])],+ collapsedSidebarSectionIds: [+ ...(initial.collapsedSidebarSectionIds ?? []),+ ],+ }),+ createTasksViewPersistence({+ handle: panel.handle,+ userId,+ restoreEntryState: props.initialState === undefined,+ restorePreferences: initial.collapsedSidebarSectionIds === undefined,+ })+ );++ const setTab = (tab: TaskTab) => {+ if (state.tab === tab) return;++ setState(+ produce((draft) => {+ draft.tab = tab;+ draft.groupBy = TASK_DEFAULT_GROUP_BY[tab];+ draft.facets = normalizeFacetSelection(DEFAULT_TASK_FACET_SELECTION);+ draft.collapsedGroupIds = [];+ })+ );+ };++ const setFacets = (facets: TasksViewState['facets']) => {+ setState('facets', reconcile(normalizeFacetSelection(facets)));+ };++ const setPrimarySort = (id: TaskSortId) => {+ const current = state.sort[0];+ const reversed = current?.id === id ? !current.reversed : false;++ setState('sort', [{ id, reversed }]);+ };++ return {+ state,+ setState,+ setTab,+ setFacets,+ setPrimarySort,+ };+});diff --git a/apps/web/src/features/tasks-view/tasks-view.tsx b/apps/web/src/features/tasks-view/tasks-view.tsxnew file mode 100644index 0000000000..1f4480cf87--- /dev/null+++ b/apps/web/src/features/tasks-view/tasks-view.tsx@@ -0,0 +1,71 @@+import { ViewShell } from '@app/components/view-shell';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { SplitPanel } from '@components/app/split-panel';+import { ListEntityMetadataQueryProvider } from '@entity';+import SpinnerIcon from '@phosphor/spinner.svg';+import { Surface } from '@ui';+import { onMount, Suspense } from 'solid-js';+import { TasksHeader } from './components/TasksHeader';+import { TasksSidebar } from './components/TasksSidebar';+import { TaskList } from './components/task-list/TaskList';+import { TasksViewProvider } from './tasks-view-context';+import type { TasksViewStateOptions } from './types';++export type TasksViewProps = {+ /** Explicit navigation state. When present, it wins over entry restoration. */+ initialState?: TasksViewStateOptions;+};++function TasksListFallback() {+ return (+ <Surface+ depth={2}+ class="grid min-h-0 min-w-0 place-items-center rounded-2xl text-ink-muted"+ >+ <SpinnerIcon aria-label="Loading tasks" class="size-5 animate-spin" />+ </Surface>+ );+}++function TasksViewRoot() {+ const panel = useSplitPanelOrThrow();++ onMount(() => panel.handle.setDisplayName('Tasks'));++ return (+ <ListEntityMetadataQueryProvider>+ <SplitPanel.Root>+ <SplitPanel.Body>+ <ViewShell.Root+ resizable+ aside={{ preserveDuringResize: false }}+ main={{ preferredWidth: 640 }}+ >+ <ViewShell.Aside>+ <TasksSidebar />+ </ViewShell.Aside>+ <ViewShell.Main>+ <ViewShell.Header>+ <TasksHeader />+ </ViewShell.Header>+ <ViewShell.Content>+ <Suspense fallback={<TasksListFallback />}>+ <TaskList />+ </Suspense>+ </ViewShell.Content>+ </ViewShell.Main>+ </ViewShell.Root>+ </SplitPanel.Body>+ </SplitPanel.Root>+ </ListEntityMetadataQueryProvider>+ );+}++/** Production Tasks view. */+export function TasksView(props: TasksViewProps) {+ return (+ <TasksViewProvider initialState={props.initialState}>+ <TasksViewRoot />+ </TasksViewProvider>+ );+}diff --git a/apps/web/src/features/tasks-view/types.ts b/apps/web/src/features/tasks-view/types.tsnew file mode 100644index 0000000000..36bccacd5d--- /dev/null+++ b/apps/web/src/features/tasks-view/types.ts@@ -0,0 +1,25 @@+import type { FacetSelection, SortSelection } from '@app/features/soup';++export type TaskTab = 'my-tasks' | 'created-by-me' | 'team-tasks';++export type TaskGroupBy =+ | 'none'+ | 'status'+ | 'priority'+ | 'assignee'+ | 'project'+ | 'date';++export type TaskSortId = 'updated_at' | 'created_at' | 'viewed_at';++export type TasksViewState = {+ tab: TaskTab;+ search: string;+ groupBy: TaskGroupBy;+ sort: SortSelection<TaskSortId>[];+ facets: FacetSelection;+ collapsedGroupIds: string[];+ collapsedSidebarSectionIds: string[];+};++export type TasksViewStateOptions = Partial<TasksViewState>;