File size: 11,228 Bytes
cfd4ac1
 
 
a83fcff
 
 
 
cfd4ac1
a83fcff
 
cfd4ac1
 
 
 
 
 
 
 
a93637f
 
 
 
 
 
 
 
cfd4ac1
 
a83fcff
cfd4ac1
 
 
 
 
 
a83fcff
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
cfd4ac1
c920df3
cfd4ac1
c920df3
 
 
 
 
 
 
 
 
cfd4ac1
a83fcff
c920df3
 
a83fcff
 
 
 
 
c920df3
a93637f
 
 
 
 
 
c920df3
a93637f
a83fcff
 
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
 
a83fcff
cfd4ac1
 
 
a93637f
 
 
 
 
 
 
 
 
 
cfd4ac1
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ---------------------------------------------------------------------------------------------
// sheet/cellBorders.ts β€” THE PER-CELL BORDER PAINT, LIFTED OUT OF `SheetGrid.tsx`.
//
// ⭐ WAVE 54 BASE KIT β€” this is the border seam lifted from `SheetGrid.tsx::paintCell`, so border
// geometry can change without disturbing the grid's selection, chart, marquee or formula paint.
// W55-T05 makes the live cell rectangle the source for four filled edge strips and gives inserted
// borders their explicit black default. Both main and frozen grids still call this one paint door.
//
// β›” `tokenColour` CAME ALONG, AND THAT IS A FENCE DECISION RATHER THAN A DESIGN ONE. Border paint
// and the grid's other canvas paint read CSS properties through one memoised resolver, which was
// a module-local `const` there and is not exported. The three ways out were: import it back from
// `SheetGrid.tsx` (a cycle, and a NEW export on the file this split exists to shrink), copy it
// (two caches for one palette), or move the definition here and let `SheetGrid.tsx` import it.
// The third is the only one that is a pure move, so it is the one taken. `sheet/colors.ts` is the
// tidier home and this file's editing fence does not reach it β€” recorded here rather than done
// behind the fence, the same way `sheet/index.ts` records W49-T01's route constant.
// ---------------------------------------------------------------------------------------------

// ⭐⭐ S67-T14 / CONTRACT C2: EACH SIDE NOW CARRIES `{style, color}`, AND A STORED `true` STILL
// PAINTS EXACTLY AS IT ALWAYS DID (thin, `--sheet-cell-border`, today's strips byte for byte).
// β›” THIS FILE TAKES ONLY TYPES FROM `./types`, ON PURPOSE. `verify_grid_ux.py`'s S65-T06 probe
// transpiles THIS FILE ALONE and runs it in a bare `vm` context, so a value import would be a
// `require("./types")` that cannot resolve there. The side reader below is therefore local, and
// its style table is typed `Record<CellBorderStyle, ...>`, so the compiler refuses a table that
// drifts from `types.ts::CELL_BORDER_STYLES`.
import type { CellBorder, CellBorderStyle } from "./types";

/**
 * A CSS custom-property name resolved to the hue the document currently gives it.
 *
 * ⭐ MEMOISED, BECAUSE `drawCell` RUNS PER CELL PER FRAME. `getComputedStyle` forces a style
 * recalculation on every call, and a 26 by 40 viewport of styled cells would ask for it a
 * thousand times a frame. The tokens are declared once on `:root` and nothing in this app swaps
 * a palette at runtime, so one read each is the whole of it.
 *
 * Each caller supplies its own safe fallback. Inserted cell borders deliberately supply black;
 * other canvas paint keeps the existing palette fallbacks owned by `SheetGrid`.
 */
const TOKEN_CACHE = new Map<string, string>();
export const tokenColour = (token: string, fallback: string): string => {
  if (!token) return fallback;
  if (token.startsWith("#")) return token;
  const cached = TOKEN_CACHE.get(token);
  if (cached !== undefined) return cached || fallback;
  const value = getComputedStyle(document.documentElement).getPropertyValue(token).trim();
  TOKEN_CACHE.set(token, value);
  return value || fallback;
};

/** The executable default for an inserted border. The stylesheet publishes the same value. */
export const DEFAULT_CELL_BORDER_COLOR = "#000000";

