mrkr
v0.1.0
Published
`mrkr` is a lightweight TypeScript library providing a `markable` template tag. It allows you to create strings with embedded markers to easily track positions, compose strings, and split them at marked locations.
Readme
mrkr
mrkr is a lightweight TypeScript library providing a markable template tag. It allows you to create strings with embedded markers to easily track positions, compose strings, and split them at marked locations.
Features
- Create strings with markers using a simple template literal syntax.
- Automatically tracks the
startandendpositions of markers. - Compose
markablestrings together, preserving marker information. - Use
markRefto create references to specific markers and find their offsets. - Split strings into parts using the
cut()method. - Fully typed with TypeScript.
Installation
Install the dependencies:
pnpm installUsage
Basic Marking
Import markable and mark to create your first marked string. The mark symbol indicates where a marker should be placed.
import { markable, mark as v } from 'mrkr';
const str = markable`Hello, ${v}world!`;
console.log(str.toString()); // "Hello, world!"
// Get the position of the first and last marks
console.log(str.start); // 7
console.log(str.end); // 7Multiple Markers and cut()
You can place multiple marks. The cut() method will split the string at each marker.
import { markable, mark as v } from 'mrkr';
const str = markable`foo${v}bar${v}baz`;
console.log(str.cut()); // ['foo', 'bar', 'baz']
console.log(str.start); // 3
console.log(str.end); // 6Composition
markable strings can be nested and composed seamlessly.
import { markable, mark as v } from 'mrkr';
const foo = markable`fo${v}o`;
const bar = markable`b${v}ar`;
const foobar = markable`${foo}${v}${bar}`;
console.log(foobar.toString()); // "foobar"
console.log(foobar.start); // 2 (from foo)
console.log(foobar.end); // 4 (from bar)
// .cut() splits at all nested and new marks
console.log(foobar.cut()); // ['fo', 'o', 'b', 'ar']markRef for Tagged Markers
For more advanced control, markRef allows you to create a reference to a marker. This reference can be used to find the offset of that specific marker, even in composed strings.
import { markable, markRef } from 'mrkr';
const nameRef = markRef();
const greeting = markable`Hello, ${nameRef}John Doe!`;
// Find the position of the marker using the reference
const namePosition = nameRef.offsetFrom(greeting);
// You can also get it from the string instance
// const namePosition = greeting.offsetOf(nameRef);
console.log(namePosition); // 7
console.log(greeting.substring(greeting.start)); // "John Doe!"
// The reference works across compositions
const announcement = markable`Attention! ${greeting}. Welcome.`;
const namePositionInAnnouncement = nameRef.offsetFrom(announcement);
console.log(namePositionInAnnouncement); // 18Development
Build the library:
pnpm run buildBuild the library in watch mode:
pnpm run dev