UIPackage React Native
Search

Task Queue

A native task inbox with overdue, today, upcoming, and unscheduled groups, open and completed views, priority labels, and completion with undo.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add task-queue

Source files

Expand a file to read the source the installer copies into your app.

components/blocks/task-queue/TaskQueue.tsx
import * as React from 'react'
import { AppState, SectionList, View, type ViewProps } from 'react-native'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { ListItem, ListItemContent, ListItemDescription, ListItemTitle, ListSeparator } from '@/components/ui/list'
import { SegmentedControl, SegmentedControlItem } from '@/components/ui/segmented-control'
import { Text } from '@/components/ui/text'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'

export interface TaskQueueEntry {
  id: string
  title: string
  project?: string
  /** Unix timestamp in milliseconds. Deadlines use local calendar days. */
  dueAt?: number
  priority?: 'normal' | 'high'
  completed?: boolean
}

const labels = {
  open: 'Open',
  completed: 'Completed',
  overdue: 'Overdue',
  today: 'Today',
  upcoming: 'Upcoming',
  unscheduled: 'No due date',
  highPriority: 'High priority',
  emptyOpen: 'No open tasks',
  emptyCompleted: 'No completed tasks',
  completedNotice: 'Task completed',
  undo: 'Undo',
  completeHint: 'Mark this task complete',
  reopenHint: 'Move this task back to Open',
  dueDate: (date: string) => `Due ${date}`,
}

export interface TaskQueueProps extends ViewProps {
  className?: string
  /**
   * Controlled tasks. Omit to try an interactive sample. The caller owns
   * persistence and can pass an empty array to show a real empty state.
   */
  tasks?: readonly TaskQueueEntry[]
  /** Adds content above the task views inside the list's scroll area. */
  header?: React.ReactNode
  locale?: string
  labels?: Partial<typeof labels>
  /** Reference time for due dates. Defaults to the current local day. */
  now?: number
  /** With controlled tasks, update the matching task in response to this intent. */
  onTaskCompletionChange?: (id: string, completed: boolean) => void
}

type OpenGroup = 'overdue' | 'today' | 'upcoming' | 'unscheduled'
type TaskView = 'open' | 'completed'

const groupOrder: OpenGroup[] = ['overdue', 'today', 'upcoming', 'unscheduled']

function validDeadline(value: number | undefined) {
  return value !== undefined && Number.isFinite(new Date(value).getTime()) ? value : undefined
}

function dayStart(time: number, offset = 0) {
  const date = new Date(time)
  if (offset) date.setDate(date.getDate() + offset)
  return date.setHours(0, 0, 0, 0)
}

function useTaskDay(now: number | undefined) {
  const [localDay, setLocalDay] = React.useState(() => dayStart(Date.now()))
  const liveClock = now === undefined

  React.useEffect(() => {
    if (!liveClock) return
    let timer: ReturnType<typeof setTimeout> | undefined
    function refresh() {
      clearTimeout(timer)
      const time = Date.now()
      setLocalDay(dayStart(time))
      timer = setTimeout(refresh, Math.max(1, dayStart(time, 1) - time))
    }
    refresh()
    const subscription = AppState.addEventListener('change', (state) => {
      if (state === 'active') refresh()
      else clearTimeout(timer)
    })
    return () => {
      clearTimeout(timer)
      subscription.remove()
    }
  }, [liveClock])

  return now === undefined ? localDay : dayStart(now)
}

function taskSections(entries: readonly TaskQueueEntry[], completed: boolean, now: number, copy: typeof labels) {
  if (completed) {
    const data = entries.filter((task) => task.completed)
    return data.length ? [{ key: 'completed', title: copy.completed, data }] : []
  }

  const tomorrow = dayStart(now, 1)
  const groups: Record<OpenGroup, TaskQueueEntry[]> = { overdue: [], today: [], upcoming: [], unscheduled: [] }
  for (const task of entries) {
    if (task.completed) continue
    const deadline = validDeadline(task.dueAt)
    const group =
      deadline === undefined ? 'unscheduled' : deadline < now ? 'overdue' : deadline < tomorrow ? 'today' : 'upcoming'
    groups[group].push(task)
  }

  return groupOrder
    .filter((key) => groups[key].length > 0)
    .map((key) => ({
      key,
      title: copy[key],
      data: groups[key].sort(
        (a, b) =>
          Number(b.priority === 'high') - Number(a.priority === 'high') ||
          (key === 'unscheduled' ? 0 : (a.dueAt ?? 0) - (b.dueAt ?? 0)),
      ),
    }))
}

