mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 19:07:41 +00:00
refactor(github): organize concrete feature owners (#41601)
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildBoardColumns, resolveBoardColumnField } from './project-board-columns'
|
||||
import type {
|
||||
GitHubProjectField,
|
||||
GitHubProjectFieldValue,
|
||||
GitHubProjectRow,
|
||||
GitHubProjectView
|
||||
} from './project-types'
|
||||
|
||||
const STATUS_FIELD: GitHubProjectField = {
|
||||
kind: 'single-select',
|
||||
id: 'f_status',
|
||||
name: 'Status',
|
||||
dataType: 'SINGLE_SELECT',
|
||||
options: [
|
||||
{ id: 'opt_todo', name: 'Todo', color: 'GREEN' },
|
||||
{ id: 'opt_prog', name: 'In Progress', color: 'YELLOW' },
|
||||
{ id: 'opt_done', name: 'Done', color: 'PURPLE' }
|
||||
]
|
||||
}
|
||||
|
||||
const SPRINT_FIELD: GitHubProjectField = {
|
||||
kind: 'iteration',
|
||||
id: 'f_sprint',
|
||||
name: 'Sprint',
|
||||
dataType: 'ITERATION',
|
||||
iterations: [
|
||||
{ id: 'it_1', title: 'Sprint 1', startDate: '2026-08-24', duration: 14, completed: true },
|
||||
{ id: 'it_2', title: 'Sprint 2', startDate: '2026-09-07', duration: 14, completed: false }
|
||||
]
|
||||
}
|
||||
|
||||
function view(overrides: Partial<GitHubProjectView>): GitHubProjectView {
|
||||
return {
|
||||
id: 'PVTV_1',
|
||||
number: 1,
|
||||
name: 'Board',
|
||||
layout: 'BOARD_LAYOUT',
|
||||
filter: '',
|
||||
fields: [],
|
||||
groupByFields: [],
|
||||
sortByFields: [],
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function row(id: string, values: GitHubProjectFieldValue[]): GitHubProjectRow {
|
||||
const fieldValuesByFieldId: Record<string, GitHubProjectFieldValue> = {}
|
||||
for (const value of values) {
|
||||
fieldValuesByFieldId[value.fieldId] = value
|
||||
}
|
||||
return {
|
||||
id,
|
||||
itemType: 'ISSUE',
|
||||
content: {
|
||||
number: 1,
|
||||
title: id,
|
||||
body: null,
|
||||
url: `https://github.com/o/r/issues/1`,
|
||||
state: 'OPEN',
|
||||
stateReason: null,
|
||||
isDraft: null,
|
||||
repository: 'o/r',
|
||||
assignees: [],
|
||||
labels: [],
|
||||
parentIssue: null,
|
||||
issueType: null
|
||||
},
|
||||
fieldValuesByFieldId,
|
||||
updatedAt: '2026-09-01T00:00:00Z',
|
||||
position: 0
|
||||
}
|
||||
}
|
||||
|
||||
const statusValue = (optionId: string, name: string): GitHubProjectFieldValue => ({
|
||||
kind: 'single-select',
|
||||
fieldId: 'f_status',
|
||||
optionId,
|
||||
name,
|
||||
color: ''
|
||||
})
|
||||
|
||||
describe('resolveBoardColumnField', () => {
|
||||
it('prefers the view-configured vertical group field', () => {
|
||||
const v = view({ fields: [STATUS_FIELD], verticalGroupByFields: [SPRINT_FIELD] })
|
||||
expect(resolveBoardColumnField(v)).toBe(SPRINT_FIELD)
|
||||
})
|
||||
|
||||
it('ignores a non-select vertical field instead of building clear-only columns', () => {
|
||||
const textField: GitHubProjectField = {
|
||||
kind: 'field',
|
||||
id: 'f_text',
|
||||
name: 'Notes',
|
||||
dataType: 'TEXT'
|
||||
}
|
||||
const v = view({ fields: [STATUS_FIELD], verticalGroupByFields: [textField] })
|
||||
expect(resolveBoardColumnField(v)).toBe(STATUS_FIELD)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildBoardColumns', () => {
|
||||
it('routes no-value rows to the trailing column whose drop clears the field', () => {
|
||||
const columns = buildBoardColumns(STATUS_FIELD, [row('a', [])])
|
||||
const trailing = columns.at(-1)!
|
||||
expect(trailing.label).toBe('No Status')
|
||||
expect(trailing.rows.map((r) => r.id)).toEqual(['a'])
|
||||
expect(trailing.dropValue).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps rows pointing at a deleted option in their own non-droppable column', () => {
|
||||
const columns = buildBoardColumns(STATUS_FIELD, [
|
||||
row('a', [statusValue('opt_gone', 'Archived')])
|
||||
])
|
||||
const ghost = columns.find((c) => c.label === 'Archived')!
|
||||
expect(ghost.rows.map((r) => r.id)).toEqual(['a'])
|
||||
expect(ghost.dropValue).toBeUndefined()
|
||||
// Ghost columns sit between the real options and the no-value column.
|
||||
expect(columns.at(-1)?.label).toBe('No Status')
|
||||
})
|
||||
|
||||
it('buckets non-select fields read-only', () => {
|
||||
const assignees: GitHubProjectField = {
|
||||
kind: 'field',
|
||||
id: 'f_assignees',
|
||||
name: 'Assignees',
|
||||
dataType: 'ASSIGNEES'
|
||||
}
|
||||
const columns = buildBoardColumns(assignees, [
|
||||
row('a', [
|
||||
{
|
||||
kind: 'users',
|
||||
fieldId: 'f_assignees',
|
||||
users: [{ login: 'alice', name: null, avatarUrl: null }]
|
||||
}
|
||||
]),
|
||||
row('b', [])
|
||||
])
|
||||
expect(columns.map((c) => c.label)).toEqual(['alice', 'No Assignees'])
|
||||
expect(columns[0]?.dropValue).toBeUndefined()
|
||||
expect(columns.at(-1)?.dropValue).toBeUndefined()
|
||||
expect(columns.at(-1)?.rows.map((r) => r.id)).toEqual(['b'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { EMPTY_PROJECT_GROUP_KEY, groupRowsByField } from './project-group-sort'
|
||||
import type {
|
||||
GitHubProjectField,
|
||||
GitHubProjectFieldMutationValue,
|
||||
GitHubProjectRow,
|
||||
GitHubProjectView
|
||||
} from './project-types'
|
||||
|
||||
export type ProjectBoardColumn = {
|
||||
key: string
|
||||
label: string
|
||||
/** GitHub single-select color token ('GREEN', …) when the column is one. */
|
||||
color: string | null
|
||||
/** undefined is read-only; null clears the field. */
|
||||
dropValue: GitHubProjectFieldMutationValue | null | undefined
|
||||
rows: GitHubProjectRow[]
|
||||
}
|
||||
|
||||
export function resolveBoardColumnField(view: GitHubProjectView): GitHubProjectField | null {
|
||||
const vertical = view.verticalGroupByFields?.[0]
|
||||
// Non-select fields must never expose clear-only drop targets.
|
||||
if (vertical && (vertical.kind === 'single-select' || vertical.kind === 'iteration')) {
|
||||
return vertical
|
||||
}
|
||||
// Older hosts omit vertical grouping; Status is GitHub's default.
|
||||
const singleSelects = view.fields.filter((field) => field.kind === 'single-select')
|
||||
return singleSelects.find((field) => /^status$/i.test(field.name)) ?? singleSelects[0] ?? null
|
||||
}
|
||||
|
||||
/** Includes empty options, deleted-option buckets, and a final unset bucket. */
|
||||
export function buildBoardColumns(
|
||||
field: GitHubProjectField,
|
||||
rowsInOrder: GitHubProjectRow[]
|
||||
): ProjectBoardColumn[] {
|
||||
const buckets = groupRowsByField(field, rowsInOrder)
|
||||
const bucketsByKey = new Map(buckets.map((bucket) => [bucket.key, bucket]))
|
||||
const columns: ProjectBoardColumn[] = []
|
||||
if (field.kind === 'single-select') {
|
||||
for (const option of field.options) {
|
||||
columns.push({
|
||||
key: option.id,
|
||||
label: option.name,
|
||||
color: option.color || null,
|
||||
dropValue: { kind: 'single-select', optionId: option.id },
|
||||
rows: bucketsByKey.get(option.id)?.rows ?? []
|
||||
})
|
||||
bucketsByKey.delete(option.id)
|
||||
}
|
||||
} else if (field.kind === 'iteration') {
|
||||
for (const iteration of field.iterations) {
|
||||
columns.push({
|
||||
key: iteration.id,
|
||||
label: iteration.title,
|
||||
color: null,
|
||||
dropValue: { kind: 'iteration', iterationId: iteration.id },
|
||||
rows: bucketsByKey.get(iteration.id)?.rows ?? []
|
||||
})
|
||||
bucketsByKey.delete(iteration.id)
|
||||
}
|
||||
}
|
||||
// Preserve deleted options as read-only columns.
|
||||
for (const bucket of buckets) {
|
||||
if (!bucketsByKey.has(bucket.key) || bucket.key === EMPTY_PROJECT_GROUP_KEY) {
|
||||
continue
|
||||
}
|
||||
columns.push({
|
||||
key: bucket.key,
|
||||
label: bucket.label,
|
||||
color: null,
|
||||
dropValue: undefined,
|
||||
rows: bucket.rows
|
||||
})
|
||||
}
|
||||
columns.push({
|
||||
key: EMPTY_PROJECT_GROUP_KEY,
|
||||
label: `No ${field.name}`,
|
||||
color: null,
|
||||
dropValue: field.kind === 'single-select' || field.kind === 'iteration' ? null : undefined,
|
||||
rows: bucketsByKey.get(EMPTY_PROJECT_GROUP_KEY)?.rows ?? []
|
||||
})
|
||||
return columns
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { GitHubProjectRow } from './project-types'
|
||||
|
||||
type ProjectContent = Pick<
|
||||
GitHubProjectRow['content'],
|
||||
'repository' | 'linkedPullRequests' | 'subIssuesProgress'
|
||||
> & { parentIssue?: GitHubProjectRow['content']['parentIssue'] }
|
||||
|
||||
export type ProjectContentField =
|
||||
| { kind: 'parent'; parent: NonNullable<ProjectContent['parentIssue']> }
|
||||
| { kind: 'repository'; repository: string }
|
||||
| { kind: 'progress'; progress: NonNullable<ProjectContent['subIssuesProgress']> }
|
||||
| { kind: 'linked'; linked: NonNullable<ProjectContent['linkedPullRequests']> }
|
||||
|
||||
// Undefined leaves unsupported fields on the field-value path; null is authoritative emptiness.
|
||||
export function projectContentField(
|
||||
content: ProjectContent,
|
||||
dataType: string
|
||||
): ProjectContentField | null | undefined {
|
||||
switch (dataType) {
|
||||
case 'PARENT_ISSUE':
|
||||
return content.parentIssue ? { kind: 'parent', parent: content.parentIssue } : null
|
||||
case 'REPOSITORY':
|
||||
return content.repository ? { kind: 'repository', repository: content.repository } : null
|
||||
case 'SUB_ISSUES_PROGRESS':
|
||||
return content.subIssuesProgress && content.subIssuesProgress.total !== 0
|
||||
? { kind: 'progress', progress: content.subIssuesProgress }
|
||||
: null
|
||||
case 'LINKED_PULL_REQUESTS':
|
||||
return content.linkedPullRequests &&
|
||||
(content.linkedPullRequests.pullRequests.length > 0 ||
|
||||
content.linkedPullRequests.totalCount > 0)
|
||||
? { kind: 'linked', linked: content.linkedPullRequests }
|
||||
: null
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function projectContentFieldLabel(value: ProjectContentField): string {
|
||||
switch (value.kind) {
|
||||
case 'parent':
|
||||
return `#${value.parent.number}`
|
||||
case 'repository':
|
||||
return value.repository
|
||||
case 'progress':
|
||||
return `${value.progress.completed}/${value.progress.total} (${value.progress.percentCompleted}%)`
|
||||
case 'linked':
|
||||
return value.linked.pullRequests.map((pr) => `#${pr.number}`).join(', ')
|
||||
}
|
||||
}
|
||||
|
||||
export function projectContentFieldSortValue(
|
||||
value: ProjectContentField | null
|
||||
): string | number | null {
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
switch (value.kind) {
|
||||
case 'parent':
|
||||
return value.parent.number
|
||||
case 'repository':
|
||||
return value.repository
|
||||
case 'progress':
|
||||
return value.progress.percentCompleted
|
||||
case 'linked':
|
||||
return value.linked.pullRequests[0]?.number ?? null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
// Pure selected-view grouping/sorting keeps desktop/mobile order independent of fetch order.
|
||||
import type {
|
||||
GitHubProjectField,
|
||||
GitHubProjectRow,
|
||||
GitHubProjectSort,
|
||||
GitHubProjectTable
|
||||
} from './project-types'
|
||||
|
||||
import {
|
||||
projectContentField,
|
||||
projectContentFieldLabel,
|
||||
projectContentFieldSortValue
|
||||
} from './project-content-field'
|
||||
|
||||
export type ProjectGroup = {
|
||||
key: string
|
||||
label: string
|
||||
/** Iteration metadata for headers that render a date range + Current pill. */
|
||||
iteration: {
|
||||
startDate: string
|
||||
duration: number
|
||||
completed: boolean
|
||||
} | null
|
||||
rows: GitHubProjectRow[]
|
||||
}
|
||||
|
||||
export const EMPTY_PROJECT_GROUP_KEY = '__empty__'
|
||||
|
||||
type ProjectFieldValue = GitHubProjectRow['fieldValuesByFieldId'][string]
|
||||
|
||||
/** False for anything that renders as an empty cell — absent, or present with a blank payload. */
|
||||
function hasNonEmptyFieldValue(value: ProjectFieldValue | undefined): boolean {
|
||||
if (!value) {
|
||||
return false
|
||||
}
|
||||
switch (value.kind) {
|
||||
case 'users':
|
||||
return Boolean(value.users[0]?.login)
|
||||
case 'labels':
|
||||
return Boolean(value.labels[0]?.name)
|
||||
case 'text':
|
||||
return value.text.trim().length > 0
|
||||
case 'date':
|
||||
return value.date.trim().length > 0
|
||||
case 'iteration':
|
||||
case 'number':
|
||||
case 'single-select':
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Finite sentinels avoid Infinity - Infinity yielding NaN and skipping sort tie-breaks.
|
||||
const UNKNOWN_INDEX_SENTINEL = Number.MAX_SAFE_INTEGER
|
||||
|
||||
function createFieldOrderIndex(field: GitHubProjectField): ReadonlyMap<string, number> {
|
||||
const entries =
|
||||
field.kind === 'iteration'
|
||||
? (field.iterations ?? [])
|
||||
: field.kind === 'single-select'
|
||||
? (field.options ?? [])
|
||||
: []
|
||||
const indices = new Map<string, number>()
|
||||
entries.forEach((entry, index) => {
|
||||
const id = entry.id
|
||||
if (!indices.has(id)) {
|
||||
indices.set(id, index)
|
||||
}
|
||||
})
|
||||
return indices
|
||||
}
|
||||
|
||||
// Preserve the mobile mirror's fallback for partial ordering metadata.
|
||||
function getFieldValueForGrouping(
|
||||
row: GitHubProjectRow,
|
||||
field: GitHubProjectField,
|
||||
orderIndex: ReadonlyMap<string, number>
|
||||
): { key: string; label: string; orderHint: number; iteration: ProjectGroup['iteration'] } {
|
||||
const contentValue = projectContentField(row.content, field.dataType)
|
||||
if (contentValue && contentValue.kind !== 'linked') {
|
||||
const label = projectContentFieldLabel(contentValue)
|
||||
const order = projectContentFieldSortValue(contentValue)
|
||||
return {
|
||||
key: contentValue.kind === 'parent' ? contentValue.parent.url : `raw:${label}`,
|
||||
label,
|
||||
orderHint: typeof order === 'number' ? order : UNKNOWN_INDEX_SENTINEL - 1,
|
||||
iteration: null
|
||||
}
|
||||
}
|
||||
const value = contentValue === null ? undefined : row.fieldValuesByFieldId[field.id]
|
||||
if (!value || !hasNonEmptyFieldValue(value)) {
|
||||
return {
|
||||
key: EMPTY_PROJECT_GROUP_KEY,
|
||||
label: labelForEmpty(field),
|
||||
orderHint: UNKNOWN_INDEX_SENTINEL,
|
||||
iteration: null
|
||||
}
|
||||
}
|
||||
if (field.kind === 'iteration' && value.kind === 'iteration') {
|
||||
const iterations = field.iterations ?? []
|
||||
const idx = orderIndex.get(value.iterationId) ?? -1
|
||||
const meta = iterations[idx]
|
||||
return {
|
||||
key: value.iterationId,
|
||||
label: value.title || meta?.title || 'Iteration',
|
||||
orderHint: idx === -1 ? UNKNOWN_INDEX_SENTINEL - 1 : idx,
|
||||
iteration: meta
|
||||
? { startDate: meta.startDate, duration: meta.duration, completed: meta.completed }
|
||||
: null
|
||||
}
|
||||
}
|
||||
if (field.kind === 'single-select' && value.kind === 'single-select') {
|
||||
const idx = orderIndex.get(value.optionId) ?? -1
|
||||
return {
|
||||
key: value.optionId,
|
||||
label: value.name,
|
||||
orderHint: idx === -1 ? UNKNOWN_INDEX_SENTINEL - 1 : idx,
|
||||
iteration: null
|
||||
}
|
||||
}
|
||||
const label = deriveStringValue(value)
|
||||
return {
|
||||
key: `raw:${label}`,
|
||||
label,
|
||||
// Why: number labels sort as text (10 before 2, -10 between -1 and -2).
|
||||
orderHint: value.kind === 'number' ? value.number : UNKNOWN_INDEX_SENTINEL - 1,
|
||||
iteration: null
|
||||
}
|
||||
}
|
||||
|
||||
function labelForEmpty(field: GitHubProjectField): string {
|
||||
return `No ${field.name}`
|
||||
}
|
||||
|
||||
function deriveStringValue(value: GitHubProjectRow['fieldValuesByFieldId'][string]): string {
|
||||
switch (value.kind) {
|
||||
case 'text':
|
||||
return value.text
|
||||
case 'number':
|
||||
return String(value.number)
|
||||
case 'date':
|
||||
return value.date
|
||||
case 'single-select':
|
||||
return value.name
|
||||
case 'iteration':
|
||||
return value.title
|
||||
case 'labels':
|
||||
return value.labels.map((l) => l.name).join(', ')
|
||||
case 'users':
|
||||
return value.users.map((u) => u.login).join(', ')
|
||||
}
|
||||
}
|
||||
|
||||
export function groupRows(
|
||||
table: GitHubProjectTable,
|
||||
rowsInOrder: GitHubProjectRow[]
|
||||
): ProjectGroup[] {
|
||||
const groupField = table.selectedView.groupByFields[0]
|
||||
if (!groupField) {
|
||||
return [{ key: 'all', label: '', iteration: null, rows: rowsInOrder }]
|
||||
}
|
||||
return groupRowsByField(groupField, rowsInOrder)
|
||||
}
|
||||
|
||||
/** Share field grouping between table/board so labels and ordering agree. */
|
||||
export function groupRowsByField(
|
||||
groupField: GitHubProjectField,
|
||||
rowsInOrder: GitHubProjectRow[]
|
||||
): ProjectGroup[] {
|
||||
const groupOrderIndex = createFieldOrderIndex(groupField)
|
||||
const buckets = new Map<
|
||||
string,
|
||||
{
|
||||
label: string
|
||||
orderHint: number
|
||||
iteration: ProjectGroup['iteration']
|
||||
rows: GitHubProjectRow[]
|
||||
}
|
||||
>()
|
||||
for (const row of rowsInOrder) {
|
||||
const { key, label, orderHint, iteration } = getFieldValueForGrouping(
|
||||
row,
|
||||
groupField,
|
||||
groupOrderIndex
|
||||
)
|
||||
let bucket = buckets.get(key)
|
||||
if (!bucket) {
|
||||
bucket = { label, orderHint, iteration, rows: [] }
|
||||
buckets.set(key, bucket)
|
||||
}
|
||||
bucket.rows.push(row)
|
||||
}
|
||||
const entries = Array.from(buckets.entries())
|
||||
entries.sort((a, b) => {
|
||||
if (a[0] === EMPTY_PROJECT_GROUP_KEY) {
|
||||
return 1
|
||||
}
|
||||
if (b[0] === EMPTY_PROJECT_GROUP_KEY) {
|
||||
return -1
|
||||
}
|
||||
if (groupField.kind === 'iteration' || groupField.kind === 'single-select') {
|
||||
return a[1].orderHint - b[1].orderHint
|
||||
}
|
||||
if (
|
||||
groupField.dataType === 'NUMBER' ||
|
||||
groupField.dataType === 'PARENT_ISSUE' ||
|
||||
groupField.dataType === 'SUB_ISSUES_PROGRESS'
|
||||
) {
|
||||
return a[1].orderHint - b[1].orderHint || a[1].label.localeCompare(b[1].label)
|
||||
}
|
||||
return a[1].label.localeCompare(b[1].label)
|
||||
})
|
||||
return entries.map(([key, v]) => ({
|
||||
key,
|
||||
label: v.label,
|
||||
iteration: v.iteration,
|
||||
rows: v.rows
|
||||
}))
|
||||
}
|
||||
|
||||
function compareSort(
|
||||
a: GitHubProjectRow,
|
||||
b: GitHubProjectRow,
|
||||
sort: GitHubProjectSort,
|
||||
orderIndex: ReadonlyMap<string, number>
|
||||
): number {
|
||||
const field = sort.field
|
||||
const aContent = projectContentField(a.content, field.dataType)
|
||||
if (aContent !== undefined) {
|
||||
const bContent = projectContentField(b.content, field.dataType)
|
||||
const aOrder = projectContentFieldSortValue(aContent)
|
||||
const bOrder = projectContentFieldSortValue(bContent ?? null)
|
||||
if (aOrder === null || bOrder === null) {
|
||||
return aOrder === bOrder ? 0 : aOrder === null ? 1 : -1
|
||||
}
|
||||
const cmp =
|
||||
typeof aOrder === 'number' && typeof bOrder === 'number'
|
||||
? aOrder - bOrder
|
||||
: String(aOrder).localeCompare(String(bOrder))
|
||||
return sort.direction === 'DESC' ? -cmp : cmp
|
||||
}
|
||||
const aValue = a.fieldValuesByFieldId[field.id]
|
||||
const bValue = b.fieldValuesByFieldId[field.id]
|
||||
// Why: return before the trailing DESC flip so empty sorts last in both directions.
|
||||
const aFilled = hasNonEmptyFieldValue(aValue)
|
||||
const bFilled = hasNonEmptyFieldValue(bValue)
|
||||
if (!aFilled || !bFilled) {
|
||||
return aFilled === bFilled ? 0 : aFilled ? -1 : 1
|
||||
}
|
||||
|
||||
let cmp = 0
|
||||
if (
|
||||
field.kind === 'single-select' &&
|
||||
aValue.kind === 'single-select' &&
|
||||
bValue.kind === 'single-select'
|
||||
) {
|
||||
const aIdx = orderIndex.get(aValue.optionId) ?? -1
|
||||
const bIdx = orderIndex.get(bValue.optionId) ?? -1
|
||||
cmp =
|
||||
(aIdx === -1 ? UNKNOWN_INDEX_SENTINEL : aIdx) - (bIdx === -1 ? UNKNOWN_INDEX_SENTINEL : bIdx)
|
||||
} else if (
|
||||
field.kind === 'iteration' &&
|
||||
aValue.kind === 'iteration' &&
|
||||
bValue.kind === 'iteration'
|
||||
) {
|
||||
const aIdx = orderIndex.get(aValue.iterationId) ?? -1
|
||||
const bIdx = orderIndex.get(bValue.iterationId) ?? -1
|
||||
cmp =
|
||||
(aIdx === -1 ? UNKNOWN_INDEX_SENTINEL : aIdx) - (bIdx === -1 ? UNKNOWN_INDEX_SENTINEL : bIdx)
|
||||
} else if (aValue.kind === 'number' && bValue.kind === 'number') {
|
||||
cmp = aValue.number - bValue.number
|
||||
} else if (aValue.kind === 'date' && bValue.kind === 'date') {
|
||||
cmp = aValue.date.localeCompare(bValue.date)
|
||||
} else if (aValue.kind === 'text' && bValue.kind === 'text') {
|
||||
cmp = aValue.text.localeCompare(bValue.text)
|
||||
} else if (aValue.kind === 'users' && bValue.kind === 'users') {
|
||||
cmp = (aValue.users[0]?.login ?? '').localeCompare(bValue.users[0]?.login ?? '')
|
||||
} else if (aValue.kind === 'labels' && bValue.kind === 'labels') {
|
||||
cmp = (aValue.labels[0]?.name ?? '').localeCompare(bValue.labels[0]?.name ?? '')
|
||||
} else {
|
||||
// Ignore unknown sort kinds and continue tie-breaks, ending at row.position.
|
||||
return 0
|
||||
}
|
||||
return sort.direction === 'DESC' ? -cmp : cmp
|
||||
}
|
||||
|
||||
export function sortRows(table: GitHubProjectTable, rows: GitHubProjectRow[]): GitHubProjectRow[] {
|
||||
const sorts = table.selectedView.sortByFields.map((sort) => ({
|
||||
sort,
|
||||
orderIndex: createFieldOrderIndex(sort.field)
|
||||
}))
|
||||
const out = [...rows]
|
||||
out.sort((a, b) => {
|
||||
for (const { sort, orderIndex } of sorts) {
|
||||
const cmp = compareSort(a, b, sort, orderIndex)
|
||||
if (cmp !== 0) {
|
||||
return cmp
|
||||
}
|
||||
}
|
||||
return (a.position ?? UNKNOWN_INDEX_SENTINEL) - (b.position ?? UNKNOWN_INDEX_SENTINEL)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
export function isIterationCurrent(iteration: { startDate: string; duration: number }): boolean {
|
||||
const start = new Date(`${iteration.startDate}T00:00:00Z`).getTime()
|
||||
if (Number.isNaN(start)) {
|
||||
return false
|
||||
}
|
||||
const end = start + iteration.duration * 86_400_000
|
||||
const now = Date.now()
|
||||
return now >= start && now < end
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { githubProjectIdentityKey } from './project-identity'
|
||||
|
||||
describe('GitHub project identity', () => {
|
||||
it('keeps legacy github.com keys while isolating Enterprise hosts and ports', () => {
|
||||
const project = { owner: 'Acme', ownerType: 'organization' as const, number: 7 }
|
||||
|
||||
expect(githubProjectIdentityKey(project)).toBe('organization:acme:7')
|
||||
expect(githubProjectIdentityKey({ ...project, host: 'github.com' })).toBe('organization:acme:7')
|
||||
expect(githubProjectIdentityKey({ ...project, host: ' GitHub.com ' })).toBe(
|
||||
'organization:acme:7'
|
||||
)
|
||||
expect(githubProjectIdentityKey({ ...project, host: 'GHE.EXAMPLE:8443' })).toBe(
|
||||
'ghe.example:8443:organization:acme:7'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { isDefaultGitHubHost } from '../repositories/repository-identity-key'
|
||||
|
||||
export type GitHubProjectIdentity = {
|
||||
owner: string
|
||||
ownerType: 'organization' | 'user'
|
||||
number: number
|
||||
host?: string
|
||||
}
|
||||
|
||||
/** Stable settings/cache identity. Default-host keys intentionally retain the
|
||||
* legacy shape so existing github.com project preferences survive upgrades. */
|
||||
export function githubProjectIdentityKey(project: GitHubProjectIdentity): string {
|
||||
const projectKey = `${project.ownerType}:${project.owner.toLowerCase()}:${project.number}`
|
||||
const host = project.host?.trim().toLowerCase()
|
||||
return host && !isDefaultGitHubHost(host) ? `${host}:${projectKey}` : projectKey
|
||||
}
|
||||
|
||||
/** Project API calls must pin github.com too; otherwise process GH_HOST can
|
||||
* redirect a host-less persisted project to an Enterprise server. */
|
||||
export function githubProjectHost(host?: string | null): string {
|
||||
const trimmed = host?.trim()
|
||||
return trimmed || 'github.com'
|
||||
}
|
||||
|
||||
/** Settings rows carry only identity fields: the host's settings schema rejects extra keys
|
||||
* such as a picker row's title, and hosts before 2026-07-21 reject `host`, so github.com stays implicit. */
|
||||
export function toGitHubProjectIdentity(project: GitHubProjectIdentity): GitHubProjectIdentity {
|
||||
const host = project.host?.trim()
|
||||
return {
|
||||
owner: project.owner,
|
||||
ownerType: project.ownerType,
|
||||
number: project.number,
|
||||
...(host && !isDefaultGitHubHost(host) ? { host } : {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { isClipboardTextByteLengthOverLimit } from '../../clipboard-text'
|
||||
|
||||
export const GITHUB_PROJECT_REF_INPUT_MAX_BYTES = 2 * 1024
|
||||
export const GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR = 'Project reference is too large to resolve.'
|
||||
|
||||
export function isGitHubProjectRefInputTooLarge(
|
||||
input: string,
|
||||
maxBytes = GITHUB_PROJECT_REF_INPUT_MAX_BYTES
|
||||
): boolean {
|
||||
return isClipboardTextByteLengthOverLimit(input, maxBytes)
|
||||
}
|
||||
|
||||
export function hasBoundedGitHubProjectRefInputText(input: string): boolean {
|
||||
return !isGitHubProjectRefInputTooLarge(input) && /\S/.test(input)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { GitHubProjectRow, GitHubProjectTable } from './project-types'
|
||||
|
||||
export function projectRelationsTableFixture(): GitHubProjectTable {
|
||||
const row = (id: string, position: number, points: number): GitHubProjectRow => ({
|
||||
id,
|
||||
itemType: 'ISSUE',
|
||||
position,
|
||||
updatedAt: '',
|
||||
content: {
|
||||
number: position + 1,
|
||||
title: id,
|
||||
body: null,
|
||||
url: null,
|
||||
state: 'OPEN',
|
||||
stateReason: null,
|
||||
isDraft: null,
|
||||
repository: 'acme/repo',
|
||||
assignees: [],
|
||||
labels: [],
|
||||
parentIssue: null,
|
||||
issueType: null
|
||||
},
|
||||
fieldValuesByFieldId: { points: { kind: 'number', fieldId: 'points', number: points } }
|
||||
})
|
||||
const populated = row('populated', 0, 2)
|
||||
populated.content.linkedPullRequests = {
|
||||
pullRequests: [{ number: 12, title: 'Change', url: 'https://github.com/acme/repo/pull/12' }],
|
||||
totalCount: 3
|
||||
}
|
||||
populated.content.subIssuesProgress = { completed: 1, total: 2, percentCompleted: 50 }
|
||||
const points = { kind: 'field', id: 'points', name: 'Points', dataType: 'NUMBER' } as const
|
||||
return {
|
||||
project: {
|
||||
id: 'project-1',
|
||||
owner: 'acme',
|
||||
ownerType: 'organization',
|
||||
number: 1,
|
||||
title: 'Roadmap',
|
||||
url: 'https://github.com/orgs/acme/projects/1'
|
||||
},
|
||||
selectedView: {
|
||||
id: 'view-1',
|
||||
number: 1,
|
||||
name: 'Table',
|
||||
layout: 'TABLE_LAYOUT',
|
||||
filter: '',
|
||||
fields: [
|
||||
points,
|
||||
{
|
||||
kind: 'field',
|
||||
id: 'prs',
|
||||
name: 'Linked pull requests',
|
||||
dataType: 'LINKED_PULL_REQUESTS'
|
||||
},
|
||||
{
|
||||
kind: 'field',
|
||||
id: 'progress',
|
||||
name: 'Sub-issues progress',
|
||||
dataType: 'SUB_ISSUES_PROGRESS'
|
||||
}
|
||||
],
|
||||
groupByFields: [points],
|
||||
sortByFields: [{ field: points, direction: 'ASC' }]
|
||||
},
|
||||
rows: [populated, row('legacy', 1, 1)],
|
||||
totalCount: 2,
|
||||
parentFieldDropped: false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Keep Project request payloads separate from ProjectV2 domain shapes so renderer domain imports do not pull IPC arguments.
|
||||
import type { GitHubProjectFieldMutationValue, GitHubProjectOwnerType } from './project-types'
|
||||
import type { GitHubIssueUpdate } from '../../issue-mutation-types'
|
||||
|
||||
/** Set by a click: it may start the stopped WSL distro gh lives in (E9). Loads that also run
|
||||
* unprompted (mount effects, restore) leave it unset. Local IPC only. */
|
||||
export type WakeWslDistroArg = { wakeWslDistro?: boolean }
|
||||
|
||||
export type GetProjectViewTableArgs = {
|
||||
owner: string
|
||||
ownerType: GitHubProjectOwnerType
|
||||
projectNumber: number
|
||||
/** GitHub host (e.g. GHES); absent means github.com. */
|
||||
host?: string
|
||||
/** View selection: viewId > viewNumber > viewName > first TABLE_LAYOUT. */
|
||||
viewId?: string
|
||||
viewNumber?: number
|
||||
viewName?: string
|
||||
/** Fetch-only GitHub search override; never mutates the saved view filter. Undefined uses the saved filter, while empty clears it and has a distinct cache key. */
|
||||
queryOverride?: string
|
||||
}
|
||||
|
||||
export type ProjectWorkItemDetailsBySlugArgs = WakeWslDistroArg & {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
number: number
|
||||
type: 'issue' | 'pr'
|
||||
}
|
||||
|
||||
export type UpdateProjectItemFieldArgs = WakeWslDistroArg & {
|
||||
projectId: string
|
||||
host?: string
|
||||
itemId: string
|
||||
fieldId: string
|
||||
value: GitHubProjectFieldMutationValue
|
||||
}
|
||||
|
||||
export type ClearProjectItemFieldArgs = WakeWslDistroArg & {
|
||||
projectId: string
|
||||
host?: string
|
||||
itemId: string
|
||||
fieldId: string
|
||||
}
|
||||
|
||||
export type UpdateIssueBySlugArgs = WakeWslDistroArg & {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
number: number
|
||||
updates: GitHubIssueUpdate & { body?: string }
|
||||
}
|
||||
|
||||
export type UpdatePullRequestBySlugArgs = WakeWslDistroArg & {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
number: number
|
||||
updates: { title?: string; body?: string; state?: 'open' | 'closed' }
|
||||
}
|
||||
|
||||
export type AddIssueCommentBySlugArgs = WakeWslDistroArg & {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
number: number
|
||||
body: string
|
||||
}
|
||||
|
||||
export type UpdateIssueCommentBySlugArgs = WakeWslDistroArg & {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
commentId: number
|
||||
body: string
|
||||
}
|
||||
|
||||
export type DeleteIssueCommentBySlugArgs = WakeWslDistroArg & {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
commentId: number
|
||||
}
|
||||
|
||||
export type ListLabelsBySlugArgs = {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
}
|
||||
|
||||
export type ListAssignableUsersBySlugArgs = {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
seedLogins?: string[]
|
||||
}
|
||||
|
||||
export type ListIssueTypesBySlugArgs = {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
}
|
||||
|
||||
export type UpdateIssueTypeBySlugArgs = WakeWslDistroArg & {
|
||||
owner: string
|
||||
repo: string
|
||||
host?: string
|
||||
number: number
|
||||
/** null clears the issue type. */
|
||||
issueTypeId: string | null
|
||||
}
|
||||
|
||||
export type ResolveProjectRefArgs = WakeWslDistroArg & {
|
||||
input: string
|
||||
host?: string
|
||||
}
|
||||
|
||||
export type ListProjectViewsArgs = WakeWslDistroArg & {
|
||||
owner: string
|
||||
ownerType: GitHubProjectOwnerType
|
||||
projectNumber: number
|
||||
host?: string
|
||||
}
|
||||
|
||||
export type ListAccessibleProjectsArgs = WakeWslDistroArg & {
|
||||
/** GitHub host (e.g. GHES); absent means github.com. */
|
||||
host?: string
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Project IPC envelopes share classified failures and cross-module work-item/comment/user types unnecessary in the ProjectV2 domain model.
|
||||
import type { PRComment } from '../comments/comment-types'
|
||||
import type {
|
||||
GitHubIssueType,
|
||||
GitHubProjectOwnerType,
|
||||
GitHubProjectSummary,
|
||||
GitHubProjectTable,
|
||||
GitHubProjectViewSummary
|
||||
} from './project-types'
|
||||
import type { GitHubAssignableUser } from '../pull-requests/pull-request-types'
|
||||
import type { GitHubWorkItemDetails } from '../work-items/work-item-types'
|
||||
|
||||
export type GitHubProjectViewErrorType =
|
||||
| 'auth_required'
|
||||
| 'scope_missing'
|
||||
| 'not_found'
|
||||
| 'unsupported_layout'
|
||||
| 'too_large'
|
||||
| 'schema_drift'
|
||||
| 'validation_error'
|
||||
| 'network_error'
|
||||
| 'rate_limited'
|
||||
| 'unknown'
|
||||
|
||||
/** Distinguishes Orca-authored sentences that share one `type`; renderers fall back to `message` for unknown or missing reasons. */
|
||||
export type GitHubProjectViewErrorReason =
|
||||
| 'project_or_view_not_found'
|
||||
| 'project_not_found'
|
||||
| 'view_not_found'
|
||||
| 'owner_not_found'
|
||||
| 'item_not_found'
|
||||
| 'issue_not_found'
|
||||
| 'input_required'
|
||||
| 'input_too_large'
|
||||
| 'input_unparseable'
|
||||
| 'invalid_slug'
|
||||
| 'invalid_positive_integer'
|
||||
| 'invalid_owner_type'
|
||||
| 'invalid_item_type'
|
||||
| 'missing_ids'
|
||||
| 'updates_required'
|
||||
| 'comment_body_required'
|
||||
| 'duplicate_target_not_allowed'
|
||||
| 'duplicate_target_required'
|
||||
| 'request_invalid'
|
||||
| 'request_failed'
|
||||
| 'unexpected_rest_response'
|
||||
|
||||
export type GitHubProjectViewError = {
|
||||
type: GitHubProjectViewErrorType
|
||||
/** English copy kept for mobile, older clients and logs. */
|
||||
message: string
|
||||
reason?: GitHubProjectViewErrorReason
|
||||
/** GitHub host for sign-in commands. */
|
||||
host?: string
|
||||
rateLimit?: { remaining: number; limit: number; resetMinutes: number }
|
||||
/** Untranslated diagnostic or field name that follows Orca's own prefix. */
|
||||
detail?: string
|
||||
/** Rejected slug value for `invalid_slug`. */
|
||||
value?: string
|
||||
/** Classified GraphQL details only; never include tokens or full command stdout. */
|
||||
details?: { path?: (string | number)[]; code?: string }
|
||||
}
|
||||
|
||||
export type GetProjectViewTableResult =
|
||||
| { ok: true; data: GitHubProjectTable }
|
||||
| {
|
||||
ok: false
|
||||
error: GitHubProjectViewError
|
||||
/** Populated for the `too_large` case and best-effort for
|
||||
* `unsupported_layout` when a cheap count-only query succeeds. */
|
||||
totalCount?: number
|
||||
}
|
||||
|
||||
export type ListAccessibleProjectsResult =
|
||||
| {
|
||||
ok: true
|
||||
projects: GitHubProjectSummary[]
|
||||
/** Org discovery can partially fail; name failed owners so the picker can show incompleteness and accept pasted URLs for missing projects. */
|
||||
partialFailures?: { owner: string; message: string }[]
|
||||
}
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
|
||||
export type ResolveProjectRefResult =
|
||||
| {
|
||||
ok: true
|
||||
owner: string
|
||||
ownerType: GitHubProjectOwnerType
|
||||
number: number
|
||||
title: string
|
||||
host?: string
|
||||
// Parsed /views/{n} lets the picker commit directly; absent for shorthand and plain project URLs.
|
||||
viewNumber?: number
|
||||
}
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
|
||||
export type ListProjectViewsResult =
|
||||
| { ok: true; views: GitHubProjectViewSummary[] }
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
|
||||
export type ProjectWorkItemDetailsBySlugResult =
|
||||
| { ok: true; details: GitHubWorkItemDetails }
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
|
||||
export type GitHubProjectMutationResult =
|
||||
| { ok: true; bodyImageUrls?: Record<string, string> }
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
|
||||
export type GitHubProjectCommentMutationResult =
|
||||
| { ok: true; comment: PRComment }
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
|
||||
export type ListLabelsBySlugResult =
|
||||
| { ok: true; labels: string[] }
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
|
||||
export type ListAssignableUsersBySlugResult =
|
||||
| { ok: true; users: GitHubAssignableUser[] }
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
|
||||
export type ListIssueTypesBySlugResult =
|
||||
| { ok: true; types: GitHubIssueType[] }
|
||||
| { ok: false; error: GitHubProjectViewError }
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildRoadmapTicks, parseRoadmapDate, type RoadmapSpan } from './project-roadmap-timeline'
|
||||
|
||||
const utc = (iso: string): number => Date.parse(`${iso}T00:00:00Z`)
|
||||
|
||||
describe('parseRoadmapDate', () => {
|
||||
it('rejects invalid calendar dates instead of letting Date.UTC normalize them', () => {
|
||||
expect(parseRoadmapDate('2026-02-30')).toBeNull()
|
||||
expect(parseRoadmapDate('2026-13-01')).toBeNull()
|
||||
expect(parseRoadmapDate('2026-04-31')).toBeNull()
|
||||
expect(parseRoadmapDate('2024-02-29')).toBe(Date.parse('2024-02-29T00:00:00Z'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRoadmapTicks', () => {
|
||||
const span = (from: string, to: string): RoadmapSpan => ({
|
||||
startMs: utc(from),
|
||||
endMs: utc(to),
|
||||
point: false
|
||||
})
|
||||
|
||||
it('caps the grid instead of expanding for a far-future date, keeping today visible', () => {
|
||||
const today = utc('2026-03-15')
|
||||
const ticks = buildRoadmapTicks([span('2026-03-02', '9999-01-01')], 'month', today)
|
||||
expect(ticks).toHaveLength(480)
|
||||
expect(ticks[0]!.startMs).toBeLessThanOrEqual(today)
|
||||
expect(ticks.at(-1)!.endMs).toBeGreaterThan(today)
|
||||
})
|
||||
|
||||
it('caps the grid for a far-past date without pushing today off the edge', () => {
|
||||
const today = utc('2026-03-15')
|
||||
const ticks = buildRoadmapTicks([span('0206-03-02', '0206-03-10')], 'month', today)
|
||||
expect(ticks).toHaveLength(480)
|
||||
expect(ticks[0]!.startMs).toBeLessThanOrEqual(today)
|
||||
expect(ticks.at(-1)!.endMs).toBeGreaterThan(today)
|
||||
// One month of trailing padding after today survives the trim.
|
||||
expect(ticks.at(-1)!.endMs).toBe(utc('2026-05-01'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,280 @@
|
||||
// GraphQL ProjectV2View omits roadmap date configuration; derive placement from fields here for consistent, testable desktop/mobile bars.
|
||||
import type { GitHubProjectField, GitHubProjectRow, GitHubProjectView } from './project-types'
|
||||
|
||||
export const ROADMAP_DAY_MS = 86_400_000
|
||||
|
||||
export type RoadmapZoom = 'month' | 'quarter' | 'year'
|
||||
|
||||
export type RoadmapDateSource =
|
||||
| { kind: 'date-range'; startField: GitHubProjectField; targetField: GitHubProjectField }
|
||||
| { kind: 'date-point'; field: GitHubProjectField }
|
||||
| { kind: 'iteration'; field: GitHubProjectField }
|
||||
|
||||
export type RoadmapSpan = {
|
||||
startMs: number
|
||||
/** Exclusive — a single-day item ends one day after it starts. */
|
||||
endMs: number
|
||||
/** True when only one date was known, so the bar renders as a marker. */
|
||||
point: boolean
|
||||
}
|
||||
|
||||
export type RoadmapTick = {
|
||||
key: string
|
||||
startMs: number
|
||||
/** Exclusive. */
|
||||
endMs: number
|
||||
}
|
||||
|
||||
const START_FIELD_PATTERN = /start|kick.?off|begin/i
|
||||
const TARGET_FIELD_PATTERN = /target|end|due|finish|complet|deadline|ship/i
|
||||
|
||||
const MONTHS_PER_UNIT: Record<RoadmapZoom, number> = { month: 1, quarter: 3, year: 12 }
|
||||
const MIN_UNITS: Record<RoadmapZoom, number> = { month: 6, quarter: 4, year: 3 }
|
||||
// Cap typo-driven date ranges to avoid huge grids; out-of-range bars clamp visibly instead of hanging.
|
||||
const MAX_TICKS = 480
|
||||
|
||||
function isDateField(field: GitHubProjectField): boolean {
|
||||
return field.kind === 'field' && field.dataType === 'DATE'
|
||||
}
|
||||
|
||||
function pickDateSource(
|
||||
dateFields: GitHubProjectField[],
|
||||
iterationField: GitHubProjectField | null
|
||||
): RoadmapDateSource | null {
|
||||
const startField = dateFields.find((field) => START_FIELD_PATTERN.test(field.name))
|
||||
const targetField = dateFields.find(
|
||||
(field) => field.id !== startField?.id && TARGET_FIELD_PATTERN.test(field.name)
|
||||
)
|
||||
if (startField && targetField) {
|
||||
return { kind: 'date-range', startField, targetField }
|
||||
}
|
||||
// Keep a singly matched date field in its role; plain field order could invert start/target.
|
||||
if (startField) {
|
||||
const other = dateFields.find((field) => field.id !== startField.id)
|
||||
if (other) {
|
||||
return { kind: 'date-range', startField, targetField: other }
|
||||
}
|
||||
}
|
||||
if (targetField) {
|
||||
const other = dateFields.find((field) => field.id !== targetField.id)
|
||||
if (other) {
|
||||
return { kind: 'date-range', startField: other, targetField }
|
||||
}
|
||||
}
|
||||
const [first, second] = dateFields
|
||||
// Fallback to view field order for localized/unusual names instead of degrading ranges to markers.
|
||||
if (first && second) {
|
||||
return { kind: 'date-range', startField: first, targetField: second }
|
||||
}
|
||||
if (iterationField) {
|
||||
return { kind: 'iteration', field: iterationField }
|
||||
}
|
||||
if (first) {
|
||||
return { kind: 'date-point', field: first }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function resolveRoadmapDateSource(
|
||||
view: GitHubProjectView,
|
||||
rows: readonly GitHubProjectRow[] = []
|
||||
): RoadmapDateSource | null {
|
||||
// Placement fields can be hidden; sort/group fields provide secondary configuration evidence.
|
||||
const seen = new Set<string>()
|
||||
const candidates: GitHubProjectField[] = []
|
||||
for (const field of [
|
||||
...view.fields,
|
||||
...view.sortByFields.map((sort) => sort.field),
|
||||
...view.groupByFields
|
||||
]) {
|
||||
if (!seen.has(field.id)) {
|
||||
seen.add(field.id)
|
||||
candidates.push(field)
|
||||
}
|
||||
}
|
||||
const fromConfig = pickDateSource(
|
||||
candidates.filter(isDateField),
|
||||
candidates.find((field) => field.kind === 'iteration') ?? null
|
||||
)
|
||||
// Row values may supply dates even when view configuration exposes no placement fields.
|
||||
return fromConfig ?? pickDateSource(...collectRowPlacementFields(rows))
|
||||
}
|
||||
|
||||
function collectRowPlacementFields(
|
||||
rows: readonly GitHubProjectRow[]
|
||||
): [GitHubProjectField[], GitHubProjectField | null] {
|
||||
const dateFieldsById = new Map<string, GitHubProjectField>()
|
||||
let iterationField: GitHubProjectField | null = null
|
||||
for (const row of rows) {
|
||||
for (const value of Object.values(row.fieldValuesByFieldId)) {
|
||||
if (value.kind === 'date' && !dateFieldsById.has(value.fieldId)) {
|
||||
dateFieldsById.set(value.fieldId, {
|
||||
kind: 'field',
|
||||
id: value.fieldId,
|
||||
name: value.fieldName ?? 'Date',
|
||||
dataType: 'DATE'
|
||||
})
|
||||
} else if (value.kind === 'iteration' && !iterationField) {
|
||||
iterationField = {
|
||||
kind: 'iteration',
|
||||
id: value.fieldId,
|
||||
name: value.fieldName ?? 'Iteration',
|
||||
dataType: 'ITERATION',
|
||||
iterations: []
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return [Array.from(dateFieldsById.values()), iterationField]
|
||||
}
|
||||
|
||||
/** Read GitHub YYYY-MM-DD dates, tolerating the date portion of full ISO timestamps. */
|
||||
export function parseRoadmapDate(value: string): number | null {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value)
|
||||
if (!match) {
|
||||
return null
|
||||
}
|
||||
const [, year, month, day] = match
|
||||
const ms = Date.UTC(Number(year), Number(month) - 1, Number(day))
|
||||
if (Number.isNaN(ms)) {
|
||||
return null
|
||||
}
|
||||
// Date.UTC normalizes overflow (Feb 30 → Mar 2); round-trip components to reject invalid dates.
|
||||
const roundTrip = new Date(ms)
|
||||
if (
|
||||
roundTrip.getUTCFullYear() !== Number(year) ||
|
||||
roundTrip.getUTCMonth() !== Number(month) - 1 ||
|
||||
roundTrip.getUTCDate() !== Number(day)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return ms
|
||||
}
|
||||
|
||||
function readDateValue(row: GitHubProjectRow, field: GitHubProjectField): number | null {
|
||||
const value = row.fieldValuesByFieldId[field.id]
|
||||
return value?.kind === 'date' ? parseRoadmapDate(value.date) : null
|
||||
}
|
||||
|
||||
export function getRoadmapSpan(
|
||||
row: GitHubProjectRow,
|
||||
source: RoadmapDateSource
|
||||
): RoadmapSpan | null {
|
||||
if (source.kind === 'iteration') {
|
||||
const value = row.fieldValuesByFieldId[source.field.id]
|
||||
if (value?.kind !== 'iteration') {
|
||||
return null
|
||||
}
|
||||
const startMs = parseRoadmapDate(value.startDate)
|
||||
if (startMs === null) {
|
||||
return null
|
||||
}
|
||||
const days = value.duration > 0 ? value.duration : 1
|
||||
return { startMs, endMs: startMs + days * ROADMAP_DAY_MS, point: false }
|
||||
}
|
||||
if (source.kind === 'date-point') {
|
||||
const ms = readDateValue(row, source.field)
|
||||
return ms === null ? null : { startMs: ms, endMs: ms + ROADMAP_DAY_MS, point: true }
|
||||
}
|
||||
const startValue = readDateValue(row, source.startField)
|
||||
const targetValue = readDateValue(row, source.targetField)
|
||||
if (startValue === null || targetValue === null) {
|
||||
const known = startValue ?? targetValue
|
||||
return known === null ? null : { startMs: known, endMs: known + ROADMAP_DAY_MS, point: true }
|
||||
}
|
||||
// Reversed dates are user data; order them so the item retains a bar.
|
||||
return {
|
||||
startMs: Math.min(startValue, targetValue),
|
||||
endMs: Math.max(startValue, targetValue) + ROADMAP_DAY_MS,
|
||||
point: false
|
||||
}
|
||||
}
|
||||
|
||||
function unitIndexOf(ms: number, zoom: RoadmapZoom): number {
|
||||
const date = new Date(ms)
|
||||
return Math.floor((date.getUTCFullYear() * 12 + date.getUTCMonth()) / MONTHS_PER_UNIT[zoom])
|
||||
}
|
||||
|
||||
function unitStart(index: number, zoom: RoadmapZoom): number {
|
||||
const months = index * MONTHS_PER_UNIT[zoom]
|
||||
return Date.UTC(Math.floor(months / 12), months % 12, 1)
|
||||
}
|
||||
|
||||
/** Cover spans and today, with one unit of padding per side and a readable minimum width. */
|
||||
export function buildRoadmapTicks(
|
||||
spans: readonly RoadmapSpan[],
|
||||
zoom: RoadmapZoom,
|
||||
todayMs: number
|
||||
): RoadmapTick[] {
|
||||
let earliest = todayMs
|
||||
let latest = todayMs
|
||||
for (const span of spans) {
|
||||
earliest = Math.min(earliest, span.startMs)
|
||||
latest = Math.max(latest, span.endMs)
|
||||
}
|
||||
let firstIdx = unitIndexOf(earliest, zoom) - 1
|
||||
// Exclusive span ends on unit boundaries belong to the previous tick; subtract before computing trailing padding.
|
||||
let lastIdxExclusive = unitIndexOf(latest - 1, zoom) + 2
|
||||
if (lastIdxExclusive - firstIdx < MIN_UNITS[zoom]) {
|
||||
lastIdxExclusive = firstIdx + MIN_UNITS[zoom]
|
||||
}
|
||||
// Keep today within the capped grid; trim the farther side first so one typo cannot consume all columns.
|
||||
if (lastIdxExclusive - firstIdx > MAX_TICKS) {
|
||||
const todayIdx = unitIndexOf(todayMs, zoom)
|
||||
firstIdx = Math.max(firstIdx, todayIdx + 2 - MAX_TICKS)
|
||||
lastIdxExclusive = Math.min(lastIdxExclusive, firstIdx + MAX_TICKS)
|
||||
}
|
||||
const ticks: RoadmapTick[] = []
|
||||
for (let index = firstIdx; index < lastIdxExclusive; index++) {
|
||||
const startMs = unitStart(index, zoom)
|
||||
ticks.push({
|
||||
key: new Date(startMs).toISOString().slice(0, 10),
|
||||
startMs,
|
||||
endMs: unitStart(index + 1, zoom)
|
||||
})
|
||||
}
|
||||
return ticks
|
||||
}
|
||||
|
||||
/** Interpolate inside each tick to align bar edges despite unequal month lengths. */
|
||||
export function roadmapOffsetPx(
|
||||
ms: number,
|
||||
ticks: readonly RoadmapTick[],
|
||||
tickWidthPx: number
|
||||
): number {
|
||||
const first = ticks[0]
|
||||
const last = ticks.at(-1)
|
||||
if (!first || !last) {
|
||||
return 0
|
||||
}
|
||||
if (ms <= first.startMs) {
|
||||
return 0
|
||||
}
|
||||
if (ms >= last.endMs) {
|
||||
return ticks.length * tickWidthPx
|
||||
}
|
||||
let low = 0
|
||||
let high = ticks.length - 1
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1
|
||||
const tick = ticks[mid]
|
||||
if (tick && ms >= tick.endMs) {
|
||||
low = mid + 1
|
||||
} else {
|
||||
high = mid
|
||||
}
|
||||
}
|
||||
const tick = ticks[low]
|
||||
if (!tick) {
|
||||
return 0
|
||||
}
|
||||
const ratio = (ms - tick.startMs) / (tick.endMs - tick.startMs)
|
||||
return (low + ratio) * tickWidthPx
|
||||
}
|
||||
|
||||
export function roadmapSourceFieldNames(source: RoadmapDateSource): string[] {
|
||||
if (source.kind === 'date-range') {
|
||||
return [source.startField.name, source.targetField.name]
|
||||
}
|
||||
return [source.field.name]
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// Import ProjectV2 shapes directly; re-exporting through issue/PR types.ts obscures Project ownership.
|
||||
|
||||
export type GitHubProjectViewLayout = 'TABLE_LAYOUT' | 'BOARD_LAYOUT' | 'ROADMAP_LAYOUT'
|
||||
|
||||
/** One layout allowlist serves host/tab/picker gates; unchecked raw.layout must reject unknown future values consistently. */
|
||||
export function isRenderableProjectViewLayout(layout: string): boolean {
|
||||
return layout === 'TABLE_LAYOUT' || layout === 'BOARD_LAYOUT' || layout === 'ROADMAP_LAYOUT'
|
||||
}
|
||||
export type GitHubProjectOwnerType = 'organization' | 'user'
|
||||
|
||||
// Unknown data types render empty, never throw; string & {} preserves unknown wire values while retaining known discriminants.
|
||||
export type GitHubProjectFieldDataType =
|
||||
| 'TITLE'
|
||||
| 'ASSIGNEES'
|
||||
| 'LABELS'
|
||||
| 'LINKED_PULL_REQUESTS'
|
||||
| 'REVIEWERS'
|
||||
| 'REPOSITORY'
|
||||
| 'MILESTONE'
|
||||
| 'PARENT_ISSUE'
|
||||
| 'SUB_ISSUES_PROGRESS'
|
||||
| 'TRACKS'
|
||||
| 'TRACKED_BY'
|
||||
| 'ISSUE_TYPE'
|
||||
| 'TEXT'
|
||||
| 'NUMBER'
|
||||
| 'DATE'
|
||||
| 'SINGLE_SELECT'
|
||||
| 'ITERATION'
|
||||
|
||||
export type GitHubProjectSingleSelectOption = {
|
||||
id: string
|
||||
name: string
|
||||
color: string
|
||||
}
|
||||
|
||||
export type GitHubProjectIteration = {
|
||||
id: string
|
||||
title: string
|
||||
/** YYYY-MM-DD — GitHub returns a calendar date, not an ISO timestamp. */
|
||||
startDate: string
|
||||
/** Length in days. */
|
||||
duration: number
|
||||
/** True when GitHub returned this iteration under `completedIterations`. */
|
||||
completed: boolean
|
||||
}
|
||||
|
||||
export type GitHubProjectField =
|
||||
| {
|
||||
kind: 'field'
|
||||
id: string
|
||||
name: string
|
||||
dataType: Exclude<GitHubProjectFieldDataType, 'SINGLE_SELECT' | 'ITERATION'> | (string & {})
|
||||
}
|
||||
| {
|
||||
kind: 'single-select'
|
||||
id: string
|
||||
name: string
|
||||
dataType: 'SINGLE_SELECT'
|
||||
options: GitHubProjectSingleSelectOption[]
|
||||
}
|
||||
| {
|
||||
kind: 'iteration'
|
||||
id: string
|
||||
name: string
|
||||
dataType: 'ITERATION'
|
||||
iterations: GitHubProjectIteration[]
|
||||
}
|
||||
|
||||
export type GitHubProjectSortDirection = 'ASC' | 'DESC'
|
||||
|
||||
export type GitHubProjectSort = {
|
||||
direction: GitHubProjectSortDirection
|
||||
field: GitHubProjectField
|
||||
}
|
||||
|
||||
export type GitHubProjectView = {
|
||||
id: string
|
||||
number: number
|
||||
name: string
|
||||
layout: GitHubProjectViewLayout
|
||||
/** Null normalizes to empty: ProjectV2.items(query:) defaults to empty, equivalent to omitting query. Empty signals unfiltered UI; no separate non-search field exists. */
|
||||
filter: string
|
||||
fields: GitHubProjectField[]
|
||||
groupByFields: GitHubProjectField[]
|
||||
sortByFields: GitHubProjectSort[]
|
||||
/** Optional for older hosts/GHES schemas lacking verticalGroupByFields. */
|
||||
verticalGroupByFields?: GitHubProjectField[]
|
||||
}
|
||||
|
||||
export type GitHubProjectUser = {
|
||||
login: string
|
||||
name: string | null
|
||||
avatarUrl: string | null
|
||||
}
|
||||
|
||||
export type GitHubProjectLabel = {
|
||||
name: string
|
||||
color: string
|
||||
}
|
||||
|
||||
export type GitHubProjectParentIssue = {
|
||||
number: number
|
||||
title: string
|
||||
url: string
|
||||
}
|
||||
|
||||
// Opted-in repos expose Issue Types; carry id/name/color so pickers and cells reflect changes without refetching.
|
||||
export type GitHubIssueType = {
|
||||
id: string
|
||||
name: string
|
||||
color: string | null
|
||||
description: string | null
|
||||
}
|
||||
|
||||
export type GitHubProjectLinkedPullRequests = {
|
||||
pullRequests: { number: number; title: string; url: string }[]
|
||||
totalCount: number
|
||||
}
|
||||
|
||||
export type GitHubProjectFieldValue =
|
||||
| {
|
||||
kind: 'single-select'
|
||||
fieldId: string
|
||||
optionId: string
|
||||
name: string
|
||||
color: string
|
||||
}
|
||||
| {
|
||||
kind: 'iteration'
|
||||
fieldId: string
|
||||
iterationId: string
|
||||
title: string
|
||||
startDate: string
|
||||
duration: number
|
||||
/** Owning field label for fields hidden in view config; older hosts omit it. */
|
||||
fieldName?: string
|
||||
}
|
||||
| { kind: 'text'; fieldId: string; text: string }
|
||||
| { kind: 'number'; fieldId: string; number: number }
|
||||
| { kind: 'date'; fieldId: string; date: string; fieldName?: string }
|
||||
| { kind: 'labels'; fieldId: string; labels: GitHubProjectLabel[] }
|
||||
| { kind: 'users'; fieldId: string; users: GitHubProjectUser[] }
|
||||
|
||||
export type GitHubProjectRowItemType = 'ISSUE' | 'PULL_REQUEST' | 'DRAFT_ISSUE' | 'REDACTED'
|
||||
|
||||
export type GitHubProjectRow = {
|
||||
id: string
|
||||
itemType: GitHubProjectRowItemType
|
||||
content: {
|
||||
number: number | null
|
||||
title: string
|
||||
/** DraftIssue body and optional detail-cache patch target; list rows do
|
||||
* not render issue/PR body. */
|
||||
body: string | null
|
||||
url: string | null
|
||||
state: string | null
|
||||
/** Issue-only stateReason distinguishes closed-as-not-planned glyphs; null for PRs/drafts. */
|
||||
stateReason: string | null
|
||||
/** PullRequest.isDraft; null otherwise. */
|
||||
isDraft: boolean | null
|
||||
/** nameWithOwner, e.g. 'stablyai/orca'. */
|
||||
repository: string | null
|
||||
assignees: GitHubProjectUser[]
|
||||
labels: GitHubProjectLabel[]
|
||||
parentIssue: GitHubProjectParentIssue | null
|
||||
linkedPullRequests?: GitHubProjectLinkedPullRequests | null
|
||||
/** Present when the ProjectV2Item content is an Issue and GitHub returned its summary. */
|
||||
subIssuesProgress?: { completed: number; total: number; percentCompleted: number } | null
|
||||
/** Issue.issueType when set; null on PRs/drafts/redacted or when unset. */
|
||||
issueType: GitHubIssueType | null
|
||||
}
|
||||
fieldValuesByFieldId: Record<string, GitHubProjectFieldValue>
|
||||
updatedAt: string
|
||||
/** Zero-based fully paginated POSITION ASC order; final tie-break preserves GitHub rank. */
|
||||
position: number
|
||||
}
|
||||
|
||||
export type GitHubProjectTable = {
|
||||
project: {
|
||||
id: string
|
||||
host?: string
|
||||
owner: string
|
||||
ownerType: GitHubProjectOwnerType
|
||||
number: number
|
||||
title: string
|
||||
url: string
|
||||
}
|
||||
selectedView: GitHubProjectView
|
||||
rows: GitHubProjectRow[]
|
||||
/** Echoes ProjectV2.items.totalCount for the view filter. */
|
||||
totalCount: number
|
||||
/** True after parent-field fallback; permits a sub-issues-unavailable hint without a hard error. */
|
||||
parentFieldDropped: boolean
|
||||
}
|
||||
|
||||
export type GitHubProjectSummary = {
|
||||
id: string
|
||||
host?: string
|
||||
owner: string
|
||||
ownerType: GitHubProjectOwnerType
|
||||
number: number
|
||||
title: string
|
||||
url: string
|
||||
source: 'viewer' | `org:${string}`
|
||||
}
|
||||
|
||||
export type GitHubProjectViewSummary = {
|
||||
id: string
|
||||
number: number
|
||||
name: string
|
||||
layout: GitHubProjectViewLayout
|
||||
}
|
||||
|
||||
export type GitHubProjectSettings = {
|
||||
pinned: { owner: string; ownerType: GitHubProjectOwnerType; number: number; host?: string }[]
|
||||
recent: {
|
||||
owner: string
|
||||
ownerType: GitHubProjectOwnerType
|
||||
number: number
|
||||
host?: string
|
||||
lastOpenedAt: string
|
||||
}[]
|
||||
lastViewByProject: Record<string, { viewId: string }>
|
||||
activeProject: {
|
||||
owner: string
|
||||
ownerType: GitHubProjectOwnerType
|
||||
number: number
|
||||
host?: string
|
||||
} | null
|
||||
}
|
||||
|
||||
export type GitHubProjectFieldMutationValue =
|
||||
| { kind: 'single-select'; optionId: string }
|
||||
| { kind: 'iteration'; iterationId: string }
|
||||
| { kind: 'text'; text: string }
|
||||
| { kind: 'number'; number: number }
|
||||
/** YYYY-MM-DD. */
|
||||
| { kind: 'date'; date: string }
|
||||
Reference in New Issue
Block a user