本文へ移動

インターチェンジとエクスポート ​

コアは、計画ツールや作図ツールがやり取りするファイル形式を読み書きします。Microsoft Project XML(タスク、リンク、カレンダー、リソース、割り当て)、iCalendar(繰り返しを含む)、CSV、Mermaid のフローチャート、GraphML(yEd を含む)、draw.io に対応しています。読み込みはコンポーネントのプロップと、読めなかった内容の警告リストを返すので、取り込む前にユーザーに示せます。バージョン付きの JSON スナップショットはチャートのデータと表示状態を保存し、renderGraphSvg と renderTimelineSvg はサーバーで SVG を作ります。コンポーネントにも exportSvg と exportPng があります。

どれも純粋で依存関係がありません。XML パーサー、DOM、ネットワークは使いません。

最小の例 ​

ts
import { fromMsProjectXml, timelineFromMsProject, toMermaid } from '@eightkk/vue-weave/core'

// Microsoft Project XML から GanttChart のプロップへ
const project = fromMsProjectXml(xmlText)
const { rows, bars, dependencies } = timelineFromMsProject(project)
if (project.warnings.length) console.warn(project.warnings)

// NetworkGraph のプロップから Mermaid のフローチャートへ
const mermaid = toMermaid({ nodes, edges })

例: インポートとエクスポートのデモは例の一覧にあります。ガイド: ダイアグラムのファイル、表示状態の保存と復元、SVG と PNG へのエクスポート。型: fromMsProjectXml、toICalendar、fromDrawio、serializeWeaveSnapshot。

英語の詳細

ここから下の詳細なリファレンスは英語です。

Interchange exports ​

The core entry builds three interchange formats as strings, and reads CSV, Microsoft Project XML and iCalendar back, without a DOM or dependencies. Save them with a Blob (application/xml, text/calendar or text/csv) or send them from a server.

