@tc96/cli 0.27.0 → 0.28.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 +4 -4
- package/cli.js +82 -27
- package/package.json +1 -1
- package/registry/agenda-1.json +1297 -0
- package/registry/aggregate.json +1 -1
- package/registry/ai-chat-1.json +91 -0
- package/registry/checklist.json +21 -7
- package/registry/collection.json +624 -351
- package/registry/crm-1.json +1317 -0
- package/registry/crm-2.json +1400 -0
- package/registry/dashboard-5.json +167 -0
- package/registry/dashboard-6.json +143 -0
- package/registry/dashboard-7.json +188 -0
- package/registry/documents-1.json +1322 -0
- package/registry/finance-1.json +845 -0
- package/registry/finance-2.json +973 -0
- package/registry/finance-3.json +1436 -0
- package/registry/{workflow-editor.json → flow-1.json} +37 -37
- package/registry/{agent-builder.json → flow-2.json} +55 -55
- package/registry/{run-monitor.json → flow-3.json} +16 -16
- package/registry/{impact-map.json → flow-4.json} +16 -16
- package/registry/inbox-1.json +1184 -0
- package/registry/inventory-1.json +828 -0
- package/registry/inventory-2.json +956 -0
- package/registry/legal-1.json +1345 -0
- package/registry/legal-2.json +1279 -0
- package/registry/legal-3.json +1273 -0
- package/registry/legal-4.json +1273 -0
- package/registry/legal-5.json +1393 -0
- package/registry/legal-6.json +1309 -0
- package/registry/legal-7.json +1315 -0
- package/registry/legal-8.json +1358 -0
- package/registry/legal-9.json +1381 -0
- package/registry/marketing-1.json +833 -0
- package/registry/marketing-2.json +961 -0
- package/registry/navbar-1.json +6 -6
- package/registry/navbar-10.json +50 -0
- package/registry/navbar-11.json +48 -0
- package/registry/navbar-12.json +48 -0
- package/registry/navbar-6.json +48 -0
- package/registry/navbar-7.json +72 -0
- package/registry/navbar-8.json +50 -0
- package/registry/navbar-9.json +54 -0
- package/registry/projects-1.json +865 -0
- package/registry/projects-2.json +993 -0
- package/registry/projects-3.json +1346 -0
- package/registry/properties.json +65 -58
- package/registry/record-group.json +5 -1
- package/registry/revenue-1.json +834 -0
- package/registry/revenue-2.json +968 -0
- package/registry/revenue-3.json +821 -0
- package/registry/revenue-4.json +949 -0
- package/registry/rich-text-editor-1.json +172 -0
- package/registry/rich-text-editor-2.json +158 -0
- package/registry/rich-text-editor-3.json +198 -0
- package/registry/rich-text-editor-4.json +200 -0
- package/registry/rich-text-editor-5.json +237 -0
- package/registry/rich-text-editor.json +27 -7
- package/registry/{settings-1.json → settings-account-1.json} +17 -17
- package/registry/{settings-23.json → settings-account-2.json} +17 -17
- package/registry/{settings-7.json → settings-catalog-1.json} +17 -17
- package/registry/{settings-16.json → settings-catalog-10.json} +17 -17
- package/registry/{settings-8.json → settings-catalog-2.json} +17 -17
- package/registry/{settings-9.json → settings-catalog-3.json} +17 -17
- package/registry/{settings-10.json → settings-catalog-4.json} +29 -20
- package/registry/{settings-11.json → settings-catalog-5.json} +17 -17
- package/registry/{settings-12.json → settings-catalog-6.json} +17 -17
- package/registry/{settings-13.json → settings-catalog-7.json} +17 -17
- package/registry/{settings-14.json → settings-catalog-8.json} +29 -19
- package/registry/{settings-15.json → settings-catalog-9.json} +28 -18
- package/registry/{settings-19.json → settings-integration-1.json} +17 -17
- package/registry/settings-integration-2.json +122 -0
- package/registry/{settings-22.json → settings-integration-3.json} +17 -17
- package/registry/settings-integration-4.json +129 -0
- package/registry/settings-integration-5.json +122 -0
- package/registry/settings-integration-6.json +92 -0
- package/registry/{settings-21.json → settings-integration-7.json} +23 -17
- package/registry/settings-integration-8.json +593 -0
- package/registry/{settings-20.json → settings-notification-channel-1.json} +17 -17
- package/registry/{settings-2.json → settings-preference-1.json} +17 -17
- package/registry/{settings-3.json → settings-preference-2.json} +17 -17
- package/registry/{settings-4.json → settings-preference-3.json} +17 -17
- package/registry/{settings-18.json → settings-role-permission-1.json} +17 -17
- package/registry/{settings-17.json → settings-security-1.json} +17 -17
- package/registry/{settings-5.json → settings-workspace-1.json} +28 -28
- package/registry/{settings-6.json → settings-workspace-2.json} +31 -31
- package/registry/support-1.json +853 -0
- package/registry/support-2.json +981 -0
- package/registry/support-3.json +762 -0
- package/registry/support-4.json +538 -0
- package/registry/team-1.json +829 -0
- package/registry/team-2.json +957 -0
- package/registry/ui/gauge.json +1 -1
- package/registry/ui/menu.json +1 -1
- package/registry/ui/property-meta.json +16 -0
- package/registry/ui/property-tone.json +12 -0
- package/registry/ui/scroll-area.json +1 -1
- package/registry/ui/select.json +1 -1
- package/registry/view.json +624 -351
- package/registry/app-shell-5.json +0 -106
- package/registry/bulk-import-1.json +0 -151
- package/registry/collection-layouts.json +0 -836
- package/registry/collection-views.json +0 -836
- package/registry/detail-sheet.json +0 -54
- package/registry/icon-row.json +0 -52
- package/registry/lookup-create-1.json +0 -157
- package/registry/next-steps-1.json +0 -147
- package/registry/settings-shell.json +0 -60
|
@@ -1,836 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "collection-views",
|
|
3
|
-
"type": "registry:block",
|
|
4
|
-
"files": [
|
|
5
|
-
{
|
|
6
|
-
"path": "elements/src/icon-frame.tsx",
|
|
7
|
-
"type": "registry:file",
|
|
8
|
-
"content": "'use client'\n\nimport { mergeProps } from '@base-ui/react/merge-props'\nimport { useRender } from '@base-ui/react/use-render'\nimport { cn } from '@tc96/utils'\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport type * as React from 'react'\n\nexport const iconFrameVariants = cva(\n 'inline-flex shrink-0 items-center justify-center [&_svg]:shrink-0',\n {\n defaultVariants: {\n shape: 'circle',\n size: 'default',\n variant: 'color',\n },\n variants: {\n shape: {\n circle: 'rounded-full',\n rounded: 'rounded-lg',\n },\n size: {\n default: 'size-9 [&_svg:not([class*=size-])]:size-4.5',\n lg: 'size-11 [&_svg:not([class*=size-])]:size-5',\n xl: 'size-14 [&_svg:not([class*=size-])]:size-6',\n },\n variant: {\n color: 'bg-muted text-foreground',\n plain: 'bg-transparent text-foreground',\n },\n },\n },\n)\n\nexport const iconFrameShapes = ['circle', 'rounded'] as const\nexport type IconFrameShape = (typeof iconFrameShapes)[number]\nexport const iconFrameSizes = ['default', 'lg', 'xl'] as const\nexport type IconFrameSize = (typeof iconFrameSizes)[number]\nexport const iconFrameVariantNames = ['color', 'plain'] as const\nexport type IconFrameVariant = (typeof iconFrameVariantNames)[number]\n\ntype IconFrameVariantProps = VariantProps<typeof iconFrameVariants>\n\nexport interface IconFrameProps extends useRender.ComponentProps<'span'> {\n color?: string\n shape?: IconFrameShape\n size?: IconFrameSize\n variant?: IconFrameVariant\n}\n\nexport function iconFrameStyle(\n color: string | undefined,\n variant: IconFrameVariantProps['variant'],\n): React.CSSProperties | undefined {\n if (!color) return undefined\n return variant === 'plain'\n ? { color }\n : {\n backgroundColor: `color-mix(in srgb, ${color} 6%, transparent)`,\n color,\n }\n}\n\nexport function IconFrame({\n className,\n color,\n render,\n shape = 'circle',\n size = 'default',\n style,\n variant = 'color',\n ...props\n}: IconFrameProps): React.ReactElement {\n const defaultProps = {\n 'aria-hidden': true,\n className: cn(iconFrameVariants({ shape, size, variant }), className),\n 'data-shape': shape,\n 'data-size': size,\n 'data-slot': 'icon-frame',\n 'data-variant': variant,\n style: { ...iconFrameStyle(color, variant), ...style },\n }\n\n return useRender({\n defaultTagName: 'span',\n props: mergeProps<'span'>(defaultProps, props),\n render,\n })\n}\n",
|
|
9
|
-
"target": "~/packages/elements/src/icon-frame.tsx"
|
|
10
|
-
},
|
|
11
|
-
{
|
|
12
|
-
"path": "elements/src/text.tsx",
|
|
13
|
-
"type": "registry:file",
|
|
14
|
-
"content": "'use client'\n\nimport { mergeProps } from '@base-ui/react/merge-props'\nimport { useRender } from '@base-ui/react/use-render'\nimport { cn } from '@tc96/utils'\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport type * as React from 'react'\n\nexport const textVariants = cva('', {\n defaultVariants: {\n family: 'sans',\n foreground: 'base',\n size: 'base',\n weight: 'normal',\n },\n variants: {\n align: {\n center: 'text-center',\n end: 'text-end',\n justify: 'text-justify',\n left: 'text-left',\n right: 'text-right',\n start: 'text-start',\n },\n family: {\n heading: 'font-heading',\n mono: 'font-mono',\n sans: 'font-sans',\n },\n foreground: {\n base: 'text-foreground',\n destructive: 'text-destructive-foreground',\n inherit: 'text-inherit',\n muted: 'text-muted-foreground',\n },\n leading: {\n loose: 'leading-loose',\n none: 'leading-none',\n normal: 'leading-normal',\n relaxed: 'leading-relaxed',\n snug: 'leading-snug',\n tight: 'leading-tight',\n },\n size: {\n '2xl': 'text-2xl',\n '3xl': 'text-3xl',\n '4xl': 'text-4xl',\n '5xl': 'text-5xl',\n '6xl': 'text-6xl',\n '7xl': 'text-7xl',\n '8xl': 'text-8xl',\n base: 'text-base',\n lg: 'text-lg',\n sm: 'text-sm',\n xl: 'text-xl',\n xs: 'text-xs',\n },\n tracking: {\n normal: 'tracking-normal',\n tight: 'tracking-tight',\n tighter: 'tracking-tighter',\n wide: 'tracking-wide',\n wider: 'tracking-wider',\n widest: 'tracking-widest',\n },\n truncate: {\n true: 'truncate',\n },\n weight: {\n black: 'font-black',\n bold: 'font-bold',\n extrabold: 'font-extrabold',\n extralight: 'font-extralight',\n light: 'font-light',\n medium: 'font-medium',\n normal: 'font-normal',\n semibold: 'font-semibold',\n thin: 'font-thin',\n },\n },\n})\n\nexport const textSizes = [\n 'xs',\n 'sm',\n 'base',\n 'lg',\n 'xl',\n '2xl',\n '3xl',\n '4xl',\n '5xl',\n '6xl',\n '7xl',\n '8xl',\n] as const\nexport type TextSize = (typeof textSizes)[number]\n\ntype TextVariantProps = VariantProps<typeof textVariants>\n\nexport interface TextProps extends useRender.ComponentProps<'span'> {\n align?: TextVariantProps['align']\n family?: TextVariantProps['family']\n foreground?: TextVariantProps['foreground']\n leading?: TextVariantProps['leading']\n size?: TextSize\n tracking?: TextVariantProps['tracking']\n truncate?: TextVariantProps['truncate']\n weight?: TextVariantProps['weight']\n}\n\nexport function Text({\n align,\n className,\n family,\n foreground,\n leading,\n render,\n size,\n tracking,\n truncate,\n weight,\n ...props\n}: TextProps): React.ReactElement {\n const defaultProps = {\n className: cn(\n textVariants({\n align,\n family,\n foreground,\n leading,\n size,\n tracking,\n truncate,\n weight,\n }),\n className,\n ),\n 'data-slot': 'text',\n }\n\n return useRender({\n defaultTagName: 'span',\n props: mergeProps<'span'>(defaultProps, props),\n render,\n })\n}\n",
|
|
15
|
-
"target": "~/packages/elements/src/text.tsx"
|
|
16
|
-
},
|
|
17
|
-
{
|
|
18
|
-
"path": "helpers/src/calendar-date.ts",
|
|
19
|
-
"type": "registry:file",
|
|
20
|
-
"content": "/** Span of days {@link calendarRange} produces around an anchor date. */\nexport type CalendarRangeMode = 'day' | 'month' | 'week'\n\n/**\n * A calendar day with no time and no time zone attached. `month` runs from\n * 1 to 12.\n */\nexport interface CalendarDate {\n day: number\n month: number\n year: number\n}\n\nconst DATE_KEY_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/\n\n/**\n * Serializes a calendar date as `YYYY-MM-DD`, a stable key for maps and DOM\n * attributes.\n *\n * @param date - The calendar date to serialize.\n */\nexport function calendarDateKey(date: CalendarDate): string {\n const month = String(date.month).padStart(2, '0')\n const day = String(date.day).padStart(2, '0')\n\n return `${date.year}-${month}-${day}`\n}\n\n/**\n * Parses a `YYYY-MM-DD` key produced by {@link calendarDateKey}.\n *\n * @param key - The serialized date.\n * @returns The calendar date, or `null` when the text is malformed or names a\n * day that does not exist, such as February 30.\n */\nexport function parseCalendarDateKey(key: string): CalendarDate | null {\n const match = DATE_KEY_PATTERN.exec(key)\n if (!match) return null\n\n const candidate = {\n day: Number(match[3]),\n month: Number(match[2]),\n year: Number(match[1]),\n }\n\n return isSameCalendarDate(candidate, normalizeCalendarDate(candidate))\n ? candidate\n : null\n}\n\n/**\n * Reads the local calendar day of a `Date`, dropping its time.\n *\n * @param date - A valid date, such as the one a date picker selects.\n */\nexport function calendarDateFromDate(date: Date): CalendarDate {\n return {\n day: date.getDate(),\n month: date.getMonth() + 1,\n year: date.getFullYear(),\n }\n}\n\n/**\n * Builds the local midnight `Date` of a calendar date, the value a date\n * picker expects for a day.\n *\n * @param date - The calendar date to convert.\n */\nexport function calendarDateToDate(date: CalendarDate): Date {\n return new Date(date.year, date.month - 1, date.day)\n}\n\n/**\n * Moves a calendar date by a number of days, rolling over months and years.\n *\n * @param date - The starting date.\n * @param days - Days to add; negative values move backwards.\n */\nexport function addCalendarDays(\n date: CalendarDate,\n days: number,\n): CalendarDate {\n return normalizeCalendarDate({ ...date, day: date.day + days })\n}\n\n/**\n * Orders two calendar dates chronologically.\n *\n * @returns Negative when `a` is earlier, positive when later, zero when equal.\n */\nexport function compareCalendarDates(a: CalendarDate, b: CalendarDate): number {\n return a.year - b.year || a.month - b.month || a.day - b.day\n}\n\n/** Whether two calendar dates name the same day. */\nexport function isSameCalendarDate(a: CalendarDate, b: CalendarDate): boolean {\n return compareCalendarDates(a, b) === 0\n}\n\n/**\n * Day of the week of a calendar date.\n *\n * @returns `0` for Sunday through `6` for Saturday.\n */\nexport function calendarDayOfWeek(date: CalendarDate): number {\n return new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay()\n}\n\n/**\n * First day of the week that contains a calendar date.\n *\n * @param date - Any day of the week.\n * @param weekStartsOn - `0` when weeks start on Sunday, `1` on Monday.\n */\nexport function startOfWeek(\n date: CalendarDate,\n weekStartsOn: 0 | 1,\n): CalendarDate {\n const offset = (calendarDayOfWeek(date) - weekStartsOn + 7) % 7\n\n return addCalendarDays(date, -offset)\n}\n\n/**\n * Lists the days a calendar view shows for an anchor date. A month spans from\n * the first week containing the 1st to the last week containing the final day,\n * so adjacent days of neighbouring months are included.\n *\n * @param anchor - The date the view is centred on.\n * @param mode - Whether to list one day, one week or one month.\n * @param weekStartsOn - `0` when weeks start on Sunday, `1` on Monday.\n * @returns The visible days in chronological order.\n */\nexport function calendarRange(\n anchor: CalendarDate,\n mode: CalendarRangeMode,\n weekStartsOn: 0 | 1,\n): CalendarDate[] {\n if (mode === 'day') return [anchor]\n\n if (mode === 'week') {\n const first = startOfWeek(anchor, weekStartsOn)\n\n return Array.from({ length: 7 }, (_, index) =>\n addCalendarDays(first, index),\n )\n }\n\n const firstOfMonth = { ...anchor, day: 1 }\n const lastOfMonth = addCalendarDays(\n {\n ...normalizeCalendarDate({ ...anchor, day: 1, month: anchor.month + 1 }),\n },\n -1,\n )\n const first = startOfWeek(firstOfMonth, weekStartsOn)\n const last = addCalendarDays(startOfWeek(lastOfMonth, weekStartsOn), 6)\n const days: CalendarDate[] = []\n\n for (\n let day = first;\n compareCalendarDates(day, last) <= 0;\n day = addCalendarDays(day, 1)\n ) {\n days.push(day)\n }\n\n return days\n}\n\n/**\n * Normalizes an out-of-range day or month through `Date.UTC`, which rolls it\n * over into the right month and year. Arithmetic stays in year/month/day\n * rather than adding 86400 seconds to an instant, which would break across\n * daylight saving transitions.\n */\nfunction normalizeCalendarDate(date: CalendarDate): CalendarDate {\n const normalized = new Date(Date.UTC(date.year, date.month - 1, date.day))\n\n return {\n day: normalized.getUTCDate(),\n month: normalized.getUTCMonth() + 1,\n year: normalized.getUTCFullYear(),\n }\n}\n",
|
|
21
|
-
"target": "~/packages/helpers/src/calendar-date.ts"
|
|
22
|
-
},
|
|
23
|
-
{
|
|
24
|
-
"path": "helpers/src/date.ts",
|
|
25
|
-
"type": "registry:file",
|
|
26
|
-
"content": "import type { CalendarDate } from './calendar-date'\nimport { toZonedDateTime } from './zoned-date-time'\n\nconst DATE_ONLY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\nconst MILLISECONDS_IN_DAY = 86_400_000\n\nconst DATE_FORMAT_OPTIONS = {\n long: { dateStyle: 'long' },\n medium: { dateStyle: 'medium' },\n short: { day: 'numeric', month: 'short' },\n weekdayAndDay: { day: 'numeric', weekday: 'long' },\n} satisfies Record<string, Intl.DateTimeFormatOptions>\n\nconst dateFormatters = new Map<string, Intl.DateTimeFormat>()\nconst relativeDayFormatters = new Map<string, Intl.RelativeTimeFormat>()\n\n/**\n * Type guard for a `Date` whose time is not `NaN`.\n *\n * @param value - Any value, typically the result of parsing user input.\n */\nexport function isValidDate(value: unknown): value is Date {\n return value instanceof Date && !Number.isNaN(value.getTime())\n}\n\n/**\n * Parses an ISO 8601 string, such as the value stored by a date property.\n *\n * @param value - The serialized date; empty values are treated as absent.\n * @returns The parsed date, or `null` when the value is absent or invalid.\n */\nexport function parseIsoDate(value: string | null | undefined): Date | null {\n if (!value) return null\n const date = new Date(value)\n return isValidDate(date) ? date : null\n}\n\n/**\n * Coerces a cell value into a `Date`. A date-only string (`2026-08-04`) is\n * read as local midnight, because `new Date('2026-08-04')` is UTC midnight and\n * would display as the previous day in any negative time zone.\n *\n * @param value - A `Date`, a date string or anything `String()` can serialize.\n * @returns A date that may be invalid; check it with {@link isValidDate}.\n */\nexport function parseDateValue(value: unknown): Date {\n if (value instanceof Date) return value\n const raw = String(value)\n return DATE_ONLY_PATTERN.test(raw)\n ? new Date(`${raw}T00:00:00`)\n : new Date(raw)\n}\n\n/**\n * Serializes the local calendar day of a date as noon UTC, so the day survives\n * a round trip through any time zone.\n *\n * @param date - A date whose local year, month and day are kept.\n * @returns An ISO string such as `2026-06-19T12:00:00.000Z`.\n */\nexport function serializeIsoDay(date: Date): string {\n return new Date(\n Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12),\n ).toISOString()\n}\n\n/**\n * Formats a date as day and abbreviated month, without the year.\n *\n * @param date - A valid date.\n * @param locale - A BCP 47 locale tag such as `pt-BR`.\n * @param timeZone - An IANA time zone; when omitted the date is read in the\n * runtime's local zone, which suits local day markers.\n * @returns The formatted date, such as `Jun 19` or `19 de jun.`.\n */\nexport function formatShortDate(\n date: Date,\n locale: string,\n timeZone?: string,\n): string {\n return getDateFormatter('short', locale, timeZone).format(date)\n}\n\n/**\n * Formats a date with day, abbreviated month and year, as a date picker\n * trigger shows it.\n *\n * @param date - A valid date.\n * @param locale - A BCP 47 locale tag such as `pt-BR`.\n * @param timeZone - An IANA time zone; when omitted the date is read in the\n * runtime's local zone.\n * @returns The formatted date, such as `Oct 20, 2026` or `20 de out. de 2026`.\n */\nexport function formatMediumDate(\n date: Date,\n locale: string,\n timeZone?: string,\n): string {\n return getDateFormatter('medium', locale, timeZone).format(date)\n}\n\n/**\n * Formats a date with day, full month name and year.\n *\n * @param date - A valid date.\n * @param locale - A BCP 47 locale tag such as `pt-BR`.\n * @param timeZone - An IANA time zone; when omitted the date is read in the\n * runtime's local zone.\n * @returns The formatted date, such as `October 20, 2026` or\n * `20 de outubro de 2026`.\n */\nexport function formatLongDate(\n date: Date,\n locale: string,\n timeZone?: string,\n): string {\n return getDateFormatter('long', locale, timeZone).format(date)\n}\n\n/**\n * Formats the weekday name with the day of the month, as a day heading over a\n * list of time slots.\n *\n * @param date - A valid date.\n * @param locale - A BCP 47 locale tag such as `pt-BR`.\n * @param timeZone - An IANA time zone; when omitted the date is read in the\n * runtime's local zone.\n * @returns The formatted day, such as `Tuesday 20` or `terça-feira, 20`.\n */\nexport function formatWeekdayAndDay(\n date: Date,\n locale: string,\n timeZone?: string,\n): string {\n return getDateFormatter('weekdayAndDay', locale, timeZone).format(date)\n}\n\n/**\n * Counts the civil days between two instants as seen on the wall clock of a\n * time zone, so an instant just after midnight in that zone counts as the\n * next day even when it is still the previous day in UTC.\n *\n * @param from - The reference instant, usually now.\n * @param to - The instant being measured, such as a due date.\n * @param timeZone - An IANA time zone.\n * @returns Negative when `to` falls on an earlier day than `from`.\n */\nexport function dayOffsetInTimeZone(\n from: Date,\n to: Date,\n timeZone: string,\n): number {\n return (\n dayNumber(toZonedDateTime(to, timeZone).date) -\n dayNumber(toZonedDateTime(from, timeZone).date)\n )\n}\n\n/**\n * Names a day relative to today (`Yesterday`, `Today`, `Tomorrow`, `In 3\n * days`) with the first letter upper-cased for the locale.\n *\n * @param dayOffset - Civil days from today; see {@link dayOffsetInTimeZone}.\n * @param locale - A BCP 47 locale tag such as `pt-BR`.\n */\nexport function formatRelativeDay(dayOffset: number, locale: string): string {\n const label = getRelativeDayFormatter(locale).format(dayOffset, 'day')\n return label.charAt(0).toLocaleUpperCase(locale) + label.slice(1)\n}\n\n/**\n * Moves a date by a number of local calendar days, keeping its time of day.\n *\n * @param date - The starting date; it is not mutated.\n * @param days - Days to add; negative values move backwards.\n */\nexport function addDays(date: Date, days: number): Date {\n const next = new Date(date)\n next.setDate(next.getDate() + days)\n return next\n}\n\n/**\n * Moves a date by a number of months. When the target month is shorter, the\n * day is clamped to its last day, so January 31 plus one month is the end of\n * February instead of early March.\n *\n * @param date - The starting date; it is not mutated.\n * @param months - Months to add; negative values move backwards.\n */\nexport function addMonths(date: Date, months: number): Date {\n const next = new Date(date)\n next.setDate(1)\n next.setMonth(next.getMonth() + months)\n const lastDay = new Date(next.getFullYear(), next.getMonth() + 1, 0).getDate()\n next.setDate(Math.min(date.getDate(), lastDay))\n return next\n}\n\n/**\n * Moves a date by a number of years. February 29 becomes February 28 in a\n * common year.\n *\n * @param date - The starting date; it is not mutated.\n * @param years - Years to add; negative values move backwards.\n */\nexport function addYears(date: Date, years: number): Date {\n return addMonths(date, years * 12)\n}\n\n/** Building an `Intl` formatter costs ~50 formats, so one is kept per key. */\nfunction getDateFormatter(\n style: keyof typeof DATE_FORMAT_OPTIONS,\n locale: string,\n timeZone?: string,\n): Intl.DateTimeFormat {\n const key = `${style}|${locale}|${timeZone ?? ''}`\n const cached = dateFormatters.get(key)\n if (cached) return cached\n\n const formatter = new Intl.DateTimeFormat(locale, {\n ...DATE_FORMAT_OPTIONS[style],\n ...(timeZone ? { timeZone } : {}),\n })\n dateFormatters.set(key, formatter)\n\n return formatter\n}\n\nfunction getRelativeDayFormatter(locale: string): Intl.RelativeTimeFormat {\n const cached = relativeDayFormatters.get(locale)\n if (cached) return cached\n\n const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })\n relativeDayFormatters.set(locale, formatter)\n\n return formatter\n}\n\n/** Days since the Unix epoch for a calendar date, ignoring time zones. */\nfunction dayNumber(date: CalendarDate): number {\n return Date.UTC(date.year, date.month - 1, date.day) / MILLISECONDS_IN_DAY\n}\n",
|
|
27
|
-
"target": "~/packages/helpers/src/date.ts"
|
|
28
|
-
},
|
|
29
|
-
{
|
|
30
|
-
"path": "helpers/src/zoned-date-time.ts",
|
|
31
|
-
"type": "registry:file",
|
|
32
|
-
"content": "import type { CalendarDate } from './calendar-date'\n\n/**\n * A wall-clock reading in some time zone: the calendar day and the minutes\n * elapsed since local midnight.\n */\nexport interface ZonedDateTime {\n date: CalendarDate\n minutes: number\n}\n\nconst formatterCache = new Map<string, Intl.DateTimeFormat>()\n\n/**\n * Returns the formatter for a time zone. `Intl.DateTimeFormat` is expensive\n * to construct, so one instance per zone is kept for the life of the module.\n */\nfunction getFormatter(timeZone: string): Intl.DateTimeFormat {\n const cached = formatterCache.get(timeZone)\n if (cached) return cached\n\n const formatter = new Intl.DateTimeFormat('en-US', {\n day: '2-digit',\n hour: '2-digit',\n hourCycle: 'h23',\n minute: '2-digit',\n month: '2-digit',\n second: '2-digit',\n timeZone,\n year: 'numeric',\n })\n formatterCache.set(timeZone, formatter)\n\n return formatter\n}\n\n/** Numeric date and time fields of an instant, read in a time zone. */\ninterface WallClockParts {\n day: number\n hour: number\n minute: number\n month: number\n second: number\n year: number\n}\n\n/**\n * Reads the wall-clock fields of an instant in a time zone.\n *\n * @param instant - The UTC instant to project.\n * @param timeZone - An IANA time zone.\n */\nfunction wallClockPartsOf(instant: Date, timeZone: string): WallClockParts {\n const parts: Partial<WallClockParts> = {}\n\n for (const part of getFormatter(timeZone).formatToParts(instant)) {\n if (part.type === 'literal') continue\n if (part.type in partKeys)\n parts[partKeys[part.type as keyof typeof partKeys]] = Number(part.value)\n }\n\n return parts as WallClockParts\n}\n\nconst partKeys = {\n day: 'day',\n hour: 'hour',\n minute: 'minute',\n month: 'month',\n second: 'second',\n year: 'year',\n} as const\n\n/**\n * Projects a UTC instant onto the wall clock of a time zone.\n *\n * @param instant - The UTC instant to project.\n * @param timeZone - An IANA time zone.\n * @returns The calendar day and the minutes since local midnight.\n */\nexport function toZonedDateTime(\n instant: Date,\n timeZone: string,\n): ZonedDateTime {\n const parts = wallClockPartsOf(instant, timeZone)\n\n return {\n date: { day: parts.day, month: parts.month, year: parts.year },\n minutes: parts.hour * 60 + parts.minute,\n }\n}\n\n/**\n * Offset of a time zone from UTC at a given instant. The formatter stops at\n * seconds, so the instant is truncated to the second before comparing;\n * otherwise milliseconds would leak into the offset.\n *\n * @param instant - The UTC instant to measure at.\n * @param timeZone - An IANA time zone.\n * @returns The offset in milliseconds; positive east of UTC.\n */\nexport function getTimeZoneOffsetMs(instant: Date, timeZone: string): number {\n const parts = wallClockPartsOf(instant, timeZone)\n const wallAsUtc = Date.UTC(\n parts.year,\n parts.month - 1,\n parts.day,\n parts.hour,\n parts.minute,\n parts.second,\n )\n const truncated =\n instant.getTime() - (((instant.getTime() % 1000) + 1000) % 1000)\n\n return wallAsUtc - truncated\n}\n\n/**\n * Converts a wall-clock reading in a time zone back to a UTC instant without a\n * date library: the wall time is first treated as UTC and then corrected by the\n * zone offset. A second pass handles transition edges, since offsets only\n * change there: an ambiguous time (fall back) keeps the first offset found,\n * and a nonexistent time (spring forward) resolves to the instant after the\n * transition.\n *\n * @param zoned - The calendar day and minutes since local midnight.\n * @param timeZone - An IANA time zone.\n * @returns The UTC instant that shows that wall time in the zone.\n */\nexport function fromZonedDateTime(\n zoned: ZonedDateTime,\n timeZone: string,\n): Date {\n const { date, minutes } = zoned\n const guess = Date.UTC(date.year, date.month - 1, date.day, 0, minutes)\n const firstOffset = getTimeZoneOffsetMs(new Date(guess), timeZone)\n const candidate = guess - firstOffset\n const secondOffset = getTimeZoneOffsetMs(new Date(candidate), timeZone)\n\n if (firstOffset === secondOffset) return new Date(candidate)\n\n const corrected = guess - secondOffset\n const projected = toZonedDateTime(new Date(corrected), timeZone)\n const matchesWall =\n projected.minutes === ((minutes % 1440) + 1440) % 1440 &&\n projected.date.day === date.day &&\n projected.date.month === date.month &&\n projected.date.year === date.year\n\n return matchesWall ? new Date(corrected) : new Date(candidate)\n}\n",
|
|
33
|
-
"target": "~/packages/helpers/src/zoned-date-time.ts"
|
|
34
|
-
},
|
|
35
|
-
{
|
|
36
|
-
"path": "parttens/src/collection-views/composition/collection-view-outlet.tsx",
|
|
37
|
-
"type": "registry:file",
|
|
38
|
-
"content": "import type { RowData } from '@tanstack/react-table'\nimport { type ReactNode, useCallback, useMemo } from 'react'\nimport { projectCollection } from '../shared/lib/project-collection'\nimport { useCollectionPreferences } from '../store/collection-provider'\nimport type {\n CollectionDefinition,\n CollectionGroup,\n CollectionItemChange,\n} from '../types/collection'\nimport {\n CalendarView,\n type CalendarViewProps,\n} from '../views/calendar/components/calendar-view'\nimport {\n DataGrid,\n type DataGridProps,\n} from '../views/data-grid/components/data-grid'\nimport { DataTable, type DataTableProps } from '../views/data-table/data-table'\nimport {\n GalleryView,\n type GalleryViewProps,\n} from '../views/gallery/components/gallery-view'\nimport {\n KanbanView,\n type KanbanViewProps,\n} from '../views/kanban/components/kanban-view'\nimport type { KanbanCardMove, KanbanColumnData } from '../views/kanban/types'\nimport {\n ListView,\n type ListViewProps,\n} from '../views/list/components/list-view'\n\nexport type CollectionCalendarViewProps<TItem> = Omit<\n CalendarViewProps<TItem>,\n 'collection'\n>\n\nexport type CollectionDataGridViewProps<TItem extends RowData> =\n DataGridProps<TItem>\n\nexport type CollectionDataTableViewProps<TItem extends RowData> =\n DataTableProps<TItem>\n\nexport type CollectionGalleryViewProps<TItem> = Omit<\n GalleryViewProps<TItem>,\n 'collection' | 'renderItem'\n>\n\nexport interface CollectionKanbanCardMove<TItem> extends KanbanCardMove<TItem> {\n sourceGroup: CollectionGroup<TItem>\n targetGroup: CollectionGroup<TItem>\n}\n\nexport interface CollectionKanbanViewProps<TItem>\n extends Omit<\n KanbanViewProps<TItem>,\n 'columns' | 'getKey' | 'onMoveCard' | 'renderCard'\n > {\n onMoveCard?: (\n move: CollectionKanbanCardMove<TItem>,\n ) => boolean | Promise<boolean>\n}\n\nexport type CollectionListViewProps<TItem> = Omit<\n ListViewProps<TItem>,\n 'collection' | 'grouping' | 'renderItem'\n>\n\nexport interface CollectionViewOutletProps<TItem extends RowData> {\n collection: CollectionDefinition<TItem>\n groups?: readonly CollectionGroup<TItem>[]\n /** Obrigatória quando a view é `calendar`: agenda, modo e fuso são do consumer. */\n calendar?: CollectionCalendarViewProps<TItem>\n datagrid?: CollectionDataGridViewProps<TItem>\n datatable?: CollectionDataTableViewProps<TItem>\n gallery?: CollectionGalleryViewProps<TItem>\n kanban?: CollectionKanbanViewProps<TItem>\n list?: CollectionListViewProps<TItem>\n onItemChange?: (\n change: CollectionItemChange<TItem>,\n ) => boolean | Promise<boolean>\n renderGalleryItem?: (item: TItem) => ReactNode\n renderKanbanItem?: (item: TItem) => ReactNode\n renderListItem?: (item: TItem) => ReactNode\n}\n\nexport function CollectionViewOutlet<TItem extends RowData>({\n collection,\n groups,\n calendar,\n datagrid,\n datatable,\n gallery,\n kanban,\n list,\n onItemChange,\n renderGalleryItem,\n renderKanbanItem,\n renderListItem,\n}: CollectionViewOutletProps<TItem>) {\n const { preferences } = useCollectionPreferences()\n const canRenderKanban = Boolean(renderKanbanItem)\n const kanbanGroups = useMemo(\n () =>\n preferences.view === 'kanban' && canRenderKanban\n ? (groups ?? projectCollection(collection, preferences.groupBy))\n : [],\n [\n canRenderKanban,\n collection,\n groups,\n preferences.groupBy,\n preferences.view,\n ],\n )\n const columns = useMemo<KanbanColumnData<TItem>[]>(\n () =>\n kanbanGroups.map((group) => ({\n cards: [...group.items],\n count: group.count,\n id: group.id,\n title: group.label,\n })),\n [kanbanGroups],\n )\n const { onMoveCard: onCollectionMoveCard, ...kanbanProps } = kanban ?? {}\n const canWriteGroup = Boolean(\n onItemChange &&\n collection.groupings.find(({ id }) => id === preferences.groupBy)\n ?.setGroupId,\n )\n const onMoveCard = useCallback(\n (move: KanbanCardMove<TItem>) => {\n const sourceGroup = kanbanGroups.find(\n (group) => group.id === move.sourceColumnId,\n )\n const targetGroup = kanbanGroups.find(\n (group) => group.id === move.targetColumnId,\n )\n\n if (!sourceGroup || !targetGroup) return false\n if (onCollectionMoveCard)\n return onCollectionMoveCard({ ...move, sourceGroup, targetGroup })\n\n const setGroupId = collection.groupings.find(\n ({ id }) => id === targetGroup.grouping,\n )?.setGroupId\n\n if (!onItemChange || !setGroupId || sourceGroup.id === targetGroup.id)\n return false\n\n return onItemChange({\n grouping: targetGroup.grouping,\n item: setGroupId(move.card, targetGroup.value),\n previousItem: move.card,\n reason: 'grouping',\n })\n },\n [collection.groupings, kanbanGroups, onCollectionMoveCard, onItemChange],\n )\n\n if (preferences.view === 'datagrid') {\n if (!datagrid) {\n throw new Error(\n 'CollectionViewOutlet: a view \"datagrid\" exige a prop `datagrid`.',\n )\n }\n\n return <DataGrid {...datagrid} />\n }\n\n if (preferences.view === 'datatable') {\n if (!datatable) {\n throw new Error(\n 'CollectionViewOutlet: a view \"datatable\" exige a prop `datatable`.',\n )\n }\n\n return <DataTable {...datatable} />\n }\n\n if (preferences.view === 'calendar') {\n if (!calendar) {\n throw new Error(\n 'CollectionViewOutlet: a view \"calendar\" exige a prop `calendar`.',\n )\n }\n\n return <CalendarView collection={collection} {...calendar} />\n }\n\n if (preferences.view === 'gallery') {\n if (!renderGalleryItem) {\n throw new Error(\n 'CollectionViewOutlet: a view \"gallery\" exige a prop `renderGalleryItem`.',\n )\n }\n\n return (\n <GalleryView\n collection={collection}\n renderItem={renderGalleryItem}\n {...gallery}\n />\n )\n }\n\n if (preferences.view === 'list') {\n if (!renderListItem) {\n throw new Error(\n 'CollectionViewOutlet: a view \"list\" exige a prop `renderListItem`.',\n )\n }\n\n return (\n <ListView\n collection={collection}\n grouping={preferences.groupBy}\n renderItem={renderListItem}\n {...list}\n groups={groups ?? list?.groups}\n />\n )\n }\n\n if (!renderKanbanItem) {\n throw new Error(\n 'CollectionViewOutlet: a view \"kanban\" exige a prop `renderKanbanItem`.',\n )\n }\n\n return (\n <KanbanView\n columns={columns}\n getCardLabel={collection.getLabel}\n getKey={collection.getKey}\n renderCard={renderKanbanItem}\n {...kanbanProps}\n {...(onCollectionMoveCard || canWriteGroup ? { onMoveCard } : {})}\n />\n )\n}\n",
|
|
39
|
-
"target": "~/packages/patterns/src/collection-views/composition/collection-view-outlet.tsx"
|
|
40
|
-
},
|
|
41
|
-
{
|
|
42
|
-
"path": "parttens/src/collection-views/composition/index.ts",
|
|
43
|
-
"type": "registry:file",
|
|
44
|
-
"content": "export type {\n CollectionCalendarViewProps,\n CollectionDataGridViewProps,\n CollectionDataTableViewProps,\n CollectionGalleryViewProps,\n CollectionKanbanCardMove,\n CollectionKanbanViewProps,\n CollectionListViewProps,\n CollectionViewOutletProps,\n} from './collection-view-outlet'\nexport { CollectionViewOutlet } from './collection-view-outlet'\n",
|
|
45
|
-
"target": "~/packages/patterns/src/collection-views/composition/index.ts"
|
|
46
|
-
},
|
|
47
|
-
{
|
|
48
|
-
"path": "parttens/src/collection-views/index.ts",
|
|
49
|
-
"type": "registry:file",
|
|
50
|
-
"content": "export * from './composition/index'\nexport * from './shared/index'\nexport * from './store/index'\nexport * from './types/index'\nexport * from './views/calendar/index'\nexport * from './views/data-grid/index'\nexport * from './views/data-table/index'\nexport * from './views/gallery/index'\nexport * from './views/kanban/index'\nexport * from './views/list/index'\n",
|
|
51
|
-
"target": "~/packages/patterns/src/collection-views/index.ts"
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
"path": "parttens/src/collection-views/shared/components/action-bar.tsx",
|
|
55
|
-
"type": "registry:file",
|
|
56
|
-
"content": "'use client'\n\nimport { Button, type ButtonProps } from '@tc96/ui/button'\nimport {\n Menu,\n MenuGroup,\n MenuGroupLabel,\n MenuItem,\n MenuPopup,\n MenuSeparator,\n MenuTrigger,\n} from '@tc96/ui/menu'\nimport { cn } from '@tc96/utils'\nimport { GripVerticalIcon, XIcon } from 'lucide-react'\nimport { Fragment, type ReactNode } from 'react'\n\nexport interface ActionBarContext<TData = unknown> {\n selectedCount: number\n selectedRows: readonly TData[]\n}\n\nexport interface ActionBarItem<TData = unknown> {\n disabled?: boolean\n icon?: ReactNode\n id?: string\n label: string\n onSelect?: (context: ActionBarContext<TData>) => void\n shortcut?: string\n submenu?: ActionBarGroup<TData>[]\n variant?: 'default' | 'primary' | 'destructive'\n}\n\nexport interface ActionBarGroup<TData = unknown> {\n id?: string\n items: ActionBarItem<TData>[]\n label?: string\n}\n\nexport interface ActionBarProps<TData = unknown> {\n actions: ActionBarGroup<TData>[]\n className?: string\n onClearSelection?: () => void\n selectedCount: number\n selectedRows?: readonly TData[]\n}\n\nfunction selectionLabel(count: number) {\n return `${count} selecionado${count === 1 ? '' : 's'}`\n}\n\nfunction actionKey<TData>(action: ActionBarItem<TData>) {\n return action.id ?? action.label\n}\n\nfunction groupKey<TData>(group: ActionBarGroup<TData>) {\n return (\n group.id ??\n group.label ??\n group.items.map((action) => actionKey(action)).join('|')\n )\n}\n\nfunction buttonAppearance(\n variant: ActionBarItem['variant'] = 'default',\n): Pick<ButtonProps, 'className' | 'variant'> {\n if (variant === 'primary') return { variant: 'default' }\n // O COSS não tem botão ghost destrutivo: o ghost leva o texto destrutivo.\n if (variant === 'destructive')\n return { className: 'text-destructive-foreground', variant: 'ghost' }\n return { variant: 'ghost' }\n}\n\nfunction ActionItem<TData>({\n action,\n context,\n}: Readonly<{\n action: ActionBarItem<TData>\n context: ActionBarContext<TData>\n}>): ReactNode {\n const content = (\n <>\n {action.icon}\n <span>{action.label}</span>\n {action.shortcut ? (\n <kbd className=\"ms-auto text-xs\">{action.shortcut}</kbd>\n ) : null}\n </>\n )\n\n if (action.submenu) {\n return (\n <Menu modal={false}>\n <MenuTrigger\n aria-label={action.label}\n disabled={action.disabled}\n render={\n <Button\n aria-label={action.label}\n disabled={action.disabled}\n size=\"sm\"\n {...buttonAppearance(action.variant)}\n />\n }\n >\n {content}\n </MenuTrigger>\n <MenuPopup align=\"center\" side=\"top\" sideOffset={8}>\n {action.submenu.map((group, groupIndex) => (\n <Fragment key={groupKey(group)}>\n {groupIndex > 0 ? <MenuSeparator /> : null}\n <MenuGroup>\n {group.label ? (\n <MenuGroupLabel>{group.label}</MenuGroupLabel>\n ) : null}\n {group.items.map((item) => (\n <MenuItem\n disabled={item.disabled}\n key={actionKey(item)}\n onClick={() => item.onSelect?.(context)}\n variant={\n item.variant === 'destructive' ? 'destructive' : 'default'\n }\n >\n {item.icon}\n <span>{item.label}</span>\n {item.shortcut ? (\n <kbd className=\"ms-auto text-xs\">{item.shortcut}</kbd>\n ) : null}\n </MenuItem>\n ))}\n </MenuGroup>\n </Fragment>\n ))}\n </MenuPopup>\n </Menu>\n )\n }\n\n return (\n <Button\n aria-label={action.label}\n disabled={action.disabled}\n onClick={() => action.onSelect?.(context)}\n size=\"sm\"\n title={action.label}\n {...buttonAppearance(action.variant)}\n >\n {content}\n </Button>\n )\n}\n\nexport function ActionBar<TData = unknown>({\n actions,\n className,\n onClearSelection,\n selectedCount,\n selectedRows = [],\n}: Readonly<ActionBarProps<TData>>): ReactNode {\n if (selectedCount < 1) return null\n\n const context: ActionBarContext<TData> = {\n selectedCount,\n selectedRows,\n }\n\n return (\n <div\n aria-label=\"Ações dos itens selecionados\"\n className={cn(\n 'flex min-h-11 w-fit max-w-full items-center gap-1 overflow-x-auto rounded-xl border bg-popover px-2 py-1 text-popover-foreground shadow-lg',\n className,\n )}\n data-slot=\"action-bar\"\n role=\"toolbar\"\n >\n <GripVerticalIcon\n aria-hidden=\"true\"\n className=\"size-4 shrink-0 text-muted-foreground\"\n />\n <span className=\"px-1 font-medium text-sm\">\n {selectionLabel(selectedCount)}\n </span>\n {actions.map((group, groupIndex) => (\n <div className=\"flex items-center gap-0.5\" key={groupKey(group)}>\n {groupIndex > 0 ? (\n <hr\n aria-orientation=\"vertical\"\n className=\"mx-1 h-5 w-px border-0 bg-border\"\n />\n ) : null}\n {group.items.map((action) => (\n <ActionItem\n action={action}\n context={context}\n key={actionKey(action)}\n />\n ))}\n </div>\n ))}\n {onClearSelection ? (\n <Button\n aria-label=\"Limpar seleção\"\n onClick={onClearSelection}\n size=\"sm\"\n title=\"Limpar seleção\"\n variant=\"ghost\"\n >\n <XIcon />\n </Button>\n ) : null}\n </div>\n )\n}\n",
|
|
57
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/action-bar.tsx"
|
|
58
|
-
},
|
|
59
|
-
{
|
|
60
|
-
"path": "parttens/src/collection-views/shared/components/collection-action.tsx",
|
|
61
|
-
"type": "registry:file",
|
|
62
|
-
"content": "'use client'\n\nimport { Button } from '@tc96/ui/button'\nimport { ToolbarButton } from '@tc96/ui/toolbar'\nimport type { ReactElement } from 'react'\n\nexport interface ActionProps {\n className?: string\n disabled?: boolean\n label?: string\n onClick: () => void\n}\n\nexport function Action({\n className,\n disabled = false,\n label = 'Adicionar',\n onClick,\n}: Readonly<ActionProps>): ReactElement {\n return (\n <ToolbarButton\n disabled={disabled}\n onClick={onClick}\n render={\n <Button\n className={className}\n disabled={disabled}\n type=\"button\"\n variant=\"default\"\n />\n }\n >\n {label}\n </ToolbarButton>\n )\n}\n",
|
|
63
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/collection-action.tsx"
|
|
64
|
-
},
|
|
65
|
-
{
|
|
66
|
-
"path": "parttens/src/collection-views/shared/components/collection-filter-submenu.tsx",
|
|
67
|
-
"type": "registry:file",
|
|
68
|
-
"content": "'use client'\n\nimport {\n MenuRadioGroup,\n MenuSub,\n MenuSubPopup,\n MenuSubTrigger,\n} from '@tc96/ui/menu'\nimport type { LucideIcon } from 'lucide-react'\nimport type { ReactElement } from 'react'\nimport { MenuRadioOption } from '../../../shared/components/menu-selection-item'\n\n/**\n * `MenuRadioGroup` não representa ausência de escolha: `value=''` deixa o grupo\n * sem item marcado, e a opção \"todos\" fica indistinguível de nenhuma opção. O\n * sentinela ocupa esse lugar na UI e é traduzido de volta para `''` na borda.\n */\nconst CLEAR_VALUE = '__all__'\n\nexport interface FilterRadioSubmenuProps {\n clearLabel?: string\n icon: LucideIcon\n label: string\n /** Recebe `''` quando a opção \"todos\" é escolhida. */\n onValueChange: (value: string) => void\n options: readonly (readonly [string, string])[]\n value?: string\n}\n\n/**\n * Submenu de filtro por valor único — a forma que Tasks e Contatos repetem\n * dentro do `ViewSettingsMenu`. O pacote fornece a moldura e a semântica do\n * \"todos\"; quais opções existem e o que cada uma significa é da vitrine.\n */\nexport function FilterRadioSubmenu({\n clearLabel = 'Todos',\n icon: Icon,\n label,\n onValueChange,\n options,\n value,\n}: Readonly<FilterRadioSubmenuProps>): ReactElement {\n return (\n <MenuSub>\n <MenuSubTrigger>\n <Icon aria-hidden=\"true\" />\n {label}\n </MenuSubTrigger>\n <MenuSubPopup>\n <MenuRadioGroup\n onValueChange={(next) =>\n onValueChange(next === CLEAR_VALUE ? '' : next)\n }\n value={value || CLEAR_VALUE}\n >\n <MenuRadioOption value={CLEAR_VALUE}>{clearLabel}</MenuRadioOption>\n {options.map(([optionValue, optionLabel]) => (\n <MenuRadioOption key={optionValue} value={optionValue}>\n {optionLabel}\n </MenuRadioOption>\n ))}\n </MenuRadioGroup>\n </MenuSubPopup>\n </MenuSub>\n )\n}\n",
|
|
69
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/collection-filter-submenu.tsx"
|
|
70
|
-
},
|
|
71
|
-
{
|
|
72
|
-
"path": "parttens/src/collection-views/shared/components/collection-presets-menu.tsx",
|
|
73
|
-
"type": "registry:file",
|
|
74
|
-
"content": "'use client'\n\nimport { Badge } from '@tc96/ui/badge'\nimport { Menu, MenuPopup } from '@tc96/ui/menu'\nimport { ChevronDownIcon } from 'lucide-react'\nimport type { ReactElement, ReactNode } from 'react'\nimport { CollectionToolbarMenuTrigger } from './collection-toolbar-menu-trigger'\n\nexport interface PresetsMenuProps {\n children: ReactNode\n className?: string\n count: number\n countLabel?: string\n label: string\n}\n\nexport function PresetsMenu({\n children,\n className,\n count,\n countLabel,\n label,\n}: Readonly<PresetsMenuProps>): ReactElement {\n const normalizedCount = Math.max(0, count)\n\n return (\n <Menu>\n <CollectionToolbarMenuTrigger className={className}>\n <span className=\"min-w-0 truncate font-medium\">{label}</span>\n <Badge\n aria-label={countLabel ?? `${normalizedCount} itens`}\n variant=\"secondary\"\n >\n {normalizedCount}\n </Badge>\n <ChevronDownIcon aria-hidden=\"true\" />\n </CollectionToolbarMenuTrigger>\n <MenuPopup align=\"start\" className=\"w-56\">\n {children}\n </MenuPopup>\n </Menu>\n )\n}\n",
|
|
75
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/collection-presets-menu.tsx"
|
|
76
|
-
},
|
|
77
|
-
{
|
|
78
|
-
"path": "parttens/src/collection-views/shared/components/collection-search-field.tsx",
|
|
79
|
-
"type": "registry:file",
|
|
80
|
-
"content": "'use client'\n\nimport { Input } from '@tc96/ui/input'\nimport { ToolbarInput } from '@tc96/ui/toolbar'\nimport { cn } from '@tc96/utils'\nimport { SearchIcon } from 'lucide-react'\nimport { type FormEvent, type ReactElement, useEffect, useState } from 'react'\n\nexport interface CollectionSearchFieldProps {\n className?: string\n label?: string\n /**\n * Chamado no submit e ao esvaziar, nunca a cada tecla: quem consome escreve o\n * valor na URL, e escrever por tecla empilha uma entrada de histórico por\n * letra digitada.\n */\n onCommit: (value: string) => void\n placeholder?: string\n /** Valor já confirmado. O rascunho até o submit é local. */\n value?: string\n}\n\n/**\n * Busca da coleção, à esquerda da toolbar. Compõe dentro do `CollectionToolbar`:\n * o campo se registra no roving focus da toolbar e não monta fora dela.\n *\n * O rascunho é estado local porque ainda não foi escrito em lugar nenhum — não\n * é cópia do valor confirmado, e por isso não concorre com ele. Quando o valor\n * confirmado muda por fora (botão voltar, link compartilhado), o rascunho o\n * reflete.\n */\nexport function CollectionSearchField({\n className,\n label = 'Buscar',\n onCommit,\n placeholder = 'Buscar',\n value = '',\n}: Readonly<CollectionSearchFieldProps>): ReactElement {\n const [draft, setDraft] = useState(value)\n useEffect(() => setDraft(value), [value])\n\n const submit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault()\n onCommit(draft.trim())\n }\n\n return (\n <form className={cn('relative', className)} onSubmit={submit}>\n <SearchIcon\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute top-1/2 left-2.5 z-1 size-4 -translate-y-1/2 text-muted-foreground\"\n />\n <ToolbarInput\n render={\n // O recuo vai no invólucro do Input, não no campo: só o invólucro\n // aceita classe, e é ele que abre o espaço para a lupa.\n <Input\n aria-label={label}\n className=\"w-56 ps-6 sm:w-64\"\n nativeInput\n onChange={(event) => {\n setDraft(event.target.value)\n if (event.target.value === '') onCommit('')\n }}\n placeholder={placeholder}\n type=\"search\"\n value={draft}\n />\n }\n />\n </form>\n )\n}\n",
|
|
81
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/collection-search-field.tsx"
|
|
82
|
-
},
|
|
83
|
-
{
|
|
84
|
-
"path": "parttens/src/collection-views/shared/components/collection-selected-view.tsx",
|
|
85
|
-
"type": "registry:file",
|
|
86
|
-
"content": "'use client'\n\nimport { Button } from '@tc96/ui/button'\nimport { Menu, MenuPopup, MenuTrigger } from '@tc96/ui/menu'\nimport {\n Popover,\n PopoverClose,\n PopoverPopup,\n PopoverTrigger,\n} from '@tc96/ui/popover'\nimport { ToolbarButton } from '@tc96/ui/toolbar'\nimport { cn } from '@tc96/utils'\nimport { ChevronDownIcon, EllipsisIcon, PlusIcon } from 'lucide-react'\nimport type { ReactElement, ReactNode } from 'react'\nimport { createContext, useContext, useState } from 'react'\n\n/*\n * O seletor é um popover, não um menu: ele reúne um campo de busca e, em cada\n * view, um botão de opções, e um `role=\"menu\"` não pode conter nenhum dos dois.\n * Escolher uma view, criar outra ou usar uma opção fecha o popover.\n */\nconst SelectedViewCloseContext = createContext<() => void>(() => undefined)\n\nexport interface SelectedViewMenuProps {\n children: ReactNode\n className?: string\n icon?: ReactNode\n label: string\n}\n\n/** Gatilho com a view ativa e popup alinhado ao início da toolbar. */\nexport function SelectedViewMenu({\n children,\n className,\n icon,\n label,\n}: Readonly<SelectedViewMenuProps>): ReactElement {\n const [open, setOpen] = useState(false)\n\n return (\n <Popover onOpenChange={setOpen} open={open}>\n <PopoverTrigger\n render={\n <ToolbarButton\n render={\n <Button className={className} type=\"button\" variant=\"ghost\" />\n }\n />\n }\n >\n {icon ? <span className=\"shrink-0\">{icon}</span> : null}\n <span className=\"min-w-0 truncate font-medium\">{label}</span>\n <ChevronDownIcon aria-hidden=\"true\" className=\"shrink-0\" />\n </PopoverTrigger>\n <PopoverPopup align=\"start\" aria-label={label} className=\"w-72\">\n <SelectedViewCloseContext.Provider value={() => setOpen(false)}>\n <div className=\"flex flex-col gap-1\">{children}</div>\n </SelectedViewCloseContext.Provider>\n </PopoverPopup>\n </Popover>\n )\n}\n\nexport interface SelectedViewSearchProps {\n label?: string\n onValueChange: (value: string) => void\n placeholder?: string\n value: string\n}\n\nexport function SelectedViewSearch({\n label = 'Buscar views',\n onValueChange,\n placeholder = 'Buscar views...',\n value,\n}: Readonly<SelectedViewSearchProps>): ReactElement {\n return (\n <div className=\"pb-1\" data-slot=\"selected-view-search\">\n <input\n aria-label={label}\n className=\"h-8 w-full rounded-md bg-transparent px-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n onChange={(event) => onValueChange(event.target.value)}\n placeholder={placeholder}\n type=\"search\"\n value={value}\n />\n </div>\n )\n}\n\nexport interface SelectedViewItemsProps {\n children: ReactNode\n label?: string\n}\n\nexport function SelectedViewItems({\n children,\n label = 'Views',\n}: Readonly<SelectedViewItemsProps>): ReactElement {\n return (\n <fieldset\n aria-label={label}\n className=\"m-0 flex min-w-0 flex-col gap-0.5 border-0 p-0\"\n data-slot=\"selected-view-items\"\n >\n {children}\n </fieldset>\n )\n}\n\nexport interface SelectedViewItemProps {\n icon?: ReactNode\n label: string\n onSelect: () => void\n options?: ReactNode\n optionsLabel?: string\n selected?: boolean\n}\n\nexport function SelectedViewItem({\n icon,\n label,\n onSelect,\n options,\n optionsLabel = `Opções de ${label}`,\n selected = false,\n}: Readonly<SelectedViewItemProps>): ReactElement {\n const close = useContext(SelectedViewCloseContext)\n\n return (\n <div\n className={cn(\n 'flex min-w-0 items-center rounded-md',\n selected && 'bg-accent/60',\n )}\n data-selected={selected ? '' : undefined}\n data-slot=\"selected-view-item\"\n >\n <PopoverClose\n aria-current={selected ? 'true' : undefined}\n onClick={onSelect}\n render={\n <Button\n className=\"min-w-0 flex-1 justify-start\"\n size=\"sm\"\n type=\"button\"\n variant=\"ghost\"\n />\n }\n >\n {icon ? <span className=\"shrink-0\">{icon}</span> : null}\n <span className=\"truncate\">{label}</span>\n </PopoverClose>\n {options ? (\n <Menu\n onOpenChange={(menuOpen, details) => {\n if (!menuOpen && details.reason === 'item-press') close()\n }}\n >\n <MenuTrigger\n aria-label={optionsLabel}\n render={<Button size=\"icon-sm\" type=\"button\" variant=\"ghost\" />}\n >\n <EllipsisIcon aria-hidden=\"true\" className=\"size-4\" />\n </MenuTrigger>\n <MenuPopup align=\"start\" className=\"w-64\" side=\"right\">\n {options}\n </MenuPopup>\n </Menu>\n ) : null}\n </div>\n )\n}\n\nexport interface SelectedViewCreateProps {\n label?: string\n onClick: () => void\n}\n\nexport function SelectedViewCreate({\n label = 'Criar nova view',\n onClick,\n}: Readonly<SelectedViewCreateProps>): ReactElement {\n return (\n <PopoverClose\n data-slot=\"selected-view-create\"\n onClick={onClick}\n render={\n <Button\n className=\"w-full justify-start\"\n size=\"sm\"\n type=\"button\"\n variant=\"ghost\"\n />\n }\n >\n <PlusIcon aria-hidden=\"true\" />\n {label}\n </PopoverClose>\n )\n}\n",
|
|
87
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/collection-selected-view.tsx"
|
|
88
|
-
},
|
|
89
|
-
{
|
|
90
|
-
"path": "parttens/src/collection-views/shared/components/collection-selection-actions.tsx",
|
|
91
|
-
"type": "registry:file",
|
|
92
|
-
"content": "'use client'\n\nexport type {\n ActionBarContext as CollectionSelectionActionContext,\n ActionBarGroup as CollectionSelectionActionGroup,\n ActionBarItem as CollectionSelectionAction,\n ActionBarProps as CollectionSelectionActionsProps,\n} from './action-bar'\nexport { ActionBar as CollectionSelectionActions } from './action-bar'\n",
|
|
93
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/collection-selection-actions.tsx"
|
|
94
|
-
},
|
|
95
|
-
{
|
|
96
|
-
"path": "parttens/src/collection-views/shared/components/collection-toolbar-menu-trigger.tsx",
|
|
97
|
-
"type": "registry:file",
|
|
98
|
-
"content": "'use client'\n\nimport { Button } from '@tc96/ui/button'\nimport { MenuTrigger } from '@tc96/ui/menu'\nimport { ToolbarButton } from '@tc96/ui/toolbar'\nimport type { ReactElement, ReactNode } from 'react'\n\ninterface CollectionToolbarMenuTriggerProps {\n children: ReactNode\n className?: string\n disabled?: boolean\n}\n\nexport function CollectionToolbarMenuTrigger({\n children,\n className,\n disabled = false,\n}: Readonly<CollectionToolbarMenuTriggerProps>): ReactElement {\n return (\n <MenuTrigger\n render={\n <ToolbarButton\n render={\n <Button\n className={className}\n disabled={disabled}\n type=\"button\"\n variant=\"ghost\"\n />\n }\n />\n }\n >\n {children}\n </MenuTrigger>\n )\n}\n",
|
|
99
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/collection-toolbar-menu-trigger.tsx"
|
|
100
|
-
},
|
|
101
|
-
{
|
|
102
|
-
"path": "parttens/src/collection-views/shared/components/collection-view-settings.tsx",
|
|
103
|
-
"type": "registry:file",
|
|
104
|
-
"content": "'use client'\n\nimport {\n MenuGroup,\n MenuGroupLabel,\n MenuItem,\n MenuPopup,\n MenuPrimitive,\n MenuRadioGroup,\n Menu as MenuRoot,\n MenuSeparator,\n} from '@tc96/ui/menu'\nimport { cn } from '@tc96/utils'\nimport {\n type LucideIcon,\n RotateCcwIcon,\n SaveIcon,\n SlidersHorizontalIcon,\n} from 'lucide-react'\nimport type { ReactElement, ReactNode } from 'react'\nimport { CollectionToolbarMenuTrigger } from './collection-toolbar-menu-trigger'\n\nexport interface ViewSettingsMode<TMode extends string = string> {\n icon: LucideIcon\n label: string\n value: TMode\n}\n\nexport interface ViewSettingsMenuProps<TMode extends string = string> {\n /** Some no rótulo do gatilho quando zero, na mesma gramática do `FilterMenu`. */\n activeFilterCount?: number\n children: ReactNode\n className?: string\n clearLabel?: string\n label?: string\n mode?: TMode\n /** Na ordem da coleção; com menos de dois modos, as tabs não aparecem. */\n modes?: readonly ViewSettingsMode<TMode>[]\n onClearFilters: () => void\n onModeChange?: (mode: TMode) => void\n /** Sem handler o rodapé não compõe o item: guardar preferência é opcional. */\n onSavePreference?: () => void\n savePreferenceDisabled?: boolean\n savePreferenceLabel?: string\n}\n\nexport interface ViewSettingsSectionProps {\n children: ReactNode\n label: ReactNode\n}\n\nconst popupWidth = (modeCount: number) => {\n if (modeCount < 2) return 'w-56'\n if (modeCount === 2) return 'w-64'\n // Com três modos a linha única trunca \"Tabela\", \"Kanban\" e \"Planilha\" em 16rem.\n if (modeCount === 3) return 'w-72'\n return 'w-96'\n}\n\n/**\n * Superfície única de ajustes da view: filtro avançado e configuração deixam de\n * ser dois gatilhos vizinhos e passam a ser seções de um só menu.\n *\n * O pacote não decide quais modos ou seções existem — só a moldura, as tabs de\n * modo, a contagem no rótulo e o rodapé. A coleção fornece as opções.\n */\nexport function ViewSettingsMenu<TMode extends string = string>({\n activeFilterCount = 0,\n children,\n className,\n clearLabel = 'Limpar filtros',\n label = 'Exibição',\n mode,\n modes = [],\n onClearFilters,\n onModeChange,\n onSavePreference,\n savePreferenceDisabled = false,\n savePreferenceLabel = 'Salvar preferência',\n}: Readonly<ViewSettingsMenuProps<TMode>>): ReactElement {\n const normalizedActiveCount = Math.max(0, activeFilterCount)\n const triggerLabel = normalizedActiveCount\n ? `${label} (${normalizedActiveCount})`\n : label\n const hasModeTabs = modes.length > 1\n\n return (\n <MenuRoot>\n <CollectionToolbarMenuTrigger className={className}>\n <SlidersHorizontalIcon aria-hidden=\"true\" />\n {triggerLabel}\n </CollectionToolbarMenuTrigger>\n <MenuPopup align=\"end\" className={popupWidth(modes.length)}>\n {hasModeTabs ? (\n <ViewSettingsModeTabs\n modes={modes}\n onModeChange={onModeChange}\n value={mode}\n />\n ) : null}\n {children}\n <MenuSeparator />\n {/* Limpar antes de guardar: descartar volta ao ponto de partida, guardar\n avança a partir dele — a ordem é a mesma sequência de decisão. */}\n <MenuItem disabled={!normalizedActiveCount} onClick={onClearFilters}>\n <RotateCcwIcon aria-hidden=\"true\" />\n {clearLabel}\n </MenuItem>\n {onSavePreference ? (\n <MenuItem\n disabled={savePreferenceDisabled}\n onClick={onSavePreference}\n >\n <SaveIcon aria-hidden=\"true\" />\n {savePreferenceLabel}\n </MenuItem>\n ) : null}\n </MenuPopup>\n </MenuRoot>\n )\n}\n\nfunction ViewSettingsModeTabs<TMode extends string>({\n modes,\n onModeChange,\n value,\n}: Readonly<{\n modes: readonly ViewSettingsMode<TMode>[]\n onModeChange?: (mode: TMode) => void\n value?: TMode\n}>): ReactElement {\n const layout = modes.length < 4 ? 'inline' : 'stacked'\n\n return (\n <MenuRadioGroup\n className={cn(\n 'flex rounded-lg',\n layout === 'stacked' ? 'gap-1 p-1' : 'gap-0.5 p-0.5',\n )}\n onValueChange={(next: TMode) => onModeChange?.(next)}\n value={value}\n >\n {modes.map(({ icon: Icon, label, value: modeValue }) => (\n <MenuPrimitive.RadioItem\n className={cn(\n 'flex min-w-0 flex-auto cursor-default select-none items-center justify-center rounded-md text-muted-foreground outline-none data-checked:bg-background not-data-checked:data-highlighted:bg-accent data-highlighted:text-foreground data-checked:text-foreground data-checked:shadow-sm/5 dark:data-checked:bg-input [&_svg:not([class*=size-])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0',\n layout === 'stacked'\n ? 'flex-col gap-1.5 px-2 py-2 text-xs'\n : 'min-h-7 gap-1.5 px-1.5 text-sm',\n )}\n closeOnClick\n data-layout={layout}\n data-slot=\"view-settings-mode-tab\"\n key={modeValue}\n value={modeValue}\n >\n <span className=\"inline-flex size-4 shrink-0 items-center justify-center rounded-sm bg-primary text-primary-foreground\">\n <Icon aria-hidden=\"true\" className=\"size-3\" />\n </span>\n <span className=\"truncate\">{label}</span>\n </MenuPrimitive.RadioItem>\n ))}\n </MenuRadioGroup>\n )\n}\n\n/** Divisão nomeada dentro do `ViewSettingsMenu`. */\nexport function ViewSettingsSection({\n children,\n label,\n}: Readonly<ViewSettingsSectionProps>): ReactElement {\n return (\n <MenuGroup>\n <MenuGroupLabel>{label}</MenuGroupLabel>\n {children}\n </MenuGroup>\n )\n}\n",
|
|
105
|
-
"target": "~/packages/patterns/src/collection-views/shared/components/collection-view-settings.tsx"
|
|
106
|
-
},
|
|
107
|
-
{
|
|
108
|
-
"path": "parttens/src/collection-views/shared/index.ts",
|
|
109
|
-
"type": "registry:file",
|
|
110
|
-
"content": "export type {\n ActionBarContext,\n ActionBarGroup,\n ActionBarItem,\n ActionBarProps,\n} from './components/action-bar'\nexport { ActionBar } from './components/action-bar'\nexport type { ActionProps } from './components/collection-action'\nexport { Action } from './components/collection-action'\nexport type { FilterRadioSubmenuProps } from './components/collection-filter-submenu'\nexport { FilterRadioSubmenu } from './components/collection-filter-submenu'\nexport type { PresetsMenuProps } from './components/collection-presets-menu'\nexport { PresetsMenu } from './components/collection-presets-menu'\nexport type { CollectionSearchFieldProps } from './components/collection-search-field'\nexport { CollectionSearchField } from './components/collection-search-field'\nexport type {\n SelectedViewCreateProps,\n SelectedViewItemProps,\n SelectedViewItemsProps,\n SelectedViewMenuProps,\n SelectedViewSearchProps,\n} from './components/collection-selected-view'\nexport {\n SelectedViewCreate,\n SelectedViewItem,\n SelectedViewItems,\n SelectedViewMenu,\n SelectedViewSearch,\n} from './components/collection-selected-view'\nexport type {\n CollectionSelectionAction,\n CollectionSelectionActionContext,\n CollectionSelectionActionGroup,\n CollectionSelectionActionsProps,\n} from './components/collection-selection-actions'\nexport { CollectionSelectionActions } from './components/collection-selection-actions'\nexport type {\n ViewSettingsMenuProps,\n ViewSettingsMode,\n ViewSettingsSectionProps,\n} from './components/collection-view-settings'\nexport {\n ViewSettingsMenu,\n ViewSettingsSection,\n} from './components/collection-view-settings'\nexport { projectCollection } from './lib/project-collection'\n",
|
|
111
|
-
"target": "~/packages/patterns/src/collection-views/shared/index.ts"
|
|
112
|
-
},
|
|
113
|
-
{
|
|
114
|
-
"path": "parttens/src/collection-views/shared/lib/interactive-descendants.ts",
|
|
115
|
-
"type": "registry:file",
|
|
116
|
-
"content": "export const interactiveDescendants =\n '[&_:is(a[href],button,input,select,textarea,summary,label,[role=button],[role=checkbox],[role=combobox],[role=link],[role=menuitem],[role=option],[role=radio],[role=slider],[role=spinbutton],[role=switch],[role=tab],[role=textbox],[tabindex]:not([tabindex=\"-1\"]),[contenteditable]:not([contenteditable=false]))]:pointer-events-auto'\n",
|
|
117
|
-
"target": "~/packages/patterns/src/collection-views/shared/lib/interactive-descendants.ts"
|
|
118
|
-
},
|
|
119
|
-
{
|
|
120
|
-
"path": "parttens/src/collection-views/shared/lib/project-collection.ts",
|
|
121
|
-
"type": "registry:file",
|
|
122
|
-
"content": "import type {\n CollectionDefinition,\n CollectionGroup,\n CollectionGroupingId,\n CollectionOption,\n} from '../../types/collection'\n\nconst DEFAULT_UNASSIGNED_LABEL = 'Sem valor'\n\ninterface MutableCollectionGroup<TItem>\n extends Omit<CollectionGroup<TItem>, 'items'> {\n items: TItem[]\n}\n\nfunction createGroup<TItem>(\n grouping: string,\n option: CollectionOption,\n): MutableCollectionGroup<TItem> {\n return {\n ...option,\n count: 0,\n grouping,\n items: [],\n value: option.id,\n }\n}\n\nexport function projectCollection<TItem>(\n collection: CollectionDefinition<TItem>,\n groupBy: CollectionGroupingId | null,\n): readonly CollectionGroup<TItem>[] {\n // Ausência de agrupamento não é uma projeção vazia: é a view que renderiza a\n // coleção plana. Chegar aqui sem dimensão é sempre erro de programação — não um\n // estado de usuário a degradar silenciosamente.\n if (groupBy === null) {\n throw new Error(\n 'projectCollection: sem agrupamento não há grupos a projetar.',\n )\n }\n\n const dimension = collection.groupings.find(\n (candidate) => candidate.id === groupBy,\n )\n\n if (!dimension) {\n throw new Error(\n `projectCollection: dimensão \"${groupBy}\" não declarada em collection.groupings.`,\n )\n }\n\n const {\n getGroupId,\n options,\n unassignedLabel = DEFAULT_UNASSIGNED_LABEL,\n } = dimension\n const groups = options.map((option) => createGroup<TItem>(groupBy, option))\n const groupsByValue = new Map(groups.map((group) => [group.value, group]))\n let unassignedGroup: MutableCollectionGroup<TItem> | undefined\n\n for (const item of collection.items) {\n const value = getGroupId(item)\n let group = groupsByValue.get(value)\n\n if (value === null && !group) {\n unassignedGroup = {\n count: 0,\n grouping: groupBy,\n id: `${groupBy}:unassigned`,\n items: [],\n label: unassignedLabel,\n value: null,\n }\n group = unassignedGroup\n groupsByValue.set(null, group)\n } else if (value !== null && !group) {\n group = createGroup(groupBy, { id: value, label: value })\n groups.push(group)\n groupsByValue.set(value, group)\n }\n\n if (!group) continue\n group.items.push(item)\n group.count = group.items.length\n }\n\n if (unassignedGroup) groups.push(unassignedGroup)\n\n return groups.map((group) => ({\n ...group,\n id: group.value === null ? group.id : `${groupBy}:${group.id}`,\n }))\n}\n",
|
|
123
|
-
"target": "~/packages/patterns/src/collection-views/shared/lib/project-collection.ts"
|
|
124
|
-
},
|
|
125
|
-
{
|
|
126
|
-
"path": "parttens/src/collection-views/shared/lib/skeleton-keys.ts",
|
|
127
|
-
"type": "registry:file",
|
|
128
|
-
"content": "export function skeletonKeys(prefix: string, count: number): string[] {\n return Array.from({ length: count }).map(\n (_, position) => `${prefix}-${position + 1}`,\n )\n}\n",
|
|
129
|
-
"target": "~/packages/patterns/src/collection-views/shared/lib/skeleton-keys.ts"
|
|
130
|
-
},
|
|
131
|
-
{
|
|
132
|
-
"path": "parttens/src/collection-views/store/collection-provider.tsx",
|
|
133
|
-
"type": "registry:file",
|
|
134
|
-
"content": "import {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nimport type {\n CollectionDefinition,\n CollectionPreferences,\n CollectionPreferencesChangeDetails,\n CollectionPreferencesChangeReason,\n} from '../types/collection'\n\nfunction haveSamePreferences(\n left: CollectionPreferences | undefined,\n right: CollectionPreferences | undefined,\n): boolean {\n return left?.groupBy === right?.groupBy && left?.view === right?.view\n}\n\nexport interface CollectionProviderProps<TItem> {\n children: ReactNode | ((context: CollectionProviderValue<TItem>) => ReactNode)\n collection: CollectionDefinition<TItem>\n defaultPreferences?: Partial<CollectionPreferences>\n onPreferencesChange?: (\n preferences: CollectionPreferences,\n details: CollectionPreferencesChangeDetails,\n ) => void\n preferences?: CollectionPreferences\n}\n\nexport interface CollectionProviderValue<TItem> {\n collection: CollectionDefinition<TItem>\n preferences: CollectionPreferences\n setPreferences: (\n preferences:\n | CollectionPreferences\n | ((preferences: CollectionPreferences) => CollectionPreferences),\n reason: CollectionPreferencesChangeReason,\n ) => void\n}\n\nexport interface CollectionPreferencesContextValue {\n preferences: CollectionPreferences\n setPreferences: CollectionProviderValue<unknown>['setPreferences']\n}\n\nconst CollectionPreferencesContext =\n createContext<CollectionPreferencesContextValue | null>(null)\n\nexport function CollectionProvider<TItem>({\n children,\n collection,\n defaultPreferences: defaultPreferencesProp,\n onPreferencesChange,\n preferences: controlledPreferences,\n}: CollectionProviderProps<TItem>) {\n const [uncontrolledPreferences, setUncontrolledPreferences] =\n useState<CollectionPreferences>(\n // Sem dimensão declarada por defaultPreferencesProp, agrupa pela primeira que a\n // coleção anunciar — o pacote não tem vocabulário próprio para escolher uma.\n () => ({\n groupBy: collection.groupings[0]?.id ?? null,\n view: 'kanban',\n ...defaultPreferencesProp,\n }),\n )\n const preferences = controlledPreferences ?? uncontrolledPreferences\n const latestPreferencesRef = useRef(preferences)\n const controlledSnapshotRef = useRef(controlledPreferences)\n const wasControlledRef = useRef(controlledPreferences !== undefined)\n\n if (!controlledPreferences) {\n latestPreferencesRef.current = preferences\n wasControlledRef.current = false\n } else if (\n !wasControlledRef.current ||\n !haveSamePreferences(controlledSnapshotRef.current, controlledPreferences)\n ) {\n latestPreferencesRef.current = controlledPreferences\n controlledSnapshotRef.current = controlledPreferences\n wasControlledRef.current = true\n }\n const setPreferences = useCallback(\n (\n update:\n | CollectionPreferences\n | ((preferences: CollectionPreferences) => CollectionPreferences),\n reason: CollectionPreferencesChangeReason,\n ) => {\n const nextPreferences =\n typeof update === 'function'\n ? update(latestPreferencesRef.current)\n : update\n latestPreferencesRef.current = nextPreferences\n if (!controlledPreferences) setUncontrolledPreferences(nextPreferences)\n onPreferencesChange?.(nextPreferences, { reason })\n },\n [controlledPreferences, onPreferencesChange],\n )\n const value = useMemo<CollectionProviderValue<TItem>>(\n () => ({ collection, preferences, setPreferences }),\n [collection, preferences, setPreferences],\n )\n const preferencesValue = useMemo<CollectionPreferencesContextValue>(\n () => ({ preferences, setPreferences }),\n [preferences, setPreferences],\n )\n\n return (\n <CollectionPreferencesContext.Provider value={preferencesValue}>\n {typeof children === 'function' ? children(value) : children}\n </CollectionPreferencesContext.Provider>\n )\n}\n\nexport function useCollectionPreferences(): CollectionPreferencesContextValue {\n const context = useContext(CollectionPreferencesContext)\n\n if (!context) {\n throw new Error(\n 'useCollectionPreferences must be used within CollectionProvider',\n )\n }\n\n return context\n}\n",
|
|
135
|
-
"target": "~/packages/patterns/src/collection-views/store/collection-provider.tsx"
|
|
136
|
-
},
|
|
137
|
-
{
|
|
138
|
-
"path": "parttens/src/collection-views/store/index.ts",
|
|
139
|
-
"type": "registry:file",
|
|
140
|
-
"content": "export type {\n CollectionPreferencesContextValue,\n CollectionProviderProps,\n CollectionProviderValue,\n} from './collection-provider'\nexport {\n CollectionProvider,\n useCollectionPreferences,\n} from './collection-provider'\n",
|
|
141
|
-
"target": "~/packages/patterns/src/collection-views/store/index.ts"
|
|
142
|
-
},
|
|
143
|
-
{
|
|
144
|
-
"path": "parttens/src/collection-views/types/collection.ts",
|
|
145
|
-
"type": "registry:file",
|
|
146
|
-
"content": "import type { ReactNode } from 'react'\n\nexport type CollectionGroupingId = string\nexport type CollectionViewMode =\n | 'calendar'\n | 'datagrid'\n | 'datatable'\n | 'gallery'\n | 'kanban'\n | 'list'\n\n/** @deprecated Use CollectionViewMode. */\nexport type CollectionView = CollectionViewMode\n\nexport interface CollectionOption {\n icon?: ReactNode\n id: string\n label: string\n}\n\nexport interface CollectionGroupingDimension<TItem = unknown> {\n getGroupId: (item: TItem) => string | null\n id: CollectionGroupingId\n label: string\n options: readonly CollectionOption[]\n setGroupId?: (item: TItem, groupId: string | null) => TItem\n /** Label for items whose getGroupId returns null. Defaults to a generic \"unassigned\". */\n unassignedLabel?: string\n}\n\nexport interface CollectionDefinition<TItem = unknown> {\n getKey: (item: TItem) => string | number\n getLabel: (item: TItem) => string\n groupings: readonly CollectionGroupingDimension<TItem>[]\n items: readonly TItem[]\n}\n\nexport interface CollectionPreferences {\n /** `null` é a coleção sem agrupamento, que a Lista e o DataGrid sabem renderizar. */\n groupBy: CollectionGroupingId | null\n view: CollectionViewMode\n}\n\nexport interface CollectionItemChange<TItem = unknown> {\n grouping: CollectionGroupingId\n item: TItem\n previousItem: TItem\n reason: 'grouping'\n}\n\nexport type CollectionPreferencesChangeReason = 'grouping' | 'view'\n\nexport interface CollectionPreferencesChangeDetails {\n reason: CollectionPreferencesChangeReason\n}\n\nexport interface CollectionGroup<TItem = unknown> extends CollectionOption {\n count: number\n grouping: CollectionGroupingId\n items: readonly TItem[]\n value: string | null\n}\n",
|
|
147
|
-
"target": "~/packages/patterns/src/collection-views/types/collection.ts"
|
|
148
|
-
},
|
|
149
|
-
{
|
|
150
|
-
"path": "parttens/src/collection-views/types/index.ts",
|
|
151
|
-
"type": "registry:file",
|
|
152
|
-
"content": "export type {\n CollectionDefinition,\n CollectionGroup,\n CollectionGroupingDimension,\n CollectionGroupingId,\n CollectionItemChange,\n CollectionOption,\n CollectionPreferences,\n CollectionPreferencesChangeDetails,\n CollectionPreferencesChangeReason,\n CollectionView,\n CollectionViewMode,\n} from './collection'\n",
|
|
153
|
-
"target": "~/packages/patterns/src/collection-views/types/index.ts"
|
|
154
|
-
},
|
|
155
|
-
{
|
|
156
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-all-day-cell.tsx",
|
|
157
|
-
"type": "registry:file",
|
|
158
|
-
"content": "'use client'\n\nimport { CollisionPriority } from '@dnd-kit/abstract'\nimport { pointerIntersection } from '@dnd-kit/collision'\nimport { useDroppable } from '@dnd-kit/react'\nimport { calendarDateKey } from '@tc96/helpers/calendar-date'\nimport { cn } from '@tc96/utils'\nimport type { ReactNode } from 'react'\nimport { useId } from 'react'\nimport type { CalendarItemSegment } from '../lib/calendar-layout'\nimport { createCalendarDropId } from '../lib/drag-and-drop'\nimport type { CalendarDate } from '../types'\n\nexport interface CalendarAllDayCellProps<TItem> {\n date: CalendarDate\n dropEnabled: boolean\n renderSegment: (segment: CalendarItemSegment<TItem>) => ReactNode\n segments: readonly CalendarItemSegment<TItem>[]\n}\n\nexport function CalendarAllDayCell<TItem>({\n date,\n dropEnabled,\n renderSegment,\n segments,\n}: CalendarAllDayCellProps<TItem>) {\n const instanceId = useId()\n const dateKey = calendarDateKey(date)\n const { isDropTarget, ref } = useDroppable({\n accept: 'calendar-item-all-day',\n collisionDetector: pointerIntersection,\n collisionPriority: CollisionPriority.Lowest,\n data: { dateKey, type: 'all-day' },\n disabled: !dropEnabled,\n id: createCalendarDropId('all-day', dateKey, instanceId),\n type: 'calendar-all-day',\n })\n\n return (\n <div\n className={cn(\n 'flex min-h-7 min-w-0 flex-col gap-0.5 border-border/80 border-s p-0.5',\n isDropTarget && 'bg-accent/40',\n )}\n data-calendar-all-day-date={dateKey}\n ref={ref}\n >\n {segments.map((segment) => (\n <div className=\"min-w-0\" key={segment.itemKey}>\n {renderSegment(segment)}\n </div>\n ))}\n </div>\n )\n}\n",
|
|
159
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-all-day-cell.tsx"
|
|
160
|
-
},
|
|
161
|
-
{
|
|
162
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-day-column.tsx",
|
|
163
|
-
"type": "registry:file",
|
|
164
|
-
"content": "'use client'\n\nimport { CollisionPriority } from '@dnd-kit/abstract'\nimport { pointerIntersection } from '@dnd-kit/collision'\nimport { useDroppable } from '@dnd-kit/react'\nimport { calendarDateKey } from '@tc96/helpers/calendar-date'\nimport { cn } from '@tc96/utils'\nimport type { MouseEvent, PointerEvent, ReactNode } from 'react'\nimport { useId, useRef } from 'react'\nimport type { CalendarItemSegment, TimeGridLane } from '../lib/calendar-layout'\nimport { timeGridPosition } from '../lib/calendar-layout'\nimport { createCalendarDropId } from '../lib/drag-and-drop'\nimport { slotFromOffset } from '../lib/slot'\nimport type { CalendarDate, CalendarSlot } from '../types'\nimport { CalendarItemSkeleton } from './calendar-item-skeleton'\n\nexport interface CalendarDayColumnProps<TItem> {\n date: CalendarDate\n dropEnabled: boolean\n headingLabel: string\n isToday: boolean\n lanes: ReadonlyMap<string, TimeGridLane>\n loading: boolean\n loadingItemLabel?: string\n /** Minutos do instante corrente no fuso — posiciona a linha \"agora\". */\n nowMinutes: number | null\n onSelectSlot?: (slot: CalendarSlot) => void\n renderSegment: (segment: CalendarItemSegment<TItem>) => ReactNode\n segments: readonly CalendarItemSegment<TItem>[]\n snapMinutes?: number\n}\n\nexport function CalendarDayColumn<TItem>({\n date,\n dropEnabled,\n headingLabel,\n isToday,\n lanes,\n loading,\n loadingItemLabel,\n nowMinutes,\n onSelectSlot,\n renderSegment,\n segments,\n snapMinutes = 15,\n}: CalendarDayColumnProps<TItem>) {\n const instanceId = useId()\n const titleId = `calendar-day-column-title-${instanceId}`\n const dateKey = calendarDateKey(date)\n const { isDropTarget, ref } = useDroppable({\n accept: 'calendar-item',\n collisionDetector: pointerIntersection,\n collisionPriority: CollisionPriority.Lowest,\n data: { dateKey, type: 'time-column' },\n disabled: !dropEnabled,\n id: createCalendarDropId('time-column', dateKey, instanceId),\n type: 'calendar-time-column',\n })\n\n const pressedOnSlot = useRef(false)\n const selectSlot = onSelectSlot\n ? {\n onClick: (event: MouseEvent<HTMLDivElement>) => {\n const pressed = pressedOnSlot.current\n pressedOnSlot.current = false\n if (!pressed || event.target !== event.currentTarget) return\n\n const rect = event.currentTarget.getBoundingClientRect()\n onSelectSlot({\n day: date,\n ...slotFromOffset({\n height: rect.height,\n offsetY: event.clientY - rect.top,\n snapMinutes,\n }),\n })\n },\n onPointerDown: (event: PointerEvent<HTMLDivElement>) => {\n pressedOnSlot.current = event.target === event.currentTarget\n },\n }\n : {}\n\n return (\n <section\n aria-labelledby={titleId}\n className=\"relative min-w-0 border-border/80 border-s\"\n >\n <h3 className=\"sr-only\" id={titleId}>\n {headingLabel}\n </h3>\n <div\n className={cn(\n // Linhas de hora por gradiente repetido: sem 24 spans por coluna e\n // sem medir o container.\n 'absolute inset-0 bg-[repeating-linear-gradient(to_bottom,var(--border)_0,var(--border)_1px,transparent_1px,transparent_calc(100%/24))]',\n isDropTarget && 'bg-accent/30',\n )}\n data-calendar-date={dateKey}\n data-today={isToday ? '' : undefined}\n ref={ref}\n {...selectSlot}\n >\n {loading ? (\n <div className=\"absolute inset-x-1 top-[30%] h-[6%]\">\n <CalendarItemSkeleton\n display=\"block\"\n {...(loadingItemLabel ? { label: loadingItemLabel } : {})}\n />\n </div>\n ) : (\n segments.map((segment) => {\n const position = timeGridPosition(segment)\n const lane = lanes.get(segment.itemKey) ?? {\n laneCount: 1,\n laneIndex: 0,\n }\n const width = 100 / lane.laneCount\n\n return (\n <div\n className=\"@container-size/calendar-item absolute px-px\"\n key={segment.itemKey}\n style={{\n height: `${position.heightPct}%`,\n left: `${lane.laneIndex * width}%`,\n top: `${position.topPct}%`,\n width: `${width}%`,\n }}\n >\n {renderSegment(segment)}\n </div>\n )\n })\n )}\n\n {isToday && nowMinutes !== null ? (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-x-0 z-10 border-destructive border-t-2\"\n data-slot=\"calendar-now-line\"\n style={{ top: `${(nowMinutes / 1440) * 100}%` }}\n >\n <span className=\"-start-1 -top-[5px] absolute size-2 rounded-full bg-destructive\" />\n </div>\n ) : null}\n </div>\n </section>\n )\n}\n",
|
|
165
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-day-column.tsx"
|
|
166
|
-
},
|
|
167
|
-
{
|
|
168
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-event-chip.tsx",
|
|
169
|
-
"type": "registry:file",
|
|
170
|
-
"content": "'use client'\n\nimport { mergeProps } from '@base-ui/react/merge-props'\nimport { useRender } from '@base-ui/react/use-render'\nimport { cn } from '@tc96/utils'\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport type { ComponentPropsWithoutRef, ReactElement } from 'react'\n\nexport type CalendarEventChipTone = VariantProps<\n typeof calendarEventChipVariants\n>['tone']\nexport type CalendarEventChipDisplay = 'block' | 'chip'\n\nexport const calendarEventChipVariants = cva(\n 'relative isolate flex min-w-0 select-none overflow-hidden rounded-md border-s-2 text-start text-xs leading-4 has-focus-visible:ring-2 has-focus-visible:ring-primary [&_[data-calendar-item-action]]:relative [&_[data-calendar-item-action]]:z-10',\n {\n defaultVariants: {\n completed: false,\n display: 'chip',\n tone: 'neutral',\n },\n variants: {\n completed: {\n // Concluída aparece com distinção visual, nunca some (TASK-044).\n false: null,\n true: 'opacity-60 [&_[data-slot=calendar-event-chip-title]]:line-through',\n },\n display: {\n block:\n 'h-full w-full flex-col gap-0.5 px-2 py-1 [&_[data-slot=calendar-event-chip-time]]:order-last [&_[data-slot=calendar-event-chip-title]]:flex-initial [@container_calendar-item_(height<2.625rem)]:flex-row [@container_calendar-item_(height<2.625rem)]:flex-wrap [@container_calendar-item_(height<2.625rem)]:content-start [@container_calendar-item_(height<2.625rem)]:gap-x-1 [@container_calendar-item_(height<2.625rem)]:gap-y-6 [@container_calendar-item_(height<2.625rem)]:py-0.5 [@container_calendar-item_(width<3.5rem)]:px-px',\n chip: 'w-full items-center gap-1 px-1.5 py-0.5',\n },\n tone: {\n destructive:\n 'border-s-destructive bg-destructive/8 text-destructive-foreground dark:bg-destructive/16',\n neutral:\n 'border-s-muted-foreground/40 bg-muted/60 text-foreground dark:bg-muted/40',\n primary:\n 'border-s-primary bg-primary/8 text-foreground dark:bg-primary/16',\n success:\n 'border-s-success bg-success/8 text-success-foreground dark:bg-success/16',\n warning:\n 'border-s-warning bg-warning/8 text-warning-foreground dark:bg-warning/16',\n },\n },\n },\n)\n\nexport interface CalendarEventChipProps\n extends useRender.ComponentProps<'article'> {\n /** Distinção visual de item concluído (`TASK-044`). */\n completed?: boolean\n /** `chip` é a linha única do mês e da faixa all-day; `block` preenche o segmento do time grid. */\n display?: CalendarEventChipDisplay\n /** Vocabulário visual neutro — o consumidor mapeia o domínio para um tom. */\n tone?: CalendarEventChipTone\n}\n\nexport type CalendarEventChipTimeProps = ComponentPropsWithoutRef<'time'>\nexport type CalendarEventChipTitleProps = ComponentPropsWithoutRef<'span'>\nexport type CalendarEventChipOpenTriggerProps =\n ComponentPropsWithoutRef<'button'>\n\nexport function CalendarEventChip({\n className,\n completed = false,\n display = 'chip',\n render,\n tone = 'neutral',\n ...props\n}: CalendarEventChipProps): ReactElement {\n const defaultProps = {\n className: cn(\n calendarEventChipVariants({ completed, display, tone }),\n className,\n ),\n 'data-completed': completed ? '' : undefined,\n 'data-display': display,\n 'data-slot': 'calendar-event-chip',\n 'data-tone': tone,\n }\n\n return useRender({\n defaultTagName: 'article',\n props: mergeProps<'article'>(defaultProps, props),\n render,\n })\n}\n\nexport function CalendarEventChipTime({\n className,\n ...props\n}: CalendarEventChipTimeProps): ReactElement {\n return (\n <time\n className={cn(\n 'shrink-0 whitespace-nowrap font-medium tabular-nums opacity-70',\n className,\n )}\n data-slot=\"calendar-event-chip-time\"\n {...props}\n />\n )\n}\n\nexport function CalendarEventChipTitle({\n className,\n ...props\n}: CalendarEventChipTitleProps): ReactElement {\n return (\n <span\n className={cn('min-w-0 flex-1 truncate font-medium', className)}\n data-slot=\"calendar-event-chip-title\"\n {...props}\n />\n )\n}\n\n/**\n * Alvo de clique do chip inteiro, esticado sobre ele.\n *\n * O chip é `article`, não `button`: controle interno futuro segue clicável\n * marcado com `data-calendar-item-action`, que o eleva acima deste gatilho — o\n * mesmo desenho do KanbanCard. O arraste fica numa alça fora do chip.\n */\nexport function CalendarEventChipOpenTrigger({\n className,\n ...props\n}: CalendarEventChipOpenTriggerProps): ReactElement {\n return (\n <button\n className={cn(\n 'absolute inset-0 cursor-pointer rounded-[inherit] outline-none',\n className,\n )}\n data-slot=\"calendar-event-chip-open-trigger\"\n type=\"button\"\n {...props}\n />\n )\n}\n",
|
|
171
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-event-chip.tsx"
|
|
172
|
-
},
|
|
173
|
-
{
|
|
174
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-item-skeleton.tsx",
|
|
175
|
-
"type": "registry:file",
|
|
176
|
-
"content": "import { Skeleton } from '@tc96/ui/skeleton'\nimport { cn } from '@tc96/utils'\nimport type { ReactElement } from 'react'\n\nexport interface CalendarItemSkeletonProps {\n className?: string\n display?: 'block' | 'chip'\n label?: string\n}\n\nexport function CalendarItemSkeleton({\n className,\n display = 'chip',\n label = 'Carregando compromisso',\n}: CalendarItemSkeletonProps): ReactElement {\n return (\n <output\n aria-busy=\"true\"\n aria-label={label}\n className={cn(\n 'pointer-events-none flex min-w-0 select-none gap-1 overflow-hidden rounded-md border-s-2 border-s-muted-foreground/20 bg-muted/40',\n display === 'block'\n ? 'h-full w-full flex-col px-2 py-1'\n : 'px-1.5 py-0.5',\n className,\n )}\n data-slot=\"calendar-item-skeleton\"\n >\n <Skeleton aria-hidden=\"true\" className=\"h-3 w-8 shrink-0\" />\n <Skeleton aria-hidden=\"true\" className=\"h-3 w-2/3\" />\n </output>\n )\n}\n",
|
|
177
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-item-skeleton.tsx"
|
|
178
|
-
},
|
|
179
|
-
{
|
|
180
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-month-day-cell.tsx",
|
|
181
|
-
"type": "registry:file",
|
|
182
|
-
"content": "'use client'\n\nimport { CollisionPriority } from '@dnd-kit/abstract'\nimport { pointerIntersection } from '@dnd-kit/collision'\nimport { useDroppable } from '@dnd-kit/react'\nimport { calendarDateKey } from '@tc96/helpers/calendar-date'\nimport {\n Popover,\n PopoverClose,\n PopoverPopup,\n PopoverTrigger,\n} from '@tc96/ui/popover'\nimport { cn } from '@tc96/utils'\nimport type { ReactNode } from 'react'\nimport { useId } from 'react'\nimport type { CalendarItemSegment } from '../lib/calendar-layout'\nimport { createCalendarDropId } from '../lib/drag-and-drop'\nimport type { CalendarDate } from '../types'\nimport { CalendarItemSkeleton } from './calendar-item-skeleton'\n\nexport interface CalendarMonthDayCellProps<TItem> {\n date: CalendarDate\n dayLabel: string\n dropEnabled: boolean\n isOutsideMonth: boolean\n isToday: boolean\n loading: boolean\n loadingItemLabel?: string\n maxVisibleItems: number\n onSelectDay?: (date: CalendarDate) => void\n overflowLabel: (hiddenCount: number) => string\n renderSegment: (segment: CalendarItemSegment<TItem>) => ReactNode\n segments: readonly CalendarItemSegment<TItem>[]\n showSkeleton: boolean\n}\n\nexport function CalendarMonthDayCell<TItem>({\n date,\n dayLabel,\n dropEnabled,\n isOutsideMonth,\n isToday,\n loading,\n loadingItemLabel,\n maxVisibleItems,\n onSelectDay,\n overflowLabel,\n renderSegment,\n segments,\n showSkeleton,\n}: CalendarMonthDayCellProps<TItem>) {\n const instanceId = useId()\n const dateKey = calendarDateKey(date)\n const { isDropTarget, ref } = useDroppable({\n accept: ['calendar-item', 'calendar-item-all-day'],\n collisionDetector: pointerIntersection,\n collisionPriority: CollisionPriority.Lowest,\n data: { dateKey, type: 'day' },\n disabled: !dropEnabled,\n id: createCalendarDropId('day', dateKey, instanceId),\n type: 'calendar-day',\n })\n const visibleSegments = loading ? [] : segments.slice(0, maxVisibleItems)\n const hiddenSegments = loading ? [] : segments.slice(maxVisibleItems)\n const hiddenCount = hiddenSegments.length\n\n return (\n <div\n className={cn(\n 'flex min-h-24 min-w-0 flex-col gap-1 p-1.5',\n isOutsideMonth && 'text-muted-foreground',\n isDropTarget\n ? 'bg-accent/40 ring-1 ring-ring ring-inset'\n : isOutsideMonth\n ? 'bg-muted/30'\n : 'bg-background',\n )}\n data-calendar-date={dateKey}\n data-outside-month={isOutsideMonth ? '' : undefined}\n data-today={isToday ? '' : undefined}\n ref={ref}\n >\n <span\n aria-hidden=\"true\"\n className={cn(\n 'flex size-6 items-center justify-center rounded-full text-xs tabular-nums',\n isToday && 'bg-primary font-semibold text-primary-foreground',\n )}\n >\n {date.day}\n </span>\n\n {showSkeleton ? (\n <CalendarItemSkeleton\n {...(loadingItemLabel ? { label: loadingItemLabel } : {})}\n />\n ) : null}\n\n {visibleSegments.map((segment) => (\n <div className=\"min-w-0\" key={segment.itemKey}>\n {renderSegment(segment)}\n </div>\n ))}\n\n {hiddenCount > 0 ? (\n <Popover>\n <PopoverTrigger\n aria-label={`Mostrar mais ${hiddenCount} ${hiddenCount === 1 ? 'item' : 'itens'} de ${dayLabel}`}\n className=\"self-start rounded-sm px-1.5 text-muted-foreground text-xs outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-popup-open:text-foreground\"\n >\n {overflowLabel(hiddenCount)}\n </PopoverTrigger>\n <PopoverPopup align=\"start\" aria-label={dayLabel} className=\"w-72\">\n <div className=\"flex flex-col gap-2\">\n {onSelectDay ? (\n <PopoverClose\n aria-label={`Mostrar todos os ${segments.length} itens de ${dayLabel}`}\n className=\"self-start rounded-sm text-start font-medium text-sm outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\"\n onClick={() => onSelectDay(date)}\n >\n {dayLabel}\n </PopoverClose>\n ) : (\n <p className=\"font-medium text-sm\">{dayLabel}</p>\n )}\n <ul className=\"flex flex-col gap-1\">\n {hiddenSegments.map((segment) => (\n <li className=\"min-w-0\" key={segment.itemKey}>\n {renderSegment(segment)}\n </li>\n ))}\n </ul>\n </div>\n </PopoverPopup>\n </Popover>\n ) : null}\n </div>\n )\n}\n",
|
|
183
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-month-day-cell.tsx"
|
|
184
|
-
},
|
|
185
|
-
{
|
|
186
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-month-grid.tsx",
|
|
187
|
-
"type": "registry:file",
|
|
188
|
-
"content": "'use client'\n\nimport {\n calendarDateKey,\n isSameCalendarDate,\n} from '@tc96/helpers/calendar-date'\nimport type { ReactNode } from 'react'\nimport type { CalendarItemSegment } from '../lib/calendar-layout'\nimport type { CalendarDate } from '../types'\nimport { CalendarMonthDayCell } from './calendar-month-day-cell'\n\nexport interface CalendarMonthGridProps<TItem> {\n anchorMonth: number\n dayLabelOf: (date: CalendarDate) => string\n dropEnabled: boolean\n gridLabel: string\n loading: boolean\n loadingItemCount: number\n loadingItemLabel?: string\n maxVisibleItems: number\n onSelectDay?: (date: CalendarDate) => void\n range: readonly CalendarDate[]\n renderSegment: (segment: CalendarItemSegment<TItem>) => ReactNode\n segmentsByDay: ReadonlyMap<string, CalendarItemSegment<TItem>[]>\n today: CalendarDate\n weekdayLabels: readonly string[]\n}\n\nexport function CalendarMonthGrid<TItem>({\n anchorMonth,\n dayLabelOf,\n dropEnabled,\n gridLabel,\n loading,\n loadingItemCount,\n loadingItemLabel,\n maxVisibleItems,\n onSelectDay,\n range,\n renderSegment,\n segmentsByDay,\n today,\n weekdayLabels,\n}: CalendarMonthGridProps<TItem>) {\n const weeks: CalendarDate[][] = []\n for (let index = 0; index < range.length; index += 7) {\n weeks.push(range.slice(index, index + 7) as CalendarDate[])\n }\n\n return (\n <div\n className=\"grid min-w-0 overflow-hidden rounded-lg border border-border/80 bg-border/70\"\n data-slot=\"calendar-month-grid\"\n >\n <h2 className=\"sr-only\">{gridLabel}</h2>\n <div aria-hidden=\"true\" className=\"grid grid-cols-7 gap-px\">\n {weekdayLabels.map((label) => (\n <div\n className=\"bg-background px-1.5 py-2 text-center font-medium text-muted-foreground text-xs\"\n key={label}\n >\n {label}\n </div>\n ))}\n </div>\n\n {weeks.map((week, weekIndex) => (\n <div\n className=\"grid grid-cols-7 gap-px pt-px\"\n key={calendarDateKey(week[0] as CalendarDate)}\n >\n {week.map((date, dayIndex) => {\n const position = weekIndex * 7 + dayIndex\n\n return (\n <CalendarMonthDayCell\n date={date}\n dayLabel={dayLabelOf(date)}\n dropEnabled={dropEnabled}\n isOutsideMonth={date.month !== anchorMonth}\n isToday={isSameCalendarDate(date, today)}\n key={calendarDateKey(date)}\n loading={loading}\n maxVisibleItems={maxVisibleItems}\n overflowLabel={(hiddenCount) => `+${hiddenCount}`}\n renderSegment={renderSegment}\n segments={segmentsByDay.get(calendarDateKey(date)) ?? []}\n showSkeleton={loading && position < loadingItemCount}\n {...(loadingItemLabel ? { loadingItemLabel } : {})}\n {...(onSelectDay ? { onSelectDay } : {})}\n />\n )\n })}\n </div>\n ))}\n </div>\n )\n}\n",
|
|
189
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-month-grid.tsx"
|
|
190
|
-
},
|
|
191
|
-
{
|
|
192
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-resize-handle.tsx",
|
|
193
|
-
"type": "registry:file",
|
|
194
|
-
"content": "'use client'\n\nimport { cn } from '@tc96/utils'\nimport type { PointerEvent } from 'react'\nimport { useRef } from 'react'\nimport {\n type CalendarResizeEdge,\n type CalendarResizeGrid,\n resizeCalendarSchedule,\n} from '../lib/resize'\nimport type { CalendarItemSchedule } from '../types'\n\nconst MINUTES_PER_DAY = 1440\n\ninterface ResizeGesture {\n edgeTime: number\n originY: number\n pixelsPerMinute: number\n pointerId: number\n preview: CalendarItemSchedule | null\n source: CalendarItemSchedule\n}\n\nexport interface CalendarResizeHandleProps {\n edge: CalendarResizeEdge\n grid: CalendarResizeGrid\n onCommit: (schedule: CalendarItemSchedule) => void\n onPreview: (schedule: CalendarItemSchedule | null) => void\n schedule: CalendarItemSchedule\n}\n\nconst edgeTimeOf = (schedule: CalendarItemSchedule, edge: CalendarResizeEdge) =>\n (edge === 'start' ? schedule.start : schedule.end)?.getTime() ?? 0\n\nexport function CalendarResizeHandle({\n edge,\n grid,\n onCommit,\n onPreview,\n schedule,\n}: CalendarResizeHandleProps) {\n const gestureRef = useRef<ResizeGesture | null>(null)\n\n const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n const column = event.currentTarget.closest('[data-calendar-date]')\n const height = column?.getBoundingClientRect().height ?? 0\n if (height <= 0) return\n\n event.preventDefault()\n event.currentTarget.setPointerCapture(event.pointerId)\n gestureRef.current = {\n edgeTime: edgeTimeOf(schedule, edge),\n originY: event.clientY,\n pixelsPerMinute: height / MINUTES_PER_DAY,\n pointerId: event.pointerId,\n preview: null,\n source: schedule,\n }\n }\n\n const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {\n const gesture = gestureRef.current\n if (!gesture || gesture.pointerId !== event.pointerId) return\n\n const next = resizeCalendarSchedule(\n gesture.source,\n edge,\n (event.clientY - gesture.originY) / gesture.pixelsPerMinute,\n grid,\n )\n if (!next) return\n const edgeTime = edgeTimeOf(next, edge)\n if (edgeTime === gesture.edgeTime) return\n\n gesture.edgeTime = edgeTime\n gesture.preview =\n edgeTime === edgeTimeOf(gesture.source, edge) ? null : next\n onPreview(gesture.preview)\n }\n\n const finishGesture = (event: PointerEvent<HTMLDivElement>) => {\n const gesture = gestureRef.current\n if (!gesture || gesture.pointerId !== event.pointerId) return null\n\n gestureRef.current = null\n if (event.currentTarget.hasPointerCapture(event.pointerId))\n event.currentTarget.releasePointerCapture(event.pointerId)\n return gesture\n }\n\n const handlePointerUp = (event: PointerEvent<HTMLDivElement>) => {\n const gesture = finishGesture(event)\n if (!gesture) return\n\n if (gesture.preview) onCommit(gesture.preview)\n else onPreview(null)\n }\n\n const handlePointerCancel = (event: PointerEvent<HTMLDivElement>) => {\n if (finishGesture(event)) onPreview(null)\n }\n\n return (\n <div\n aria-hidden=\"true\"\n className={cn(\n 'absolute inset-x-0 z-30 h-1.5 cursor-ns-resize touch-none rounded-sm hover:bg-foreground/10 pointer-coarse:h-3',\n edge === 'start' ? 'top-0' : 'bottom-0',\n )}\n data-calendar-item-resize={edge}\n onPointerCancel={handlePointerCancel}\n onPointerDown={handlePointerDown}\n onPointerMove={handlePointerMove}\n onPointerUp={handlePointerUp}\n />\n )\n}\n",
|
|
195
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-resize-handle.tsx"
|
|
196
|
-
},
|
|
197
|
-
{
|
|
198
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-segment-content.tsx",
|
|
199
|
-
"type": "registry:file",
|
|
200
|
-
"content": "'use client'\n\nimport { parseCalendarDateKey } from '@tc96/helpers/calendar-date'\nimport type { ReactNode } from 'react'\nimport { memo } from 'react'\nimport type { CalendarItemPlacement, CalendarItemRenderContext } from '../types'\n\ninterface CalendarSegmentContentProps<TItem> {\n dateKey: string\n endMinutes: number | null\n isEnd: boolean\n isStart: boolean\n item: TItem\n placement: CalendarItemPlacement\n renderItem: (item: TItem, context: CalendarItemRenderContext) => ReactNode\n startMinutes: number | null\n}\n\nfunction CalendarSegmentContentImpl<TItem>({\n dateKey,\n endMinutes,\n isEnd,\n isStart,\n item,\n placement,\n renderItem,\n startMinutes,\n}: CalendarSegmentContentProps<TItem>) {\n const date = parseCalendarDateKey(dateKey)\n if (!date) return null\n\n return renderItem(item, {\n date,\n endMinutes,\n isEnd,\n isStart,\n placement,\n startMinutes,\n })\n}\n\nexport const CalendarSegmentContent = memo(\n CalendarSegmentContentImpl,\n) as typeof CalendarSegmentContentImpl\n",
|
|
201
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-segment-content.tsx"
|
|
202
|
-
},
|
|
203
|
-
{
|
|
204
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-time-grid.tsx",
|
|
205
|
-
"type": "registry:file",
|
|
206
|
-
"content": "'use client'\n\nimport {\n calendarDateKey,\n isSameCalendarDate,\n} from '@tc96/helpers/calendar-date'\nimport { ScrollArea } from '@tc96/ui/scroll-area'\nimport { cn } from '@tc96/utils'\nimport type { ReactNode } from 'react'\nimport { useEffect, useRef } from 'react'\nimport type { CalendarItemSegment, TimeGridLane } from '../lib/calendar-layout'\nimport type { CalendarDate, CalendarSlot } from '../types'\nimport { CalendarAllDayCell } from './calendar-all-day-cell'\nimport { CalendarDayColumn } from './calendar-day-column'\n\n/** Altura fixa por hora: layout determinístico, sem medir o container. */\nconst HOUR_HEIGHT_REM = 3\nconst INITIAL_SCROLL_HOUR = 7\n\nexport interface CalendarTimeGridProps<TItem> {\n allDaySegmentsByDay: ReadonlyMap<string, CalendarItemSegment<TItem>[]>\n columnHeadingOf: (date: CalendarDate) => string\n dayNumberLabels: readonly { label: string; weekday: string }[]\n dropEnabled: boolean\n gridLabel: string\n hourLabels: readonly string[]\n lanesByDay: ReadonlyMap<string, ReadonlyMap<string, TimeGridLane>>\n loading: boolean\n loadingItemLabel?: string\n nowMinutes: number | null\n onSelectSlot?: (slot: CalendarSlot) => void\n range: readonly CalendarDate[]\n renderAllDaySegment: (segment: CalendarItemSegment<TItem>) => ReactNode\n renderSegment: (segment: CalendarItemSegment<TItem>) => ReactNode\n snapMinutes: number\n timedSegmentsByDay: ReadonlyMap<string, CalendarItemSegment<TItem>[]>\n timeZoneLabel: string\n today: CalendarDate\n}\n\nexport function CalendarTimeGrid<TItem>({\n allDaySegmentsByDay,\n columnHeadingOf,\n dayNumberLabels,\n dropEnabled,\n gridLabel,\n hourLabels,\n lanesByDay,\n loading,\n loadingItemLabel,\n nowMinutes,\n onSelectSlot,\n range,\n renderAllDaySegment,\n renderSegment,\n snapMinutes,\n timedSegmentsByDay,\n timeZoneLabel,\n today,\n}: CalendarTimeGridProps<TItem>) {\n const viewportRef = useRef<HTMLDivElement | null>(null)\n const columnsTemplate = `4rem repeat(${range.length}, minmax(0, 1fr))`\n\n // O dia útil começa bem depois da meia-noite; abrir a grade já em ~07h evita\n // um scroll manual a cada visita.\n useEffect(() => {\n const viewport = viewportRef.current?.querySelector(\n '[data-slot=scroll-area-viewport]',\n )\n if (!(viewport instanceof HTMLElement)) return\n\n const rem =\n Number.parseFloat(getComputedStyle(document.documentElement).fontSize) ||\n 16\n viewport.scrollTop = INITIAL_SCROLL_HOUR * HOUR_HEIGHT_REM * rem\n }, [])\n\n return (\n <div\n className=\"group/time-grid flex h-full min-h-0 min-w-0 flex-col overflow-hidden rounded-lg border border-border/80\"\n data-slot=\"calendar-time-grid\"\n >\n <h2 className=\"sr-only\">{gridLabel}</h2>\n\n <div\n className=\"grid border-border/80 border-b group-has-[[data-has-overflow-y]]/time-grid:pe-2.5\"\n style={{ gridTemplateColumns: columnsTemplate }}\n >\n <div className=\"px-2 py-2 text-end text-[0.625rem] text-muted-foreground\">\n {timeZoneLabel}\n </div>\n {range.map((date, index) => {\n const labels = dayNumberLabels[index]\n\n return (\n <div\n aria-hidden=\"true\"\n className=\"flex items-baseline justify-center gap-1 border-border/80 border-s px-1.5 py-2\"\n data-today={isSameCalendarDate(date, today) ? '' : undefined}\n key={calendarDateKey(date)}\n >\n <span className=\"text-muted-foreground text-xs\">\n {labels?.weekday}\n </span>\n <span\n className={cn(\n 'flex size-6 items-center justify-center rounded-full font-medium text-sm tabular-nums',\n isSameCalendarDate(date, today) &&\n 'bg-primary text-primary-foreground',\n )}\n >\n {labels?.label}\n </span>\n </div>\n )\n })}\n </div>\n\n <div\n className=\"grid border-border/80 border-b group-has-[[data-has-overflow-y]]/time-grid:pe-2.5\"\n style={{ gridTemplateColumns: columnsTemplate }}\n >\n <div className=\"px-2 py-1 text-end text-[0.625rem] text-muted-foreground\">\n <span className=\"sr-only\">Dia inteiro</span>\n <span aria-hidden=\"true\">dia inteiro</span>\n </div>\n {range.map((date) => (\n <CalendarAllDayCell\n date={date}\n dropEnabled={dropEnabled}\n key={calendarDateKey(date)}\n renderSegment={renderAllDaySegment}\n segments={allDaySegmentsByDay.get(calendarDateKey(date)) ?? []}\n />\n ))}\n </div>\n\n <ScrollArea\n className=\"min-h-0 flex-1\"\n fill\n ref={viewportRef}\n scrollbarGutter\n >\n <div\n className=\"grid\"\n style={{\n gridTemplateColumns: columnsTemplate,\n height: `${24 * HOUR_HEIGHT_REM}rem`,\n }}\n >\n <div aria-hidden=\"true\" className=\"relative\">\n {hourLabels.map((label, hour) => (\n <span\n className=\"absolute end-2 -translate-y-1/2 text-[0.625rem] text-muted-foreground tabular-nums\"\n key={label}\n style={{ top: `${(hour / 24) * 100}%` }}\n >\n {hour === 0 ? '' : label}\n </span>\n ))}\n </div>\n\n {range.map((date) => (\n <CalendarDayColumn\n date={date}\n dropEnabled={dropEnabled}\n headingLabel={columnHeadingOf(date)}\n isToday={isSameCalendarDate(date, today)}\n key={calendarDateKey(date)}\n lanes={lanesByDay.get(calendarDateKey(date)) ?? new Map()}\n loading={loading}\n nowMinutes={nowMinutes}\n renderSegment={renderSegment}\n segments={timedSegmentsByDay.get(calendarDateKey(date)) ?? []}\n snapMinutes={snapMinutes}\n {...(loadingItemLabel ? { loadingItemLabel } : {})}\n {...(onSelectSlot ? { onSelectSlot } : {})}\n />\n ))}\n </div>\n </ScrollArea>\n </div>\n )\n}\n",
|
|
207
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-time-grid.tsx"
|
|
208
|
-
},
|
|
209
|
-
{
|
|
210
|
-
"path": "parttens/src/collection-views/views/calendar/components/calendar-view.tsx",
|
|
211
|
-
"type": "registry:file",
|
|
212
|
-
"content": "'use client'\n\nimport { DragDropProvider, DragOverlay } from '@dnd-kit/react'\nimport { calendarDateKey, calendarRange } from '@tc96/helpers/calendar-date'\nimport { toZonedDateTime } from '@tc96/helpers/zoned-date-time'\nimport type { ReactNode } from 'react'\nimport { useLayoutEffect, useMemo, useRef } from 'react'\nimport type { CollectionDefinition } from '../../../types/collection'\nimport { useCalendarDragAndDrop } from '../hooks/use-calendar-drag-and-drop'\nimport { useNow } from '../hooks/use-now'\nimport type { CalendarItemSegment, TimeGridLane } from '../lib/calendar-layout'\nimport { assignTimeGridLanes, segmentItems } from '../lib/calendar-layout'\nimport { createCalendarItemDragId } from '../lib/drag-and-drop'\nimport {\n type CalendarResizeDirection,\n type CalendarResizeEdge,\n stepCalendarScheduleEdge,\n} from '../lib/resize'\nimport type {\n CalendarDate,\n CalendarItemRenderContext,\n CalendarItemReschedule,\n CalendarItemSchedule,\n CalendarSlot,\n CalendarViewMode,\n} from '../types'\nimport { CalendarMonthGrid } from './calendar-month-grid'\nimport { CalendarResizeHandle } from './calendar-resize-handle'\nimport { CalendarSegmentContent } from './calendar-segment-content'\nimport { CalendarTimeGrid } from './calendar-time-grid'\nimport { DraggableCalendarItem } from './draggable-calendar-item'\n\nexport interface CalendarViewProps<TItem = unknown> {\n /** Instante de referência; a view projeta o período visível no `timeZone`. */\n anchor: Date\n /** Só `getKey`, `getLabel` e `items` são lidos — data não é dimensão de agrupamento estática. */\n collection: CollectionDefinition<TItem>\n /** Nome acessível do arraste (\"Mover {label}\"). Default: `collection.getLabel`. */\n getItemLabel?: (item: TItem) => string\n /** `null` = item sem lugar no calendário; a view não o renderiza. */\n getItemSchedule: (item: TItem) => CalendarItemSchedule | null\n loading?: boolean\n /** Esqueletos distribuídos pela grade durante o carregamento. */\n loadingItemCount?: number\n loadingItemLabel?: string\n /** Localidade dos rótulos de data e hora. */\n locale?: string\n /** Chips visíveis por célula do mês antes do \"+N\". */\n maxVisibleMonthItems?: number\n mode: CalendarViewMode\n /** Instante corrente (linha \"agora\", destaque de hoje). Sem controle, avança por minuto. */\n now?: Date\n /** Reagendamento otimista: `false` (ou rejeição) devolve o item ao lugar. */\n onItemReschedule?: (\n change: CalendarItemReschedule<TItem>,\n ) => boolean | Promise<boolean>\n onSelectSlot?: (slot: CalendarSlot) => void\n /** Título do dia no popover do \"+N\" de uma célula cheia do mês. */\n onSelectDay?: (date: CalendarDate) => void\n /** Incremento do arraste no time grid, em minutos. */\n snapMinutes?: number\n renderItem: (item: TItem, context: CalendarItemRenderContext) => ReactNode\n /** IANA, ex. `America/Fortaleza` — toda bucketização e drop convertem na borda. */\n timeZone: string\n /** 0 = domingo. */\n weekStartsOn?: 0 | 1\n}\n\nexport function CalendarView<TItem>({\n anchor,\n collection,\n getItemLabel,\n getItemSchedule,\n loading = false,\n loadingItemCount = 3,\n loadingItemLabel,\n locale = 'pt-BR',\n maxVisibleMonthItems = 3,\n mode,\n now: controlledNow,\n onItemReschedule,\n onSelectDay,\n onSelectSlot,\n renderItem,\n snapMinutes = 15,\n timeZone,\n weekStartsOn = 0,\n}: CalendarViewProps<TItem>) {\n const now = useNow(controlledNow)\n const contentRef = useRef<HTMLDivElement | null>(null)\n const {\n dragEnabled,\n focusItemDragId,\n handleDragEnd,\n handleDragStart,\n handleItemFocusRestored,\n previewSchedule,\n resizeItem,\n resolveSchedule,\n } = useCalendarDragAndDrop({\n getItemSchedule,\n getKey: collection.getKey,\n items: collection.items,\n snapMinutes,\n timeZone,\n ...(!loading && onItemReschedule ? { onItemReschedule } : {}),\n })\n\n const anchorDate = useMemo(\n () => toZonedDateTime(anchor, timeZone).date,\n [anchor, timeZone],\n )\n const zonedNow = useMemo(\n () => toZonedDateTime(now, timeZone),\n [now, timeZone],\n )\n const range = useMemo(\n () => calendarRange(anchorDate, mode, weekStartsOn),\n [anchorDate, mode, weekStartsOn],\n )\n const segmentsByDay = useMemo(\n () =>\n segmentItems({\n getItemSchedule: resolveSchedule,\n getKey: collection.getKey,\n items: collection.items,\n range,\n timeZone,\n }),\n [collection.getKey, collection.items, range, resolveSchedule, timeZone],\n )\n const labels = useMemo(\n () => createLabelFormatters(locale, timeZone),\n [locale, timeZone],\n )\n\n const resolveLabel = getItemLabel ?? collection.getLabel\n const itemsByKey = useMemo(\n () =>\n new Map(\n collection.items.map(\n (item) => [String(collection.getKey(item)), item] as const,\n ),\n ),\n [collection],\n )\n\n const renderSegment = (\n segment: CalendarItemSegment<TItem>,\n placement: 'all-day' | 'month' | 'time-grid',\n ) => {\n const dateKey = calendarDateKey(segment.date)\n const label = resolveLabel(segment.item)\n const schedule =\n dragEnabled && placement === 'time-grid' && !segment.isAllDay\n ? resolveSchedule(segment.item)\n : null\n const resizable = schedule?.end != null\n const resizeGrid = { snapMinutes, timeZone }\n const resizeHandle = (edge: 'end' | 'start') =>\n schedule ? (\n <CalendarResizeHandle\n edge={edge}\n grid={resizeGrid}\n onCommit={(next) => resizeItem(segment.itemKey, next)}\n onPreview={(next) => previewSchedule(segment.itemKey, next)}\n schedule={schedule}\n />\n ) : null\n const stepEdge = (\n edge: CalendarResizeEdge,\n direction: CalendarResizeDirection,\n ) => {\n if (!schedule) return\n const next = stepCalendarScheduleEdge(\n schedule,\n edge,\n direction,\n resizeGrid,\n )\n if (next) resizeItem(segment.itemKey, next)\n }\n\n return (\n <DraggableCalendarItem\n className={placement === 'time-grid' ? 'h-full' : undefined}\n disabled={!dragEnabled}\n dragLabel={`Mover ${label}`}\n dragType={segment.isAllDay ? 'calendar-item-all-day' : 'calendar-item'}\n id={createCalendarItemDragId(segment.itemKey, dateKey)}\n itemData={{ dateKey, itemKey: segment.itemKey, type: 'item' }}\n itemKey={segment.itemKey}\n {...(resizable ? { onResizeStep: stepEdge } : {})}\n >\n {resizable && segment.isStart ? resizeHandle('start') : null}\n <CalendarSegmentContent\n dateKey={dateKey}\n endMinutes={placement === 'time-grid' ? segment.endMinutes : null}\n isEnd={segment.isEnd}\n isStart={segment.isStart}\n item={segment.item}\n placement={placement}\n renderItem={renderItem}\n startMinutes={placement === 'time-grid' ? segment.startMinutes : null}\n />\n {resizable && segment.isEnd ? resizeHandle('end') : null}\n </DraggableCalendarItem>\n )\n }\n\n // Restaura o foco no chip que acabou de trocar de célula — o nó original é\n // desmontado no drop e o teclado perderia o fio da meada.\n useLayoutEffect(() => {\n if (!focusItemDragId) return\n\n const frame = requestAnimationFrame(() => {\n const chip = Array.from(\n contentRef.current?.querySelectorAll<HTMLElement>(\n '[data-calendar-item-drag-id]',\n ) ?? [],\n ).find(\n (element) =>\n element.getAttribute('data-calendar-item-drag-id') ===\n focusItemDragId,\n )\n\n if (!chip) return\n chip.focus({ preventScroll: true })\n handleItemFocusRestored()\n })\n\n return () => cancelAnimationFrame(frame)\n }, [focusItemDragId, handleItemFocusRestored])\n\n const timeGrid = useMemo(() => {\n if (mode === 'month') return null\n\n const allDaySegmentsByDay = new Map<string, CalendarItemSegment<TItem>[]>()\n const timedSegmentsByDay = new Map<string, CalendarItemSegment<TItem>[]>()\n const lanesByDay = new Map<string, ReadonlyMap<string, TimeGridLane>>()\n\n for (const [dateKey, segments] of segmentsByDay) {\n const allDay = segments.filter((segment) => segment.isAllDay)\n const timed = segments.filter((segment) => !segment.isAllDay)\n allDaySegmentsByDay.set(dateKey, allDay)\n timedSegmentsByDay.set(dateKey, timed)\n lanesByDay.set(dateKey, assignTimeGridLanes(timed))\n }\n\n return { allDaySegmentsByDay, lanesByDay, timedSegmentsByDay }\n }, [mode, segmentsByDay])\n\n return (\n <div\n aria-busy={loading ? 'true' : undefined}\n className=\"flex h-full min-h-0 min-w-0 flex-col\"\n data-calendar-mode={mode}\n data-slot=\"calendar-view\"\n ref={contentRef}\n >\n <DragDropProvider onDragEnd={handleDragEnd} onDragStart={handleDragStart}>\n {mode === 'month' ? (\n <CalendarMonthGrid\n anchorMonth={anchorDate.month}\n dayLabelOf={labels.fullDate}\n dropEnabled={dragEnabled && !loading}\n gridLabel={labels.monthTitle(anchorDate)}\n loading={loading}\n loadingItemCount={loadingItemCount}\n maxVisibleItems={maxVisibleMonthItems}\n range={range}\n renderSegment={(segment) => renderSegment(segment, 'month')}\n segmentsByDay={segmentsByDay}\n today={zonedNow.date}\n weekdayLabels={range.slice(0, 7).map(labels.weekdayShort)}\n {...(loadingItemLabel ? { loadingItemLabel } : {})}\n {...(onSelectDay ? { onSelectDay } : {})}\n />\n ) : timeGrid ? (\n <CalendarTimeGrid\n allDaySegmentsByDay={timeGrid.allDaySegmentsByDay}\n columnHeadingOf={labels.fullDate}\n dayNumberLabels={range.map((date) => ({\n label: String(date.day),\n weekday: labels.weekdayShort(date),\n }))}\n dropEnabled={dragEnabled && !loading}\n gridLabel={labels.rangeTitle(range)}\n hourLabels={HOURS.map(\n (hour) => `${String(hour).padStart(2, '0')}:00`,\n )}\n lanesByDay={timeGrid.lanesByDay}\n loading={loading}\n nowMinutes={zonedNow.minutes}\n range={range}\n renderAllDaySegment={(segment) => renderSegment(segment, 'all-day')}\n renderSegment={(segment) => renderSegment(segment, 'time-grid')}\n snapMinutes={snapMinutes}\n timedSegmentsByDay={timeGrid.timedSegmentsByDay}\n timeZoneLabel={labels.timeZoneLabel(now)}\n today={zonedNow.date}\n {...(loadingItemLabel ? { loadingItemLabel } : {})}\n {...(onSelectSlot && !loading ? { onSelectSlot } : {})}\n />\n ) : null}\n\n <DragOverlay className=\"pointer-events-none\" dropAnimation={null}>\n {(source) => {\n const itemKey = (source.data as { itemKey?: string } | undefined)\n ?.itemKey\n const item =\n itemKey === undefined ? undefined : itemsByKey.get(itemKey)\n if (item === undefined) return null\n\n const schedule = resolveSchedule(item)\n const zoned = schedule\n ? toZonedDateTime(schedule.start, timeZone)\n : null\n\n return renderItem(item, {\n date: zoned?.date ?? anchorDate,\n endMinutes: null,\n isEnd: true,\n isStart: true,\n placement: mode === 'month' ? 'month' : 'time-grid',\n startMinutes: null,\n })\n }}\n </DragOverlay>\n </DragDropProvider>\n </div>\n )\n}\n\nconst HOURS = Array.from({ length: 24 }, (_, hour) => hour)\n\nfunction createLabelFormatters(locale: string, timeZone: string) {\n // A CalendarDate já está no fuso da view; formatar em UTC evita que o\n // Intl desloque o dia uma segunda vez.\n const asUtcDate = (date: CalendarDate) =>\n new Date(Date.UTC(date.year, date.month - 1, date.day))\n const weekday = new Intl.DateTimeFormat(locale, {\n timeZone: 'UTC',\n weekday: 'short',\n })\n const full = new Intl.DateTimeFormat(locale, {\n dateStyle: 'full',\n timeZone: 'UTC',\n })\n const month = new Intl.DateTimeFormat(locale, {\n month: 'long',\n timeZone: 'UTC',\n year: 'numeric',\n })\n const offset = new Intl.DateTimeFormat(locale, {\n timeZone,\n timeZoneName: 'shortOffset',\n })\n\n return {\n fullDate: (date: CalendarDate) => full.format(asUtcDate(date)),\n monthTitle: (date: CalendarDate) => month.format(asUtcDate(date)),\n rangeTitle: (range: readonly CalendarDate[]) => {\n const first = range[0]\n const last = range[range.length - 1]\n if (!first || !last) return ''\n\n return range.length === 1\n ? full.format(asUtcDate(first))\n : `${full.format(asUtcDate(first))} – ${full.format(asUtcDate(last))}`\n },\n timeZoneLabel: (instant: Date) =>\n offset.formatToParts(instant).find((part) => part.type === 'timeZoneName')\n ?.value ?? '',\n weekdayShort: (date: CalendarDate) => weekday.format(asUtcDate(date)),\n }\n}\n",
|
|
213
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/calendar-view.tsx"
|
|
214
|
-
},
|
|
215
|
-
{
|
|
216
|
-
"path": "parttens/src/collection-views/views/calendar/components/draggable-calendar-item.tsx",
|
|
217
|
-
"type": "registry:file",
|
|
218
|
-
"content": "'use client'\n\nimport {\n KeyboardSensor,\n PointerActivationConstraints,\n PointerSensor,\n} from '@dnd-kit/dom'\nimport { useDraggable } from '@dnd-kit/react'\nimport { cn } from '@tc96/utils'\nimport { GripVerticalIcon } from 'lucide-react'\nimport type { CSSProperties, KeyboardEvent, ReactNode } from 'react'\n\nimport type { CalendarItemDragData } from '../lib/drag-and-drop'\nimport type { CalendarResizeDirection, CalendarResizeEdge } from '../lib/resize'\n\nconst OWN_GESTURE_TARGETS = [\n 'input:not([disabled])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n 'button:not([disabled]):not([data-slot=\"calendar-event-chip-open-trigger\"])',\n 'a[href]',\n '[data-calendar-item-resize]',\n '[contenteditable]:not([contenteditable=\"false\"])',\n '[role=\"button\"]',\n '[role=\"checkbox\"]',\n '[role=\"combobox\"]',\n '[role=\"menuitem\"]',\n '[role=\"option\"]',\n '[role=\"slider\"]',\n '[role=\"switch\"]',\n].join(',')\n\nexport const CALENDAR_ITEM_SENSORS = [\n PointerSensor.configure({\n activatorElements: (source) => [source.element],\n preventActivation: (event, source) =>\n event.target instanceof Element &&\n !source.handle?.contains(event.target) &&\n event.target.closest(OWN_GESTURE_TARGETS) !== null,\n activationConstraints: (event) =>\n event.pointerType === 'touch'\n ? [new PointerActivationConstraints.Delay({ tolerance: 5, value: 250 })]\n : [new PointerActivationConstraints.Distance({ value: 5 })],\n }),\n KeyboardSensor.configure({\n keyboardCodes: {\n cancel: ['Escape'],\n down: ['ArrowDown'],\n end: ['Space', 'Tab'],\n left: ['ArrowLeft'],\n right: ['ArrowRight'],\n start: ['Space'],\n up: ['ArrowUp'],\n },\n }),\n]\n\nexport interface DraggableCalendarItemProps {\n children: ReactNode\n className?: string\n disabled?: boolean\n dragLabel: string\n /** Tipo do draggable — casa com o `accept` das células (timed × all-day). */\n dragType: 'calendar-item' | 'calendar-item-all-day'\n id: string\n itemData: CalendarItemDragData\n itemKey: string\n onResizeStep?: (\n edge: CalendarResizeEdge,\n direction: CalendarResizeDirection,\n ) => void\n style?: CSSProperties\n}\n\nconst RESIZE_KEY_SHORTCUTS =\n 'Alt+ArrowUp Alt+ArrowDown Shift+ArrowUp Shift+ArrowDown'\n\nexport function DraggableCalendarItem({\n children,\n className,\n disabled = false,\n dragLabel,\n dragType,\n id,\n itemData,\n itemKey,\n onResizeStep,\n style,\n}: DraggableCalendarItemProps) {\n const { handleRef, isDragSource, ref } = useDraggable({\n data: itemData,\n disabled,\n id,\n sensors: CALENDAR_ITEM_SENSORS,\n type: dragType,\n })\n\n const handleResizeKey = (event: KeyboardEvent<HTMLButtonElement>) => {\n if (!onResizeStep || isDragSource) return\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return\n if (event.altKey === event.shiftKey) return\n\n event.preventDefault()\n onResizeStep(\n event.altKey ? 'start' : 'end',\n event.key === 'ArrowUp' ? 'earlier' : 'later',\n )\n }\n\n return (\n <div\n className={cn(\n 'relative min-w-0 rounded-md',\n !disabled && 'cursor-grab active:cursor-grabbing',\n isDragSource && 'opacity-40',\n className,\n )}\n data-calendar-item-draggable={disabled ? undefined : ''}\n data-calendar-item-id={itemKey}\n ref={disabled ? undefined : ref}\n style={style}\n >\n {disabled ? null : (\n <button\n aria-keyshortcuts={onResizeStep ? RESIZE_KEY_SHORTCUTS : undefined}\n aria-label={dragLabel}\n className=\"absolute inset-y-0 start-0 z-20 flex w-4 items-center justify-center rounded-s-md bg-background text-muted-foreground opacity-0 outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring\"\n data-calendar-item-drag-handle=\"\"\n data-calendar-item-drag-id={id}\n onKeyDown={handleResizeKey}\n ref={handleRef}\n type=\"button\"\n >\n <GripVerticalIcon aria-hidden=\"true\" className=\"size-3\" />\n </button>\n )}\n {children}\n </div>\n )\n}\n",
|
|
219
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/components/draggable-calendar-item.tsx"
|
|
220
|
-
},
|
|
221
|
-
{
|
|
222
|
-
"path": "parttens/src/collection-views/views/calendar/hooks/use-calendar-drag-and-drop.ts",
|
|
223
|
-
"type": "registry:file",
|
|
224
|
-
"content": "import type { DragEndEvent, DragStartEvent } from '@dnd-kit/react'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport {\n parseCalendarItemDragId,\n resolveCalendarDrop,\n} from '../lib/drag-and-drop'\nimport type { CalendarItemReschedule, CalendarItemSchedule } from '../types'\n\ninterface UseCalendarDragAndDropOptions<TItem> {\n getItemSchedule: (item: TItem) => CalendarItemSchedule | null\n getKey: (item: TItem) => string | number\n items: readonly TItem[]\n onItemReschedule?: (\n change: CalendarItemReschedule<TItem>,\n ) => boolean | Promise<boolean>\n snapMinutes: number\n timeZone: string\n}\n\ninterface PendingReschedule {\n accepted: boolean\n itemKey: string\n requestId: number\n schedule: CalendarItemSchedule\n}\n\n/**\n * Reagendamento otimista sem índices: um mapa de overrides por item substitui a\n * janela do prop até o dado confirmado chegar — rollback é só remover a\n * entrada. Mesmo fluxo de `suspend()`/settle do kanban.\n */\nexport function useCalendarDragAndDrop<TItem>({\n getItemSchedule,\n getKey,\n items,\n onItemReschedule,\n snapMinutes,\n timeZone,\n}: UseCalendarDragAndDropOptions<TItem>) {\n const [overrides, setOverrides] = useState<\n ReadonlyMap<string, CalendarItemSchedule>\n >(new Map())\n const [previews, setPreviews] = useState<\n ReadonlyMap<string, CalendarItemSchedule>\n >(new Map())\n const [focusItemDragId, setFocusItemDragId] = useState<string | null>(null)\n const itemsRef = useRef(items)\n const overridesRef = useRef(overrides)\n const pendingRef = useRef<PendingReschedule | null>(null)\n const requestIdRef = useRef(0)\n itemsRef.current = items\n overridesRef.current = overrides\n\n const resolveSchedule = useCallback(\n (item: TItem): CalendarItemSchedule | null =>\n previews.get(String(getKey(item))) ??\n overrides.get(String(getKey(item))) ??\n getItemSchedule(item),\n [getItemSchedule, getKey, overrides, previews],\n )\n\n const removeOverride = useCallback((itemKey: string) => {\n setOverrides((current) => {\n if (!current.has(itemKey)) return current\n const next = new Map(current)\n next.delete(itemKey)\n return next\n })\n }, [])\n\n // Confirmação: quando a janela vinda do prop passa a bater com o override\n // pendente aceito, o override cumpriu o papel e sai.\n useEffect(() => {\n const pending = pendingRef.current\n if (!pending?.accepted) return\n\n const item = items.find(\n (candidate) => String(getKey(candidate)) === pending.itemKey,\n )\n if (!item) return\n if (!schedulesMatch(getItemSchedule(item), pending.schedule)) return\n\n pendingRef.current = null\n removeOverride(pending.itemKey)\n }, [getItemSchedule, getKey, items, removeOverride])\n\n const handleDragStart = useCallback((_event: DragStartEvent) => {\n setFocusItemDragId(null)\n }, [])\n const handleItemFocusRestored = useCallback(\n () => setFocusItemDragId(null),\n [],\n )\n\n const commitReschedule = useCallback(\n (\n item: TItem,\n itemKey: string,\n schedule: CalendarItemSchedule,\n nextSchedule: CalendarItemSchedule,\n suspend?: () => { abort: () => void; resume: () => void },\n ) => {\n if (!onItemReschedule) return\n\n const change: CalendarItemReschedule<TItem> = {\n end: nextSchedule.end,\n isAllDay: nextSchedule.isAllDay,\n item,\n itemKey,\n sourceEnd: schedule.end,\n sourceStart: schedule.start,\n start: nextSchedule.start,\n }\n\n setOverrides((current) => new Map(current).set(itemKey, nextSchedule))\n const requestId = requestIdRef.current + 1\n requestIdRef.current = requestId\n pendingRef.current = {\n accepted: false,\n itemKey,\n requestId,\n schedule: nextSchedule,\n }\n const suspension = suspend?.()\n\n const settle = (accepted: boolean, settleSuspension: boolean) => {\n const pending = pendingRef.current\n if (!pending || pending.requestId !== requestId) return\n\n if (!accepted) {\n pendingRef.current = null\n if (settleSuspension) suspension?.abort()\n removeOverride(itemKey)\n return\n }\n\n pending.accepted = true\n if (settleSuspension) suspension?.resume()\n }\n\n try {\n const accepted = onItemReschedule(change)\n\n if (isPromiseLike(accepted)) {\n // Segurar a operação suspensa através da latência de rede manteria o\n // feedback de arraste vivo depois do pointer-up. O drop nativo\n // termina agora; o override acima cuida só da reconciliação.\n suspension?.resume()\n void Promise.resolve(accepted).then(\n (value) => settle(value, false),\n () => settle(false, false),\n )\n } else {\n settle(accepted, true)\n }\n } catch {\n settle(false, true)\n }\n },\n [onItemReschedule, removeOverride],\n )\n\n const handleDragEnd = useCallback(\n (event: DragEndEvent) => {\n if (event.canceled || !onItemReschedule) return\n\n const source = event.operation.source\n const parsed = source ? parseCalendarItemDragId(source.id) : null\n if (!parsed) return\n\n const item = itemsRef.current.find(\n (candidate) => String(getKey(candidate)) === parsed.itemKey,\n )\n if (!item) return\n\n // Parte da janela visível: com um reagendamento ainda pendente, o prop\n // segue com o valor antigo e o override é o que a pessoa está vendo.\n const schedule =\n overridesRef.current.get(parsed.itemKey) ?? getItemSchedule(item)\n if (!schedule) return\n\n const next = resolveCalendarDrop(event, schedule, timeZone, snapMinutes)\n if (!next || schedulesMatch(schedule, { ...schedule, ...next })) return\n\n const nextSchedule: CalendarItemSchedule = {\n ...next,\n isAllDay: schedule.isAllDay,\n }\n\n setFocusItemDragId(String(source?.id))\n commitReschedule(item, parsed.itemKey, schedule, nextSchedule, () =>\n event.suspend(),\n )\n },\n [\n commitReschedule,\n getItemSchedule,\n getKey,\n onItemReschedule,\n snapMinutes,\n timeZone,\n ],\n )\n\n const previewSchedule = useCallback(\n (itemKey: string, schedule: CalendarItemSchedule | null) => {\n setPreviews((current) => {\n if (!schedule && !current.has(itemKey)) return current\n const next = new Map(current)\n if (schedule) next.set(itemKey, schedule)\n else next.delete(itemKey)\n return next\n })\n },\n [],\n )\n\n const resizeItem = useCallback(\n (itemKey: string, nextSchedule: CalendarItemSchedule) => {\n previewSchedule(itemKey, null)\n const item = itemsRef.current.find(\n (candidate) => String(getKey(candidate)) === itemKey,\n )\n if (!item) return\n\n const schedule =\n overridesRef.current.get(itemKey) ?? getItemSchedule(item)\n if (!schedule || schedulesMatch(schedule, nextSchedule)) return\n\n commitReschedule(item, itemKey, schedule, nextSchedule)\n },\n [commitReschedule, getItemSchedule, getKey, previewSchedule],\n )\n\n return {\n dragEnabled: Boolean(onItemReschedule),\n focusItemDragId,\n handleDragEnd,\n handleDragStart,\n handleItemFocusRestored,\n previewSchedule,\n resizeItem,\n resolveSchedule,\n }\n}\n\nfunction schedulesMatch(\n left: CalendarItemSchedule | null,\n right: CalendarItemSchedule,\n): boolean {\n if (!left) return false\n\n return (\n left.start.getTime() === right.start.getTime() &&\n (left.end?.getTime() ?? null) === (right.end?.getTime() ?? null) &&\n left.isAllDay === right.isAllDay\n )\n}\n\nfunction isPromiseLike(\n value: boolean | Promise<boolean>,\n): value is Promise<boolean> {\n return typeof value === 'object' && value !== null && 'then' in value\n}\n",
|
|
225
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/hooks/use-calendar-drag-and-drop.ts"
|
|
226
|
-
},
|
|
227
|
-
{
|
|
228
|
-
"path": "parttens/src/collection-views/views/calendar/hooks/use-now.ts",
|
|
229
|
-
"type": "registry:file",
|
|
230
|
-
"content": "import { useEffect, useState } from 'react'\n\n/**\n * Instante corrente para a linha \"agora\" e o destaque de hoje. Controlado pelo\n * consumidor quando fornecido (stories e testes precisam de fixture estável);\n * sem controle, avança por conta própria a cada minuto.\n */\nexport function useNow(controlled?: Date): Date {\n const [now, setNow] = useState(() => controlled ?? new Date())\n\n useEffect(() => {\n if (controlled) return\n\n const interval = setInterval(() => setNow(new Date()), 60_000)\n\n return () => clearInterval(interval)\n }, [controlled])\n\n return controlled ?? now\n}\n",
|
|
231
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/hooks/use-now.ts"
|
|
232
|
-
},
|
|
233
|
-
{
|
|
234
|
-
"path": "parttens/src/collection-views/views/calendar/index.ts",
|
|
235
|
-
"type": "registry:file",
|
|
236
|
-
"content": "export {\n addCalendarDays,\n calendarDateKey,\n calendarRange,\n compareCalendarDates,\n isSameCalendarDate,\n parseCalendarDateKey,\n startOfWeek,\n} from '@tc96/helpers/calendar-date'\nexport type { ZonedDateTime } from '@tc96/helpers/zoned-date-time'\nexport {\n fromZonedDateTime,\n getTimeZoneOffsetMs,\n toZonedDateTime,\n} from '@tc96/helpers/zoned-date-time'\nexport type { CalendarAllDayCellProps } from './components/calendar-all-day-cell'\nexport { CalendarAllDayCell } from './components/calendar-all-day-cell'\nexport type { CalendarDayColumnProps } from './components/calendar-day-column'\nexport { CalendarDayColumn } from './components/calendar-day-column'\nexport type {\n CalendarEventChipDisplay,\n CalendarEventChipOpenTriggerProps,\n CalendarEventChipProps,\n CalendarEventChipTimeProps,\n CalendarEventChipTitleProps,\n CalendarEventChipTone,\n} from './components/calendar-event-chip'\nexport {\n CalendarEventChip,\n CalendarEventChipOpenTrigger,\n CalendarEventChipTime,\n CalendarEventChipTitle,\n calendarEventChipVariants,\n} from './components/calendar-event-chip'\nexport type { CalendarItemSkeletonProps } from './components/calendar-item-skeleton'\nexport { CalendarItemSkeleton } from './components/calendar-item-skeleton'\nexport type { CalendarMonthGridProps } from './components/calendar-month-grid'\nexport { CalendarMonthGrid } from './components/calendar-month-grid'\nexport type { CalendarTimeGridProps } from './components/calendar-time-grid'\nexport { CalendarTimeGrid } from './components/calendar-time-grid'\nexport type { CalendarViewProps } from './components/calendar-view'\nexport { CalendarView } from './components/calendar-view'\nexport type {\n CalendarDate,\n CalendarItemPlacement,\n CalendarItemRenderContext,\n CalendarItemReschedule,\n CalendarItemSchedule,\n CalendarSlot,\n CalendarViewMode,\n} from './types'\n",
|
|
237
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/index.ts"
|
|
238
|
-
},
|
|
239
|
-
{
|
|
240
|
-
"path": "parttens/src/collection-views/views/calendar/lib/calendar-layout.ts",
|
|
241
|
-
"type": "registry:file",
|
|
242
|
-
"content": "import {\n addCalendarDays,\n calendarDateKey,\n compareCalendarDates,\n isSameCalendarDate,\n} from '@tc96/helpers/calendar-date'\nimport { toZonedDateTime } from '@tc96/helpers/zoned-date-time'\nimport type { CalendarDate, CalendarItemSchedule } from '../types'\n\nexport const MINUTES_IN_DAY = 1440\n\nexport interface CalendarItemSegment<TItem = unknown> {\n date: CalendarDate\n /** Clampado em [0, 1440] dentro do dia. Igual ao início para instante único. */\n endMinutes: number\n isAllDay: boolean\n isEnd: boolean\n isStart: boolean\n item: TItem\n itemKey: string\n startMinutes: number\n}\n\nexport interface SegmentItemsInput<TItem> {\n getItemSchedule: (item: TItem) => CalendarItemSchedule | null\n getKey: (item: TItem) => string | number\n items: readonly TItem[]\n range: readonly CalendarDate[]\n timeZone: string\n}\n\n/**\n * Fatia cada item nos dias visíveis, já no fuso da view — uma passada por item,\n * nunca uma varredura por célula. Fim em meia-noite exata não vaza para o dia\n * seguinte: `[10, 11)` de dia inteiro pertence só ao dia 10.\n */\nexport function segmentItems<TItem>({\n getItemSchedule,\n getKey,\n items,\n range,\n timeZone,\n}: SegmentItemsInput<TItem>): Map<string, CalendarItemSegment<TItem>[]> {\n const segmentsByDay = new Map<string, CalendarItemSegment<TItem>[]>()\n const first = range[0]\n const last = range[range.length - 1]\n\n if (!first || !last) return segmentsByDay\n\n for (const day of range) segmentsByDay.set(calendarDateKey(day), [])\n\n for (const item of items) {\n const schedule = getItemSchedule(item)\n if (!schedule) continue\n\n const itemKey = String(getKey(item))\n const start = toZonedDateTime(schedule.start, timeZone)\n const effectiveEnd = schedule.end ?? schedule.start\n const end = toZonedDateTime(effectiveEnd, timeZone)\n const endsAtMidnight =\n end.minutes === 0 && compareCalendarDates(end.date, start.date) > 0\n const lastDay = endsAtMidnight ? addCalendarDays(end.date, -1) : end.date\n\n let day = compareCalendarDates(start.date, first) < 0 ? first : start.date\n const stop = compareCalendarDates(lastDay, last) > 0 ? last : lastDay\n\n for (\n ;\n compareCalendarDates(day, stop) <= 0;\n day = addCalendarDays(day, 1)\n ) {\n const bucket = segmentsByDay.get(calendarDateKey(day))\n if (!bucket) continue\n\n const isStart = isSameCalendarDate(day, start.date)\n const isEnd = isSameCalendarDate(day, lastDay)\n const startMinutes = isStart ? start.minutes : 0\n const endMinutes = isEnd && !endsAtMidnight ? end.minutes : MINUTES_IN_DAY\n\n bucket.push({\n date: day,\n endMinutes: schedule.end ? endMinutes : startMinutes,\n isAllDay: schedule.isAllDay,\n isEnd,\n isStart,\n item,\n itemKey,\n startMinutes,\n })\n }\n }\n\n for (const bucket of segmentsByDay.values()) {\n bucket.sort(\n (a, b) =>\n a.startMinutes - b.startMinutes || a.itemKey.localeCompare(b.itemKey),\n )\n }\n\n return segmentsByDay\n}\n\nexport interface TimeGridPosition {\n heightPct: number\n topPct: number\n}\n\n/** Altura mínima para instante único e janela curta seguirem clicáveis. */\nconst MIN_HEIGHT_PCT = 2\n\nexport function timeGridPosition(segment: {\n endMinutes: number\n startMinutes: number\n}): TimeGridPosition {\n const topPct = (segment.startMinutes / MINUTES_IN_DAY) * 100\n const rawHeightPct =\n ((segment.endMinutes - segment.startMinutes) / MINUTES_IN_DAY) * 100\n const heightPct = Math.max(rawHeightPct, MIN_HEIGHT_PCT)\n\n return {\n heightPct: Math.min(heightPct, 100 - topPct),\n topPct,\n }\n}\n\nexport interface TimeGridLane {\n laneCount: number\n laneIndex: number\n}\n\n/**\n * Sobreposição por partição gulosa em lanes: segmentos que se tocam dividem a\n * largura da coluna lado a lado. Cada cluster de sobreposição fecha a própria\n * contagem — um evento isolado segue com a coluna inteira.\n */\nexport function assignTimeGridLanes(\n segments: readonly {\n endMinutes: number\n itemKey: string\n startMinutes: number\n }[],\n): Map<string, TimeGridLane> {\n const lanes = new Map<string, TimeGridLane>()\n const ordered = [...segments].sort(\n (a, b) => a.startMinutes - b.startMinutes || b.endMinutes - a.endMinutes,\n )\n // Fim efetivo com piso de 1 minuto: instante único ainda ocupa uma lane.\n const endOf = (segment: { endMinutes: number; startMinutes: number }) =>\n Math.max(segment.endMinutes, segment.startMinutes + 1)\n\n let cluster: { itemKey: string }[] = []\n let laneEnds: number[] = []\n let clusterEnd = Number.NEGATIVE_INFINITY\n\n const flushCluster = () => {\n for (const member of cluster) {\n const lane = lanes.get(member.itemKey)\n if (lane) lane.laneCount = laneEnds.length\n }\n cluster = []\n laneEnds = []\n clusterEnd = Number.NEGATIVE_INFINITY\n }\n\n for (const segment of ordered) {\n if (segment.startMinutes >= clusterEnd) flushCluster()\n\n let laneIndex = laneEnds.findIndex((end) => end <= segment.startMinutes)\n if (laneIndex === -1) {\n laneIndex = laneEnds.length\n laneEnds.push(endOf(segment))\n } else {\n laneEnds[laneIndex] = endOf(segment)\n }\n\n lanes.set(segment.itemKey, { laneCount: 1, laneIndex })\n cluster.push(segment)\n clusterEnd = Math.max(clusterEnd, endOf(segment))\n }\n\n flushCluster()\n\n return lanes\n}\n",
|
|
243
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/lib/calendar-layout.ts"
|
|
244
|
-
},
|
|
245
|
-
{
|
|
246
|
-
"path": "parttens/src/collection-views/views/calendar/lib/drag-and-drop.ts",
|
|
247
|
-
"type": "registry:file",
|
|
248
|
-
"content": "import type { DragEndEvent } from '@dnd-kit/react'\nimport { parseCalendarDateKey } from '@tc96/helpers/calendar-date'\nimport {\n fromZonedDateTime,\n toZonedDateTime,\n} from '@tc96/helpers/zoned-date-time'\nimport type { CalendarDate, CalendarItemSchedule } from '../types'\nimport { MINUTES_IN_DAY } from './calendar-layout'\n\nconst ITEM_DRAG_PREFIX = 'calendar-item:'\nconst DROP_PREFIX = 'calendar-drop:'\n\nexport type CalendarDropKind = 'all-day' | 'day' | 'time-column'\n\nexport interface CalendarDropData {\n dateKey: string\n type: CalendarDropKind\n [key: string]: unknown\n}\n\nexport interface CalendarItemDragData {\n dateKey: string\n itemKey: string\n type: 'item'\n [key: string]: unknown\n}\n\n/**\n * O mesmo item aparece em vários segmentos quando cruza dias; o dateKey no id\n * desambigua qual segmento está sendo arrastado.\n */\nexport function createCalendarItemDragId(\n itemKey: string,\n dateKey: string,\n): string {\n return `${ITEM_DRAG_PREFIX}${encodeURIComponent(itemKey)}:${dateKey}`\n}\n\nexport function parseCalendarItemDragId(\n id: string | number,\n): { dateKey: string; itemKey: string } | null {\n const value = String(id)\n if (!value.startsWith(ITEM_DRAG_PREFIX)) return null\n\n const rest = value.slice(ITEM_DRAG_PREFIX.length)\n const separator = rest.lastIndexOf(':')\n if (separator === -1) return null\n\n const encodedItemKey = rest.slice(0, separator)\n const dateKey = rest.slice(separator + 1)\n\n try {\n return { dateKey, itemKey: decodeURIComponent(encodedItemKey) }\n } catch {\n return { dateKey, itemKey: encodedItemKey }\n }\n}\n\nexport function createCalendarDropId(\n kind: CalendarDropKind,\n dateKey: string,\n instanceId: string,\n): string {\n return `${DROP_PREFIX}${kind}:${dateKey}:${encodeURIComponent(instanceId)}`\n}\n\n/**\n * Mês e faixa all-day: muda a data preservando a hora de parede e a duração em\n * ms absolutos — arrastar através de uma transição de horário de verão mantém a\n * duração real do compromisso, não a de parede.\n */\nexport function resolveDayDrop(\n schedule: CalendarItemSchedule,\n targetDate: CalendarDate,\n timeZone: string,\n): { end: Date | null; start: Date } {\n const zoned = toZonedDateTime(schedule.start, timeZone)\n const start = fromZonedDateTime(\n { date: targetDate, minutes: zoned.minutes },\n timeZone,\n )\n const durationMs = schedule.end\n ? schedule.end.getTime() - schedule.start.getTime()\n : null\n\n return {\n end: durationMs === null ? null : new Date(start.getTime() + durationMs),\n start,\n }\n}\n\n/** Fração vertical da coluna → minutos com snap, clampado dentro do dia. */\nexport function snapToSlot(offsetRatio: number, snapMinutes: number): number {\n const minutes =\n Math.round((offsetRatio * MINUTES_IN_DAY) / snapMinutes) * snapMinutes\n\n return Math.min(Math.max(minutes, 0), MINUTES_IN_DAY - snapMinutes)\n}\n\nexport function resolveTimeColumnDrop(\n schedule: CalendarItemSchedule,\n targetDate: CalendarDate,\n minutes: number,\n timeZone: string,\n): { end: Date | null; start: Date } {\n const start = fromZonedDateTime({ date: targetDate, minutes }, timeZone)\n const durationMs = schedule.end\n ? schedule.end.getTime() - schedule.start.getTime()\n : null\n\n return {\n end: durationMs === null ? null : new Date(start.getTime() + durationMs),\n start,\n }\n}\n\n/**\n * Casca impura chamada no fim do arraste: lê o alvo e a geometria do drop e\n * delega às resoluções puras. A borda superior do bloco arrastado define o novo\n * início; sem geometria disponível, o ponteiro é o fallback.\n */\nexport function resolveCalendarDrop(\n event: DragEndEvent,\n schedule: CalendarItemSchedule,\n timeZone: string,\n snapMinutes: number,\n): { end: Date | null; start: Date } | undefined {\n const target = event.operation.target\n const data = target?.data as CalendarDropData | undefined\n if (!target || !data?.dateKey) return undefined\n\n const targetDate = parseCalendarDateKey(data.dateKey)\n if (!targetDate) return undefined\n\n if (data.type === 'day' || data.type === 'all-day') {\n return resolveDayDrop(schedule, targetDate, timeZone)\n }\n\n if (data.type !== 'time-column') return undefined\n\n const element = target.element\n if (!(element instanceof Element)) return undefined\n\n const rect = element.getBoundingClientRect()\n if (rect.height <= 0) return undefined\n\n const topEdge =\n event.operation.shape?.current.boundingRectangle.top ??\n event.operation.position.current.y\n const minutes = snapToSlot((topEdge - rect.top) / rect.height, snapMinutes)\n\n return resolveTimeColumnDrop(schedule, targetDate, minutes, timeZone)\n}\n",
|
|
249
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/lib/drag-and-drop.ts"
|
|
250
|
-
},
|
|
251
|
-
{
|
|
252
|
-
"path": "parttens/src/collection-views/views/calendar/lib/resize.ts",
|
|
253
|
-
"type": "registry:file",
|
|
254
|
-
"content": "import {\n fromZonedDateTime,\n toZonedDateTime,\n} from '@tc96/helpers/zoned-date-time'\nimport type { CalendarItemSchedule } from '../types'\n\nexport type CalendarResizeEdge = 'end' | 'start'\nexport type CalendarResizeDirection = 'earlier' | 'later'\n\nexport interface CalendarResizeGrid {\n snapMinutes: number\n timeZone: string\n}\n\nconst MINUTE_MS = 60_000\n\ntype SlotRounding = (minutes: number, snapMinutes: number) => number\n\nconst nearestSlot: SlotRounding = (minutes, snap) =>\n Math.round(minutes / snap) * snap\nconst nextSlot: SlotRounding = (minutes, snap) =>\n Math.floor(minutes / snap) * snap + snap\nconst previousSlot: SlotRounding = (minutes, snap) =>\n Math.ceil(minutes / snap) * snap - snap\n\nfunction alignToSlot(\n instant: Date,\n { snapMinutes, timeZone }: CalendarResizeGrid,\n round: SlotRounding,\n): Date {\n const zoned = toZonedDateTime(instant, timeZone)\n const seconds = instant.getUTCSeconds() + instant.getUTCMilliseconds() / 1000\n const minutes = zoned.minutes + seconds / 60\n\n return fromZonedDateTime(\n { date: zoned.date, minutes: round(minutes, snapMinutes) },\n timeZone,\n )\n}\n\nfunction withEdge(\n schedule: CalendarItemSchedule,\n edge: CalendarResizeEdge,\n target: Date,\n snapMinutes: number,\n): CalendarItemSchedule | null {\n if (!schedule.end || schedule.isAllDay) return null\n\n const start = schedule.start.getTime()\n const end = schedule.end.getTime()\n const minDuration = snapMinutes * MINUTE_MS\n\n return edge === 'start'\n ? {\n ...schedule,\n start: new Date(Math.min(target.getTime(), end - minDuration)),\n }\n : {\n ...schedule,\n end: new Date(Math.max(target.getTime(), start + minDuration)),\n }\n}\n\nfunction edgeOf(schedule: CalendarItemSchedule, edge: CalendarResizeEdge) {\n return edge === 'start' ? schedule.start : schedule.end\n}\n\nexport function resizeCalendarSchedule(\n schedule: CalendarItemSchedule,\n edge: CalendarResizeEdge,\n deltaMinutes: number,\n grid: CalendarResizeGrid,\n): CalendarItemSchedule | null {\n const current = edgeOf(schedule, edge)\n if (!current) return null\n\n const target = alignToSlot(\n new Date(current.getTime() + deltaMinutes * MINUTE_MS),\n grid,\n nearestSlot,\n )\n return withEdge(schedule, edge, target, grid.snapMinutes)\n}\n\nexport function stepCalendarScheduleEdge(\n schedule: CalendarItemSchedule,\n edge: CalendarResizeEdge,\n direction: CalendarResizeDirection,\n grid: CalendarResizeGrid,\n): CalendarItemSchedule | null {\n const current = edgeOf(schedule, edge)\n if (!current) return null\n\n const target = alignToSlot(\n current,\n grid,\n direction === 'later' ? nextSlot : previousSlot,\n )\n return withEdge(schedule, edge, target, grid.snapMinutes)\n}\n",
|
|
255
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/lib/resize.ts"
|
|
256
|
-
},
|
|
257
|
-
{
|
|
258
|
-
"path": "parttens/src/collection-views/views/calendar/lib/slot.ts",
|
|
259
|
-
"type": "registry:file",
|
|
260
|
-
"content": "const MINUTES_PER_DAY = 1440\n\nexport function slotFromOffset({\n height,\n offsetY,\n snapMinutes,\n}: {\n height: number\n offsetY: number\n snapMinutes: number\n}) {\n const ratio = height > 0 ? Math.min(Math.max(offsetY / height, 0), 1) : 0\n const snapped = Math.floor((ratio * MINUTES_PER_DAY) / snapMinutes)\n const startMinutes = Math.min(\n snapped * snapMinutes,\n MINUTES_PER_DAY - snapMinutes,\n )\n\n return { endMinutes: startMinutes + snapMinutes, startMinutes }\n}\n",
|
|
261
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/lib/slot.ts"
|
|
262
|
-
},
|
|
263
|
-
{
|
|
264
|
-
"path": "parttens/src/collection-views/views/calendar/types.ts",
|
|
265
|
-
"type": "registry:file",
|
|
266
|
-
"content": "import type {\n CalendarDate,\n CalendarRangeMode,\n} from '@tc96/helpers/calendar-date'\n\nexport type { CalendarDate } from '@tc96/helpers/calendar-date'\n\nexport type CalendarViewMode = CalendarRangeMode\n\nexport interface CalendarItemSchedule {\n /** `null` é o instante único (item só com prazo); o time grid dá altura mínima. */\n end: Date | null\n isAllDay: boolean\n start: Date\n}\n\nexport type CalendarItemPlacement = 'all-day' | 'month' | 'time-grid'\n\nexport interface CalendarItemRenderContext {\n /** Dia do segmento — item multi-dia é fatiado em um segmento por dia. */\n date: CalendarDate\n /** Minutos do fim do segmento dentro do dia; `null` fora do time grid. */\n endMinutes: number | null\n /** O segmento contém o fim real do item. */\n isEnd: boolean\n /** O segmento contém o início real do item. */\n isStart: boolean\n placement: CalendarItemPlacement\n /** Minutos do início do segmento dentro do dia; `null` fora do time grid. */\n startMinutes: number | null\n}\n\nexport interface CalendarItemReschedule<TItem = unknown> {\n end: Date | null\n isAllDay: boolean\n item: TItem\n itemKey: string\n /** Janela original no momento em que a interação começou. */\n sourceEnd: Date | null\n sourceStart: Date\n start: Date\n}\n\nexport interface CalendarSlot {\n day: CalendarDate\n endMinutes: number\n startMinutes: number\n}\n",
|
|
267
|
-
"target": "~/packages/patterns/src/collection-views/views/calendar/types.ts"
|
|
268
|
-
},
|
|
269
|
-
{
|
|
270
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-add-row.tsx",
|
|
271
|
-
"type": "registry:file",
|
|
272
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport { Button } from '@tc96/ui/button'\nimport { PlusIcon } from 'lucide-react'\n\nexport interface DataGridAddRowProps {\n ariaRowIndex: number\n label: string\n minWidth: number\n onAdd: () => void | Promise<void>\n}\n\nexport function DataGridAddRow({\n ariaRowIndex,\n label,\n minWidth,\n onAdd,\n}: DataGridAddRowProps) {\n return (\n <div\n className=\"sticky bottom-0 z-10 grid border-t bg-background\"\n data-slot=\"data-grid-add-row-group\"\n role=\"rowgroup\"\n >\n <div\n aria-rowindex={ariaRowIndex}\n className=\"flex min-h-9 w-full\"\n role=\"row\"\n style={{ minWidth }}\n tabIndex={-1}\n >\n <div\n className=\"flex grow items-center bg-muted/30\"\n role=\"gridcell\"\n tabIndex={-1}\n >\n <Button\n aria-label={label}\n className=\"h-full w-full justify-start rounded-none px-3\"\n onClick={() => void onAdd()}\n variant=\"ghost\"\n >\n <PlusIcon />\n {label}\n </Button>\n </div>\n </div>\n </div>\n )\n}\n",
|
|
273
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-add-row.tsx"
|
|
274
|
-
},
|
|
275
|
-
{
|
|
276
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-body-cell.tsx",
|
|
277
|
-
"type": "registry:file",
|
|
278
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport { type Cell, flexRender, type RowData } from '@tanstack/react-table'\nimport { cn } from '@tc96/utils'\nimport { memo } from 'react'\nimport type { CellInteractions } from '../hooks/use-data-grid-cell-events'\nimport type { ColumnLayout } from '../lib/column-layout'\nimport { CELL_DENSITY } from '../lib/constants'\nimport type {\n DataGridFeatures,\n DataGridTableMeta,\n} from '../lib/data-grid-features'\nimport type { DataGridDensity } from '../types'\n\nexport interface DataGridBodyCellProps<TData extends RowData> {\n cell: Cell<DataGridFeatures, TData, unknown>\n columnIndex: number\n density: DataGridDensity\n interactions: CellInteractions\n isFocused: boolean\n isSelected: boolean\n layout: ColumnLayout | undefined\n rowSelected: boolean\n showFocus: boolean\n canSelect: boolean\n meta: DataGridTableMeta | undefined\n}\n\nfunction DataGridBodyCellView<TData extends RowData>({\n cell,\n columnIndex,\n density,\n interactions,\n isFocused,\n isSelected,\n layout,\n showFocus,\n}: DataGridBodyCellProps<TData>) {\n const columnId = cell.column.id\n\n return (\n <div\n aria-colindex={columnIndex + 1}\n aria-selected={isSelected}\n className={cn(\n 'flex min-w-0 items-center overflow-hidden border-e outline-none last:border-e-0 data-[pinned]:bg-background data-[selected=true]:bg-primary/10 data-[focused=true]:ring-1 data-[focused=true]:ring-inset data-[focused=true]:ring-ring',\n CELL_DENSITY[density],\n )}\n data-column-id={columnId}\n data-focused={showFocus ? 'true' : undefined}\n data-pinned={layout?.pinned || undefined}\n data-selected={isSelected ? 'true' : undefined}\n data-slot=\"data-grid-cell\"\n onClick={interactions.onClick}\n onClickCapture={interactions.onClickCapture}\n onKeyDown={interactions.onKeyDown}\n onMouseDownCapture={interactions.onMouseDownCapture}\n onPointerDownCapture={interactions.onPointerDownCapture}\n role=\"gridcell\"\n style={layout?.style}\n tabIndex={isFocused ? 0 : -1}\n >\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </div>\n )\n}\n\nexport const DataGridBodyCell = memo(\n DataGridBodyCellView,\n) as typeof DataGridBodyCellView\n",
|
|
279
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-body-cell.tsx"
|
|
280
|
-
},
|
|
281
|
-
{
|
|
282
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-body.tsx",
|
|
283
|
-
"type": "registry:file",
|
|
284
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport type { VirtualItem } from '@tanstack/react-virtual'\nimport type { BodyEntry, RowBodyEntry } from '../lib/body-entries'\nimport type { ColumnLayouts } from '../lib/column-layout'\nimport type { CellSelection } from '../lib/selection'\nimport { createSkeletonRowIds } from '../lib/skeleton'\nimport type { DataGridDensity } from '../types'\nimport { DataGridEmptyRow } from './data-grid-empty-row'\nimport { DataGridGroupRow } from './data-grid-group-row'\nimport { DataGridRow } from './data-grid-row'\nimport { DataGridSkeletonRows } from './data-grid-skeleton-rows'\n\nexport interface DataGridBodyProps<TData extends RowData> {\n columnIds: readonly string[]\n columnLayouts: ColumnLayouts\n density: DataGridDensity\n emptyMessage: string\n entries: readonly BodyEntry<TData>[]\n focusedColumnId?: string\n focusedRowId?: string\n getRowSelected?: (row: TData) => boolean\n hasInteracted: boolean\n headerRowCount: number\n isLoading: boolean\n loadingRowCount: number\n minWidth: number\n onToggleGroup: (group: string, collapsed: boolean) => void\n pageRowCount: number\n selection: CellSelection\n totalSize?: number\n virtualItems: readonly VirtualItem[]\n virtualized: boolean\n}\n\nexport function DataGridBody<TData extends RowData>({\n columnIds,\n columnLayouts,\n density,\n emptyMessage,\n entries,\n focusedColumnId,\n focusedRowId,\n getRowSelected,\n hasInteracted,\n headerRowCount,\n isLoading,\n loadingRowCount,\n minWidth,\n onToggleGroup,\n pageRowCount,\n selection,\n totalSize,\n virtualItems,\n virtualized,\n}: DataGridBodyProps<TData>) {\n function renderRow(\n entry: RowBodyEntry<TData>,\n virtual?: { size: number; start: number },\n ) {\n const { row } = entry\n const focusedHere = focusedRowId === row.id\n return (\n <DataGridRow\n ariaRowIndex={entry.ariaRowIndex}\n focusedColumnId={focusedHere ? focusedColumnId : undefined}\n interacted={focusedHere && hasInteracted}\n key={entry.key}\n row={row}\n selected={\n Boolean(getRowSelected?.(row.original)) || row.getIsSelected()\n }\n selectedColumnIds={selection.get(row.id)}\n virtualSize={virtual?.size}\n virtualStart={virtual?.start}\n />\n )\n }\n\n function renderContent() {\n if (isLoading) {\n return (\n <DataGridSkeletonRows\n columnIds={columnIds}\n columnLayouts={columnLayouts}\n density={density}\n headerRowCount={headerRowCount}\n rowIds={createSkeletonRowIds(loadingRowCount)}\n />\n )\n }\n if (pageRowCount === 0) {\n return (\n <DataGridEmptyRow\n ariaRowIndex={headerRowCount + 1}\n message={emptyMessage}\n />\n )\n }\n if (virtualized) {\n return virtualItems.map((item) => {\n const entry = entries[item.index]\n return entry?.kind === 'row'\n ? renderRow(entry, { size: item.size, start: item.start })\n : null\n })\n }\n return entries.map((entry) =>\n entry.kind === 'group' ? (\n <DataGridGroupRow\n ariaRowIndex={entry.ariaRowIndex}\n collapsed={entry.collapsed}\n count={entry.count}\n group={entry.group}\n key={entry.key}\n onToggle={onToggleGroup}\n />\n ) : (\n renderRow(entry)\n ),\n )\n }\n\n return (\n <div\n className=\"relative grid\"\n data-slot=\"data-grid-body\"\n data-virtualized={virtualized ? 'true' : undefined}\n role=\"rowgroup\"\n style={{ height: virtualized ? totalSize : undefined, minWidth }}\n >\n {renderContent()}\n </div>\n )\n}\n",
|
|
285
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-body.tsx"
|
|
286
|
-
},
|
|
287
|
-
{
|
|
288
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-cell.tsx",
|
|
289
|
-
"type": "registry:file",
|
|
290
|
-
"content": "'use client'\n\nimport type { CellContext, RowData } from '@tanstack/react-table'\nimport { Badge } from '@tc96/ui/badge'\nimport {\n Select,\n SelectItem,\n SelectPopup,\n SelectPrimitive,\n SelectValue,\n} from '@tc96/ui/select'\nimport { cn } from '@tc96/utils'\nimport { CheckIcon, MinusIcon } from 'lucide-react'\nimport { CELL_ALIGN } from '../lib/constants'\nimport type { DataGridFeatures } from '../lib/data-grid-features'\nimport { formatDate, toStringValue } from '../lib/format-value'\nimport type { DataGridColumnMeta, DataGridSelectOption } from '../types'\n\nconst optionToLabel = (option: DataGridSelectOption) => option.label\nconst optionToValue = (option: DataGridSelectOption) => option.value\n\nexport function DataGridCell<TData extends RowData>({\n context,\n}: {\n context: CellContext<DataGridFeatures, TData, unknown>\n}) {\n const { column, getValue, row, table } = context\n const meta = (column.columnDef.meta ?? {}) as DataGridColumnMeta\n const variant = meta.variant ?? 'text'\n const align = CELL_ALIGN[meta.align ?? 'start']\n const value = getValue()\n\n switch (variant) {\n case 'checkbox': {\n const checked = Boolean(value)\n return (\n <span className={cn('flex items-center text-muted-foreground', align)}>\n {checked ? (\n <CheckIcon aria-hidden=\"true\" className=\"size-4\" />\n ) : (\n <MinusIcon aria-hidden=\"true\" className=\"size-4 opacity-40\" />\n )}\n <span className=\"sr-only\">{checked ? 'Marcado' : 'Desmarcado'}</span>\n </span>\n )\n }\n\n case 'select': {\n const options = meta.options ?? []\n const selectedOption = options.find(\n (option) => option.value === toStringValue(value),\n )\n const onValueChange = table.options.meta?.onDataGridCellValueChange\n\n if (meta.editable && onValueChange && options.length > 0) {\n const accessibleValue =\n selectedOption?.label ?? meta.placeholder ?? 'Sem valor'\n return (\n <Select\n itemToStringLabel={optionToLabel}\n itemToStringValue={optionToValue}\n items={options}\n onValueChange={(option) => {\n if (!option) return\n onValueChange({\n columnId: column.id,\n rowId: row.id,\n value: option.value,\n })\n }}\n value={selectedOption ?? null}\n >\n <SelectPrimitive.Trigger\n aria-label={`${meta.label ?? column.id}: ${accessibleValue}`}\n data-grid-select-trigger\n render={\n <Badge\n className=\"max-w-full\"\n render={<button type=\"button\" />}\n variant={meta.badgeVariant ?? 'secondary'}\n />\n }\n >\n <SelectValue\n className=\"min-w-0\"\n placeholder={meta.placeholder ?? 'Selecionar'}\n />\n </SelectPrimitive.Trigger>\n <SelectPopup alignItemWithTrigger={false}>\n {options.map((option) => (\n <SelectItem key={option.value} value={option}>\n {option.label}\n </SelectItem>\n ))}\n </SelectPopup>\n </Select>\n )\n }\n\n return (\n <span className={cn('block truncate px-1', align)}>\n {selectedOption?.label ?? toStringValue(value)}\n </span>\n )\n }\n\n case 'date': {\n return (\n <span className={cn('block truncate px-1', align)}>\n {formatDate(value)}\n </span>\n )\n }\n\n case 'badge': {\n if (value === null || value === undefined || value === '') {\n return (\n <span className=\"px-1 text-muted-foreground/72\">\n {meta.placeholder ?? ''}\n </span>\n )\n }\n const label =\n meta.options?.find((option) => option.value === toStringValue(value))\n ?.label ?? toStringValue(value)\n return (\n <span className={cn('flex', align)}>\n <Badge variant={meta.badgeVariant ?? 'secondary'}>{label}</Badge>\n </span>\n )\n }\n\n case 'number': {\n return (\n <span className={cn('block truncate px-1 tabular-nums', align)}>\n {toStringValue(value)}\n </span>\n )\n }\n\n default: {\n return (\n <span className={cn('block truncate px-1', align)}>\n {toStringValue(value)}\n </span>\n )\n }\n }\n}\n",
|
|
291
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-cell.tsx"
|
|
292
|
-
},
|
|
293
|
-
{
|
|
294
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-column-header.tsx",
|
|
295
|
-
"type": "registry:file",
|
|
296
|
-
"content": "'use client'\n\nimport { flexRender, type RowData } from '@tanstack/react-table'\nimport { Menu, MenuTrigger } from '@tc96/ui/menu'\nimport { cn } from '@tc96/utils'\nimport { ChevronDownIcon, ChevronUpIcon } from 'lucide-react'\nimport { HEADER_ALIGN } from '../lib/constants'\nimport type { DataGridHeader } from '../lib/data-grid-features'\nimport type { DataGridColumnMeta } from '../types'\nimport { DataGridColumnMenu } from './data-grid-column-menu'\nimport { DataGridColumnTypeIcon } from './data-grid-column-type-icon'\nimport { DataGridResizeHandle } from './data-grid-resize-handle'\n\nexport function DataGridColumnHeader<TData extends RowData>({\n header,\n}: {\n header: DataGridHeader<TData>\n}) {\n const { column } = header\n const meta = (column.columnDef.meta ?? {}) as DataGridColumnMeta\n const align = HEADER_ALIGN[meta.align ?? 'start']\n const sorted = column.getIsSorted()\n const table = header.getContext().table\n const visibleLeafColumns = table.getVisibleLeafColumns()\n const isLastColumn =\n visibleLeafColumns[visibleLeafColumns.length - 1]?.id === column.id\n const label = flexRender(column.columnDef.header, header.getContext())\n const showMenu =\n column.getCanSort() || column.getCanHide() || column.getCanPin()\n\n return (\n <div className={cn('flex size-full min-w-0 items-center gap-1', align)}>\n {showMenu ? (\n <Menu modal={false}>\n <MenuTrigger\n aria-label={`Opções da coluna ${meta.label ?? column.id}`}\n className={cn(\n 'flex size-full min-w-0 items-center gap-1.5 rounded-sm px-1 font-medium outline-none hover:bg-accent/40 focus-visible:ring-1 focus-visible:ring-ring data-popup-open:bg-accent/40',\n align,\n )}\n >\n {meta.type ? <DataGridColumnTypeIcon type={meta.type} /> : null}\n <span className=\"truncate\">{label}</span>\n {sorted === 'asc' ? (\n <ChevronUpIcon className=\"size-3.5 shrink-0 text-muted-foreground\" />\n ) : sorted === 'desc' ? (\n <ChevronDownIcon className=\"size-3.5 shrink-0 text-muted-foreground\" />\n ) : null}\n <ChevronDownIcon className=\"ms-auto size-3.5 shrink-0 text-muted-foreground\" />\n </MenuTrigger>\n <DataGridColumnMenu column={column} table={table} />\n </Menu>\n ) : (\n <div\n className={cn(\n 'flex min-w-0 flex-1 items-center gap-1.5 truncate px-1 font-medium',\n align,\n )}\n >\n {meta.type ? <DataGridColumnTypeIcon type={meta.type} /> : null}\n <span className=\"truncate\">{label}</span>\n </div>\n )}\n\n {column.getCanResize() ? (\n <DataGridResizeHandle\n column={column}\n header={header}\n isLastColumn={isLastColumn}\n table={table}\n />\n ) : null}\n </div>\n )\n}\n",
|
|
297
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-column-header.tsx"
|
|
298
|
-
},
|
|
299
|
-
{
|
|
300
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-column-menu.tsx",
|
|
301
|
-
"type": "registry:file",
|
|
302
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { MenuItem, MenuPopup, MenuSeparator } from '@tc96/ui/menu'\nimport {\n ArrowLeftIcon,\n ArrowRightIcon,\n ChevronDownIcon,\n ChevronsUpDownIcon,\n ChevronUpIcon,\n EyeOffIcon,\n PinIcon,\n PinOffIcon,\n} from 'lucide-react'\nimport type { DataGridColumn, DataGridTable } from '../lib/data-grid-features'\nimport { moveColumn } from '../lib/move-column'\n\nexport interface DataGridColumnMenuProps<TData extends RowData> {\n column: DataGridColumn<TData>\n table: DataGridTable<TData>\n}\n\nexport function DataGridColumnMenu<TData extends RowData>({\n column,\n table,\n}: DataGridColumnMenuProps<TData>) {\n const canSort = column.getCanSort()\n const canHide = column.getCanHide()\n const canPin = column.getCanPin()\n const sorted = column.getIsSorted()\n\n return (\n <MenuPopup align=\"end\">\n {canSort ? (\n <>\n <MenuItem onClick={() => column.toggleSorting(false)}>\n <ChevronUpIcon />\n Ordem crescente\n </MenuItem>\n <MenuItem onClick={() => column.toggleSorting(true)}>\n <ChevronDownIcon />\n Ordem decrescente\n </MenuItem>\n {sorted ? (\n <MenuItem onClick={() => column.clearSorting()}>\n <ChevronsUpDownIcon />\n Limpar ordenação\n </MenuItem>\n ) : null}\n <MenuSeparator />\n </>\n ) : null}\n <MenuItem onClick={() => moveColumn(table, column.id, -1)}>\n <ArrowLeftIcon />\n Mover para esquerda\n </MenuItem>\n <MenuItem onClick={() => moveColumn(table, column.id, 1)}>\n <ArrowRightIcon />\n Mover para direita\n </MenuItem>\n {canPin ? (\n <>\n <MenuSeparator />\n {column.getIsPinned() ? (\n <MenuItem onClick={() => column.pin(false)}>\n <PinOffIcon />\n Desafixar coluna\n </MenuItem>\n ) : (\n <>\n <MenuItem onClick={() => column.pin('start')}>\n <PinIcon />\n Fixar à esquerda\n </MenuItem>\n <MenuItem onClick={() => column.pin('end')}>\n <PinIcon />\n Fixar à direita\n </MenuItem>\n </>\n )}\n </>\n ) : null}\n {canHide ? (\n <>\n <MenuSeparator />\n <MenuItem onClick={() => column.toggleVisibility(false)}>\n <EyeOffIcon />\n Ocultar coluna\n </MenuItem>\n </>\n ) : null}\n </MenuPopup>\n )\n}\n",
|
|
303
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-column-menu.tsx"
|
|
304
|
-
},
|
|
305
|
-
{
|
|
306
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-column-type-icon.tsx",
|
|
307
|
-
"type": "registry:file",
|
|
308
|
-
"content": "'use client'\n\nimport {\n CalculatorIcon,\n CalendarIcon,\n CalendarPlusIcon,\n CircleDotIcon,\n ExternalLinkIcon,\n FingerprintIcon,\n HashIcon,\n Heading1Icon,\n HistoryIcon,\n Link2Icon,\n ListIcon,\n type LucideIcon,\n MailIcon,\n MapPinIcon,\n MousePointerClickIcon,\n PaperclipIcon,\n PhoneIcon,\n SigmaIcon,\n SquareCheckIcon,\n TagsIcon,\n TypeIcon,\n UserIcon,\n UserPenIcon,\n UserPlusIcon,\n} from 'lucide-react'\nimport type { DataGridColumnType } from '../types'\n\nexport const DATA_GRID_COLUMN_TYPE_ICONS = {\n title: Heading1Icon,\n text: TypeIcon,\n number: HashIcon,\n select: ListIcon,\n 'multi-select': TagsIcon,\n status: CircleDotIcon,\n date: CalendarIcon,\n formula: SigmaIcon,\n relation: Link2Icon,\n rollup: CalculatorIcon,\n person: UserIcon,\n file: PaperclipIcon,\n checkbox: SquareCheckIcon,\n url: ExternalLinkIcon,\n email: MailIcon,\n phone: PhoneIcon,\n 'created-time': CalendarPlusIcon,\n 'created-by': UserPlusIcon,\n 'last-edited-time': HistoryIcon,\n 'last-edited-by': UserPenIcon,\n button: MousePointerClickIcon,\n id: FingerprintIcon,\n place: MapPinIcon,\n} satisfies Record<DataGridColumnType, LucideIcon>\n\nexport function DataGridColumnTypeIcon({ type }: { type: DataGridColumnType }) {\n const Icon = DATA_GRID_COLUMN_TYPE_ICONS[type]\n\n return (\n <Icon\n aria-hidden=\"true\"\n className=\"size-3.5 shrink-0 text-muted-foreground\"\n data-column-type={type}\n data-slot=\"data-grid-column-type-icon\"\n />\n )\n}\n",
|
|
309
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-column-type-icon.tsx"
|
|
310
|
-
},
|
|
311
|
-
{
|
|
312
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-columns-submenu.tsx",
|
|
313
|
-
"type": "registry:file",
|
|
314
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { MenuSub, MenuSubPopup, MenuSubTrigger } from '@tc96/ui/menu'\nimport { Columns3Icon } from 'lucide-react'\nimport type React from 'react'\nimport { MenuCheckboxOption } from '../../../../shared/components/menu-selection-item'\nimport type { DataGridTable } from '../lib/data-grid-features'\nimport type { DataGridColumnMeta } from '../types'\n\nexport interface DataGridColumnsSubmenuProps<TData extends RowData> {\n label?: string\n table: DataGridTable<TData>\n}\n\nexport function DataGridColumnsSubmenu<TData extends RowData>({\n label = 'Colunas',\n table,\n}: DataGridColumnsSubmenuProps<TData>): React.ReactElement | null {\n const columns = table\n .getAllLeafColumns()\n .filter((column) => column.getCanHide())\n if (columns.length === 0) return null\n\n return (\n <MenuSub>\n <MenuSubTrigger>\n <Columns3Icon aria-hidden=\"true\" />\n {label}\n </MenuSubTrigger>\n <MenuSubPopup>\n {columns.map((column) => {\n const meta = (column.columnDef.meta ?? {}) as DataGridColumnMeta\n return (\n <MenuCheckboxOption\n checked={column.getIsVisible()}\n closeOnClick={false}\n key={column.id}\n onCheckedChange={(checked) =>\n column.toggleVisibility(Boolean(checked))\n }\n >\n {meta.label ?? column.id}\n </MenuCheckboxOption>\n )\n })}\n </MenuSubPopup>\n </MenuSub>\n )\n}\n",
|
|
315
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-columns-submenu.tsx"
|
|
316
|
-
},
|
|
317
|
-
{
|
|
318
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-density-submenu.tsx",
|
|
319
|
-
"type": "registry:file",
|
|
320
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport {\n MenuRadioGroup,\n MenuSub,\n MenuSubPopup,\n MenuSubTrigger,\n} from '@tc96/ui/menu'\nimport {\n AlignVerticalSpaceAroundIcon,\n ChevronsDownUpIcon,\n EqualIcon,\n MinusIcon,\n} from 'lucide-react'\nimport type React from 'react'\nimport { MenuRadioOption } from '../../../../shared/components/menu-selection-item'\nimport type { DataGridTable } from '../lib/data-grid-features'\nimport type { DataGridDensity } from '../types'\n\ninterface DensityOption {\n icon: React.ComponentType<React.ComponentProps<'svg'>>\n label: string\n value: DataGridDensity\n}\n\nconst DENSITIES: [DensityOption, ...DensityOption[]] = [\n { icon: MinusIcon, label: 'Compacta', value: 'short' },\n { icon: EqualIcon, label: 'Média', value: 'medium' },\n { icon: AlignVerticalSpaceAroundIcon, label: 'Alta', value: 'tall' },\n { icon: ChevronsDownUpIcon, label: 'Extra alta', value: 'extra-tall' },\n]\n\nexport interface DataGridDensitySubmenuProps<TData extends RowData> {\n label?: string\n table: DataGridTable<TData>\n}\n\nexport function DataGridDensitySubmenu<TData extends RowData>({\n label = 'Altura das linhas',\n table,\n}: DataGridDensitySubmenuProps<TData>): React.ReactElement {\n const density = table.options.meta?.dataGridDensity ?? 'short'\n const selected =\n DENSITIES.find((option) => option.value === density) ?? DENSITIES[0]\n const SelectedIcon = selected.icon\n\n return (\n <MenuSub>\n <MenuSubTrigger>\n <SelectedIcon aria-hidden=\"true\" />\n {label}\n </MenuSubTrigger>\n <MenuSubPopup>\n <MenuRadioGroup\n onValueChange={(value) =>\n table.options.meta?.onDataGridDensityChange?.(\n value as DataGridDensity,\n )\n }\n value={density}\n >\n {DENSITIES.map((option) => (\n <MenuRadioOption key={option.value} value={option.value}>\n <option.icon />\n {option.label}\n </MenuRadioOption>\n ))}\n </MenuRadioGroup>\n </MenuSubPopup>\n </MenuSub>\n )\n}\n",
|
|
321
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-density-submenu.tsx"
|
|
322
|
-
},
|
|
323
|
-
{
|
|
324
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-empty-row.tsx",
|
|
325
|
-
"type": "registry:file",
|
|
326
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nexport function DataGridEmptyRow({\n ariaRowIndex,\n message,\n}: {\n ariaRowIndex: number\n message: string\n}) {\n return (\n <div\n aria-rowindex={ariaRowIndex}\n className=\"flex min-h-24 items-center justify-center text-muted-foreground\"\n role=\"row\"\n tabIndex={-1}\n >\n <div aria-colindex={1} role=\"gridcell\" tabIndex={-1}>\n {message}\n </div>\n </div>\n )\n}\n",
|
|
327
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-empty-row.tsx"
|
|
328
|
-
},
|
|
329
|
-
{
|
|
330
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-filter-menu.tsx",
|
|
331
|
-
"type": "registry:file",
|
|
332
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { Button } from '@tc96/ui/button'\nimport { Input } from '@tc96/ui/input'\nimport { Popover, PopoverPopup, PopoverTrigger } from '@tc96/ui/popover'\nimport { ListFilterIcon } from 'lucide-react'\nimport type React from 'react'\nimport type { DataGridTable } from '../lib/data-grid-features'\nimport type { DataGridColumnMeta } from '../types'\n\nexport interface DataGridFilterMenuProps<TData extends RowData> {\n className?: string\n label?: string\n table: DataGridTable<TData>\n}\n\nexport function DataGridFilterMenu<TData extends RowData>({\n className,\n label = 'Filtrar',\n table,\n}: DataGridFilterMenuProps<TData>): React.ReactElement | null {\n const columns = table\n .getAllLeafColumns()\n .filter((column) => column.getCanFilter())\n if (columns.length === 0) return null\n\n return (\n <Popover>\n <PopoverTrigger\n render={\n <Button\n aria-label={label}\n className={className}\n size=\"sm\"\n variant=\"ghost\"\n />\n }\n >\n <ListFilterIcon />\n {label}\n </PopoverTrigger>\n <PopoverPopup align=\"end\" aria-label={label} className=\"w-72\">\n <div className=\"flex flex-col gap-3\" data-slot=\"data-grid-filter-menu\">\n <div>\n <h3 className=\"font-medium text-sm\">Filtrar por</h3>\n <p className=\"text-muted-foreground text-xs\">\n Preencha um ou mais campos.\n </p>\n </div>\n {columns.map((column) => {\n const meta = (column.columnDef.meta ?? {}) as DataGridColumnMeta\n const columnLabel = meta.label ?? column.id\n const inputId = `data-grid-filter-${column.id}`\n return (\n <label\n className=\"grid gap-1.5 text-sm\"\n htmlFor={inputId}\n key={column.id}\n >\n <span className=\"font-medium\">{columnLabel}</span>\n <Input\n aria-label={`Filtrar ${columnLabel}`}\n id={inputId}\n onChange={(event) => {\n const value = event.target.value\n column.setFilterValue(value || undefined)\n table.setPageIndex(0)\n }}\n placeholder={`Buscar em ${columnLabel.toLocaleLowerCase('pt-BR')}…`}\n value={String(column.getFilterValue() ?? '')}\n />\n </label>\n )\n })}\n {table.store.state.columnFilters.length > 0 ? (\n <Button\n onClick={() => table.resetColumnFilters()}\n size=\"sm\"\n variant=\"ghost\"\n >\n Limpar filtros\n </Button>\n ) : null}\n </div>\n </PopoverPopup>\n </Popover>\n )\n}\n",
|
|
333
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-filter-menu.tsx"
|
|
334
|
-
},
|
|
335
|
-
{
|
|
336
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-footer.tsx",
|
|
337
|
-
"type": "registry:file",
|
|
338
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport type { ReactNode } from 'react'\n\nexport function DataGridFooter({\n ariaRowIndex,\n children,\n columnCount,\n}: {\n ariaRowIndex: number\n children: ReactNode\n columnCount: number\n}) {\n return (\n <div\n aria-rowindex={ariaRowIndex}\n className=\"sticky bottom-0 z-10 border-t bg-background\"\n data-slot=\"data-grid-footer\"\n role=\"row\"\n tabIndex={-1}\n >\n <div aria-colspan={columnCount} role=\"gridcell\" tabIndex={-1}>\n {children}\n </div>\n </div>\n )\n}\n",
|
|
339
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-footer.tsx"
|
|
340
|
-
},
|
|
341
|
-
{
|
|
342
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-group-row.tsx",
|
|
343
|
-
"type": "registry:file",
|
|
344
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport { Badge } from '@tc96/ui/badge'\nimport { Button } from '@tc96/ui/button'\nimport { ChevronDownIcon, ChevronRightIcon } from 'lucide-react'\nimport { memo } from 'react'\n\nexport interface DataGridGroupRowProps {\n ariaRowIndex: number\n collapsed: boolean\n count: number\n group: string\n onToggle: (group: string, collapsed: boolean) => void\n}\n\nfunction DataGridGroupRowView({\n ariaRowIndex,\n collapsed,\n count,\n group,\n onToggle,\n}: DataGridGroupRowProps) {\n return (\n <div\n aria-rowindex={ariaRowIndex}\n className=\"flex min-h-9 items-center border-b bg-muted/40 px-1 font-medium\"\n data-collapsed={collapsed ? 'true' : undefined}\n data-slot=\"data-grid-group-row\"\n role=\"row\"\n tabIndex={-1}\n >\n <div\n className=\"flex min-w-0 items-center gap-1\"\n role=\"gridcell\"\n tabIndex={-1}\n >\n <Button\n aria-expanded={!collapsed}\n aria-label={`${collapsed ? 'Expand' : 'Collapse'} ${group}`}\n onClick={() => onToggle(group, !collapsed)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n {collapsed ? (\n <ChevronRightIcon aria-hidden=\"true\" />\n ) : (\n <ChevronDownIcon aria-hidden=\"true\" />\n )}\n </Button>\n <span className=\"truncate\" data-slot=\"data-grid-group-label\">\n {group}\n </span>\n <Badge\n className=\"size-5 min-w-5 shrink-0 rounded-full p-0 text-xs tabular-nums sm:size-5 sm:min-w-5\"\n data-slot=\"data-grid-group-count\"\n variant=\"secondary\"\n >\n {count}\n </Badge>\n </div>\n </div>\n )\n}\n\nexport const DataGridGroupRow = memo(DataGridGroupRowView)\n",
|
|
345
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-group-row.tsx"
|
|
346
|
-
},
|
|
347
|
-
{
|
|
348
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-header-rows.tsx",
|
|
349
|
-
"type": "registry:file",
|
|
350
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { type ColumnLayouts, resolveColumnLayout } from '../lib/column-layout'\nimport type { DataGridTable } from '../lib/data-grid-features'\nimport { DataGridColumnHeader } from './data-grid-column-header'\n\nexport interface DataGridHeaderRowsProps<TData extends RowData> {\n columnLayouts: ColumnLayouts\n fillColumnId?: string\n table: DataGridTable<TData>\n}\n\nexport function DataGridHeaderRows<TData extends RowData>({\n columnLayouts,\n fillColumnId,\n table,\n}: DataGridHeaderRowsProps<TData>) {\n const totalSize = table.getTotalSize()\n\n return (\n <div\n className=\"sticky top-0 z-10 grid border-b bg-[color-mix(in_srgb,var(--card),var(--color-black)_2%)] dark:bg-[color-mix(in_srgb,var(--card),var(--color-white)_2%)]\"\n data-slot=\"data-grid-header\"\n role=\"rowgroup\"\n style={{ minWidth: totalSize }}\n >\n {table.getHeaderGroups().map((headerGroup, rowIndex) => (\n <div\n aria-rowindex={rowIndex + 1}\n className=\"flex w-full\"\n data-slot=\"data-grid-header-row\"\n key={headerGroup.id}\n role=\"row\"\n style={{ minWidth: totalSize }}\n tabIndex={-1}\n >\n {headerGroup.headers.map((header, columnIndex) => {\n const sorted = header.column.getIsSorted()\n const layout =\n columnLayouts.get(header.column.id) ??\n resolveColumnLayout(header.column, fillColumnId)\n return (\n <div\n aria-colindex={columnIndex + 1}\n aria-sort={\n sorted === 'asc'\n ? 'ascending'\n : sorted === 'desc'\n ? 'descending'\n : header.column.getCanSort()\n ? 'none'\n : undefined\n }\n className=\"relative flex min-h-9 items-center border-e px-1.5 text-muted-foreground last:border-e-0 data-[pinned]:bg-[color-mix(in_srgb,var(--card),var(--color-black)_2%)] dark:data-[pinned]:bg-[color-mix(in_srgb,var(--card),var(--color-white)_2%)]\"\n data-column-id={header.column.id}\n data-pinned={layout?.pinned || undefined}\n data-slot=\"data-grid-header-cell\"\n key={header.id}\n role=\"columnheader\"\n style={layout?.style}\n tabIndex={-1}\n >\n {header.isPlaceholder ? null : (\n <DataGridColumnHeader header={header} />\n )}\n </div>\n )\n })}\n </div>\n ))}\n </div>\n )\n}\n",
|
|
351
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-header-rows.tsx"
|
|
352
|
-
},
|
|
353
|
-
{
|
|
354
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-pagination.tsx",
|
|
355
|
-
"type": "registry:file",
|
|
356
|
-
"content": "'use client'\n\nimport type { PaginationState } from '@tanstack/react-table'\nimport type React from 'react'\nimport { CollectionPagination } from '../../../../shared/components/collection-pagination'\n\nexport interface PaginatedTable {\n readonly store: { readonly state: { pagination: PaginationState } }\n getPageCount: () => number\n getRowCount: () => number\n setPageIndex: (pageIndex: number) => void\n}\n\nexport interface DataGridPaginationProps\n extends Omit<React.ComponentProps<'div'>, 'children'> {\n table: PaginatedTable\n}\n\nexport function DataGridPagination({\n table,\n ...props\n}: DataGridPaginationProps): React.ReactElement {\n const { pageIndex, pageSize } = table.store.state.pagination\n\n return (\n <CollectionPagination\n data-slot=\"data-grid-pagination\"\n label=\"Paginação da tabela\"\n onPageChange={(page) => table.setPageIndex(page - 1)}\n page={pageIndex + 1}\n pageCount={table.getPageCount()}\n pageSize={pageSize}\n total={table.getRowCount()}\n {...props}\n />\n )\n}\n",
|
|
357
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-pagination.tsx"
|
|
358
|
-
},
|
|
359
|
-
{
|
|
360
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-resize-handle.tsx",
|
|
361
|
-
"type": "registry:file",
|
|
362
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { cn } from '@tc96/utils'\nimport type {\n DataGridColumn,\n DataGridHeader,\n DataGridTable,\n} from '../lib/data-grid-features'\nimport { resolveColumnSizeBounds, resolveResizeKeySize } from '../lib/resize'\nimport type { DataGridColumnMeta } from '../types'\n\nexport interface DataGridResizeHandleProps<TData extends RowData> {\n column: DataGridColumn<TData>\n header: DataGridHeader<TData>\n isLastColumn: boolean\n table: DataGridTable<TData>\n}\n\nexport function DataGridResizeHandle<TData extends RowData>({\n column,\n header,\n isLastColumn,\n table,\n}: DataGridResizeHandleProps<TData>) {\n const meta = (column.columnDef.meta ?? {}) as DataGridColumnMeta\n const { max, min } = resolveColumnSizeBounds(column)\n\n return (\n <div\n aria-label={`Redimensionar coluna ${meta.label ?? column.id}`}\n aria-orientation=\"vertical\"\n aria-valuemax={max}\n aria-valuemin={min}\n aria-valuenow={column.getSize()}\n className={cn(\n 'absolute top-0 z-20 h-full w-0.5 cursor-ew-resize touch-none select-none outline-none after:absolute after:inset-y-0 after:start-1/2 after:w-4 hover:bg-primary focus-visible:bg-primary',\n isLastColumn\n ? 'end-0 after:-translate-x-full'\n : '-end-px after:-translate-x-1/2',\n column.getIsResizing() ? 'bg-primary' : 'bg-border',\n )}\n onDoubleClick={() => column.resetSize()}\n onKeyDown={(event) => {\n const size = resolveResizeKeySize(column, event.key)\n if (size === undefined) return\n event.preventDefault()\n table.setColumnSizing((current) => ({\n ...current,\n [column.id]: size,\n }))\n }}\n onMouseDown={header.getResizeHandler()}\n onTouchStart={header.getResizeHandler()}\n role=\"separator\"\n tabIndex={0}\n />\n )\n}\n",
|
|
363
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-resize-handle.tsx"
|
|
364
|
-
},
|
|
365
|
-
{
|
|
366
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-row.tsx",
|
|
367
|
-
"type": "registry:file",
|
|
368
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport type { Row, RowData } from '@tanstack/react-table'\nimport { cn } from '@tc96/utils'\nimport { memo, useCallback, useMemo } from 'react'\nimport { useDataGridRowContext } from '../hooks/use-data-grid-row-context'\nimport { ROW_DENSITY } from '../lib/constants'\nimport type { DataGridFeatures } from '../lib/data-grid-features'\nimport { DataGridBodyCell } from './data-grid-body-cell'\n\nexport interface DataGridRowProps<TData extends RowData> {\n ariaRowIndex: number\n focusedColumnId?: string\n interacted: boolean\n row: Row<DataGridFeatures, TData>\n selected: boolean\n selectedColumnIds?: ReadonlySet<string>\n virtualSize?: number\n virtualStart?: number\n}\n\nfunction DataGridRowView<TData extends RowData>({\n ariaRowIndex,\n focusedColumnId,\n interacted,\n row,\n selected,\n selectedColumnIds,\n virtualSize,\n virtualStart,\n}: DataGridRowProps<TData>) {\n const { columnLayouts, density, interactions, rowSelectable, meta } =\n useDataGridRowContext()\n const rowId = row.id\n const registerRef = useCallback(\n (node: HTMLDivElement | null) => interactions.registerRow(rowId, node),\n [interactions, rowId],\n )\n const virtualStyle = useMemo(\n () =>\n virtualStart === undefined\n ? undefined\n : {\n height: virtualSize,\n transform: `translateY(${virtualStart}px)`,\n },\n [virtualSize, virtualStart],\n )\n\n return (\n <div\n aria-rowindex={ariaRowIndex}\n aria-selected={rowSelectable ? selected : undefined}\n className={cn(\n 'group flex w-full border-b transition-colors last:border-b-0 hover:bg-accent/40 data-[state=selected]:bg-primary/10',\n ROW_DENSITY[density],\n virtualStyle && 'absolute start-0 top-0',\n )}\n data-slot=\"data-grid-row\"\n data-state={selected ? 'selected' : undefined}\n ref={registerRef}\n role=\"row\"\n style={virtualStyle}\n tabIndex={-1}\n >\n {row.getVisibleCells().map((cell, columnIndex) => {\n const isFocused = focusedColumnId === cell.column.id\n return (\n <DataGridBodyCell\n canSelect={row.getCanSelect()}\n cell={cell}\n columnIndex={columnIndex}\n density={density}\n interactions={interactions}\n isFocused={isFocused}\n isSelected={selectedColumnIds?.has(cell.column.id) ?? false}\n key={cell.id}\n layout={columnLayouts.get(cell.column.id)}\n rowSelected={selected}\n showFocus={isFocused && interacted}\n meta={meta}\n />\n )\n })}\n </div>\n )\n}\n\nexport const DataGridRow = memo(DataGridRowView) as typeof DataGridRowView\n",
|
|
369
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-row.tsx"
|
|
370
|
-
},
|
|
371
|
-
{
|
|
372
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-search.tsx",
|
|
373
|
-
"type": "registry:file",
|
|
374
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { Input } from '@tc96/ui/input'\nimport { cn } from '@tc96/utils'\nimport type React from 'react'\nimport type { DataGridTable } from '../lib/data-grid-features'\n\nexport interface DataGridSearchProps<TData extends RowData>\n extends Omit<\n React.ComponentProps<typeof Input>,\n 'onChange' | 'value' | 'type'\n > {\n table: DataGridTable<TData>\n}\n\nexport function DataGridSearch<TData extends RowData>({\n 'aria-label': ariaLabel,\n className,\n placeholder = 'Buscar…',\n table,\n ...props\n}: DataGridSearchProps<TData>): React.ReactElement {\n const accessibleName = ariaLabel ?? placeholder\n\n return (\n <Input\n aria-label={accessibleName}\n className={cn('max-w-64', className)}\n data-slot=\"data-grid-search\"\n onChange={(event) => {\n table.setGlobalFilter(event.target.value)\n table.setPageIndex(0)\n }}\n placeholder={placeholder}\n type=\"search\"\n value={(table.store.state.globalFilter as string) ?? ''}\n {...props}\n />\n )\n}\n",
|
|
375
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-search.tsx"
|
|
376
|
-
},
|
|
377
|
-
{
|
|
378
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-selection-actions.tsx",
|
|
379
|
-
"type": "registry:file",
|
|
380
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport type { ReactNode } from 'react'\nimport type { ActionBarContext } from '../../../shared/components/action-bar'\nimport type { DataGridTable } from '../lib/data-grid-features'\n\nexport type DataGridSelectionActionsProp<TData extends RowData> =\n | ReactNode\n | ((\n context: ActionBarContext<TData> & {\n clearSelection: () => void\n },\n ) => ReactNode)\n\nexport interface DataGridSelectionActionsProps<TData extends RowData> {\n selectionActions?: DataGridSelectionActionsProp<TData>\n table: DataGridTable<TData>\n}\n\nexport function DataGridSelectionActions<TData extends RowData>({\n selectionActions,\n table,\n}: DataGridSelectionActionsProps<TData>) {\n if (!selectionActions) return null\n const selectedRows = table\n .getSelectedRowModel()\n .rows.map((row) => row.original)\n if (selectedRows.length === 0) return null\n\n const content =\n typeof selectionActions === 'function'\n ? selectionActions({\n clearSelection: () => table.resetRowSelection(),\n selectedCount: selectedRows.length,\n selectedRows,\n })\n : selectionActions\n if (!content) return null\n\n return (\n <div\n className=\"pointer-events-none absolute inset-x-0 bottom-3 z-20 flex justify-center px-3\"\n data-slot=\"data-grid-selection-actions\"\n >\n <div className=\"pointer-events-auto\">{content}</div>\n </div>\n )\n}\n",
|
|
381
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-selection-actions.tsx"
|
|
382
|
-
},
|
|
383
|
-
{
|
|
384
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-selection-summary.tsx",
|
|
385
|
-
"type": "registry:file",
|
|
386
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { cn } from '@tc96/utils'\nimport type React from 'react'\nimport type { DataGridTable } from '../lib/data-grid-features'\n\nexport interface DataGridSelectionSummaryProps<TData extends RowData>\n extends Omit<React.ComponentProps<'span'>, 'children'> {\n table: DataGridTable<TData>\n}\n\nexport function DataGridSelectionSummary<TData extends RowData>({\n className,\n table,\n ...props\n}: DataGridSelectionSummaryProps<TData>): React.ReactElement {\n const count = table.getSelectedRowModel().rows.length\n return (\n <span\n aria-live=\"polite\"\n className={cn(\n 'px-2 text-muted-foreground text-sm tabular-nums',\n className,\n )}\n data-slot=\"data-grid-selection-summary\"\n {...props}\n >\n {count} {count === 1 ? 'selecionado' : 'selecionados'}\n </span>\n )\n}\n",
|
|
387
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-selection-summary.tsx"
|
|
388
|
-
},
|
|
389
|
-
{
|
|
390
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-skeleton-rows.tsx",
|
|
391
|
-
"type": "registry:file",
|
|
392
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: the WAI-ARIA grid pattern is used instead of table layout elements so the body can be virtualized\n\n'use client'\n\nimport { Skeleton } from '@tc96/ui/skeleton'\nimport { cn } from '@tc96/utils'\nimport type { ColumnLayouts } from '../lib/column-layout'\nimport { CELL_DENSITY, ROW_DENSITY } from '../lib/constants'\nimport type { DataGridDensity } from '../types'\n\nexport interface DataGridSkeletonRowsProps {\n columnIds: readonly string[]\n columnLayouts: ColumnLayouts\n density: DataGridDensity\n headerRowCount: number\n rowIds: readonly string[]\n}\n\nexport function DataGridSkeletonRows({\n columnIds,\n columnLayouts,\n density,\n headerRowCount,\n rowIds,\n}: DataGridSkeletonRowsProps) {\n return rowIds.map((rowId, rowIndex) => (\n <div\n aria-rowindex={headerRowCount + rowIndex + 1}\n className={cn(\n 'flex w-full border-b last:border-b-0',\n ROW_DENSITY[density],\n )}\n key={rowId}\n role=\"row\"\n tabIndex={-1}\n >\n {columnIds.map((columnId, columnIndex) => {\n const layout = columnLayouts.get(columnId)\n return (\n <div\n aria-colindex={columnIndex + 1}\n className={cn(\n 'flex items-center border-e last:border-e-0 data-[pinned]:bg-background',\n CELL_DENSITY[density],\n )}\n data-column-id={columnId}\n data-pinned={layout?.pinned || undefined}\n key={columnId}\n role=\"gridcell\"\n style={layout?.style}\n tabIndex={-1}\n >\n <Skeleton className=\"h-4 w-full\" />\n </div>\n )\n })}\n </div>\n ))\n}\n",
|
|
393
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-skeleton-rows.tsx"
|
|
394
|
-
},
|
|
395
|
-
{
|
|
396
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid-sort-submenu.tsx",
|
|
397
|
-
"type": "registry:file",
|
|
398
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport {\n MenuItem,\n MenuSeparator,\n MenuSub,\n MenuSubPopup,\n MenuSubTrigger,\n} from '@tc96/ui/menu'\nimport { ArrowDownUpIcon } from 'lucide-react'\nimport type React from 'react'\nimport type { DataGridTable } from '../lib/data-grid-features'\nimport type { DataGridColumnMeta } from '../types'\n\nexport interface DataGridSortSubmenuProps<TData extends RowData> {\n label?: string\n table: DataGridTable<TData>\n}\n\nexport function DataGridSortSubmenu<TData extends RowData>({\n label = 'Ordenar por',\n table,\n}: DataGridSortSubmenuProps<TData>): React.ReactElement | null {\n const columns = table\n .getAllLeafColumns()\n .filter((column) => column.getCanSort())\n if (columns.length === 0) return null\n\n return (\n <MenuSub>\n <MenuSubTrigger>\n <ArrowDownUpIcon aria-hidden=\"true\" />\n {label}\n </MenuSubTrigger>\n <MenuSubPopup>\n {columns.flatMap((column) => {\n const meta = (column.columnDef.meta ?? {}) as DataGridColumnMeta\n const columnLabel = meta.label ?? column.id\n return [\n <MenuItem\n key={`${column.id}-asc`}\n onClick={() => column.toggleSorting(false)}\n >\n {columnLabel}: crescente\n </MenuItem>,\n <MenuItem\n key={`${column.id}-desc`}\n onClick={() => column.toggleSorting(true)}\n >\n {columnLabel}: decrescente\n </MenuItem>,\n ]\n })}\n {table.store.state.sorting.length > 0 ? (\n <>\n <MenuSeparator />\n <MenuItem onClick={() => table.resetSorting()}>\n Limpar ordenação\n </MenuItem>\n </>\n ) : null}\n </MenuSubPopup>\n </MenuSub>\n )\n}\n",
|
|
399
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid-sort-submenu.tsx"
|
|
400
|
-
},
|
|
401
|
-
{
|
|
402
|
-
"path": "parttens/src/collection-views/views/data-grid/components/data-grid.tsx",
|
|
403
|
-
"type": "registry:file",
|
|
404
|
-
"content": "// biome-ignore-all lint/a11y/useSemanticElements: a virtualizable spreadsheet uses the WAI-ARIA grid pattern instead of table layout elements\n\n'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { ScrollAreaPrimitive, ScrollBar } from '@tc96/ui/scroll-area'\nimport { cn } from '@tc96/utils'\nimport { type ReactNode, useMemo, useRef } from 'react'\nimport { useCollapsedGroups } from '../hooks/use-collapsed-groups'\nimport { useColumnLayouts } from '../hooks/use-column-layouts'\nimport { useDataGridCellEvents } from '../hooks/use-data-grid-cell-events'\nimport { useDataGridCellSelection } from '../hooks/use-data-grid-cell-selection'\nimport { useDataGridDragScroll } from '../hooks/use-data-grid-drag-scroll'\nimport { useDataGridFocus } from '../hooks/use-data-grid-focus'\nimport { DataGridRowContext } from '../hooks/use-data-grid-row-context'\nimport { useDataGridRows } from '../hooks/use-data-grid-rows'\nimport { useDataGridVirtualizer } from '../hooks/use-data-grid-virtualizer'\nimport { useLatestCallback } from '../hooks/use-latest-callback'\nimport {\n findFirstNavigableColumnIndex,\n indexColumns,\n resolveFillColumnId,\n} from '../lib/columns'\nimport type { DataGridTable } from '../lib/data-grid-features'\nimport type { DataGridDensity } from '../types'\nimport { DataGridAddRow } from './data-grid-add-row'\nimport { DataGridBody } from './data-grid-body'\nimport { DataGridFooter } from './data-grid-footer'\nimport { DataGridHeaderRows } from './data-grid-header-rows'\nimport { DataGridPagination } from './data-grid-pagination'\nimport {\n DataGridSelectionActions,\n type DataGridSelectionActionsProp,\n} from './data-grid-selection-actions'\n\nexport interface DataGridProps<TData extends RowData> {\n table: DataGridTable<TData>\n pagination?: boolean\n fillColumn?: string | false\n footer?: ReactNode\n density?: DataGridDensity\n isLoading?: boolean\n loadingRowCount?: number\n emptyMessage?: string\n maxHeight?: number | string\n getRowGroup?: (row: TData) => string | null\n collapsedGroupIds?: readonly string[]\n defaultCollapsedGroupIds?: readonly string[]\n onCollapsedGroupIdsChange?: (groupIds: readonly string[]) => void\n getRowSelected?: (row: TData) => boolean\n onRowAdd?: () => void | Promise<void>\n addRowLabel?: string\n virtualize?: boolean\n overscan?: number\n className?: string\n selectionActions?: DataGridSelectionActionsProp<TData>\n 'aria-label'?: string\n}\n\nconst NO_GROUPS: readonly string[] = []\n\nexport function DataGrid<TData extends RowData>({\n table,\n pagination,\n fillColumn,\n footer,\n density: densityProp,\n isLoading = false,\n loadingRowCount = 5,\n emptyMessage = 'Nenhum registro para exibir.',\n maxHeight,\n getRowGroup,\n collapsedGroupIds: controlledCollapsedGroupIds,\n defaultCollapsedGroupIds = NO_GROUPS,\n onCollapsedGroupIdsChange,\n getRowSelected,\n onRowAdd,\n addRowLabel = 'Adicionar linha',\n virtualize = false,\n overscan = 8,\n className,\n selectionActions,\n 'aria-label': ariaLabel,\n}: DataGridProps<TData>) {\n const gridRef = useRef<HTMLDivElement>(null)\n const showsPagination = pagination ?? !table.options.manualPagination\n const footerContent =\n footer ?? (showsPagination ? <DataGridPagination table={table} /> : null)\n const density = densityProp ?? table.options.meta?.dataGridDensity ?? 'short'\n const leafColumns = table.getVisibleLeafColumns()\n const fillColumnId = resolveFillColumnId(leafColumns, fillColumn)\n const columnIndexById = useMemo(\n () => indexColumns(leafColumns),\n [leafColumns],\n )\n const columnLayouts = useColumnLayouts(leafColumns, fillColumnId)\n const firstNavigableColumn = findFirstNavigableColumnIndex(leafColumns)\n\n const { collapsedGroupIds, setGroupCollapsed } = useCollapsedGroups({\n controlled: controlledCollapsedGroupIds,\n defaultValue: defaultCollapsedGroupIds,\n onChange: onCollapsedGroupIdsChange,\n })\n const onToggleGroup = useLatestCallback(setGroupCollapsed)\n const model = useDataGridRows({ collapsedGroupIds, getRowGroup, table })\n const { rows } = model\n\n const cellSelection = useDataGridCellSelection({\n availableColumnIds: columnIndexById,\n coreRowsById: table.getCoreRowModel().rowsById,\n availableRowIds: model.positions,\n firstColumnId: leafColumns[firstNavigableColumn]?.id,\n firstRowId: rows[0]?.id,\n visibleRowIds: model.rowIndexById,\n })\n const { focusCell, registry } = useDataGridFocus({\n focusedColumnId: cellSelection.focusedColumnId,\n focusedRowId: cellSelection.focusedRowId,\n hasInteracted: cellSelection.hasInteracted,\n })\n\n const shouldVirtualize =\n virtualize && !getRowGroup && !isLoading && rows.length > 0\n const virtualizer = useDataGridVirtualizer({\n density,\n enabled: shouldVirtualize,\n gridRef,\n hasBottomBar: Boolean(onRowAdd || footerContent),\n maxHeight,\n overscan,\n rows,\n table,\n })\n const interactions = useDataGridCellEvents({\n columnIndexById,\n columns: leafColumns,\n firstNavigableColumn,\n focusCell,\n registry,\n rowIndexById: model.rowIndexById,\n rows,\n scrollRowIntoView: shouldVirtualize\n ? virtualizer.scrollRowIntoView\n : undefined,\n selectCell: cellSelection.selectCell,\n selection: cellSelection.selection,\n })\n const dragScroll = useDataGridDragScroll()\n\n const rowSelectable =\n Boolean(getRowSelected) || Boolean(table.options.enableRowSelection)\n const meta = table.options.meta\n const enableRowSelection = table.options.enableRowSelection\n const rowContext = useMemo(\n () => ({\n columnLayouts,\n columns: leafColumns,\n density,\n enableRowSelection,\n interactions,\n meta,\n rowSelectable,\n }),\n [\n columnLayouts,\n density,\n enableRowSelection,\n interactions,\n leafColumns,\n meta,\n rowSelectable,\n ],\n )\n\n const bodyRowCount = isLoading\n ? loadingRowCount\n : model.collectionRowCount === 0\n ? 1\n : model.collectionRowCount + model.groupRowCount\n const ariaRowCount =\n model.headerRowCount +\n bodyRowCount +\n (onRowAdd ? 1 : 0) +\n (footerContent ? 1 : 0)\n const totalSize = table.getTotalSize()\n\n return (\n <div\n className={cn(\n 'relative min-w-0',\n fillColumnId ? 'w-full' : 'w-fit max-w-full',\n className,\n )}\n >\n <ScrollAreaPrimitive.Root\n className={cn(\n 'relative h-auto rounded-md border bg-background text-sm',\n fillColumnId ? 'w-full' : 'w-fit max-w-full',\n )}\n data-slot=\"data-grid\"\n >\n <ScrollAreaPrimitive.Viewport\n aria-busy={isLoading || undefined}\n aria-colcount={leafColumns.length}\n aria-label={ariaLabel}\n aria-multiselectable\n aria-rowcount={ariaRowCount}\n className=\"grid h-full cursor-grab select-none rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-[drag-scroll=dragging]:cursor-grabbing data-has-overflow-x:overscroll-x-contain data-has-overflow-y:overscroll-y-contain\"\n data-density={density}\n data-drag-scroll={dragScroll.isDragScrolling ? 'dragging' : undefined}\n data-slot=\"scroll-area-viewport\"\n onClickCapture={dragScroll.onClickCapture}\n onLostPointerCapture={dragScroll.onLostPointerCapture}\n onPointerCancel={dragScroll.onPointerCancel}\n onPointerDownCapture={dragScroll.onPointerDownCapture}\n onPointerMove={dragScroll.onPointerMove}\n onPointerUp={dragScroll.onPointerUp}\n ref={gridRef}\n role=\"grid\"\n style={{ maxHeight }}\n tabIndex={rows.length > 0 && !isLoading ? -1 : 0}\n >\n <ScrollAreaPrimitive.Content\n data-slot=\"scroll-area-content\"\n style={{ minWidth: 0 }}\n >\n <DataGridHeaderRows\n columnLayouts={columnLayouts}\n fillColumnId={fillColumnId}\n table={table}\n />\n <DataGridRowContext value={rowContext}>\n <DataGridBody\n columnIds={leafColumns.map((column) => column.id)}\n columnLayouts={columnLayouts}\n density={density}\n emptyMessage={emptyMessage}\n entries={model.entries}\n focusedColumnId={cellSelection.focusedColumnId}\n focusedRowId={cellSelection.focusedRowId}\n getRowSelected={getRowSelected}\n hasInteracted={cellSelection.hasInteracted}\n headerRowCount={model.headerRowCount}\n isLoading={isLoading}\n loadingRowCount={loadingRowCount}\n minWidth={totalSize}\n onToggleGroup={onToggleGroup}\n pageRowCount={model.pageRows.length}\n selection={cellSelection.selection}\n totalSize={virtualizer.totalSize}\n virtualItems={virtualizer.virtualItems}\n virtualized={shouldVirtualize}\n />\n </DataGridRowContext>\n {onRowAdd ? (\n <DataGridAddRow\n ariaRowIndex={model.headerRowCount + bodyRowCount + 1}\n label={addRowLabel}\n minWidth={totalSize}\n onAdd={onRowAdd}\n />\n ) : null}\n {footerContent ? (\n <DataGridFooter\n ariaRowIndex={ariaRowCount}\n columnCount={leafColumns.length}\n >\n {footerContent}\n </DataGridFooter>\n ) : null}\n </ScrollAreaPrimitive.Content>\n </ScrollAreaPrimitive.Viewport>\n <ScrollBar orientation=\"vertical\" />\n <ScrollBar orientation=\"horizontal\" />\n <ScrollAreaPrimitive.Corner data-slot=\"scroll-area-corner\" />\n </ScrollAreaPrimitive.Root>\n <DataGridSelectionActions\n selectionActions={selectionActions}\n table={table}\n />\n </div>\n )\n}\n",
|
|
405
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/components/data-grid.tsx"
|
|
406
|
-
},
|
|
407
|
-
{
|
|
408
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-collapsed-groups.ts",
|
|
409
|
-
"type": "registry:file",
|
|
410
|
-
"content": "import { useRef, useState } from 'react'\n\ninterface UseCollapsedGroupsOptions {\n controlled?: readonly string[]\n defaultValue: readonly string[]\n onChange?: (groupIds: readonly string[]) => void\n}\n\nexport function useCollapsedGroups({\n controlled,\n defaultValue,\n onChange,\n}: UseCollapsedGroupsOptions) {\n const [uncontrolled, setUncontrolled] =\n useState<readonly string[]>(defaultValue)\n const uncontrolledRef = useRef(uncontrolled)\n const collapsedGroupIds = controlled ?? uncontrolled\n\n function setGroupCollapsed(group: string, collapsed: boolean) {\n const current = controlled ?? uncontrolledRef.current\n const others = current.filter((id) => id !== group)\n const next = collapsed ? [...others, group] : others\n if (!controlled) {\n uncontrolledRef.current = next\n setUncontrolled(next)\n }\n onChange?.(next)\n }\n\n return { collapsedGroupIds, setGroupCollapsed }\n}\n",
|
|
411
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-collapsed-groups.ts"
|
|
412
|
-
},
|
|
413
|
-
{
|
|
414
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-column-layouts.ts",
|
|
415
|
-
"type": "registry:file",
|
|
416
|
-
"content": "import type { RowData } from '@tanstack/react-table'\nimport { useState } from 'react'\nimport { buildColumnLayouts } from '../lib/column-layout'\nimport type { DataGridColumn } from '../lib/data-grid-features'\n\nexport function useColumnLayouts<TData extends RowData>(\n columns: readonly DataGridColumn<TData>[],\n fillColumnId?: string,\n) {\n const [layouts, setLayouts] = useState(() =>\n buildColumnLayouts(columns, fillColumnId),\n )\n const next = buildColumnLayouts(columns, fillColumnId, layouts)\n if (next !== layouts) setLayouts(next)\n return next\n}\n",
|
|
417
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-column-layouts.ts"
|
|
418
|
-
},
|
|
419
|
-
{
|
|
420
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-data-grid-cell-events.ts",
|
|
421
|
-
"type": "registry:file",
|
|
422
|
-
"content": "import type { Row, RowData } from '@tanstack/react-table'\nimport {\n type KeyboardEvent,\n type MouseEvent,\n type PointerEvent,\n useMemo,\n useRef,\n} from 'react'\nimport type { CellIdentity, CellRegistry } from '../lib/cell-registry'\nimport {\n PENDING_SELECT_CLICK_WINDOW_MS,\n SELECT_TRIGGER_SELECTOR,\n} from '../lib/constants'\nimport type {\n DataGridColumn,\n DataGridFeatures,\n} from '../lib/data-grid-features'\nimport { hasSelectTrigger } from '../lib/dom'\nimport { type CellSelection, isCellSelected } from '../lib/selection'\nimport { useLatestCallback } from './use-latest-callback'\n\nexport interface CellInteractions {\n onClick: (event: MouseEvent<HTMLDivElement>) => void\n onClickCapture: (event: MouseEvent<HTMLDivElement>) => void\n onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void\n onMouseDownCapture: (event: MouseEvent<HTMLDivElement>) => void\n onPointerDownCapture: (event: PointerEvent<HTMLDivElement>) => void\n registerRow: CellRegistry['registerRow']\n}\n\ninterface UseDataGridCellEventsOptions<TData extends RowData> {\n columnIndexById: ReadonlyMap<string, number>\n columns: readonly DataGridColumn<TData>[]\n firstNavigableColumn: number\n focusCell: (rowId: string, columnId: string) => void\n registry: CellRegistry\n rowIndexById: ReadonlyMap<string, number>\n rows: readonly Row<DataGridFeatures, TData>[]\n scrollRowIntoView?: (rowIndex: number) => void\n selectCell: (rowId: string, columnId: string, extend?: boolean) => void\n selection: CellSelection\n}\n\ninterface PendingSelectClick extends CellIdentity {\n timestamp: number\n}\n\nexport function useDataGridCellEvents<TData extends RowData>({\n columnIndexById,\n columns,\n firstNavigableColumn,\n focusCell,\n registry,\n rowIndexById,\n rows,\n scrollRowIntoView,\n selectCell,\n selection,\n}: UseDataGridCellEventsOptions<TData>): CellInteractions {\n const pendingRef = useRef<PendingSelectClick | null>(null)\n\n const isPendingPointerSelect = (identity: CellIdentity) => {\n const pending = pendingRef.current\n return (\n pending?.rowId === identity.rowId &&\n pending.columnId === identity.columnId &&\n performance.now() - pending.timestamp < PENDING_SELECT_CLICK_WINDOW_MS\n )\n }\n\n const onKeyDown = useLatestCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget) return\n const identity = registry.identify(event.currentTarget)\n const rowIndex = identity && rowIndexById.get(identity.rowId)\n const columnIndex = identity && columnIndexById.get(identity.columnId)\n if (rowIndex === undefined || columnIndex === undefined) return\n\n let nextRow = rowIndex\n let nextColumn = columnIndex\n if (event.key === 'ArrowLeft') nextColumn -= 1\n else if (event.key === 'ArrowRight') nextColumn += 1\n else if (event.key === 'ArrowUp') nextRow -= 1\n else if (event.key === 'ArrowDown') nextRow += 1\n else if (event.key === 'Home') {\n nextColumn = firstNavigableColumn\n if (event.ctrlKey || event.metaKey) nextRow = 0\n } else if (event.key === 'End') {\n nextColumn = columns.length - 1\n if (event.ctrlKey || event.metaKey) nextRow = rows.length - 1\n } else return\n\n event.preventDefault()\n nextRow = Math.max(0, Math.min(rows.length - 1, nextRow))\n nextColumn = Math.max(\n firstNavigableColumn,\n Math.min(columns.length - 1, nextColumn),\n )\n if (scrollRowIntoView && nextRow !== rowIndex) scrollRowIntoView(nextRow)\n const nextRowId = rows[nextRow]?.id\n const nextColumnId = columns[nextColumn]?.id\n if (!(nextRowId && nextColumnId)) return\n selectCell(nextRowId, nextColumnId, event.shiftKey)\n focusCell(nextRowId, nextColumnId)\n },\n )\n\n const onPointerDownCapture = useLatestCallback(\n (event: PointerEvent<HTMLDivElement>) => {\n const identity = registry.identify(event.currentTarget)\n if (!identity) return\n const selected = isCellSelected(\n selection,\n identity.rowId,\n identity.columnId,\n )\n if (selected || !hasSelectTrigger(event.currentTarget)) return\n\n event.preventDefault()\n event.stopPropagation()\n pendingRef.current = { ...identity, timestamp: performance.now() }\n selectCell(identity.rowId, identity.columnId, event.shiftKey)\n },\n )\n\n const onMouseDownCapture = useLatestCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n const identity = registry.identify(event.currentTarget)\n if (!identity) return\n\n if (isPendingPointerSelect(identity)) {\n event.preventDefault()\n event.stopPropagation()\n return\n }\n\n const selected = isCellSelected(\n selection,\n identity.rowId,\n identity.columnId,\n )\n if (selected || !hasSelectTrigger(event.currentTarget)) return\n\n event.preventDefault()\n event.stopPropagation()\n pendingRef.current = { ...identity, timestamp: performance.now() }\n selectCell(identity.rowId, identity.columnId, event.shiftKey)\n },\n )\n\n const onClickCapture = useLatestCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n const identity = registry.identify(event.currentTarget)\n if (!identity) return\n\n if (isPendingPointerSelect(identity)) {\n event.preventDefault()\n event.stopPropagation()\n pendingRef.current = null\n return\n }\n\n const selected = isCellSelected(\n selection,\n identity.rowId,\n identity.columnId,\n )\n if (selected || !hasSelectTrigger(event.currentTarget)) return\n\n event.preventDefault()\n event.stopPropagation()\n selectCell(identity.rowId, identity.columnId, event.shiftKey)\n },\n )\n\n const onClick = useLatestCallback((event: MouseEvent<HTMLDivElement>) => {\n const identity = registry.identify(event.currentTarget)\n if (!identity) return\n const selected = isCellSelected(\n selection,\n identity.rowId,\n identity.columnId,\n )\n selectCell(identity.rowId, identity.columnId, event.shiftKey)\n if (!selected) return\n\n const trigger = event.currentTarget.querySelector<HTMLElement>(\n SELECT_TRIGGER_SELECTOR,\n )\n if (!trigger || trigger.contains(event.target as Node)) return\n trigger.click()\n })\n\n return useMemo(\n () => ({\n onClick,\n onClickCapture,\n onKeyDown,\n onMouseDownCapture,\n onPointerDownCapture,\n registerRow: registry.registerRow,\n }),\n [\n onClick,\n onClickCapture,\n onKeyDown,\n onMouseDownCapture,\n onPointerDownCapture,\n registry,\n ],\n )\n}\n",
|
|
423
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-data-grid-cell-events.ts"
|
|
424
|
-
},
|
|
425
|
-
{
|
|
426
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-data-grid-cell-selection.ts",
|
|
427
|
-
"type": "registry:file",
|
|
428
|
-
"content": "import { useMemo, useState } from 'react'\nimport {\n addCellToSelection,\n type CellSelection,\n EMPTY_SELECTION,\n pruneSelection,\n selectSingleCell,\n} from '../lib/selection'\n\ninterface FocusedCell {\n columnId?: string\n rowId?: string\n}\n\ninterface UseDataGridCellSelectionOptions {\n coreRowsById: object\n availableColumnIds: ReadonlyMap<string, number>\n availableRowIds: ReadonlyMap<string, number>\n firstColumnId?: string\n firstRowId?: string\n visibleRowIds: ReadonlyMap<string, number>\n}\n\nexport function useDataGridCellSelection({\n coreRowsById,\n availableColumnIds,\n availableRowIds,\n firstColumnId,\n firstRowId,\n visibleRowIds,\n}: UseDataGridCellSelectionOptions) {\n const [focusedCell, setFocusedCell] = useState<FocusedCell>({\n columnId: firstColumnId,\n rowId: firstRowId,\n })\n const [hasInteracted, setHasInteracted] = useState(false)\n const [selectedCells, setSelectedCells] =\n useState<CellSelection>(EMPTY_SELECTION)\n\n const [seenCoreRows, setSeenCoreRows] = useState(coreRowsById)\n if (seenCoreRows !== coreRowsById) {\n setSeenCoreRows(coreRowsById)\n setSelectedCells((current) =>\n pruneSelection(\n current,\n (rowId) => rowId in coreRowsById,\n () => true,\n ),\n )\n }\n\n const focusedCellIsAvailable =\n focusedCell.rowId !== undefined &&\n focusedCell.columnId !== undefined &&\n visibleRowIds.has(focusedCell.rowId) &&\n availableColumnIds.has(focusedCell.columnId)\n const activeFocusedCell: FocusedCell = focusedCellIsAvailable\n ? focusedCell\n : { columnId: firstColumnId, rowId: firstRowId }\n\n const selection = useMemo(\n () =>\n pruneSelection(\n selectedCells,\n (rowId) => availableRowIds.has(rowId),\n (columnId) => availableColumnIds.has(columnId),\n ),\n [availableColumnIds, availableRowIds, selectedCells],\n )\n\n function selectCell(rowId: string, columnId: string, extend = false) {\n setHasInteracted(true)\n setFocusedCell({ columnId, rowId })\n setSelectedCells((current) =>\n extend\n ? addCellToSelection(\n pruneSelection(\n current,\n (id) => availableRowIds.has(id),\n (id) => availableColumnIds.has(id),\n ),\n rowId,\n columnId,\n )\n : selectSingleCell(rowId, columnId),\n )\n }\n\n return {\n focusedColumnId: activeFocusedCell.columnId,\n focusedRowId: activeFocusedCell.rowId,\n hasInteracted,\n selectCell,\n selection,\n }\n}\n",
|
|
429
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-data-grid-cell-selection.ts"
|
|
430
|
-
},
|
|
431
|
-
{
|
|
432
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-data-grid-drag-scroll.ts",
|
|
433
|
-
"type": "registry:file",
|
|
434
|
-
"content": "import { type MouseEvent, type PointerEvent, useRef, useState } from 'react'\nimport {\n DRAG_CLICK_SUPPRESSION_MS,\n DRAG_SCROLL_THRESHOLD_PX,\n} from '../lib/constants'\nimport { isDragScrollExcludedTarget } from '../lib/dom'\n\ninterface DragScrollGesture {\n dragging: boolean\n pointerId: number\n startScrollLeft: number\n startX: number\n startY: number\n}\n\ninterface SuppressedDragClick {\n until: number\n x: number\n y: number\n}\n\nexport function useDataGridDragScroll() {\n const [isDragScrolling, setIsDragScrolling] = useState(false)\n const gestureRef = useRef<DragScrollGesture | null>(null)\n const suppressedClickRef = useRef<SuppressedDragClick | null>(null)\n\n function resetGesture(grid?: HTMLDivElement) {\n const gesture = gestureRef.current\n if (grid && gesture && grid.hasPointerCapture?.(gesture.pointerId)) {\n grid.releasePointerCapture(gesture.pointerId)\n }\n gestureRef.current = null\n setIsDragScrolling(false)\n }\n\n function onPointerDownCapture(event: PointerEvent<HTMLDivElement>) {\n if (\n event.button !== 0 ||\n event.pointerType === 'touch' ||\n isDragScrollExcludedTarget(event.target)\n ) {\n return\n }\n\n const grid = event.currentTarget\n if (grid.scrollWidth <= grid.clientWidth) return\n\n gestureRef.current = {\n dragging: false,\n pointerId: event.pointerId,\n startScrollLeft: grid.scrollLeft,\n startX: event.clientX,\n startY: event.clientY,\n }\n }\n\n function onPointerMove(event: PointerEvent<HTMLDivElement>) {\n const gesture = gestureRef.current\n if (!gesture || gesture.pointerId !== event.pointerId) return\n\n const deltaX = event.clientX - gesture.startX\n const deltaY = event.clientY - gesture.startY\n const horizontalMovement = Math.abs(deltaX)\n\n if (!gesture.dragging) {\n if (\n horizontalMovement < DRAG_SCROLL_THRESHOLD_PX ||\n horizontalMovement <= Math.abs(deltaY)\n ) {\n return\n }\n event.currentTarget.setPointerCapture?.(event.pointerId)\n gesture.dragging = true\n setIsDragScrolling(true)\n }\n\n event.preventDefault()\n event.currentTarget.scrollLeft = Math.max(\n 0,\n Math.min(\n event.currentTarget.scrollWidth - event.currentTarget.clientWidth,\n gesture.startScrollLeft - deltaX,\n ),\n )\n }\n\n function onPointerEnd(event: PointerEvent<HTMLDivElement>) {\n const gesture = gestureRef.current\n if (!gesture || gesture.pointerId !== event.pointerId) return\n if (gesture.dragging) {\n suppressedClickRef.current = {\n until: performance.now() + DRAG_CLICK_SUPPRESSION_MS,\n x: event.clientX,\n y: event.clientY,\n }\n }\n resetGesture(event.currentTarget)\n }\n\n function onClickCapture(event: MouseEvent<HTMLDivElement>) {\n const suppressed = suppressedClickRef.current\n if (!suppressed) return\n\n suppressedClickRef.current = null\n const isExpired = performance.now() > suppressed.until\n const isReleaseClick =\n Math.abs(event.clientX - suppressed.x) <= DRAG_SCROLL_THRESHOLD_PX &&\n Math.abs(event.clientY - suppressed.y) <= DRAG_SCROLL_THRESHOLD_PX\n if (isExpired || !isReleaseClick) return\n\n event.preventDefault()\n event.stopPropagation()\n }\n\n return {\n isDragScrolling,\n onClickCapture,\n onLostPointerCapture: onPointerEnd,\n onPointerCancel: onPointerEnd,\n onPointerDownCapture,\n onPointerMove,\n onPointerUp: onPointerEnd,\n }\n}\n",
|
|
435
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-data-grid-drag-scroll.ts"
|
|
436
|
-
},
|
|
437
|
-
{
|
|
438
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-data-grid-focus.ts",
|
|
439
|
-
"type": "registry:file",
|
|
440
|
-
"content": "import { useCallback, useLayoutEffect, useState } from 'react'\nimport { createCellRegistry } from '../lib/cell-registry'\nimport { shouldPullFocus } from '../lib/dom'\n\ninterface UseDataGridFocusOptions {\n focusedColumnId?: string\n focusedRowId?: string\n hasInteracted: boolean\n}\n\nexport function useDataGridFocus({\n focusedColumnId,\n focusedRowId,\n hasInteracted,\n}: UseDataGridFocusOptions) {\n const [registry] = useState(createCellRegistry)\n\n useLayoutEffect(() => {\n if (!(hasInteracted && focusedRowId && focusedColumnId)) return\n const node = registry.get(focusedRowId, focusedColumnId)\n if (!node || node.contains(document.activeElement)) return\n queueMicrotask(() => {\n if (shouldPullFocus(node)) node.focus()\n })\n })\n\n const focusCell = useCallback(\n (rowId: string, columnId: string) => {\n queueMicrotask(() => registry.get(rowId, columnId)?.focus())\n },\n [registry],\n )\n\n return { focusCell, registry }\n}\n",
|
|
441
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-data-grid-focus.ts"
|
|
442
|
-
},
|
|
443
|
-
{
|
|
444
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-data-grid-row-context.ts",
|
|
445
|
-
"type": "registry:file",
|
|
446
|
-
"content": "import { createContext, useContext } from 'react'\nimport type { ColumnLayouts } from '../lib/column-layout'\nimport type { DataGridTableMeta } from '../lib/data-grid-features'\nimport type { DataGridDensity } from '../types'\nimport type { CellInteractions } from './use-data-grid-cell-events'\n\nexport type DataGridRowSelectionOption =\n | boolean\n | ((row: never) => boolean)\n | undefined\n\nexport interface DataGridRowContextValue {\n columnLayouts: ColumnLayouts\n columns: readonly { readonly id: string }[]\n enableRowSelection: DataGridRowSelectionOption\n meta: DataGridTableMeta | undefined\n density: DataGridDensity\n interactions: CellInteractions\n rowSelectable: boolean\n}\n\nexport const DataGridRowContext = createContext<DataGridRowContextValue | null>(\n null,\n)\n\nexport function useDataGridRowContext() {\n const value = useContext(DataGridRowContext)\n if (!value) throw new Error('DataGridRow must render inside DataGrid')\n return value\n}\n",
|
|
447
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-data-grid-row-context.ts"
|
|
448
|
-
},
|
|
449
|
-
{
|
|
450
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-data-grid-rows.ts",
|
|
451
|
-
"type": "registry:file",
|
|
452
|
-
"content": "import type { RowData } from '@tanstack/react-table'\nimport { useMemo } from 'react'\nimport { buildBodyEntries } from '../lib/body-entries'\nimport type { DataGridTable } from '../lib/data-grid-features'\nimport {\n computeGroupRuns,\n countGroupRows,\n EMPTY_GROUP_RUNS,\n mapRowGroups,\n} from '../lib/group-runs'\nimport { indexRowPositions } from '../lib/row-index'\n\ninterface UseDataGridRowsOptions<TData extends RowData> {\n collapsedGroupIds: readonly string[]\n getRowGroup?: (row: TData) => string | null\n table: DataGridTable<TData>\n}\n\nconst NO_GROUPS: ReadonlyMap<string, string | null> = new Map()\nconst NO_COUNTS: ReadonlyMap<string, number> = new Map()\n\nexport function useDataGridRows<TData extends RowData>({\n collapsedGroupIds,\n getRowGroup,\n table,\n}: UseDataGridRowsOptions<TData>) {\n const pageRows = table.getRowModel().rows\n const collectionRows = table.getSortedRowModel().rows\n const headerRowCount = table.getHeaderGroups().length\n const paginationRowOffset =\n table.options.meta?.dataGridPaginationRowOffset ?? 0\n\n const positions = useMemo(\n () => indexRowPositions(collectionRows),\n [collectionRows],\n )\n const groupByRowId = useMemo(\n () =>\n getRowGroup\n ? mapRowGroups(collectionRows, pageRows, getRowGroup)\n : NO_GROUPS,\n [collectionRows, getRowGroup, pageRows],\n )\n const groupRuns = useMemo(\n () =>\n getRowGroup\n ? computeGroupRuns(collectionRows, groupByRowId)\n : EMPTY_GROUP_RUNS,\n [collectionRows, getRowGroup, groupByRowId],\n )\n const groupCounts = useMemo(\n () => (getRowGroup ? countGroupRows(pageRows, groupByRowId) : NO_COUNTS),\n [getRowGroup, groupByRowId, pageRows],\n )\n const collapsedGroups = useMemo(\n () => new Set(collapsedGroupIds),\n [collapsedGroupIds],\n )\n const rows = useMemo(\n () =>\n getRowGroup\n ? pageRows.filter((row) => {\n const group = groupByRowId.get(row.id)\n return !(group && collapsedGroups.has(group))\n })\n : pageRows,\n [collapsedGroups, getRowGroup, groupByRowId, pageRows],\n )\n const rowIndexById = useMemo(() => indexRowPositions(rows), [rows])\n const entries = useMemo(\n () =>\n buildBodyEntries({\n collapsedGroups,\n groupByRowId,\n groupCounts,\n groupRuns,\n headerRowCount,\n pageRows,\n paginationRowOffset,\n positions,\n }),\n [\n collapsedGroups,\n groupByRowId,\n groupCounts,\n groupRuns,\n headerRowCount,\n pageRows,\n paginationRowOffset,\n positions,\n ],\n )\n\n return {\n collectionRowCount: table.getRowCount(),\n collectionRows,\n entries,\n groupRowCount: groupRuns.groupRowCount,\n headerRowCount,\n pageRows,\n positions,\n rowIndexById,\n rows,\n }\n}\n",
|
|
453
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-data-grid-rows.ts"
|
|
454
|
-
},
|
|
455
|
-
{
|
|
456
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-data-grid-virtualizer.ts",
|
|
457
|
-
"type": "registry:file",
|
|
458
|
-
"content": "import type { Row, RowData } from '@tanstack/react-table'\nimport { observeElementRect, useVirtualizer } from '@tanstack/react-virtual'\nimport type { RefObject } from 'react'\nimport {\n BOTTOM_BAR_HEIGHT_PX,\n DEFAULT_MAX_HEIGHT_PX,\n FALLBACK_HEADER_HEIGHT_PX,\n HEADER_SELECTOR,\n ROW_HEIGHT,\n} from '../lib/constants'\nimport type { DataGridFeatures, DataGridTable } from '../lib/data-grid-features'\nimport { resolveVirtualScrollTop } from '../lib/virtual-scroll'\nimport type { DataGridDensity } from '../types'\n\ninterface UseDataGridVirtualizerOptions<TData extends RowData> {\n density: DataGridDensity\n enabled: boolean\n gridRef: RefObject<HTMLDivElement | null>\n hasBottomBar: boolean\n maxHeight?: number | string\n overscan: number\n rows: readonly Row<DataGridFeatures, TData>[]\n table: DataGridTable<TData>\n}\n\nexport function useDataGridVirtualizer<TData extends RowData>({\n density,\n enabled,\n gridRef,\n hasBottomBar,\n maxHeight,\n overscan,\n rows,\n table,\n}: UseDataGridVirtualizerOptions<TData>) {\n const fallbackHeight =\n typeof maxHeight === 'number' ? maxHeight : DEFAULT_MAX_HEIGHT_PX\n const rowVirtualizer = useVirtualizer({\n count: enabled ? rows.length : 0,\n estimateSize: () => ROW_HEIGHT[density],\n getItemKey: (index) => rows[index]?.id ?? index,\n getScrollElement: () => gridRef.current,\n initialRect:\n typeof maxHeight === 'number'\n ? { height: maxHeight, width: table.getTotalSize() }\n : undefined,\n observeElementRect: (instance, callback) =>\n observeElementRect(instance, (rect) =>\n callback({\n height: rect.height || fallbackHeight,\n width: rect.width || table.getTotalSize(),\n }),\n ),\n overscan,\n useFlushSync: false,\n })\n\n function scrollRowIntoView(rowIndex: number) {\n const grid = gridRef.current\n if (!grid) return\n const top = resolveVirtualScrollTop({\n bottomHeight: hasBottomBar ? BOTTOM_BAR_HEIGHT_PX : 0,\n headerHeight:\n grid.querySelector<HTMLElement>(HEADER_SELECTOR)?.clientHeight ||\n FALLBACK_HEADER_HEIGHT_PX,\n rowHeight: ROW_HEIGHT[density],\n rowIndex,\n scrollTop: grid.scrollTop,\n viewportHeight: grid.clientHeight || fallbackHeight,\n })\n if (top !== undefined) grid.scrollTo({ behavior: 'auto', top })\n }\n\n return {\n scrollRowIntoView,\n totalSize: rowVirtualizer.getTotalSize(),\n virtualItems: rowVirtualizer.getVirtualItems(),\n }\n}\n",
|
|
459
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-data-grid-virtualizer.ts"
|
|
460
|
-
},
|
|
461
|
-
{
|
|
462
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-data-grid.ts",
|
|
463
|
-
"type": "registry:file",
|
|
464
|
-
"content": "'use client'\n\nimport {\n type ColumnFiltersState,\n type ColumnOrderState,\n type ColumnPinningState,\n type ColumnSizingState,\n type ColumnVisibilityState,\n type PaginationState,\n type ReactTable,\n type RowData,\n type RowSelectionState,\n type SortingState,\n type TableOptions,\n useTable,\n} from '@tanstack/react-table'\nimport { createElement, useMemo, useState } from 'react'\nimport { DataGridCell } from '../components/data-grid-cell'\nimport {\n type DataGridColumnDef,\n type DataGridFeatures,\n type DataGridTableMeta,\n dataGridFeatures,\n} from '../lib/data-grid-features'\nimport type { DataGridCellValueChange, DataGridDensity } from '../types'\nimport { useLatestCallback } from './use-latest-callback'\n\nexport interface UseDataGridOptions<TData extends RowData> {\n data: TData[]\n columns: DataGridColumnDef<TData>[]\n getRowId?: (row: TData, index: number) => string\n enableSorting?: boolean\n enableRowSelection?: boolean\n enableColumnResizing?: boolean\n enableColumnFilters?: boolean\n enablePagination?: boolean\n pageSize?: number\n density?: DataGridDensity\n onCellValueChange?: (change: DataGridCellValueChange) => void\n tableOptions?: Partial<TableOptions<DataGridFeatures, TData>>\n}\n\nexport interface UseDataGridReturn<TData extends RowData> {\n table: ReactTable<DataGridFeatures, TData>\n}\n\nexport function useDataGrid<TData extends RowData>({\n data,\n columns,\n getRowId,\n enableSorting = true,\n enableRowSelection = false,\n enableColumnResizing = true,\n enableColumnFilters = true,\n enablePagination = false,\n pageSize = 10,\n density: densityProp = 'short',\n onCellValueChange,\n tableOptions,\n}: UseDataGridOptions<TData>): UseDataGridReturn<TData> {\n const initialState = tableOptions?.initialState\n const [sorting, setSorting] = useState<SortingState>(\n () => initialState?.sorting ?? [],\n )\n const [globalFilter, setGlobalFilter] = useState(\n () => initialState?.globalFilter ?? '',\n )\n const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>(\n () => initialState?.columnFilters ?? [],\n )\n const [columnVisibility, setColumnVisibility] =\n useState<ColumnVisibilityState>(() => initialState?.columnVisibility ?? {})\n const [columnOrder, setColumnOrder] = useState<ColumnOrderState>(\n () => initialState?.columnOrder ?? [],\n )\n const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(\n () => initialState?.columnPinning ?? { end: [], start: [] },\n )\n const [columnSizing, setColumnSizing] = useState<ColumnSizingState>(\n () => initialState?.columnSizing ?? {},\n )\n const [rowSelection, setRowSelection] = useState<RowSelectionState>(\n () => initialState?.rowSelection ?? {},\n )\n const [pagination, setPagination] = useState<PaginationState>({\n pageIndex: initialState?.pagination?.pageIndex ?? 0,\n pageSize: initialState?.pagination?.pageSize ?? pageSize,\n })\n const [density, setDensity] = useState<DataGridDensity>(densityProp)\n\n const defaultColumn = useMemo<Partial<DataGridColumnDef<TData>>>(\n () => ({\n cell: (context) => createElement(DataGridCell<TData>, { context }),\n minSize: 80,\n }),\n [],\n )\n\n const consumerMeta = tableOptions?.meta\n const fallbackCellValueChange = consumerMeta?.onDataGridCellValueChange\n const hasCellValueChange = Boolean(\n onCellValueChange ?? fallbackCellValueChange,\n )\n const handleCellValueChange = useLatestCallback(\n (change: DataGridCellValueChange) =>\n (onCellValueChange ?? fallbackCellValueChange)?.(change),\n )\n const paginationRowOffset = enablePagination\n ? pagination.pageIndex * pagination.pageSize\n : 0\n const meta = useMemo<DataGridTableMeta>(\n () => ({\n ...consumerMeta,\n dataGridDensity: density,\n dataGridPaginationRowOffset: paginationRowOffset,\n onDataGridCellValueChange: hasCellValueChange\n ? handleCellValueChange\n : undefined,\n onDataGridDensityChange: setDensity,\n }),\n [\n consumerMeta,\n density,\n handleCellValueChange,\n hasCellValueChange,\n paginationRowOffset,\n ],\n )\n\n const table = useTable<DataGridFeatures, TData>({\n features: dataGridFeatures,\n data,\n columns,\n defaultColumn,\n getRowId,\n state: {\n sorting,\n globalFilter,\n columnFilters,\n columnVisibility,\n columnOrder,\n columnPinning,\n columnSizing,\n rowSelection,\n ...(enablePagination ? { pagination } : {}),\n },\n enableSorting,\n enableRowSelection,\n enableColumnResizing,\n enableColumnFilters,\n columnResizeMode: 'onChange',\n globalFilterFn: 'includesString',\n onSortingChange: setSorting,\n onGlobalFilterChange: setGlobalFilter,\n onColumnFiltersChange: setColumnFilters,\n onColumnVisibilityChange: setColumnVisibility,\n onColumnOrderChange: setColumnOrder,\n onColumnPinningChange: setColumnPinning,\n onColumnSizingChange: setColumnSizing,\n onRowSelectionChange: setRowSelection,\n onPaginationChange: setPagination,\n manualPagination: !enablePagination,\n ...tableOptions,\n meta,\n })\n\n return { table }\n}\n",
|
|
465
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-data-grid.ts"
|
|
466
|
-
},
|
|
467
|
-
{
|
|
468
|
-
"path": "parttens/src/collection-views/views/data-grid/hooks/use-latest-callback.ts",
|
|
469
|
-
"type": "registry:file",
|
|
470
|
-
"content": "import { useCallback, useLayoutEffect, useRef } from 'react'\n\nexport function useLatestCallback<Args extends unknown[], Result>(\n callback: (...args: Args) => Result,\n) {\n const ref = useRef(callback)\n useLayoutEffect(() => {\n ref.current = callback\n })\n return useCallback((...args: Args) => ref.current(...args), [])\n}\n",
|
|
471
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/hooks/use-latest-callback.ts"
|
|
472
|
-
},
|
|
473
|
-
{
|
|
474
|
-
"path": "parttens/src/collection-views/views/data-grid/index.ts",
|
|
475
|
-
"type": "registry:file",
|
|
476
|
-
"content": "export type { DataGridProps } from './components/data-grid'\nexport { DataGrid } from './components/data-grid'\nexport { DataGridCell } from './components/data-grid-cell'\nexport {\n DATA_GRID_COLUMN_TYPE_ICONS,\n DataGridColumnTypeIcon,\n} from './components/data-grid-column-type-icon'\nexport type { DataGridColumnsSubmenuProps } from './components/data-grid-columns-submenu'\nexport { DataGridColumnsSubmenu } from './components/data-grid-columns-submenu'\nexport type { DataGridDensitySubmenuProps } from './components/data-grid-density-submenu'\nexport { DataGridDensitySubmenu } from './components/data-grid-density-submenu'\nexport type { DataGridFilterMenuProps } from './components/data-grid-filter-menu'\nexport { DataGridFilterMenu } from './components/data-grid-filter-menu'\nexport type {\n DataGridPaginationProps,\n PaginatedTable,\n} from './components/data-grid-pagination'\nexport { DataGridPagination } from './components/data-grid-pagination'\nexport type { DataGridSearchProps } from './components/data-grid-search'\nexport { DataGridSearch } from './components/data-grid-search'\nexport type { DataGridSelectionSummaryProps } from './components/data-grid-selection-summary'\nexport { DataGridSelectionSummary } from './components/data-grid-selection-summary'\nexport type { DataGridSortSubmenuProps } from './components/data-grid-sort-submenu'\nexport { DataGridSortSubmenu } from './components/data-grid-sort-submenu'\nexport type {\n UseDataGridOptions,\n UseDataGridReturn,\n} from './hooks/use-data-grid'\nexport { useDataGrid } from './hooks/use-data-grid'\nexport { createSelectColumn } from './lib/create-select-column'\nexport type {\n DataGridColumn,\n DataGridColumnDef,\n DataGridFeatures,\n DataGridHeader,\n DataGridTable,\n DataGridTableMeta,\n} from './lib/data-grid-features'\nexport { dataGridFeatures } from './lib/data-grid-features'\nexport type {\n DataGridAlign,\n DataGridCellValueChange,\n DataGridCellVariant,\n DataGridColumnMeta,\n DataGridColumnType,\n DataGridDensity,\n DataGridSelectOption,\n} from './types'\nexport { DATA_GRID_COLUMN_TYPES } from './types'\n",
|
|
477
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/index.ts"
|
|
478
|
-
},
|
|
479
|
-
{
|
|
480
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/body-entries.ts",
|
|
481
|
-
"type": "registry:file",
|
|
482
|
-
"content": "import type { Row, RowData } from '@tanstack/react-table'\nimport type { DataGridFeatures } from './data-grid-features'\nimport type { GroupRuns } from './group-runs'\nimport { resolveCollectionRowIndex } from './row-index'\n\ntype GridRow<TData extends RowData> = Row<DataGridFeatures, TData>\n\nexport interface GroupBodyEntry {\n ariaRowIndex: number\n collapsed: boolean\n count: number\n group: string\n key: string\n kind: 'group'\n}\n\nexport interface RowBodyEntry<TData extends RowData> {\n ariaRowIndex: number\n key: string\n kind: 'row'\n row: GridRow<TData>\n}\n\nexport type BodyEntry<TData extends RowData> =\n | GroupBodyEntry\n | RowBodyEntry<TData>\n\ninterface BodyEntriesInput<TData extends RowData> {\n collapsedGroups: ReadonlySet<string>\n groupByRowId: ReadonlyMap<string, string | null>\n groupCounts: ReadonlyMap<string, number>\n groupRuns: GroupRuns\n headerRowCount: number\n pageRows: readonly GridRow<TData>[]\n paginationRowOffset: number\n positions: ReadonlyMap<string, number>\n}\n\nexport function buildBodyEntries<TData extends RowData>({\n collapsedGroups,\n groupByRowId,\n groupCounts,\n groupRuns,\n headerRowCount,\n pageRows,\n paginationRowOffset,\n positions,\n}: BodyEntriesInput<TData>): BodyEntry<TData>[] {\n const entries: BodyEntry<TData>[] = []\n pageRows.forEach((row, rowIndex) => {\n const group = groupByRowId.get(row.id) ?? null\n const collectionIndex = resolveCollectionRowIndex({\n fallbackIndex: rowIndex,\n paginationRowOffset,\n positions,\n row,\n })\n const runPosition = positions.get(row.id) ?? -1\n const groupRunsBefore = groupRuns.runsThrough[runPosition] ?? 0\n const collapsed = group !== null && collapsedGroups.has(group)\n const startsGroup = Boolean(\n group && (groupRuns.runStarts[runPosition] || rowIndex === 0),\n )\n\n if (startsGroup && group) {\n entries.push({\n ariaRowIndex: headerRowCount + collectionIndex + groupRunsBefore,\n collapsed,\n count: groupCounts.get(group) ?? 0,\n group,\n key: `group-${group}-${row.id}`,\n kind: 'group',\n })\n }\n if (!collapsed) {\n entries.push({\n ariaRowIndex: headerRowCount + collectionIndex + groupRunsBefore + 1,\n key: row.id,\n kind: 'row',\n row,\n })\n }\n })\n return entries\n}\n",
|
|
483
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/body-entries.ts"
|
|
484
|
-
},
|
|
485
|
-
{
|
|
486
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/cell-registry.ts",
|
|
487
|
-
"type": "registry:file",
|
|
488
|
-
"content": "export interface CellIdentity {\n columnId: string\n rowId: string\n}\n\nexport interface CellRegistry {\n get: (rowId: string, columnId: string) => HTMLElement | undefined\n identify: (cell: HTMLElement) => CellIdentity | undefined\n registerRow: (rowId: string, node: HTMLElement | null) => void\n}\n\nexport function createCellRegistry(): CellRegistry {\n const rows = new Map<string, HTMLElement>()\n const rowIds = new Map<Element, string>()\n\n return {\n get: (rowId, columnId) => {\n const row = rows.get(rowId)\n if (!row) return undefined\n for (const child of Array.from(row.children)) {\n if (\n child instanceof HTMLElement &&\n child.dataset.columnId === columnId\n ) {\n return child\n }\n }\n return undefined\n },\n identify: (cell) => {\n const rowElement = cell.parentElement\n const rowId = rowElement ? rowIds.get(rowElement) : undefined\n const columnId = cell.dataset.columnId\n return rowId === undefined || columnId === undefined\n ? undefined\n : { columnId, rowId }\n },\n registerRow: (rowId, node) => {\n if (node) {\n rows.set(rowId, node)\n rowIds.set(node, rowId)\n return\n }\n const current = rows.get(rowId)\n if (current) rowIds.delete(current)\n rows.delete(rowId)\n },\n }\n}\n",
|
|
489
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/cell-registry.ts"
|
|
490
|
-
},
|
|
491
|
-
{
|
|
492
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/column-layout.ts",
|
|
493
|
-
"type": "registry:file",
|
|
494
|
-
"content": "import type { RowData } from '@tanstack/react-table'\nimport type { CSSProperties } from 'react'\nimport type { DataGridColumn } from './data-grid-features'\n\nexport interface ColumnLayout {\n pinned: false | 'start' | 'end'\n style: CSSProperties\n}\n\nexport type ColumnLayouts = ReadonlyMap<string, ColumnLayout>\n\nfunction columnStyle(size: number, fill: boolean): CSSProperties {\n return {\n flex: `${fill ? 1 : 0} 0 ${size}px`,\n minWidth: size,\n width: size,\n }\n}\n\nfunction pinnedColumnStyle<TData extends RowData>(\n column: DataGridColumn<TData>,\n pinned: ColumnLayout['pinned'],\n fillColumnId?: string,\n): CSSProperties {\n const base = columnStyle(\n column.getSize(),\n !pinned && column.id === fillColumnId,\n )\n if (pinned === 'start') {\n return {\n ...base,\n insetInlineStart: column.getStart('start'),\n position: 'sticky',\n zIndex: 5,\n }\n }\n if (pinned === 'end') {\n return {\n ...base,\n insetInlineEnd: column.getAfter('end'),\n position: 'sticky',\n zIndex: 5,\n }\n }\n return base\n}\n\nfunction sameStyle(a: CSSProperties, b: CSSProperties) {\n const keys = Object.keys(a) as (keyof CSSProperties)[]\n return (\n keys.length === Object.keys(b).length &&\n keys.every((key) => a[key] === b[key])\n )\n}\n\nexport function resolveColumnLayout<TData extends RowData>(\n column: DataGridColumn<TData>,\n fillColumnId?: string,\n): ColumnLayout {\n const pinned = column.getIsPinned()\n return { pinned, style: pinnedColumnStyle(column, pinned, fillColumnId) }\n}\n\nexport function buildColumnLayouts<TData extends RowData>(\n columns: readonly DataGridColumn<TData>[],\n fillColumnId?: string,\n previous?: ColumnLayouts,\n): ColumnLayouts {\n const layouts = new Map<string, ColumnLayout>()\n for (const column of columns) {\n const pinned = column.getIsPinned()\n const style = pinnedColumnStyle(column, pinned, fillColumnId)\n const before = previous?.get(column.id)\n layouts.set(\n column.id,\n before && before.pinned === pinned && sameStyle(before.style, style)\n ? before\n : { pinned, style },\n )\n }\n if (previous && previous.size === layouts.size) {\n const before = [...previous]\n const unchanged = [...layouts].every(\n ([id, layout], index) =>\n before[index]?.[0] === id && before[index]?.[1] === layout,\n )\n if (unchanged) return previous\n }\n return layouts\n}\n",
|
|
495
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/column-layout.ts"
|
|
496
|
-
},
|
|
497
|
-
{
|
|
498
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/columns.ts",
|
|
499
|
-
"type": "registry:file",
|
|
500
|
-
"content": "import type { RowData } from '@tanstack/react-table'\nimport { NON_NAVIGABLE_COLUMN_IDS } from './constants'\nimport type { DataGridColumn } from './data-grid-features'\n\nexport function isNavigableColumnId(columnId: string) {\n return !NON_NAVIGABLE_COLUMN_IDS.includes(columnId)\n}\n\nexport function findFirstNavigableColumnIndex<TData extends RowData>(\n columns: readonly DataGridColumn<TData>[],\n) {\n return Math.max(\n 0,\n columns.findIndex((column) => isNavigableColumnId(column.id)),\n )\n}\n\nexport function resolveFillColumnId<TData extends RowData>(\n columns: readonly DataGridColumn<TData>[],\n fillColumn: string | false | undefined,\n) {\n if (fillColumn === false) return undefined\n if (fillColumn !== undefined) return fillColumn\n for (let index = columns.length - 1; index >= 0; index -= 1) {\n const column = columns[index]\n if (column && !column.getIsPinned() && isNavigableColumnId(column.id)) {\n return column.id\n }\n }\n return undefined\n}\n\nexport function indexColumns<TData extends RowData>(\n columns: readonly DataGridColumn<TData>[],\n) {\n const indexes = new Map<string, number>()\n columns.forEach((column, index) => {\n indexes.set(column.id, index)\n })\n return indexes\n}\n",
|
|
501
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/columns.ts"
|
|
502
|
-
},
|
|
503
|
-
{
|
|
504
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/constants.ts",
|
|
505
|
-
"type": "registry:file",
|
|
506
|
-
"content": "import type { DataGridAlign, DataGridDensity } from '../types'\n\nexport const HEADER_ALIGN: Record<DataGridAlign, string> = {\n center: 'justify-center',\n end: 'justify-end',\n start: 'justify-start',\n}\n\nexport const CELL_ALIGN: Record<DataGridAlign, string> = {\n center: 'text-center justify-center',\n end: 'text-end justify-end',\n start: 'text-start justify-start',\n}\n\nexport const ROW_DENSITY: Record<DataGridDensity, string> = {\n 'extra-tall': 'min-h-18',\n medium: 'min-h-11',\n short: 'min-h-9',\n tall: 'min-h-14',\n}\n\nexport const CELL_DENSITY: Record<DataGridDensity, string> = {\n 'extra-tall': 'px-3 py-4',\n medium: 'px-2.5 py-2',\n short: 'px-2 py-1.5',\n tall: 'px-3 py-3',\n}\n\nexport const ROW_HEIGHT: Record<DataGridDensity, number> = {\n 'extra-tall': 72,\n medium: 44,\n short: 36,\n tall: 56,\n}\n\nexport const DEFAULT_MAX_HEIGHT_PX = 600\nexport const FALLBACK_HEADER_HEIGHT_PX = 36\nexport const BOTTOM_BAR_HEIGHT_PX = 36\n\nexport const DRAG_SCROLL_THRESHOLD_PX = 8\nexport const DRAG_CLICK_SUPPRESSION_MS = 500\nexport const PENDING_SELECT_CLICK_WINDOW_MS = 750\nexport const DRAG_SCROLL_EXCLUDED_TARGETS = [\n 'a',\n 'button',\n 'input',\n 'select',\n 'textarea',\n '[contenteditable=\"true\"]',\n '[data-grid-select-trigger]',\n '[role=\"button\"]',\n '[role=\"checkbox\"]',\n '[role=\"combobox\"]',\n '[role=\"columnheader\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"option\"]',\n '[role=\"separator\"]',\n].join(',')\n\nexport const SELECT_TRIGGER_SELECTOR = '[data-grid-select-trigger]'\nexport const CELL_SELECTOR = '[data-slot=\"data-grid-cell\"]'\nexport const HEADER_SELECTOR = '[data-slot=\"data-grid-header\"]'\n\nexport const RESIZE_STEP_PX = 8\nexport const DEFAULT_MIN_COLUMN_SIZE = 20\nexport const DEFAULT_MAX_COLUMN_SIZE = Number.MAX_SAFE_INTEGER\n\nexport const NON_NAVIGABLE_COLUMN_IDS: readonly string[] = ['select', 'actions']\n",
|
|
507
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/constants.ts"
|
|
508
|
-
},
|
|
509
|
-
{
|
|
510
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/create-select-column.tsx",
|
|
511
|
-
"type": "registry:file",
|
|
512
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { Checkbox } from '@tc96/ui/checkbox'\nimport type { DataGridColumnDef } from './data-grid-features'\n\nexport function createSelectColumn<TData extends RowData>(\n options: { showRowNumbers?: boolean; size?: number } = {},\n): DataGridColumnDef<TData> {\n const showRowNumbers = options.showRowNumbers ?? true\n\n return {\n id: 'select',\n meta: { align: 'center' },\n size: options.size ?? 44,\n enableSorting: false,\n enableHiding: false,\n enablePinning: false,\n enableResizing: false,\n header: ({ table }) => (\n <div className=\"flex items-center justify-center\">\n <Checkbox\n aria-label=\"Selecionar todos os registros\"\n checked={table.getIsAllPageRowsSelected()}\n indeterminate={\n table.getIsSomePageRowsSelected() &&\n !table.getIsAllPageRowsSelected()\n }\n onCheckedChange={(checked) =>\n table.toggleAllPageRowsSelected(Boolean(checked))\n }\n />\n </div>\n ),\n cell: ({ row }) => (\n <div className=\"group/marker relative flex size-full items-center justify-center\">\n {showRowNumbers ? (\n <span\n aria-hidden=\"true\"\n className=\"pointer-coarse:opacity-0 text-muted-foreground text-xs tabular-nums group-hover/marker:opacity-0 group-focus-within/marker:opacity-0 group-data-[state=selected]:opacity-0\"\n data-slot=\"data-grid-row-marker\"\n >\n {row.index + 1}\n </span>\n ) : null}\n <Checkbox\n aria-label=\"Selecionar registro\"\n checked={row.getIsSelected()}\n className={\n showRowNumbers\n ? 'pointer-coarse:opacity-100 absolute opacity-0 group-hover/marker:opacity-100 group-focus-within/marker:opacity-100 data-checked:opacity-100'\n : undefined\n }\n disabled={!row.getCanSelect()}\n onCheckedChange={(checked) => row.toggleSelected(Boolean(checked))}\n />\n </div>\n ),\n }\n}\n",
|
|
513
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/create-select-column.tsx"
|
|
514
|
-
},
|
|
515
|
-
{
|
|
516
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/data-grid-features.ts",
|
|
517
|
-
"type": "registry:file",
|
|
518
|
-
"content": "import {\n type Column,\n type ColumnDef,\n columnFilteringFeature,\n columnOrderingFeature,\n columnPinningFeature,\n columnResizingFeature,\n columnSizingFeature,\n columnVisibilityFeature,\n createFilteredRowModel,\n createPaginatedRowModel,\n createSortedRowModel,\n filterFns,\n globalFilteringFeature,\n type Header,\n metaHelper,\n type RowData,\n rowPaginationFeature,\n rowSelectionFeature,\n rowSortingFeature,\n sortFns,\n type Table,\n tableFeatures,\n} from '@tanstack/react-table'\nimport type {\n DataGridCellValueChange,\n DataGridColumnMeta,\n DataGridDensity,\n} from '../types'\n\nexport interface DataGridTableMeta {\n dataGridDensity?: DataGridDensity\n dataGridPaginationRowOffset?: number\n onDataGridDensityChange?: (density: DataGridDensity) => void\n onDataGridCellValueChange?: (change: DataGridCellValueChange) => void\n}\n\nexport const dataGridFeatures = tableFeatures({\n columnFilteringFeature,\n globalFilteringFeature,\n rowSortingFeature,\n rowPaginationFeature,\n rowSelectionFeature,\n columnVisibilityFeature,\n columnOrderingFeature,\n columnPinningFeature,\n columnSizingFeature,\n columnResizingFeature,\n filteredRowModel: createFilteredRowModel(),\n sortedRowModel: createSortedRowModel(),\n paginatedRowModel: createPaginatedRowModel(),\n filterFns,\n sortFns,\n columnMeta: metaHelper<DataGridColumnMeta>(),\n tableMeta: metaHelper<DataGridTableMeta>(),\n})\n\nexport type DataGridFeatures = typeof dataGridFeatures\n\nexport type DataGridTable<TData extends RowData> = Table<\n DataGridFeatures,\n TData\n>\n\nexport type DataGridColumnDef<TData extends RowData> = ColumnDef<\n DataGridFeatures,\n TData,\n unknown\n>\n\nexport type DataGridColumn<TData extends RowData> = Column<\n DataGridFeatures,\n TData,\n unknown\n>\n\nexport type DataGridHeader<TData extends RowData> = Header<\n DataGridFeatures,\n TData,\n unknown\n>\n",
|
|
519
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/data-grid-features.ts"
|
|
520
|
-
},
|
|
521
|
-
{
|
|
522
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/dom.ts",
|
|
523
|
-
"type": "registry:file",
|
|
524
|
-
"content": "import {\n CELL_SELECTOR,\n DRAG_SCROLL_EXCLUDED_TARGETS,\n SELECT_TRIGGER_SELECTOR,\n} from './constants'\n\nexport function shouldPullFocus(cell: HTMLElement) {\n const active = document.activeElement\n if (!active || active === document.body) return true\n if (cell.contains(active)) return false\n return Boolean(active.closest(CELL_SELECTOR))\n}\n\nexport function isDragScrollExcludedTarget(target: EventTarget | null) {\n return (\n target instanceof Element &&\n Boolean(target.closest(DRAG_SCROLL_EXCLUDED_TARGETS))\n )\n}\n\nexport function hasSelectTrigger(cell: Element) {\n return Boolean(cell.querySelector(SELECT_TRIGGER_SELECTOR))\n}\n",
|
|
525
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/dom.ts"
|
|
526
|
-
},
|
|
527
|
-
{
|
|
528
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/format-value.ts",
|
|
529
|
-
"type": "registry:file",
|
|
530
|
-
"content": "import { isValidDate, parseDateValue } from '@tc96/helpers/date'\n\nlet dateFormatter: Intl.DateTimeFormat | undefined\n\nexport function toStringValue(value: unknown): string {\n if (value === null || value === undefined) return ''\n return String(value)\n}\n\nexport function formatDate(value: unknown): string {\n if (!value) return ''\n const date = parseDateValue(value)\n if (!isValidDate(date)) return toStringValue(value)\n dateFormatter ??= new Intl.DateTimeFormat()\n return dateFormatter.format(date)\n}\n",
|
|
531
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/format-value.ts"
|
|
532
|
-
},
|
|
533
|
-
{
|
|
534
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/group-runs.ts",
|
|
535
|
-
"type": "registry:file",
|
|
536
|
-
"content": "import type { Row, RowData } from '@tanstack/react-table'\nimport type { DataGridFeatures } from './data-grid-features'\n\ntype GridRow<TData extends RowData> = Row<DataGridFeatures, TData>\n\nexport interface GroupRuns {\n groupRowCount: number\n runStarts: boolean[]\n runsThrough: number[]\n}\n\nexport const EMPTY_GROUP_RUNS: GroupRuns = {\n groupRowCount: 0,\n runStarts: [],\n runsThrough: [],\n}\n\nexport function mapRowGroups<TData extends RowData>(\n collectionRows: readonly GridRow<TData>[],\n pageRows: readonly GridRow<TData>[],\n getRowGroup: (row: TData) => string | null,\n) {\n const groups = new Map<string, string | null>()\n for (const row of collectionRows) {\n groups.set(row.id, getRowGroup(row.original))\n }\n for (const row of pageRows) {\n if (!groups.has(row.id)) groups.set(row.id, getRowGroup(row.original))\n }\n return groups\n}\n\nexport function computeGroupRuns<TData extends RowData>(\n collectionRows: readonly GridRow<TData>[],\n groupByRowId: ReadonlyMap<string, string | null>,\n): GroupRuns {\n const runsThrough: number[] = []\n const runStarts: boolean[] = []\n let previousGroup: string | null = null\n let groupRowCount = 0\n for (const row of collectionRows) {\n const group = groupByRowId.get(row.id) ?? null\n const startsRun = Boolean(group && group !== previousGroup)\n if (group && startsRun) {\n groupRowCount += 1\n previousGroup = group\n }\n runsThrough.push(groupRowCount)\n runStarts.push(startsRun)\n }\n return { groupRowCount, runStarts, runsThrough }\n}\n\nexport function countGroupRows<TData extends RowData>(\n pageRows: readonly GridRow<TData>[],\n groupByRowId: ReadonlyMap<string, string | null>,\n) {\n const counts = new Map<string, number>()\n for (const row of pageRows) {\n const group = groupByRowId.get(row.id)\n if (group) counts.set(group, (counts.get(group) ?? 0) + 1)\n }\n return counts\n}\n",
|
|
537
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/group-runs.ts"
|
|
538
|
-
},
|
|
539
|
-
{
|
|
540
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/move-column.ts",
|
|
541
|
-
"type": "registry:file",
|
|
542
|
-
"content": "import type { RowData } from '@tanstack/react-table'\nimport type { DataGridTable } from './data-grid-features'\n\nexport function moveColumn<TData extends RowData>(\n table: DataGridTable<TData>,\n columnId: string,\n direction: -1 | 1,\n) {\n const leafIds = table.getAllLeafColumns().map((column) => column.id)\n const state = table.atoms.columnOrder.get()\n const order = state.length ? [...state] : leafIds\n const from = order.indexOf(columnId)\n const to = from + direction\n if (from === -1 || to < 0 || to >= order.length) return\n const [moved] = order.splice(from, 1)\n if (!moved) return\n order.splice(to, 0, moved)\n table.setColumnOrder(order)\n}\n",
|
|
543
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/move-column.ts"
|
|
544
|
-
},
|
|
545
|
-
{
|
|
546
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/resize.ts",
|
|
547
|
-
"type": "registry:file",
|
|
548
|
-
"content": "import type { RowData } from '@tanstack/react-table'\nimport {\n DEFAULT_MAX_COLUMN_SIZE,\n DEFAULT_MIN_COLUMN_SIZE,\n RESIZE_STEP_PX,\n} from './constants'\nimport type { DataGridColumn } from './data-grid-features'\n\nexport function resolveColumnSizeBounds<TData extends RowData>(\n column: DataGridColumn<TData>,\n) {\n return {\n max: column.columnDef.maxSize ?? DEFAULT_MAX_COLUMN_SIZE,\n min: column.columnDef.minSize ?? DEFAULT_MIN_COLUMN_SIZE,\n }\n}\n\nexport function resolveResizeKeySize<TData extends RowData>(\n column: DataGridColumn<TData>,\n key: string,\n) {\n const delta =\n key === 'ArrowLeft'\n ? -RESIZE_STEP_PX\n : key === 'ArrowRight'\n ? RESIZE_STEP_PX\n : 0\n if (!delta) return undefined\n const { max, min } = resolveColumnSizeBounds(column)\n return Math.min(max, Math.max(min, column.getSize() + delta))\n}\n",
|
|
549
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/resize.ts"
|
|
550
|
-
},
|
|
551
|
-
{
|
|
552
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/row-index.ts",
|
|
553
|
-
"type": "registry:file",
|
|
554
|
-
"content": "import type { Row, RowData } from '@tanstack/react-table'\nimport type { DataGridFeatures } from './data-grid-features'\n\nexport function indexRowPositions<TData extends RowData>(\n rows: readonly Row<DataGridFeatures, TData>[],\n) {\n const positions = new Map<string, number>()\n rows.forEach((row, position) => {\n positions.set(row.id, position)\n })\n return positions\n}\n\ninterface CollectionRowIndexInput<TData extends RowData> {\n fallbackIndex: number\n paginationRowOffset: number\n positions: ReadonlyMap<string, number>\n row: Row<DataGridFeatures, TData>\n}\n\nexport function resolveCollectionRowIndex<TData extends RowData>({\n fallbackIndex,\n paginationRowOffset,\n positions,\n row,\n}: CollectionRowIndexInput<TData>) {\n if (paginationRowOffset > 0) return paginationRowOffset + fallbackIndex\n return positions.get(row.id) ?? row.index ?? fallbackIndex\n}\n",
|
|
555
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/row-index.ts"
|
|
556
|
-
},
|
|
557
|
-
{
|
|
558
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/selection.ts",
|
|
559
|
-
"type": "registry:file",
|
|
560
|
-
"content": "export type CellSelection = ReadonlyMap<string, ReadonlySet<string>>\n\nexport const EMPTY_SELECTION: CellSelection = new Map()\n\nexport function selectSingleCell(\n rowId: string,\n columnId: string,\n): CellSelection {\n return new Map([[rowId, new Set([columnId])]])\n}\n\nexport function addCellToSelection(\n selection: CellSelection,\n rowId: string,\n columnId: string,\n): CellSelection {\n const next = new Map(selection)\n next.set(rowId, new Set(selection.get(rowId)).add(columnId))\n return next\n}\n\nexport function isCellSelected(\n selection: CellSelection,\n rowId: string,\n columnId: string,\n) {\n return selection.get(rowId)?.has(columnId) ?? false\n}\n\nexport function pruneSelection(\n selection: CellSelection,\n isRowAvailable: (rowId: string) => boolean,\n isColumnAvailable: (columnId: string) => boolean,\n): CellSelection {\n if (selection.size === 0) return selection\n let changed = false\n const next = new Map<string, ReadonlySet<string>>()\n for (const [rowId, columnIds] of selection) {\n if (!isRowAvailable(rowId)) {\n changed = true\n continue\n }\n const kept = new Set<string>()\n for (const columnId of columnIds) {\n if (isColumnAvailable(columnId)) kept.add(columnId)\n }\n if (kept.size === columnIds.size) {\n next.set(rowId, columnIds)\n } else {\n changed = true\n if (kept.size > 0) next.set(rowId, kept)\n }\n }\n return changed ? next : selection\n}\n",
|
|
561
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/selection.ts"
|
|
562
|
-
},
|
|
563
|
-
{
|
|
564
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/skeleton.ts",
|
|
565
|
-
"type": "registry:file",
|
|
566
|
-
"content": "export function createSkeletonRowIds(count: number) {\n const ids: string[] = []\n for (let position = 1; position <= count; position += 1) {\n ids.push(`skeleton-${position}`)\n }\n return ids\n}\n",
|
|
567
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/skeleton.ts"
|
|
568
|
-
},
|
|
569
|
-
{
|
|
570
|
-
"path": "parttens/src/collection-views/views/data-grid/lib/virtual-scroll.ts",
|
|
571
|
-
"type": "registry:file",
|
|
572
|
-
"content": "interface VirtualScrollInput {\n bottomHeight: number\n headerHeight: number\n rowHeight: number\n rowIndex: number\n scrollTop: number\n viewportHeight: number\n}\n\nexport function resolveVirtualScrollTop({\n bottomHeight,\n headerHeight,\n rowHeight,\n rowIndex,\n scrollTop,\n viewportHeight,\n}: VirtualScrollInput): number | undefined {\n const bodyViewportHeight = Math.max(\n rowHeight,\n viewportHeight - headerHeight - bottomHeight,\n )\n const rowStart = rowIndex * rowHeight\n const rowEnd = rowStart + rowHeight\n const bodyScrollStart = Math.max(0, scrollTop - headerHeight)\n\n if (rowStart < bodyScrollStart) return rowStart\n if (rowEnd > bodyScrollStart + bodyViewportHeight) {\n return rowEnd - bodyViewportHeight + headerHeight\n }\n return undefined\n}\n",
|
|
573
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/lib/virtual-scroll.ts"
|
|
574
|
-
},
|
|
575
|
-
{
|
|
576
|
-
"path": "parttens/src/collection-views/views/data-grid/types.ts",
|
|
577
|
-
"type": "registry:file",
|
|
578
|
-
"content": "export type DataGridCellVariant =\n | 'text'\n | 'number'\n | 'select'\n | 'checkbox'\n | 'date'\n | 'badge'\n | 'custom'\n\nexport const DATA_GRID_COLUMN_TYPES = [\n 'title',\n 'text',\n 'number',\n 'select',\n 'multi-select',\n 'status',\n 'date',\n 'formula',\n 'relation',\n 'rollup',\n 'person',\n 'file',\n 'checkbox',\n 'url',\n 'email',\n 'phone',\n 'created-time',\n 'created-by',\n 'last-edited-time',\n 'last-edited-by',\n 'button',\n 'id',\n 'place',\n] as const\n\nexport type DataGridColumnType = (typeof DATA_GRID_COLUMN_TYPES)[number]\n\nexport type DataGridAlign = 'start' | 'center' | 'end'\n\nexport type DataGridDensity = 'short' | 'medium' | 'tall' | 'extra-tall'\n\nexport interface DataGridSelectOption {\n label: string\n value: string\n}\n\nexport interface DataGridCellValueChange {\n columnId: string\n rowId: string\n value: string\n}\n\nexport interface DataGridColumnMeta {\n variant?: DataGridCellVariant\n type?: DataGridColumnType\n align?: DataGridAlign\n label?: string\n placeholder?: string\n options?: DataGridSelectOption[]\n editable?: boolean\n badgeVariant?:\n | 'default'\n | 'secondary'\n | 'outline'\n | 'destructive'\n | 'success'\n | 'warning'\n | 'info'\n | 'error'\n}\n",
|
|
579
|
-
"target": "~/packages/patterns/src/collection-views/views/data-grid/types.ts"
|
|
580
|
-
},
|
|
581
|
-
{
|
|
582
|
-
"path": "parttens/src/collection-views/views/data-table/data-table-aggregation-cell.tsx",
|
|
583
|
-
"type": "registry:file",
|
|
584
|
-
"content": "'use client'\n\nimport { Button } from '@tc96/ui/button'\nimport { Menu, MenuPopup, MenuRadioGroup, MenuTrigger } from '@tc96/ui/menu'\nimport { cn } from '@tc96/utils'\nimport { ChevronDownIcon } from 'lucide-react'\nimport type { ReactElement, ReactNode } from 'react'\nimport { MenuRadioOption } from '../../../shared/components/menu-selection-item'\nimport type {\n DataTableAggregation,\n DataTableAggregationLabels,\n} from './data-table-aggregation'\n\nconst NONE = '__none__'\n\nconst isAggregation = (\n value: unknown,\n options: readonly DataTableAggregation[],\n): value is DataTableAggregation =>\n options.includes(value as DataTableAggregation)\n\nexport function DataTableAggregationCell({\n align = 'start',\n labels,\n onValueChange,\n options,\n result,\n value,\n}: Readonly<{\n align?: 'end' | 'start'\n labels: DataTableAggregationLabels\n onValueChange: (value: DataTableAggregation | null) => void\n options: readonly DataTableAggregation[]\n result: ReactNode\n value: DataTableAggregation | null\n}>): ReactElement {\n return (\n <div\n className={cn('flex', align === 'end' && 'justify-end')}\n data-aggregation={value ?? undefined}\n data-slot=\"data-table-aggregation\"\n >\n <Menu>\n <MenuTrigger\n render={\n <Button\n className={cn(\n '-mx-2 font-normal',\n value === null &&\n 'opacity-0 focus-visible:opacity-100 data-popup-open:opacity-100 group-focus-within/footer:opacity-100 group-hover/footer:opacity-100 pointer-coarse:opacity-100',\n )}\n size=\"xs\"\n variant=\"ghost\"\n />\n }\n >\n {value === null ? (\n <span className=\"text-muted-foreground\">{labels.trigger}</span>\n ) : (\n <>\n <span className=\"text-muted-foreground\">{labels[value]}</span>{' '}\n <span className=\"font-medium tabular-nums\">{result}</span>\n </>\n )}\n <ChevronDownIcon aria-hidden=\"true\" />\n </MenuTrigger>\n <MenuPopup align={align}>\n <MenuRadioGroup\n onValueChange={(next) =>\n onValueChange(isAggregation(next, options) ? next : null)\n }\n value={value ?? NONE}\n >\n <MenuRadioOption value={NONE}>{labels.none}</MenuRadioOption>\n {options.map((option) => (\n <MenuRadioOption key={option} value={option}>\n {labels[option]}\n </MenuRadioOption>\n ))}\n </MenuRadioGroup>\n </MenuPopup>\n </Menu>\n </div>\n )\n}\n",
|
|
585
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/data-table-aggregation-cell.tsx"
|
|
586
|
-
},
|
|
587
|
-
{
|
|
588
|
-
"path": "parttens/src/collection-views/views/data-table/data-table-aggregation.ts",
|
|
589
|
-
"type": "registry:file",
|
|
590
|
-
"content": "import type { ReactNode } from 'react'\n\nexport type DataTableAggregation = 'count' | 'sum'\n\nexport type DataTableAggregations = Readonly<\n Record<string, DataTableAggregation | null>\n>\n\nexport interface DataTableAggregationLabels {\n count: string\n none: string\n sum: string\n trigger: string\n}\n\nexport interface DataTableColumnMeta<TData> {\n aggregations?: readonly DataTableAggregation[]\n align?: 'end' | 'start'\n formatAggregation?: (\n value: number,\n aggregation: DataTableAggregation,\n ) => ReactNode\n getAggregationValue?: (row: TData) => number | null | undefined\n label?: string\n}\n\nexport const defaultAggregationLabels: DataTableAggregationLabels = {\n count: 'Contagem',\n none: 'Nenhum',\n sum: 'Soma',\n trigger: 'Calcular',\n}\n\nexport function aggregate<TRow>(\n rows: readonly TRow[],\n aggregation: DataTableAggregation,\n readValue: (row: TRow) => unknown,\n): number {\n if (aggregation === 'count') return rows.length\n return rows.reduce((total, row) => {\n const value = readValue(row)\n return typeof value === 'number' && Number.isFinite(value)\n ? total + value\n : total\n }, 0)\n}\n",
|
|
591
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/data-table-aggregation.ts"
|
|
592
|
-
},
|
|
593
|
-
{
|
|
594
|
-
"path": "parttens/src/collection-views/views/data-table/data-table-columns-submenu.tsx",
|
|
595
|
-
"type": "registry:file",
|
|
596
|
-
"content": "'use client'\n\nimport type { RowData } from '@tanstack/react-table'\nimport { MenuSub, MenuSubPopup, MenuSubTrigger } from '@tc96/ui/menu'\nimport { Columns3Icon } from 'lucide-react'\nimport type React from 'react'\nimport { MenuCheckboxOption } from '../../../shared/components/menu-selection-item'\nimport type { DataTableColumnMeta } from './data-table-aggregation'\nimport type { DataTableTable } from './use-data-table'\n\nexport interface DataTableColumnsSubmenuProps<TData extends RowData> {\n label?: string\n table: DataTableTable<TData>\n}\n\nexport function DataTableColumnsSubmenu<TData extends RowData>({\n label = 'Colunas',\n table,\n}: DataTableColumnsSubmenuProps<TData>): React.ReactElement | null {\n const columns = table\n .getAllLeafColumns()\n .filter((column) => column.getCanHide())\n if (columns.length === 0) return null\n\n return (\n <MenuSub>\n <MenuSubTrigger>\n <Columns3Icon aria-hidden=\"true\" />\n {label}\n </MenuSubTrigger>\n <MenuSubPopup>\n {columns.map((column) => {\n const meta = (column.columnDef.meta ??\n {}) as DataTableColumnMeta<TData>\n return (\n <MenuCheckboxOption\n checked={column.getIsVisible()}\n closeOnClick={false}\n key={column.id}\n onCheckedChange={(checked) =>\n column.toggleVisibility(Boolean(checked))\n }\n >\n {meta.label ?? column.id}\n </MenuCheckboxOption>\n )\n })}\n </MenuSubPopup>\n </MenuSub>\n )\n}\n",
|
|
597
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/data-table-columns-submenu.tsx"
|
|
598
|
-
},
|
|
599
|
-
{
|
|
600
|
-
"path": "parttens/src/collection-views/views/data-table/data-table-resize-handle.tsx",
|
|
601
|
-
"type": "registry:file",
|
|
602
|
-
"content": "'use client'\n\nimport type { Header, RowData } from '@tanstack/react-table'\nimport { cn } from '@tc96/utils'\nimport type { KeyboardEvent, ReactElement } from 'react'\nimport type { DataTableFeatures, DataTableTable } from './use-data-table'\n\nconst RESIZE_STEP_PX = 8\nconst DEFAULT_MIN_COLUMN_SIZE = 20\nconst DEFAULT_MAX_COLUMN_SIZE = Number.MAX_SAFE_INTEGER\n\nexport interface DataTableResizeHandleProps<TData extends RowData> {\n header: Header<DataTableFeatures, TData, unknown>\n table: DataTableTable<TData>\n}\n\nexport function DataTableResizeHandle<TData extends RowData>({\n header,\n table,\n}: DataTableResizeHandleProps<TData>): ReactElement {\n const { column } = header\n const min = column.columnDef.minSize ?? DEFAULT_MIN_COLUMN_SIZE\n const max = column.columnDef.maxSize ?? DEFAULT_MAX_COLUMN_SIZE\n const size = column.getSize()\n const label =\n typeof column.columnDef.header === 'string'\n ? column.columnDef.header\n : column.id\n\n const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n const delta =\n event.key === 'ArrowLeft'\n ? -RESIZE_STEP_PX\n : event.key === 'ArrowRight'\n ? RESIZE_STEP_PX\n : 0\n if (!delta) return\n event.preventDefault()\n table.setColumnSizing((current) => ({\n ...current,\n [column.id]: Math.min(max, Math.max(min, size + delta)),\n }))\n }\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: the grab area is an ::after box, which a void <hr> cannot render\n <div\n aria-label={`Redimensionar coluna ${label}`}\n aria-orientation=\"vertical\"\n aria-valuemax={max}\n aria-valuemin={min}\n aria-valuenow={size}\n className={cn(\n 'absolute inset-y-0 end-0 z-10 w-0.5 cursor-ew-resize touch-none select-none outline-none after:absolute after:inset-y-0 after:end-0 after:w-3 hover:bg-primary focus-visible:bg-primary',\n column.getIsResizing() ? 'bg-primary' : 'bg-border',\n )}\n onDoubleClick={() => column.resetSize()}\n onKeyDown={handleKeyDown}\n onMouseDown={header.getResizeHandler()}\n onTouchStart={header.getResizeHandler()}\n role=\"separator\"\n tabIndex={0}\n />\n )\n}\n",
|
|
603
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/data-table-resize-handle.tsx"
|
|
604
|
-
},
|
|
605
|
-
{
|
|
606
|
-
"path": "parttens/src/collection-views/views/data-table/data-table-row.tsx",
|
|
607
|
-
"type": "registry:file",
|
|
608
|
-
"content": "'use client'\n\nimport { flexRender, type Row, type RowData } from '@tanstack/react-table'\nimport { TableCell, TableRow } from '@tc96/ui/table'\nimport { cn } from '@tc96/utils'\nimport { memo } from 'react'\nimport { interactiveDescendants } from '../../shared/lib/interactive-descendants'\nimport type { DataTableFeatures, DataTableTable } from './use-data-table'\n\nexport interface DataTableRowProps<TData extends RowData> {\n canSelect: boolean\n meta: DataTableTable<TData>['options']['meta']\n onRowClick?: (row: Row<DataTableFeatures, TData>) => void\n openLabel?: string\n row: Row<DataTableFeatures, TData>\n selected: boolean\n visibleColumns: ReturnType<DataTableTable<TData>['getVisibleLeafColumns']>\n}\n\nfunction DataTableRowView<TData extends RowData>({\n onRowClick,\n openLabel,\n row,\n selected,\n}: DataTableRowProps<TData>) {\n return (\n <TableRow\n className={onRowClick ? 'isolate' : undefined}\n data-interactive={onRowClick ? '' : undefined}\n data-state={selected ? 'selected' : undefined}\n >\n {row.getVisibleCells().map((cell, position) => (\n <TableCell\n className={\n onRowClick\n ? cn('pointer-events-none', interactiveDescendants)\n : undefined\n }\n key={cell.id}\n >\n {onRowClick && position === 0 ? (\n <button\n aria-label={openLabel}\n className=\"absolute inset-0 -z-10 cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset\"\n data-slot=\"data-table-row-trigger\"\n onClick={() => onRowClick(row)}\n type=\"button\"\n />\n ) : null}\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </TableCell>\n ))}\n </TableRow>\n )\n}\n\nexport const DataTableRow = memo(DataTableRowView) as typeof DataTableRowView\n",
|
|
609
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/data-table-row.tsx"
|
|
610
|
-
},
|
|
611
|
-
{
|
|
612
|
-
"path": "parttens/src/collection-views/views/data-table/data-table.tsx",
|
|
613
|
-
"type": "registry:file",
|
|
614
|
-
"content": "'use client'\n\nimport { flexRender, type Row, type RowData } from '@tanstack/react-table'\nimport { Skeleton } from '@tc96/ui/skeleton'\nimport {\n Table,\n TableBody,\n TableCell,\n TableFooter,\n TableHead,\n TableHeader,\n TableRow,\n} from '@tc96/ui/table'\nimport { cn } from '@tc96/utils'\nimport { type ComponentProps, type ReactElement, useState } from 'react'\nimport { skeletonKeys } from '../../shared/lib/skeleton-keys'\nimport {\n aggregate,\n type DataTableAggregation,\n type DataTableAggregationLabels,\n type DataTableAggregations,\n type DataTableColumnMeta,\n defaultAggregationLabels,\n} from './data-table-aggregation'\nimport { DataTableAggregationCell } from './data-table-aggregation-cell'\nimport { DataTableResizeHandle } from './data-table-resize-handle'\nimport { DataTableRow } from './data-table-row'\nimport type { DataTableFeatures, DataTableTable } from './use-data-table'\nimport { useHorizontalOverflow } from './use-horizontal-overflow'\n\nexport interface DataTableProps<TData extends RowData>\n extends Omit<ComponentProps<'table'>, 'children'> {\n table: DataTableTable<TData>\n isLoading?: boolean\n loadingRowCount?: number\n emptyMessage?: string\n /** Moldura do DataGrid, para as duas views lerem como a mesma superfície. */\n bordered?: boolean\n aggregations?: DataTableAggregations\n defaultAggregations?: DataTableAggregations\n onAggregationsChange?: (aggregations: DataTableAggregations) => void\n aggregationLabels?: Partial<DataTableAggregationLabels>\n onRowClick?: (row: Row<DataTableFeatures, TData>) => void\n getRowOpenLabel?: (row: Row<DataTableFeatures, TData>) => string\n}\n\nconst defaultRowOpenLabel = 'Abrir registro'\n\nconst columnMetaOf = <TData,>(column: {\n columnDef: { meta?: unknown }\n}): DataTableColumnMeta<TData> =>\n (column.columnDef.meta ?? {}) as DataTableColumnMeta<TData>\n\nexport function DataTable<TData extends RowData>({\n table,\n isLoading = false,\n loadingRowCount = 5,\n emptyMessage = 'Nenhum registro para exibir.',\n bordered = true,\n aggregations: controlledAggregations,\n defaultAggregations = {},\n onAggregationsChange,\n aggregationLabels,\n onRowClick,\n getRowOpenLabel,\n className,\n style,\n ...props\n}: DataTableProps<TData>): ReactElement {\n const [uncontrolledAggregations, setUncontrolledAggregations] =\n useState<DataTableAggregations>(defaultAggregations)\n const aggregations = controlledAggregations ?? uncontrolledAggregations\n const labels = { ...defaultAggregationLabels, ...aggregationLabels }\n const changeAggregation = (\n columnId: string,\n aggregation: DataTableAggregation | null,\n ) => {\n const next = { ...aggregations, [columnId]: aggregation }\n if (controlledAggregations === undefined) setUncontrolledAggregations(next)\n onAggregationsChange?.(next)\n }\n const rows = table.getRowModel().rows\n const visibleColumns = table.getVisibleLeafColumns()\n const columnCount = visibleColumns.length\n const resizable = Boolean(table.options.enableColumnResizing)\n const fillColumnId = visibleColumns.at(-1)?.id\n const meta = table.options.meta\n const aggregatedRows = table.getPrePaginatedRowModel().rows\n const showAggregations = !isLoading && aggregatedRows.length > 0\n const hasFooter = table\n .getAllLeafColumns()\n .some(\n (column) =>\n column.columnDef.footer ||\n (showAggregations && columnMetaOf<TData>(column).aggregations?.length),\n )\n const [scrollContainerRef, overflow] = useHorizontalOverflow<HTMLDivElement>()\n\n return (\n <div\n className=\"group/data-table relative min-w-0\"\n data-overflow-end={overflow.end || undefined}\n data-overflow-start={overflow.start || undefined}\n data-slot=\"data-table\"\n >\n <Table\n aria-busy={isLoading || undefined}\n render={\n <div\n className={bordered ? 'rounded-md border bg-background' : undefined}\n data-bordered={bordered ? '' : undefined}\n ref={scrollContainerRef}\n />\n }\n className={cn(\n resizable &&\n 'table-fixed [&_td]:overflow-hidden [&_td]:text-ellipsis [&_th]:overflow-hidden',\n className,\n )}\n style={resizable ? { minWidth: table.getTotalSize(), ...style } : style}\n {...props}\n >\n {resizable ? (\n <colgroup>\n {visibleColumns.map((column) => (\n <col\n key={column.id}\n style={\n column.id === fillColumnId\n ? undefined\n : { width: column.getSize() }\n }\n />\n ))}\n </colgroup>\n ) : null}\n <TableHeader className=\"not-in-data-[variant=card]:bg-[color-mix(in_srgb,var(--card),var(--color-black)_2%)] dark:not-in-data-[variant=card]:bg-[color-mix(in_srgb,var(--card),var(--color-white)_2%)]\">\n {table.getHeaderGroups().map((headerGroup) => (\n <TableRow key={headerGroup.id}>\n {headerGroup.headers.map((header) => (\n <TableHead\n className={resizable ? 'relative' : undefined}\n key={header.id}\n >\n {header.isPlaceholder\n ? null\n : flexRender(\n header.column.columnDef.header,\n header.getContext(),\n )}\n {resizable &&\n !header.isPlaceholder &&\n header.subHeaders.length === 0 &&\n header.column.id !== fillColumnId &&\n header.column.getCanResize() ? (\n <DataTableResizeHandle header={header} table={table} />\n ) : null}\n </TableHead>\n ))}\n </TableRow>\n ))}\n </TableHeader>\n <TableBody>\n {isLoading ? (\n skeletonKeys('loading', loadingRowCount).map((rowKey) => (\n <TableRow key={rowKey}>\n {skeletonKeys(rowKey, columnCount).map((cellKey) => (\n <TableCell key={cellKey}>\n <Skeleton className=\"h-4 min-w-4 w-full\" />\n </TableCell>\n ))}\n </TableRow>\n ))\n ) : rows.length ? (\n rows.map((row) => (\n <DataTableRow\n canSelect={row.getCanSelect()}\n key={row.id}\n meta={meta}\n onRowClick={onRowClick}\n openLabel={\n onRowClick\n ? (getRowOpenLabel?.(row) ?? defaultRowOpenLabel)\n : undefined\n }\n row={row}\n selected={row.getIsSelected()}\n visibleColumns={visibleColumns}\n />\n ))\n ) : (\n <TableRow>\n <TableCell className=\"h-24 text-center\" colSpan={columnCount}>\n {emptyMessage}\n </TableCell>\n </TableRow>\n )}\n </TableBody>\n {hasFooter ? (\n <TableFooter>\n {table.getFooterGroups().map((footerGroup) => (\n <TableRow className=\"group/footer\" key={footerGroup.id}>\n {footerGroup.headers.map((header) => {\n const { column } = header\n const meta = columnMetaOf<TData>(column)\n const options = meta.aggregations ?? []\n const selected = aggregations[column.id] ?? null\n const aggregation =\n selected && options.includes(selected) ? selected : null\n const result =\n aggregation === null\n ? 0\n : aggregate(aggregatedRows, aggregation, (row) =>\n meta.getAggregationValue\n ? meta.getAggregationValue(row.original)\n : row.getValue(column.id),\n )\n\n const content =\n header.isPlaceholder ? null : options.length === 0 ? (\n flexRender(column.columnDef.footer, header.getContext())\n ) : showAggregations ? (\n <DataTableAggregationCell\n align={meta.align}\n labels={labels}\n onValueChange={(next) =>\n changeAggregation(column.id, next)\n }\n options={options}\n result={\n aggregation === null\n ? null\n : (meta.formatAggregation?.(result, aggregation) ??\n String(result))\n }\n value={aggregation}\n />\n ) : null\n\n return <TableCell key={header.id}>{content}</TableCell>\n })}\n </TableRow>\n ))}\n </TableFooter>\n ) : null}\n </Table>\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-y-px start-px w-10 rounded-s-md bg-linear-to-r from-background to-transparent opacity-0 transition-opacity group-data-overflow-start/data-table:opacity-100 rtl:bg-linear-to-l\"\n data-slot=\"data-table-overflow-start\"\n />\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-y-px end-px w-10 rounded-e-md bg-linear-to-l from-background to-transparent opacity-0 transition-opacity group-data-overflow-end/data-table:opacity-100 rtl:bg-linear-to-r\"\n data-slot=\"data-table-overflow-end\"\n />\n </div>\n )\n}\n",
|
|
615
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/data-table.tsx"
|
|
616
|
-
},
|
|
617
|
-
{
|
|
618
|
-
"path": "parttens/src/collection-views/views/data-table/index.ts",
|
|
619
|
-
"type": "registry:file",
|
|
620
|
-
"content": "export type { DataTableProps } from './data-table'\nexport { DataTable } from './data-table'\nexport type {\n DataTableAggregation,\n DataTableAggregationLabels,\n DataTableAggregations,\n DataTableColumnMeta,\n} from './data-table-aggregation'\nexport type { DataTableColumnsSubmenuProps } from './data-table-columns-submenu'\nexport { DataTableColumnsSubmenu } from './data-table-columns-submenu'\nexport type {\n DataTableColumnDef,\n DataTableFeatures,\n DataTableTable,\n UseDataTableOptions,\n UseDataTableReturn,\n} from './use-data-table'\nexport { dataTableFeatures, useDataTable } from './use-data-table'\n",
|
|
621
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/index.ts"
|
|
622
|
-
},
|
|
623
|
-
{
|
|
624
|
-
"path": "parttens/src/collection-views/views/data-table/use-data-table.ts",
|
|
625
|
-
"type": "registry:file",
|
|
626
|
-
"content": "'use client'\n\nimport {\n type ColumnDef,\n type ColumnSizingState,\n columnResizingFeature,\n columnSizingFeature,\n columnVisibilityFeature,\n createPaginatedRowModel,\n createSortedRowModel,\n type PaginationState,\n type ReactTable,\n type RowData,\n type RowSelectionState,\n rowPaginationFeature,\n rowSelectionFeature,\n rowSortingFeature,\n type SortingState,\n sortFns,\n type Table,\n type TableOptions,\n tableFeatures,\n useTable,\n} from '@tanstack/react-table'\nimport { useState } from 'react'\n\n/** Features, row models and sort registry the DataTable relies on. */\nexport const dataTableFeatures = tableFeatures({\n columnVisibilityFeature,\n columnSizingFeature,\n columnResizingFeature,\n rowSelectionFeature,\n rowSortingFeature,\n rowPaginationFeature,\n sortedRowModel: createSortedRowModel(),\n paginatedRowModel: createPaginatedRowModel(),\n sortFns,\n})\n\nexport type DataTableFeatures = typeof dataTableFeatures\n\n/** Table instance consumed by `<DataTable />`. */\nexport type DataTableTable<TData extends RowData> = Table<\n DataTableFeatures,\n TData\n>\n\nexport type DataTableColumnDef<TData extends RowData> = ColumnDef<\n DataTableFeatures,\n TData,\n unknown\n>\n\nexport interface UseDataTableOptions<TData extends RowData> {\n /** Row data. */\n data: TData[]\n /** Column definitions. Declare `footer` or `meta.aggregations` on a column to render the table footer. */\n columns: DataTableColumnDef<TData>[]\n /** Stable row identity. Strongly recommended so selection survives reordering. */\n getRowId?: (row: TData, index: number) => string\n enableRowSelection?: boolean\n enableSorting?: boolean\n /** Header edges resize columns; the last visible column takes the remaining width. */\n enableColumnResizing?: boolean\n /** Enables client-side pagination. */\n enablePagination?: boolean\n /** Rows per page when pagination is enabled. Defaults to 10. */\n pageSize?: number\n /** Escape hatch for any TanStack Table option not surfaced above. */\n tableOptions?: Partial<TableOptions<DataTableFeatures, TData>>\n}\n\nexport interface UseDataTableReturn<TData extends RowData> {\n table: ReactTable<DataTableFeatures, TData>\n}\n\n/**\n * Wraps TanStack Table with the features the DataTable expects — selection,\n * sorting and optional pagination. Returns the table instance to hand to\n * `<DataTable table={table} />`.\n */\nexport function useDataTable<TData extends RowData>({\n data,\n columns,\n getRowId,\n enableRowSelection = false,\n enableSorting = false,\n enableColumnResizing = false,\n enablePagination = false,\n pageSize = 10,\n tableOptions,\n}: UseDataTableOptions<TData>): UseDataTableReturn<TData> {\n const initialState = tableOptions?.initialState\n const [sorting, setSorting] = useState<SortingState>(\n () => initialState?.sorting ?? [],\n )\n const [columnSizing, setColumnSizing] = useState<ColumnSizingState>(\n () => initialState?.columnSizing ?? {},\n )\n const [rowSelection, setRowSelection] = useState<RowSelectionState>(\n () => initialState?.rowSelection ?? {},\n )\n const [pagination, setPagination] = useState<PaginationState>({\n pageIndex: initialState?.pagination?.pageIndex ?? 0,\n pageSize: initialState?.pagination?.pageSize ?? pageSize,\n })\n\n const table = useTable<DataTableFeatures, TData>({\n features: dataTableFeatures,\n data,\n columns,\n getRowId,\n state: { sorting, columnSizing, rowSelection, pagination },\n enableRowSelection,\n enableSorting,\n enableColumnResizing,\n columnResizeMode: 'onChange',\n // Paginação é sempre registrada; desligada, a tabela entrega todas as linhas.\n manualPagination: !enablePagination,\n onSortingChange: setSorting,\n onColumnSizingChange: setColumnSizing,\n onRowSelectionChange: setRowSelection,\n onPaginationChange: setPagination,\n ...tableOptions,\n })\n\n return { table }\n}\n",
|
|
627
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/use-data-table.ts"
|
|
628
|
-
},
|
|
629
|
-
{
|
|
630
|
-
"path": "parttens/src/collection-views/views/data-table/use-horizontal-overflow.ts",
|
|
631
|
-
"type": "registry:file",
|
|
632
|
-
"content": "'use client'\n\nimport { type RefObject, useEffect, useRef, useState } from 'react'\n\nexport interface HorizontalOverflow {\n end: boolean\n start: boolean\n}\n\nexport function useHorizontalOverflow<TElement extends HTMLElement>(): [\n RefObject<TElement | null>,\n HorizontalOverflow,\n] {\n const ref = useRef<TElement>(null)\n const [overflow, setOverflow] = useState<HorizontalOverflow>({\n end: false,\n start: false,\n })\n\n useEffect(() => {\n const element = ref.current\n if (!element) return\n\n const measure = () => {\n const offset = Math.abs(element.scrollLeft)\n const maxOffset = element.scrollWidth - element.clientWidth\n const next = { end: offset < maxOffset - 1, start: offset > 1 }\n setOverflow((current) =>\n current.end === next.end && current.start === next.start\n ? current\n : next,\n )\n }\n\n measure()\n element.addEventListener('scroll', measure, { passive: true })\n const observer =\n typeof ResizeObserver === 'undefined'\n ? undefined\n : new ResizeObserver(measure)\n observer?.observe(element)\n if (element.firstElementChild) observer?.observe(element.firstElementChild)\n\n return () => {\n element.removeEventListener('scroll', measure)\n observer?.disconnect()\n }\n }, [])\n\n return [ref, overflow]\n}\n",
|
|
633
|
-
"target": "~/packages/patterns/src/collection-views/views/data-table/use-horizontal-overflow.ts"
|
|
634
|
-
},
|
|
635
|
-
{
|
|
636
|
-
"path": "parttens/src/collection-views/views/gallery/components/gallery-item-skeleton.tsx",
|
|
637
|
-
"type": "registry:file",
|
|
638
|
-
"content": "import { Card, CardFooter, CardHeader } from '@tc96/ui/card'\nimport { Separator } from '@tc96/ui/separator'\nimport { Skeleton } from '@tc96/ui/skeleton'\nimport type { ReactElement } from 'react'\n\nexport interface GalleryItemSkeletonProps {\n label?: string\n}\n\nexport function GalleryItemSkeleton({\n label = 'Loading item',\n}: GalleryItemSkeletonProps): ReactElement {\n return (\n <output aria-busy=\"true\" aria-label={label} className=\"contents\">\n <Card\n aria-hidden=\"true\"\n className=\"min-h-52 pointer-events-none select-none\"\n render={<article />}\n >\n <CardHeader>\n <Skeleton className=\"h-3 w-1/3\" />\n <Skeleton className=\"h-4.5 w-1/2\" />\n <Skeleton className=\"h-3.5 w-4/5\" />\n </CardHeader>\n <Separator className=\"mt-auto\" />\n <CardFooter className=\"justify-between gap-3\">\n <Skeleton className=\"h-3 w-28\" />\n <Skeleton className=\"size-4 rounded-full\" />\n </CardFooter>\n </Card>\n </output>\n )\n}\n",
|
|
639
|
-
"target": "~/packages/patterns/src/collection-views/views/gallery/components/gallery-item-skeleton.tsx"
|
|
640
|
-
},
|
|
641
|
-
{
|
|
642
|
-
"path": "parttens/src/collection-views/views/gallery/components/gallery-view-item.tsx",
|
|
643
|
-
"type": "registry:file",
|
|
644
|
-
"content": "import { memo, type ReactNode } from 'react'\n\ninterface GalleryViewItemProps<TItem> {\n item: TItem\n renderItem: (item: TItem) => ReactNode\n}\n\nexport const GalleryViewItem = memo(function GalleryViewItem<TItem>({\n item,\n renderItem,\n}: GalleryViewItemProps<TItem>) {\n return renderItem(item)\n}) as <TItem>(props: GalleryViewItemProps<TItem>) => ReactNode\n",
|
|
645
|
-
"target": "~/packages/patterns/src/collection-views/views/gallery/components/gallery-view-item.tsx"
|
|
646
|
-
},
|
|
647
|
-
{
|
|
648
|
-
"path": "parttens/src/collection-views/views/gallery/components/gallery-view.tsx",
|
|
649
|
-
"type": "registry:file",
|
|
650
|
-
"content": "'use client'\n\nimport { Empty, EmptyDescription } from '@tc96/ui/empty'\nimport type { ReactNode } from 'react'\nimport { skeletonKeys } from '../../../shared/lib/skeleton-keys'\nimport type { CollectionDefinition } from '../../../types/collection'\nimport { GalleryItemSkeleton } from './gallery-item-skeleton'\nimport { GalleryViewItem } from './gallery-view-item'\n\nexport interface GalleryViewProps<TItem> {\n collection: CollectionDefinition<TItem>\n emptyMessage?: ReactNode\n loading?: boolean\n loadingItemCount?: number\n loadingItemLabel?: string\n renderItem: (item: TItem) => ReactNode\n}\n\nexport function GalleryView<TItem>({\n collection,\n emptyMessage = 'No items to show.',\n loading = false,\n loadingItemCount = 4,\n loadingItemLabel,\n renderItem,\n}: GalleryViewProps<TItem>) {\n return (\n <div\n aria-busy={loading ? 'true' : undefined}\n className=\"grid min-w-0 grid-cols-1 items-stretch gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4\"\n data-slot=\"gallery-view\"\n >\n {loading ? (\n skeletonKeys('gallery-loading', loadingItemCount).map((skeletonKey) => (\n <GalleryItemSkeleton\n key={skeletonKey}\n {...(loadingItemLabel ? { label: loadingItemLabel } : {})}\n />\n ))\n ) : collection.items.length ? (\n collection.items.map((item) => (\n <GalleryViewItem\n item={item}\n key={collection.getKey(item)}\n renderItem={renderItem}\n />\n ))\n ) : (\n <Empty className=\"col-span-full\">\n <EmptyDescription>{emptyMessage}</EmptyDescription>\n </Empty>\n )}\n </div>\n )\n}\n",
|
|
651
|
-
"target": "~/packages/patterns/src/collection-views/views/gallery/components/gallery-view.tsx"
|
|
652
|
-
},
|
|
653
|
-
{
|
|
654
|
-
"path": "parttens/src/collection-views/views/gallery/index.ts",
|
|
655
|
-
"type": "registry:file",
|
|
656
|
-
"content": "export type { GalleryItemSkeletonProps } from './components/gallery-item-skeleton'\nexport { GalleryItemSkeleton } from './components/gallery-item-skeleton'\nexport type { GalleryViewProps } from './components/gallery-view'\nexport { GalleryView } from './components/gallery-view'\n",
|
|
657
|
-
"target": "~/packages/patterns/src/collection-views/views/gallery/index.ts"
|
|
658
|
-
},
|
|
659
|
-
{
|
|
660
|
-
"path": "parttens/src/collection-views/views/kanban/components/kanban-badge.tsx",
|
|
661
|
-
"type": "registry:file",
|
|
662
|
-
"content": "import { Badge } from '@tc96/ui/badge'\nimport type { ReactNode } from 'react'\n\nexport interface KanbanBadgeProps {\n children: ReactNode\n className?: string\n tone?: 'muted' | 'neutral' | 'primary'\n}\n\nexport function KanbanBadge({\n children,\n className,\n tone: _tone = 'neutral',\n}: KanbanBadgeProps) {\n return (\n <Badge className={className} variant=\"secondary\">\n {children}\n </Badge>\n )\n}\n",
|
|
663
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/components/kanban-badge.tsx"
|
|
664
|
-
},
|
|
665
|
-
{
|
|
666
|
-
"path": "parttens/src/collection-views/views/kanban/components/kanban-card-skeleton.tsx",
|
|
667
|
-
"type": "registry:file",
|
|
668
|
-
"content": "import { Skeleton } from '@tc96/ui/skeleton'\nimport { cn } from '@tc96/utils'\nimport type { ReactElement } from 'react'\nimport {\n KanbanCard,\n KanbanCardContent,\n KanbanCardFooter,\n KanbanCardHeader,\n type KanbanCardProps,\n} from './kanban-card'\n\nexport interface KanbanCardSkeletonProps\n extends Omit<\n KanbanCardProps,\n 'aria-busy' | 'aria-label' | 'children' | 'role'\n > {\n label?: string\n}\n\nexport function KanbanCardSkeleton({\n className,\n display = 'full',\n label = 'Carregando card',\n ...props\n}: KanbanCardSkeletonProps): ReactElement {\n // `article` não pode ser `status`: um `output`, que já é status, envolve\n // o card sem caixa própria, e o card fica oculto da tecnologia assistiva.\n return (\n <output aria-busy=\"true\" aria-label={label} className=\"contents\">\n <KanbanCard\n {...props}\n aria-hidden=\"true\"\n className={cn('pointer-events-none select-none', className)}\n display={display}\n >\n <KanbanCardHeader aria-hidden=\"true\">\n <Skeleton className=\"h-4 w-2/3\" />\n {display === 'compact' ? (\n <Skeleton className=\"h-3 w-8 shrink-0\" />\n ) : (\n <div className=\"grid gap-2\">\n <Skeleton className=\"h-3 w-full\" />\n <Skeleton className=\"h-3 w-4/5\" />\n </div>\n )}\n </KanbanCardHeader>\n <KanbanCardContent aria-hidden=\"true\">\n <Skeleton className=\"h-6 w-12 rounded-full\" />\n </KanbanCardContent>\n <KanbanCardFooter aria-hidden=\"true\" className=\"justify-between gap-4\">\n <Skeleton className=\"h-3 w-16\" />\n <Skeleton className=\"h-3 w-12\" />\n </KanbanCardFooter>\n </KanbanCard>\n </output>\n )\n}\n",
|
|
669
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/components/kanban-card-skeleton.tsx"
|
|
670
|
-
},
|
|
671
|
-
{
|
|
672
|
-
"path": "parttens/src/collection-views/views/kanban/components/kanban-card.tsx",
|
|
673
|
-
"type": "registry:file",
|
|
674
|
-
"content": "'use client'\n\nimport { mergeProps } from '@base-ui/react/merge-props'\nimport { useRender } from '@base-ui/react/use-render'\nimport {\n Card,\n CardAction,\n CardContent,\n CardDescription,\n CardFooter,\n CardHeader,\n CardTitle,\n} from '@tc96/ui/card'\nimport { cn } from '@tc96/utils'\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport {\n type ComponentProps,\n type ComponentPropsWithoutRef,\n createContext,\n type ReactElement,\n useContext,\n} from 'react'\n\nexport type KanbanCardDisplay = 'full' | 'compact'\n\nconst kanbanCardSurfaceVariants = cva(null, {\n defaultVariants: { density: 'md' },\n variants: {\n density: {\n md: '[--card-padding:--spacing(6)] [--card-section-gap:--spacing(4)]',\n sm: '[--card-padding:--spacing(4)] [--card-section-gap:--spacing(2)]',\n },\n },\n})\n\nexport const kanbanCardVariants = cva(\n 'relative isolate min-w-0 w-full overflow-hidden transition-colors hover:bg-card/60 has-focus-visible:ring-2 has-focus-visible:ring-primary has-focus-visible:ring-offset-2 has-focus-visible:ring-offset-background [&_[data-kanban-card-action]]:relative [&_[data-kanban-card-action]]:z-10',\n {\n defaultVariants: {\n dimmed: false,\n selected: false,\n variant: 'default',\n },\n variants: {\n dimmed: {\n false: null,\n true: 'border-dashed shadow-none',\n },\n selected: {\n false: null,\n true: 'ring-2 ring-primary/40 ring-offset-2 ring-offset-background',\n },\n variant: {\n default: null,\n interactive:\n 'cursor-pointer text-left outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background [&>:focus-visible]:outline-none',\n },\n },\n },\n)\n\nconst kanbanCardHeaderVariants = cva(\n 'gap-1 in-[[data-slot=card]:has(>[data-slot=card-panel])]:pb-2',\n {\n variants: {\n display: {\n compact: 'flex min-h-10 min-w-0 items-center gap-2 px-3 py-2',\n full: 'px-3 pt-3 pb-2',\n },\n },\n },\n)\n\nconst kanbanCardTitleVariants = cva('font-medium text-sm leading-5', {\n variants: {\n display: {\n compact: 'min-w-0 flex-1 truncate',\n full: null,\n },\n },\n})\n\nconst kanbanCardDescriptionVariants = cva('text-xs leading-5', {\n variants: {\n display: {\n compact: null,\n full: 'line-clamp-3',\n },\n },\n})\n\nconst kanbanCardContentVariants = cva('px-3 pt-0 pb-3')\n\nconst kanbanCardFooterVariants = cva(\n 'min-h-9 px-3 py-2 text-xs in-[[data-slot=card]:has(>[data-slot=card-panel])]:pt-2',\n)\n\nexport interface KanbanCardProps extends useRender.ComponentProps<'article'> {\n density?: VariantProps<typeof kanbanCardSurfaceVariants>['density']\n dimmed?: boolean\n display?: KanbanCardDisplay\n selected?: boolean\n variant?: VariantProps<typeof kanbanCardVariants>['variant']\n}\n\nexport type KanbanCardActionProps = ComponentProps<typeof CardAction>\nexport interface KanbanCardActionButtonProps\n extends useRender.ComponentProps<'button'> {\n size?: 'default' | 'icon'\n}\nexport type KanbanCardContentProps = ComponentProps<typeof CardContent>\nexport type KanbanCardBodyProps = KanbanCardContentProps\nexport interface KanbanCardBodyRowProps\n extends ComponentPropsWithoutRef<'div'> {\n align?: 'start' | 'between'\n}\nexport type KanbanCardDescriptionProps = ComponentProps<typeof CardDescription>\nexport type KanbanCardFooterProps = ComponentProps<typeof CardFooter>\nexport type KanbanCardHeaderProps = ComponentProps<typeof CardHeader>\nexport type KanbanCardOpenTriggerProps = ComponentPropsWithoutRef<'button'>\nexport type KanbanCardTitleProps = ComponentProps<typeof CardTitle>\n\nconst KanbanCardDisplayContext = createContext<KanbanCardDisplay>('full')\n\nexport function KanbanCard({\n className,\n density = 'sm',\n dimmed = false,\n display = 'full',\n ref,\n render,\n selected = false,\n variant = 'default',\n ...props\n}: KanbanCardProps): ReactElement {\n const card = (\n <Card\n className={cn(\n kanbanCardSurfaceVariants({ density }),\n kanbanCardVariants({ dimmed, selected, variant }),\n className,\n )}\n data-density={density}\n data-display={display}\n data-pattern=\"kanban-card\"\n data-state={selected ? 'selected' : undefined}\n data-variant={variant}\n render={render ?? <article />}\n ref={ref as ComponentProps<typeof Card>['ref']}\n {...props}\n />\n )\n\n return (\n <KanbanCardDisplayContext.Provider value={display}>\n {card}\n </KanbanCardDisplayContext.Provider>\n )\n}\n\nexport function KanbanCardHeader({\n className,\n ...props\n}: KanbanCardHeaderProps): ReactElement {\n const display = useContext(KanbanCardDisplayContext)\n\n return (\n <CardHeader\n className={cn(kanbanCardHeaderVariants({ display }), className)}\n {...props}\n />\n )\n}\n\nexport function KanbanCardTitle({\n className,\n ...props\n}: KanbanCardTitleProps): ReactElement {\n const display = useContext(KanbanCardDisplayContext)\n\n return (\n <CardTitle\n className={cn(kanbanCardTitleVariants({ display }), className)}\n {...props}\n />\n )\n}\n\nexport function KanbanCardDescription({\n className,\n ...props\n}: KanbanCardDescriptionProps): ReactElement {\n const display = useContext(KanbanCardDisplayContext)\n\n return (\n <CardDescription\n className={cn(kanbanCardDescriptionVariants({ display }), className)}\n {...props}\n hidden={display === 'compact' || props.hidden}\n />\n )\n}\n\nexport function KanbanCardAction({\n className,\n ...props\n}: KanbanCardActionProps): ReactElement {\n const display = useContext(KanbanCardDisplayContext)\n\n return (\n <CardAction\n className={cn(display === 'compact' && 'shrink-0 self-center', className)}\n data-kanban-card-action=\"\"\n {...props}\n />\n )\n}\n\nexport function KanbanCardActionButton({\n className,\n render,\n size = 'default',\n ...props\n}: KanbanCardActionButtonProps): ReactElement {\n const defaultProps = {\n className: cn(\n 'inline-flex min-h-7 shrink-0 cursor-pointer items-center justify-center gap-1 rounded-md border border-transparent px-1.5 text-card-foreground/70 text-xs outline-none transition-colors hover:bg-accent hover:text-card-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50',\n size === 'icon' && 'size-7 p-0',\n className,\n ),\n 'data-kanban-card-action': '',\n 'data-slot': 'kanban-card-action-button',\n type: 'button' as const,\n }\n\n return useRender({\n defaultTagName: 'button',\n props: mergeProps<'button'>(defaultProps, props),\n render,\n })\n}\n\nexport function KanbanCardOpenTrigger({\n className,\n ...props\n}: KanbanCardOpenTriggerProps): ReactElement {\n return (\n <button\n className={cn(\n 'absolute inset-0 cursor-pointer rounded-[inherit] outline-none',\n className,\n )}\n data-slot=\"kanban-card-open-trigger\"\n type=\"button\"\n {...props}\n />\n )\n}\n\nexport function KanbanCardContent({\n className,\n ...props\n}: KanbanCardContentProps): ReactElement {\n const display = useContext(KanbanCardDisplayContext)\n\n return (\n <CardContent\n className={cn(kanbanCardContentVariants(), className)}\n {...props}\n hidden={display === 'compact' || props.hidden}\n />\n )\n}\n\nexport const KanbanCardBody = KanbanCardContent\n\nexport function KanbanCardBodyRow({\n align = 'start',\n className,\n ...props\n}: KanbanCardBodyRowProps): ReactElement {\n return (\n <div\n className={cn(\n 'flex min-w-0 items-center gap-2',\n align === 'between' ? 'justify-between' : 'justify-start',\n className,\n )}\n data-slot=\"kanban-card-body-row\"\n {...props}\n />\n )\n}\n\nexport function KanbanCardFooter({\n className,\n ...props\n}: KanbanCardFooterProps): ReactElement {\n const display = useContext(KanbanCardDisplayContext)\n\n return (\n <CardFooter\n className={cn(kanbanCardFooterVariants(), className)}\n {...props}\n hidden={display === 'compact' || props.hidden}\n />\n )\n}\n",
|
|
675
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/components/kanban-card.tsx"
|
|
676
|
-
},
|
|
677
|
-
{
|
|
678
|
-
"path": "parttens/src/collection-views/views/kanban/components/kanban-column-selector.tsx",
|
|
679
|
-
"type": "registry:file",
|
|
680
|
-
"content": "import { Button } from '@tc96/ui/button'\nimport { ScrollArea } from '@tc96/ui/scroll-area'\nimport { useId } from 'react'\n\nimport type { KanbanColumnOption } from '../types'\n\nexport interface KanbanColumnSelectorProps {\n columns: KanbanColumnOption[]\n hint?: string\n id?: string\n label?: string\n value: string\n onValueChange: (value: string) => void\n}\n\nexport function KanbanColumnSelector({\n columns,\n hint,\n id,\n label = 'Coluna',\n value,\n onValueChange,\n}: KanbanColumnSelectorProps) {\n const generatedId = useId()\n const selectorId = id ?? `kanban-column-${generatedId}`\n\n return (\n <div className=\"md:hidden\">\n <div\n className=\"mb-1.5 font-medium text-muted-foreground text-xs\"\n id={`${selectorId}-label`}\n >\n {label}\n </div>\n <ScrollArea\n aria-labelledby={`${selectorId}-label`}\n className=\"h-9\"\n scrollbarGutter\n >\n <div className=\"flex w-max gap-1\">\n {columns.map((column) => {\n const selected = column.value === value\n return (\n <Button\n aria-pressed={selected}\n data-kanban-column-option={column.value}\n key={column.value}\n onClick={() => onValueChange(column.value)}\n size=\"sm\"\n variant={selected ? 'secondary' : 'ghost'}\n >\n {column.label}\n </Button>\n )\n })}\n </div>\n </ScrollArea>\n {hint ? (\n <p className=\"mt-2 text-muted-foreground text-xs\">{hint}</p>\n ) : null}\n </div>\n )\n}\n",
|
|
681
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/components/kanban-column-selector.tsx"
|
|
682
|
-
},
|
|
683
|
-
{
|
|
684
|
-
"path": "parttens/src/collection-views/views/kanban/components/kanban-column.tsx",
|
|
685
|
-
"type": "registry:file",
|
|
686
|
-
"content": "import { CollisionPriority } from '@dnd-kit/abstract'\nimport { useDroppable } from '@dnd-kit/react'\nimport { Button } from '@tc96/ui/button'\nimport { ScrollArea } from '@tc96/ui/scroll-area'\nimport { cn } from '@tc96/utils'\nimport { EllipsisIcon, PlusIcon } from 'lucide-react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { memo, useId } from 'react'\n\nimport { createColumnDropId } from '../lib/drag-and-drop'\nimport type { KanbanColumnActions, KanbanColumnData } from '../types'\nimport { KanbanBadge } from './kanban-badge'\nimport { KanbanCardSkeleton } from './kanban-card-skeleton'\nimport { SortableKanbanCard } from './sortable-kanban-card'\n\nexport interface KanbanColumnProps<TCard = unknown> {\n column: KanbanColumnData<TCard>\n renderCard: (card: TCard) => ReactNode\n getKey: (card: TCard) => string | number\n emptyLabel?: string\n className?: string\n getCardDragId?: (card: TCard) => string\n getCardLabel?: (card: TCard) => string\n loading?: boolean\n loadingCardCount?: number\n loadingCardLabel?: string\n renderColumnTitle?: (column: KanbanColumnData<TCard>) => ReactNode\n renderHeaderActions?: (column: KanbanColumnData<TCard>) => ReactNode\n sortableCards?: boolean\n actions?: KanbanColumnActions\n}\n\nfunction KanbanEmptyState({\n children,\n className,\n}: Readonly<{ children: ReactNode; className?: string }>) {\n return (\n <div\n className={cn(\n 'min-w-0 max-w-full rounded-md border border-dashed px-3 py-6 text-center text-muted-foreground text-sm',\n className,\n )}\n >\n {children}\n </div>\n )\n}\n\nfunction KanbanColumnHeader<TCard>({\n actions,\n column,\n renderColumnTitle,\n renderHeaderActions,\n titleId,\n}: Readonly<{\n actions?: KanbanColumnActions\n column: KanbanColumnData<TCard>\n renderColumnTitle?: (column: KanbanColumnData<TCard>) => ReactNode\n renderHeaderActions?: (column: KanbanColumnData<TCard>) => ReactNode\n titleId: string\n}>) {\n return (\n <header\n className={cn(\n 'mb-3 flex shrink-0 items-center justify-between gap-3 pt-3',\n column.collapsed ? 'flex-col px-1.5' : 'px-3',\n )}\n >\n <div\n className={cn(\n 'flex min-w-0 items-center gap-2',\n column.collapsed && 'flex-col',\n )}\n >\n {column.color ? (\n <span\n aria-hidden=\"true\"\n className=\"size-3 shrink-0 rounded-full\"\n style={{ backgroundColor: column.color }}\n />\n ) : null}\n <h2\n className={cn(\n 'truncate font-semibold text-sm leading-none',\n column.collapsed && 'order-1 max-h-48 [writing-mode:vertical-rl]',\n )}\n id={titleId}\n >\n {renderColumnTitle?.(column) ?? column.title}\n </h2>\n <KanbanBadge\n className={column.collapsed ? 'order-0' : undefined}\n tone=\"neutral\"\n >\n {column.count}\n </KanbanBadge>\n </div>\n {actions?.onOpenSettings ||\n (!column.collapsed && actions?.onAddCard) ||\n renderHeaderActions ? (\n <div\n className={cn(\n 'flex shrink-0 items-center gap-0.5',\n column.collapsed && 'flex-col',\n )}\n >\n {!column.collapsed && actions?.onAddCard ? (\n <Button\n aria-label={\n actions.addLabel ?? `Adicionar item à seção ${column.title}`\n }\n onClick={() => actions.onAddCard?.(column.id)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <PlusIcon aria-hidden=\"true\" />\n </Button>\n ) : null}\n {actions?.onOpenSettings ? (\n <Button\n aria-label={\n actions.settingsLabel ?? `Configurar seção ${column.title}`\n }\n onClick={() => actions.onOpenSettings?.(column.id)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <EllipsisIcon aria-hidden=\"true\" />\n </Button>\n ) : null}\n {renderHeaderActions?.(column)}\n </div>\n ) : null}\n </header>\n )\n}\n\ninterface KanbanColumnCardsProps<TCard> {\n column: KanbanColumnData<TCard>\n emptyLabel: string\n getCardDragId?: (card: TCard) => string\n getCardLabel: (card: TCard) => string\n getKey: (card: TCard) => string | number\n loading: boolean\n loadingCardCount: number\n loadingCardLabel?: string\n renderCard: (card: TCard) => ReactNode\n sortableCards: boolean\n}\n\nfunction KanbanColumnCards<TCard>({\n column,\n emptyLabel,\n getCardDragId,\n getCardLabel,\n getKey,\n loading,\n loadingCardCount,\n loadingCardLabel,\n renderCard,\n sortableCards,\n}: KanbanColumnCardsProps<TCard>) {\n if (loading) {\n const loadingCards = Array.from(\n { length: loadingCardCount },\n (_, position) => ({\n id: `${column.id}-loading-${position + 1}`,\n }),\n )\n\n return loadingCards.map((card) => (\n <KanbanCardSkeleton\n key={card.id}\n {...(loadingCardLabel ? { label: loadingCardLabel } : {})}\n />\n ))\n }\n\n if (!column.cards.length) {\n return (\n <KanbanEmptyState className=\"bg-card/60 py-10\">\n {emptyLabel}\n </KanbanEmptyState>\n )\n }\n\n const sortable = sortableCards && getCardDragId\n\n return column.cards.map((card, index) => (\n <KanbanColumnCard\n card={card}\n columnId={column.id}\n dragLabel={`Mover card ${getCardLabel(card)}`}\n index={index}\n key={getKey(card)}\n renderCard={renderCard}\n {...(sortable ? { dragId: getCardDragId(card) } : {})}\n />\n ))\n}\n\ninterface KanbanColumnCardProps<TCard> {\n card: TCard\n columnId: string\n dragId?: string\n dragLabel: string\n index: number\n renderCard: (card: TCard) => ReactNode\n}\n\nconst KanbanColumnCard = memo(function KanbanColumnCard<TCard>({\n card,\n columnId,\n dragId,\n dragLabel,\n index,\n renderCard,\n}: KanbanColumnCardProps<TCard>) {\n const content = <KanbanCardContentSlot card={card} renderCard={renderCard} />\n\n if (dragId === undefined) {\n return (\n <div className=\"min-w-0 max-w-full\" data-kanban-card-container=\"\">\n {content}\n </div>\n )\n }\n\n return (\n <SortableKanbanCard\n columnId={columnId}\n dragLabel={dragLabel}\n id={dragId}\n index={index}\n >\n {content}\n </SortableKanbanCard>\n )\n}) as <TCard>(props: KanbanColumnCardProps<TCard>) => ReactNode\n\nconst KanbanCardContentSlot = memo(function KanbanCardContentSlot<TCard>({\n card,\n renderCard,\n}: Pick<KanbanColumnCardProps<TCard>, 'card' | 'renderCard'>) {\n return renderCard(card)\n}) as <TCard>(\n props: Pick<KanbanColumnCardProps<TCard>, 'card' | 'renderCard'>,\n) => ReactNode\n\nexport function KanbanColumn<TCard>({\n column,\n renderCard,\n getKey,\n emptyLabel = 'Nenhum item nesta coluna.',\n className,\n getCardDragId,\n getCardLabel = (card) => String(getKey(card)),\n loading = false,\n loadingCardCount = 1,\n loadingCardLabel,\n renderColumnTitle,\n renderHeaderActions,\n sortableCards = false,\n actions,\n}: KanbanColumnProps<TCard>) {\n const instanceId = useId()\n const titleId = `kanban-column-title-${instanceId}`\n const surfaceStyle: CSSProperties | undefined = column.color\n ? {\n backgroundColor: `color-mix(in srgb, var(--card) 96%, ${column.color} 4%)`,\n borderColor: `color-mix(in srgb, ${column.color} 8%, transparent)`,\n }\n : undefined\n const { ref } = useDroppable({\n accept: 'kanban-card',\n collisionPriority: CollisionPriority.Lowest,\n id: createColumnDropId(column.id, instanceId),\n data: { columnId: column.id, type: 'column' },\n disabled: !sortableCards || !!column.collapsed,\n type: 'kanban-column',\n })\n\n return (\n <section\n aria-labelledby={titleId}\n data-collapsed={column.collapsed ? 'true' : undefined}\n data-slot=\"kanban-column\"\n className={cn(\n 'flex h-full min-h-0 min-w-0 max-w-full flex-col rounded-lg border border-border bg-card text-card-foreground shadow-none',\n column.collapsed && 'w-12',\n className,\n )}\n style={surfaceStyle}\n >\n <KanbanColumnHeader\n column={column}\n titleId={titleId}\n {...(!loading && actions ? { actions } : {})}\n {...(renderColumnTitle ? { renderColumnTitle } : {})}\n {...(renderHeaderActions ? { renderHeaderActions } : {})}\n />\n\n {!column.collapsed ? (\n <ScrollArea className=\"min-h-0 flex-1\" fill scrollbarGutter scrollFade>\n <div\n ref={ref}\n className=\"grid h-full min-h-full min-w-0 max-w-full content-start gap-2 px-2 pb-2\"\n >\n <KanbanColumnCards\n column={column}\n emptyLabel={emptyLabel}\n getCardLabel={getCardLabel}\n getKey={getKey}\n loading={loading}\n loadingCardCount={loadingCardCount}\n renderCard={renderCard}\n sortableCards={sortableCards}\n {...(getCardDragId ? { getCardDragId } : {})}\n {...(loadingCardLabel ? { loadingCardLabel } : {})}\n />\n </div>\n </ScrollArea>\n ) : null}\n </section>\n )\n}\n",
|
|
687
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/components/kanban-column.tsx"
|
|
688
|
-
},
|
|
689
|
-
{
|
|
690
|
-
"path": "parttens/src/collection-views/views/kanban/components/kanban-view.tsx",
|
|
691
|
-
"type": "registry:file",
|
|
692
|
-
"content": "import { DragDropProvider, DragOverlay } from '@dnd-kit/react'\nimport { ScrollArea } from '@tc96/ui/scroll-area'\nimport { cn } from '@tc96/utils'\nimport type { ReactNode } from 'react'\nimport { useLayoutEffect, useMemo, useRef } from 'react'\n\nimport { useActiveColumnId } from '../hooks/use-active-column-id'\nimport { useHorizontalDragScroll } from '../hooks/use-horizontal-drag-scroll'\nimport { useKanbanDragAndDrop } from '../hooks/use-kanban-drag-and-drop'\nimport type {\n KanbanCardMove,\n KanbanColumnActions,\n KanbanColumnData,\n KanbanColumnOption,\n} from '../types'\nimport { KanbanColumn } from './kanban-column'\nimport { KanbanColumnSelector } from './kanban-column-selector'\n\nexport interface KanbanViewProps<TCard = unknown> {\n columns: KanbanColumnData<TCard>[]\n renderCard: (card: TCard) => ReactNode\n getKey: (card: TCard) => string | number\n getCardLabel?: (card: TCard) => string\n getColumnActions?: (\n column: KanbanColumnData<TCard>,\n ) => KanbanColumnActions | undefined\n emptyColumnLabel?: string\n loading?: boolean\n loadingCardCount?: number\n loadingCardLabel?: string\n mobileColumnHint?: string\n onMoveCard?: (move: KanbanCardMove<TCard>) => boolean | Promise<boolean>\n renderColumnTitle?: (column: KanbanColumnData<TCard>) => ReactNode\n renderHeaderActions?: (column: KanbanColumnData<TCard>) => ReactNode\n}\n\nexport function KanbanView<TCard>({\n columns,\n renderCard,\n getKey,\n getCardLabel,\n getColumnActions,\n emptyColumnLabel,\n loading = false,\n loadingCardCount = 1,\n loadingCardLabel,\n mobileColumnHint,\n onMoveCard,\n renderColumnTitle,\n renderHeaderActions,\n}: KanbanViewProps<TCard>) {\n const shownColumns = useMemo(\n () => columns.filter((column) => !column.hidden),\n [columns],\n )\n const [activeColumnId, setActiveColumnId] = useActiveColumnId(shownColumns)\n const {\n cardDragEnabled,\n focusCardDragId,\n getCardDragId,\n handleCardFocusRestored,\n handleDragEnd,\n handleDragOver,\n handleDragStart,\n visibleColumns,\n } = useKanbanDragAndDrop({\n columns: shownColumns,\n getKey,\n ...(!loading && onMoveCard ? { onMoveCard } : {}),\n })\n const { isDragging: isBoardDragging, rootRef } = useHorizontalDragScroll()\n const boardContentRef = useRef<HTMLDivElement | null>(null)\n const columnOptions = createColumnOptions(shownColumns)\n const cardsByDragId = useMemo(\n () =>\n new Map(\n visibleColumns.flatMap((column) =>\n column.cards.map((card) => [getCardDragId(card), card] as const),\n ),\n ),\n [getCardDragId, visibleColumns],\n )\n const activeColumn = useMemo(\n () =>\n visibleColumns.find((column) => column.id === activeColumnId) ??\n visibleColumns[0],\n [activeColumnId, visibleColumns],\n )\n const columnProps = {\n getCardDragId,\n getKey,\n loading,\n loadingCardCount,\n loadingCardLabel,\n renderColumnTitle,\n renderHeaderActions,\n renderCard,\n sortableCards: cardDragEnabled,\n ...(emptyColumnLabel ? { emptyLabel: emptyColumnLabel } : {}),\n ...(getCardLabel ? { getCardLabel } : {}),\n }\n const showHorizontalScrollbar = cardDragEnabled && isBoardDragging\n const getColumnActionProps = (column: KanbanColumnData<TCard>) => {\n const actions = getColumnActions?.(column)\n return actions ? { actions } : {}\n }\n\n useLayoutEffect(() => {\n if (!focusCardDragId) return\n\n const frame = requestAnimationFrame(() => {\n const card = Array.from(\n boardContentRef.current?.querySelectorAll<HTMLElement>(\n '[data-kanban-card-drag-id]',\n ) ?? [],\n ).find(\n (element) =>\n element.getAttribute('data-kanban-card-drag-id') === focusCardDragId,\n )\n\n if (!card) return\n card.focus({ preventScroll: true })\n card.scrollIntoView({\n behavior: 'instant',\n block: 'nearest',\n inline: 'nearest',\n })\n handleCardFocusRestored()\n })\n\n return () => cancelAnimationFrame(frame)\n }, [focusCardDragId, handleCardFocusRestored])\n\n return (\n <div\n aria-busy={loading ? 'true' : undefined}\n className=\"h-full min-h-0\"\n data-slot=\"kanban-view\"\n >\n <DragDropProvider\n onDragEnd={handleDragEnd}\n onDragOver={handleDragOver}\n onDragStart={handleDragStart}\n >\n <div className=\"flex h-full min-h-0 flex-col gap-2\">\n <KanbanColumnSelector\n columns={columnOptions}\n onValueChange={setActiveColumnId}\n value={activeColumnId}\n {...(mobileColumnHint ? { hint: mobileColumnHint } : {})}\n />\n\n <div className=\"grid min-h-0 flex-1 gap-2 md:hidden\">\n {activeColumn ? (\n <KanbanColumn\n column={activeColumn}\n {...columnProps}\n sortableCards={false}\n {...getColumnActionProps(activeColumn)}\n />\n ) : null}\n </div>\n\n <ScrollArea\n className={cn(\n 'hidden min-h-0 flex-1 md:block',\n '[&_[data-orientation=horizontal][data-slot=scroll-area-scrollbar]]:!delay-0',\n showHorizontalScrollbar\n ? '[&_[data-orientation=horizontal][data-slot=scroll-area-scrollbar]]:!opacity-100'\n : '[&_[data-orientation=horizontal][data-slot=scroll-area-scrollbar]]:!pointer-events-none [&_[data-orientation=horizontal][data-slot=scroll-area-scrollbar]]:!opacity-0',\n cardDragEnabled\n ? '[&_[data-slot=scroll-area-viewport]]:cursor-grab [&_[data-slot=scroll-area-viewport]]:select-none'\n : '[&_[data-slot=scroll-area-viewport]]:cursor-default',\n showHorizontalScrollbar &&\n '[&_[data-slot=scroll-area-viewport]]:cursor-grabbing',\n )}\n data-kanban-board-scroll-area=\"\"\n data-kanban-horizontal-scrollbar={\n showHorizontalScrollbar ? 'visible' : 'hidden'\n }\n fill\n ref={cardDragEnabled ? rootRef : undefined}\n scrollbarGutter\n scrollFade\n >\n <div\n className=\"flex h-full min-h-full w-max gap-2 [&>[data-slot=kanban-column]]:shrink-0 [&>[data-slot=kanban-column]:not([data-collapsed])]:w-76 xl:[&>[data-slot=kanban-column]:not([data-collapsed])]:w-88\"\n ref={boardContentRef}\n >\n {visibleColumns.map((column) => (\n <KanbanColumn\n column={column}\n key={column.id}\n {...columnProps}\n {...getColumnActionProps(column)}\n />\n ))}\n </div>\n </ScrollArea>\n </div>\n <DragOverlay className=\"pointer-events-none\" dropAnimation={null}>\n {(source) => {\n const card = cardsByDragId.get(String(source.id))\n return card ? renderCard(card) : null\n }}\n </DragOverlay>\n </DragDropProvider>\n </div>\n )\n}\n\nfunction createColumnOptions(\n columns: KanbanColumnData[],\n): KanbanColumnOption[] {\n return columns.map((column) => ({\n label: `${column.title} · ${column.count}`,\n value: column.id,\n }))\n}\n",
|
|
693
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/components/kanban-view.tsx"
|
|
694
|
-
},
|
|
695
|
-
{
|
|
696
|
-
"path": "parttens/src/collection-views/views/kanban/components/sortable-kanban-card.tsx",
|
|
697
|
-
"type": "registry:file",
|
|
698
|
-
"content": "import { pointerIntersection } from '@dnd-kit/collision'\nimport {\n KeyboardSensor,\n PointerActivationConstraints,\n PointerSensor,\n} from '@dnd-kit/dom'\nimport { useSortable } from '@dnd-kit/react/sortable'\nimport { cn } from '@tc96/utils'\nimport { GripVerticalIcon } from 'lucide-react'\nimport type { ReactNode } from 'react'\n\nconst OWN_GESTURE_TARGETS = [\n 'input:not([disabled])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n 'button:not([disabled]):not([data-slot=\"kanban-card-open-trigger\"])',\n 'a[href]',\n '[contenteditable]:not([contenteditable=\"false\"])',\n '[role=\"button\"]',\n '[role=\"checkbox\"]',\n '[role=\"combobox\"]',\n '[role=\"menuitem\"]',\n '[role=\"option\"]',\n '[role=\"slider\"]',\n '[role=\"switch\"]',\n].join(',')\n\nconst KANBAN_CARD_SENSORS = [\n PointerSensor.configure({\n activatorElements: (source) => [source.element],\n preventActivation: (event, source) =>\n event.target instanceof Element &&\n !source.handle?.contains(event.target) &&\n event.target.closest(OWN_GESTURE_TARGETS) !== null,\n activationConstraints: (event) =>\n event.pointerType === 'touch'\n ? [new PointerActivationConstraints.Delay({ value: 250, tolerance: 5 })]\n : [new PointerActivationConstraints.Distance({ value: 5 })],\n }),\n KeyboardSensor.configure({\n keyboardCodes: {\n cancel: ['Escape'],\n down: ['ArrowDown'],\n end: ['Space', 'Tab'],\n left: ['ArrowLeft'],\n right: ['ArrowRight'],\n start: ['Space'],\n up: ['ArrowUp'],\n },\n }),\n]\n\ninterface SortableKanbanCardProps {\n children: ReactNode\n columnId: string\n dragLabel: string\n id: string\n index: number\n}\n\nexport function SortableKanbanCard({\n children,\n columnId,\n dragLabel,\n id,\n index,\n}: SortableKanbanCardProps) {\n const { handleRef, isDragSource, ref } = useSortable({\n accept: 'kanban-card',\n collisionDetector: pointerIntersection,\n data: { cardId: id, columnId, type: 'card' },\n group: columnId,\n id,\n index,\n sensors: KANBAN_CARD_SENSORS,\n transition: null,\n type: 'kanban-card',\n })\n\n return (\n <div\n className={cn(\n 'relative min-w-0 cursor-grab',\n isDragSource && 'opacity-0',\n )}\n data-kanban-card-container=\"\"\n data-kanban-card-draggable=\"\"\n ref={ref}\n >\n <button\n aria-label={dragLabel}\n className=\"absolute top-1 left-1 z-10 flex size-6 cursor-grab touch-none items-center justify-center rounded-md bg-card text-muted-foreground opacity-0 outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing\"\n data-kanban-card-drag-handle=\"\"\n data-kanban-card-drag-id={id}\n ref={handleRef}\n type=\"button\"\n >\n <GripVerticalIcon aria-hidden=\"true\" className=\"size-4\" />\n </button>\n {children}\n </div>\n )\n}\n",
|
|
699
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/components/sortable-kanban-card.tsx"
|
|
700
|
-
},
|
|
701
|
-
{
|
|
702
|
-
"path": "parttens/src/collection-views/views/kanban/hooks/use-active-column-id.ts",
|
|
703
|
-
"type": "registry:file",
|
|
704
|
-
"content": "import { useEffect, useState } from 'react'\n\nimport type { KanbanColumnData } from '../types'\n\nexport function useActiveColumnId(\n columns: KanbanColumnData[],\n): [string, (id: string) => void] {\n const [activeColumnId, setActiveColumnId] = useState(columns[0]?.id ?? '')\n\n useEffect(() => {\n if (!columns.some((column) => column.id === activeColumnId)) {\n setActiveColumnId(columns[0]?.id ?? '')\n }\n }, [activeColumnId, columns])\n\n return [activeColumnId, setActiveColumnId]\n}\n",
|
|
705
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/hooks/use-active-column-id.ts"
|
|
706
|
-
},
|
|
707
|
-
{
|
|
708
|
-
"path": "parttens/src/collection-views/views/kanban/hooks/use-horizontal-drag-scroll.ts",
|
|
709
|
-
"type": "registry:file",
|
|
710
|
-
"content": "import { useCallback, useEffect, useRef, useState } from 'react'\n\nconst DRAG_THRESHOLD = 8\nconst CLICK_SUPPRESSION_WINDOW_MS = 500\nconst EXCLUDED_TARGETS = [\n 'a',\n 'button',\n 'input',\n 'select',\n 'textarea',\n '[contenteditable=\"true\"]',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"menuitem\"]',\n '[role=\"option\"]',\n '[role=\"slider\"]',\n '[data-kanban-card-draggable]',\n '[data-slot=\"scroll-area-scrollbar\"]',\n].join(',')\n\ninterface DragOrigin {\n pointerId: number\n scrollLeft: number\n x: number\n y: number\n dragging: boolean\n}\n\ninterface ReleasedDrag {\n at: number\n x: number\n y: number\n}\n\nfunction isExcludedTarget(target: EventTarget | null): boolean {\n return target instanceof Element && target.closest(EXCLUDED_TARGETS) !== null\n}\n\nexport function useHorizontalDragScroll() {\n const dragOriginRef = useRef<DragOrigin | null>(null)\n const releasedDragRef = useRef<ReleasedDrag | null>(null)\n const [isDragging, setIsDragging] = useState(false)\n const [rootElement, setRootElement] = useState<HTMLDivElement | null>(null)\n\n const resetDrag = useCallback(() => {\n dragOriginRef.current = null\n setIsDragging(false)\n }, [])\n\n useEffect(() => {\n const viewport = rootElement?.querySelector<HTMLDivElement>(\n '[data-slot=\"scroll-area-viewport\"]',\n )\n if (!viewport) return\n\n const handlePointerDown = (event: PointerEvent) => {\n if (\n event.button !== 0 ||\n !event.isPrimary ||\n isExcludedTarget(event.target)\n )\n return\n\n releasedDragRef.current = null\n dragOriginRef.current = {\n dragging: false,\n pointerId: event.pointerId,\n scrollLeft: viewport.scrollLeft,\n x: event.clientX,\n y: event.clientY,\n }\n }\n\n const handlePointerMove = (event: PointerEvent) => {\n const origin = dragOriginRef.current\n if (!origin || origin.pointerId !== event.pointerId) return\n\n const deltaX = event.clientX - origin.x\n const deltaY = event.clientY - origin.y\n\n if (!origin.dragging) {\n if (\n Math.abs(deltaX) < DRAG_THRESHOLD &&\n Math.abs(deltaY) < DRAG_THRESHOLD\n )\n return\n if (Math.abs(deltaX) <= Math.abs(deltaY)) {\n dragOriginRef.current = null\n return\n }\n\n origin.dragging = true\n viewport.setPointerCapture?.(event.pointerId)\n setIsDragging(true)\n }\n\n event.preventDefault()\n const maximumScrollLeft = Math.max(\n 0,\n viewport.scrollWidth - viewport.clientWidth,\n )\n viewport.scrollLeft = Math.min(\n maximumScrollLeft,\n Math.max(0, origin.scrollLeft - deltaX),\n )\n }\n\n const handlePointerEnd = (event: PointerEvent) => {\n const origin = dragOriginRef.current\n if (!origin || origin.pointerId !== event.pointerId) return\n\n if (origin.dragging) {\n releasedDragRef.current = {\n at: Date.now(),\n x: event.clientX,\n y: event.clientY,\n }\n if (viewport.hasPointerCapture?.(event.pointerId)) {\n viewport.releasePointerCapture(event.pointerId)\n }\n }\n\n resetDrag()\n }\n\n const handleClickCapture = (event: MouseEvent) => {\n const releasedDrag = releasedDragRef.current\n if (!releasedDrag) return\n\n releasedDragRef.current = null\n const isReleasedDragClick =\n Date.now() - releasedDrag.at <= CLICK_SUPPRESSION_WINDOW_MS &&\n Math.abs(event.clientX - releasedDrag.x) <= 1 &&\n Math.abs(event.clientY - releasedDrag.y) <= 1\n\n if (isReleasedDragClick) {\n event.preventDefault()\n event.stopPropagation()\n }\n }\n\n viewport.addEventListener('click', handleClickCapture, true)\n viewport.addEventListener('lostpointercapture', resetDrag)\n viewport.addEventListener('pointercancel', handlePointerEnd)\n viewport.addEventListener('pointerdown', handlePointerDown)\n viewport.addEventListener('pointermove', handlePointerMove)\n viewport.addEventListener('pointerup', handlePointerEnd)\n\n return () => {\n resetDrag()\n viewport.removeEventListener('click', handleClickCapture, true)\n viewport.removeEventListener('lostpointercapture', resetDrag)\n viewport.removeEventListener('pointercancel', handlePointerEnd)\n viewport.removeEventListener('pointerdown', handlePointerDown)\n viewport.removeEventListener('pointermove', handlePointerMove)\n viewport.removeEventListener('pointerup', handlePointerEnd)\n }\n }, [resetDrag, rootElement])\n\n return {\n isDragging,\n rootRef: setRootElement,\n }\n}\n",
|
|
711
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/hooks/use-horizontal-drag-scroll.ts"
|
|
712
|
-
},
|
|
713
|
-
{
|
|
714
|
-
"path": "parttens/src/collection-views/views/kanban/hooks/use-kanban-drag-and-drop.ts",
|
|
715
|
-
"type": "registry:file",
|
|
716
|
-
"content": "import type {\n DragEndEvent,\n DragOverEvent,\n DragStartEvent,\n} from '@dnd-kit/react'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport {\n createCardDragId,\n findCardLocation,\n projectKanbanColumns,\n resolveKanbanCardMove,\n} from '../lib/drag-and-drop'\nimport type { KanbanCardMove, KanbanColumnData } from '../types'\n\ninterface UseKanbanDragAndDropOptions<TCard> {\n columns: KanbanColumnData<TCard>[]\n getKey: (card: TCard) => string | number\n onMoveCard?: (move: KanbanCardMove<TCard>) => boolean | Promise<boolean>\n}\n\ninterface PendingCardMove {\n accepted: boolean\n cardDragId: string\n requestId: number\n targetColumnId: string\n targetIndex?: number\n}\n\nexport function useKanbanDragAndDrop<TCard>({\n columns,\n getKey,\n onMoveCard,\n}: UseKanbanDragAndDropOptions<TCard>) {\n const [optimisticColumns, setOptimisticColumns] = useState<\n KanbanColumnData<TCard>[] | null\n >(null)\n const [focusCardDragId, setFocusCardDragId] = useState<string | null>(null)\n const columnsRef = useRef(columns)\n const optimisticColumnsRef = useRef<KanbanColumnData<TCard>[] | null>(null)\n const dragSourceColumnsRef = useRef<KanbanColumnData<TCard>[] | null>(null)\n const rollbackSourceColumnsRef = useRef<KanbanColumnData<TCard>[] | null>(\n null,\n )\n const pendingCardMoveRef = useRef<PendingCardMove | null>(null)\n const moveRequestIdRef = useRef(0)\n columnsRef.current = columns\n\n const getCardDragId = useCallback(\n (card: TCard) => createCardDragId(getKey(card)),\n [getKey],\n )\n const updateOptimisticColumns = useCallback(\n (nextColumns: KanbanColumnData<TCard>[] | null) => {\n if (optimisticColumnsRef.current === nextColumns) return\n optimisticColumnsRef.current = nextColumns\n setOptimisticColumns(nextColumns)\n },\n [],\n )\n\n useEffect(() => {\n const rollbackSourceColumns = rollbackSourceColumnsRef.current\n if (rollbackSourceColumns && columns !== rollbackSourceColumns) {\n rollbackSourceColumnsRef.current = null\n updateOptimisticColumns(null)\n return\n }\n\n const pendingCardMove = pendingCardMoveRef.current\n if (!pendingCardMove?.accepted) return\n if (!isPendingCardMoveConfirmed(columns, pendingCardMove, getCardDragId))\n return\n\n pendingCardMoveRef.current = null\n updateOptimisticColumns(null)\n }, [columns, getCardDragId, updateOptimisticColumns])\n\n const handleDragStart = useCallback((_event: DragStartEvent) => {\n setFocusCardDragId(null)\n dragSourceColumnsRef.current =\n optimisticColumnsRef.current ?? columnsRef.current\n }, [])\n const handleCardFocusRestored = useCallback(\n () => setFocusCardDragId(null),\n [],\n )\n\n const handleDragOver = useCallback(\n (event: DragOverEvent) => {\n const { source, target } = event.operation\n const { type: sourceType } = source?.data ?? {}\n const { columnId: targetColumnId, type: targetType } = target?.data ?? {}\n\n if (!onMoveCard || !source || sourceType !== 'card') return\n\n const visibleColumns =\n optimisticColumnsRef.current ??\n dragSourceColumnsRef.current ??\n columnsRef.current\n\n if (targetType === 'card') {\n const sourceLocation = findCardLocation(\n visibleColumns,\n String(source.id),\n getCardDragId,\n )\n // Na mesma coluna o plugin otimista do dnd-kit reordena o DOM sem\n // render. Entre colunas o no mudaria de pai por fora do React, que\n // depois falharia ao remove-lo (removeChild); por isso o plugin e\n // impedido e a troca de coluna passa pelo estado.\n if (!sourceLocation || sourceLocation.columnId === targetColumnId)\n return\n event.preventDefault()\n } else if (targetType !== 'column') {\n return\n }\n const projectedColumns = projectKanbanColumns(\n visibleColumns,\n event,\n getCardDragId,\n )\n\n if (projectedColumns !== visibleColumns)\n updateOptimisticColumns(projectedColumns)\n },\n [getCardDragId, onMoveCard, updateOptimisticColumns],\n )\n\n const handleDragEnd = useCallback(\n (event: DragEndEvent) => {\n const sourceColumns = dragSourceColumnsRef.current ?? columnsRef.current\n dragSourceColumnsRef.current = null\n\n if (event.canceled) {\n if (!pendingCardMoveRef.current) updateOptimisticColumns(null)\n return\n }\n\n const visibleColumns = optimisticColumnsRef.current ?? sourceColumns\n const projectedColumns = projectKanbanColumns(\n visibleColumns,\n event,\n getCardDragId,\n )\n const move = resolveKanbanCardMove(\n sourceColumns,\n projectedColumns,\n event,\n getCardDragId,\n )\n\n if (!move || !onMoveCard) {\n if (!pendingCardMoveRef.current) updateOptimisticColumns(null)\n return\n }\n\n if (move.sourceColumnId !== move.targetColumnId) {\n setFocusCardDragId(String(event.operation.source?.id))\n }\n updateOptimisticColumns(projectedColumns)\n rollbackSourceColumnsRef.current = null\n const requestId = moveRequestIdRef.current + 1\n moveRequestIdRef.current = requestId\n pendingCardMoveRef.current = {\n accepted: false,\n cardDragId: String(event.operation.source?.id),\n requestId,\n targetColumnId: move.targetColumnId,\n ...(move.targetIndex === undefined\n ? {}\n : { targetIndex: move.targetIndex }),\n }\n const suspension = event.suspend()\n\n const settleCardMove = (accepted: boolean, settleSuspension: boolean) => {\n const pendingCardMove = pendingCardMoveRef.current\n if (!pendingCardMove || pendingCardMove.requestId !== requestId) return\n\n if (!accepted) {\n pendingCardMoveRef.current = null\n if (settleSuspension) suspension.abort()\n rollbackSourceColumnsRef.current = sourceColumns\n updateOptimisticColumns(cloneColumnOrder(sourceColumns))\n return\n }\n\n pendingCardMove.accepted = true\n if (settleSuspension) suspension.resume()\n if (\n !isPendingCardMoveConfirmed(\n columnsRef.current,\n pendingCardMove,\n getCardDragId,\n )\n )\n return\n\n pendingCardMoveRef.current = null\n updateOptimisticColumns(null)\n }\n\n try {\n const moveAccepted = onMoveCard(move)\n\n if (isPromiseLike(moveAccepted)) {\n // Holding a suspended operation across network latency keeps the\n // drag feedback active after pointer-up. Finish the native drop now;\n // the optimistic columns below own cache reconciliation only.\n suspension.resume()\n void Promise.resolve(moveAccepted).then(\n (accepted) => settleCardMove(accepted, false),\n () => settleCardMove(false, false),\n )\n } else {\n settleCardMove(moveAccepted, true)\n }\n } catch {\n settleCardMove(false, true)\n }\n },\n [getCardDragId, onMoveCard, updateOptimisticColumns],\n )\n\n return {\n cardDragEnabled: Boolean(onMoveCard),\n focusCardDragId,\n getCardDragId,\n handleCardFocusRestored,\n handleDragEnd,\n handleDragOver,\n handleDragStart,\n visibleColumns: optimisticColumns ?? columns,\n }\n}\n\nfunction isPendingCardMoveConfirmed<TCard>(\n columns: KanbanColumnData<TCard>[],\n pendingCardMove: PendingCardMove,\n getCardDragId: (card: TCard) => string,\n): boolean {\n const cardLocation = findCardLocation(\n columns,\n pendingCardMove.cardDragId,\n getCardDragId,\n )\n\n return (\n cardLocation?.columnId === pendingCardMove.targetColumnId &&\n (pendingCardMove.targetIndex === undefined ||\n cardLocation.cardIndex === pendingCardMove.targetIndex)\n )\n}\n\nfunction isPromiseLike(\n value: boolean | Promise<boolean>,\n): value is Promise<boolean> {\n return typeof value === 'object' && value !== null && 'then' in value\n}\n\nfunction cloneColumnOrder<TCard>(\n columns: KanbanColumnData<TCard>[],\n): KanbanColumnData<TCard>[] {\n return columns.map((column) => ({ ...column, cards: [...column.cards] }))\n}\n",
|
|
717
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/hooks/use-kanban-drag-and-drop.ts"
|
|
718
|
-
},
|
|
719
|
-
{
|
|
720
|
-
"path": "parttens/src/collection-views/views/kanban/index.ts",
|
|
721
|
-
"type": "registry:file",
|
|
722
|
-
"content": "export type { KanbanBadgeProps } from './components/kanban-badge'\nexport { KanbanBadge } from './components/kanban-badge'\nexport type {\n KanbanCardActionButtonProps,\n KanbanCardActionProps,\n KanbanCardBodyProps,\n KanbanCardBodyRowProps,\n KanbanCardContentProps,\n KanbanCardDescriptionProps,\n KanbanCardDisplay,\n KanbanCardFooterProps,\n KanbanCardHeaderProps,\n KanbanCardOpenTriggerProps,\n KanbanCardProps,\n KanbanCardTitleProps,\n} from './components/kanban-card'\nexport {\n KanbanCard,\n KanbanCardAction,\n KanbanCardActionButton,\n KanbanCardBody,\n KanbanCardBodyRow,\n KanbanCardContent,\n KanbanCardDescription,\n KanbanCardFooter,\n KanbanCardHeader,\n KanbanCardOpenTrigger,\n KanbanCardTitle,\n kanbanCardVariants,\n} from './components/kanban-card'\nexport type { KanbanCardSkeletonProps } from './components/kanban-card-skeleton'\nexport { KanbanCardSkeleton } from './components/kanban-card-skeleton'\nexport type { KanbanColumnProps } from './components/kanban-column'\nexport { KanbanColumn } from './components/kanban-column'\nexport type { KanbanColumnSelectorProps } from './components/kanban-column-selector'\nexport { KanbanColumnSelector } from './components/kanban-column-selector'\nexport type { KanbanViewProps } from './components/kanban-view'\nexport { KanbanView } from './components/kanban-view'\nexport { useActiveColumnId } from './hooks/use-active-column-id'\nexport type {\n KanbanCardMove,\n KanbanColumnActions,\n KanbanColumnData,\n KanbanColumnOption,\n} from './types'\n",
|
|
723
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/index.ts"
|
|
724
|
-
},
|
|
725
|
-
{
|
|
726
|
-
"path": "parttens/src/collection-views/views/kanban/lib/drag-and-drop.ts",
|
|
727
|
-
"type": "registry:file",
|
|
728
|
-
"content": "import { move } from '@dnd-kit/helpers'\nimport type { DragEndEvent, DragOverEvent } from '@dnd-kit/react'\n\nimport type { KanbanCardMove, KanbanColumnData } from '../types'\n\nconst CARD_DRAG_PREFIX = 'kanban-card:'\nconst COLUMN_DROP_PREFIX = 'kanban-column:'\n\ntype DragIdentifier = string | number\ntype KanbanDragEvent = DragEndEvent | DragOverEvent\n\ninterface ProjectedCard<TCard> {\n card: TCard\n id: string\n}\n\nexport interface CardLocation<TCard> {\n card: TCard\n cardIndex: number\n columnId: string\n columnIndex: number\n}\n\nexport function createCardDragId(cardId: DragIdentifier): string {\n return `${CARD_DRAG_PREFIX}${String(cardId)}`\n}\n\nexport function parseCardDragId(id: DragIdentifier): string {\n return String(id).replace(new RegExp(`^${CARD_DRAG_PREFIX}`), '')\n}\n\nexport function createColumnDropId(\n columnId: string,\n instanceId?: string,\n): string {\n const columnPart = encodeURIComponent(columnId)\n const instancePart = instanceId ? `:${encodeURIComponent(instanceId)}` : ''\n\n return `${COLUMN_DROP_PREFIX}${columnPart}${instancePart}`\n}\n\nexport function parseColumnId(id: DragIdentifier): string {\n const value = String(id)\n\n if (!value.startsWith(COLUMN_DROP_PREFIX)) return ''\n\n const encodedColumnId =\n value.slice(COLUMN_DROP_PREFIX.length).split(':', 1)[0] ?? ''\n\n try {\n return decodeURIComponent(encodedColumnId)\n } catch {\n return encodedColumnId\n }\n}\n\nexport function findCardLocation<TCard>(\n columns: KanbanColumnData<TCard>[],\n cardDragId: string,\n getCardDragId: (card: TCard) => DragIdentifier,\n): CardLocation<TCard> | undefined {\n for (const [columnIndex, column] of columns.entries()) {\n const cardIndex = column.cards.findIndex(\n (card) => String(getCardDragId(card)) === cardDragId,\n )\n\n if (cardIndex !== -1) {\n const card = column.cards[cardIndex]\n if (card === undefined) continue\n\n return {\n card,\n cardIndex,\n columnId: column.id,\n columnIndex,\n }\n }\n }\n}\n\n/**\n * Projects the consumer's columns with dnd-kit's official `move` helper.\n * Sortable cards use the indices and groups maintained by the library. A plain\n * column target only adapts the instance-scoped droppable id to the logical\n * column id, which is the additional case required for empty lists.\n */\nexport function projectKanbanColumns<TCard>(\n columns: KanbanColumnData<TCard>[],\n event: KanbanDragEvent,\n getCardDragId: (card: TCard) => DragIdentifier,\n): KanbanColumnData<TCard>[] {\n const target = event.operation.target\n const { columnId, type: targetType } = target?.data ?? {}\n const targetColumnId =\n targetType === 'column' && typeof columnId === 'string'\n ? columnId\n : undefined\n const collectionKeys = new Map<string, string>()\n const collections = Object.fromEntries(\n columns.map((column) => {\n const collectionKey =\n column.id === targetColumnId && target ? String(target.id) : column.id\n collectionKeys.set(column.id, collectionKey)\n\n return [\n collectionKey,\n column.cards.map((card) => ({ card, id: String(getCardDragId(card)) })),\n ]\n }),\n ) as Record<string, ProjectedCard<TCard>[]>\n const projectedCollections = move(collections, event)\n\n if (projectedCollections === collections) return columns\n\n let changed = false\n const projectedColumns = columns.map((column) => {\n const collectionKey = collectionKeys.get(column.id)\n const projectedCards = collectionKey\n ? projectedCollections[collectionKey]?.map(({ card }) => card)\n : undefined\n\n if (\n !projectedCards ||\n hasSameCardOrder(column.cards, projectedCards, getCardDragId)\n ) {\n return column\n }\n\n changed = true\n return { ...column, cards: projectedCards, count: projectedCards.length }\n })\n\n return changed ? projectedColumns : columns\n}\n\nexport function resolveKanbanCardMove<TCard>(\n sourceColumns: KanbanColumnData<TCard>[],\n projectedColumns: KanbanColumnData<TCard>[],\n event: DragEndEvent,\n getCardDragId: (card: TCard) => DragIdentifier,\n): KanbanCardMove<TCard> | undefined {\n const source = event.operation.source\n const { type: sourceType } = source?.data ?? {}\n\n if (event.canceled || !source || sourceType !== 'card') return undefined\n\n const cardDragId = String(source.id)\n const sourceLocation = findCardLocation(\n sourceColumns,\n cardDragId,\n getCardDragId,\n )\n const targetLocation = findCardLocation(\n projectedColumns,\n cardDragId,\n getCardDragId,\n )\n\n if (\n !sourceLocation ||\n !targetLocation ||\n (sourceLocation.columnId === targetLocation.columnId &&\n sourceLocation.cardIndex === targetLocation.cardIndex)\n ) {\n return undefined\n }\n\n return {\n card: sourceLocation.card,\n cardId: parseCardDragId(cardDragId),\n sourceColumnId: sourceLocation.columnId,\n sourceIndex: sourceLocation.cardIndex,\n targetColumnId: targetLocation.columnId,\n targetIndex: targetLocation.cardIndex,\n }\n}\n\nfunction hasSameCardOrder<TCard>(\n currentCards: TCard[],\n projectedCards: TCard[],\n getCardDragId: (card: TCard) => DragIdentifier,\n): boolean {\n return (\n currentCards.length === projectedCards.length &&\n currentCards.every((card, index) => {\n const projectedCard = projectedCards[index]\n return (\n projectedCard !== undefined &&\n String(getCardDragId(card)) === String(getCardDragId(projectedCard))\n )\n })\n )\n}\n",
|
|
729
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/lib/drag-and-drop.ts"
|
|
730
|
-
},
|
|
731
|
-
{
|
|
732
|
-
"path": "parttens/src/collection-views/views/kanban/types.ts",
|
|
733
|
-
"type": "registry:file",
|
|
734
|
-
"content": "export interface KanbanColumnData<TCard = unknown> {\n id: string\n title: string\n count: number\n cards: TCard[]\n /** CSS color used for the column marker and its tinted surface. */\n color?: string\n /** Presentation state controlled by the consumer. */\n collapsed?: boolean\n /** Hidden columns remain in consumer data so view settings can restore them. */\n hidden?: boolean\n}\n\nexport interface KanbanColumnActions {\n /** Accessible label for the add action. Defaults to a label containing the column title. */\n addLabel?: string\n /** Accessible label for the settings action. Defaults to a label containing the column title. */\n settingsLabel?: string\n onAddCard?: (columnId: string) => void\n onOpenSettings?: (columnId: string) => void\n}\n\nexport interface KanbanCardMove<TCard = unknown> {\n card: TCard\n cardId: string\n /** Column containing the card when the interaction started. */\n sourceColumnId: string\n /** Original zero-based position in the source column. */\n sourceIndex?: number\n /** Destination column; equal to sourceColumnId for an in-column reorder. */\n targetColumnId: string\n /** Requested zero-based position for consumer-owned persistence. */\n targetIndex?: number\n}\n\nexport interface KanbanColumnOption {\n label: string\n value: string\n}\n",
|
|
735
|
-
"target": "~/packages/patterns/src/collection-views/views/kanban/types.ts"
|
|
736
|
-
},
|
|
737
|
-
{
|
|
738
|
-
"path": "parttens/src/collection-views/views/list/components/list-group.tsx",
|
|
739
|
-
"type": "registry:file",
|
|
740
|
-
"content": "import { Badge } from '@tc96/ui/badge'\nimport { Button } from '@tc96/ui/button'\nimport {\n Collapsible,\n CollapsiblePanel,\n CollapsibleTrigger,\n} from '@tc96/ui/collapsible'\nimport { Empty, EmptyDescription } from '@tc96/ui/empty'\nimport { Separator } from '@tc96/ui/separator'\nimport { ChevronDownIcon, ChevronRightIcon, PlusIcon } from 'lucide-react'\nimport { Fragment, type ReactNode, useId } from 'react'\nimport type { CollectionGroup } from '../../../types/collection'\nimport { ListItemSkeleton } from './list-item-skeleton'\nimport { ListViewItem } from './list-view-item'\n\nexport interface ListGroupActions {\n addLabel?: string\n onAddItem?: (groupId: string) => void\n}\n\nexport interface ListGroupProps<TItem> {\n actions?: ListGroupActions\n collapsed: boolean\n separated?: boolean\n emptyLabel: ReactNode\n group: CollectionGroup<TItem>\n onCollapsedChange: (collapsed: boolean) => void\n renderItem: (item: TItem) => ReactNode\n renderGroupTitle?: (group: CollectionGroup<TItem>) => ReactNode\n getKey: (item: TItem) => string | number\n loading?: boolean\n loadingItemCount?: number\n loadingItemLabel?: string\n}\n\nexport function ListGroup<TItem>({\n actions,\n collapsed,\n separated = false,\n emptyLabel,\n getKey,\n group,\n loading = false,\n loadingItemCount = 1,\n loadingItemLabel,\n onCollapsedChange,\n renderGroupTitle,\n renderItem,\n}: ListGroupProps<TItem>) {\n const instanceId = useId()\n const titleId = `list-group-title-${instanceId}`\n const groupLabel = typeof group.label === 'string' ? group.label : group.id\n const loadingItems = Array.from(\n { length: loadingItemCount },\n (_, position) => ({\n id: `${group.id}-loading-${position + 1}`,\n }),\n )\n\n return (\n <Collapsible\n onOpenChange={(open) => onCollapsedChange(!open)}\n open={!collapsed}\n >\n <section\n aria-labelledby={titleId}\n className=\"flex flex-col gap-0.5\"\n data-slot=\"list-group\"\n >\n <div\n className=\"flex min-h-9 items-center justify-between rounded-lg bg-card/90 px-1\"\n data-slot=\"list-group-header\"\n >\n <div className=\"flex min-w-0 items-center gap-1\">\n <CollapsibleTrigger\n render={\n <Button\n aria-label={`${collapsed ? 'Expand' : 'Collapse'} ${groupLabel}`}\n size=\"icon-sm\"\n variant=\"ghost\"\n />\n }\n >\n {collapsed ? (\n <ChevronRightIcon aria-hidden=\"true\" />\n ) : (\n <ChevronDownIcon aria-hidden=\"true\" />\n )}\n </CollapsibleTrigger>\n {renderGroupTitle ? null : (\n <span className=\"flex size-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-4\">\n {group.icon}\n </span>\n )}\n <h2 className=\"truncate font-medium text-sm\" id={titleId}>\n {renderGroupTitle?.(group) ?? group.label}\n </h2>\n <Badge\n className=\"size-5 min-w-5 shrink-0 rounded-full p-0 text-xs tabular-nums sm:size-5 sm:min-w-5\"\n data-slot=\"list-group-count\"\n variant=\"secondary\"\n >\n {group.count}\n </Badge>\n </div>\n {!loading && actions?.onAddItem ? (\n <Button\n aria-label={actions.addLabel ?? `Add item to ${groupLabel}`}\n onClick={() => actions.onAddItem?.(group.id)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <PlusIcon aria-hidden=\"true\" />\n </Button>\n ) : null}\n </div>\n <CollapsiblePanel>\n <div className=\"flex flex-col\" data-slot=\"list-group-items\">\n {loading ? (\n loadingItems.map((item) => (\n <ListItemSkeleton\n key={item.id}\n {...(loadingItemLabel ? { label: loadingItemLabel } : {})}\n />\n ))\n ) : group.items.length ? (\n group.items.map((item, position) => (\n <Fragment key={getKey(item)}>\n {separated && position > 0 ? (\n <Separator className=\"bg-border/40\" />\n ) : null}\n <ListViewItem item={item} renderItem={renderItem} />\n </Fragment>\n ))\n ) : (\n <Empty>\n <EmptyDescription>{emptyLabel}</EmptyDescription>\n </Empty>\n )}\n </div>\n </CollapsiblePanel>\n </section>\n </Collapsible>\n )\n}\n",
|
|
741
|
-
"target": "~/packages/patterns/src/collection-views/views/list/components/list-group.tsx"
|
|
742
|
-
},
|
|
743
|
-
{
|
|
744
|
-
"path": "parttens/src/collection-views/views/list/components/list-item-skeleton.tsx",
|
|
745
|
-
"type": "registry:file",
|
|
746
|
-
"content": "import { Skeleton } from '@tc96/ui/skeleton'\nimport type { ReactElement } from 'react'\nimport {\n ListItem,\n ListItemBody,\n ListItemLeading,\n ListItemTrailing,\n} from './list-item'\n\nexport interface ListItemSkeletonProps {\n label?: string\n}\n\nexport function ListItemSkeleton({\n label = 'Loading item',\n}: ListItemSkeletonProps): ReactElement {\n // `article` não pode ser `status`: um `output`, que já é status, envolve\n // o item sem caixa própria, e o item fica oculto da tecnologia assistiva.\n return (\n <output aria-busy=\"true\" aria-label={label} className=\"contents\">\n <ListItem aria-hidden=\"true\">\n <ListItemLeading aria-hidden=\"true\">\n <Skeleton className=\"size-4 rounded-sm\" />\n </ListItemLeading>\n <ListItemBody aria-hidden=\"true\">\n <Skeleton className=\"h-4 w-1/3\" />\n <Skeleton className=\"h-3 w-1/2\" />\n </ListItemBody>\n <ListItemTrailing aria-hidden=\"true\">\n <div className=\"hidden items-center gap-2 md:flex\">\n <Skeleton className=\"h-6 w-20 rounded-full\" />\n <Skeleton className=\"h-6 w-16 rounded-full\" />\n <Skeleton className=\"h-6 w-24 rounded-full\" />\n <Skeleton className=\"h-6 w-10 rounded-md\" />\n <Skeleton className=\"size-6 rounded-full\" />\n </div>\n <Skeleton className=\"size-7 rounded-md\" />\n </ListItemTrailing>\n </ListItem>\n </output>\n )\n}\n",
|
|
747
|
-
"target": "~/packages/patterns/src/collection-views/views/list/components/list-item-skeleton.tsx"
|
|
748
|
-
},
|
|
749
|
-
{
|
|
750
|
-
"path": "parttens/src/collection-views/views/list/components/list-item.tsx",
|
|
751
|
-
"type": "registry:file",
|
|
752
|
-
"content": "import { cn } from '@tc96/utils'\nimport {\n type ComponentPropsWithoutRef,\n createContext,\n type ReactElement,\n useContext,\n} from 'react'\n\nexport const ListItemHeadingLevelContext = createContext<2 | 3>(3)\n\nexport type ListItemDensity = 'comfortable' | 'compact'\n\nexport interface ListItemProps extends ComponentPropsWithoutRef<'article'> {\n density?: ListItemDensity\n interactive?: boolean\n}\nexport type ListItemActionProps = ComponentPropsWithoutRef<'div'>\nexport type ListItemBodyProps = ComponentPropsWithoutRef<'div'>\nexport type ListItemContentProps = ComponentPropsWithoutRef<'div'>\nexport type ListItemDescriptionProps = ComponentPropsWithoutRef<'span'>\nexport interface ListItemFieldProps extends ComponentPropsWithoutRef<'div'> {\n always?: boolean\n}\nexport type ListItemFooterProps = ComponentPropsWithoutRef<'footer'>\nexport type ListItemHeaderProps = ComponentPropsWithoutRef<'header'>\nexport type ListItemLeadingProps = ComponentPropsWithoutRef<'div'>\nexport type ListItemTitleProps = ComponentPropsWithoutRef<'h3'>\nexport type ListItemTitleTriggerProps = ComponentPropsWithoutRef<'button'>\nexport type ListItemTrailingProps = ComponentPropsWithoutRef<'div'>\n\nexport function ListItem({\n className,\n density = 'comfortable',\n interactive = true,\n ...props\n}: ListItemProps): ReactElement {\n return (\n <article\n className={cn(\n 'flex min-h-9 min-w-0 items-center gap-3 overflow-hidden rounded-lg px-2',\n density === 'compact' ? 'py-1' : 'py-1.5',\n interactive && 'hover:bg-muted/50',\n className,\n )}\n data-density={density}\n data-interactive={interactive ? '' : undefined}\n data-slot=\"list-item\"\n {...props}\n />\n )\n}\n\nexport function ListItemHeader({\n className,\n ...props\n}: ListItemHeaderProps): ReactElement {\n return (\n <header\n className={cn('flex min-w-0 flex-1 items-center gap-2', className)}\n data-slot=\"list-item-header\"\n {...props}\n />\n )\n}\n\nexport function ListItemLeading({\n className,\n ...props\n}: ListItemLeadingProps): ReactElement {\n return (\n <div\n className={cn('flex shrink-0 items-center gap-1', className)}\n data-slot=\"list-item-leading\"\n {...props}\n />\n )\n}\n\nexport function ListItemBody({\n className,\n ...props\n}: ListItemBodyProps): ReactElement {\n return (\n <div\n className={cn('flex flex-col min-w-0 flex-1', className)}\n data-slot=\"list-item-body\"\n {...props}\n />\n )\n}\n\nexport function ListItemTitle({\n className,\n ...props\n}: ListItemTitleProps): ReactElement {\n const Heading = useContext(ListItemHeadingLevelContext) === 2 ? 'h2' : 'h3'\n\n return (\n <Heading\n className={cn('min-w-0 truncate font-medium text-sm', className)}\n data-slot=\"list-item-title\"\n {...props}\n />\n )\n}\n\nexport function ListItemTitleTrigger({\n className,\n ...props\n}: ListItemTitleTriggerProps): ReactElement {\n return (\n <button\n className={cn('min-w-0 truncate text-start', className)}\n data-slot=\"list-item-title-trigger\"\n type=\"button\"\n {...props}\n />\n )\n}\n\nexport function ListItemDescription({\n className,\n ...props\n}: ListItemDescriptionProps): ReactElement {\n return (\n <span\n className={cn(\n 'min-w-0 truncate text-muted-foreground text-sm',\n className,\n )}\n data-slot=\"list-item-description\"\n {...props}\n />\n )\n}\n\nexport function ListItemContent({\n className,\n ...props\n}: ListItemContentProps): ReactElement {\n return (\n <div\n className={cn(\n 'flex min-w-0 flex-1 items-center gap-1 truncate text-muted-foreground text-sm',\n className,\n )}\n data-slot=\"list-item-content\"\n {...props}\n />\n )\n}\n\nexport function ListItemFooter({\n className,\n ...props\n}: ListItemFooterProps): ReactElement {\n return (\n <footer\n className={cn(\n 'ms-auto flex shrink-0 items-center gap-2 text-muted-foreground text-sm tabular-nums',\n className,\n )}\n data-slot=\"list-item-footer\"\n {...props}\n />\n )\n}\n\nexport function ListItemTrailing({\n className,\n ...props\n}: ListItemTrailingProps): ReactElement {\n return (\n <div\n className={cn('ms-auto flex shrink-0 items-center gap-2', className)}\n data-slot=\"list-item-trailing\"\n {...props}\n />\n )\n}\n\nexport function ListItemField({\n always = false,\n className,\n ...props\n}: ListItemFieldProps): ReactElement {\n return (\n <div\n className={cn(\n 'shrink-0 items-center',\n always ? 'flex' : 'hidden lg:flex',\n className,\n )}\n data-slot=\"list-item-field\"\n {...props}\n />\n )\n}\n\nexport function ListItemAction({\n className,\n ...props\n}: ListItemActionProps): ReactElement {\n return (\n <div\n className={cn('flex shrink-0 items-center', className)}\n data-slot=\"list-item-action\"\n {...props}\n />\n )\n}\n",
|
|
753
|
-
"target": "~/packages/patterns/src/collection-views/views/list/components/list-item.tsx"
|
|
754
|
-
},
|
|
755
|
-
{
|
|
756
|
-
"path": "parttens/src/collection-views/views/list/components/list-row.tsx",
|
|
757
|
-
"type": "registry:file",
|
|
758
|
-
"content": "import { IconFrame, type IconFrameProps } from '@tc96/elements/icon-frame'\nimport { Text } from '@tc96/elements/text'\nimport { cn } from '@tc96/utils'\nimport {\n Children,\n Fragment,\n isValidElement,\n type MouseEventHandler,\n type ReactElement,\n type ReactNode,\n} from 'react'\n\nimport { interactiveDescendants } from '../../../shared/lib/interactive-descendants'\nimport {\n ListItem,\n ListItemAction,\n ListItemBody,\n ListItemDescription,\n ListItemField,\n ListItemLeading,\n type ListItemProps,\n ListItemTitle,\n ListItemTitleTrigger,\n ListItemTrailing,\n} from './list-item'\n\nexport type ListRowIconFrame = Pick<\n IconFrameProps,\n 'color' | 'shape' | 'size' | 'variant'\n>\n\nexport interface ListRowProps extends Omit<ListItemProps, 'title'> {\n actions?: ReactNode\n description?: ReactNode | readonly ReactNode[]\n icon?: ReactNode\n iconFrame?: ListRowIconFrame\n onClick?: MouseEventHandler<HTMLButtonElement>\n openDisabled?: boolean\n openLabel?: string\n properties?: ReactNode\n title: ReactNode\n value?: ReactNode\n}\n\nfunction ListRowDescription({\n description,\n}: Readonly<{ description: ReactNode | readonly ReactNode[] }>) {\n const nodes = Children.toArray(description)\n\n if (nodes.length === 0) return null\n\n return (\n <ListItemDescription>\n {nodes.map((node, position) => (\n <Fragment\n key={isValidElement(node) ? node.key : `${position}:${String(node)}`}\n >\n {position > 0 ? (\n <span aria-hidden=\"true\" className=\"px-1\">\n ·\n </span>\n ) : null}\n {node}\n </Fragment>\n ))}\n </ListItemDescription>\n )\n}\n\nexport function ListRow({\n actions,\n className,\n description,\n icon,\n iconFrame,\n interactive,\n onClick,\n openDisabled,\n openLabel,\n properties,\n title,\n value,\n ...props\n}: ListRowProps): ReactElement {\n return (\n <ListItem\n className={cn('relative', className)}\n interactive={interactive ?? onClick !== undefined}\n {...props}\n >\n {icon ? (\n <ListItemLeading>\n <IconFrame shape=\"rounded\" {...iconFrame}>\n {icon}\n </IconFrame>\n </ListItemLeading>\n ) : null}\n <ListItemBody>\n <ListItemTitle>\n {onClick ? (\n <ListItemTitleTrigger\n aria-label={openLabel}\n disabled={openDisabled}\n className=\"outline-none after:absolute after:inset-0 after:rounded-[inherit] focus-visible:after:ring-2 focus-visible:after:ring-ring\"\n onClick={onClick}\n >\n {title}\n </ListItemTitleTrigger>\n ) : (\n title\n )}\n </ListItemTitle>\n {description ? <ListRowDescription description={description} /> : null}\n </ListItemBody>\n {value || properties || actions ? (\n <ListItemTrailing>\n {value ? (\n <Text className=\"tabular-nums\" size=\"sm\" truncate weight=\"medium\">\n {value}\n </Text>\n ) : null}\n {properties ? (\n <ListItemField\n always\n className={cn(\n 'relative z-10 pointer-events-none',\n interactiveDescendants,\n )}\n >\n {properties}\n </ListItemField>\n ) : null}\n {actions ? (\n <ListItemAction className=\"relative z-10\">{actions}</ListItemAction>\n ) : null}\n </ListItemTrailing>\n ) : null}\n </ListItem>\n )\n}\n",
|
|
759
|
-
"target": "~/packages/patterns/src/collection-views/views/list/components/list-row.tsx"
|
|
760
|
-
},
|
|
761
|
-
{
|
|
762
|
-
"path": "parttens/src/collection-views/views/list/components/list-view-item.tsx",
|
|
763
|
-
"type": "registry:file",
|
|
764
|
-
"content": "import { memo, type ReactNode } from 'react'\n\ninterface ListViewItemProps<TItem> {\n item: TItem\n renderItem: (item: TItem) => ReactNode\n}\n\nexport const ListViewItem = memo(function ListViewItem<TItem>({\n item,\n renderItem,\n}: ListViewItemProps<TItem>) {\n return renderItem(item)\n}) as <TItem>(props: ListViewItemProps<TItem>) => ReactNode\n",
|
|
765
|
-
"target": "~/packages/patterns/src/collection-views/views/list/components/list-view-item.tsx"
|
|
766
|
-
},
|
|
767
|
-
{
|
|
768
|
-
"path": "parttens/src/collection-views/views/list/components/list-view.tsx",
|
|
769
|
-
"type": "registry:file",
|
|
770
|
-
"content": "'use client'\n\nimport { Empty, EmptyDescription } from '@tc96/ui/empty'\nimport { Separator } from '@tc96/ui/separator'\nimport { Fragment, type ReactNode, useMemo, useState } from 'react'\n\nimport { projectCollection } from '../../../shared/lib/project-collection'\nimport { skeletonKeys } from '../../../shared/lib/skeleton-keys'\nimport type {\n CollectionDefinition,\n CollectionGroup,\n CollectionGroupingId,\n} from '../../../types/collection'\nimport { ListGroup, type ListGroupActions } from './list-group'\nimport { ListItemHeadingLevelContext } from './list-item'\nimport { ListItemSkeleton } from './list-item-skeleton'\nimport { ListViewItem } from './list-view-item'\n\nexport interface ListViewProps<TItem> {\n collection: CollectionDefinition<TItem>\n groups?: readonly CollectionGroup<TItem>[]\n collapsedGroupIds?: readonly string[]\n /**\n * Grupo sem itens nasce colapsado. A escolha manual da pessoa prevalece, e um\n * grupo que ganha itens volta a abrir sozinho enquanto ninguém o tocou.\n *\n * Ignorado quando `collapsedGroupIds` é passado: ali o array é a autoridade.\n */\n collapseEmptyGroups?: boolean\n defaultCollapsedGroupIds?: readonly string[]\n separated?: boolean\n emptyGroupLabel?: ReactNode | ((group: CollectionGroup<TItem>) => ReactNode)\n emptyMessage?: ReactNode\n getGroupActions?: (\n group: CollectionGroup<TItem>,\n ) => ListGroupActions | undefined\n /** `null` lê a coleção como uma lista plana, sem cabeçalho nem colapso. */\n grouping: CollectionGroupingId | null\n loading?: boolean\n /** Esqueletos por grupo — ou da lista inteira, quando não há agrupamento. */\n loadingItemCount?: number\n loadingItemLabel?: string\n onCollapsedGroupIdsChange?: (groupIds: readonly string[]) => void\n renderGroupTitle?: (group: CollectionGroup<TItem>) => ReactNode\n renderItem: (item: TItem) => ReactNode\n}\n\nexport function ListView<TItem>({\n collection,\n groups: preparedGroups,\n collapsedGroupIds: controlledCollapsedGroupIds,\n collapseEmptyGroups = false,\n defaultCollapsedGroupIds = [],\n separated = false,\n emptyGroupLabel = 'No items in this group.',\n emptyMessage = 'No items to show.',\n getGroupActions,\n grouping,\n loading = false,\n loadingItemCount = 1,\n loadingItemLabel,\n onCollapsedGroupIdsChange,\n renderGroupTitle,\n renderItem,\n}: ListViewProps<TItem>) {\n const [choices, setChoices] = useState<Readonly<Record<string, boolean>>>(\n () =>\n Object.fromEntries(\n defaultCollapsedGroupIds.map((groupId) => [groupId, true]),\n ),\n )\n const groups = useMemo(\n () =>\n preparedGroups ??\n (grouping === null ? [] : projectCollection(collection, grouping)),\n [collection, grouping, preparedGroups],\n )\n\n const resolveCollapsed = (\n group: CollectionGroup<TItem>,\n choice: boolean | undefined,\n ) => choice ?? (collapseEmptyGroups && group.count === 0 && !loading)\n\n const isCollapsed = (group: CollectionGroup<TItem>) =>\n controlledCollapsedGroupIds\n ? controlledCollapsedGroupIds.includes(group.id)\n : resolveCollapsed(group, choices[group.id])\n\n const setGroupCollapsed = (groupId: string, collapsed: boolean) => {\n if (controlledCollapsedGroupIds) {\n onCollapsedGroupIdsChange?.(\n collapsed\n ? [\n ...controlledCollapsedGroupIds.filter((id) => id !== groupId),\n groupId,\n ]\n : controlledCollapsedGroupIds.filter((id) => id !== groupId),\n )\n return\n }\n\n const nextChoices = { ...choices, [groupId]: collapsed }\n setChoices(nextChoices)\n onCollapsedGroupIdsChange?.(\n groups\n .filter((group) => resolveCollapsed(group, nextChoices[group.id]))\n .map((group) => group.id),\n )\n }\n\n return (\n <div\n className=\"flex min-w-0 flex-col gap-1 p-2 rounded-lg bg-card/40 shadow-black/5 border border-border/80\"\n aria-busy={loading ? 'true' : undefined}\n data-collection-grouping={grouping ?? undefined}\n data-slot=\"list-view\"\n >\n {grouping === null && preparedGroups === undefined ? (\n <ListItemHeadingLevelContext.Provider value={2}>\n <div className=\"flex flex-col\" data-slot=\"list-view-items\">\n {loading ? (\n skeletonKeys('loading', loadingItemCount).map((skeletonKey) => (\n <ListItemSkeleton\n key={skeletonKey}\n {...(loadingItemLabel ? { label: loadingItemLabel } : {})}\n />\n ))\n ) : collection.items.length ? (\n collection.items.map((item, position) => (\n <Fragment key={collection.getKey(item)}>\n {separated && position > 0 ? (\n <Separator className=\"bg-border/40\" />\n ) : null}\n <ListViewItem item={item} renderItem={renderItem} />\n </Fragment>\n ))\n ) : (\n <Empty>\n <EmptyDescription>{emptyMessage}</EmptyDescription>\n </Empty>\n )}\n </div>\n </ListItemHeadingLevelContext.Provider>\n ) : (\n groups.map((group) => {\n const actions = getGroupActions?.(group)\n\n return (\n <ListGroup\n collapsed={isCollapsed(group)}\n separated={separated}\n emptyLabel={\n typeof emptyGroupLabel === 'function'\n ? emptyGroupLabel(group)\n : emptyGroupLabel\n }\n getKey={collection.getKey}\n group={group}\n key={group.id}\n loading={loading}\n loadingItemCount={loadingItemCount}\n onCollapsedChange={(collapsed) =>\n setGroupCollapsed(group.id, collapsed)\n }\n {...(renderGroupTitle ? { renderGroupTitle } : {})}\n renderItem={renderItem}\n {...(loadingItemLabel ? { loadingItemLabel } : {})}\n {...(actions ? { actions } : {})}\n />\n )\n })\n )}\n </div>\n )\n}\n",
|
|
771
|
-
"target": "~/packages/patterns/src/collection-views/views/list/components/list-view.tsx"
|
|
772
|
-
},
|
|
773
|
-
{
|
|
774
|
-
"path": "parttens/src/collection-views/views/list/index.ts",
|
|
775
|
-
"type": "registry:file",
|
|
776
|
-
"content": "export type { ListGroupActions, ListGroupProps } from './components/list-group'\nexport { ListGroup } from './components/list-group'\nexport type {\n ListItemActionProps,\n ListItemBodyProps,\n ListItemContentProps,\n ListItemDensity,\n ListItemDescriptionProps,\n ListItemFieldProps,\n ListItemFooterProps,\n ListItemHeaderProps,\n ListItemLeadingProps,\n ListItemProps,\n ListItemTitleProps,\n ListItemTitleTriggerProps,\n ListItemTrailingProps,\n} from './components/list-item'\nexport {\n ListItem,\n ListItemAction,\n ListItemBody,\n ListItemContent,\n ListItemDescription,\n ListItemField,\n ListItemFooter,\n ListItemHeader,\n ListItemLeading,\n ListItemTitle,\n ListItemTitleTrigger,\n ListItemTrailing,\n} from './components/list-item'\nexport type { ListItemSkeletonProps } from './components/list-item-skeleton'\nexport { ListItemSkeleton } from './components/list-item-skeleton'\nexport type {\n ListRowIconFrame,\n ListRowProps,\n} from './components/list-row'\nexport { ListRow } from './components/list-row'\nexport type { ListViewProps } from './components/list-view'\nexport { ListView } from './components/list-view'\n",
|
|
777
|
-
"target": "~/packages/patterns/src/collection-views/views/list/index.ts"
|
|
778
|
-
},
|
|
779
|
-
{
|
|
780
|
-
"path": "parttens/src/shared/components/collection-pagination.tsx",
|
|
781
|
-
"type": "registry:file",
|
|
782
|
-
"content": "'use client'\n\nimport { Button } from '@tc96/ui/button'\nimport {\n Pagination,\n PaginationContent,\n PaginationItem,\n} from '@tc96/ui/pagination'\nimport { cn } from '@tc96/utils'\nimport {\n ChevronLeftIcon,\n ChevronRightIcon,\n ChevronsLeftIcon,\n ChevronsRightIcon,\n} from 'lucide-react'\nimport type React from 'react'\n\nexport interface CollectionPaginationProps\n extends Omit<React.ComponentProps<'div'>, 'children' | 'onChange'> {\n /** Nome acessível da navegação, no vocabulário da coleção — `Paginação de contatos`. */\n label: string\n onPageChange: (page: number) => void\n /** Página corrente, a partir de 1 — a mesma numeração dos contratos de listagem. */\n page: number\n pageCount: number\n /** Com `total`, resume o recorte visível (`1–25 de 57`) à esquerda dos controles. */\n pageSize?: number\n total?: number\n}\n\n/**\n * A paginação de uma coleção, seja ela servida pelo servidor (contratos com\n * `pagination.page`) ou pelo modelo de paginação de uma tabela. O consumer\n * decide quando mostrá-la; o pacote fixa anatomia, rótulos e estados das pontas.\n */\nexport function CollectionPagination({\n className,\n label,\n onPageChange,\n page,\n pageCount,\n pageSize,\n total,\n ...props\n}: CollectionPaginationProps): React.ReactElement {\n const lastPage = Math.max(pageCount, 1)\n const currentPage = Math.min(Math.max(page, 1), lastPage)\n const summary =\n total !== undefined && pageSize !== undefined\n ? summarizeRange(currentPage, pageSize, total)\n : null\n\n return (\n <div\n className={cn(\n 'flex flex-wrap items-center justify-between gap-2 p-2',\n className,\n )}\n data-slot=\"collection-pagination\"\n {...props}\n >\n {summary ? (\n <p\n aria-live=\"polite\"\n className=\"px-2 text-muted-foreground text-sm tabular-nums\"\n >\n {summary}\n </p>\n ) : null}\n <Pagination\n aria-label={label}\n className=\"mx-0 ml-auto w-auto justify-end\"\n >\n <PaginationContent>\n <PaginationItem>\n <Button\n aria-label=\"Primeira página\"\n disabled={currentPage <= 1}\n onClick={() => onPageChange(1)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <ChevronsLeftIcon />\n </Button>\n </PaginationItem>\n <PaginationItem>\n <Button\n aria-label=\"Página anterior\"\n disabled={currentPage <= 1}\n onClick={() => onPageChange(currentPage - 1)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <ChevronLeftIcon />\n </Button>\n </PaginationItem>\n <PaginationItem>\n <span\n aria-current=\"page\"\n className=\"px-2 text-muted-foreground text-sm tabular-nums\"\n data-slot=\"collection-pagination-page\"\n >\n {currentPage} / {lastPage}\n </span>\n </PaginationItem>\n <PaginationItem>\n <Button\n aria-label=\"Próxima página\"\n disabled={currentPage >= lastPage}\n onClick={() => onPageChange(currentPage + 1)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <ChevronRightIcon />\n </Button>\n </PaginationItem>\n <PaginationItem>\n <Button\n aria-label=\"Última página\"\n disabled={currentPage >= lastPage}\n onClick={() => onPageChange(lastPage)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <ChevronsRightIcon />\n </Button>\n </PaginationItem>\n </PaginationContent>\n </Pagination>\n </div>\n )\n}\n\nfunction summarizeRange(page: number, pageSize: number, total: number): string {\n if (total === 0) return '0 de 0'\n const first = (page - 1) * pageSize + 1\n const last = Math.min(page * pageSize, total)\n return `${first}–${last} de ${total}`\n}\n",
|
|
783
|
-
"target": "~/packages/patterns/src/shared/components/collection-pagination.tsx"
|
|
784
|
-
},
|
|
785
|
-
{
|
|
786
|
-
"path": "parttens/src/shared/components/collection-toolbar.tsx",
|
|
787
|
-
"type": "registry:file",
|
|
788
|
-
"content": "'use client'\n\nimport { Text } from '@tc96/elements/text'\nimport { ToolbarGroup, Toolbar as ToolbarPrimitive } from '@tc96/ui/toolbar'\nimport { cn } from '@tc96/utils'\nimport type { ComponentProps, ReactElement, ReactNode } from 'react'\n\ninterface CollectionToolbarBaseProps\n extends Omit<ComponentProps<typeof ToolbarPrimitive>, 'title' | 'variant'> {\n centerSlot?: ReactNode\n endSlot?: ReactNode\n startSlot?: ReactNode\n}\n\nexport type CollectionToolbarProps = CollectionToolbarBaseProps &\n (\n | {\n /** Texto visível à esquerda dos controles, sobre a superfície plain. */\n variant: 'text'\n title: string\n description: string\n }\n | {\n /** `default` é a moldura do COSS; `plain` senta direto na página. */\n variant?: 'default' | 'plain'\n /** Tooltip HTML das variantes sem bloco de texto. */\n title?: string\n description?: never\n }\n )\n\nexport type CollectionToolbarGroupProps = ComponentProps<typeof ToolbarGroup>\n\nexport function CollectionToolbar({\n 'aria-label': ariaLabel = 'Controles da coleção',\n centerSlot,\n children,\n className,\n description,\n endSlot,\n startSlot,\n title,\n variant = 'plain',\n ...props\n}: Readonly<CollectionToolbarProps>): ReactElement {\n const centered = centerSlot != null\n const spacer = centered ? (\n <div aria-hidden=\"true\" className=\"flex-1 basis-0\" />\n ) : null\n\n return (\n <ToolbarPrimitive\n aria-label={ariaLabel}\n className={cn(\n 'justify-between',\n variant === 'text' ? 'min-h-14' : 'h-9 md:h-10',\n (variant === 'plain' || variant === 'text') &&\n 'items-center rounded-none border-0 bg-transparent p-0',\n className,\n )}\n data-variant={variant}\n title={variant === 'text' ? undefined : title}\n {...props}\n >\n {variant === 'text' ? (\n <ToolbarGroup className=\"min-w-0 flex-1\">\n <div className=\"min-w-0\">\n <Text\n className=\"truncate leading-tight\"\n family=\"heading\"\n render={<h2>{title}</h2>}\n size=\"base\"\n weight=\"semibold\"\n />\n <Text\n className=\"truncate leading-tight\"\n foreground=\"muted\"\n render={<p>{description}</p>}\n size=\"sm\"\n />\n </div>\n </ToolbarGroup>\n ) : null}\n {startSlot ? (\n <ToolbarGroup\n className={centered ? 'min-w-0 flex-1 basis-0' : 'min-w-0'}\n >\n {startSlot}\n </ToolbarGroup>\n ) : (\n spacer\n )}\n {centered ? (\n <ToolbarGroup className=\"shrink-0\">{centerSlot}</ToolbarGroup>\n ) : null}\n {children}\n {endSlot ? (\n <ToolbarGroup\n className={centered ? 'flex-1 basis-0 justify-end' : 'ms-auto'}\n >\n {endSlot}\n </ToolbarGroup>\n ) : (\n spacer\n )}\n </ToolbarPrimitive>\n )\n}\n\nexport function CollectionToolbarGroup(\n props: CollectionToolbarGroupProps,\n): ReactElement {\n return <ToolbarGroup {...props} />\n}\n",
|
|
789
|
-
"target": "~/packages/patterns/src/shared/components/collection-toolbar.tsx"
|
|
790
|
-
},
|
|
791
|
-
{
|
|
792
|
-
"path": "parttens/src/shared/components/menu-selection-item.tsx",
|
|
793
|
-
"type": "registry:file",
|
|
794
|
-
"content": "'use client'\n\nimport { MenuPrimitive } from '@tc96/ui/menu'\nimport { cn } from '@tc96/utils'\nimport type React from 'react'\n\nconst selectionItemClassName =\n \"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1fr_.75rem] items-center gap-4 rounded-sm py-1 ps-2 pe-2.5 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0\"\n\nfunction CheckIcon(): React.ReactElement {\n return (\n <svg\n aria-hidden=\"true\"\n fill=\"none\"\n height=\"24\"\n stroke=\"currentColor\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth=\"2\"\n viewBox=\"0 0 24 24\"\n width=\"24\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M5.252 12.7 10.2 18.63 18.748 5.37\" />\n </svg>\n )\n}\n\nexport type MenuRadioOptionProps = MenuPrimitive.RadioItem.Props\n\nexport function MenuRadioOption({\n className,\n children,\n ...props\n}: MenuRadioOptionProps): React.ReactElement {\n return (\n <MenuPrimitive.RadioItem\n className={cn(selectionItemClassName, className)}\n data-slot=\"menu-radio-option\"\n {...props}\n >\n <span className=\"col-start-1 flex min-w-0 items-center gap-2\">\n {children}\n </span>\n <MenuPrimitive.RadioItemIndicator className=\"col-start-2 -me-0.5\">\n <CheckIcon />\n </MenuPrimitive.RadioItemIndicator>\n </MenuPrimitive.RadioItem>\n )\n}\n\nexport type MenuCheckboxOptionProps = MenuPrimitive.CheckboxItem.Props\n\nexport function MenuCheckboxOption({\n className,\n children,\n ...props\n}: MenuCheckboxOptionProps): React.ReactElement {\n return (\n <MenuPrimitive.CheckboxItem\n className={cn(selectionItemClassName, className)}\n data-slot=\"menu-checkbox-option\"\n {...props}\n >\n <span className=\"col-start-1 flex min-w-0 items-center gap-2\">\n {children}\n </span>\n <MenuPrimitive.CheckboxItemIndicator className=\"col-start-2 -me-0.5\">\n <CheckIcon />\n </MenuPrimitive.CheckboxItemIndicator>\n </MenuPrimitive.CheckboxItem>\n )\n}\n",
|
|
795
|
-
"target": "~/packages/patterns/src/shared/components/menu-selection-item.tsx"
|
|
796
|
-
},
|
|
797
|
-
{
|
|
798
|
-
"path": "parttens/src/shared/index.ts",
|
|
799
|
-
"type": "registry:file",
|
|
800
|
-
"content": "'use client'\n\nexport type { CollectionPaginationProps } from './components/collection-pagination'\nexport { CollectionPagination } from './components/collection-pagination'\nexport type {\n CollectionToolbarGroupProps,\n CollectionToolbarProps,\n} from './components/collection-toolbar'\nexport {\n CollectionToolbar,\n CollectionToolbarGroup,\n} from './components/collection-toolbar'\nexport type {\n MenuCheckboxOptionProps,\n MenuRadioOptionProps,\n} from './components/menu-selection-item'\nexport {\n MenuCheckboxOption,\n MenuRadioOption,\n} from './components/menu-selection-item'\n",
|
|
801
|
-
"target": "~/packages/patterns/src/shared/index.ts"
|
|
802
|
-
}
|
|
803
|
-
],
|
|
804
|
-
"dependencies": [
|
|
805
|
-
"@base-ui/react@1.8.0",
|
|
806
|
-
"@dnd-kit/abstract@0.5.0",
|
|
807
|
-
"@dnd-kit/collision@0.5.0",
|
|
808
|
-
"@dnd-kit/dom@0.5.0",
|
|
809
|
-
"@dnd-kit/helpers@0.5.0",
|
|
810
|
-
"@dnd-kit/react@0.5.0",
|
|
811
|
-
"@tanstack/react-table@9.2.4",
|
|
812
|
-
"@tanstack/react-virtual@3.14.2",
|
|
813
|
-
"class-variance-authority@0.7.1",
|
|
814
|
-
"lucide-react@1.28.0",
|
|
815
|
-
"react@19.1.1"
|
|
816
|
-
],
|
|
817
|
-
"registryDependencies": [
|
|
818
|
-
"@coss/badge",
|
|
819
|
-
"@coss/button",
|
|
820
|
-
"@coss/card",
|
|
821
|
-
"@coss/checkbox",
|
|
822
|
-
"@coss/collapsible",
|
|
823
|
-
"@coss/empty",
|
|
824
|
-
"@coss/input",
|
|
825
|
-
"@coss/menu",
|
|
826
|
-
"@coss/pagination",
|
|
827
|
-
"@coss/popover",
|
|
828
|
-
"@coss/scroll-area",
|
|
829
|
-
"@coss/select",
|
|
830
|
-
"@coss/separator",
|
|
831
|
-
"@coss/skeleton",
|
|
832
|
-
"@coss/table",
|
|
833
|
-
"@coss/toolbar"
|
|
834
|
-
],
|
|
835
|
-
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
836
|
-
}
|