@motionscript/code 0.1.0-alpha.8 → 0.1.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 +1 @@
1
- {"version":3,"file":"tokens.js","sourceRoot":"","sources":["../src/tokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAoB7F,+EAA+E;AAC/E,+EAA+E;AAC/E,qCAAqC;AACrC,IAAI,WAAW,GAAG,CAAC,CAAC;AACpB,IAAI,UAAU,GAAG,CAAC,CAAC;AAEnB,MAAM,UAAU,WAAW,CAAC,OAAe,EAAE,KAAc;IACvD,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AACjD,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,MAAiB;IACxC,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,IAAY,EAAE,QAAgB,EAAE,KAAgB;IAClF,6EAA6E;IAC7E,wEAAwE;IACxE,0DAA0D;IAC1D,IAAI,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAC7B,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC;QACjC,wEAAwE;QACxE,8BAA8B;QAC9B,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,WAAW,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACpF,CAAC;IACD,OAAO,iBAAiB,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CACvD,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CACnE,CAAC;AACN,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CACzB,MAAiB,EACjB,GAAW;IAEX,MAAM,MAAM,GAAc,EAAE,CAAC;IAC7B,MAAM,KAAK,GAAc,EAAE,CAAC;IAC5B,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACvB,MAAM,MAAM,GAAG,GAAG,CAAC;QACnB,MAAM,IAAI,GAAG,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC;QACtC,IAAI,IAAI,IAAI,GAAG,EAAE,CAAC;YACd,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC;aAAM,IAAI,MAAM,IAAI,GAAG,EAAE,CAAC;YACvB,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACpB,CAAC;aAAM,CAAC;YACJ,MAAM,GAAG,GAAG,GAAG,GAAG,MAAM,CAAC;YACzB,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;YAC/D,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;QAC/D,CAAC;QACD,GAAG,GAAG,IAAI,CAAC;IACf,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["import { canHighlight, highlightToTokens, normalizeSource, resolveTheme } from \"./highlight\";\r\nimport { CodeTheme } from \"./style\";\r\n\r\n// IdToken is our internal wrapper around a highlighter token that gives every\r\n// token a stable identity across line insertions/removals. All animation state\r\n// is keyed by `id`, so concurrent edits at different positions don't clobber\r\n// each other while one is mid-animation.\r\nexport interface IdToken {\r\n id: number;\r\n content: string;\r\n color?: string;\r\n}\r\n\r\n// IdLine wraps a row of tokens with its own stable id, so per-line animations\r\n// (heightScale during insert/remove) survive line insertions/removals.\r\nexport interface IdLine {\r\n id: number;\r\n tokens: IdToken[];\r\n}\r\n\r\n// Module-global, monotonic id counters shared across all Code nodes — ids only\r\n// need to be unique within a node, but a global counter is the simplest way to\r\n// guarantee that and never collides.\r\nlet nextTokenId = 1;\r\nlet nextLineId = 1;\r\n\r\nexport function makeIdToken(content: string, color?: string): IdToken {\r\n return { id: nextTokenId++, content, color };\r\n}\r\n\r\nexport function makeIdLine(tokens: IdToken[]): IdLine {\r\n return { id: nextLineId++, tokens };\r\n}\r\n\r\nexport function tokenizeCodeToIdLines(code: string, language: string, theme: CodeTheme): IdLine[] {\r\n // Until the language parser has loaded (it streams in via the asset loader),\r\n // fall back to flat, uncolored lines instead of throwing on an unloaded\r\n // grammar. The node re-tokenizes once the load completes.\r\n code = normalizeSource(code);\r\n if (!canHighlight(language, theme)) {\r\n // Resolved for its warning: an unknown theme is reported whether or not\r\n // the grammar has landed yet.\r\n resolveTheme(theme);\r\n return code.split('\\n').map(line => makeIdLine([makeIdToken(line, '#d1d5db')]));\r\n }\r\n return highlightToTokens(code, language, theme).map(line =>\r\n makeIdLine(line.map(tok => makeIdToken(tok.content, tok.color))),\r\n );\r\n}\r\n\r\n/**\r\n * Split `tokens` at character offset `col` (relative to the joined content of\r\n * the tokens). If `col` falls inside a token, that token is split into two new\r\n * tokens with fresh ids (the original id is discarded — it didn't exist as a\r\n * single unit on either side of the cut).\r\n */\r\nexport function splitTokensAt(\r\n tokens: IdToken[],\r\n col: number,\r\n): { before: IdToken[]; after: IdToken[] } {\r\n const before: IdToken[] = [];\r\n const after: IdToken[] = [];\r\n let off = 0;\r\n for (const tok of tokens) {\r\n const tStart = off;\r\n const tEnd = off + tok.content.length;\r\n if (tEnd <= col) {\r\n before.push(tok);\r\n } else if (tStart >= col) {\r\n after.push(tok);\r\n } else {\r\n const cut = col - tStart;\r\n before.push(makeIdToken(tok.content.slice(0, cut), tok.color));\r\n after.push(makeIdToken(tok.content.slice(cut), tok.color));\r\n }\r\n off = tEnd;\r\n }\r\n return { before, after };\r\n}\r\n"]}
1
+ {"version":3,"file":"tokens.js","sourceRoot":"","sources":["../src/tokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAoB7F,+EAA+E;AAC/E,+EAA+E;AAC/E,qCAAqC;AACrC,IAAI,WAAW,GAAG,CAAC,CAAC;AACpB,IAAI,UAAU,GAAG,CAAC,CAAC;AAEnB,MAAM,UAAU,WAAW,CAAC,OAAe,EAAE,KAAc;IACvD,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AACjD,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,MAAiB;IACxC,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,IAAY,EAAE,QAAgB,EAAE,KAAgB;IAClF,6EAA6E;IAC7E,wEAAwE;IACxE,0DAA0D;IAC1D,IAAI,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAC7B,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC;QACjC,wEAAwE;QACxE,8BAA8B;QAC9B,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,WAAW,CAAC,IAAI,EAAE,SAAS,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OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["import { canHighlight, highlightToTokens, normalizeSource, resolveTheme } from \"./highlight\";\nimport { CodeTheme } from \"./style\";\n\n// IdToken is our internal wrapper around a highlighter token that gives every\n// token a stable identity across line insertions/removals. All animation state\n// is keyed by `id`, so concurrent edits at different positions don't clobber\n// each other while one is mid-animation.\nexport interface IdToken {\n id: number;\n content: string;\n color?: string;\n}\n\n// IdLine wraps a row of tokens with its own stable id, so per-line animations\n// (heightScale during insert/remove) survive line insertions/removals.\nexport interface IdLine {\n id: number;\n tokens: IdToken[];\n}\n\n// Module-global, monotonic id counters shared across all Code nodes — ids only\n// need to be unique within a node, but a global counter is the simplest way to\n// guarantee that and never collides.\nlet nextTokenId = 1;\nlet nextLineId = 1;\n\nexport function makeIdToken(content: string, color?: string): IdToken {\n return { id: nextTokenId++, content, color };\n}\n\nexport function makeIdLine(tokens: IdToken[]): IdLine {\n return { id: nextLineId++, tokens };\n}\n\nexport function tokenizeCodeToIdLines(code: string, language: string, theme: CodeTheme): IdLine[] {\n // Until the language parser has loaded (it streams in via the asset loader),\n // fall back to flat, uncolored lines instead of throwing on an unloaded\n // grammar. The node re-tokenizes once the load completes.\n code = normalizeSource(code);\n if (!canHighlight(language, theme)) {\n // Resolved for its warning: an unknown theme is reported whether or not\n // the grammar has landed yet.\n resolveTheme(theme);\n return code.split('\\n').map(line => makeIdLine([makeIdToken(line, '#d1d5db')]));\n }\n return highlightToTokens(code, language, theme).map(line =>\n makeIdLine(line.map(tok => makeIdToken(tok.content, tok.color))),\n );\n}\n\n/**\n * Split `tokens` at character offset `col` (relative to the joined content of\n * the tokens). If `col` falls inside a token, that token is split into two new\n * tokens with fresh ids (the original id is discarded — it didn't exist as a\n * single unit on either side of the cut).\n */\nexport function splitTokensAt(\n tokens: IdToken[],\n col: number,\n): { before: IdToken[]; after: IdToken[] } {\n const before: IdToken[] = [];\n const after: IdToken[] = [];\n let off = 0;\n for (const tok of tokens) {\n const tStart = off;\n const tEnd = off + tok.content.length;\n if (tEnd <= col) {\n before.push(tok);\n } else if (tStart >= col) {\n after.push(tok);\n } else {\n const cut = col - tStart;\n before.push(makeIdToken(tok.content.slice(0, cut), tok.color));\n after.push(makeIdToken(tok.content.slice(cut), tok.color));\n }\n off = tEnd;\n }\n return { before, after };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"transitions.js","sourceRoot":"","sources":["../src/transitions.ts"],"names":[],"mappings":"AAkHA,iFAAiF;AACjF,MAAM,UAAU,WAAW,CAAC,IAAc,EAAE,MAAgB,EAAE,CAAS;IACnE,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;QAAE,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;IACnC,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAAE,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACjE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YACnB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YACnC,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;YACpD,OAAO,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;QAC3D,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC,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IAED,KAAK,MAAM,EAAE,IAAI,WAAW,EAAE,CAAC;QAC3B,IAAI,EAAE,CAAC,IAAI,KAAK,KAAK;YAAE,SAAS;QAChC,KAAK,MAAM,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,CAAC;YACzB,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,OAAO,EAAE,WAAW,CAAC,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACtF,CAAC;IACL,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["import type { NormalizedColor } from \"@motionscript/sdk\";\r\nimport type { CodeLayout } from \"./layout\";\r\nimport { IdLine } from \"./tokens\";\r\n\r\n// A single animated token entry owned by one dim transition. Keyed by stable\r\n// token id rather than (line, tokenIndex) so concurrent animations don't clobber\r\n// each other when one shifts the indices of tokens the other is animating.\r\nexport interface AnimToken {\r\n id: number;\r\n opacity: number[];\r\n opacityKeys: number[];\r\n}\r\n\r\n/**\r\n * A highlight cross-fade: opacity, and nothing else.\r\n *\r\n * Structure is untouched, so several of these stack happily and a listing held\r\n * under a highlight still hits the static-layout cache.\r\n */\r\nexport interface DimTransition {\r\n kind: \"dim\";\r\n tokens: AnimToken[];\r\n progress: number;\r\n}\r\n\r\n/**\r\n * When each part of a structural edit happens, in normalized transition time.\r\n *\r\n * The order is what an edit *looks like* being made: what is going away leaves\r\n * first, what stays reflows into its new place, and only then does what is new\r\n * appear. Running them together is what made a replacement look like a\r\n * cross-dissolve of two unrelated listings.\r\n */\r\nexport interface Phases {\r\n /** Removed tokens fade out. Null when the edit removes nothing. */\r\n out: [number, number] | null;\r\n /** Surviving tokens travel, and the block resizes. Always present. */\r\n move: [number, number];\r\n /** Added tokens fade (and slide) in. Null when the edit adds nothing. */\r\n in: [number, number] | null;\r\n}\r\n\r\n/**\r\n * One edit in flight: the structure before, the structure after, and who is\r\n * doing what.\r\n *\r\n * Both endpoints are fixed for the transition's whole life, which is why the\r\n * two resolved layouts hang off it — they are computed once and reused for\r\n * every frame the edit spans, rather than rebuilt per frame from a structure\r\n * that is being mutated underneath.\r\n */\r\nexport interface StructuralTransition {\r\n kind: \"structural\";\r\n from: IdLine[];\r\n to: IdLine[];\r\n removedIds: Set<number>;\r\n addedIds: Set<number>;\r\n /**\r\n * Ids of rows in `to` that did not exist before, and so enter as a whole\r\n * row rather than as tokens spliced into one.\r\n *\r\n * They enter by fading in place, and that is the *only* thing they do. An\r\n * earlier version slid each one in from the edge the block had just grown\r\n * along — appended rows rising from below, prepended ones descending, ones\r\n * spliced into the middle arriving from the left. Every one of those is a\r\n * claim about where the line came from, and a listing has no such story to\r\n * tell: text is written where it belongs, it does not travel there. Sliding\r\n * also puts the row under the neighbours it is meant to sit between for the\r\n * length of its entrance, which reads as the listing redrawing itself.\r\n */\r\n enteringLineIds: Set<number>;\r\n fromColorById: Map<number, string | undefined>;\r\n phases: Phases;\r\n progress: number;\r\n /** @internal Layout cache — see {@link StructuralTransition}. */\r\n layoutKey: string | null;\r\n fromLayout: CodeLayout | null;\r\n toLayout: CodeLayout | null;\r\n}\r\n\r\n/** A filled band behind whole rows: the first and last line it covers, by line id so it follows them through an edit, and its paint. */\r\nexport interface RowBand {\r\n startId: number;\r\n endId: number;\r\n color: NormalizedColor;\r\n radius: number;\r\n}\r\n\r\n/**\r\n * One set of row bands becoming another. Bands at the same position in both\r\n * lists travel and recolour; one with no counterpart fades.\r\n */\r\nexport interface RowsTransition {\r\n kind: \"rows\";\r\n from: RowBand[];\r\n to: RowBand[];\r\n progress: number;\r\n}\r\n\r\nexport type CodeTransition = DimTransition | StructuralTransition | RowsTransition;\r\n\r\n/**\r\n * Decides *when* (in normalized transition time) each part of a structural\r\n * edit happens, given only whether the edit removes/adds anything.\r\n * `phasesFor` below is the default implementation (exported as\r\n * `defaultCodePhases`) — pass a `phaseStrategy` of this shape to `<Code>` to\r\n * replace it with your own timing.\r\n */\r\nexport type CodePhaseStrategy = (hasRemoved: boolean, hasAdded: boolean) => Phases;\r\n\r\nexport interface TokenState {\r\n opacity: number;\r\n}\r\n\r\n/** Sample a piecewise-linear curve (keys → values) at progress `p` in [0, 1]. */\r\nexport function sampleCurve(keys: number[], values: number[], p: number): number {\r\n if (p <= keys[0]) return values[0];\r\n if (p >= keys[keys.length - 1]) return values[values.length - 1];\r\n for (let i = 0; i < keys.length - 1; i++) {\r\n if (p <= keys[i + 1]) {\r\n const span = keys[i + 1] - keys[i];\r\n const local = span === 0 ? 0 : (p - keys[i]) / span;\r\n return values[i] + (values[i + 1] - values[i]) * local;\r\n }\r\n }\r\n return values[values.length - 1];\r\n}\r\n\r\n/** Progress *within* a phase window, clamped to [0, 1]. A null window is complete. */\r\nexport function windowProgress(w: [number, number] | null, p: number): number {\r\n if (!w) return 1;\r\n const [a, b] = w;\r\n if (p <= a) return 0;\r\n if (p >= b) return 1;\r\n return b === a ? 1 : (p - a) / (b - a);\r\n}\r\n\r\n/** Smooth start and end, so a phase never begins or ends with a velocity step. */\r\nexport function smoothstep(t: number): number {\r\n return t * t * (3 - 2 * t);\r\n}\r\n\r\nexport function makeAnim(id: number, curve: { keys: number[]; values: number[] }): AnimToken {\r\n return { id, opacity: curve.values, opacityKeys: curve.keys };\r\n}\r\n\r\n/**\r\n * The phase schedule for an edit, shaped by what the edit actually contains.\r\n *\r\n * A fixed schedule wastes time it does not need: a pure append has nothing to\r\n * fade out, so holding the first 40% of the duration empty just makes the\r\n * animation feel late. Each shape gets the whole duration spent on the parts\r\n * that exist, with adjacent phases overlapping enough to read as one movement.\r\n */\r\nexport function phasesFor(hasRemoved: boolean, hasAdded: boolean): Phases {\r\n // The overlaps are deliberate and small. Butt-joining the phases leaves the\r\n // block sitting empty at its new size for a beat between the old content\r\n // leaving and the new content arriving; letting the arrival start while the\r\n // reflow's eased tail is still running closes that gap without blurring the\r\n // order the edit reads in.\r\n if (hasRemoved && hasAdded) return { out: [0, 0.38], move: [0.10, 0.68], in: [0.52, 1] };\r\n if (hasRemoved) return { out: [0, 0.45], move: [0.22, 1], in: null };\r\n if (hasAdded) return { out: null, move: [0, 0.55], in: [0.38, 1] };\r\n return { out: null, move: [0, 1], in: null };\r\n}\r\n\r\n/** {@link phasesFor} under the name a `phaseStrategy` default is looked up by. */\r\nexport const defaultCodePhases: CodePhaseStrategy = phasesFor;\r\n\r\n/** How far through the \"everything reflows\" phase a frame is, eased. A settled frame (no edit) is always fully moved. */\r\nexport function moveProgress(edit: { phases: Phases; progress: number } | null): number {\r\n return edit ? smoothstep(windowProgress(edit.phases.move, edit.progress)) : 1;\r\n}\r\n\r\n/**\r\n * Resolve the per-token opacity multiplier for the current frame from the\r\n * persistent highlight dim plus every active dim transition.\r\n */\r\nexport function resolveTokenStates(\r\n tokenLines: IdLine[],\r\n transitions: CodeTransition[],\r\n highlightDimOpacity: number | null,\r\n highlightedIds: Set<number>,\r\n): Map<number, TokenState> {\r\n const out = new Map<number, TokenState>();\r\n\r\n if (highlightDimOpacity !== null) {\r\n const dim = highlightDimOpacity;\r\n for (const line of tokenLines) {\r\n for (const tok of line.tokens) {\r\n out.set(tok.id, { opacity: highlightedIds.has(tok.id) ? 1 : dim });\r\n }\r\n }\r\n }\r\n\r\n for (const tr of transitions) {\r\n if (tr.kind !== \"dim\") continue;\r\n for (const at of tr.tokens) {\r\n out.set(at.id, { opacity: sampleCurve(at.opacityKeys, at.opacity, tr.progress) });\r\n }\r\n }\r\n\r\n return out;\r\n}\r\n"]}
1
+ {"version":3,"file":"transitions.js","sourceRoot":"","sources":["../src/transitions.ts"],"names":[],"mappings":"AAkHA,iFAAiF;AACjF,MAAM,UAAU,WAAW,CAAC,IAAc,EAAE,MAAgB,EAAE,CAAS;IACnE,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;QAAE,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;IACnC,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG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,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAClF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAC9B,UAAoB,EACpB,WAA6B,EAC7B,mBAAkC,EAClC,cAA2B;IAE3B,MAAM,GAAG,GAAG,IAAI,GAAG,EAAsB,CAAC;IAE1C,IAAI,mBAAmB,KAAK,IAAI,EAAE,CAAC;QAC/B,MAAM,GAAG,GAAG,mBAAmB,CAAC;QAChC,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE,CAAC;YAC5B,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAC5B,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,OAAO,EAAE,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;YACvE,CAAC;QACL,CAAC;IACL,CAAC;IAED,KAAK,MAAM,EAAE,IAAI,WAAW,EAAE,CAAC;QAC3B,IAAI,EAAE,CAAC,IAAI,KAAK,KAAK;YAAE,SAAS;QAChC,KAAK,MAAM,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,CAAC;YACzB,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,OAAO,EAAE,WAAW,CAAC,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACtF,CAAC;IACL,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["import type { NormalizedColor } from \"@motionscript/sdk\";\nimport type { CodeLayout } from \"./layout\";\nimport { IdLine } from \"./tokens\";\n\n// A single animated token entry owned by one dim transition. Keyed by stable\n// token id rather than (line, tokenIndex) so concurrent animations don't clobber\n// each other when one shifts the indices of tokens the other is animating.\nexport interface AnimToken {\n id: number;\n opacity: number[];\n opacityKeys: number[];\n}\n\n/**\n * A highlight cross-fade: opacity, and nothing else.\n *\n * Structure is untouched, so several of these stack happily and a listing held\n * under a highlight still hits the static-layout cache.\n */\nexport interface DimTransition {\n kind: \"dim\";\n tokens: AnimToken[];\n progress: number;\n}\n\n/**\n * When each part of a structural edit happens, in normalized transition time.\n *\n * The order is what an edit *looks like* being made: what is going away leaves\n * first, what stays reflows into its new place, and only then does what is new\n * appear. Running them together is what made a replacement look like a\n * cross-dissolve of two unrelated listings.\n */\nexport interface Phases {\n /** Removed tokens fade out. Null when the edit removes nothing. */\n out: [number, number] | null;\n /** Surviving tokens travel, and the block resizes. Always present. */\n move: [number, number];\n /** Added tokens fade (and slide) in. Null when the edit adds nothing. */\n in: [number, number] | null;\n}\n\n/**\n * One edit in flight: the structure before, the structure after, and who is\n * doing what.\n *\n * Both endpoints are fixed for the transition's whole life, which is why the\n * two resolved layouts hang off it — they are computed once and reused for\n * every frame the edit spans, rather than rebuilt per frame from a structure\n * that is being mutated underneath.\n */\nexport interface StructuralTransition {\n kind: \"structural\";\n from: IdLine[];\n to: IdLine[];\n removedIds: Set<number>;\n addedIds: Set<number>;\n /**\n * Ids of rows in `to` that did not exist before, and so enter as a whole\n * row rather than as tokens spliced into one.\n *\n * They enter by fading in place, and that is the *only* thing they do. An\n * earlier version slid each one in from the edge the block had just grown\n * along — appended rows rising from below, prepended ones descending, ones\n * spliced into the middle arriving from the left. Every one of those is a\n * claim about where the line came from, and a listing has no such story to\n * tell: text is written where it belongs, it does not travel there. Sliding\n * also puts the row under the neighbours it is meant to sit between for the\n * length of its entrance, which reads as the listing redrawing itself.\n */\n enteringLineIds: Set<number>;\n fromColorById: Map<number, string | undefined>;\n phases: Phases;\n progress: number;\n /** @internal Layout cache — see {@link StructuralTransition}. */\n layoutKey: string | null;\n fromLayout: CodeLayout | null;\n toLayout: CodeLayout | null;\n}\n\n/** A filled band behind whole rows: the first and last line it covers, by line id so it follows them through an edit, and its paint. */\nexport interface RowBand {\n startId: number;\n endId: number;\n color: NormalizedColor;\n radius: number;\n}\n\n/**\n * One set of row bands becoming another. Bands at the same position in both\n * lists travel and recolour; one with no counterpart fades.\n */\nexport interface RowsTransition {\n kind: \"rows\";\n from: RowBand[];\n to: RowBand[];\n progress: number;\n}\n\nexport type CodeTransition = DimTransition | StructuralTransition | RowsTransition;\n\n/**\n * Decides *when* (in normalized transition time) each part of a structural\n * edit happens, given only whether the edit removes/adds anything.\n * `phasesFor` below is the default implementation (exported as\n * `defaultCodePhases`) — pass a `phaseStrategy` of this shape to `<Code>` to\n * replace it with your own timing.\n */\nexport type CodePhaseStrategy = (hasRemoved: boolean, hasAdded: boolean) => Phases;\n\nexport interface TokenState {\n opacity: number;\n}\n\n/** Sample a piecewise-linear curve (keys → values) at progress `p` in [0, 1]. */\nexport function sampleCurve(keys: number[], values: number[], p: number): number {\n if (p <= keys[0]) return values[0];\n if (p >= keys[keys.length - 1]) return values[values.length - 1];\n for (let i = 0; i < keys.length - 1; i++) {\n if (p <= keys[i + 1]) {\n const span = keys[i + 1] - keys[i];\n const local = span === 0 ? 0 : (p - keys[i]) / span;\n return values[i] + (values[i + 1] - values[i]) * local;\n }\n }\n return values[values.length - 1];\n}\n\n/** Progress *within* a phase window, clamped to [0, 1]. A null window is complete. */\nexport function windowProgress(w: [number, number] | null, p: number): number {\n if (!w) return 1;\n const [a, b] = w;\n if (p <= a) return 0;\n if (p >= b) return 1;\n return b === a ? 1 : (p - a) / (b - a);\n}\n\n/** Smooth start and end, so a phase never begins or ends with a velocity step. */\nexport function smoothstep(t: number): number {\n return t * t * (3 - 2 * t);\n}\n\nexport function makeAnim(id: number, curve: { keys: number[]; values: number[] }): AnimToken {\n return { id, opacity: curve.values, opacityKeys: curve.keys };\n}\n\n/**\n * The phase schedule for an edit, shaped by what the edit actually contains.\n *\n * A fixed schedule wastes time it does not need: a pure append has nothing to\n * fade out, so holding the first 40% of the duration empty just makes the\n * animation feel late. Each shape gets the whole duration spent on the parts\n * that exist, with adjacent phases overlapping enough to read as one movement.\n */\nexport function phasesFor(hasRemoved: boolean, hasAdded: boolean): Phases {\n // The overlaps are deliberate and small. Butt-joining the phases leaves the\n // block sitting empty at its new size for a beat between the old content\n // leaving and the new content arriving; letting the arrival start while the\n // reflow's eased tail is still running closes that gap without blurring the\n // order the edit reads in.\n if (hasRemoved && hasAdded) return { out: [0, 0.38], move: [0.10, 0.68], in: [0.52, 1] };\n if (hasRemoved) return { out: [0, 0.45], move: [0.22, 1], in: null };\n if (hasAdded) return { out: null, move: [0, 0.55], in: [0.38, 1] };\n return { out: null, move: [0, 1], in: null };\n}\n\n/** {@link phasesFor} under the name a `phaseStrategy` default is looked up by. */\nexport const defaultCodePhases: CodePhaseStrategy = phasesFor;\n\n/** How far through the \"everything reflows\" phase a frame is, eased. A settled frame (no edit) is always fully moved. */\nexport function moveProgress(edit: { phases: Phases; progress: number } | null): number {\n return edit ? smoothstep(windowProgress(edit.phases.move, edit.progress)) : 1;\n}\n\n/**\n * Resolve the per-token opacity multiplier for the current frame from the\n * persistent highlight dim plus every active dim transition.\n */\nexport function resolveTokenStates(\n tokenLines: IdLine[],\n transitions: CodeTransition[],\n highlightDimOpacity: number | null,\n highlightedIds: Set<number>,\n): Map<number, TokenState> {\n const out = new Map<number, TokenState>();\n\n if (highlightDimOpacity !== null) {\n const dim = highlightDimOpacity;\n for (const line of tokenLines) {\n for (const tok of line.tokens) {\n out.set(tok.id, { opacity: highlightedIds.has(tok.id) ? 1 : dim });\n }\n }\n }\n\n for (const tr of transitions) {\n if (tr.kind !== \"dim\") continue;\n for (const at of tr.tokens) {\n out.set(at.id, { opacity: sampleCurve(at.opacityKeys, at.opacity, tr.progress) });\n }\n }\n\n return out;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionscript/code",
3
- "version": "0.1.0-alpha.8",
3
+ "version": "0.1.0",
4
4
  "type": "module",
5
5
  "description": "Animated, syntax-highlighted code blocks for Motion Script, with token-level append, insert, remove, replace, and highlight transitions.",
6
6
  "repository": {
@@ -46,7 +46,7 @@
46
46
  "license": "Apache-2.0",
47
47
  "author": "Motionscript",
48
48
  "peerDependencies": {
49
- "@motionscript/sdk": "^0.1.0-alpha.8"
49
+ "@motionscript/sdk": "^0.1.0"
50
50
  },
51
51
  "dependencies": {
52
52
  "@lezer/common": "^1.5.2",
@@ -74,8 +74,8 @@
74
74
  "typescript": "^6.0.3",
75
75
  "typescript-eslint": "^8.48.0",
76
76
  "vitest": "^4.1.5",
77
- "@motionscript/core": "0.1.0-alpha.8",
78
- "@motionscript/sdk": "0.1.0-alpha.8"
77
+ "@motionscript/core": "0.1.0",
78
+ "@motionscript/sdk": "0.1.0"
79
79
  },
80
80
  "scripts": {
81
81
  "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json --resolve-full-paths && node ../../../scripts/build-browser.mjs",
package/registry.json CHANGED
@@ -1,6 +1,6 @@
1
- {
2
- "kit": { "barrel": "src/engine.ts", "specifier": "@motionscript/code" },
3
- "items": [
4
- { "name": "code", "root": "src", "files": ["node.ts"], "flatten": true }
5
- ]
6
- }
1
+ {
2
+ "kit": { "barrel": "src/engine.ts", "specifier": "@motionscript/code" },
3
+ "items": [
4
+ { "name": "code", "root": "src", "files": ["node.ts"], "flatten": true }
5
+ ]
6
+ }
package/src/code-range.ts CHANGED
@@ -1,165 +1,165 @@
1
- /**
2
- * A range over a code document. Lines and columns are 1-indexed.
3
- *
4
- * `endLine`/`endCol` may be `Infinity` to mean "to the end of the line" or
5
- * "to the end of the document".
6
- */
7
- export interface CodeRange {
8
- startLine: number;
9
- startCol: number;
10
- endLine: number;
11
- endCol: number;
12
- }
13
-
14
- /**
15
- * Create a range that spans `length` characters starting at (line, col).
16
- * If `length` is omitted, the range extends to the end of the line.
17
- *
18
- * Example:
19
- * word(1, 3, 3) // line 1, column 3, spans 3 characters
20
- * word(1, 3) // line 1, column 3, to end of line
21
- */
22
- export function word(line: number, col: number, length?: number): CodeRange {
23
- return {
24
- startLine: line,
25
- startCol: col,
26
- endLine: line,
27
- endCol: length === undefined ? Infinity : col + length,
28
- };
29
- }
30
-
31
- /**
32
- * Create a range that covers entire lines from `from` to `to` (inclusive).
33
- * If `to` is omitted, only line `from` is covered.
34
- *
35
- * Example:
36
- * lines(1, 3) // lines 1 through 3
37
- * lines(2) // line 2 only
38
- */
39
- export function lines(from: number, to?: number): CodeRange {
40
- return {
41
- startLine: from,
42
- startCol: 1,
43
- endLine: to ?? from,
44
- endCol: Infinity,
45
- };
46
- }
47
-
48
-
49
-
50
- /**
51
- * Immutable, chainable, iterable builder over multiple ranges — mirrors
52
- * {@link FillChain}/`Fills` in `@motionscript/sdk`. Every method returns a
53
- * *new* chain with one more range appended, so the next range-kind method is
54
- * called directly rather than through a separate combinator:
55
- *
56
- * @example
57
- * CodeRanges.lines(2).word(5, 1, 3) // a 2-range selection, one expression
58
- */
59
- export class CodeRangeChain {
60
- constructor(public readonly list: CodeRange[] = []) { }
61
-
62
- lines(from: number, to?: number): CodeRangeChain {
63
- return new CodeRangeChain([...this.list, lines(from, to)]);
64
- }
65
-
66
- word(line: number, col: number, length?: number): CodeRangeChain {
67
- return new CodeRangeChain([...this.list, word(line, col, length)]);
68
- }
69
-
70
- *[Symbol.iterator](): Iterator<CodeRange> {
71
- yield* this.list;
72
- }
73
-
74
- /**
75
- * A chain is stored as its ranges. Without this it serialises as
76
- * `{ "list": [...] }`, which has no iterator once read back and so selects
77
- * nothing; a plain array of ranges reads back as the selection it was.
78
- */
79
- toJSON(): CodeRange[] {
80
- return this.list;
81
- }
82
- }
83
-
84
- /**
85
- * Entry point for building multi-range selections fluently — an empty
86
- * {@link CodeRangeChain}, so `CodeRanges.lines(2)` *is* `new
87
- * CodeRangeChain().lines(2)`. `word`/`lines` stay directly importable and
88
- * usable standalone for a single range; reach for `CodeRanges` when a call
89
- * needs more than one.
90
- */
91
- export const CodeRanges = new CodeRangeChain();
92
-
93
- /**
94
- * Convert a CodeRange to absolute character offsets [start, end) in the joined
95
- * source text, given the per-line lengths of that source. Lines/columns are
96
- * clamped into the document so out-of-bounds inputs produce a valid range.
97
- */
98
- export function rangeToCharOffsets(
99
- r: CodeRange,
100
- lineLengths: number[],
101
- ): { start: number; end: number } {
102
- if (lineLengths.length === 0) return { start: 0, end: 0 };
103
-
104
- // Cumulative line starts in the joined string (lines joined with '\n').
105
- const lineStart: number[] = new Array(lineLengths.length);
106
- let acc = 0;
107
- for (let i = 0; i < lineLengths.length; i++) {
108
- lineStart[i] = acc;
109
- acc += lineLengths[i] + 1; // +1 for the joining newline
110
- }
111
- const docEnd = acc > 0 ? acc - 1 : 0; // strip trailing newline
112
-
113
- const clampLine = (n: number) =>
114
- Math.max(0, Math.min(lineLengths.length - 1, n - 1)); // to 0-indexed
115
-
116
- // A range read back from JSON holds `Infinity` as `null`; both mean "to the end".
117
- const endLine = r.endLine ?? Infinity;
118
- const endCol = r.endCol ?? Infinity;
119
-
120
- const sLine = clampLine(r.startLine);
121
- const eLine = clampLine(endLine);
122
- const sColMax = lineLengths[sLine];
123
- const eColMax = lineLengths[eLine];
124
-
125
- // Columns are 1-indexed; clamp to [1, lineLength+1] so endCol can sit past
126
- // the last char (one-past-end).
127
- const sCol = Math.max(0, Math.min(sColMax, r.startCol - 1));
128
- const eCol = endCol === Infinity
129
- ? eColMax
130
- : Math.max(0, Math.min(eColMax, endCol - 1));
131
-
132
- const start = Math.min(docEnd, lineStart[sLine] + sCol);
133
- const end = Math.min(docEnd, lineStart[eLine] + eCol);
134
- return { start: Math.min(start, end), end: Math.max(start, end) };
135
- }
136
-
137
- /**
138
- * Convert [start, end) character offsets in joined source to a CodeRange.
139
- * Lines/cols in the returned range are 1-indexed.
140
- */
141
- export function charOffsetsToRange(
142
- start: number,
143
- end: number,
144
- lineLengths: number[],
145
- ): CodeRange {
146
- let off = 0;
147
- let startLine = 1, startCol = 1, endLine = 1, endCol = 1;
148
- let foundStart = false;
149
- for (let li = 0; li < lineLengths.length; li++) {
150
- const lineStart = off;
151
- const lineEnd = off + lineLengths[li];
152
- if (!foundStart && start >= lineStart && start <= lineEnd) {
153
- startLine = li + 1;
154
- startCol = (start - lineStart) + 1;
155
- foundStart = true;
156
- }
157
- if (end >= lineStart && end <= lineEnd) {
158
- endLine = li + 1;
159
- endCol = (end - lineStart) + 1;
160
- break;
161
- }
162
- off = lineEnd + 1;
163
- }
164
- return { startLine, startCol, endLine, endCol };
165
- }
1
+ /**
2
+ * A range over a code document. Lines and columns are 1-indexed.
3
+ *
4
+ * `endLine`/`endCol` may be `Infinity` to mean "to the end of the line" or
5
+ * "to the end of the document".
6
+ */
7
+ export interface CodeRange {
8
+ startLine: number;
9
+ startCol: number;
10
+ endLine: number;
11
+ endCol: number;
12
+ }
13
+
14
+ /**
15
+ * Create a range that spans `length` characters starting at (line, col).
16
+ * If `length` is omitted, the range extends to the end of the line.
17
+ *
18
+ * Example:
19
+ * word(1, 3, 3) // line 1, column 3, spans 3 characters
20
+ * word(1, 3) // line 1, column 3, to end of line
21
+ */
22
+ export function word(line: number, col: number, length?: number): CodeRange {
23
+ return {
24
+ startLine: line,
25
+ startCol: col,
26
+ endLine: line,
27
+ endCol: length === undefined ? Infinity : col + length,
28
+ };
29
+ }
30
+
31
+ /**
32
+ * Create a range that covers entire lines from `from` to `to` (inclusive).
33
+ * If `to` is omitted, only line `from` is covered.
34
+ *
35
+ * Example:
36
+ * lines(1, 3) // lines 1 through 3
37
+ * lines(2) // line 2 only
38
+ */
39
+ export function lines(from: number, to?: number): CodeRange {
40
+ return {
41
+ startLine: from,
42
+ startCol: 1,
43
+ endLine: to ?? from,
44
+ endCol: Infinity,
45
+ };
46
+ }
47
+
48
+
49
+
50
+ /**
51
+ * Immutable, chainable, iterable builder over multiple ranges — mirrors
52
+ * {@link FillChain}/`Fills` in `@motionscript/sdk`. Every method returns a
53
+ * *new* chain with one more range appended, so the next range-kind method is
54
+ * called directly rather than through a separate combinator:
55
+ *
56
+ * @example
57
+ * CodeRanges.lines(2).word(5, 1, 3) // a 2-range selection, one expression
58
+ */
59
+ export class CodeRangeChain {
60
+ constructor(public readonly list: CodeRange[] = []) { }
61
+
62
+ lines(from: number, to?: number): CodeRangeChain {
63
+ return new CodeRangeChain([...this.list, lines(from, to)]);
64
+ }
65
+
66
+ word(line: number, col: number, length?: number): CodeRangeChain {
67
+ return new CodeRangeChain([...this.list, word(line, col, length)]);
68
+ }
69
+
70
+ *[Symbol.iterator](): Iterator<CodeRange> {
71
+ yield* this.list;
72
+ }
73
+
74
+ /**
75
+ * A chain is stored as its ranges. Without this it serialises as
76
+ * `{ "list": [...] }`, which has no iterator once read back and so selects
77
+ * nothing; a plain array of ranges reads back as the selection it was.
78
+ */
79
+ toJSON(): CodeRange[] {
80
+ return this.list;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Entry point for building multi-range selections fluently — an empty
86
+ * {@link CodeRangeChain}, so `CodeRanges.lines(2)` *is* `new
87
+ * CodeRangeChain().lines(2)`. `word`/`lines` stay directly importable and
88
+ * usable standalone for a single range; reach for `CodeRanges` when a call
89
+ * needs more than one.
90
+ */
91
+ export const CodeRanges = new CodeRangeChain();
92
+
93
+ /**
94
+ * Convert a CodeRange to absolute character offsets [start, end) in the joined
95
+ * source text, given the per-line lengths of that source. Lines/columns are
96
+ * clamped into the document so out-of-bounds inputs produce a valid range.
97
+ */
98
+ export function rangeToCharOffsets(
99
+ r: CodeRange,
100
+ lineLengths: number[],
101
+ ): { start: number; end: number } {
102
+ if (lineLengths.length === 0) return { start: 0, end: 0 };
103
+
104
+ // Cumulative line starts in the joined string (lines joined with '\n').
105
+ const lineStart: number[] = new Array(lineLengths.length);
106
+ let acc = 0;
107
+ for (let i = 0; i < lineLengths.length; i++) {
108
+ lineStart[i] = acc;
109
+ acc += lineLengths[i] + 1; // +1 for the joining newline
110
+ }
111
+ const docEnd = acc > 0 ? acc - 1 : 0; // strip trailing newline
112
+
113
+ const clampLine = (n: number) =>
114
+ Math.max(0, Math.min(lineLengths.length - 1, n - 1)); // to 0-indexed
115
+
116
+ // A range read back from JSON holds `Infinity` as `null`; both mean "to the end".
117
+ const endLine = r.endLine ?? Infinity;
118
+ const endCol = r.endCol ?? Infinity;
119
+
120
+ const sLine = clampLine(r.startLine);
121
+ const eLine = clampLine(endLine);
122
+ const sColMax = lineLengths[sLine];
123
+ const eColMax = lineLengths[eLine];
124
+
125
+ // Columns are 1-indexed; clamp to [1, lineLength+1] so endCol can sit past
126
+ // the last char (one-past-end).
127
+ const sCol = Math.max(0, Math.min(sColMax, r.startCol - 1));
128
+ const eCol = endCol === Infinity
129
+ ? eColMax
130
+ : Math.max(0, Math.min(eColMax, endCol - 1));
131
+
132
+ const start = Math.min(docEnd, lineStart[sLine] + sCol);
133
+ const end = Math.min(docEnd, lineStart[eLine] + eCol);
134
+ return { start: Math.min(start, end), end: Math.max(start, end) };
135
+ }
136
+
137
+ /**
138
+ * Convert [start, end) character offsets in joined source to a CodeRange.
139
+ * Lines/cols in the returned range are 1-indexed.
140
+ */
141
+ export function charOffsetsToRange(
142
+ start: number,
143
+ end: number,
144
+ lineLengths: number[],
145
+ ): CodeRange {
146
+ let off = 0;
147
+ let startLine = 1, startCol = 1, endLine = 1, endCol = 1;
148
+ let foundStart = false;
149
+ for (let li = 0; li < lineLengths.length; li++) {
150
+ const lineStart = off;
151
+ const lineEnd = off + lineLengths[li];
152
+ if (!foundStart && start >= lineStart && start <= lineEnd) {
153
+ startLine = li + 1;
154
+ startCol = (start - lineStart) + 1;
155
+ foundStart = true;
156
+ }
157
+ if (end >= lineStart && end <= lineEnd) {
158
+ endLine = li + 1;
159
+ endCol = (end - lineStart) + 1;
160
+ break;
161
+ }
162
+ off = lineEnd + 1;
163
+ }
164
+ return { startLine, startCol, endLine, endCol };
165
+ }