Merge remote-tracking branch 'origin/sub_laptop_3' into sub_laptop_2

This commit is contained in:
2026-09-27 20:29:44 +09:00
7 changed files with 417 additions and 31 deletions
+82 -6
View File
@@ -84,9 +84,25 @@ function internStyle(book: Workbook, style: CellStyle): number {
return book.서식.length - 1;
}
/** 칸 자리에서 물려받는 서식(칸 서식 없을 때) — 행 · 열 · 0 */
function setComments(s: Sheet, notes: Record<string, string>) {
if (Object.keys(notes).length) s.comments = notes;
else delete s.comments;
}
/** 시트 통째 서식 */
const sheetStyle = (s: Sheet) => s.기본?.서식 ?? 0;
/** 칸 자리에서 물려받는 서식(칸 서식 없을 때) — 행 · 열 · 시트 · 0 */
const inherited = (s: Sheet, r: number, c: number) =>
s.행?.[r + 1]?.서식 ?? s.열?.[colName(c)]?.서식 ?? 0;
s.행?.[r + 1]?.서식 ?? s.열?.[colName(c)]?.서식 ?? sheetStyle(s);
/** 시트 `기본` 한 칸 — undefined 면 지움 · 빈 `기본` 도 지움 */
function setSheetDefault(s: Sheet, key: "서식" | "열폭" | "행높이", value: number | undefined) {
const d = (s.기본 ??= {});
if (value === undefined) delete d[key];
else d[key] = value;
if (!Object.keys(d).length) delete s.기본;
}
const addr = (시트: string, r: number, c: number): SheetCellAddress => ({ 시트, r, c });
@@ -179,8 +195,8 @@ function restyle(
const setInfo = (axis: "행" | "열", key: string) => {
const table = (s[axis] ??= {});
const info = (table[key] ??= {});
const idx = f(info.서식 ?? 0);
if (idx) info.서식 = idx;
const idx = f(info.서식 ?? sheetStyle(s));
if (idx !== sheetStyle(s)) info.서식 = idx;
else delete info.서식;
if (!Object.keys(info).length) delete table[key];
};
@@ -201,8 +217,9 @@ function restyle(
const fullRows = isFull(rg, true);
const fullCols = isFull(rg, false);
if (fullRows && fullCols) {
// ponytail: 시트 통째 서식은 든 칸 · 있는 행 · 열 서식만 — 시트 기본 서식 칸이 계약에 없음
whole = true;
const idx = f(sheetStyle(s));
setSheetDefault(s, "서식", idx || undefined);
for (const k of Object.keys(s.행 ?? {})) setInfo("행", k);
for (const k of Object.keys(s.열 ?? {})) setInfo("열", k);
} else if (fullRows || fullCols) {
@@ -265,6 +282,15 @@ function insertDelete(
if (i !== undefined) cells[rows ? toA1(i, p.c) : toA1(p.r, i)] = cell;
}
s.칸 = cells;
if (s.comments) {
const notes: Record<string, string> = {};
for (const [a1, text] of Object.entries(s.comments)) {
const p = parseA1(a1);
const i = p && span(rows ? p.r : p.c);
if (p && i !== undefined && i !== null) notes[rows ? toA1(i, p.c) : toA1(p.r, i)] = text;
}
setComments(s, notes);
}
const merges: CellRange[] = [];
for (const m of mergesOf(s)) {
@@ -289,6 +315,23 @@ function insertDelete(
else delete s[axis];
}
// 넣은 줄은 위(왼) 줄 서식 · 폭 · 높이를 따라감(엑셀 「위와 같은 서식」) — 첫 줄 앞 넣기는 안 따라감
if (insert && at > 0) {
for (const [a1, cell] of Object.entries(s.칸)) {
const p = parseA1(a1)!;
if ((rows ? p.r : p.c) !== at - 1 || cell.서식 === undefined) continue;
for (let k = 0; k < n; k++)
s.칸[rows ? toA1(at + k, p.c) : toA1(p.r, at + k)] = { 서식: cell.서식 };
}
const info = s[axis]?.[rows ? String(at) : colName(at - 1)];
if (info) {
const { 숨김: _hidden, ...look } = info;
if (Object.keys(look).length)
for (let k = 0; k < n; k++)
s[axis]![rows ? String(at + k + 1) : colName(at + k)] = { ...look };
}
}
const key = rows ? "행" : "열";
const frozen = s.틀고정?.[key];
if (frozen && at < frozen)
@@ -326,6 +369,23 @@ function move(book: Workbook, cmd: Of<"옮기기">): CommandEffect {
rewriteAll(book, cmd);
for (const [a1] of cellsIn(t, [dst])) delete t.칸[a1];
for (const [r, c, cell] of moved) t.칸[toA1(r, c)] = cell;
// 메모도 칸과 같이 — 덮은 자리 메모는 지움
const carriedNotes: [string, string][] = [];
const srcNotes = { ...s.comments };
for (const [a1, text] of Object.entries(srcNotes)) {
const p = parseA1(a1);
if (p && inRange(src, p.r, p.c)) {
carriedNotes.push([toA1(p.r + dr, p.c + dc), text]);
delete srcNotes[a1];
}
}
setComments(s, srcNotes);
const dstNotes = { ...t.comments };
for (const a1 of Object.keys(dstNotes)) {
const p = parseA1(a1);
if (p && inRange(dst, p.r, p.c)) delete dstNotes[a1];
}
setComments(t, { ...dstNotes, ...Object.fromEntries(carriedNotes) });
const sm = mergesOf(s);
const carried = sm.filter((m) => rangeInside(m, src));
@@ -410,6 +470,20 @@ function setAxis<V>(
return { 종류: "묶음", 명령: [...groups].map(([g, list]) => undoOf(list, JSON.parse(g))) };
}
/** 모두 고르기 폭 · 높이 — 시트 `기본` 에 두고 줄마다 값은 지움(엑셀 기본 폭 · 높이) */
function sheetSize(s: Sheet, axis: "행" | "열", value: number | null): CommandEffect {
const before = clone(s);
const prop = axis === "열" ? "폭" : "높이";
setSheetDefault(s, axis === "열" ? "열폭" : "행높이", value ?? undefined);
const table = s[axis] as Record<string, Record<string, unknown>> | undefined;
for (const [k, info] of Object.entries(table ?? {})) {
delete info[prop];
if (!Object.keys(info).length) delete table![k];
}
if (table && !Object.keys(table).length) delete s[axis];
return { undo: { 종류: "시트통째", 시트: before }, cells: [], rebuild: false };
}
// ── 시트 ────────────────────────────────────────────────────────────────────
function addSheet(book: Workbook, cmd: Of<"시트더하기">): CommandEffect {
@@ -506,6 +580,7 @@ export function applyCommand(book: Workbook, command: Command): CommandEffect {
return unmerge(book, command);
case "열폭": {
const s = sheetOf(book, command.시트);
if (new Set(command.열).size >= MAX_COLS) return sheetSize(s, "열", command.폭);
return plain(
setAxis(s, "열", command.열, "폭", command.폭, (열, 폭) => ({
종류: "열폭",
@@ -517,6 +592,7 @@ export function applyCommand(book: Workbook, command: Command): CommandEffect {
}
case "행높이": {
const s = sheetOf(book, command.시트);
if (new Set(command.행).size >= MAX_ROWS) return sheetSize(s, "행", command.높이);
return plain(
setAxis(s, "행", command.행, "높이", command.높이, (행, 높이) => ({
종류: "행높이",
@@ -611,7 +687,7 @@ export function compactStyles(book: Workbook): void {
map(0);
for (const s of book.시트) {
for (const cell of Object.values(s.칸)) if (cell.서식 !== undefined) cell.서식 = map(cell.서식);
for (const info of [...Object.values(s.행 ?? {}), ...Object.values(s.열 ?? {})])
for (const info of [...Object.values(s.행 ?? {}), ...Object.values(s.열 ?? {}), s.기본 ?? {}])
if (info.서식 !== undefined) info.서식 = map(info.서식);
}
book.서식 = next;
+25 -8
View File
@@ -66,6 +66,25 @@ function single(value: EvalResult): Scalar {
: err("#VALUE!", "범위를 값 하나로 못 씀");
}
/** 엔진이 만든 범위 — 적힌 자리(끝 자름 전) · 암묵 교차에 씀 */
export interface PlacedRange extends RangeValue {
r0: number;
c0: number;
r1: number;
c1: number;
}
/** 범위 → 칸 하나 — 1×1 이면 그 칸 · 아니면 식 든 행(한 열 범위) · 열(한 행 범위)과 겹친 칸(엑셀 암묵 교차) */
export function intersect(value: EvalResult, at: { r: number; c: number }): Scalar {
if (!isRange(value) || (value.rows === 1 && value.cols === 1)) return single(value);
const p = value as Partial<PlacedRange>;
if (p.r0 !== undefined && p.c0 !== undefined && p.r1 !== undefined && p.c1 !== undefined) {
if (p.c0 === p.c1 && at.r >= p.r0 && at.r <= p.r1) return value.at(at.r - p.r0, 0);
if (p.r0 === p.r1 && at.c >= p.c0 && at.c <= p.c1) return value.at(0, at.c - p.c0);
}
return err("#VALUE!", "범위가 식 든 행 · 열과 안 겹침");
}
/** 수로 — 빈 칸 0 · 참거짓 1/0 · 수 글 · 아니면 `#VALUE!` · 범위는 칸 하나일 때만 */
export function asNumber(value: EvalResult): Frac | ErrorValue {
const v = single(value);
@@ -237,15 +256,15 @@ export function evaluate(node: FormulaNode, ctx: EvalContext): EvalResult {
return ctx.range(sheet, normRange(node.from.r, node.from.c, node.to.r, node.to.c));
}
case "unary": {
const v = evaluate(node.arg, ctx);
if (node.op === "+") return single(v);
const v = intersect(evaluate(node.arg, ctx), ctx);
if (node.op === "+") return v;
const n = asNumber(v);
if (isError(n)) return n;
return node.op === "-" ? frac(-n.n, n.d) : div(n, HUNDRED);
}
case "binary": {
const left = evaluate(node.left, ctx);
const right = evaluate(node.right, ctx);
const left = intersect(evaluate(node.left, ctx), ctx);
const right = intersect(evaluate(node.right, ctx), ctx);
if (node.op === "&") {
const a = asText(left);
if (isError(a)) return a;
@@ -258,10 +277,8 @@ export function evaluate(node: FormulaNode, ctx: EvalContext): EvalResult {
const b = asNumber(right);
return isError(b) ? b : arith(node.op, a, b);
}
const a = single(left);
if (isError(a)) return a;
const b = single(right);
return isError(b) ? b : compareOp(node.op, a, b);
if (isError(left)) return left;
return isError(right) ? right : compareOp(node.op, left, right);
}
case "call": {
const fn = getFunction(node.name);
+55 -12
View File
@@ -8,7 +8,8 @@
import { FormulaError, ZERO } from "@ui/sheet/ui_template_sheet_frac";
import { cellId, fromCellId, inRange, parseA1, toA1 } from "./spreadsheet_address";
import { err, evaluate, inputValue, isRange, toCalcValue } from "./spreadsheet_eval";
import { err, evaluate, inputValue, intersect, toCalcValue } from "./spreadsheet_eval";
import type { PlacedRange } from "./spreadsheet_eval";
import { parseFormula } from "./spreadsheet_parser";
import type {
CalcEngine,
@@ -19,7 +20,6 @@ import type {
EvalResult,
FormulaNode,
ParseResult,
RangeValue,
Scalar,
SheetCellAddress,
Workbook,
@@ -175,7 +175,7 @@ export function createCalcEngine(book: Workbook): CalcEngine {
if (at) index(idx, cellId(at.r, at.c), cell);
}
}
for (const key of precs.keys()) compute(key);
for (const key of precs.keys()) ensure(key);
}
function ctxFor(sheet: string, r: number, c: number): EvalContext {
@@ -188,7 +188,7 @@ export function createCalcEngine(book: Workbook): CalcEngine {
return vals.get(key) ?? null;
}
function range(sheet: string, rg: CellRange): RangeValue {
function range(sheet: string, rg: CellRange): PlacedRange {
const s = sheets.get(sheet);
// ponytail: 행 · 열 전체 범위는 값 든 끝까지만 — INDEX(A:A, 끝 너머)는 #REF! 로 갈림
const r1 = Math.min(rg.r1, Math.max(rg.r0, s?.maxR ?? 0));
@@ -198,9 +198,54 @@ export function createCalcEngine(book: Workbook): CalcEngine {
rows: r1 - rg.r0 + 1,
cols: c1 - rg.c0 + 1,
at: (i, j) => read(sheet, rg.r0 + i, rg.c0 + j),
...rg,
};
}
/** 가리키는 식 칸들(범위는 넓이 · 든 칸 수 중 작은 쪽으로 훑음) */
function formulaPrecs(key: string): string[] {
const out: string[] = [];
for (const d of precs.get(key) ?? []) {
const s = sheets.get(d.sheet);
if (!s) continue;
const r1 = Math.min(d.range.r1, s.maxR);
const c1 = Math.min(d.range.c1, s.maxC);
if ((r1 - d.range.r0 + 1) * (c1 - d.range.c0 + 1) <= s.cells.size) {
for (let r = d.range.r0; r <= r1; r++)
for (let c = d.range.c0; c <= c1; c++) {
const k = keyOf(d.sheet, cellId(r, c));
if (precs.has(k)) out.push(k);
}
} else
for (const id of s.cells.keys()) {
const k = keyOf(d.sheet, id);
const { r, c } = fromCellId(id);
if (precs.has(k) && inRange(d.range, r, c)) out.push(k);
}
}
return out;
}
/** 앞 식 칸부터 반복으로 풂 — 깊은 사슬에도 스택이 안 넘침 · 고리는 compute 가 잡음 */
function ensure(key: string): Scalar {
const todo: [string, boolean][] = [[key, false]];
const seen = new Set<string>();
while (todo.length) {
const [k, ready] = todo.pop()!;
if (state.get(k) === DONE) continue;
if (ready) {
compute(k);
continue;
}
if (seen.has(k)) continue;
seen.add(k);
todo.push([k, true]);
for (const d of formulaPrecs(k))
if (!seen.has(d) && state.get(d) !== DONE) todo.push([d, false]);
}
return vals.get(key) ?? null;
}
/** 식 칸 하나 풂 — 풀이 중인 칸을 다시 만나면 그 사이가 고리 */
function compute(key: string): Scalar {
const st = state.get(key);
@@ -217,7 +262,6 @@ export function createCalcEngine(book: Workbook): CalcEngine {
const cell = sheets.get(시트)!.cells.get(cellId(r, c))!;
let v: Scalar;
try {
// ponytail: 끌어 풀기는 재귀 — 수천 칸 사슬이면 스택이 넘침, 그때 위상 순서 반복으로
v = run(cell.식!, ctxFor(시트, r, c));
} catch (e) {
state.delete(key);
@@ -249,10 +293,8 @@ export function createCalcEngine(book: Workbook): CalcEngine {
return err("#DIV/0!", e.message);
return err("#VALUE!", e instanceof Error ? e.message : String(e));
}
// ponytail: 범위를 칸에 넣으면 한 칸만 — 엑셀 암묵 교차(식 든 행 · 열과 겹친 칸)는 안 함
if (isRange(v))
v = v.rows === 1 && v.cols === 1 ? v.at(0, 0) : err("#VALUE!", "범위를 칸 하나에 못 넣음");
return v === null ? ZERO : v;
const one = intersect(v, ctx);
return one === null ? ZERO : one;
}
function dependents(key: string, out: Set<string>) {
@@ -291,12 +333,13 @@ export function createCalcEngine(book: Workbook): CalcEngine {
state.delete(k);
cycle.delete(k);
}
for (const k of dirty) if (precs.has(k)) compute(k);
for (const k of dirty) if (precs.has(k)) ensure(k);
return [...dirty].map(splitKey);
},
rebuild,
value(sheet, r, c) {
return read(sheet, r, c);
const key = keyOf(sheet, cellId(r, c));
return precs.has(key) ? ensure(key) : (vals.get(key) ?? null);
},
precedents(sheet, r, c) {
return (precs.get(keyOf(sheet, cellId(r, c))) ?? []).map((d) => ({
@@ -308,7 +351,7 @@ export function createCalcEngine(book: Workbook): CalcEngine {
const out: CalcValues = {};
for (const key of precs.keys()) {
const { 시트, r, c } = splitKey(key);
(out[시트] ??= {})[toA1(r, c)] = toCalcValue(compute(key));
(out[시트] ??= {})[toA1(r, c)] = toCalcValue(ensure(key));
}
return out;
},
+6 -1
View File
@@ -78,7 +78,7 @@ export interface Cell {
값?: CellInput;
/** A1 식 — 앞 `=` 뺌(`ROUNDDOWN((G31+J31/2)*P31,2)`). 행열을 넣고 지우면 글을 고쳐 적음. */
식?: string;
/** `서식` 표 번호 — 없으면 행 · 열 서식 · 그다음 0(기본). */
/** `서식` 표 번호 — 없으면 행 · 열 서식 · 시트 `기본.서식` · 그다음 0(기본). */
서식?: number;
}
@@ -142,6 +142,11 @@ export interface Sheet {
/** 위에서 고정할 행 수 · 왼쪽에서 고정할 열 수. */
틀고정?: { 행?: number; 열?: number };
보기?: { 눈금선?: boolean };
/** 시트 통째(모두 고르기) — 서식 번호 · 열 폭(글자 단위) · 행 높이(pt). 칸 · 행 · 열 값이 없을 때 씀 ·
* 없으면 통합문서 `기본`. */
기본?: { 서식?: number; 열폭?: number; 행높이?: number };
/** 칸 메모 — A1 열쇠 → 메모 글. 행열 넣기 · 지우기 · 잘라 붙이기 때 칸과 같이 옮김(지운 칸 메모는 지움). */
comments?: Record<string, string>;
}
/** 새 시트 기본값 — 값은 사용자 협의로 확정(9_엑셀검토 8장 · 임의 확정 금지). 없으면 A 의 임시값. */