ExportBehavior
toMsProjectXml(project, options?)Microsoft Project XML (MSPDI) for MsProjectInput: name, tasks (MsProjectTask: id, name, start, end in epoch milliseconds, optional outlineLevel from 1, percentComplete from 0 to 100, milestone, baselines, each an MsProjectBaseline with number from 0 to 10, start and end, constraints, a TimelineConstraints in epoch milliseconds, inactive and manual) and optional dependencies (MsProjectDependency: from, to, type FS/SS/FF/SF, default FS, and elapsed lag in milliseconds). MsProjectXmlOptions.utcOffsetMinutes (default 0) sets the wall-clock offset of the written dates. Optional calendars (MsProjectCalendar: id, name, week, a WorkWeek), defaultCalendarId, resources (MsProjectResource: id, name, type, maxUnits, calendarId), assignments (MsProjectAssignment: taskId, resourceId, units) and a task's calendarId are written too (see below)
toICalendar(events, options?)RFC 5545 text with one VEVENT per ICalendarEvent (id, summary, start, end, optional description). ICalendarOptions: productId (default -//vue-weave//Timeline export//EN), calendarName (NAME and X-WR-CALNAME) and timestamp, the DTSTAMP of every event (default Date.now(); pass it for reproducible output). An event with recurrence (CalendarRecurrence) also gets RRULE, EXDATE and RDATE; with an IANA recurrence.timeZone other than UTC its DTSTART, DTEND, EXDATE and RDATE are local times with that TZID and the document gets a VTIMEZONE derived from Intl from the year before the zone's first event, so its observances begin before every event; with a nonzero utcOffsetMinutes (and no timeZone) they are local times with a fixed-offset TZID such as UTC+0900 and a VTIMEZONE of that offset, so BYDAY, BYMONTHDAY and UNTIL keep their local meaning; otherwise (UTC or no zone) they are in UTC. An event with seriesId and recurrenceId but no recurrence whose series is in the same export is an override: it is written with the series' UID and a RECURRENCE-ID in the series' zone
toCsv(table, options?)RFC 4180 text from rows of CsvCell (string, finite number or undefined for an empty field). Numbers are written as String writes them, except that one below 1e-6 is written in plain decimal notation (0.0000005, not 5e-7), so timelineFromCsvTable reads a progress back. CsvOptions.escapeFormulas (default false) writes text cells that start with =, +, -, @, a tab or a carriage return with a leading apostrophe ('=1+1), so spreadsheets show them as text instead of running them as formulas; number cells such as -2 are unchanged, and parseCsv does not remove the apostrophe
timelineCsvTable(rows, bars, options?)CsvCell[][]: a header and one record per bar, ordered by row in tree preorder and then by bar order. TimelineCsvOptions: formatTime (default ISO 8601 UTC), columns (TimelineCsvColumn[], any of row, wbs, bar, start, end, progress; default all, in that order) and headers (defaults Row, WBS, Bar, Start, End, Progress). Progress is written from 0 to 1 and is empty without progress
parseCsv(text, options?)string[][] from RFC 4180 text, the inverse of toCsv. CsvParseOptions.delimiter is one character other than a double quote, CR or LF (default ,)
timelineFromCsvTable(table, options)TimelineCsvImport ({ rows, bars }) from a table in the timelineCsvTable layout, for example the result of parseCsv. TimelineCsvImportOptions: parseTime(text) (required; return NaN for text that is not a time), columns (the TimelineCsvColumn of each field in order, undefined to skip one; the first record is still a header) and headers (the header texts to look for without columns; defaults as for export)

MSPDI. Tasks get UID and ID from 1 in input order and are written as manually scheduled tasks (Manual 1, with ManualStart, ManualFinish and ManualDuration), so Microsoft Project keeps their dates instead of rescheduling them on its default calendar. Each task has Name, Start, Finish, Duration (the elapsed span as PT#H#M#S; 0 for milestones), OutlineLevel, OutlineNumber and WBS (both derived from the outline levels), Milestone (set for milestone: true and for start === end), Summary (set when the next task is one level deeper) and PercentComplete (rounded). Dependencies become PredecessorLink elements on the successor with PredecessorUID, Type (FF 0, FS 1, SF 2, SS 3), LinkLag in tenths of a minute and LagFormat 4 (elapsed minutes). Task baselines become Baseline elements after the predecessor links, with Number, Interim 0, Start, Finish and the elapsed Duration, rounded like the task dates; map your baseline set IDs to Microsoft Project's numbers (0 is Baseline, 1 to 10 are Baseline1 to Baseline10), for example plan to 0 and rev1 to 1. The project carries Name, Title, ScheduleFromStart and the earliest start and latest finish as StartDate and FinishDate. Dates are local times without an offset suffix, as MSPDI expects, at second resolution: every start and finish is rounded to the nearest whole second (halves up) and Duration is the difference of the rounded times, so the three always agree. A task whose constraints has exactly one set constraint gets ConstraintType (2 Must Start On for fixedStart, 4 Start No Earlier Than, 5 Start No Later Than, 6 Finish No Earlier Than, 7 Finish No Later Than) and ConstraintDate, rounded like the task dates, after PercentComplete. Microsoft Project holds one constraint per task, so a task with two or more gets none, with one exception: exactly finishNoEarlierThan and finishNoLaterThan at the same time are written as ConstraintType 3 (Must Finish On) with that ConstraintDate. Pick the one to keep before exporting any other combination. inactive: true writes Active 0 and manual: false writes Manual 0, an automatically scheduled task whose dates Microsoft Project recalculates from its links, constraint and calendar when it opens the file; without these fields every task is written with Active 1 and Manual 1. Calendars, resources and assignments are written when the input has them, with UIDs from 1 in input order (the input IDs are not written): Calendars before Tasks and Resources and Assignments after it, CalendarUID on the project, tasks and resources, Type (0 material, 1 work; a 'cost' resource is written as Type 0 with IsCostResource 1, so a reader that does not know IsCostResource sees no work capacity; Microsoft's schema pages disagree on how a cost resource is encoded and neither form has been opened in Microsoft Project, so check it there before relying on it), MaxUnits (when set) and Units (default 1; 1 is 100 %). Every calendar is written as a base calendar with its complete weekly pattern (DayType 1 to 7, Sunday first, with WorkingTimes) and each date of week.exceptions as a DayType 0 entry with a TimePeriod; week.utcOffsetMinutes and week.timeZone are ignored because MSPDI times are wall-clock times, and a shift that ends after minute 1440 throws a RangeError (split it at midnight). Unknown calendar, task or resource references, duplicate IDs, a repeated task and resource pair, a week.exceptions that is not an object of dates and an exception date whose shifts are not an array throw an Error, and invalid shifts, exception dates, maxUnits and units a RangeError. These elements follow the MSPDI schema order but have not been opened in Microsoft Project itself. Not exported: a second constraint of a task (apart from the Must Finish On pair), notes, custom fields, baseline work and cost, the base calendar link and recurring exceptions, and the input task IDs. Text is escaped with escapeXml. Invalid or duplicate task IDs, a missing (undefined or null) project or task name, unknown dependency ends, a dependency from a task to itself (Microsoft Project does not accept a task as its own predecessor), unknown types, baselines that is not an array, a baseline number used twice on a task and an inactive or manual that is not a boolean throw an Error; non-finite or inverted dates (of tasks and baselines), a baseline number that is not an integer from 0 to 10, an outline level that is not an integer from 1 or that grows by more than one from the previous task, a percent complete outside 0 to 100, a non-finite lag and a constraint time that is not finite throw a RangeError.

iCalendar. Lines end with CRLF and are folded at 75 octets, never inside a UTF-8 character; continuation lines start with a space. Times are UTC (20261109T080000Z), rounded to the nearest whole second (halves up). An event whose rounded end equals its rounded start, for example end === start, is written without DTEND, because RFC 5545 requires DTEND to be after DTSTART. TEXT values escape backslashes, semicolons, commas and line breaks and drop other control characters. Use globally unique IDs, for example task-1@example.com. Invalid or duplicate IDs and a missing (undefined or null) summary throw an Error; non-finite or inverted times throw a RangeError.

CSV. Fields that contain a comma, a double quote, CR or LF are quoted, with inner quotes doubled; every record ends with CRLF. A non-finite number throws a RangeError. Formulas are not neutralized: when untrusted text is opened in a spreadsheet, prefix cells that start with =, +, - or @ yourself.

CSV import. parseCsv accepts CRLF, LF and lone CR line ends, an optional final line break and a leading byte order mark, which it removes. A quoted field can contain the delimiter, line breaks and doubled quotes; a quote inside an unquoted field is kept as text. Every field is a string, an empty line is a record with one empty field and empty text has no records. An unterminated quoted field and text after a closing quote throw an Error with the line and column, for example Unterminated quoted CSV field starting at line 2, column 3.

timelineFromCsvTable finds its columns by header text, ignoring case and surrounding spaces, or takes them from columns; other columns are ignored. It needs bar, start and end and either row or wbs. With WBS codes, each code is a row with the ID row-<code> (for example row-1.2), its first row cell that is not blank as label (the code when every one is blank) and the row of the shorter code as parent; a parent code without a record of its own becomes a row labelled with its code, and rows are returned in tree preorder by code. Without WBS codes, each distinct row label is a top-level row row-1, row-2, … in order of appearance. Bars are bar-1, bar-2, … in record order with the label, the parsed start and end and, when the cell is not empty, progress. Rows without bars are not in a timelineCsvTable export, so they are not restored, and WBS codes are renumbered by timelineWbsCodes after such a gap. Records whose fields are all empty are skipped. Progress must be written as a plain decimal number, such as 0.25, .5 or 1; hexadecimal, binary, octal and exponent forms (0x1, 1e0) are rejected. WBS codes are ordered part by part as whole numbers of any length. A custom header in headers takes precedence over another column's default header, so headers: { wbs: 'Row' } reads the Row column as WBS codes and leaves row unmatched. Missing or repeated columns, and two custom headers that are equal ignoring case and surrounding spaces, throw an Error; an invalid WBS code throws an Error and a WBS code of more than 1,000 levels (which would create that many rows), an unreadable time, an end before the start and a progress that is not a plain decimal number from 0 to 1 throw a RangeError, each naming the CSV line (the one-based record number, with the header as line 1). Add application fields such as editable to the returned bars yourself.

ts
import { parseCsv, timelineCsvTable, timelineFromCsvTable, toCsv, toICalendar, toMsProjectXml } from '@eightkk/vue-weave/core'

const csv = toCsv(timelineCsvTable(rows, bars, { formatTime }))
const ics = toICalendar(bars.map(bar => ({ id: bar.id + '@example.com', summary: bar.label, start: bar.start, end: bar.end })))
const xml = toMsProjectXml({ name: 'Plan', tasks: bars.map(bar => ({ id: bar.id, name: bar.label, start: bar.start, end: bar.end })) })

// Import: the reverse of the CSV export above.
const imported = timelineFromCsvTable(parseCsv(await file.text()), { parseTime: text => Date.parse(text) })

Microsoft Project import ​

ExportBehavior
fromMsProjectXml(xml, options?)MsProjectImport ({ name, tasks, dependencies, warnings }, plus calendars, defaultCalendarId, resources and assignments when the file has them) from a Microsoft Project XML (MSPDI) document, such as Microsoft Project's "Save as XML" or toMsProjectXml output. options.utcOffsetMinutes (default 0) is the offset of the wall-clock dates, as for the export
workCalendarsFromMsProject(project, range)WorkCalendar[] for scheduleTasks and levelResources: buildWorkPeriods(range, calendar.week) for each calendar
resourceLoadFromMsProject(project, options?){ resources, assignments, warnings } in the shapes of calculateResourceLoad, levelResources and projectResourceTimeline; see Resources below
timelineFromMsProject(project, options?)MsProjectTimeline ({ rows, bars, dependencies, hiddenDependencyIds }) for GanttChart from an MsProjectImport or any MsProjectInput. MsProjectTimelineOptions.baselineId(number) names the baseline sets (default baseline for 0, baseline1 to baseline10); summaryDependencies keeps links that touch a summary task in dependencies

Reading. The reader is a small XML tokenizer written as a loop, so it runs in Node.js, workers and browsers without DOMParser and handles deep or long documents. It reads elements, attributes, text, CDATA, comments and processing instructions, the five predefined entities and character references; a leading byte order mark is removed and line ends become LF. A DOCTYPE is skipped without reading its declarations, and a reference to any other entity throws, so a document cannot reach external files or expand entities (no XXE, no "billion laughs"). Elements are matched by local name, so the default namespace and prefixes such as p:Task both work. Malformed XML throws an Error with the line and column, for example Invalid XML at line 3, column 1: unknown or invalid entity &bad;; a document whose root element is not Project throws an Error, and an invalid utcOffsetMinutes a RangeError.

Tasks. The project name is Name when it is not blank, else Title, else empty. Every Task except the project summary task (UID 0) and empty rows (IsNull 1) becomes an MsProjectImportTask: an MsProjectTask with its UID as id (leading zeros removed), Name (not trimmed), Start and Finish in epoch milliseconds, and the fields a file always has set: outlineLevel (default 1), percentComplete (default 0), milestone, summary, manual (Manual 1) and inactive (Active 0). Dates are wall-clock times at utcOffsetMinutes, mirroring the export, unless they end with Z or an offset; fractional seconds are kept. duration is Duration in milliseconds (an ISO 8601 duration with weeks, days, hours, minutes and seconds; days count 24 hours), which Microsoft Project stores as working time for automatically scheduled tasks, so it suits ScheduleTask.duration. ConstraintType 2 and 4 to 7 with their ConstraintDate become constraints with the export's mapping, type 3 (Must Finish On) becomes { finishNoEarlierThan: date, finishNoLaterThan: date }, and type 1 (As Late As Possible) becomes mode: 'alap'. Baseline elements with dates become baselines; baselines with only work or cost are skipped without a warning. PredecessorLink elements become dependencies in the order of their successor tasks and then of their links, with type always set (FF 0, FS 1, SF 2, SS 3; default FS) and lag only when it is not 0: LinkLag in tenths of a minute as elapsed milliseconds.

Warnings. What the reader works around is reported in warnings (MsProjectImportWarning: code, optional taskId, an English message) instead of thrown:

codeCause and handling
skipped-taskA task without a valid UID, without valid Start and Finish, with Finish before Start or with a UID used before: the task and its links are skipped
outline-levelAn outline level more than one below the task before it, for example under a skipped task: raised to one below it
invalid-valueAn unreadable OutlineLevel (read as 1), PercentComplete (read as 0), Duration (left out; years and months have no fixed length), LinkLag (left out), or a resource Type, MaxUnits or assignment Units (left out)
unsupported-constraintAn unknown constraint type, or a constraint (Must Finish On included) without a valid date: left out
skipped-baselineA baseline with dates and an invalid or repeated number, or with unreadable or inverted dates
unknown-predecessorA link from a task that was not imported: skipped
skipped-linkA link to another project (CrossProject 1), from a task to itself, or of an unknown type: skipped
skipped-calendarA calendar without a valid UID or with a UID used before: skipped
invalid-calendarA working time with unreadable or inverted times, an exception without valid dates or with an unreadable or out-of-range Period, DaysOfWeek, Month, MonthDay, MonthItem or MonthPosition, a working day without working times, an exception with more than 3,660 dates (the first 3,660 are kept) or a circular base calendar: left out (a working weekday without times is left to the base calendar). An exception that says the day is working (DayWorking 1) but has no readable WorkingTimes gets one warning that names the calendar and the exception, "is a working day without working times: its dates were treated as days off"; the exception stays in the result with those dates as days off, and no working hours are invented
unsupported-calendarAn exception recurrence that is not expanded (see Calendars), an alternate work week (WorkWeeks) or a DayType other than 0 to 7: left out. The message names the calendar and the exception's Name
unknown-calendarA project, task, resource or base CalendarUID that no imported calendar has: left out
skipped-resourceA resource without a valid UID or with a UID used before: skipped
skipped-assignmentAn assignment to a task or resource that was not imported, or a repeated task and resource pair: skipped
percent-lagA lag in percent of the predecessor's duration (LagFormat 19, 20, 51 or 52): the link is kept without its lag
working-time-lagA non-zero lag in a working-time format (minutes, hours, days, weeks or months of working time) or without LagFormat: read as the same amount of elapsed time

Calendars. calendars (MsProjectCalendar: id = UID, name, base = IsBaseCalendar, baseCalendarId and week) holds each calendar's weekly working times (WeekDay entries of DayType 1 to 7, Sunday first, with their WorkingTimes) and its exceptions (DayType 0 entries with a TimePeriod, and Exceptions) as the one-off dates of the WorkWeek of buildWorkPeriods: weekly shifts in minutes after local midnight (a working time that ends at 00:00:00 ends at minute 1440; seconds are rounded to minutes) and exceptions by YYYY-MM-DD date (an empty list is a day off). Base calendars are resolved, so each week is complete: a weekday the calendar does not define comes from its base calendar, and a calendar without a base has no working time on it. Exceptions are inherited too, and the calendar's own ones win. Times are wall-clock times, so week.utcOffsetMinutes is set to options.utcOffsetMinutes when that is not 0. The project CalendarUID becomes defaultCalendarId, and a task's or resource's CalendarUID (not -1) its calendarId; a reference to a calendar that was not imported is left out with a warning. Each Exception is classified by its Type (1 daily, 2 yearly by day of the month, 3 yearly by position, 4 monthly by day of the month, 5 monthly by position, 6 weekly, 7 by day count, 8 by weekday count, 9 no exception type) before any date is expanded, and the dates that WorkWeek gets are exactly the ones the exception denotes:

ExceptionImported as
DayType 0 entry; Exception without Type or with Type 9; Type 1 or 7 with Period 1 or none (what Microsoft Project writes for a single day or a date range)Every date from FromDate to ToDate (only FromDate when ToDate is missing)
Type 1 or 7 with Period N above 1Every N-th date from FromDate
Type 6 with Period 1 or noneEvery date whose weekday is in DaysOfWeek (1 Sunday, 2 Monday, 4 Tuesday … 64 Saturday, added)
Type 4 or 5 with Period 1 or noneEvery month on MonthDay 1 to 28, or on the MonthPosition (0 to 3 first to fourth, 4 last) of the MonthItem 3 to 9 (Sunday to Saturday)
Type 2 or 3Every year in Month (0 January … 11 December) on MonthDay (not 29 February), or on such a position
Type 6 with Period 2 or more, Type 2 to 5 with Period 2 or more, MonthDay 29 to 31 (or 29 February), MonthItem 0 to 2 (day, weekday, weekend day), Type 8, any other TypeLeft out with unsupported-calendar: Microsoft Project's rule for these (which week or month an interval counts from, months without that day, what counts as a weekday) is not documented

The dates are those from FromDate to ToDate; with EnteredByOccurrences 1 (or Type 7) and a positive Occurrences, they are the first Occurrences dates from FromDate instead. An exception keeps at most 3,660 dates (invalid-calendar beyond). An alternate work week and a DayType 8 or above cannot be represented by WorkWeek and are reported as unsupported-calendar, not guessed. workCalendarsFromMsProject(project, range) builds the WorkCalendars with buildWorkPeriods, so scheduleTasks({ range, calendars, defaultCalendarId: project.defaultCalendarId, tasks }) can use task.calendarId as ScheduleTask.calendarId; the range is limited like buildWorkPeriods.

Resources. resources (MsProjectResource: id = UID, name, type 'work' (Type 1), 'material' (Type 0) or 'cost' (IsCostResource 1 with any Type, or Type 2; both forms are accepted because Microsoft's schema pages disagree and neither has been verified in Microsoft Project), maxUnits and calendarId) and assignments (MsProjectAssignment: taskId, resourceId, units) keep Microsoft Project's fractions, where 1 is 100 %. The placeholder resource 0, unassigned work (ResourceUID -65535) and assignments to the project summary task are not imported. resourceLoadFromMsProject(project, { unitScale, range }) maps them to the integer shapes of the load functions: only work resources, with capacity = round(maxUnits * unitScale) (maxUnits default 1) and assignments with units = round(units * unitScale) (default 1) to tasks that are not summary tasks. unitScale defaults to 100, so one unit is 1 %; use 1 for whole-numbered files. An assignment that rounds to 0 units is left out and reported in the helper's warnings. With range, a resource with a calendar gets periods, the working time of that calendar inside the range. timelineFromMsProject adds resources (id and label of the work resources) and assignments (the same units in percent) to its result when the plan has resources, so projectResourceTimeline({ resources, assignments, tasks }) needs no further mapping.

Not imported: notes, extended attributes, baseline work and cost, the working-time meaning of lags, lags in percent, resource cost rates and availability tables, and assignment work, dates and contours. fromMsProjectXml(toMsProjectXml(plan)) reproduces the plan, apart from IDs (the UIDs 1, 2, … in task order): names, dates and baselines rounded to the second, outline levels, rounded percent complete, milestones (also every task with start === end), single constraints and Must Finish On, dependency types and lags (rounded to tenths of a minute), inactive and manual (true when it was not set), with type and percentComplete filled in. Calendars, resources and assignments round-trip too (calendar and resource IDs become the UIDs 1, 2, …, and a calendar comes back as a base calendar with its complete week). An MsProjectImport is an MsProjectInput, so toMsProjectXml writes it again.

Timeline. timelineFromMsProject validates its input like toMsProjectXml and throws the same errors. Every task becomes a row with the task ID and name, and the outline levels become parentId. A task that the next task is nested under is a summary task: its row has no bar, so GanttChart showSummaries draws it from its subtasks. Every other task becomes a bar with the task ID (so bar IDs, task IDs and ScheduleTask IDs agree), its name and dates, progress (percent complete / 100) when percentComplete is set, constraints, and baselines named by baselineId; a milestone (milestone or start === end) is a zero-length bar at its start, and an inactive task has appearance: 'outline'. Dependencies get the IDs link-1, link-2, … by position in project.dependencies, with type and a non-zero lag copied; one that touches a summary task is listed in hiddenDependencyIds instead, unless summaryDependencies is set: then it stays in dependencies with the summary's row ID as its end, for GanttChart summaryDependencies with showSummaries (see Dependencies on summary rows), and hiddenDependencyIds is empty. A baseline set ID that is empty, timelineBaselineId or used for two numbers throws an Error. Add application fields such as editable to the returned bars yourself.

ts
import { fromMsProjectXml, scheduleTasks, timelineFromMsProject, type ScheduleTask } from '@eightkk/vue-weave/core'

const project = fromMsProjectXml(await file.text(), { utcOffsetMinutes: 540 })
for (const warning of project.warnings) console.warn(warning.code, warning.message)
const { rows, bars, dependencies } = timelineFromMsProject(project)

// Schedule the leaf tasks: manual tasks keep their dates, inactive tasks stay out of the calculation.
const tasks = project.tasks.filter(task => !task.summary).map((task): ScheduleTask => ({
  id: task.id, duration: task.duration ?? task.end - task.start, ...task.constraints,
  ...(task.manual ? { manual: { start: task.start, end: task.end } } : {}),
  ...(task.inactive ? { inactive: true } : {}),
}))
const plan = scheduleTasks({ range, tasks, dependencies })

The dependencies of timelineFromMsProject have IDs and connect leaf tasks only, so they serve as ScheduleLinks. Without calendars, duration is scheduled in continuous time; pass workCalendarsFromMsProject(project, range) as calendars, project.defaultCalendarId as defaultCalendarId and each task's calendarId for working time.

Related exported types: MsProjectImportWarningCode, MsProjectResourceLoad, MsProjectResourceLoadOptions.

iCalendar import ​

ExportBehavior
fromICalendar(text, options?)ICalendarImport ({ name?, events, warnings }) from RFC 5545 text, such as toICalendar output or a calendar application's export. ICalendarImportOptions.utcOffsetMinutes (default 0, within ±1080) is the offset of local times without a zone
timelineFromICalendar(events)ICalendarTimeline ({ rows, bars }) from any ICalendarEvent[]: one row and one bar per event, with the event ID as both IDs, the summary as label and the description (when not empty) as the bar's description. An event with start === end is a zero-length milestone bar. Throws the Errors and RangeErrors of toICalendar

Reading. Pure string parsing with loops, without a DOM, network or file access. Lines are unfolded (a line that starts with a space or tab continues the one before it), CRLF, LF and lone CR line ends and a leading byte order mark are accepted, names and parameter names are case-insensitive and quoted parameter values may contain ; and :. TEXT values are unescaped (backslash followed by n or N, ,, ; or backslash; any other backslash is kept). Only properties directly inside a VEVENT count; other components (VTODO, VTIMEZONE, …) and nested ones such as VALARM are ignored. The calendar name is NAME, else X-WR-CALNAME. The reader sets no size limit, so bound uploaded files yourself.

Events. Each VEVENT becomes an ICalendarImportEvent, an ICalendarEvent (so toICalendar accepts it) with id (UID), summary (empty when missing), description when present, start and end in epoch milliseconds, allDay and, for a recurring event, recurrenceRule. Times: a UTC time (Z) is exact; a time with a TZID is resolved with Intl as RFC 5545 section 3.3.5 says: a wall time skipped by a daylight-saving gap is read with the UTC offset in effect before the gap, so DTSTART;TZID=America/New_York:20070311T023000 is 07:30 UTC (local 03:30), and a repeated wall time takes its first occurrence. This differs from buildWorkPeriods with timeZone and from editing, which move a skipped time to the transition, and the nonstandard prefix of /mozilla.org/…/Europe/Berlin is stripped; VTIMEZONE definitions are not read, so a TZID that Intl does not know (for example a Windows zone name) is reported as unknown-time-zone and the time is read as a floating time. The exception is a TZID that Intl does not know but a VTIMEZONE of the file defines with one fixed offset (every TZOFFSETTO the same, such as the UTC+0900 zones toICalendar writes): it is read at that offset. A floating time, and a date (VALUE=DATE, midnight), are wall-clock times at utcOffsetMinutes. The end is DTEND, else DTSTART plus DURATION, else the start plus one day for a date and the start itself for a date-time, which is an instant like the events toICalendar writes without DTEND. For dates DTEND is exclusive, matching the half-open [start, end) interval. A DURATION (weeks, days, hours, minutes and seconds, optionally with +) is added as RFC 5545 section 3.3.6 says: the weeks and days are nominal and are added to the local date and time of DTSTART, then the hours, minutes and seconds are added as elapsed time. With a TZID, P1D therefore ends at the same local time on the next day, 23 or 25 hours later across a daylight saving change, while PT24H is always 24 hours, and P1DT2H is the next day at the same time plus two hours; a local end in a skipped or repeated hour is resolved like DTSTART. For a UTC, floating or date DTSTART a day is 24 hours. An event with RRULE, RDATE or EXDATE is imported once, at its first instance, with a recurrence warning (the rule is not expanded); a changed instance (RECURRENCE-ID) is skipped. fromICalendar(toICalendar(events)) returns the same events with allDay false.

Recurring events (opt-in, ICalendarImportOptions.recurrence). 'first' is the default described above. With 'series', a recurring event is imported once with recurrence: the parsed rule (parseRecurrenceRule), exdates and rdates (every EXDATE and RDATE line and comma-separated value; an RDATE period adds its start) and its zone, the TZID of DTSTART, 'UTC' for a UTC time, or utcOffsetMinutes for a fixed-offset TZID, a floating time or a date; there is no recurrence warning. A changed instance (RECURRENCE-ID) becomes an event with ID <UID>:<recurrenceId>, seriesId (the UID) and recurrenceId, so expandRecurringEvents treats it as an override; one with RANGE=THISANDFUTURE or an unreadable RECURRENCE-ID is skipped (skipped-event). A rule that parseRecurrenceRule rejects (for example BYHOUR) keeps the default with a recurrence warning that names the part. With { range, maxOccurrences? } the series are replaced by their occurrences that overlap the range, as expandRecurrence computes them, and changed instances take the place of the occurrences they change; other events and changed instances are kept whether or not they overlap the range. An invalid recurrence option or range, and more than maxOccurrences instances, throw a RangeError. fromICalendar(toICalendar(events), { recurrence: 'series' }) returns the recurrences that toICalendar wrote (a fixed-offset series with the same utcOffsetMinutes), and their overrides with the IDs <seriesId>:<recurrenceId>, so the occurrences expand the same.

Warnings (ICalendarImportWarning: code, optional eventId and one-based line, an English message): skipped-event (no valid DTSTART, a RECURRENCE-ID, a repeated UID or no END:VEVENT), missing-uid (the event is named event-<n>), recurrence, unknown-time-zone, invalid-value (an unreadable or negative DURATION, an unreadable DTEND, a DTEND before DTSTART or both DTEND and DURATION; the event becomes an instant, or DTEND wins) and malformed (a line without a colon or an END that does not match). Text without BEGIN:VCALENDAR and a non-string throw an Error, and an invalid utcOffsetMinutes a RangeError.

ts
import { fromICalendar, timelineFromICalendar } from '@eightkk/vue-weave/core'

const { events, warnings } = fromICalendar(await file.text(), { utcOffsetMinutes: 540 })
const { rows, bars } = timelineFromICalendar(events)

Related exported types: ICalendarImportWarningCode and ICalendarExpandOptions.

Graph interchange ​

The core entry writes and reads NetworkGraph diagrams in three diagram formats, as strings, without a DOM or dependencies: Mermaid flowcharts, GraphML (including yEd files) and draw.io (diagrams.net). The writers take a GraphInterchangeInput (nodes, edges, optional groups, and positions with top-left corners and sizes, as the NetworkGraph props) and check it as NetworkGraph does, with the same Errors and RangeErrors; they never change it. The readers return a GraphInterchangeImport: nodes, edges, groups (nested with parentId, parents first, only groups with nodes), positions and sizes (Maps, empty for Mermaid), direction (Mermaid only, TD read as TB) and warnings. An import is itself a GraphInterchangeInput, so it can be written again, and its fields go straight into NetworkGraph:

ts
import { fromDrawioAsync, toMermaid } from '@eightkk/vue-weave/core'

const diagram = await fromDrawioAsync(await file.text())
for (const warning of diagram.warnings) console.warn(warning.code, warning.message)
// <NetworkGraph :nodes="diagram.nodes" :edges="diagram.edges" :groups="diagram.groups"
//   :positions="diagram.positions" :sizes="diagram.sizes" />
const mermaid = toMermaid(diagram, { direction: 'TD' })
ExportBehavior
toMermaid(graph, options?)A flowchart (MermaidOptions.direction TD, TB, LR, RL or BT, default LR). Nodes are declared once with their shape and quoted label (then <br> and the detail when there is one); groups become nested subgraph id["label"] … end blocks with their direct members; edges follow, with labels as |"label"|. MermaidOptions.edgeIds writes edge IDs as a e1@--> b (Mermaid 11.6 and later; default false). Positions, sizes, tones, ports, waypoints and edge styles have no Mermaid form
fromMermaid(text, options?)Reads the subset of the flowchart syntax described under Mermaid reading
toGraphMl(graph, options?)GraphML with <key> definitions for the node label, detail, shape, tone, x, y, width and height and the edge label, markerStart, markerEnd, edgeStyle, animated and points (x,y x,y …). Groups are nodes with a nested <graph> (ID <group>:) that holds their members and nested groups; edges are in the top-level graph. GraphMlOptions.directed (default true) sets edgedefault
fromGraphMl(xml, options?)Reads those keys (matched by attr.name; name is also read as the label; <default> values apply; other keys are ignored) and yEd graphics: the first y:NodeLabel (its first line as label, the rest as detail), y:Geometry, the y:Shape type or y:GenericNode configuration, and the y:EdgeLabel, y:Arrows and y:Path points of edges. A node with a nested graph is a group. In an undirected graph (edgedefault="undirected", or directed="false" on the edge) an edge without a marker gets markerEnd: 'none'
toDrawio(graph, options?)An uncompressed mxfile with one page (DrawioOptions.pageName, default Page-1). Nodes are vertex cells with the label (and a line break and the detail) as value (a label that itself has a line break is also written URI-encoded as vwLabel, so fromDrawio does not split it), a shape style, the tone as draw.io fill and stroke colours plus vwTone, and their geometry (default size 144 by 58; nodes without a position are placed with layoutLayeredGraph (with slots as large as the largest node size, so wide nodes do not overlap), or around the saved boxes and their sizes with layoutGraphIncrementally when some nodes have positions, in DrawioOptions.direction, default LR). Groups are container cells around their members, whose geometry is relative to the container. Edges carry endArrow and startArrow, the edge style, flowAnimation=1 and their waypoints
fromDrawio(xml, options?)Reads an uncompressed mxfile (the first page, or DrawioImportOptions.page by zero-based index or by name) or a bare mxGraphModel. HTML labels (html=1) lose their markup and keep their line breaks; the first line is the label and the rest the detail. A vertex that contains vertices is a group (containers, swimlanes and group cells), and child geometry is made absolute. UserObject and object wrappers and text cells on edges (edge labels) are read. A compressed page throws an Error that points to fromDrawioAsync
fromDrawioAsync(xml, options?)fromDrawio that also inflates compressed pages (base64, raw deflate and URI encoding), the default of draw.io files, with the standard DecompressionStream('deflate-raw') of browsers, workers and Node.js (an Error where the runtime has none). DrawioAsyncImportOptions.maxInflatedLength (default 20,000,000 characters) bounds the inflated page; beyond it the promise rejects with a RangeError

Shapes and markers. Each format maps the NetworkGraph shapes through one table, so a new shape is a new row:

shapeMermaiddraw.io styleAlso read from
box (default)id["…"]rounded=0Mermaid rect, proc; yEd rectangle; draw.io text, label
roundedid("…")rounded=1Mermaid rounded, event; yEd roundrectangle
diamondid{"…"}rhombusMermaid diam, decision; yEd diamond and the flowchart decision
ellipseid(("…")) (read back as circle)ellipseyEd ellipse, oval
hexagonid…shape=hexagonMermaid hex, prepare; yEd hexagon
circleid(("…"))ellipse;aspect=fixed;vwShape=circleMermaid circle, circ, sm-circ, start, stop; draw.io flowchart on-page_reference
stadiumid(["…"])rounded=1;arcSize=50;vwShape=stadiumMermaid terminal, pill; draw.io flowchart terminator
parallelogramid[/"…"/]shape=parallelogramMermaid lean-r, lean-l, in-out; yEd parallelogram; draw.io flowchart data
documentid["…"] (a box)shape=documentMermaid doc; draw.io flowchart document
cylinderid[("…")]shape=cylinder3Mermaid cyl, db, database; draw.io flowchart database, stored_data
data-objectid["…"] (a box)shape=notedataobject, card

Other shapes in a file (Mermaid subroutines and trapezoids, yEd octagons, …) are read as boxes with an unsupported-shape warning, and a shape the writers do not know is written as a box. The readers leave shape unset for boxes, except for GraphML's own shape key. Markers: Mermaid has --> for an arrow end (also for open-arrow, hollow-arrow and diamond, which have no Mermaid form), --- for markerEnd: 'none', --o for circle and --x for bar, with a matching start (<-->, o--o, x--x) when markerStart has the same form; draw.io uses classic, open, block without fill (hollow-arrow), oval, diamond, dash and none, and dashed=1 for GraphEdge.dashed (GraphML has a dashed key; Mermaid does not keep it); the yEd arrow types standard, delta, plain, white_delta (as hollow-arrow), circle, transparent_circle, diamond, white_diamond, dash and skewed_dash are read, and other ends become arrows with an unsupported-style warning.

Mermaid reading. The text starts with flowchart or graph (leading spaces are allowed) (leading spaces are allowed) (also flowchart-elk) and an optional direction; %% comment lines, %%{…}%% directives and front matter are skipped, maxItems is checked as nodes and subgraphs are met and before & lists are expanded into edges, and statements end at a line break or ; (an ignored statement such as style a fill:red; and a subgraph line end at their ; outside quotes, so subgraph g; a --> b; end is read as one line). Read: node declarations with every Mermaid delimiter ([ ], ( ), { }, (( )), , ([ ]), [[ ]], [( )], [/ /], > ], …), quoted or unquoted text and @{ shape: …, label: … }; chains (a --> b --> c) and & lists (a & b --> c, every pair); the links -->, ---, -.->, -.-, ==>, === and their longer forms, with o and x ends, < starts, |label| or -- label --> text and id@ edge IDs; and nested subgraph id[title] … end blocks as groups (subgraph title uses the title as ID, subgraph "title" gets subGraph<n>). Entity codes (#35;, #quot;) are decoded. A node belongs to the first subgraph it is mentioned in, or to a subgraph nested in that one; a mention in another subgraph is reported as group-member. The line style of dotted and thick links is not kept. Edges get the IDs e1, e2, … unless they have an id@. Ignored with an unsupported-statement warning (with its line): classDef, class, :::class, style, click, linkStyle, direction inside a subgraph, accTitle, accDescr, front matter and invisible ~~~ links. Another diagram type (sequenceDiagram, classDiagram, …) throws Unsupported Mermaid diagram type: <type>, and syntax the reader cannot follow throws Invalid Mermaid flowchart at line <n>, column <n>: <reason>.

IDs. Mermaid IDs cannot be quoted, so toMermaid writes an ID that is not ASCII letters, digits and underscores, is a Mermaid keyword (end, graph, subgraph, style, class, …) or starts with vw_ as vw_ followed by its letters and digits, with every other character as _<hex code point>_: a b becomes vw_a_20_b and end becomes vw_end. When it encodes an ID it writes the comment line %% vue-weave: encoded-ids after the header, and fromMermaid decodes IDs of that form only in text with that line, so IDs round-trip and the IDs of other Mermaid files are kept as written (order and vw_order stay two nodes). Nodes and groups share one ID space in Mermaid and GraphML, and all cells share one in draw.io: a group (or draw.io edge) whose ID another item already has is written with a suffix (_g in Mermaid, -2 in GraphML and draw.io). GraphML and draw.io edges without an ID get e1, e2, … (skipping IDs in use).

Round trips. fromGraphMl(toGraphMl(graph)) gives back every node, edge and group field listed above, and the positions and sizes exactly. fromDrawio(toDrawio(graph)) does too, except that box shapes come back unset and every node gets a size. fromMermaid(toMermaid(graph)) keeps IDs, labels, details, shapes, groups, edge labels and the markers that have a Mermaid form; nodes come back in declaration order (ungrouped nodes first). No format writes ports, data, draggable, deletable, resizable or the ports of edges.

Warnings (GraphInterchangeWarning: code, optional id of the node, edge or group, line for Mermaid, an English message):

codeCause and handling
unsupported-statementA Mermaid statement that is read but ignored (see Mermaid reading)
unsupported-shapeA shape NetworkGraph does not draw: read as a box
unsupported-styleAn edge end NetworkGraph does not draw: read as an arrow
unsupported-elementGraphML hyperedges, ports and further top-level graphs; draw.io elements and cells that are neither a vertex nor an edge: left out
skipped-node, skipped-groupA node or group without an ID or with an ID used before, and a group without any node (also through nested groups): left out
skipped-edgeAn edge with an ID used before, without both ends, or with an end that is not an imported node (a group or a missing node): left out
group-memberA Mermaid node mentioned in a second subgraph: it stays in the first
invalid-valueAn unreadable or non-positive coordinate, size or waypoint, or an unknown tone or edge style: left out
shifted-positionsCoordinates below 0 (yEd and draw.io allow them, NetworkGraph does not): every position and waypoint moves by the same amount

Untrusted files. The GraphML and draw.io readers use the XML reader of fromMsProjectXml (see Reading under Microsoft Project import): a DOCTYPE is skipped, declared entities are never expanded and nothing outside the text is loaded. All readers walk nested groups and chains with loops, and GraphInterchangeImportOptions.maxItems (default 100,000) bounds the nodes, edges and groups together (for draw.io also the label cells of edges); past it the reader throws a RangeError. Character references in draw.io HTML labels and Mermaid entity codes are decoded only for characters XML allows (not C0 controls other than tab and line breaks, surrogates, U+FFFE or U+FFFF), as in the XML reader; other references stay as written. toMermaid drops those characters from labels, as escapeXml does for the XML writers. The readers throw an Error for malformed XML (with the line and column), a document of another kind (Not a GraphML document, Not a draw.io document, Not a Mermaid flowchart), a draw.io page that does not exist and a value that is not a string.

Related exported types: GraphInterchangeWarningCode, MermaidDirection, MermaidOptions, GraphMlOptions, DrawioOptions, DrawioImportOptions, DrawioAsyncImportOptions.

Versioned JSON snapshots ​

@eightkk/vue-weave/core stores and restores a chart's data and saved view as a versioned JSON document (schemaVersion: 1). It is pure TypeScript and does not touch the DOM or the network. Nothing is written for you: you decide where the text goes.

FunctionContract
serializeWeaveSnapshot(input, options?)Converts a WeaveSnapshotInput (Maps and Sets) to the stored form, validates it and returns JSON text. Throws WeaveSnapshotError (with diagnostics) for anything that cannot be stored.
parseWeaveSnapshot(text, options?)Checks JSON syntax, version, structure and references and returns { ok: true, snapshot, diagnostics } or { ok: false, diagnostics }. options.migrations maps an old schemaVersion to a function that returns the next document. Never throws for bad input.
restoreWeaveSnapshot(snapshot, registry?)Builds live values (Maps, Sets, decoded data, resolved layouts and columns). All or nothing: on any error there is no snapshot in the result.

WeaveSnapshotV1 is a union on kind:

kinddataview
'graph'nodes, edges, optional groups, positions and sizes (as [id, value] entries)view.graph: camera ({ center, scale } in graph coordinates, independent of the container size), collapsedGroupIds, layout ({ id, options })
'timeline'rows, bars, optional dependencies, range, timeUnit ({ id, origin? }; omitted means epoch milliseconds)view.timeline
'planning'The input of levelResources (range, quantum, calendars, tasks, dependencies, resources, assignments, ...), plus optional placements and displayview.timeline

view.timeline holds window, scroll ({ time, rowId }), zoom ({ zoom, preset }), columns (id, registryId, visible, width, editorId, rendererId, in display order), search, sort (columnId, direction, comparatorId) and collapsedRowIds. Functions are never stored: columns, comparators, layouts, editors and renderers are stored by name and resolved from the registry on restore. extensions holds your own JSON under names you choose. metadata takes title, savedAt and sourceVersion; savedAt is only what you pass, so fixed metadata gives identical text for identical input. sourceVersion is a reference to where the snapshot came from and is not the current version of any server.

Rules the functions enforce:

  • NaN, Infinity, functions, symbols, class instances and other non-JSON values fail instead of being dropped or turned into null. Application data that is not JSON (Date, BigInt, Map) needs a SnapshotCodec ({ id, version?, matches, encode, decode }), stored as { "$codec", "version", "value" }. The key $codec is reserved. A codec that is missing on restore fails the restore.
  • Map entries and Set members are checked before a Map or Set is built: a repeated node ID in positions or sizes is an error, not a last-one-wins merge. Entries must name existing nodes.
  • IDs must be unique per collection. Edges, ports, group members, parent rows, dependency endpoints, assignments and saved-view IDs must refer to existing items. Assignments have no ID; the pair (taskId, resourceId) must be unique. Use business task IDs, never the IDs of projected rows.
  • Planning input is validated by the same rules as scheduleTasks. A dependency cycle or an infeasible plan is not invalid JSON: it is returned as a schedule-cycle or schedule-infeasible warning, and restored.schedule is that result.
  • Unknown fields in the document, data and view objects are errors; put your own data in extensions. Unknown versions fail. Only schemaVersion 1 exists; migrations are for your own older documents.
  • registry.onMissing: 'fallback' turns a missing layout, column, editor, renderer or comparator from an error into a warning and uses the default display. The default is 'fail'.

parseWeaveSnapshot and restoreWeaveSnapshot report SnapshotDiagnostic items (severity, code, path, message). The graph and timeline types of the restored value are the ordinary NetworkNode, GraphEdge, NetworkGroup, TimelineRow, TimelineBar and TimelineDependency.

Related exported types: JsonValue, SnapshotKind, SnapshotMetadata, SnapshotColumnDefinition, SnapshotColumnState, SnapshotSortRule, SnapshotDiagnosticCode, SnapshotDiagnosticSeverity, SnapshotLayoutFactory, SnapshotMigration, GraphCameraTarget, GraphSnapshotView, GraphSnapshotData, GraphSnapshotInput, GraphSnapshotV1, TimelineSnapshotView, TimelineSnapshotData, TimelineSnapshotInput, TimelineSnapshotV1, PlanningTaskDisplay, PlanningPlacement, PlanningSnapshotData, PlanningSnapshotInput, PlanningSnapshotV1, SerializeWeaveSnapshotOptions, ParseWeaveSnapshotOptions, ParseWeaveSnapshotResult, WeaveSnapshotRegistry, RestoreWeaveSnapshotResult, RestoredWeaveSnapshot, RestoredGraphSnapshot, RestoredGraphView, RestoredTimelineSnapshot, RestoredTimelineView, RestoredPlanningSnapshot, RestoredColumn, RestoredSortRule.

Export to SVG and PNG ​

NetworkGraph, GanttChart, TaskBoard, EventCalendar and TreeGrid expose two export methods on their template ref. They need no dependencies and never change props or component state.

MethodReturnsBehavior
exportSvg(options?)stringA standalone SVG document (xmlns, explicit width, height and viewBox) of the whole chart
exportPng(options?)Promise<Blob>exportSvg(options) rasterized in the browser to an image/png blob

The export always covers the whole content, not the viewport. NetworkGraph exports every node, edge, edge label, group and swimlane (lanes), whatever the camera position and with or without cullOffscreen; nodes in selectedIds (or selectedId) use the selected style, and the nodes and edges of highlightedNodeIds and highlightedEdgeIds the highlight colour (--vw-graph-highlight). GanttChart exports every displayed row (descendants of collapsed rows are omitted, as on screen), the row heading column and columns, header bands and ticks, nonWorkingPeriods shading, bars with progress, segments, critical outlines, float lines, deadline indicators and late outlines, milestones, baselines (the sets selected by baselineIds, with their titles), scheduling constraint markers, summaries, dependencies (including highlightedDependencyIds and, with summaryDependencies, links to summary rows) and their lag labels, the highlightedBarIds outlines, markers, markerRanges bands and header labels, the now line, the status-date and progress lines and the load histogram rows, over the whole range at the current zoom and zoom preset. Colours are read from the --vw-* custom properties in effect on the component, and the font from its computed font-family.

The export uses the default rendering. Slot content (node, edge, row, row-heading, cell, bar, tick, load-row, load-segment) cannot be reproduced; use the label options below instead. Text is clipped to its box rather than ellipsized, and the width of marker labels is estimated. Hover, focus and pointer previews are not exported.

GanttExportOptions<R, B>: timeRange (export a narrower time window), rowRange ({ start, end }, half-open indices into the displayed rows after collapsing), includeLoad (default true), includeStatusDate (default true: the statusDate line and, with showProgressLine, the progress line), background (default true), title, rowHeading (defaults to labels.rows), idPrefix, theme (an SvgExportThemeInput that overrides the colours read from CSS), barLabel(bar) and rowLabel(row). On a chart the callbacks receive its row and bar types R and B.

TaskBoard exports every column (with its count, WIP limit and minimum states and warnings), lane and shown card, respecting filter and the collapsed columns and lanes, with the selected card outlined in the accent colour and the warning colours of --vw-board-wip-warning and --vw-board-wip-under. EventCalendar exports the shown view (day, week, month or agenda) at the shown date: the toolbar title as a heading, the column headers (resource columns in the per-resource day view), the all-day row and the whole time grid from dayStart to dayEnd whatever is scrolled into view, the month grid with its "+N more" counts, or every day of the agenda however far its list is scrolled (the days with events over the week or agendaDays, each with its long date and its entries: all-day ones first, a multi-day event on every day it covers, the times written as on screen, and the resource name; labels.empty when no day has events), with timeZone, locale, weekStartsOn, formatTime, now, the direction and the labels as on screen. TreeGrid exports every displayed line (respecting expandedIds), not only the rendered window, every column at its width, the tree column at treeColumnWidth with the indentation of --vw-tree-grid-indent, the expand glyphs, row details, status lines, cell texts as treeGridCellText gives them, alignment, tones and state marks, ▲ or ▼ on columns in sort and ⏷ on filtered ones, and the selected rows and highlights in --vw-tree-grid-selected and --vw-tree-grid-highlight. The rows are drawn as passed, so apply sort and filters to them as usual (for example with projectTreeGridRows).

TaskBoardExportOptions<C>: background (default true), title, theme, includeSelection (default true), columnWidth (default 232), cardLabel(card) and cardDetail(card).

EventCalendarExportOptions<E>: background (default true), title, theme, width (default: the component's width, or 896 before mounting), heading (default the toolbar title; false draws none), includeSelection (default true) and eventLabel(event).

TreeGridExportOptions: background (default true), title, theme, rowRange and columnRange ({ start, end }, half-open indices into the displayed lines and into columns; default all), includeTreeColumn (default true) and includeHighlight (default true: the selected rows, highlightedRowIds and highlightedCells).

GraphExportOptions<N, E>: padding (default 16), background (default true), title, idPrefix, theme, includeSelection (default true), includeHighlight (default true: the current highlight props, resolved for collapsed groups as on screen), nodeLabel(node), nodeDetail(node) and edgeLabel(edge). On a graph the callbacks receive the nodes and edges it draws, GraphShownNode<N, G> and GraphShownEdge<E, G>.

exportPng additionally takes scale (PngExportOptions), the number of device pixels per CSS pixel: greater than 0 and at most 8, default 1. The PNG is ceil(width × scale) by ceil(height × scale) pixels. It must fit within 16,384 pixels per side and 268,435,456 pixels in total; otherwise the promise rejects with a RangeError that names the size. Invalid numeric options (for example a negative padding, an inverted timeRange or an out-of-range rowRange) throw a RangeError from exportSvg and reject the exportPng promise. exportSvg on a component whose input is invalid throws the current validation error. Before the component is mounted, for example during server rendering, exportSvg of every component draws with defaultSvgExportTheme and the default font (EventCalendar also at its default width of 896) instead of the values read from CSS. PNG export requires a browser (Image, canvas): elsewhere exportPng rejects with PNG export requires a browser; call exportSvg or the core builders on a server.

ts
const svg = chart.value!.exportSvg({ title: 'Plan', timeRange: { start, end } })
const png = await chart.value!.exportPng({ scale: 2 })

The core entry provides the same rendering without Vue or a DOM, for servers, workers and tests.

ExportPurpose
renderGraphSvg(layout, nodes, edges, options?)SVG document of a graph layout. GraphSvgOptions<N, E> adds lanes (GraphSwimlaneBand bands drawn first, each a g class="vw-swimlane" with a title, alternating surface and surfaceMuted fills, a surfaceMuted header with a 1.5-unit border stroke and the label clipped to the header; validated like the NetworkGraph lanes prop), groups (GraphSvgGroup rectangles), edgeBands (GraphEdgeBand by edge ID, as the NetworkGraph prop and graphFlowBands give them: a path class="vw-flow-band" stroked with the band width in the edge or highlight colour at opacity 0.5, 0.7 when highlighted, without markers, with the band label as its title; a reference band adds vw-is-reference, opacity 0.35 and the default reference dashes (10 6, lengthened for wide bands like the NetworkGraph default); bands are drawn widest first, before the other edges, and widen the exported bounds by half their width; a width that is not finite and at least 0 throws RangeError; without the option the output is unchanged), selectedIds, highlightedNodeIds and highlightedEdgeIds (a 3-unit node outline and a 2.6-unit edge with its own arrowhead, in highlightColor, default the theme's dependencyHighlight; without highlighted items the output is unchanged), padding and the label callbacks, which receive the node and edge types of the arguments, to the shared options. Node shapes, markerStart and markerEnd (markers with the IDs <idPrefix>-<marker> and <idPrefix>-start-<marker>, plus -highlight on highlighted edges, written only when used; hollow ones filled with surfaceMuted) and animated edges (dashed 6 4, without motion) are drawn as NetworkGraph draws them; an unknown marker throws RangeError
renderTimelineSvg(rows, bars, dependencies, scale, options?)SVG document of a timeline on any TimeScale. TimelineSvgOptions covers collapsedIds, timeRange, rowRange, rowHeight (66), laneCount (1), labelWidth (154), columns (validated as the GanttChart prop), showSummaries, summaryDependencies (as the GanttChart prop; needs showSummaries), headerBands, markers, markerRanges (validated as the GanttChart prop; drawn with each range's tone, or the range, rangeLine and rangeInk theme colours, at 0.7 fill opacity), now, nowLabel, tickStep or tickSteps, tickAnchor, formatTime, rowHeading, loadRows, loadSegments, loadRowHeight (44), highlightedDependencyIds, dependencyStyle (as the GanttChart prop, default orthogonal), highlightedBarIds (bars outlined in the dependencyHighlight theme colour, with the vw-is-highlighted class on their group), nonWorkingPeriods, statusDate, statusDateLabel (default "Status date"), showProgressLine, formatLag (default formatDependencyLag; labels each dependency with a non-zero lag), baselineIds, baselineLabel (default "Baseline" for timelineBaselineId, otherwise the set ID), formatVariance (default formatDependencyLag) and varianceLabels (start, finish, duration; defaults "start", "finish" and "duration"), which draw baseline sets as described in Baseline sets, constraintLabels (text of each TimelineConstraintKind in marker titles; defaults as GanttLabels) and constraintViolatedLabel (default "violated"), barLabel and rowLabel; columns and the label callbacks receive the row and bar types of the arguments (TimelineSvgOptions<R, B>). Bar fields critical, latestEnd, deadline, segments and constraints are drawn as on screen
renderTaskBoardSvg(cards, columns, options?)SVG document of a task board, grouped by groupBoardCards and validated like it. TaskBoardSvgOptions<C> adds lanes, filter, collapsedColumnIds, collapsedLaneIds, selectedId, labels (TaskBoardSvgLabels: empty, emptyCell, of, overLimit, underMinimum), columnWidth (232), collapsedColumnWidth (44), padding (10, also the gap between columns), cardLabel, cardDetail, wipWarningColor (#a8361f) and wipUnderColor (#8a5a00) to the shared options. Column headers are g class="vw-board-column-head", lane headers g class="vw-board-lane-head" and cards g class="vw-board-card", each with a title; a collapsed column is a strip with its label turned to read downwards, a collapsed lane its header with the card count
renderEventCalendarSvg(events, date, options?)SVG document of one view of an event calendar around date, validated like EventCalendar (validateCalendarEvents and the view options). EventCalendarSvgOptions<E> adds view (day, week, month or agenda; default week; any other value throws RangeError Unsupported event calendar export view), timeZone, weekStartsOn, agendaDays (the length of the agenda, validated as the EventCalendar prop), locale (en-US), resources, dayStart (0), dayEnd (24), hourHeight (48), width (896; the agenda puts the date column beside the entries from 700 and above them below), maxMonthLanes (3), now, selectedId, formatTime (default intlTimeFormatter({ locale, timeZone })), labels (EventCalendarSvgLabels: allDay, more, resources, now, recurring and the optional empty, the text of an agenda without events, default "No events to display"), heading (default the EventCalendar toolbar title; false for none) and eventLabel. Events are placed with layoutCalendarDayEvents, packCalendarEventLanes and layoutCalendarAgenda as on screen (the agenda is a g class="vw-calendar-agenda"); each is a g class="vw-calendar-event" whose title is its accessible name, with an event.color (checked like a theme colour) as its accent stripe and a double stripe for an occurrence of a recurring series. Pass concrete events (expand series with expandRecurringEvents)
renderTreeGridSvg(rows, columns, options?)SVG document of a tree grid, validated like createTreeGridIndex. TreeGridSvgOptions<R> adds cells, missingCell, expandedIds (default all: every row expanded), formatValue, labels (as TreeGrid), rowHeight (32), headerHeight (36), treeColumnWidth (240), indent (16), sort, filters and sortRules (applied with projectTreeGridRows unless applyView is false, and marked in the headers), rowRange and columnRange, includeTreeColumn (true), selectedRowIds, highlightedRowIds, highlightedCells, highlightColor (default the theme's dependencyHighlight) and selectedColor (#e3eefa). Each line is a g class="vw-tree-grid-row" (plus vw-is-status for a status line) with a title; cell states draw their mark with the full word as a title. Traversals are loops
escapeXml(text)Escape & < > " ' and drop characters that XML 1.0 forbids
defaultSvgExportThemeThe stylesheet's fallback colours as an SvgExportTheme
mirrorTimeScale(scale)A right-to-left copy of a TimeScale: range start maps to width, range end to 0

Shared SvgExportOptions are theme (SvgExportThemeInput: any of surface, surfaceMuted, text, muted, border, grid, edge, accent, onSolid, markerInk (marker and now-flag label text; default #ffffff, read from --vw-marker-ink by the component export methods), baseline, baseline2 and baseline3 (the second and third baseline slots, read from --vw-baseline-2 and --vw-baseline-3; optional in SvgExportTheme), marker, now, load, loadOverload, loadCapacity, dependencyHighlight, nonWorking, critical, float, deadline, status, constraint and constraintViolated (read from --vw-constraint and --vw-constraint-violated), range, rangeInk and rangeLine (marker ranges without a tone, read from --vw-range, --vw-range-ink and --vw-range-line) and per-tone ink, line, pale, solid; the ten newest are optional in SvgExportTheme and always present in defaultSvgExportTheme), fontFamily, title, background, idPrefix (letters, digits, _, . and -; default vw-export) and direction (ltr or rtl). The builders validate their input like the components do and throw RangeError for invalid numbers or geometry and Error for bad references and IDs. Theme colours must be CSS colour values: hex, colour names and keywords (transparent, currentColor), and the functions rgb, rgba, hsl, hsla, hwb, lab, lch, oklab, oklch, color, color-mix, light-dark, var and calc; any other function (such as url()), quotes, semicolons and other punctuation throw a RangeError naming the key (edge, blue.pale). All text and attribute values are escaped; the output contains no scripts, event attributes or external references.

Colours that need a stylesheet (var(), currentColor) are written as given by every core builder, renderGraphSvg and renderTimelineSvg as well as renderTaskBoardSvg, renderEventCalendarSvg (an event's color) and renderTreeGridSvg (highlightColor, selectedColor), because they run without a DOM and cannot compute styles. Such a colour paints as intended only where the SVG is placed inline in a page that defines it; in a standalone file, an <img> or a PNG nothing defines the variables (an unresolved var(--booking-color) paints black). Pass concrete colours when you call the builders directly. The exportSvg and exportPng methods of TaskBoard, EventCalendar and TreeGrid resolve them first and write the computed colour (an rgb() or color() value); colours without var() or currentColor are written as given. An event color such as var(--booking-color) is computed on the event's rendered button, so a variable defined on .vw-calendar-event or on an ancestor applies as on screen (for an event drawn in several segments, the first one). An event without a rendered button (one the shown view does not draw, such as an event hidden in a month day's "+N more") is computed on the calendar's root element, so only variables defined there or on its ancestors apply; before mounting, nothing is computed and colours are written as given. A var() without a value falls back to the tone colour, as the stylesheet does on screen. The colour is read as it is at export time: the calendar's own selected, focused, hover and drag styles do not change it (the export draws the selection outline itself), but a stylesheet of yours that sets the variable only in such a state is read in that state. currentColor and var() in --vw-board-wip-warning, --vw-board-wip-under, --vw-tree-grid-highlight and --vw-tree-grid-selected are computed on the component's root element (TaskBoard cards and TreeGrid rows and cells have tones, not colour values). The callbacks (eventLabel, cardLabel, cardDetail, formatValue, column value) receive the same objects as the props and slots, class instances included.

Related exported types: GraphPngExportOptions, GanttPngExportOptions, TaskBoardPngExportOptions, EventCalendarPngExportOptions, TreeGridPngExportOptions, SvgToneColors.

MIT ライセンスで公開しています。