export function TaskQueue({
  className,
  tasks,
  header,
  locale,
  labels: overrides,
  now,
  onTaskCompletionChange,
  ...props
}: TaskQueueProps) {
  const copy = React.useMemo(() => ({ ...labels, ...overrides }), [overrides])
  const [sample, setSample] = React.useState<readonly TaskQueueEntry[]>(() => [
    {
      id: 'sample-1',
      title: 'Check the signage proof',
      project: 'Studio opening',
      dueAt: now ?? Date.now(),
      priority: 'high',
    },
    { id: 'sample-2', title: 'Send the handover checklist', project: 'Studio opening' },
  ])
  const [view, setView] = React.useState<TaskView>('open')
  const [lastCompletedId, setLastCompletedId] = React.useState<string>()
  const entries = tasks ?? sample
  const canChange = tasks === undefined || !!onTaskCompletionChange
  const lastCompleted = canChange && entries.find((task) => task.id === lastCompletedId && task.completed)
  useAnnouncement(lastCompleted ? `${lastCompleted.title}. ${copy.completedNotice}.` : undefined)
  const dateFormat = React.useMemo(() => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }), [locale])
  const today = useTaskDay(now)
  const sections = React.useMemo(
    () => taskSections(entries, view === 'completed', today, copy),
    [entries, view, today, copy],
  )

  function changeCompletion(task: TaskQueueEntry, completed: boolean) {
    if (!canChange || !!task.completed === completed) return
    if (tasks === undefined) {
      setSample((current) => current.map((entry) => (entry.id === task.id ? { ...entry, completed } : entry)))
    }
    setLastCompletedId(completed ? task.id : undefined)
    onTaskCompletionChange?.(task.id, completed)
  }

  return (
    <View {...props} className={cn('min-h-0 flex-1 bg-background', className)}>
      <SectionList
        sections={sections}
        keyExtractor={(task) => task.id}
        stickySectionHeadersEnabled={false}
        contentContainerStyle={{ paddingBottom: 16 }}
        ListHeaderComponent={
          <View className="gap-3 pb-3">
            {header}
            <SegmentedControl
              value={view}
              onValueChange={(value) => {
                if (value !== 'open' && value !== 'completed') return
                setView(value)
                setLastCompletedId(undefined)
              }}
            >
              <SegmentedControlItem value="open">{copy.open}</SegmentedControlItem>
              <SegmentedControlItem value="completed">{copy.completed}</SegmentedControlItem>
            </SegmentedControl>
          </View>
        }
        ListEmptyComponent={
          <View className="items-center rounded-xl border border-border px-4 py-8">
            <Text className="text-center font-semibold">{view === 'open' ? copy.emptyOpen : copy.emptyCompleted}</Text>
          </View>
        }
        renderSectionHeader={({ section }) =>
          view === 'open' ? (
            <Text
              size="sm"
              accessibilityRole="header"
              className={cn(
                'border-b border-border pb-2 pt-4 font-semibold',
                section.key === 'overdue' && 'text-destructive',
              )}
            >
              {section.title}
            </Text>
          ) : null
        }
        ItemSeparatorComponent={ListSeparator}
        renderItem={({ item }) => {
          const checked = !!item.completed
          const timestamp = validDeadline(item.dueAt)
          const dueDate = timestamp !== undefined ? copy.dueDate(dateFormat.format(timestamp)) : undefined
          const highPriority = item.priority === 'high'
          return (
            <ListItem
              accessible
              accessibilityRole={canChange ? 'checkbox' : undefined}
              accessibilityLabel={[
                item.title,
                item.project,
                dueDate,
                highPriority && copy.highPriority,
                !canChange && checked && copy.completed,
              ]
                .filter(Boolean)
                .join(', ')}
              accessibilityState={canChange ? { checked } : undefined}
              accessibilityHint={canChange ? (checked ? copy.reopenHint : copy.completeHint) : undefined}
              onPress={canChange ? () => changeCompletion(item, !checked) : undefined}
              className="items-start gap-1 px-0"
            >
              {canChange ? (
                <Checkbox
                  className="-ms-2"
                  aria-hidden
                  pointerEvents="none"
                  focusable={false}
                  tabIndex={-1}
                  checked={checked}
                />
              ) : null}
              <ListItemContent className="py-1">
                <ListItemTitle>{item.title}</ListItemTitle>
                {item.project ? <ListItemDescription>{item.project}</ListItemDescription> : null}
                {dueDate || highPriority ? (
                  <View className="flex-row flex-wrap items-center gap-2">
                    {dueDate ? (
                      <Text size="xs" variant="muted">
                        {dueDate}
                      </Text>
                    ) : null}
                    {highPriority ? <Badge variant="warning" text={copy.highPriority} /> : null}
                  </View>
                ) : null}
              </ListItemContent>
            </ListItem>
          )
        }}
      />
      {lastCompleted ? (
        <View className="flex-row flex-wrap items-center justify-between gap-2 border-t border-border py-1">
          <Text size="sm" className="min-w-0 shrink font-medium">
            {copy.completedNotice}
          </Text>
          <Button variant="ghost" accessibilityLabel={copy.undo} onPress={() => changeCompletion(lastCompleted, false)}>
            {copy.undo}
          </Button>
        </View>
      ) : null}
    </View>
  )
}
components/blocks/task-queue/index.ts
export { TaskQueue, type TaskQueueEntry, type TaskQueueProps } from './TaskQueue'

Dependencies

Browse work and productivity