export interface CellBorderRect { x: number; y: number; width: number; height: number }
type BorderStrip = CellBorderRect;
type Side = keyof CellBorder;
const SIDES: readonly Side[] = ["top", "right", "bottom", "left"];

/**
 * How each of the seven is drawn, chosen so no two look alike at 100% zoom. `weight` is the band
 * in pixels; `on` / `off` is a dash pattern in pixels (0 = solid); `rails` draws two 1px lines
 * with a 1px gap across a 3px band; `alpha` lightens the hairline below a dotted line.
 */
interface LineSpec { weight: number; on: number; off: number; rails?: boolean; alpha?: number }
const LINE_SPECS: Record<CellBorderStyle, LineSpec> = {
  thin: { weight: 1, on: 0, off: 0 },
  medium: { weight: 2, on: 0, off: 0 },
  thick: { weight: 3, on: 0, off: 0 },
  dashed: { weight: 1, on: 6, off: 3 },
  dotted: { weight: 1, on: 2, off: 2 },
  double: { weight: 3, on: 0, off: 0, rails: true },
  hair: { weight: 1, on: 1, off: 1, alpha: 0.6 },
};

interface PaintLine { style: CellBorderStyle; color: string }
const HEX_COLOUR = /^#[0-9a-fA-F]{6}$/;

/**
 * One stored side as a drawable line, or `null` when it draws nothing. `true` is the legacy thin
 * line in the border token's colour (black). Mirrors `types.ts::borderLine`; see the import note
 * for why it is not imported.
 */
const sideLine = (side: unknown): PaintLine | null => {
  if (side === true) {
    return { style: "thin", color: tokenColour("--sheet-cell-border", DEFAULT_CELL_BORDER_COLOR) };
  }
  if (!side || typeof side !== "object") return null;
  const { style, color } = side as { style?: unknown; color?: unknown };
  if (typeof style !== "string" || !Object.prototype.hasOwnProperty.call(LINE_SPECS, style)) return null;
  if (typeof color !== "string" || !HEX_COLOUR.test(color)) return null;
  return { style: style as CellBorderStyle, color };
};

/** Is this side drawn at all? Cheap: no colour token is resolved. */
const sideOn = (side: unknown): boolean =>
  side === true || (!!side && typeof side === "object"
    && Object.prototype.hasOwnProperty.call(LINE_SPECS, (side as { style?: unknown }).style as string)
    && HEX_COLOUR.test(String((side as { color?: unknown }).color ?? "")));

/**
 * Turn the current Glide cell rectangle into canonical one-pixel boundary strips.
 *
 * A boundary owns the pixel starting at its coordinate: left = x, right = x + width,
 * top = y, bottom = y + height. Horizontal spans are [x, x + width); vertical spans
 * are [y, y + height). Neighbours therefore tile a run and agree on the SAME shared edge.
 * The live rect remains the source on every paint, including scroll and zoom.
 *
 * Glide's damage clip really can start at x + 1 / y + 1, and its column clip excludes
 * the right boundary. SheetGrid restores these strips after Glide releases those clips,
 * before spill masks, with a pane clip instead. Moving a boundary inward is not a clip fix:
 * it creates a different edge for each neighbour. Keep this geometry independent of neighbours.
 */
export function cellBorderStrips(rect: CellBorderRect, border: CellBorder): BorderStrip[] {
  const left = rect.x;
  const top = rect.y;
  const right = rect.x + rect.width;
  const bottom = rect.y + rect.height;
  const width = Math.max(0, right - left);
  const height = Math.max(0, bottom - top);
  const strips: BorderStrip[] = [];
  if (width === 0 || height === 0) return strips;
  const on = { top: sideOn(border.top), right: sideOn(border.right),
    bottom: sideOn(border.bottom), left: sideOn(border.left) };
  if (on.top && width > 0) strips.push({ x: left, y: top, width, height: 1 });
  if (on.right && height > 0) strips.push({ x: right, y: top, width: 1, height });
  if (on.bottom && width > 0) strips.push({ x: left, y: bottom, width, height: 1 });
  if (on.left && height > 0) strips.push({ x: left, y: top, width: 1, height });
  // Half-open spans tile runs without overlap; close a box's one otherwise-excluded corner.
  if (on.right && on.bottom) strips.push({ x: right, y: bottom, width: 1, height: 1 });
  return strips;
}

