File size: 34,652 Bytes
cfd4ac1 0e600b9 cfd4ac1 0e600b9 cfd4ac1 b80130d cfd4ac1 bbfcaa6 cfd4ac1 992a41f cfd4ac1 992a41f cfd4ac1 f5696cb 0e600b9 cfd4ac1 0e600b9 cfd4ac1 992a41f cfd4ac1 b80130d cfd4ac1 bbfcaa6 cfd4ac1 bdac669 992a41f cfd4ac1 0e600b9 cfd4ac1 992a41f bdac669 b80130d bdac669 b80130d bdac669 992a41f bdac669 b80130d bdac669 992a41f cfd4ac1 992a41f cfd4ac1 992a41f cfd4ac1 992a41f cfd4ac1 992a41f cfd4ac1 bdac669 b80130d bdac669 b80130d bdac669 b80130d bdac669 cfd4ac1 bdac669 cfd4ac1 bdac669 cfd4ac1 bdac669 cfd4ac1 bdac669 cfd4ac1 bdac669 cfd4ac1 b80130d bdac669 b80130d bdac669 cfd4ac1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 | // sheet/ribbonInsert.tsx β the INSERT TAB of the Sheet's ribbon (wave 54, base kit part 2a;
// filled and REGISTERED by W54-T10, owner instruction 5, ruling R3).
//
// ββ REGISTERED NOW, AND IT WAS NOT BEFORE ON PURPOSE. The base kit shipped this module exporting
// its descriptor with an EMPTY group list, and `Ribbon.tsx`'s `TABS` carried Home alone, because a
// registered empty tab paints a clickable tab that opens a blank toolbar row. W54-T10 gives the tab
// its groups and adds its descriptor to that array in the same change, which is the whole of
// the wiring this module owes: the shell reads `keys` for the roving order, `groups` for the row,
// and the rest of the descriptor for the tab button.
//
// β WHAT A TAB MODULE OWES THE SHELL is set out in `ribbonHome.tsx`'s header, and this file is the
// same three exports:
// `INSERT_KEYS` the control keys this tab renders, IN ROVING ORDER. Every key here joins the
// shell's `ControlKey` union automatically, which is what makes a control rendered
// under an unlisted name a TYPE ERROR.
// `insertGroups` the groups, as a function of the shell's `RibbonTabContext`.
// `INSERT_TAB` the descriptor.
//
// S70 R14 revokes wave 54 R3's PivotTable exclusion. PivotTable now creates its own worksheet;
// it uses a workbook callback alongside the cell/chart doors, leaving RibbonActionKind stable.
//
// ββ THESE CONTROLS DO NOT ADD A NAMED ACT, AND THAT IS DELIBERATE. `RibbonActionKind` is closed
// by an exhaustive switch in `SheetGrid.tsx`, a file this lane does not own, so a new member would
// be a compile error in every lane at once. A chart, a sparkline, a link and a note are DOCUMENT
// WRITES rather than named acts, and they take the document's own doors instead, handed over as
// `ctx.insert` (`Ribbon.tsx::RibbonInsertDoor`): a chart is a TAB level key and takes the
// replace-the-list door, and the other three are CELL keys and take the same one commit door a
// style patch takes.
// β W54-T11 ADDS ONE CALL TO `act`, AND IT NAMES AN ACT THAT ALREADY EXISTED. The chart dialog's
// database tab writes bound cells, and a bound cell is `stale` until the workbook refreshes, so
// the block would sit empty without `refresh`. The union is untouched.
//
// β NO FAKE AFFORDANCE. `RibbonProps.canImport`'s own comment is the precedent: a control is
// offered only where a door for it exists. When `ctx.insert` is undefined every control below
// renders DISABLED, through a native `<fieldset disabled>` rather than a per-button flag, because
// the shell's shared `control(...)` helper takes no disabled argument and this lane may not widen
// it. In the app after `SheetGrid.tsx` wires the door it is never undefined; the fence is what
// keeps this module honest if the prop is ever dropped.
//
// β A TAB MODULE IS A FUNCTION, NOT A COMPONENT. `Ribbon.tsx` CALLS `activeTab.groups(ctx)` during
// its own render, so a hook here would attach to the shell and its order would change the moment
// somebody switched tabs. That is why the two small forms below are UNCONTROLLED: they read their
// value out of the submitted form rather than out of a `useState` this file cannot have.
//
// β DESIGN CONTRACT (DESIGN.md 2 through 5): inline SVG on `currentColor` and never emoji, token
// only colour and type, Excel's Title Case labels (R41), no em dash or en dash in a string that reaches a
// screen, and the two overlay shapes kept apart: POPOVERS originate at their trigger through
// `AnchoredOverlay` (the link and comment forms) while MODALS REMAIN CENTRED (the chart dialog,
// through `useOverlayLayer` and `BodyPortal`). Never a local keydown listener in either case.
import { useState } from "react";
import type { FormEvent } from "react";
import { useCellRefHighlight } from "./refHighlight";
import type { RibbonTabContext } from "./Ribbon";
import {
IconChartColumn, IconChartBar, IconChartLine, IconChartArea,
IconChartPie, IconChartDonut, IconChartScatter, IconChartRecommended,
} from "./ribbonIcons";
// W59-T08 adds shortcuts into the same dialog; chart creation still uses its single commit door.
// ββ W54-T11 (ruling R5) β THE CHART GALLERY IS GONE AND A DIALOG STANDS WHERE IT STOOD. R5 reads
// "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a database source is
// a second tab in the same dialog. Ship both." A gallery of eight kinds cannot carry a second
// source, so the eight kinds moved INTO the dialog and this tab keeps ONE Charts control that
// opens ONE surface. DESIGN.md 4: modals remain centred, which is what makes this a dialog rather
// than a wider popover.
// β THE HOOKS LIVE IN THE DIALOG, WHICH IS A REAL COMPONENT. `insertGroups` is a function the
// shell calls during its own render, so it still may not hold state of its own; `ChartDialog` may
// hold all it likes, and the shell's popover state is what mounts it.
import ChartDialog from "./ChartDialog";
import type { ChartRange } from "./ChartDialog";
// ββ W54-T14 β THE LINK FORM MOVED OUT AND GREW THE OTHER TWO KINDS. W54-T10 shipped an
// uncontrolled one-field form here that could only write `kind: "url"`; a kind picker whose
// refusal has to survive a keystroke needs state, and `insertGroups` is a function the ribbon
// shell calls during its own render and may not hold one. So the Links group mounts a real
// component, exactly as the Charts group mounts `ChartDialog`, and that component owns its own
// anchored overlay. The Comments group's form stays uncontrolled: it has one field and no refusal.
import LinkDialog from "./LinkDialog";
import type { CellLink } from "./LinkDialog";
import { MAX_CELL_NOTE } from "./types";
import type { Cell, SheetChartSpec, SparklineKind } from "./types";
// β THE DOCUMENT'S OWN ADDRESSER, in SHEET coordinates. The door hands over a sheet-coordinate
// rectangle and a sheet-coordinate reader, so the address a cell edit is keyed by is built with
// the same function `SheetGrid.tsx` builds every other one with. A second spelling of A1 in this
// file would be a second answer to a question the document already answers.
import { addressOf } from "./sheetState";
// β THE DOCUMENT'S OWN A1 PARSER, and the reason this ticket does not write a second one. A rule's
// range, a chart's range and a sparkline's range are all the same rectangle spelled the same way,
// so `D40:B2` normalises here exactly as it does in the conditional-format dialog.
import { parseRange } from "./rules";
import type { RuleRect } from "./rules";
import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
// β This tab's own stylesheet, a component-owned side-effect import, exactly as `ribbonHome.tsx`
// imports its own. See the stylesheet's header for what it restates and why.
import "../styles/wave54/ribbon-insert.css";
const CHART_SHORTCUTS = [
{ key: "chart-column", moreKey: "chart-column-choices", kind: "column", label: "Column", Icon: IconChartColumn, kt: "V" },
{ key: "chart-bar", moreKey: "chart-bar-choices", kind: "bar", label: "Bar", Icon: IconChartBar, kt: "B" },
{ key: "chart-line", moreKey: "chart-line-choices", kind: "line", label: "Line", Icon: IconChartLine, kt: "L" },
{ key: "chart-area", moreKey: "chart-area-choices", kind: "area", label: "Area", Icon: IconChartArea, kt: "A" },
{ key: "chart-pie", moreKey: "chart-pie-choices", kind: "pie", label: "Pie", Icon: IconChartPie, kt: "P" },
{ key: "chart-donut", moreKey: "chart-donut-choices", kind: "donut", label: "Donut", Icon: IconChartDonut, kt: "O" },
{ key: "chart-scatter", moreKey: "chart-scatter-choices", kind: "scatter", label: "Scatter", Icon: IconChartScatter, kt: "X" },
] as const;
const CHARTS = [
"chart", ...CHART_SHORTCUTS.flatMap(({ key, moreKey }) => [key, moreKey]), "chart-recommended",
] as const;
const SPARKLINES = ["sparkline-line", "sparkline-column", "sparkline-winloss"] as const;
const LINKS = ["link"] as const;
const COMMENTS = ["comment"] as const;
const CELL_DATA = ["cell-data"] as const;
const PIVOTS = ["pivot-table"] as const;
/**
* ββ THE INSERT TAB'S ROVING ORDER, WHICH IS ALSO ITS TYPE. The shell spreads this into the union
* every `control(...)` key is checked against, so the arrays above are the single source of both
* the reading order and the vocabulary.
* β THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no `control(...)`
* call rendering it makes ArrowRight land on nothing, with every gate still green, so the two are
* changed together or not at all.
*/
export const INSERT_KEYS = [...PIVOTS, ...CHARTS, ...SPARKLINES, ...LINKS, ...COMMENTS, ...CELL_DATA] as const;
/**
* β THE EIGHT KINDS AND THE FALLBACK RECTANGLE BOTH MOVED TO `ChartDialog.tsx` (W54-T11), which
* is where they are now chosen and computed. The dialog also SAYS which rectangle it will cover,
* which is what the retired gallery could not do: the range was grown silently, because
* `RibbonTabContext` carries no notice path and there was nowhere honest to say so.
*/
/** A short unique id. No uuid library, and none is needed: this is a key within one document. */
const chartId = (): string =>
`ch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
function IconChart() {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
<path d="M2.5 13.5h11" />
<path d="M4.5 11.5V7M8 11.5V3.5M11.5 11.5V6" />
</svg>
);
}
function IconSparkLine() {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
<path d="M2.5 11L5.5 6.5L8.5 9L13.5 4" />
</svg>
);
}
function IconSparkColumn() {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
<path d="M3 12V9M6.5 12V5M10 12V7.5M13.5 12V3.5" />
</svg>
);
}
function IconSparkWinLoss() {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
<path d="M2 8h12" />
<path d="M4 8V5M7.5 8v3M11 8V5" />
</svg>
);
}
function IconLink() {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
<path d="M6.8 9.2a2.6 2.6 0 0 0 3.7 0l2-2a2.6 2.6 0 0 0-3.7-3.7l-1 1" />
<path d="M9.2 6.8a2.6 2.6 0 0 0-3.7 0l-2 2a2.6 2.6 0 0 0 3.7 3.7l1-1" />
</svg>
);
}
function IconComment() {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
<path d="M2.5 3.5h11v7h-6l-3 2.5v-2.5h-2z" />
</svg>
);
}
/**
* The large Chart opener stays a single command. Chart-kind split controls use a separate
* choices half to open the same dialog at that kind, without inserting before confirmation.
*/
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ββ W54-T13 β THE TWO RANGES EXCEL ASKS FOR, AND WHY THE SECOND ONE IS NOT A FIELD ON THE SPEC.
//
// Excel's "Create Sparklines" asks for a DATA range and a LOCATION range, and W54-T10 shipped
// neither: it wrote one sparkline onto the cell the selection started on. That was the honest
// minimum for a tab that had to exist; a location range is what makes the group useful, because
// the ordinary case is one sparkline PER ROW of a block, not one sparkline for a block.
//
// β THE LOCATION IS THE CELL THE SPEC IS STORED ON. `CellSparkline` carries a DATA range and
// nothing else, deliberately: a location range of six cells is six cells each carrying their own
// spec over their own slice, which is what makes one of them movable, deletable and undoable on
// its own. Adding a `location` field would have given the document two answers to "where is this
// drawn" and let them disagree.
//
// β THE MAPPING IS STATED ON SCREEN, in one sentence, because it is the one thing a person cannot
// guess: N location cells split the data range into N slices ALONG THE OTHER AXIS. When the counts
// do not divide the form REFUSES rather than truncating, because a silently shortened range is a
// picture of data nobody chose.
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/** Where one sparkline goes, and the slice of the data range it draws. */
interface SparkPlacement {
col: number;
row: number;
range: RuleRect;
}
/** `B2` for one cell, `B2:E7` for a rectangle. The corners are normalised on the way in. */
const rangeText = (r: RuleRect): string => {
const a = addressOf(Math.min(r.col0, r.col1), Math.min(r.row0, r.row1));
const b = addressOf(Math.max(r.col0, r.col1), Math.max(r.row0, r.row1));
return a === b ? a : `${a}:${b}`;
};
const many = (n: number, word: string): string => `${n} ${word}${n === 1 ? "" : "s"}`;
const KIND_LABEL: Record<SparklineKind, string> = {
line: "Line Sparkline",
column: "Column Sparkline",
winloss: "Win/Loss Sparkline",
};
/**
* β A SENSIBLE NEIGHBOUR, RATHER THAN AN EMPTY BOX. Excel leaves the location blank and makes the
* person work it out; the two shapes people actually select have an obvious answer, so it is
* offered and stays editable:
* β’ a single COLUMN of readings gets ONE cell directly under it, because slicing a column of
* numbers into one sparkline per number would draw a picture of one value;
* β’ anything else gets a COLUMN of cells directly to the right, one per row, which is the
* one sparkline per row that the group exists for. A single row is that same rule with one
* row in it, so it lands on the single cell to the right.
*/
const defaultLocation = (r: RuleRect): RuleRect => {
const c0 = Math.min(r.col0, r.col1);
const c1 = Math.max(r.col0, r.col1);
const r0 = Math.min(r.row0, r.row1);
const r1 = Math.max(r.row0, r.row1);
if (c0 === c1 && r1 > r0) return { col0: c0, row0: r1 + 1, col1: c0, row1: r1 + 1 };
return { col0: c1 + 1, row0: r0, col1: c1 + 1, row1: r1 };
};
/**
* THE MAPPING RULE, IN CODE. One cell takes the whole data range; a location COLUMN of N cells
* takes the rows of the data range in N equal slices; a location ROW of N cells takes its columns
* the same way. Anything that does not divide comes back as a refusal in one sentence.
*/
const planSparklines = (
data: RuleRect,
loc: RuleRect,
): { items: SparkPlacement[] } | { why: string } => {
const dc0 = Math.min(data.col0, data.col1);
const dc1 = Math.max(data.col0, data.col1);
const dr0 = Math.min(data.row0, data.row1);
const dr1 = Math.max(data.row0, data.row1);
const lc0 = Math.min(loc.col0, loc.col1);
const lc1 = Math.max(loc.col0, loc.col1);
const lr0 = Math.min(loc.row0, loc.row1);
const lr1 = Math.max(loc.row0, loc.row1);
const lCols = lc1 - lc0 + 1;
const lRows = lr1 - lr0 + 1;
const n = lCols * lRows;
if (n === 1) {
return { items: [{ col: lc0, row: lr0, range: { col0: dc0, row0: dr0, col1: dc1, row1: dr1 } }] };
}
if (lCols > 1 && lRows > 1) {
return { why: "A location range of more than one cell has to be a single row or a single column." };
}
const items: SparkPlacement[] = [];
if (lCols === 1) {
const rows = dr1 - dr0 + 1;
if (rows % n !== 0) {
return { why: `Those counts do not divide: ${many(rows, "row")} into ${many(n, "cell")}.` };
}
const step = rows / n;
for (let i = 0; i < n; i += 1) {
items.push({
col: lc0,
row: lr0 + i,
range: { col0: dc0, col1: dc1, row0: dr0 + i * step, row1: dr0 + i * step + step - 1 },
});
}
return { items };
}
const cols = dc1 - dc0 + 1;
if (cols % n !== 0) {
return { why: `Those counts do not divide: ${many(cols, "column")} into ${many(n, "cell")}.` };
}
const step = cols / n;
for (let i = 0; i < n; i += 1) {
items.push({
col: lc0 + i,
row: lr0,
range: { row0: dr0, row1: dr1, col0: dc0 + i * step, col1: dc0 + i * step + step - 1 },
});
}
return { items };
};
/**
* ββ A REAL COMPONENT, AND THAT IS WHAT BUYS THE STATE. `insertGroups` is a FUNCTION the shell
* calls during its own render, so a `useState` written there would attach to the shell and its
* hook order would change the moment somebody switched tabs. The two older forms in this file
* dodged that by staying uncontrolled; a refusal has to survive a keystroke, so this one is
* mounted as a component instead. The shell's popover state is what mounts and unmounts it, which
* is also what re-seeds the two fields from the current selection each time it opens.
*
* β NO LOCAL KEYDOWN LISTENER. Escape comes from `AnchoredOverlay` and from nowhere else.
*/
function SparklineForm({
kind,
selection,
onCreate,
}: {
kind: SparklineKind;
selection: RuleRect | null;
onCreate: (kind: SparklineKind, items: SparkPlacement[]) => void;
}) {
const seed: RuleRect = selection ?? { col0: 0, row0: 0, col1: 0, row1: 0 };
const [data, setData] = useState(() => rangeText(seed));
const [location, setLocation] = useState(() => rangeText(defaultLocation(seed)));
const [why, setWhy] = useState("");
// Both ranges are outlined on the grid while the form is open (refHighlight.ts).
useCellRefHighlight([data, location]);
const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const d = parseRange(data);
if (!d) {
setWhy("That data range is not an address like B2:E2.");
return;
}
const l = parseRange(location);
if (!l) {
setWhy("That location range is not an address like F2.");
return;
}
const plan = planSparklines(d, l);
if ("why" in plan) {
setWhy(plan.why);
return;
}
onCreate(kind, plan.items);
};
return (
<form className="sheet-ribbon-insert-fields" onSubmit={submit}>
<p className="sheet-ribbon-insert-title">{KIND_LABEL[kind]}</p>
<label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-spark-data">
Data range
</label>
<input
id="sheet-insert-spark-data"
name="data"
type="text"
className="sheet-ribbon-insert-input"
value={data}
placeholder="B2:E2"
onChange={(event) => { setData(event.target.value); setWhy(""); }}
/>
<label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-spark-location">
Location range
</label>
<input
id="sheet-insert-spark-location"
name="location"
type="text"
className="sheet-ribbon-insert-input"
value={location}
placeholder="F2"
onChange={(event) => { setLocation(event.target.value); setWhy(""); }}
/>
<p className="sheet-ribbon-insert-hint">
A location column of N cells takes N rows of the data range, a location row of N cells
takes N columns, and one cell takes the whole range.
</p>
{why && <p className="sheet-ribbon-insert-refusal" role="alert">{why}</p>}
<button type="submit" className="sheet-ribbon-item">Add sparkline</button>
</form>
);
}
export const insertGroups = (ctx: RibbonTabContext) => {
// β `item` IS NO LONGER TAKEN OFF THE CONTEXT, and that is W54-T11's doing rather than an
// oversight: the only menu this tab ever painted was the chart gallery, and the eight kinds are
// buttons inside `ChartDialog` now. The shell still offers the helper to every tab.
const { open, anchorEl, openPop, closePop, control, group, word, large, stack, insert, act, openCellData } = ctx;
const chartShortcut = CHART_SHORTCUTS.find(({ key, moreKey }) => open === key || open === moreKey);
const chartOpen = open === "chart" || open === "chart-recommended" || !!chartShortcut;
const chartCaret = (
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-caret">
<path d="m4.5 6.5 3.5 3 3.5-3" />
</svg>
);
/**
* β THE ANCHOR CELL, IN SHEET COORDINATES. The door hands the selection over already translated
* (`SheetGrid.tsx` maps every view index through `realCol` / `realRow` before it gets here), so
* nothing in this file has to know that a hidden row moves what glide calls row 3.
*/
const anchorAt = (): { col: number; row: number } => {
const sel = insert?.selection;
if (!sel) return { col: 0, row: 0 };
return { col: Math.min(sel.col0, sel.col1), row: Math.min(sel.row0, sel.row1) };
};
/**
* ββ THE ONE DOOR OUT OF THE DIALOG, AND BOTH TABS COME THROUGH IT (W54-T11, R5).
*
* The cell-range tab hands over a kind and a rectangle and nothing else, which is exactly what
* the retired gallery did. The database tab ALSO hands over the cells it wants written, and this
* is where the ordering matters:
* 1. the cells go in ONE call, so the block is ONE history step and ONE save;
* 2. the chart is anchored over the rectangle those cells occupy;
* 3. a refresh runs, because a `stale` cell holds no value until the workbook refreshes.
*
* β RULING R9 SURVIVES THIS INTACT. The chart still READS CELLS: it is handed a rectangle and
* never a database, a binding or a query, so there is still exactly one way to fetch a number in
* this document and it is the binding path a bound cell already uses.
*
* β `refresh` IS AN EXISTING `RibbonActionKind`. Nothing new joins that union here: adding a
* member would be a compile error in `SheetGrid.tsx`'s exhaustive switch, in every lane at once.
*/
const createChart = (
kind: SheetChartSpec["kind"],
range: ChartRange,
cells?: Record<string, Cell>,
) => {
if (!insert) return;
if (cells) insert.onCells(cells);
insert.onCharts([...insert.charts, { id: chartId(), range, kind }]);
closePop();
if (cells) act("refresh");
};
/**
* ββ EVERY LOCATION CELL IN ONE CALL, WHICH IS ONE HISTORY STEP AND ONE SAVE. `insert.onCells`
* takes many cells at a time for exactly this: six sparklines written one call each would be six
* undos to take back and six writes to the store for one gesture.
*
* β A CELL WITH NO RECORD BECOMES `empty` / `typed` CARRYING ONLY THE SPARKLINE. That is the
* shape W54-T09 provisioned server side (`platform/core/sheets.py::_clean_sparkline` keeps the
* slot on an empty cell), and it is the ordinary case: a sparkline cell usually holds no text.
* A cell that DOES have a record is amended rather than replaced, so a sparkline never eats a
* formula, a style or a binding, and the renderer draws it as an underlay under that cell's own
* value (`sheet/sparkline.ts`).
*/
const addSparklines = (kind: SparklineKind, items: SparkPlacement[]) => {
if (!insert) return;
const edits: Record<string, Cell> = {};
for (const item of items) {
const held = insert.cellAt(item.col, item.row);
const sparkline = { kind, range: item.range };
edits[addressOf(item.col, item.row)] = held
? { ...held, sparkline }
: { kind: "empty", state: "typed", sparkline };
}
insert.onCells(edits);
closePop();
};
/**
* Which of the three sparkline triggers is showing its form, or `null` when none is.
* β THE KIND IS THE TRIGGER, NOT A CONTROL INSIDE THE FORM. Three buttons stay three
* affordances (the group is Excel's own three, and a menu over three items costs a press without
* buying anything); putting a fourth kind picker in the popover would also let `aria-expanded` on
* the Line button describe a Column form.
*/
const openKind: SparklineKind | null =
open === "sparkline-line" ? "line"
: open === "sparkline-column" ? "column"
: open === "sparkline-winloss" ? "winloss"
: null;
/**
* β W54-T14 β ALL THREE KINDS THROUGH ONE WRITER. The dialog has already decided which kind it
* is and validated the target for that kind; this only amends the anchor cell, so a link never
* eats a value, a formula, a style or a binding.
*/
const addLink = (link: CellLink) => {
if (!insert) return;
const { col, row } = anchorAt();
const held = insert.cellAt(col, row);
const next: Cell = held ? { ...held, link } : { kind: "empty", state: "typed", link };
insert.onCells({ [addressOf(col, row)]: next });
};
const addNote = (note: string) => {
if (!insert) return;
const { col, row } = anchorAt();
const held = insert.cellAt(col, row);
const next: Cell = held
? { ...held, note }
: { kind: "empty", state: "typed", note };
insert.onCells({ [addressOf(col, row)]: next });
};
/** What the anchor cell already carries, so the two forms open on it rather than on blank. */
const heldAt = (): Cell | null => {
if (!insert) return null;
const { col, row } = anchorAt();
return insert.cellAt(col, row);
};
return (
/* β THE FENCE IS THE DISABLED STATE, AND IT IS NATIVE RATHER THAN PER BUTTON. A
`<fieldset disabled>` disables every descendant form control the browser knows about, so one
attribute covers the six controls and both forms without the shell's `control(...)` helper
growing a ninth argument this lane may not give it. The rules that strip its own box live in
`styles/wave54/ribbon-insert.css`. */
<fieldset className="sheet-ribbon-insert-fence" disabled={!insert}>
{group("Tables", large(<>
{control("pivot-table", "PivotTable", <>
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
<path d="M2.5 2.5h11v11h-11zM2.5 6h11M6 2.5v11M6 10h7.5" />
</svg>
{word("PivotTable")}
</>, () => { insert?.onCreatePivot?.(); closePop(); },
false, undefined, "T", undefined, !insert?.onCreatePivot)}
</>))}
{group("Charts", (
<>
{large(<>
{control("chart", "Chart", <><IconChart />{word("Chart")}</>,
openPop("chart"), false, open === "chart", "C", "gallery", undefined, "dialog")}
</>)}
<span className="sheet-chart-gallery">
{CHART_SHORTCUTS.map(({ key, moreKey, label, Icon, kt }) => (
<span className="sheet-chart-kind" key={key}>
{control(key, `${label} Chart`, <Icon />,
openPop(key), false, open === key, kt, "gallery", undefined, "dialog")}
<span className="sheet-chart-kind-caret">
{/* Q prefixes chart choices; the overflow trigger already owns Y. */}
{control(moreKey, `${label} Chart Choices`, chartCaret,
openPop(moreKey), false, open === moreKey, `Q${kt}`, "gallery", undefined, "dialog")}
</span>
</span>
))}
<span className="sheet-chart-kind sheet-chart-kind-recommended">
{control("chart-recommended", "Recommended Charts", <IconChartRecommended />,
openPop("chart-recommended"), false, open === "chart-recommended", "R", "gallery", undefined, "dialog")}
</span>
</span>
{/* β MOUNTED CONDITIONALLY, never rendered behind an `open` prop: `useOverlayLayer`
claims Escape the moment it runs, so a hidden dialog would hold the key. The
`insert` guard is belt and braces, and it is not the fieldset's job here: the
dialog portals to the body and is therefore OUTSIDE the disabled fence. */}
{chartOpen && insert && (
<ChartDialog
key={open}
selection={insert.selection}
initialKind={chartShortcut?.kind}
onClose={closePop}
onCreate={createChart}
/>
)}
</>
))}
{/* β THREE CONTROLS RATHER THAN ONE WITH A GALLERY. Excel's Sparklines group is exactly
three buttons, the choice is small and closed, and a menu over three items costs a press
without buying anything. Each one opens the SAME authoring form, already knowing its kind.
β `data-kt-opens="gallery"` IS WHAT MAKES THE ALT LAYER OPEN THEM. `KeyTips.tsx` fires a
badge with no such attribute as a plain command and never descends; these three now open
a popover, so they have to say so or the key tip would flash and land nowhere. */}
{group("Sparklines", (
<>
{stack(
<>
{control("sparkline-line", "Line", <IconSparkLine />,
openPop("sparkline-line"), false, open === "sparkline-line", "SL", "gallery")}
</>,
<>
{control("sparkline-column", "Column", <IconSparkColumn />,
openPop("sparkline-column"), false, open === "sparkline-column", "SC", "gallery")}
</>,
<>
{control("sparkline-winloss", "Win/Loss", <IconSparkWinLoss />,
openPop("sparkline-winloss"), false, open === "sparkline-winloss", "SW", "gallery")}
</>
)}
{openKind && insert && (
/* β `role="dialog"` RATHER THAN `role="menu"`, for the reason the Link form states
one group down: a form is not a list of commands.
β `key` FORCES A REMOUNT PER KIND, which is what re-seeds the two fields from the
current selection when the person moves from Line to Column without closing. */
<AnchoredOverlay
anchor={anchorEl}
className="sheet-ribbon-pop sheet-ribbon-pop-portal sheet-ribbon-insert-form"
onDismiss={closePop}
role="dialog"
ariaLabel={KIND_LABEL[openKind]}
>
<SparklineForm
key={openKind}
kind={openKind}
selection={insert.selection}
onCreate={addSparklines}
/>
</AnchoredOverlay>
)}
</>
))}
{group("Links", (
large(<>
{control("link", "Link", <><IconLink />{word("Link")}</>,
openPop("link"), false, open === "link", "I", "gallery")}
{/* β MOUNTED CONDITIONALLY AND OUTSIDE THE FIELDSET, for the two reasons the Charts
group states: an overlay claims Escape the moment it runs, so a hidden one would
hold the key; and it portals to the body, which puts it outside the disabled fence,
so the `insert` guard is written here rather than inherited.
β `role="dialog"` RATHER THAN `role="menu"` (the component says so): a form is not a
list of commands, and a menu role would promise arrow-key item navigation that is
not there. The shell's `control(...)` still writes `aria-haspopup="menu"` on the
trigger, which it hardcodes for every expandable control; widening that helper is
outside this lane's fence, so the mismatch is recorded here rather than papered
over. */}
{open === "link" && insert && (
<LinkDialog
anchor={anchorEl}
held={heldAt()?.link}
onClose={closePop}
onSubmit={(link) => { addLink(link); closePop(); }}
/>
)}
</>)
))}
{group("Comments", (
large(<>
{control("comment", "Comment", <><IconComment />{word("Comment")}</>,
openPop("comment"), false, open === "comment", "M", "gallery")}
{open === "comment" && (
<AnchoredOverlay
anchor={anchorEl}
className="sheet-ribbon-pop sheet-ribbon-pop-portal sheet-ribbon-insert-form"
onDismiss={closePop}
role="dialog"
ariaLabel="Comment"
>
<form
className="sheet-ribbon-insert-fields"
onSubmit={(event) => {
event.preventDefault();
const field = event.currentTarget.elements.namedItem("note");
const note = field instanceof HTMLTextAreaElement ? field.value.trim() : "";
if (note) addNote(note.slice(0, MAX_CELL_NOTE));
closePop();
}}
>
<label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-comment">
Comment
</label>
<textarea
id="sheet-insert-comment"
name="note"
className="sheet-ribbon-insert-area"
rows={3}
maxLength={MAX_CELL_NOTE}
defaultValue={heldAt()?.note ?? ""}
/>
{/* β W54-T14 β IT EDITS RATHER THAN REPLACES, and the label is what says so. The
field is already seeded from the cell's own note above, so a second Insert >
Comment on the same cell opens what is there; the wording is the only part a
person can see before they have typed anything. */}
<button type="submit" className="sheet-ribbon-item">
{heldAt()?.note ? "Update comment" : "Add comment"}
</button>
</form>
</AnchoredOverlay>
)}
</>)
))}
{group("Cell Data", large(<>
{control("cell-data", "Cell Database", <>
<svg viewBox="0 0 16 16" stroke="currentColor" fill="none" aria-hidden="true" className="sheet-ribbon-icon">
<ellipse cx="8" cy="3.5" rx="5" ry="2" />
<path d="M3 3.5v9c0 1.1 2.2 2 5 2s5-.9 5-2v-9M3 8c0 1.1 2.2 2 5 2s5-.9 5-2" />
</svg>
{word("Cell Database")}
</>, openCellData, undefined, undefined, "D")}
</>))}
</fieldset>
);
};
/**
* β THE DESCRIPTOR, REGISTERED IN `Ribbon.tsx::TABS` SINCE W54-T10.
* β `kt` IS THE TAB'S OWN FIRST-LEVEL KEY-TIP BADGE and `N` is what Excel uses for Insert. Tab
* badges are scoped to the tab depth by `KeyTips.tsx`, so this does not collide with the Number
* format control's own `N` one depth down.
*/
export const INSERT_TAB = {
id: "insert",
key: "tab-insert",
kt: "N",
label: "Insert",
bodyClass: "sheet-ribbon-insert",
toolbarLabel: "Insert",
keys: INSERT_KEYS,
groups: insertGroups,
} as const;
|