@open-document/core 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-CNr8hd5X.js";
1
+ import { t as createViteConfig } from "./config-B7vFf9qZ.js";
2
2
  import path from "node:path";
3
3
  import { build as build$1, mergeConfig } from "vite";
4
4
  //#region src/cli/build.ts
@@ -1,6 +1,6 @@
1
- import { g as listDocIds } from "./config-CNr8hd5X.js";
2
- import { m as closeRenderSession, p as checkLayout } from "./ops-BCBmRMCS.js";
3
- import { t as cliContext } from "./context-CJpdjYfU.js";
1
+ import { g as listDocIds } from "./config-B7vFf9qZ.js";
2
+ import { m as closeRenderSession, p as checkLayout } from "./ops-ByclxTfk.js";
3
+ import { t as cliContext } from "./context-BaUE_aqU.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/check.ts
6
6
  function line(finding) {
package/dist/cli/bin.js CHANGED
@@ -165,15 +165,15 @@ async function run(argv) {
165
165
  program.name("open-doc").description("Author documents — we handle the Vite/React stack, pagination, and export.").version(version, "-v, --version", "print version").helpOption("-h, --help", "show help").showHelpAfterError(chalk.dim("(run `open-doc --help` for usage)"));
166
166
  program.command("dev").description("Start the dev server").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").option("--no-skills-check", "skip the built-in skills drift check").option("--mcp", "serve an MCP endpoint at /mcp (requires @open-document/mcp)").action(async (flags) => {
167
167
  if (flags.skillsCheck !== false) await runSkillsDriftCheck(resolveBuiltinSkillsDir());
168
- const { dev } = await import("../dev-BhXgunme.js");
168
+ const { dev } = await import("../dev-DXG-Dg-y.js");
169
169
  await dev(flags);
170
170
  });
171
171
  program.command("build").description("Build a static site").option("--out-dir <dir>", "output directory (defaults to `dist`)").action(async (flags) => {
172
- const { build } = await import("../build-BzhYQKev.js");
172
+ const { build } = await import("../build-BvIHtePO.js");
173
173
  await build(flags);
174
174
  });
175
175
  program.command("preview").description("Preview the production build").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").action(async (flags) => {
176
- const { preview } = await import("../preview-Da4Aq9yF.js");
176
+ const { preview } = await import("../preview-CdmWbaHy.js");
177
177
  await preview(flags);
178
178
  });