/**
 * Fill `[start, end)` along one axis with a dash pattern anchored to ABSOLUTE coordinates, so a
 * run of neighbouring cells reads as one continuous dashed line rather than restarting per cell.
 */
function fillPattern(
  ctx: CanvasRenderingContext2D, horizontal: boolean, at: number,
  start: number, end: number, spec: LineSpec,
): void {
  const period = spec.on + spec.off;
  for (let k = Math.floor(start / period) * period; k < end; k += period) {
    const a = Math.max(k, start);
    const b = Math.min(k + spec.on, end);
    if (b <= a) continue;
    if (horizontal) ctx.fillRect(a, at, b - a, 1);
    else ctx.fillRect(at, a, 1, b - a);
  }
}

/**
 * Paint the cell's own enabled edges outside the caller's text clip.
 *
 * ⭐ S67-T14: each side in its own weight, pattern and colour. THIN keeps the canonical strips
 * above byte for byte (a legacy `true` is thin), so neighbours still tile one shared edge. A
 * WEIGHTED band is CENTRED on the boundary pixel (`[b - floor(w/2), ... + w)`), which is a
 * function of the boundary alone, so both owners of a shared edge paint the same band; it is
 * lengthened across the perpendicular band, so a thick box closes its corners. SheetGrid paints
 * these after glide releases its clips, under a pane clip, so the band may cross the cell edge.
 */
export function paintCellBorders(
  ctx: CanvasRenderingContext2D,
  rect: CellBorderRect,
  border: CellBorder | undefined,
): void {
  if (!border) return;
  const x0 = rect.x;
  const y0 = rect.y;
  const x1 = rect.x + rect.width;
  const y1 = rect.y + rect.height;
  if (x1 - x0 <= 0 || y1 - y0 <= 0) return;
  const lines: Record<Side, PaintLine | null> = {
    top: sideLine(border.top), right: sideLine(border.right),
    bottom: sideLine(border.bottom), left: sideLine(border.left),
  };
  if (!SIDES.some((side) => lines[side])) return;
  ctx.save();
  for (const side of SIDES) {
    const line = lines[side];
    if (!line) continue;
    const spec = LINE_SPECS[line.style];
    ctx.fillStyle = line.color;
    ctx.globalAlpha = spec.alpha ?? 1;
    if (line.style === "thin") {
      cellBorderStrips(rect, { [side]: true }).forEach((s) => ctx.fillRect(s.x, s.y, s.width, s.height));
      if (side === "bottom" && lines.right?.style === "thin") ctx.fillRect(x1, y1, 1, 1);
      continue;
    }
    const horizontal = side === "top" || side === "bottom";
    const boundary = side === "top" ? y0 : side === "bottom" ? y1 : side === "left" ? x0 : x1;
    const start = horizontal ? x0 : y0;
    const end = horizontal ? x1 : y1;
    if (spec.on > 0) {
      fillPattern(ctx, horizontal, boundary, start, end, spec);
      continue;
    }
    const lead = Math.floor(spec.weight / 2);
    const from = start - lead;
    const to = end - lead + spec.weight;
    if (!spec.rails) {
      if (horizontal) ctx.fillRect(from, boundary - lead, to - from, spec.weight);
      else ctx.fillRect(boundary - lead, from, spec.weight, to - from);
      continue;
    }
    // DOUBLE: an outer rail across the whole band and an inner rail that stops short of a
    // perpendicular double, so a double box meets itself as two nested frames, not a hash.
    const inward = side === "top" || side === "left" ? 1 : -1;
    const outer = boundary - inward;
    const inner = boundary + inward;
    const [lo, hi] = horizontal ? (["left", "right"] as const) : (["top", "bottom"] as const);
    const innerFrom = lines[lo]?.style === "double" ? start + 1 : start;
    const innerTo = lines[hi]?.style === "double" ? end : end + 1;
    if (horizontal) {
      ctx.fillRect(from, outer, to - from, 1);
      ctx.fillRect(innerFrom, inner, innerTo - innerFrom, 1);
    } else {
      ctx.fillRect(outer, from, 1, to - from);
      ctx.fillRect(inner, innerFrom, 1, innerTo - innerFrom);
    }
  }
  ctx.restore();
}