@type32/tasks 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,14 +16,23 @@ ESM only. Node ≥ 20.19, Bun, Deno, browsers.
16
16
  ## The format in one minute
17
17
 
18
18
  ```yaml
19
- version: "1.0"
19
+ version: "1.1"
20
20
  lists:
21
21
  - { id: work, title: Work, color: "#3b82f6", updatedAt: 2026-11-09T10:00:00Z }
22
+ views:
23
+ - {
24
+ id: board,
25
+ title: Board,
26
+ type: board,
27
+ groupBy: values.status,
28
+ updatedAt: 2026-11-09T10:00:00Z,
29
+ }
22
30
  tasks:
23
31
  - id: invoice # a todo: no start
24
32
  title: Ship invoice
25
33
  listId: work
26
34
  due: 2026-11-12
35
+ starred: true
27
36
  values: { status: doing, priority: high, tags: [billing] }
28
37
  updatedAt: 2026-11-09T10:00:00Z
29
38
  - id: standup # an event: start + duration, repeating
@@ -82,7 +91,7 @@ const task: Task = {
82
91
  due: "2026-11-12",
83
92
  updatedAt: now,
84
93
  };
85
- const doc: TaskDocument = validate({ version: "1.0", tasks: [task] });
94
+ const doc: TaskDocument = validate({ version: "1.1", tasks: [task] });
86
95
 
87
96
  // Deleting: keep the record and mark it, so references and sync still work.
88
97
  Object.assign(doc.tasks[0]!, { deletedAt: now, updatedAt: now });
@@ -126,6 +135,19 @@ fields:
126
135
  - { id: estimate, title: Estimate (h), type: number, min: 0, updatedAt: 2026-11-09T10:00:00Z }
127
136
  ```
128
137
 
138
+ ## Views: boards, lists and calendars saved in the file
139
+
140
+ A document can keep its views, so every app that opens it shows the same board. A view has a `type` (`list`, `board`, `calendar`, `timeline`, `table`), and optionally `groupBy`, `sortBy`, `sortDescending`, `listIds`, `openOnly` and `scale`. Group and sort keys are task keys (`listId`, `due`, `starred`…) or `values.<field id>`. An app keeps its own settings for a view on it as extra keys.
141
+
142
+ ```ts
143
+ import { resolveFields, viewTasks } from "@type32/tasks";
144
+
145
+ const fields = resolveFields(doc);
146
+ for (const view of doc.views ?? []) {
147
+ const tasks = viewTasks(doc, view, fields); // filtered and sorted as the view says; grouping is yours to draw
148
+ }
149
+ ```
150
+
129
151
  ## Calendar views: occurrences in a range
130
152
 
131
153
  ```ts
@@ -168,7 +190,7 @@ save(document);
168
190
  for (const r of repairs) notify(r.message); // e.g. a value dropped because its field changed type
169
191
  ```
170
192
 
171
- - **Matching:** records (lists, tasks, custom fields, each option) match by `id`, and the later `updatedAt` wins.
193
+ - **Matching:** records (lists, views, tasks, custom fields, each option) match by `id`, and the later `updatedAt` wins.
172
194
  - **Repairs:** two edits that are each valid can still conflict, like two devices moving tasks under each other. `merge` repairs the result so it stays valid, and lists every change in `repairs`, including what was removed.
173
195
  - **Order:** record order is not synced.
174
196
 
@@ -250,6 +272,7 @@ Import never guesses. Anything the format can't represent is dropped and listed,
250
272
  | `resolveFields(doc): Record<string, ResolvedField>` | Built-in and custom fields with their options and categories |
251
273
  | `kindOf(task): "span" \| "moment" \| "todo"` | How to draw a task |
252
274
  | `statusOf`, `priorityOf`, `isComplete`, `isOpen`, `isOverdue`, `blockers` | What a task's values mean, given `resolveFields(doc)`. See "Statuses, priorities and custom fields" |
275
+ | `viewTasks(doc, view, fields): Task[]` | A view's tasks, filtered and sorted |
253
276
  | `occurrences(task, { from, to, timeZone? }): Occurrence[]` | Occurrences overlapping `[from, to)` |
254
277
  | `completeTask(task, completedAt): Task` | Mark done, or move a repeating task to its next occurrence |
255
278
  | `merge(a, b): { document, repairs }` | Combine two copies for sync |
package/SPEC.md CHANGED
@@ -1,4 +1,4 @@
1
- # Tasks format 1.0
1
+ # Tasks format 1.1
2
2
 
