-
Notifications
You must be signed in to change notification settings - Fork 17
feat(sort): add task ordering that matches the Todoist apps #480
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+1,229
−1
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
5a6d8cc
feat(sort): add task ordering that matches the Todoist apps
craigcarlyle 573412c
fix(sort): resolve due times in one timezone frame and cover the gaps
craigcarlyle 79b8ebb
refactor(view-options): validate enum values against the SDK constants
craigcarlyle File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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( | ||
| viewOptions: SavedViewOptions[], | ||
| { viewTypes, objectId = null }: { viewTypes: ViewType[]; objectId?: string | null }, | ||
| ): SavedViewOptions | undefined { | ||
| return viewOptions.find( | ||
| (entry) => entry.objectId === objectId && viewTypes.includes(entry.viewType), | ||
| ) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.