Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CODEBASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ New subcommand? Copy a sibling in the target group, wire it in that group's
`Project`, `Section`, `User`. Paginated response shape
`{ results, nextCursor }` lives in `pagination.ts`.
- **`api/` siblings** — `filters.ts`, `workspaces.ts`, `notifications.ts`,
`reminders.ts`, `stats.ts`, `user-settings.ts`, `uploads.ts`
`reminders.ts`, `stats.ts`, `user-settings.ts`, `uploads.ts`,
`view-options.ts` (per-view sorting/grouping, read straight from `/sync`
because the SDK's schema rejects the API's `object_id: null`)
- **`auth.ts`** — read-side resolver: `resolveActiveUser`, `getApiToken`,
`probeApiToken`, `getAuthMetadata`, `listStoredUsers`, `NoTokenError`. All
write/clear paths go through `auth-store.ts`.
Expand Down Expand Up @@ -169,6 +171,10 @@ New subcommand? Copy a sibling in the target group, wire it in that group's
`commentUrl`, `filterUrl`
- **`task-list.ts`** — `fetchProjects`, `filterByWorkspaceOrPersonal`,
`parsePriority`, `PRIORITY_CHOICES` (`"p1"`–`"p4"`; internally p1→4, p4→1)
- **`task-sort.ts`** — client-side task ordering that matches the Todoist
apps: `sortTasks`, `taskSortFromViewOptions`, `buildProjectOrder`,
`queryUsesDates`, `TASK_SORT_FIELDS`. The API returns storage order, so
every list view sorts locally.
- **`pagination.ts`** — `paginate()`, `LIMITS` (tasks: 300, projects: 50, …)
- **`completion.ts`** — `parseCompLine`, `getCompletions`,
`withCaseInsensitiveChoices`, `withUnvalidatedChoices` (Commander tree-walker)
Expand Down
186 changes: 186 additions & 0 deletions src/lib/api/view-options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { afterEach, describe, expect, it, vi } from 'vitest'

vi.mock('../auth.js', () => ({
getApiToken: vi.fn(async () => 'test-token'),
}))

vi.mock('../usage-tracking.js', () => ({
fetchTodoist: vi.fn(),
}))

import { fetchTodoist } from '../usage-tracking.js'
import { fetchViewOptions, fetchViewOptionsSafely, findViewOptions } from './view-options.js'
import type { SavedViewOptions } from './view-options.js'

const mockFetchTodoist = vi.mocked(fetchTodoist)

function respondWith(payload: unknown, ok = true): void {
mockFetchTodoist.mockResolvedValue({
ok,
status: ok ? 200 : 500,
statusText: ok ? 'OK' : 'Internal Server Error',
json: async () => payload,
} as unknown as Response)
}

function makeSaved(overrides: Partial<SavedViewOptions>): SavedViewOptions {
return {
viewType: 'FILTER',
objectId: 'filter-1',
sortedBy: null,
sortOrder: null,
groupedBy: null,
viewMode: 'LIST',
...overrides,
}
}

afterEach(() => {
vi.clearAllMocks()
})

