Skip to content

Commit

Permalink
feat(json-crdt-extensions): 🎸 progress on type registry implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Dec 25, 2024
1 parent 1688434 commit d239803
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/json-crdt-extensions/peritext/registry/SliceRegistry.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import {PeritextMlElement} from '../block/types';
import type {JsonMlNode} from 'very-small-parser/lib/html/json-ml/types';
import type {FromHtmlConverter, SliceTypeDefinition, ToHtmlConverter} from './types';

export class SliceRegistry {
private map: Map<string | number, SliceTypeDefinition> = new Map();
private toHtmlMap: Map<string | number, ToHtmlConverter> = new Map();
private fromHtmlMap: Map<string, FromHtmlConverter[]> = new Map();

public add(def: SliceTypeDefinition): this {
public add(def: SliceTypeDefinition<PeritextMlElement<any, any, any>>): this {
const {type, toHtml, fromHtml} = def;
this.map.set(type, def);
if (toHtml) this.toHtmlMap.set(type, toHtml);
Expand All @@ -19,5 +21,18 @@ export class SliceRegistry {
return this;
}

public toHtml(type: string | number, json: unknown): unknown {}
public toHtml(el: PeritextMlElement): JsonMlNode | undefined {
const converter = this.toHtmlMap.get(el[0]);
return converter ? converter(el) : undefined;
}

public fromHtml(el: JsonMlNode): PeritextMlElement | undefined {
const tag = el[0] + '';
const converters = this.fromHtmlMap.get(tag);
for (const converter of converters ?? []) {
const result = converter(el);
if (result) return result;
}
return;
}
}
14 changes: 14 additions & 0 deletions src/json-crdt-extensions/peritext/registry/registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {PeritextMlElement} from "../block/types";
import {CommonSliceType} from "../slice";
import {SliceRegistry} from "./SliceRegistry";
import {SliceTypeDefinition} from "./types";

/**
* Default annotation type registry.
*/
export const registry = new SliceRegistry();

registry.add({
type: CommonSliceType.a,
toHtml: (element: PeritextMlElement<CommonSliceType.a, {}, true>) => ['a', element[1], element[2]],
} as SliceTypeDefinition<PeritextMlElement<CommonSliceType.a, {href?: string, title?: string}, true>>);

0 comments on commit d239803

Please sign in to comment.