3
3
  One document format for todos, calendar events and timelines. A todo, an event and a timeline bar are the same object, a **task**; which one it is depends only on which time fields it has. Field names and meanings follow [JSCalendar (RFC 8984)](https://www.rfc-editor.org/rfc/rfc8984) where they overlap, so conversion stays mechanical.
4
4
 
@@ -7,9 +7,10 @@ A document can be written as JSON, YAML or TOML; the data model is identical. Ev
7
7
  ## Document
8
8
 
9
9
  ```yaml
10
- version: "1.0"
10
+ version: "1.1"
11
11
  lists: [] # optional
12
12
  fields: [] # optional
13
+ views: [] # optional
13
14
  tasks: []
14
15
  ```
15
16
 
@@ -18,8 +19,11 @@ tasks: []
18
19
  | `version` | string | yes | `"1.<minor>"`. Readers reject other majors. |
19
20
  | `lists` | [List](#list)[] | no | Containers: todo lists, calendars, timeline projects. |
20
21
  | `fields` | [Field](#fields)[] | no | Custom fields, and options added to built-in ones. |
22
+ | `views` | [View](#view)[] | no | Saved ways of showing the tasks: boards, calendars… |
21
23
  | `tasks` | [Task](#task)[] | yes | |
22
24
 
25
+ Version 1.1 added `views` and a task's `starred`. A 1.0 reader keeps both as unknown keys.
26
+
23
27
  Every object in the format keeps keys it doesn't define. Readers must write unknown keys back unchanged.
24
28
 
25
29
  ## Value types
@@ -36,7 +40,7 @@ Every object in the format keeps keys it doesn't define. Readers must write unkn
36
40
 
37
41
  ## Sync bookkeeping
38
42
 
39
- Lists, custom fields, field options and tasks are **synced records**:
43
+ Lists, views, custom fields, field options and tasks are **synced records**:
40
44
 
41
45
  | Key | Type | Required | Notes |
42
46
  | ----------- | ----------- | -------- | ---------------------------------------------------------------------- |
@@ -50,7 +54,7 @@ A deleted record is still a valid reference target. Apps show it as archived or
50
54
 
51
55
  Two copies of a document merge record by record, so any implementation reaches the same content:
52
56
 
53
- 1. Records match by `id` within lists, tasks, custom fields, and each field's options. A record only one side has is kept.
57
+ 1. Records match by `id` within lists, views, tasks, custom fields, and each field's options. A record only one side has is kept.
54
58
  2. The record with the later `updatedAt` instant wins whole. Compare instants, not text: `…:00Z` equals `…:00.000Z`.
55
59
  3. On equal instants, a record with `deletedAt` wins; otherwise the one whose JSON with keys sorted is larger, comparing UTF-16 code units.
56
60
  4. A field definition's options merge one by one, independently of which definition won. Built-in field entries have no `updatedAt`, so only their options matter.
@@ -61,6 +65,7 @@ Two valid copies can still combine into an invalid document. Repair it like this
61
65
  - **Cycles** in `parentId` or `dependsOn` (tasks) or `parentId` (lists): within the loop, find the record that wins by rules 2–3 and remove its link to the next record. This undoes the later move.
62
66
  - **Options** that don't fit the winning field definition: drop every option when the field is no longer a select; mark deleted an option whose category the field no longer has (values using it stay valid); remove `category` from options when the field has no categories anymore.
63
67
  - **Values** that no longer fit their field (type or range): remove them from `values`.
68
+ - **Views** grouped or sorted by a field that no longer can be (its type changed): remove `groupBy` or `sortBy`.
64
69
 
65
70
  Every record a repair changes gets `updatedAt` one millisecond later than its own. The repaired version then wins against both copies it came from, so merging a stale copy again doesn't undo the repair, and every device still computes the same result.
66
71
 
@@ -74,6 +79,27 @@ Order is not synced: a merged collection keeps the first copy's order and append
74
79
  | `color` | Color | no | |
75
80
  | `parentId` | Id | no | Another list; lists nest. No cycles. |
76
81
 
82
+ ## View
83
+
84
+ A saved way of showing the tasks, so every app that opens the document shows the same board or calendar. Apps keep their own settings for a view on it, as extra keys.
85
+
86
+ | Key | Type | Notes |
87
+ | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
88
+ | `title` | string | Required. |
89
+ | `type` | string | Required, non-empty. `list`, `board`, `calendar`, `timeline` or `table`. Apps skip a view of a type they don't draw, and keep it. |
90
+ | `groupBy` | string | Sections, columns or rows: `listId`, `starred`, or `values.<field id>` of a `select`, `multiSelect` or `boolean` field. A task with several tags is in each tag's group. |
91
+ | `sortBy` | string | `title`, `start`, `end`, `due`, `completedAt`, `updatedAt`, `starred`, or `values.<field id>` of any field but a `multiSelect`. Absent: document order. |
92
+ | `sortDescending` | boolean | |
93
+ | `listIds` | Id[] | Only tasks in these lists or lists nested in them. Each must name a list. Absent: every task. |
94
+ | `openOnly` | boolean | Only open tasks: status `todo` or `doing`. |
95
+ | `scale` | string | Calendar: the period a page shows. Timeline: the period a column stands for. `day`, `week` or `month`; an app uses its default for a value it doesn't know. |
96
+
97
+ A view never shows deleted tasks. Sorting:
98
+
99
+ - Times sort as written, ignoring time zones: by the padded local value, so a date comes before the times on its day. UTC times sort by instant.
100
+ - A `select` sorts by its options' order (built-in options first, then the document's), a value outside the options after them; `boolean` false before true, and `starred` too, absent counting as false; text in the reader's locale.
101
+ - Tasks without the value come last in either direction. Ties keep document order.
102
+
77
103
  ## Task
78
104
 
79
105
  | Key | Type | Notes |
@@ -91,6 +117,7 @@ Order is not synced: a merged collection keeps the first copy's order and append
91
117
  | `recurrence` | [Recurrence](#recurrence) | Needs `start` or `due`. |
92
118
  | `excludedDates` | (LocalDate \| LocalDateTime)[] | Occurrences to skip. Needs `recurrence`; same form as the anchor. |
93
119
  | `completedAt` | UTCDateTime | |
120
+ | `starred` | boolean | Marked to stand out (a star or a flag). |
94
121
  | `values` | object | Field id → value. See [Fields](#fields). |
95
122
 
96
123
  ### Kind
@@ -255,7 +282,7 @@ A task exports as a **VEVENT** when it has `start`, no `due`, and no status othe
255
282
 
256
283
  Time zones are referenced by IANA name without `VTIMEZONE` blocks (RFC 7809). On import, every time is converted to the zone of `DTSTART` (or `DUE`).
257
284
 
258
- **Lost on export:** lists, custom fields, custom status and priority options (exported as their category), unknown keys, deleted tasks.
285
+ **Lost on export:** lists, views, custom fields, custom status and priority options (exported as their category), `starred`, unknown keys, deleted tasks.
259
286
 
260
287
  **Dropped on import, and reported:**
261
288
 
@@ -529,6 +529,54 @@
529
529
  tasks: []
530
530
  issues: [[fields, 0, options, 1, id]]
531
531
 
532
+ # --- Views ---
533
+ - name: view without type and title
534
+ format: yaml
535
+ input: |
536
+ version: "1.1"
537
+ views: [{ id: v, updatedAt: 2026-11-09T10:00:00Z }]
538
+ tasks: []
539
+ issues: [[views, 0, title], [views, 0, type]]
540
+ - name: duplicate view id
541
+ format: yaml
542
+ input: |
543
+ version: "1.1"
544
+ views:
545
+ - { id: v, title: A, type: list, updatedAt: 2026-11-09T10:00:00Z }
546
+ - { id: v, title: B, type: board, updatedAt: 2026-11-09T10:00:00Z }
547
+ tasks: []
548
+ issues: [[views, 1, id]]
549
+ - name: view grouped by a text field, sorted by a multiSelect
550
+ format: yaml
551
+ input: |
552
+ version: "1.1"
553
+ views:
554
+ - { id: v, title: V, type: board, groupBy: values.location, sortBy: values.tags, updatedAt: 2026-11-09T10:00:00Z }
555
+ tasks: []
556
+ issues: [[views, 0, groupBy], [views, 0, sortBy]]
557
+ - name: view keys that aren't task keys or values paths
558
+ format: yaml
559
+ input: |
560
+ version: "1.1"
561
+ views:
562
+ - { id: v, title: V, type: board, groupBy: status, sortBy: notes, updatedAt: 2026-11-09T10:00:00Z }
563
+ tasks: []
564
+ issues: [[views, 0, groupBy], [views, 0, sortBy]]
565
+ - name: view of an undefined field and an unknown list
566
+ format: yaml
567
+ input: |
568
+ version: "1.1"
569
+ views:
570
+ - { id: v, title: V, type: list, sortBy: values.stage, listIds: [nope], updatedAt: 2026-11-09T10:00:00Z }
571
+ tasks: []
572
+ issues: [[views, 0, sortBy], [views, 0, listIds, 0]]
573
+ - name: starred that isn't a boolean
574
+ format: yaml
575
+ input: |
576
+ version: "1.1"
577
+ tasks: [{ id: a, title: A, starred: "yes", updatedAt: 2026-11-09T10:00:00Z }]
578
+ issues: [[tasks, 0, starred]]
579
+
532
580
  # --- Markdown task files ---
533
581
  - name: markdown without frontmatter
534
582
  format: markdown
@@ -163,6 +163,48 @@
163
163
  },
164
164
  ]
165
165
 
166
+ - name: views of a type and scale no reader draws, an app's keys, a deleted field to group by, and a starred task
167
+ format: yaml
168
+ input: |
169
+ version: "1.1"
170
+ lists: [{ id: work, title: Work, updatedAt: 2026-11-09T10:00:00Z }]
171
+ fields:
172
+ - { id: done, title: Done, type: boolean, updatedAt: 2026-11-09T10:00:00Z, deletedAt: 2026-11-09T10:00:00Z }
173
+ views:
174
+ - { id: m, title: Map, type: map, scale: quarter, x-app: { zoom: 3 }, updatedAt: 2026-11-09T10:00:00Z }
175
+ - { id: b, title: Board, type: board, groupBy: values.done, sortBy: completedAt, listIds: [work], updatedAt: 2026-11-09T10:00:00Z }
176
+ tasks: [{ id: a, title: A, starred: true, updatedAt: 2026-11-09T10:00:00Z }]
177
+ expect:
178
+ version: "1.1"
179
+ lists: [{ id: work, title: Work, updatedAt: "2026-11-09T10:00:00Z" }]
180
+ fields:
181
+ - {
182
+ id: done,
183
+ title: Done,
184
+ type: boolean,
185
+ updatedAt: "2026-11-09T10:00:00Z",
186
+ deletedAt: "2026-11-09T10:00:00Z",
187
+ }
188
+ views:
189
+ - {
190
+ id: m,
191
+ title: Map,
192
+ type: map,
193
+ scale: quarter,
194
+ x-app: { zoom: 3 },
195
+ updatedAt: "2026-11-09T10:00:00Z",
196
+ }
197
+ - {
198
+ id: b,
199
+ title: Board,
200
+ type: board,
201
+ groupBy: values.done,
202
+ sortBy: completedAt,
203
+ listIds: [work],
204
+ updatedAt: "2026-11-09T10:00:00Z",
205
+ }
206
+ tasks: [{ id: a, title: A, starred: true, updatedAt: "2026-11-09T10:00:00Z" }]
207
+
166
208
  - name: markdown with BOM, CRLF and fence-like lines in the body
167
209
  format: markdown
168
210
  input: "\uFEFF---\r\ntask: { id: a, title: A, updatedAt: 2026-11-09T10:00:00Z }\r\n--- \r\nbody\r\n---\r\n+++\r\n"
package/dist/index.d.mts CHANGED
@@ -40,6 +40,26 @@ interface List extends Synced {
40
40
  /** Parent list; lists nest. No cycles. */
41
41
  parentId?: string;
42
42
  }
43
+ /**
44
+ * A saved way of showing the document's tasks, shared by every app that reads the document. Apps keep their own
45
+ * settings on it as extra keys. Pick its tasks with `viewTasks()`.
46
+ */
47
+ interface View extends Synced {
48
+ title: string;
49
+ /** `list`, `board`, `calendar`, `timeline` or `table`. Apps skip, and keep, views of a type they don't draw. */
50
+ type: string;
51
+ /** Sections, columns or rows: `listId`, `starred`, or `values.<field id>` of a select, multiSelect or boolean field. */
52
+ groupBy?: string;
53
+ /** `title`, `start`, `end`, `due`, `completedAt`, `updatedAt`, `starred`, or `values.<field id>` of any field but a multiSelect. Absent: document order. */
54
+ sortBy?: string;
55
+ sortDescending?: boolean;
56
+ /** Only tasks in these lists or lists nested in them. Absent: every task. */
57
+ listIds?: string[];
58
+ /** Only open tasks (`isOpen`): done and cancelled ones hidden. */
59
+ openOnly?: boolean;
60
+ /** Calendar: the period a page shows. Timeline: the period a column stands for. `day`, `week` or `month`; apps use their default for one they don't know. */
61
+ scale?: string;
62
+ }
43
63
  /** A choice of a select field. Each option is its own synced record. */
44
64
  interface FieldOption extends Synced {
45
65
  /** Required, except when only recoloring or renaming a built-in option. */
@@ -115,18 +135,21 @@ interface Task extends Synced {
115
135
  /** Occurrences to skip, same form as the anchor. Needs `recurrence`. */
116
136
  excludedDates?: (LocalDate | LocalDateTime)[];
117
137
  completedAt?: UTCDateTime;
138
+ /** Marked to stand out (a star or a flag). */
139
+ starred?: boolean;
118
140
  /**
119
141
  * Field id → value, built-in (`status`, `priority`, `tags`, `progress`, `location`) and custom alike.
120
142
  * A key must name a field; a select value must be an option id. Read meanings with `resolveFields()`.
121
143
  */
122
144
  values?: Record<string, FieldValue>;
123
145
  }
124
- /** A whole file: lists, field definitions and tasks. */
146
+ /** A whole file: lists, field definitions, views and tasks. */
125
147
  interface TaskDocument {
126
- /** `"1.0"`; readers accept any `1.x`. */
148
+ /** `"1.1"`; readers accept any `1.x`. */
127
149
  version: string;
128
150
  lists?: List[];
129
151
  fields?: FieldDefinition[];
152
+ views?: View[];
130
153
  tasks: Task[];
131
154
  [key: string]: unknown;
132
155
  }
@@ -192,7 +215,7 @@ interface MergeResult {
192
215
  repairs: Repair[];
193
216
  }
194
217
  /**
195
- * Merges two copies of a document record by record: lists, tasks, custom fields and each field option.
218
+ * Merges two copies of a document record by record: lists, tasks, views, custom fields and each field option.
196
219
  * The later `updatedAt` wins; on a tie the deleted record wins, then the larger canonical JSON, so the
197
220
  * content is the same whichever side runs the merge. Record order follows `a`, with records new in `b` appended.
198
221
  *
@@ -292,4 +315,10 @@ interface OverdueOptions {
292
315
  export declare function isOverdue(task: Task, fields: Fields, options?: OverdueOptions): boolean;
293
316
  /** The tasks in `dependsOn` still in the way: not done, not cancelled, not deleted. Empty when unblocked. */
294
317
  export declare function blockers(task: Task, tasks: readonly Task[], fields: Fields): Task[];
295
- export type { Duration, FieldDefinition, FieldOption, FieldType, FieldValue, Fields, Format, Frequency, ImportResult, Issue, Kind, List, LocalDate, LocalDateTime, MarkdownTask, MergeResult, Occurrence, OccurrenceRange, OverdueOptions, Recurrence, Repair, ResolvedField, ResolvedOption, Synced, Task, TaskDocument, TaskPriority, TaskStatus, UTCDateTime, Weekday };
318
+ /**
319
+ * The tasks a view shows, in its order: not deleted, in its `listIds` or lists nested in them, open ones only
320
+ * with `openOnly`, sorted by `sortBy`. Tasks without the value come last either way; ties keep document order.
321
+ * Grouping (`groupBy`) is the app's to draw.
322
+ */
323
+ export declare function viewTasks(doc: TaskDocument, view: View, fields: Fields): Task[];
324
+ export type { Duration, FieldDefinition, FieldOption, FieldType, FieldValue, Fields, Format, Frequency, ImportResult, Issue, Kind, List, LocalDate, LocalDateTime, MarkdownTask, MergeResult, Occurrence, OccurrenceRange, OverdueOptions, Recurrence, Repair, ResolvedField, ResolvedOption, Synced, Task, TaskDocument, TaskPriority, TaskStatus, UTCDateTime, View, Weekday };
package/dist/index.mjs CHANGED
@@ -1,7 +1,6 @@
1
1
  import * as z from "zod";
2
2
  import { TomlDate, parse as parse$1, stringify as stringify$1 } from "smol-toml";
3
- import { load } from "js-yaml";
4
- import { stringify as stringify$2 } from "yaml";
3
+ import { dump, load } from "js-yaml";
5
4
  import { Temporal } from "temporal-polyfill";
6
5
  // src/cycle.ts
7
6
  /**
@@ -196,6 +195,17 @@ const optionSchema = z.looseObject({
196
195
  color: color.exactOptional(),
197
196
  category: z.string().min(1).exactOptional()
198
197
  });
198
+ const viewSchema = z.looseObject({
199
+ ...synced,
200
+ title: z.string(),
201
+ type: z.string().min(1, "expected a view type like board"),
202
+ groupBy: z.string().exactOptional(),
203
+ sortBy: z.string().exactOptional(),
204
+ sortDescending: z.boolean().exactOptional(),
205
+ listIds: z.array(id).exactOptional(),
206
+ openOnly: z.boolean().exactOptional(),
207
+ scale: z.string().exactOptional()
208
+ });
199
209
  const fieldSchema = z.looseObject({
200
210
  id,
201
211
  title: z.string().exactOptional(),
@@ -256,6 +266,7 @@ const taskSchema = z.looseObject({
256
266
  recurrence: recurrenceSchema.exactOptional(),
257
267
  excludedDates: z.array(local).exactOptional(),
258
268
  completedAt: utc$1.exactOptional(),
269
+ starred: z.boolean().exactOptional(),
259
270
  values: z.record(z.string(), z.union([
260
271
  z.string(),
261
272
  z.number(),
@@ -268,6 +279,7 @@ const documentSchema = z.looseObject({
268
279
  version: z.string().regex(/^1\.\d+$/, "unsupported version; this library reads 1.x"),
269
280
  lists: z.array(listSchema).exactOptional(),
270
281
  fields: z.array(fieldSchema).exactOptional(),
282
+ views: z.array(viewSchema).exactOptional(),
271
283
  tasks: z.array(taskSchema)
272
284
  }).superRefine((doc, ctx) => checkDocument(doc, (path, message) => ctx.addIssue({
273
285
  code: "custom",
@@ -323,6 +335,54 @@ function checkDocument(doc, issue) {
323
335
  });
324
336
  checkAcyclic(tasks, (t) => t.parentId === void 0 ? [] : [t.parentId], ["tasks"], "parentId", issue);
325
337
  checkAcyclic(tasks, (t) => t.dependsOn ?? [], ["tasks"], "dependsOn", issue);
338
+ const views = doc.views ?? [];
339
+ checkUnique(views, ["views"], issue);
340
+ views.forEach((v, i) => {
341
+ for (const use of VIEW_KEYS) {
342
+ const key = v[use];
343
+ const error = key === void 0 ? void 0 : viewKeyError(key, use, fields);
344
+ if (error) issue([
345
+ "views",
346
+ i,
347
+ use
348
+ ], error);
349
+ }
350
+ v.listIds?.forEach((l, j) => {
351
+ if (!listIds.has(l)) issue([
352
+ "views",
353
+ i,
354
+ "listIds",
355
+ j
356
+ ], `unknown list "${l}"`);
357
+ });
358
+ });
359
+ }
360
+ const VIEW_KEYS = ["groupBy", "sortBy"];
361
+ const SORT_KEYS = [
362
+ "title",
363
+ "start",
364
+ "end",
365
+ "due",
366
+ "completedAt",
367
+ "updatedAt",
368
+ "starred"
369
+ ];
370
+ /** Why `key` can't be a view's `groupBy` or `sortBy`, or undefined when it can. */
371
+ function viewKeyError(key, use, fields) {
372
+ if (key.startsWith("values.")) {
373
+ const fieldId = key.slice(7);
374
+ const field = fields[fieldId];
375
+ if (!field) return `unknown field "${fieldId}"; define it in "fields"`;
376
+ if (use === "groupBy" && ![
377
+ "select",
378
+ "multiSelect",
379
+ "boolean"
380
+ ].includes(field.type)) return `can't group by a ${field.type} field; use a select, multiSelect or boolean one`;
381
+ if (use === "sortBy" && field.type === "multiSelect") return "can't sort by a multiSelect field";
382
+ return;
383
+ }
384
+ if (use === "groupBy") return key === "listId" || key === "starred" ? void 0 : "expected listId, starred or values.<field id>";
385
+ return SORT_KEYS.includes(key) ? void 0 : `expected one of: ${SORT_KEYS.join(", ")}, or values.<field id>`;
326
386
  }
327
387
  function checkUnique(items, path, issue) {
328
388
  const seen = /* @__PURE__ */ new Set();
@@ -536,16 +596,10 @@ function checkExpansion(value, sourceLength) {
536
596
  function encode(data, format) {
537
597
  switch (format) {
538
598
  case "json": return `${JSON.stringify(data, null, 2)}\n`;
539
- case "yaml": return stringify$2(data, {
540
- version: "1.1",
541
- customTags: [
542
- "intOct",
543
- "intHex",
544
- "int",
545
- "floatExp",
546
- "floatNaN",
547
- "float"
548
- ]
599
+ case "yaml": return dump(data, {
600
+ lineWidth: -1,
601
+ noRefs: true,
602
+ quoteStyle: "double"
549
603
  });
550
604
  case "toml": {
551
605
  const path = findNull(data, []);
@@ -577,10 +631,11 @@ const CORE_KEYS = /* @__PURE__ */ new Set([
577
631
  "version",
578
632
  "lists",
579
633
  "fields",
634
+ "views",
580
635
  "tasks"
581
636
  ]);
582
637
  /**
583
- * Merges two copies of a document record by record: lists, tasks, custom fields and each field option.
638
+ * Merges two copies of a document record by record: lists, tasks, views, custom fields and each field option.
584
639
  * The later `updatedAt` wins; on a tie the deleted record wins, then the larger canonical JSON, so the
585
640
  * content is the same whichever side runs the merge. Record order follows `a`, with records new in `b` appended.
586
641
  *
@@ -600,6 +655,7 @@ function merge(a, b) {
600
655
  }
601
656
  if (x.lists || y.lists) doc.lists = mergeRecords(x.lists, y.lists);
602
657
  if (x.fields || y.fields) doc.fields = mergeRecords(x.fields, y.fields).map((f) => withOptions(f, x, y));
658
+ if (x.views || y.views) doc.views = mergeRecords(x.views, y.views);
603
659
  doc.tasks = mergeRecords(x.tasks, y.tasks);
604
660
  const repairs = [];
605
661
  breakCycles(doc.lists ?? [], "lists", "parentId", repairs);
@@ -607,6 +663,7 @@ function merge(a, b) {
607
663
  breakCycles(doc.tasks, "tasks", "dependsOn", repairs);
608
664
  repairOptions(doc, repairs);
609
665
  repairValues(doc, repairs);
666
+ repairViews(doc, repairs);
610
667
  return {
611
668
  document: validate(doc),
612
669
  repairs
@@ -743,6 +800,30 @@ function repairValues(doc, repairs) {
743
800
  if (Object.keys(t.values).length === 0) delete t.values;
744
801
  });
745
802
  }
803
+ /** A view grouped or sorted by a field whose definition changed type. */
804
+ function repairViews(doc, repairs) {
805
+ const fields = resolveFields(doc);
806
+ doc.views?.forEach((v, i) => {
807
+ let changed = false;
808
+ for (const use of VIEW_KEYS) {
809
+ const key = v[use];
810
+ const error = key === void 0 ? void 0 : viewKeyError(key, use, fields);
811
+ if (error === void 0) continue;
812
+ repairs.push({
813
+ path: [
814
+ "views",
815
+ i,
816
+ use
817
+ ],
818
+ message: error,
819
+ removed: key
820
+ });
821
+ delete v[use];
822
+ changed = true;
823
+ }
824
+ if (changed) bump(v);
825
+ });
826
+ }
746
827
  // src/recurrence.ts
747
828
  const { PlainDate, PlainDateTime } = Temporal;
748
829
  const WEEKDAYS = [
@@ -1466,4 +1547,61 @@ function blockers(task, tasks, fields) {
1466
1547
  const ids = new Set(task.dependsOn);
1467
1548
  return ids.size === 0 ? [] : tasks.filter((t) => ids.has(t.id) && isOpen(t, fields));
1468
1549
  }
1469
- export { TasksFormatError, blockers, completeTask, documentSchema, fromICS, isComplete, isOpen, isOverdue, isTaskFile, kindOf, merge, occurrences, parse, parseMarkdown, priorityOf, resolveFields, statusOf, stringify, stringifyMarkdown, toICS, validate };
1550
+ // src/views.ts
1551
+ /**
1552
+ * The tasks a view shows, in its order: not deleted, in its `listIds` or lists nested in them, open ones only
1553
+ * with `openOnly`, sorted by `sortBy`. Tasks without the value come last either way; ties keep document order.
1554
+ * Grouping (`groupBy`) is the app's to draw.
1555
+ */
1556
+ function viewTasks(doc, view, fields) {
1557
+ const lists = view.listIds && nested(doc, view.listIds);
1558
+ const shown = doc.tasks.filter((t) => t.deletedAt === void 0 && (!lists || t.listId !== void 0 && lists.has(t.listId)) && (!view.openOnly || isOpen(t, fields)));
1559
+ if (view.sortBy === void 0) return shown;
1560
+ const [get, compare] = sorter(view.sortBy, fields);
1561
+ const sign = view.sortDescending ? -1 : 1;
1562
+ const keyed = shown.map((task) => ({
1563
+ task,
1564
+ key: get(task)
1565
+ }));
1566
+ keyed.sort((p, q) => p.key === void 0 || q.key === void 0 ? Number(p.key === void 0) - Number(q.key === void 0) : sign * compare(p.key, q.key));
1567
+ return keyed.map((k) => k.task);
1568
+ }
1569
+ const words = new Intl.Collator(void 0, { numeric: true });
1570
+ const byWords = (a, b) => words.compare(a, b);
1571
+ const byNumber = (a, b) => a - b;
1572
+ const byCode = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1573
+ /** Local and UTC times as comparable text: padded, `Z` dropped. */
1574
+ const time = (v) => typeof v === "string" ? sortKey(v.replace(/Z$/, "")) : void 0;
1575
+ const text = (v) => typeof v === "string" ? v : void 0;
1576
+ function sorter(key, fields) {
1577
+ if (key === "title") return [(t) => t.title, byWords];
1578
+ if (key === "starred") return [(t) => Number(t.starred === true), byNumber];
1579
+ if (!key.startsWith("values.")) return [(t) => time(t[key]), byCode];
1580
+ const id = key.slice(7);
1581
+ const field = fields[id];
1582
+ const value = (t) => t.values?.[id];
1583
+ switch (field.type) {
1584
+ case "number": return [(t) => value(t), byNumber];
1585
+ case "boolean": return [(t) => value(t) === void 0 ? void 0 : Number(value(t)), byNumber];
1586
+ case "date": return [(t) => time(value(t)), byCode];
1587
+ case "select": {
1588
+ const rank = new Map(field.options.map((o, i) => [o.id, i]));
1589
+ return [(t) => value(t) === void 0 ? void 0 : rank.get(value(t)) ?? rank.size, byNumber];
1590
+ }
1591
+ default: return [(t) => text(value(t)), byWords];
1592
+ }
1593
+ }
1594
+ /** `ids` and every list nested under one of them. */
1595
+ function nested(doc, ids) {
1596
+ const out = new Set(ids);
1597
+ let grew = true;
1598
+ while (grew) {
1599
+ grew = false;
1600
+ for (const l of doc.lists ?? []) if (l.parentId !== void 0 && out.has(l.parentId) && !out.has(l.id)) {
1601
+ out.add(l.id);
1602
+ grew = true;
1603
+ }
1604
+ }
1605
+ return out;
1606
+ }
1607
+ export { TasksFormatError, blockers, completeTask, documentSchema, fromICS, isComplete, isOpen, isOverdue, isTaskFile, kindOf, merge, occurrences, parse, parseMarkdown, priorityOf, resolveFields, statusOf, stringify, stringifyMarkdown, toICS, validate, viewTasks };
package/dist/schema.json CHANGED
@@ -141,6 +141,64 @@
141
141
  "additionalProperties": {}
142
142
  }
143
143
  },
144
+ "views": {
145
+ "type": "array",
146
+ "items": {
147
+ "type": "object",
148
+ "properties": {
149
+ "id": {
150
+ "type": "string",
151
+ "minLength": 1
152
+ },
153
+ "updatedAt": {
154
+ "type": "string",
155
+ "format": "date-time",
156
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
157
+ },
158
+ "deletedAt": {
159
+ "type": "string",
160
+ "format": "date-time",
161
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
162
+ },
163
+ "title": {
164
+ "type": "string"
165
+ },
166
+ "type": {
167
+ "type": "string",
168
+ "minLength": 1
169
+ },
170
+ "groupBy": {
171
+ "type": "string"
172
+ },
173
+ "sortBy": {
174
+ "type": "string"
175
+ },
176
+ "sortDescending": {
177
+ "type": "boolean"
178
+ },
179
+ "listIds": {
180
+ "type": "array",
181
+ "items": {
182
+ "type": "string",
183
+ "minLength": 1
184
+ }
185
+ },
186
+ "openOnly": {
187
+ "type": "boolean"
188
+ },
189
+ "scale": {
190
+ "type": "string"
191
+ }
192
+ },
193
+ "required": [
194
+ "id",
195
+ "updatedAt",
196
+ "title",
197
+ "type"
198
+ ],
199
+ "additionalProperties": {}
200
+ }
201
+ },
144
202
  "tasks": {
145
203
  "type": "array",
146
204
  "items": {
@@ -287,6 +345,9 @@
287
345
  "format": "date-time",
288
346
  "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
289
347
  },
348
+ "starred": {
349
+ "type": "boolean"
350
+ },
290
351
  "values": {
291
352
  "type": "object",
292
353
  "propertyNames": {
package/llms.txt CHANGED
@@ -6,8 +6,8 @@ A task's kind comes from its time fields, never a type field: `start` plus `end`
6
6
 
7
7
  ## Rules for writing documents
8
8
 
9
- - Top level: `{ version: "1.0", lists?: List[], fields?: FieldDefinition[], tasks: Task[] }`.
10
- - Every task, list, custom field and field option needs `id` (UUID recommended) and `updatedAt`. Set `updatedAt` to the current UTC time on every change.
9
+ - Top level: `{ version: "1.1", lists?: List[], fields?: FieldDefinition[], views?: View[], tasks: Task[] }`.
10
+ - Every task, list, view, custom field and field option needs `id` (UUID recommended) and `updatedAt`. Set `updatedAt` to the current UTC time on every change.
11
11
  - Delete by setting `deletedAt` (UTC); never remove a record that others may reference.
12
12
  - Time formats:
13
13
  - `start`, `end`, `due`, `until` and `excludedDates` are local: `2026-11-12` (all-day) or `2026-11-12T09:30` (wall clock in `timeZone`; floating without one). Never put an offset or `Z` on these.
@@ -22,6 +22,8 @@ A task's kind comes from its time fields, never a type field: `start` plus `end`
22
22
  - Built-ins: `status: todo|doing|done|cancelled`, `priority: low|medium|high`, `tags: string[]`, `progress: 0–100`, `location: string`.
23
23
  - A custom field or custom option must be defined under `fields` before use. A custom status option maps to a built-in category: `{ id: shipped, title: Shipped, category: done, updatedAt }`.
24
24
  - Colors are `#rrggbb`.
25
+ - `task.starred: boolean` marks a task to stand out (a star or flag).
26
+ - Views (synced records like tasks): `{ id, title, type: list|board|calendar|timeline|table, groupBy?, sortBy?, sortDescending?, listIds?, openOnly?, scale?: day|week|month, updatedAt }`. `groupBy` is `listId`, `starred` or `values.<id>` of a select, multiSelect or boolean field; `sortBy` is `title`, `start`, `end`, `due`, `completedAt`, `updatedAt`, `starred` or `values.<id>` of any non-multiSelect field. Put app-specific view settings on the view as extra keys.
25
27
  - Unknown keys anywhere are kept, except inside `recurrence`, where they're an error.
26
28
 
27
29
  ## Rules for writing code
@@ -29,6 +31,7 @@ A task's kind comes from its time fields, never a type field: `start` plus `end`
29
31
  - Dates are strings throughout; the library never returns `Date` objects.
30
32
  - `parse`, `stringify`, `validate`, `parseMarkdown`, `stringifyMarkdown`, `toICS` and `fromICS` throw `TasksFormatError` (`.issues: { path, message }[]`; `.message` is ready to show). `isTaskFile` never throws.
31
33
  - Resolve `const fields = resolveFields(doc)` once, then use the helpers instead of comparing ids, because custom options like `shipped` mean `done`. The helpers: `statusOf(task, fields)` (todo|doing|done|cancelled), `priorityOf`, `isComplete`, `isOpen` (not deleted, todo or doing), `isOverdue(task, fields, { now?, timeZone? })` and `blockers(task, doc.tasks, fields)`. For other fields, read `fields[id].options` and each option's `.category`.
34
+ - To show a view, `viewTasks(doc, view, fields)` returns its tasks filtered and sorted; draw the groups yourself.
32
35
  - To draw a calendar or timeline, call `occurrences(task, { from, to, timeZone? })` for each task (`to` is exclusive). Don't expand recurrence by hand.
33
36
  - To complete a task, use `completeTask(task, new Date().toISOString())`. It returns a new task: repeating tasks move to their next occurrence, everything else becomes `status: done`. Don't move recurring dates by hand.
34
37
  - For sync, call `merge(local, remote)`. It returns `{ document, repairs }`; show `repairs` to the user.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@type32/tasks",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "One format for todos, events and timelines: schema, validation and parsing",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -36,7 +36,6 @@
36
36
  "js-yaml": "^5.5.0",
37
37
  "smol-toml": "^1.9.1",
38
38
  "temporal-polyfill": "^1.0.8",
39
- "yaml": "^2.9.1",
40
39
  "zod": "^4.6.7"
41
40
  },
42
41
  "devDependencies": {
@@ -47,7 +46,8 @@
47
46
  "tinybench": "^6.2.3",
48
47
  "tsdown": "^0.23.7",
49
48
  "typescript": "^7.0.2",
50
- "vitest": "^5.1.0"
49
+ "vitest": "^5.1.0",
50
+ "yaml": "^2.9.1"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "typescript": ">=6.0.3"