Skip to content

Instantly share code, notes, and snippets.

@killan
Last active October 12, 2023 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killan/47b490be2e5b4a479a4a0da3e222d4d2 to your computer and use it in GitHub Desktop.
Save killan/47b490be2e5b4a479a4a0da3e222d4d2 to your computer and use it in GitHub Desktop.
TipTap JSONContent mapLoops
export type PdfMap = { [key: string]: string | boolean | PdfMap[] }
export enum JSONContentType {
Heading = "heading",
Paragraph = "paragraph",
Text = "text",
BulletList = "bulletList",
OrderedList = "orderedList",
ListItem = "listItem",
HardBreak = "hardBreak",
HorizontalRule = "horizontalRule",
Section = "section"
}
export class PdfService {
static mapLoops(json: JSONContent, map: PdfMap, result?: JSONContent): JSONContent {
if (!result) {
result = {
type: "doc",
content: []
}
}
json.content?.forEach((c) => {
const varName = c.attrs?.varName
if ((c.type === JSONContentType.ListItem || c.type === JSONContentType.Section) && varName && map[varName] && Array.isArray(map[varName])) {
// Alter content with current demultiplied
result!.content?.push(
...(map[varName] as PdfMap[]).map(
(li) =>
({
...c,
attrs: c.attrs ? this.removeAttr(c.attrs, "varName") : undefined,
content: this.mapLoops(c, { ...map, ...li }, { ...c, content: [] }).content
} as JSONContent)
)
)
} else if (c.type === JSONContentType.Section && varName) {
if (map[varName] === undefined) {
result!.content?.push(this.mapLoops(c, map, { ...c, content: [] }))
} else if (map[varName]) {
// Add section
result!.content?.push(this.mapLoops(c, map, { ...c, attrs: c.attrs ? this.removeAttr(c.attrs, "varName") : undefined, content: [] }))
} // else no add
} else if (c.type === JSONContentType.Text) {
// Content replacement
let varText = c.text + ""
if (c.text) {
varText = this.mapReplace(varText, map)
}
// Add node
result!.content?.push({ ...c, text: varText })
} else {
// All others, add contents in a fresh node
result!.content?.push(this.mapLoops(c, map, { ...c, content: [] }))
}
})
return result
}
static MapReplace(str: string, map: PdfMap): string {
Object.keys(map).forEach((k) => {
if (!Array.isArray(map[k]) && map[k]) {
// Only non empty text nodes are allowed (keep placeholder for empty nodes)
str = str.replace(new RegExp("\\[" + k + "\\]", "g"), map[k] as string)
}
})
return str
}
static removeAttr(attrs: Record<string, any>, attrToRemove: string): Record<string, any> {
const newAttrs: Record<string, any> = {}
for (const key in attrs) {
if (key !== attrToRemove) {
newAttrs[key] = attrs[key]
}
}
return newAttrs
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment