Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement ImageRule #23

Merged
merged 6 commits into from
Jan 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/main/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface ContextWithMedia extends Context {
mediaIds: Set<string>;
resolvedMedia: Map<string, MediaDef>;
isExternalLink(media: MediaDef): boolean;
getNextInlineId(): string;
}

export class RhoContext extends Context
Expand All @@ -23,10 +24,16 @@ export class RhoContext extends Context
super(processor);
}

linkCounter: number = 0;
mediaIds: Set<string> = new Set();
resolvedMedia: Map<string, MediaDef> = new Map();

isExternalLink(media: MediaDef): boolean {
return media.external ?? this.processor.options.externalLinks;
}

getNextInlineId() {
this.linkCounter += 1;
return '__' + this.linkCounter;
}
}
56 changes: 36 additions & 20 deletions src/main/core/cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ const {
CHAR_LF,
CHAR_FF,
CHAR_CR,
CHAR_BACKSLASH,
CHAR_MINUS,
CHAR_UNDERSCORE,
CHAR_BACKSLASH,
} = constants;

/**
Expand Down Expand Up @@ -129,6 +129,19 @@ export class Cursor {
return this.peekCode(offset) === code;
}

/**
* Tests if cursor is at specified sequence of character blocks.
* Faster alternative to `at`.
*/
atSeq(...seq: number[]) {
for (let i = 0; i < seq.length; i++) {
if (seq[i] !== this.peekCode(i)) {
return false;
}
}
return true;
}

/**
* Tests if cursor is currently positioned at specified string,
* ignoring case.
Expand Down Expand Up @@ -230,25 +243,6 @@ export class Cursor {
return this.currentCode() === 0 && this.pos < this.region.length;
}

/**
* Scans forward till positioned at `str` and returns its index, if found.
* Backslash escapes are ignored.
*/
indexOfEscaped(str: string): number | null {
const cur = this.clone();
while (cur.hasCurrent()) {
if (cur.atCode(CHAR_BACKSLASH)) {
cur.skip(2);
continue;
}
if (cur.at(str)) {
return cur.pos;
}
cur.skip();
}
return null;
}

/**
* Advances cursor forward by `n` characters.
*/
Expand Down Expand Up @@ -396,6 +390,28 @@ export class Cursor {
return this.region.subRegion(start, this.pos);
}

/**
* Scans forward, returning an index of specified sequence of character codes.
* When backslash is encountered, it is skipped along with an adjacent character,
* allowing escaping any markers with a backslash.
* Returns null if no such sequence is found.
* Cursor is not modified.
*/
scanSeq(...seq: number[]): number | null {
const cur = this.clone();
while (cur.hasCurrent()) {
if (cur.atCode(CHAR_BACKSLASH)) {
cur.skip(2);
continue;
}
if (cur.atSeq(...seq)) {
return cur.pos;
}
cur.skip();
}
return null;
}