describe('fetchViewOptions', () => {
it('maps the sync payload to camelCase', async () => {
respondWith({
view_options: [
{
view_type: 'FILTER',
object_id: 'filter-1',
sorted_by: 'PRIORITY',
sort_order: 'DESC',
grouped_by: 'LABEL',
view_mode: 'LIST',
is_deleted: false,
},
],
})

await expect(fetchViewOptions()).resolves.toEqual([
{
viewType: 'FILTER',
objectId: 'filter-1',
sortedBy: 'PRIORITY',
sortOrder: 'DESC',
groupedBy: 'LABEL',
viewMode: 'LIST',
},
])
})

// The API sends null here for Today and Upcoming, which is what stops the
// SDK's typed sync from parsing this resource at all.
it('keeps rows whose object_id is null', async () => {
respondWith({
view_options: [
{ view_type: 'UPCOMING', object_id: null, sort_order: 'ASC', is_deleted: false },
],
})

const [upcoming] = await fetchViewOptions()
expect(upcoming).toMatchObject({ viewType: 'UPCOMING', objectId: null, sortOrder: 'ASC' })
})

it('drops deleted rows and rows with no view type', async () => {
respondWith({
view_options: [
{ view_type: 'FILTER', object_id: 'gone', is_deleted: true },
{ object_id: 'no-type' },
null,
{ view_type: 'FILTER', object_id: 'kept' },
],
})

const results = await fetchViewOptions()
expect(results.map((entry) => entry.objectId)).toEqual(['kept'])
})

// The Sync API can ship a new enum member before the SDK types know it.
it('nulls enum values the SDK does not recognise', async () => {
respondWith({
view_options: [
{
view_type: 'FILTER',
object_id: 'filter-1',
sorted_by: 'VIBES',
sort_order: 'SIDEWAYS',
grouped_by: 'PHASE_OF_MOON',
view_mode: 'HOLOGRAM',
},
],
})

const [entry] = await fetchViewOptions()
expect(entry).toEqual({
viewType: 'FILTER',
objectId: 'filter-1',
sortedBy: null,
sortOrder: null,
groupedBy: null,
viewMode: null,
})
})

it('drops rows whose view type is not one we can ask for', async () => {
respondWith({
view_options: [
{ view_type: 'INBOX_ZERO_ZONE', object_id: 'x' },
{ view_type: 'FILTER', object_id: 'kept' },
],
})

const results = await fetchViewOptions()
expect(results.map((entry) => entry.objectId)).toEqual(['kept'])
})

it('returns an empty list when the payload has no view options', async () => {
respondWith({})
await expect(fetchViewOptions()).resolves.toEqual([])
})

it('throws on a failed request', async () => {
respondWith({}, false)
await expect(fetchViewOptions()).rejects.toThrow('HTTP 500')
})
})

describe('fetchViewOptionsSafely', () => {
it('swallows failures so a view still renders', async () => {
mockFetchTodoist.mockRejectedValue(new Error('offline'))
await expect(fetchViewOptionsSafely()).resolves.toEqual([])
})
})

describe('findViewOptions', () => {
const saved = [
makeSaved({ viewType: 'PROJECT', objectId: 'shared-id' }),
makeSaved({ viewType: 'FILTER', objectId: 'filter-1', sortedBy: 'DUE_DATE' }),
makeSaved({ viewType: 'WORKSPACE_FILTER', objectId: 'filter-2', sortedBy: 'PRIORITY' }),
makeSaved({ viewType: 'UPCOMING', objectId: null, sortedBy: 'DEADLINE' }),
]

it('matches on view type and object id together', () => {
expect(
findViewOptions(saved, { viewTypes: ['FILTER'], objectId: 'filter-1' })?.sortedBy,
).toBe('DUE_DATE')
expect(
findViewOptions(saved, {
viewTypes: ['FILTER', 'WORKSPACE_FILTER'],
objectId: 'filter-2',
})?.sortedBy,
).toBe('PRIORITY')
})

it('does not match an id saved under another view type', () => {
expect(
findViewOptions(saved, { viewTypes: ['FILTER'], objectId: 'shared-id' }),
).toBeUndefined()
})

it('finds singleton views, which have no object id', () => {
expect(findViewOptions(saved, { viewTypes: ['UPCOMING'] })?.sortedBy).toBe('DEADLINE')
})

it('returns undefined when nothing matches', () => {
expect(findViewOptions(saved, { viewTypes: ['FILTER'], objectId: 'nope' })).toBeUndefined()
})
})
139 changes: 139 additions & 0 deletions src/lib/api/view-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import {
GROUPED_BY_OPTIONS,
SORT_ORDERS,
SORTED_BY_OPTIONS,
VIEW_MODES,
VIEW_TYPES,
} from '@doist/todoist-sdk'
import type { GroupedBy, SortedBy, SortOrder, ViewMode, ViewType } from '@doist/todoist-sdk'
import { getApiToken } from '../auth.js'
import { getLogger } from '../logger.js'
import { fetchTodoist } from '../usage-tracking.js'

const SYNC_ENDPOINT = 'https://api.todoist.com/api/v1/sync'

