charts.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import { EVENT_MAGIC, trackEvent } from "./analytics";
  2. import colors from "./colors";
  3. import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from "./constants";
  4. import { newElement, newTextElement, newLinearElement } from "./element";
  5. import { ExcalidrawElement } from "./element/types";
  6. import { randomId } from "./random";
  7. const BAR_WIDTH = 32;
  8. const BAR_GAP = 12;
  9. const BAR_HEIGHT = 256;
  10. export interface Spreadsheet {
  11. title: string | null;
  12. labels: string[] | null;
  13. values: number[];
  14. }
  15. export const NOT_SPREADSHEET = "NOT_SPREADSHEET";
  16. export const VALID_SPREADSHEET = "VALID_SPREADSHEET";
  17. type ParseSpreadsheetResult =
  18. | { type: typeof NOT_SPREADSHEET; reason: string }
  19. | { type: typeof VALID_SPREADSHEET; spreadsheet: Spreadsheet };
  20. const tryParseNumber = (s: string): number | null => {
  21. const match = /^[$€£¥₩]?([0-9,]+(\.[0-9]+)?)$/.exec(s);
  22. if (!match) {
  23. return null;
  24. }
  25. return parseFloat(match[1].replace(/,/g, ""));
  26. };
  27. const isNumericColumn = (lines: string[][], columnIndex: number) =>
  28. lines.slice(1).every((line) => tryParseNumber(line[columnIndex]) !== null);
  29. const tryParseCells = (cells: string[][]): ParseSpreadsheetResult => {
  30. const numCols = cells[0].length;
  31. if (numCols > 2) {
  32. return { type: NOT_SPREADSHEET, reason: "More than 2 columns" };
  33. }
  34. if (numCols === 1) {
  35. if (!isNumericColumn(cells, 0)) {
  36. return { type: NOT_SPREADSHEET, reason: "Value is not numeric" };
  37. }
  38. const hasHeader = tryParseNumber(cells[0][0]) === null;
  39. const values = (hasHeader ? cells.slice(1) : cells).map((line) =>
  40. tryParseNumber(line[0]),
  41. );
  42. if (values.length < 2) {
  43. return { type: NOT_SPREADSHEET, reason: "Less than two rows" };
  44. }
  45. return {
  46. type: VALID_SPREADSHEET,
  47. spreadsheet: {
  48. title: hasHeader ? cells[0][0] : null,
  49. labels: null,
  50. values: values as number[],
  51. },
  52. };
  53. }
  54. const valueColumnIndex = isNumericColumn(cells, 0) ? 0 : 1;
  55. if (!isNumericColumn(cells, valueColumnIndex)) {
  56. return { type: NOT_SPREADSHEET, reason: "Value is not numeric" };
  57. }
  58. const labelColumnIndex = (valueColumnIndex + 1) % 2;
  59. const hasHeader = tryParseNumber(cells[0][valueColumnIndex]) === null;
  60. const rows = hasHeader ? cells.slice(1) : cells;
  61. if (rows.length < 2) {
  62. return { type: NOT_SPREADSHEET, reason: "Less than 2 rows" };
  63. }
  64. return {
  65. type: VALID_SPREADSHEET,
  66. spreadsheet: {
  67. title: hasHeader ? cells[0][valueColumnIndex] : null,
  68. labels: rows.map((row) => row[labelColumnIndex]),
  69. values: rows.map((row) => tryParseNumber(row[valueColumnIndex])!),
  70. },
  71. };
  72. };
  73. const transposeCells = (cells: string[][]) => {
  74. const nextCells: string[][] = [];
  75. for (let col = 0; col < cells[0].length; col++) {
  76. const nextCellRow: string[] = [];
  77. for (let row = 0; row < cells.length; row++) {
  78. nextCellRow.push(cells[row][col]);
  79. }
  80. nextCells.push(nextCellRow);
  81. }
  82. return nextCells;
  83. };
  84. export const tryParseSpreadsheet = (text: string): ParseSpreadsheetResult => {
  85. // Copy/paste from excel, spreadhseets, tsv, csv.
  86. // For now we only accept 2 columns with an optional header
  87. // Check for tab separated values
  88. let lines = text
  89. .trim()
  90. .split("\n")
  91. .map((line) => line.trim().split("\t"));
  92. // Check for comma separated files
  93. if (lines.length && lines[0].length !== 2) {
  94. lines = text
  95. .trim()
  96. .split("\n")
  97. .map((line) => line.trim().split(","));
  98. }
  99. if (lines.length === 0) {
  100. return { type: NOT_SPREADSHEET, reason: "No values" };
  101. }
  102. const numColsFirstLine = lines[0].length;
  103. const isSpreadsheet = lines.every((line) => line.length === numColsFirstLine);
  104. if (!isSpreadsheet) {
  105. return {
  106. type: NOT_SPREADSHEET,
  107. reason: "All rows don't have same number of columns",
  108. };
  109. }
  110. const result = tryParseCells(lines);
  111. if (result.type !== VALID_SPREADSHEET) {
  112. const transposedResults = tryParseCells(transposeCells(lines));
  113. if (transposedResults.type === VALID_SPREADSHEET) {
  114. return transposedResults;
  115. }
  116. }
  117. return result;
  118. };
  119. // For the maths behind it https://excalidraw.com/#json=6320864370884608,O_5xfD-Agh32tytHpRJx1g
  120. export const renderSpreadsheet = (
  121. spreadsheet: Spreadsheet,
  122. x: number,
  123. y: number,
  124. ): ExcalidrawElement[] => {
  125. const values = spreadsheet.values;
  126. const max = Math.max(...values);
  127. const chartHeight = BAR_HEIGHT + BAR_GAP * 2;
  128. const chartWidth = (BAR_WIDTH + BAR_GAP) * values.length + BAR_GAP;
  129. const maxColors = colors.elementBackground.length;
  130. const bgColors = colors.elementBackground.slice(2, maxColors);
  131. // Put all the common properties here so when the whole chart is selected
  132. // the properties dialog shows the correct selected values
  133. const commonProps = {
  134. backgroundColor: bgColors[Math.floor(Math.random() * bgColors.length)],
  135. fillStyle: "hachure",
  136. fontFamily: DEFAULT_FONT_FAMILY,
  137. fontSize: DEFAULT_FONT_SIZE,
  138. groupIds: [randomId()],
  139. opacity: 100,
  140. roughness: 1,
  141. strokeColor: colors.elementStroke[0],
  142. strokeSharpness: "sharp",
  143. strokeStyle: "solid",
  144. strokeWidth: 1,
  145. verticalAlign: "middle",
  146. } as const;
  147. const minYLabel = newTextElement({
  148. ...commonProps,
  149. x: x - BAR_GAP,
  150. y: y - BAR_GAP,
  151. text: "0",
  152. textAlign: "right",
  153. });
  154. const maxYLabel = newTextElement({
  155. ...commonProps,
  156. x: x - BAR_GAP,
  157. y: y - BAR_HEIGHT - minYLabel.height / 2,
  158. text: max.toLocaleString(),
  159. textAlign: "right",
  160. });
  161. const xAxisLine = newLinearElement({
  162. type: "line",
  163. x,
  164. y,
  165. startArrowhead: null,
  166. endArrowhead: null,
  167. width: chartWidth,
  168. points: [
  169. [0, 0],
  170. [chartWidth, 0],
  171. ],
  172. ...commonProps,
  173. });
  174. const yAxisLine = newLinearElement({
  175. type: "line",
  176. x,
  177. y,
  178. startArrowhead: null,
  179. endArrowhead: null,
  180. height: chartHeight,
  181. points: [
  182. [0, 0],
  183. [0, -chartHeight],
  184. ],
  185. ...commonProps,
  186. });
  187. const maxValueLine = newLinearElement({
  188. type: "line",
  189. x,
  190. y: y - BAR_HEIGHT - BAR_GAP,
  191. startArrowhead: null,
  192. endArrowhead: null,
  193. ...commonProps,
  194. strokeStyle: "dotted",
  195. width: chartWidth,
  196. points: [
  197. [0, 0],
  198. [chartWidth, 0],
  199. ],
  200. });
  201. const bars = values.map((value, index) => {
  202. const barHeight = (value / max) * BAR_HEIGHT;
  203. return newElement({
  204. ...commonProps,
  205. type: "rectangle",
  206. x: x + index * (BAR_WIDTH + BAR_GAP) + BAR_GAP,
  207. y: y - barHeight - BAR_GAP,
  208. width: BAR_WIDTH,
  209. height: barHeight,
  210. });
  211. });
  212. const xLabels =
  213. spreadsheet.labels?.map((label, index) => {
  214. return newTextElement({
  215. ...commonProps,
  216. text: label.length > 8 ? `${label.slice(0, 5)}...` : label,
  217. x: x + index * (BAR_WIDTH + BAR_GAP) + BAR_GAP * 2,
  218. y: y + BAR_GAP / 2,
  219. width: BAR_WIDTH,
  220. angle: 5.87,
  221. fontSize: 16,
  222. textAlign: "center",
  223. verticalAlign: "top",
  224. });
  225. }) || [];
  226. const title = spreadsheet.title
  227. ? newTextElement({
  228. ...commonProps,
  229. text: spreadsheet.title,
  230. x: x + chartWidth / 2,
  231. y: y - BAR_HEIGHT - BAR_GAP * 2 - maxYLabel.height,
  232. strokeSharpness: "sharp",
  233. strokeStyle: "solid",
  234. textAlign: "center",
  235. })
  236. : null;
  237. trackEvent(EVENT_MAGIC, "chart", "bars", bars.length);
  238. return [
  239. title,
  240. ...bars,
  241. ...xLabels,
  242. xAxisLine,
  243. yAxisLine,
  244. maxValueLine,
  245. minYLabel,
  246. maxYLabel,
  247. ].filter((element) => element !== null) as ExcalidrawElement[];
  248. };