debug() {
const fmt = (str: string) => str.replace(/ /g, '·').replace(/\n/g, '↲\n');
const prefix = this.region.substring(0, this.pos);
Expand Down
2 changes: 2 additions & 0 deletions src/main/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
ParagraphRule,
LinkRule,
HeadlessLinkRule,
ImageRule,
} from './rules';
import { RhoOptions, RHO_DEFAULT_OPTIONS } from './options';
import { RhoContext } from './context';
Expand Down Expand Up @@ -67,6 +68,7 @@ export class RhoProcessor extends Processor {
new FormulaRule(ctx, { marker: '%%' }),
new LinkRule(ctx as RhoContext),
new HeadlessLinkRule(ctx as RhoContext),
new ImageRule(ctx as RhoContext),
new VerbatimRule(ctx),
]);
this.defineParser('code', ctx => [
Expand Down
23 changes: 16 additions & 7 deletions src/main/rules/block/bracket.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Rule, Region, Cursor, Node } from '../../core';
import { Rule, Region, Cursor, Node, constants } from '../../core';

const { CHAR_BACKSLASH } = constants;

/**
* A convenience rule that parsers content between opening and closing markers.
Expand All @@ -17,12 +19,19 @@ export abstract class BracketRule extends Rule {
}
cursor.skip(openMarker.length);
// Look for closeMarker, ignoring backslashes
const end = cursor.indexOfEscaped(closeMarker);
if (end == null) {
return null;
const start = cursor.pos;
while (cursor.hasCurrent()) {
if (cursor.atCode(CHAR_BACKSLASH)) {
cursor.skip(2);
continue;
}
if (cursor.at(closeMarker)) {
const region = cursor.subRegion(start, cursor.pos);
cursor.skip(closeMarker.length);
return this.parseSubRegion(region);
}
cursor.skip();
}
const region = cursor.readUntil(end);
cursor.skip(closeMarker.length);
return this.parseSubRegion(region);
return null;
}
}
3 changes: 2 additions & 1 deletion src/main/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ export * from './inline/formula';
export * from './inline/html-comment';
export * from './inline/html-entity';
export * from './inline/html-tag';
export * from './inline/image';
export * from './inline/link';
export * from './inline/plain-text';
export * from './inline/verbatim';
export * from './inline/strike';
export * from './inline/strong';
export * from './inline/verbatim';
106 changes: 106 additions & 0 deletions src/main/rules/inline/image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { Rule, Cursor, Node, constants, Region } from '../../core';
import { escapeHtml } from '../../util/escape';
import { MediaDef } from '../../util/media';
import { ContextWithMedia } from '../../context';

const {
CHAR_SQUARE_LEFT,
CHAR_SQUARE_RIGHT,
CHAR_EXCLAMATION,
CHAR_PAREN_LEFT,
CHAR_PAREN_RIGHT,
} = constants;

export class ImageRule extends Rule {

constructor(
readonly ctx: ContextWithMedia,
) {
super(ctx);
}

protected parseAt(cursor: Cursor): Node | null {
if (!(cursor.atCode(CHAR_EXCLAMATION) && cursor.atCode(CHAR_SQUARE_LEFT, 1))) {
return null;
}
const regionStart = cursor.pos;
cursor.skip(2);
const textStart = cursor.pos;
const textEnd = cursor.scanSeq(CHAR_SQUARE_RIGHT);
if (textEnd == null) {
return null;
}
cursor.set(textEnd + 1);
const text = cursor.subRegion(textStart, textEnd).toString();
return this.tryInlineImg(cursor, text, regionStart)
|| this.tryRefImg(cursor, text, regionStart);
}

protected tryInlineImg(cursor: Cursor, text: string, regionStart: number): Node | null {
if (!cursor.atCode(CHAR_PAREN_LEFT)) {
return null;
}
cursor.skip();
const hrefStart = cursor.pos;
const hrefEnd = cursor.scanSeq(CHAR_PAREN_RIGHT);
if (hrefEnd == null) {
return null;
}
cursor.set(hrefEnd + 1);
const id = this.ctx.getNextInlineId();
const href = cursor.subRegion(hrefStart, hrefEnd).toString();
const region = cursor.subRegion(regionStart, cursor.pos);
this.ctx.mediaIds.add(id);
this.ctx.resolvedMedia.set(id, { href });
return new ImageNode(region, id, text);
}

protected tryRefImg(cursor: Cursor, text: string, regionStart: number): Node | null {
if (!cursor.atCode(CHAR_SQUARE_LEFT)) {
return null;
}
cursor.skip();
const idStart = cursor.pos;
const idEnd = cursor.scanSeq(CHAR_SQUARE_RIGHT);
if (idEnd == null) {
return null;
}
const id = cursor.subRegion(idStart, idEnd).toString();
cursor.skip();
const region = cursor.subRegion(regionStart, cursor.pos);
this.ctx.mediaIds.add(id);
return new ImageNode(region, id, text);
}

}

export class ImageNode extends Node {

constructor(
region: Region,
public id: string,
public text: string = '',
) {
super(region, []);
}

resolveMedia(ctx: ContextWithMedia): MediaDef | null {
return ctx.resolvedMedia.get(this.id) || null;
}

render(ctx: ContextWithMedia) {
const media = this.resolveMedia(ctx);
if (media == null) {
return '';
}
let buffer = '<img';
buffer += ` src="${escapeHtml(media.href)}"`;
if (this.text) {
buffer += ` alt="${escapeHtml(this.text)}"`;
}
buffer += ` title="${escapeHtml(media.title || this.text)}"`;
buffer += '/>';
return buffer;
}

}
Loading