/**
* The presentation settings the Todoist apps store per view (project, label,
* filter, Today, Upcoming): list/board/calendar, grouping, and sorting.
*
* Named `SavedViewOptions` so it doesn't collide with `ViewOptions` in
* `src/lib/options.ts`, which is the CLI's own output-flag bag.
*/
export interface SavedViewOptions {
viewType: ViewType
/** `null` for the singleton views (Today, Upcoming) that have no object. */
objectId: string | null
sortedBy: SortedBy | null
sortOrder: SortOrder | null
groupedBy: GroupedBy | null
viewMode: ViewMode | null
}

interface RawViewOptions {
view_type?: unknown
object_id?: unknown
sorted_by?: unknown
sort_order?: unknown
grouped_by?: unknown
view_mode?: unknown
is_deleted?: unknown
}

function asString(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 ? value : null
}

/**
* Read an enum value only if it is one the SDK still knows about.
*
* The Sync API can grow a new member before the SDK types catch up, and a
* value we don't recognise is better dropped than asserted into a type that
* then lies to everything downstream. An unknown `sorted_by` reads as "no
* saved sort", which lands the caller on Todoist's default ordering.
*/
function asMember<T extends string>(value: unknown, allowed: readonly T[]): T | null {
const candidate = asString(value)
return candidate && (allowed as readonly string[]).includes(candidate) ? (candidate as T) : null
}

function parseViewOptions(raw: RawViewOptions): SavedViewOptions | null {
// A view type we can't name is one no caller can ask for, so the row goes.
const viewType = asMember<ViewType>(raw.view_type, VIEW_TYPES)
if (!viewType || raw.is_deleted === true) return null

return {
viewType,
objectId: asString(raw.object_id),
sortedBy: asMember<SortedBy>(raw.sorted_by, SORTED_BY_OPTIONS),
sortOrder: asMember<SortOrder>(raw.sort_order, SORT_ORDERS),
groupedBy: asMember<GroupedBy>(raw.grouped_by, GROUPED_BY_OPTIONS),
viewMode: asMember<ViewMode>(raw.view_mode, VIEW_MODES),
}
}

/**
* Read every saved view option via the Sync API.
*
* This goes to `/sync` directly instead of through `api.sync()` for one
* reason: `ViewOptionsSchema` types `object_id` as a required string, while
* the API returns `null` for the singleton views (Today, Upcoming), so a typed
* sync asking for `view_options` throws for anyone who has customised either
* one. Making that single field nullable in the SDK is the whole fix. Once it
* ships, this reader can drop back to `api.sync()` or move into the SDK
* outright, and the enum handling below goes with it.
*/
export async function fetchViewOptions(): Promise<SavedViewOptions[]> {
const token = await getApiToken()
const response = await fetchTodoist(SYNC_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
sync_token: '*',
resource_types: JSON.stringify(['view_options']),
}),
})

if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}`)
}

const data = (await response.json()) as { view_options?: unknown }
if (!Array.isArray(data.view_options)) return []

return data.view_options
.map((entry) => parseViewOptions((entry ?? {}) as RawViewOptions))
.filter((entry): entry is SavedViewOptions => entry !== null)
}

/**
* Saved view options are a display nicety: when they can't be read, callers
* should still render the list rather than fail. Returns `[]` on any error and
* leaves a breadcrumb behind `-vv`.
*/
export async function fetchViewOptionsSafely(): Promise<SavedViewOptions[]> {
try {
return await fetchViewOptions()
} catch (error) {
getLogger().detail('failed to load saved view options', {
error: error instanceof Error ? error.message : String(error),
})
return []
}
}

/**
* Find the saved options for one view, e.g. the FILTER view of a filter id.
* `objectId` defaults to `null` so the singleton views (Today, Upcoming),
* which the API stores with no object, can be looked up the same way.
*/
export function findViewOptions(
Comment thread
craigcarlyle marked this conversation as resolved.
viewOptions: SavedViewOptions[],
{ viewTypes, objectId = null }: { viewTypes: ViewType[]; objectId?: string | null },
): SavedViewOptions | undefined {
return viewOptions.find(
(entry) => entry.objectId === objectId && viewTypes.includes(entry.viewType),
)
}
Loading
Loading