179
179
  program.command("export [docIds...]").description("Render documents headlessly to PDF, HTML, or PNG").addOption(new Option("-f, --format <format>", "output format").choices([
@@ -181,15 +181,15 @@ async function run(argv) {
181
181
  "html",
182
182
  "png"
183
183
  ])).option("-o, --out-dir <dir>", "directory to write into (defaults to `out`)").option("--all", "export every document under docs/").action(async (docIds, flags) => {
184
- const { exportDocs } = await import("../export-B69kDkyp.js");
184
+ const { exportDocs } = await import("../export-CT1Axnjv.js");
185
185
  await exportDocs(docIds, flags);
186
186
  });
187
187
  program.command("check [docIds...]").description("Report layout faults — clipped content, blank sheets, stranded headings").option("--json", "print the full report as JSON").action(async (docIds, flags) => {
188
- const { checkDocs } = await import("../check-CCAaXofH.js");
188
+ const { checkDocs } = await import("../check-BqEdVH7G.js");
189
189
  await checkDocs(docIds, flags);
190
190
  });
191
191
  program.command("import <file>").description("Turn a Markdown file into a document under docs/").option("--id <id>", "document id (defaults to a slug of the title)").option("--title <title>", "override the title").option("--subtitle <subtitle>", "subtitle, also used as the cover eyebrow").option("--author <author>", "author line on the cover").option("--theme <theme>", "theme id to back-link from meta.theme").addOption(new Option("--page-size <size>", "page size").choices(PAGE_SIZE_NAMES)).addOption(new Option("--orientation <orientation>", "page orientation").choices(ORIENTATIONS)).option("--no-cover", "skip the title page").option("--contents", "add a self-filling contents page").action(async (file, flags) => {
192
- const { importDoc } = await import("../import-DBhCpUsl.js");
192
+ const { importDoc } = await import("../import-C8ZC4R6T.js");
193
193
  await importDoc(file, flags);
194
194
  });
195
195
  program.command("sync:skills").description("Sync built-in skills from @open-document/core into this workspace").option("--dry-run", "show what would change without writing").action(async (flags) => {
@@ -1223,13 +1223,15 @@ function insertMarker(source, target, note, hint) {
1223
1223
  }
1224
1224
  //#endregion
1225
1225
  //#region src/editing/edit-ops.ts
1226
- /** JSX text is written literally; only these characters have to be escaped. */
1227
1226
  function escapeJsxText(text) {
1228
1227
  return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
1229
1228
  }
1230
1229
  function normalizeText(value) {
1231
1230
  return value.replace(/\s+/g, " ").trim();
1232
1231
  }
1232
+ function isAstNode(value) {
1233
+ return typeof value === "object" && value !== null && typeof value.type === "string";
1234
+ }
1233
1235
  function jsxChildren(element) {
1234
1236
  return element.children ?? [];
1235
1237
  }
@@ -1238,33 +1240,308 @@ function labelOf(node) {
1238
1240
  if (node.type === "JSXElement") return `<${(node.openingElement?.name)?.name ?? "element"}>`;
1239
1241
  return "…";
1240
1242
  }
1241
- /** Text children with content, in document order. */
1242
- function textNodes(element) {
1243
- return jsxChildren(element).filter((child) => child.type === "JSXText" && child.value.trim() !== "");
1243
+ /** Text written straight into the JSX. Its surrounding whitespace is indentation, so the slot excludes it. */
1244
+ function literalSlot(node) {
1245
+ const raw = node.value;
1246
+ const leading = (raw.match(/^\s*/)?.[0] ?? "").length;
1247
+ const trailing = (raw.match(/\s*$/)?.[0] ?? "").length;
1248
+ return {
1249
+ value: raw.trim(),
1250
+ start: node.start + leading,
1251
+ end: node.end - trailing,
1252
+ escape: escapeJsxText
1253
+ };
1254
+ }
1255
+ /** `name="…"` at a call site. Only the quote in use has to be escaped. */
1256
+ function attributeSlot(node, source) {
1257
+ const quote = source[node.start] ?? "\"";
1258
+ const entity = quote === "\"" ? "&quot;" : "&apos;";
1259
+ return {
1260
+ value: node.value,
1261
+ start: node.start + 1,
1262
+ end: node.end - 1,
1263
+ escape: (text) => text.split(quote).join(entity)
1264
+ };
1265
+ }
1266
+ /** A plain string in an array or object literal — a JS string, not JSX. */
1267
+ function stringSlot(node, source) {
1268
+ const quote = source[node.start] ?? "'";
1269
+ return {
1270
+ value: node.value,
1271
+ start: node.start + 1,
1272
+ end: node.end - 1,
1273
+ escape: (text) => text.split("\\").join("\\\\").split(quote).join(`\\${quote}`)
1274
+ };
1275
+ }
1276
+ /**
1277
+ * A code block is written `<Code>{`docs/…`}</Code>` — the words are a template
1278
+ * literal, not JSX text. Nothing has to be traced to reach them, so they are a
1279
+ * slot wherever they appear: as a child of the element, or as the children one
1280
+ * call site handed a helper.
1281
+ */
1282
+ function expressionSlot(child, source) {
1283
+ if (child.type !== "JSXExpressionContainer") return null;
1284
+ const expression = child.expression;
1285
+ if (expression?.type === "StringLiteral") return stringSlot(expression, source);
1286
+ if (expression?.type !== "TemplateLiteral") return null;
1287
+ if ((expression.expressions ?? []).length > 0) return null;
1288
+ const quasis = expression.quasis ?? [];
1289
+ const raw = (quasis[0]?.value)?.raw ?? "";
1290
+ if (quasis.length !== 1) return null;
1291
+ return {
1292
+ value: raw,
1293
+ start: expression.start + 1,
1294
+ end: expression.end - 1,
1295
+ escape: (text) => text.split("\\").join("\\\\").split("`").join("\\`").split("${").join("\\${")
1296
+ };
1297
+ }
1298
+ function identifierName(child) {
1299
+ if (child.type !== "JSXExpressionContainer") return null;
1300
+ const expression = child.expression;
1301
+ if (expression?.type !== "Identifier") return null;
1302
+ return expression.name ?? null;
1244
1303
  }
1245
- function partsOf(element) {
1304
+ /** The chain of nodes from the program down to this element — its scopes, in order. */
1305
+ function pathTo(ast, element) {
1306
+ let found = null;
1307
+ const visit = (node, trail) => {
1308
+ if (found) return;
1309
+ const here = [...trail, node];
1310
+ if (node === element) {
1311
+ found = here;
1312
+ return;
1313
+ }
1314
+ for (const key of Object.keys(node)) {
1315
+ if (key === "loc") continue;
1316
+ const value = node[key];
1317
+ if (Array.isArray(value)) {
1318
+ for (const child of value) if (isAstNode(child)) visit(child, here);
1319
+ } else if (isAstNode(value)) visit(value, here);
1320
+ }
1321
+ };
1322
+ visit(ast, []);
1323
+ return found;
1324
+ }
1325
+ function propNames(declarator) {
1326
+ const pattern = (declarator.init?.params)?.[0];
1327
+ if (pattern?.type !== "ObjectPattern") return [];
1328
+ return (pattern.properties ?? []).map((property) => property.key?.name ?? "").filter((name) => name !== "");
1329
+ }
1330
+ /** The component this element belongs to, and the props it declares. */
1331
+ function componentScope(path) {
1332
+ for (let index = path.length - 1; index >= 0; index--) {
1333
+ const node = path[index];
1334
+ if (node?.type !== "VariableDeclarator") continue;
1335
+ const name = node.id?.name;
1336
+ const props = propNames(node);
1337
+ if (name !== void 0 && props.length > 0) return {
1338
+ name,
1339
+ props
1340
+ };
1341
+ }
1342
+ return null;
1343
+ }
1344
+ /** The `xs.map(entry => …)` this element is rendered inside, if any. */
1345
+ function mapScope(path) {
1346
+ for (let index = path.length - 1; index >= 1; index--) {
1347
+ const arrow = path[index];
1348
+ const call = path[index - 1];
1349
+ if (arrow?.type !== "ArrowFunctionExpression" || call?.type !== "CallExpression") continue;
1350
+ const callee = call.callee;
1351
+ if (callee?.type !== "MemberExpression") continue;
1352
+ if (callee.property?.name !== "map") continue;
1353
+ const object = callee.object;
1354
+ const pattern = (arrow.params ?? [])[0];
1355
+ if (object?.type !== "Identifier" || !pattern) continue;
1356
+ return {
1357
+ pattern,
1358
+ array: object.name
1359
+ };
1360
+ }
1361
+ return null;
1362
+ }
1363
+ function patternNames(pattern) {
1364
+ if (pattern.type === "Identifier") return [pattern.name];
1365
+ if (pattern.type === "ArrayPattern") return (pattern.elements ?? []).filter((element) => element?.type === "Identifier").map((element) => element.name);
1366
+ if (pattern.type === "ObjectPattern") return (pattern.properties ?? []).map((property) => property.value?.name ?? "").filter((name) => name !== "");
1367
+ return [];
1368
+ }
1369
+ /** Destructure one array entry the way the map callback does. */
1370
+ function entryBindings(pattern, entry, source) {
1371
+ if (pattern.type === "Identifier") {
1372
+ if (entry.type !== "StringLiteral") return null;
1373
+ return /* @__PURE__ */ new Map([[pattern.name, stringSlot(entry, source)]]);
1374
+ }
1375
+ const bindings = /* @__PURE__ */ new Map();
1376
+ if (pattern.type === "ArrayPattern") {
1377
+ if (entry.type !== "ArrayExpression") return null;
1378
+ const values = entry.elements ?? [];
1379
+ const targets = pattern.elements ?? [];
1380
+ for (let index = 0; index < targets.length; index++) {
1381
+ const target = targets[index];
1382
+ if (!target) continue;
1383
+ const value = values[index];
1384
+ if (target.type !== "Identifier" || value?.type !== "StringLiteral") return null;
1385
+ bindings.set(target.name, stringSlot(value, source));
1386
+ }
1387
+ return bindings.size > 0 ? bindings : null;
1388
+ }
1389
+ if (pattern.type === "ObjectPattern") {
1390
+ if (entry.type !== "ObjectExpression") return null;
1391
+ for (const property of pattern.properties ?? []) {
1392
+ const key = property.key?.name ?? "";
1393
+ const local = property.value?.name ?? "";
1394
+ if (key === "" || local === "") return null;
1395
+ const value = (entry.properties ?? []).find((candidate) => candidate.key?.name === key || candidate.key?.value === key)?.value;
1396
+ if (value?.type !== "StringLiteral") return null;
1397
+ bindings.set(local, stringSlot(value, source));
1398
+ }
1399
+ return bindings.size > 0 ? bindings : null;
1400
+ }
1401
+ return null;
1402
+ }
1403
+ /**
1404
+ * Two call sites of the same component render different words, and only what
1405
+ * is on screen can say which one was clicked — without it a save rewrites
1406
+ * whichever came first in the file. An entry that cannot be told apart from
1407
+ * its neighbours is therefore not editable at all.
1408
+ */
1409
+ function fits(bindings, shown) {
1410
+ if (shown === void 0) return true;
1411
+ const visible = normalizeText(shown);
1412
+ const values = [...bindings.values()].map((slot) => normalizeText(slot.value));
1413
+ if (values.join("") === "") return false;
1414
+ return values.every((value) => visible.includes(value));
1415
+ }
1416
+ function tagName(node) {
1417
+ return (node.openingElement?.name)?.name;
1418
+ }
1419
+ /**
1420
+ * `<Section name="主旨">…</Section>` puts its words between the tags rather
1421
+ * than in an attribute. Only a lone run of text qualifies: anything nested
1422
+ * would be flattened into a string and lost on the first save.
1423
+ */
1424
+ function childrenSlot(node, source) {
1425
+ const children = jsxChildren(node).filter((child) => child.type !== "JSXText" || child.value.trim() !== "");
1426
+ const only = children[0];
1427
+ if (children.length !== 1 || !only) return null;
1428
+ if (only.type === "JSXText") return literalSlot(only);
1429
+ return expressionSlot(only, source);
1430
+ }
1431
+ function callSiteBindings(node, wanted, source) {
1432
+ const attributes = node.openingElement?.attributes ?? [];
1433
+ const bindings = /* @__PURE__ */ new Map();
1434
+ for (const name of wanted) {
1435
+ if (name === "children") {
1436
+ const slot = childrenSlot(node, source);
1437
+ if (!slot) return null;
1438
+ bindings.set(name, slot);
1439
+ continue;
1440
+ }
1441
+ const value = attributes.find((candidate) => candidate.name?.name === name)?.value;
1442
+ if (value?.type !== "StringLiteral") return null;
1443
+ bindings.set(name, attributeSlot(value, source));
1444
+ }
1445
+ return bindings;
1446
+ }
1447
+ function propBindings(ctx, component, wanted) {
1448
+ const matches = [];
1449
+ walkJsx(ctx.ast, (node) => {
1450
+ if (tagName(node) !== component) return;
1451
+ const bindings = callSiteBindings(node, wanted, ctx.source);
1452
+ if (bindings && fits(bindings, ctx.shown)) matches.push(bindings);
1453
+ });
1454
+ return matches.length === 1 ? matches[0] ?? null : null;
1455
+ }
1456
+ /** Every array literal that could be the one being mapped over. */
1457
+ function arrayCandidates(ctx, name, component) {
1458
+ const found = [];
1459
+ walkAst(ctx.ast, (node) => {
1460
+ if (node.type === "VariableDeclarator") {
1461
+ const id = node.id;
1462
+ const init = node.init;
1463
+ if (id?.type === "Identifier" && id.name === name && init?.type === "ArrayExpression") found.push(init);
1464
+ return;
1465
+ }
1466
+ if (node.type !== "JSXElement" || component === null || tagName(node) !== component) return;
1467
+ const attributes = node.openingElement.attributes ?? [];
1468
+ for (const attribute of attributes) {
1469
+ if (attribute.name?.name !== name) continue;
1470
+ const value = attribute.value;
1471
+ if (value?.type !== "JSXExpressionContainer") continue;
1472
+ const expression = value.expression;
1473
+ if (expression?.type === "ArrayExpression") found.push(expression);
1474
+ }
1475
+ });
1476
+ return found;
1477
+ }
1478
+ function mapBindings(ctx, scope, component, wanted) {
1479
+ const matches = [];
1480
+ for (const array of arrayCandidates(ctx, scope.array, component)) for (const entry of array.elements ?? []) {
1481
+ if (!entry) continue;
1482
+ const bindings = entryBindings(scope.pattern, entry, ctx.source);
1483
+ if (!bindings || !wanted.every((name) => bindings.has(name))) continue;
1484
+ if (fits(bindings, ctx.shown)) matches.push(bindings);
1485
+ }
1486
+ return matches.length === 1 ? matches[0] ?? null : null;
1487
+ }
1488
+ function bindingsFor(ctx, element, names) {
1489
+ const path = pathTo(ctx.ast, element);
1490
+ if (!path) return null;
1491
+ const map = mapScope(path);
1492
+ const component = componentScope(path);
1493
+ const mapped = map ? patternNames(map.pattern) : [];
1494
+ const bindings = /* @__PURE__ */ new Map();
1495
+ const fromMap = names.filter((name) => mapped.includes(name));
1496
+ if (map && fromMap.length > 0) {
1497
+ const entry = mapBindings(ctx, map, component?.name ?? null, fromMap);
1498
+ if (entry) for (const name of fromMap) {
1499
+ const slot = entry.get(name);
1500
+ if (slot) bindings.set(name, slot);
1501
+ }
1502
+ }
1503
+ const fromProps = names.filter((name) => !mapped.includes(name) && (component?.props.includes(name) ?? false));
1504
+ if (component && fromProps.length > 0) {
1505
+ const call = propBindings(ctx, component.name, fromProps);
1506
+ if (call) for (const [name, slot] of call) bindings.set(name, slot);
1507
+ }
1508
+ return bindings.size > 0 ? bindings : null;
1509
+ }
1510
+ /** The element's children, each resolved to a writable slot or left as markup. */
1511
+ function resolve(element, ctx) {
1512
+ const children = jsxChildren(element);
1513
+ const names = children.map((child) => identifierName(child)).filter((name) => name !== null);
1514
+ const bindings = ctx && names.length > 0 ? bindingsFor(ctx, element, names) : null;
1246
1515
  const parts = [];
1247
- let index = 0;
1248
- for (const child of jsxChildren(element)) {
1516
+ const slots = [];
1517
+ const take = (slot) => {
1518
+ parts.push({
1519
+ kind: "text",
1520
+ index: slots.length,
1521
+ value: slot.value
1522
+ });
1523
+ slots.push(slot);
1524
+ };
1525
+ for (const child of children) {
1249
1526
  if (child.type === "JSXText") {
1250
- const value = child.value;
1251
- if (value.trim() === "") continue;
1252
- parts.push({
1253
- kind: "text",
1254
- index: index++,
1255
- value: value.trim()
1256
- });
1527
+ if (child.value.trim() !== "") take(literalSlot(child));
1257
1528
  continue;
1258
1529
  }
1259
- parts.push({
1530
+ const name = identifierName(child);
1531
+ const slot = (name === null ? void 0 : bindings?.get(name)) ?? (ctx ? expressionSlot(child, ctx.source) ?? void 0 : void 0);
1532
+ if (slot) take(slot);
1533
+ else parts.push({
1260
1534
  kind: "markup",
1261
1535
  label: labelOf(child)
1262
1536
  });
1263
1537
  }
1264
- return parts;
1538
+ return {
1539
+ parts,
1540
+ slots
1541
+ };
1265
1542
  }
1266
- function describe(element) {
1267
- const parts = partsOf(element);
1543
+ function describe(element, ctx) {
1544
+ const { parts } = resolve(element, ctx);
1268
1545
  const texts = parts.filter((part) => part.kind === "text");
1269
1546
  if (texts.length === 0) return {
1270
1547
  editable: false,
@@ -1289,6 +1566,11 @@ function describe(element) {
1289
1566
  function resolveTextTarget(source, candidates, expected) {
1290
1567
  const ast = parseSource$1(source);
1291
1568
  if (!ast) return null;
1569
+ const ctx = {
1570
+ ast,
1571
+ source,
1572
+ shown: expected
1573
+ };
1292
1574
  const shown = expected ? normalizeText(expected) : null;
1293
1575
  const matches = (info) => {
1294
1576
  if (!shown) return true;
@@ -1299,7 +1581,7 @@ function resolveTextTarget(source, candidates, expected) {
1299
1581
  for (const candidate of candidates) {
1300
1582
  const exact = findJsxAt(ast, candidate.line, candidate.column);
1301
1583
  if (exact) {
1302
- const info = describe(exact);
1584
+ const info = describe(exact, ctx);
1303
1585
  if (info.editable && matches(info)) return {
1304
1586
  ...info,
1305
1587
  ...candidate
@@ -1307,7 +1589,7 @@ function resolveTextTarget(source, candidates, expected) {
1307
1589
  }
1308
1590
  if (!shown) continue;
1309
1591
  for (const node of findJsxOnLine(ast, candidate.line, candidate.column)) {
1310
- const info = describe(node);
1592
+ const info = describe(node, ctx);
1311
1593
  const start = node.loc?.start;
1312
1594
  if (!info.editable || !matches(info) || !start) continue;
1313
1595
  return {
@@ -1321,7 +1603,7 @@ function resolveTextTarget(source, candidates, expected) {
1321
1603
  if (!first) return null;
1322
1604
  const clicked = findJsxAt(ast, first.line, first.column);
1323
1605
  return clicked ? {
1324
- ...describe(clicked),
1606
+ ...describe(clicked, ctx),
1325
1607
  ...first
1326
1608
  } : null;
1327
1609
  }
@@ -1343,29 +1625,30 @@ function replaceTextAt(source, target, text, opts = {}) {
1343
1625
  status: 404,
1344
1626
  error: "no element at that source location"
1345
1627
  };
1346
- const nodes = textNodes(element);
1347
- if (nodes.length === 0) return {
1628
+ const { slots } = resolve(element, {
1629
+ ast,
1630
+ source,
1631
+ shown: opts.shown
1632
+ });
1633
+ if (slots.length === 0) return {
1348
1634
  ok: false,
1349
1635
  status: 422,
1350
1636
  error: "element has no text to replace"
1351
1637
  };
1352
- const child = nodes[opts.index ?? 0];
1353
- if (!child) return {
1638
+ const slot = slots[opts.index ?? 0];
1639
+ if (!slot) return {
1354
1640
  ok: false,
1355
1641
  status: 404,
1356
1642
  error: "no such text run in this element"
1357
1643
  };
1358
- const raw = child.value;
1359
- if (opts.expected !== void 0 && normalizeText(raw) !== normalizeText(opts.expected)) return {
1644
+ if (opts.expected !== void 0 && normalizeText(slot.value) !== normalizeText(opts.expected)) return {
1360
1645
  ok: false,
1361
1646
  status: 409,
1362
1647
  error: "source changed since this was opened — reselect it"
1363
1648
  };
1364
- const leading = raw.match(/^\s*/)?.[0] ?? "";
1365
- const trailing = raw.match(/\s*$/)?.[0] ?? "";
1366
1649
  return {
1367
1650
  ok: true,
1368
- source: source.slice(0, child.start) + leading + escapeJsxText(text) + trailing + source.slice(child.end)
1651
+ source: source.slice(0, slot.start) + slot.escape(text) + source.slice(slot.end)
1369
1652
  };
1370
1653
  }
1371
1654
  //#endregion
@@ -1410,7 +1693,8 @@ function registerEditRoutes(server, ctx) {
1410
1693
  const source = await fs.readFile(entry, "utf8");
1411
1694
  const result = replaceTextAt(source, loc, text, {
1412
1695
  index: typeof body.index === "number" ? body.index : void 0,
1413
- expected: typeof body.expected === "string" ? body.expected : void 0
1696
+ expected: typeof body.expected === "string" ? body.expected : void 0,
1697
+ shown: typeof body.shown === "string" ? body.shown : void 0
1414
1698
  });
1415
1699
  if (!result.ok) return json(res, result.status, { error: result.error });
1416
1700
  if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
@@ -1,5 +1,5 @@
1
1
  import { t as readCoreVersion } from "./cli/bin.js";
2
- import { D as makeContext, k as loadUserConfig } from "./config-CNr8hd5X.js";
2
+ import { D as makeContext, k as loadUserConfig } from "./config-B7vFf9qZ.js";
3
3
  //#region src/cli/context.ts
4
4
  /** The same context the dev API and the MCP server run on, for commands that call `ops/`. */
5
5
  async function cliContext(userCwd = process.cwd()) {
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-CNr8hd5X.js";
1
+ import { t as createViteConfig } from "./config-B7vFf9qZ.js";
2
2
  import { createServer, mergeConfig } from "vite";
3
3
  //#region src/cli/dev.ts
4
4
  async function dev(opts = {}) {
@@ -1,6 +1,6 @@
1
- import { g as listDocIds } from "./config-CNr8hd5X.js";
2
- import { h as exportDocument, m as closeRenderSession } from "./ops-BCBmRMCS.js";
3
- import { t as cliContext } from "./context-CJpdjYfU.js";
1
+ import { g as listDocIds } from "./config-B7vFf9qZ.js";
2
+ import { h as exportDocument, m as closeRenderSession } from "./ops-ByclxTfk.js";
3
+ import { t as cliContext } from "./context-BaUE_aqU.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/export.ts
6
6
  const FORMATS = [
@@ -1,5 +1,5 @@
1
- import { _ as importMarkdown } from "./ops-BCBmRMCS.js";
2
- import { t as cliContext } from "./context-CJpdjYfU.js";
1
+ import { _ as importMarkdown } from "./ops-ByclxTfk.js";
2
+ import { t as cliContext } from "./context-BaUE_aqU.js";
3
3
  import chalk from "chalk";
4
4
  import path from "node:path";
5
5
  //#region src/cli/import.ts
package/dist/index.js CHANGED
@@ -548,6 +548,7 @@ function TableOfContents({ maxLevel = 2, showPageNumbers = true, includeOwnPage
548
548
  ...style
549
549
  },
550
550
  children: entries.map((entry) => /* @__PURE__ */ jsxs("div", {
551
+ "data-od-toc-entry": entry.id,
551
552
  style: {
552
553
  display: "flex",
553
554
  alignItems: "baseline",
package/dist/ops/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { a as PAGE_SIZE_NAMES, r as ORIENTATIONS } from "../sdk-DhcqZdAw.js";
2
- import { D as makeContext, _ as listDocuments, b as resolveEntry, d as OpsError, f as createDocument, g as listDocIds, h as duplicateDocument, m as docDir, p as deleteDocument, v as readDocument, x as writeDocument, y as renameDocument } from "../config-CNr8hd5X.js";
3
- import { _ as importMarkdown, a as deleteAsset, c as listAssets, d as readTheme, f as writeAsset, g as renderDocPage, h as exportDocument, i as createFolder, l as listFolders, m as closeRenderSession, n as readText, o as fileDocument, p as checkLayout, r as writeText, s as findAssetUsages, t as addComment, u as listThemes, v as slugify } from "../ops-BCBmRMCS.js";
2
+ import { D as makeContext, _ as listDocuments, b as resolveEntry, d as OpsError, f as createDocument, g as listDocIds, h as duplicateDocument, m as docDir, p as deleteDocument, v as readDocument, x as writeDocument, y as renameDocument } from "../config-B7vFf9qZ.js";
3
+ import { _ as importMarkdown, a as deleteAsset, c as listAssets, d as readTheme, f as writeAsset, g as renderDocPage, h as exportDocument, i as createFolder, l as listFolders, m as closeRenderSession, n as readText, o as fileDocument, p as checkLayout, r as writeText, s as findAssetUsages, t as addComment, u as listThemes, v as slugify } from "../ops-ByclxTfk.js";
4
4
  export { ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, checkLayout, closeRenderSession, createDocument, createFolder, deleteAsset, deleteDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listThemes, makeContext, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, slugify, writeAsset, writeDocument, writeText };
@@ -1,5 +1,5 @@
1
1
  import { a as PAGE_SIZE_NAMES, o as isOrientation, r as ORIENTATIONS, s as isPageSizeName } from "./sdk-DhcqZdAw.js";
2
- import { C as readManifest, E as writeManifest, O as DOC_ID_RE, S as newFolderId, T as validateName, a as insertMarker, b as resolveEntry, c as resolveScopedAssetFile, d as OpsError, f as createDocument, g as listDocIds, i as resolveTextTarget, l as resolveScopedAssetsDir, n as parseFrontmatter$1, o as assetImportPath, r as replaceTextAt, s as countAssetUsages, t as createViteConfig, u as validateAssetName, w as validateIcon } from "./config-CNr8hd5X.js";
2
+ import { C as readManifest, E as writeManifest, O as DOC_ID_RE, S as newFolderId, T as validateName, a as insertMarker, b as resolveEntry, c as resolveScopedAssetFile, d as OpsError, f as createDocument, g as listDocIds, i as resolveTextTarget, l as resolveScopedAssetsDir, n as parseFrontmatter$1, o as assetImportPath, r as replaceTextAt, s as countAssetUsages, t as createViteConfig, u as validateAssetName, w as validateIcon } from "./config-B7vFf9qZ.js";
3
3
  import path from "node:path";
4
4
  import fs from "node:fs/promises";
5
5
  import { existsSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-CNr8hd5X.js";
1
+ import { t as createViteConfig } from "./config-B7vFf9qZ.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {
@@ -1,2 +1,2 @@
1
- import { A as openDocPlugin, t as createViteConfig } from "../config-CNr8hd5X.js";
1
+ import { A as openDocPlugin, t as createViteConfig } from "../config-B7vFf9qZ.js";
2
2
  export { createViteConfig, openDocPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,7 @@
1
1
  import { Check, Loader2, MessageSquarePlus, X } from 'lucide-react';
2
2
  import {
3
3
  type CSSProperties,
4
+ Fragment,
4
5
  useCallback,
5
6
  useEffect,
6
7
  useLayoutEffect,
@@ -42,7 +43,13 @@ function normalize(value: string): string {
42
43
  }
43
44
 
44
45
  function targetFrom(el: Element | null): InspectorTarget | null {
45
- const host = (el as HTMLElement | null)?.closest?.(`[${LOC_ATTR}]`) as HTMLElement | null;
46
+ // A contents row is generated from a heading and written nowhere; the words
47
+ // to edit are the heading's. Clicking the row selects that instead, so the
48
+ // list stays what it is — a view — and still answers to a click.
49
+ const row = (el as HTMLElement | null)?.closest?.('[data-od-toc-entry]') as HTMLElement | null;
50
+ const heading = row?.dataset.odTocEntry ? document.getElementById(row.dataset.odTocEntry) : null;
51
+ const from = heading ?? el;
52
+ const host = (from as HTMLElement | null)?.closest?.(`[${LOC_ATTR}]`) as HTMLElement | null;
46
53
  const raw = host?.getAttribute(LOC_ATTR);
47
54
  if (!host || !raw) return null;
48
55
  const [line, column] = raw.split(':').map(Number);
@@ -136,6 +143,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
136
143
  const [busy, setBusy] = useState(false);
137
144
  const [status, setStatus] = useState<string | null>(null);
138
145
  const panelRef = useRef<HTMLElement>(null);
146
+ const editorRef = useRef<HTMLDivElement>(null);
139
147
 
140
148
  useLayoutEffect(() => setContainer(containerRef.current), [containerRef]);
141
149
 
@@ -157,6 +165,12 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
157
165
  if (!target) return;
158
166
  e.preventDefault();
159
167
  e.stopPropagation();
168
+ // A contents row sends the selection to a heading pages away. Without
169
+ // this the panel fills in and the document sits where it was, which
170
+ // reads as nothing having happened.
171
+ if (!target.anchor.contains(e.target as Node)) {
172
+ target.anchor.scrollIntoView({ block: 'center', behavior: 'smooth' });
173
+ }
160
174
  setSelected(target);
161
175
  setStatus(null);
162
176
  setNote('');
@@ -250,7 +264,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
250
264
  );
251
265
 
252
266
  const saveText = async () => {
253
- if (!target || dirty.length === 0 || busy) return;
267
+ if (!target || !selected || dirty.length === 0 || busy) return;
254
268
  setBusy(true);
255
269
  try {
256
270
  for (const part of dirty) {
@@ -263,6 +277,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
263
277
  column: target.column,
264
278
  index: part.index,
265
279
  expected: part.value,
280
+ shown: normalize(selected.anchor.textContent ?? ''),
266
281
  text: drafts[part.index],
267
282
  }),
268
283
  });
@@ -360,18 +375,70 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
360
375
  </div>
361
376
  ) : target.editable ? (
362
377
  <>
363
- <div className="mt-1 space-y-1.5">
364
- {target.parts.map((part, index) =>
365
- part.kind === 'markup' ? (
366
- <div
378
+ {/*
379
+ * One field, not one per run. A sentence interrupted by five
380
+ * <code> spans is still one sentence, and bordering each
381
+ * fragment turned a paragraph into eleven stacked boxes.
382
+ *
383
+ * The runs are laid out as the sentence reads, with the markup
384
+ * between them as inert chips. Nothing re-renders while typing:
385
+ * the children never change, so React leaves the DOM — and the
386
+ * caret — alone, and the text is read back out of it.
387
+ */}
388
+ {target.parts.length > 1 ? (
389
+ // biome-ignore lint/a11y/useSemanticElements: a textarea cannot hold the inert markup chips
390
+ <div
391
+ key={`${target.line}:${target.column}`}
392
+ ref={editorRef}
393
+ contentEditable
394
+ suppressContentEditableWarning
395
+ role="textbox"
396
+ tabIndex={0}
397
+ aria-label="Text"
398
+ onInput={() => {
399
+ const host = editorRef.current;
400
+ if (!host) return;
401
+ const next: Record<number, string> = {};
402
+ for (const run of host.querySelectorAll<HTMLElement>('[data-run]')) {
403
+ next[Number(run.dataset.run)] = run.textContent ?? '';
404
+ }
405
+ setDrafts(next);
406
+ }}
407
+ onKeyDown={(e) => {
408
+ // A newline would be a <br> the runs cannot carry.
409
+ if (e.key === 'Enter') {
410
+ e.preventDefault();
411
+ void saveText();
412
+ }
413
+ }}
414
+ className="mt-1 rounded border border-border px-2 py-1.5 text-xs leading-relaxed outline-none focus-within:border-foreground/40"
415
+ >
416
+ {target.parts.map((part, index) =>
417
+ part.kind === 'markup' ? (
418
+ // A chip carries no whitespace, so `real<code>/<code>`
419
+ // is one unbreakable word without these.
367
420
  // biome-ignore lint/suspicious/noArrayIndexKey: parts are positional
368
- key={`m${index}`}
369
- className="rounded border border-border border-dashed px-2 py-1 font-mono text-[10px] text-muted-foreground"
370
- title="Markup is kept as written"
371
- >
372
- {part.label}
373
- </div>
374
- ) : (
421
+ <Fragment key={`m${index}`}>
422
+ <wbr />
423
+ <span
424
+ contentEditable={false}
425
+ title="Markup is kept as written"
426
+ className="mx-0.5 select-none rounded bg-muted px-1 py-px font-mono text-[10px] text-muted-foreground"
427
+ >
428
+ {part.label}
429
+ </span>
430
+ <wbr />
431
+ </Fragment>
432
+ ) : (
433
+ <span key={`t${part.index}`} data-run={part.index}>
434
+ {part.value}
435
+ </span>
436
+ ),
437
+ )}
438
+ </div>
439
+ ) : (
440
+ target.parts.map((part) =>
441
+ part.kind === 'markup' ? null : (
375
442
  <textarea
376
443
  key={`t${part.index}`}
377
444
  value={drafts[part.index] ?? part.value}
@@ -382,14 +449,22 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
382
449
  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) void saveText();
383
450
  }}
384
451
  rows={Math.min(
385
- 6,
386
- Math.ceil((drafts[part.index] ?? part.value).length / 28) + 1,
452
+ 14,
453
+ Math.max(
454
+ 2,
455
+ (drafts[part.index] ?? part.value).split('\n').length,
456
+ Math.ceil((drafts[part.index] ?? part.value).length / 40),
457
+ ),
387
458
  )}
388
- className="w-full resize-y rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none focus:border-foreground/40"
459
+ className={`mt-1 w-full resize-y rounded border border-border bg-transparent px-2 py-1.5 outline-none focus:border-foreground/40 ${
460
+ selected?.tag === 'pre'
461
+ ? 'whitespace-pre font-mono text-[11px]'
462
+ : 'text-xs'
463
+ }`}
389
464
  />
390
465
  ),
391
- )}
392
- </div>
466
+ )
467
+ )}
393
468
  <button
394
469
  type="button"
395
470
  onClick={saveText}
@@ -50,6 +50,10 @@ export function TableOfContents({
50
50
  {entries.map((entry) => (
51
51
  <div
52
52
  key={entry.id}
53
+ /* Which heading this line stands for. The inspector follows it: a
54
+ * contents row holds no text of its own, so clicking one has to land
55
+ * on the heading that produced it. */
56
+ data-od-toc-entry={entry.id}
53
57
  style={{
54
58
  display: 'flex',
55
59
  alignItems: 'baseline',