/
template.ts
219 lines (190 loc) · 7.09 KB
/
template.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import '@logseq/libs'
import { IBatchBlock, BlockEntity } from '@logseq/libs/dist/LSPlugin.user'
import { RenderingSyntax } from './extensions/customized_eta'
import { ILogseqContext, BlockContext, Context, dayjs, ArgsContext } from './context'
import { RenderError } from './errors'
import { getTemplateTagsContext } from './tags'
import {
p, IBlockNode, walkBlockTree, coerceToBool, LogseqReferenceAccessType,
PropertiesUtils, Properties
} from './utils'
// export enum VariableType {
// string,
// choices,
// queryChoices,
// queryPages,
// queryBlocks,
// queryProperties,
// }
// export class TemplateVariable {
// name: string
// type: VariableType
// options: {[index: string]: string}
// value: string
// // @ts-nocheck
// constructor(
// name: string,
// type = VariableType.string,
// options = {},
// value = "",
// ) {
// this.name = name
// this.type = type
// this.options = options
// this.value = value
// }
// }
export interface ITemplate {
name: string
getArgProperties(): Properties
render(context: ILogseqContext): Promise<IBlockNode>
isEmpty(): boolean
toString(): string
}
export class Template implements ITemplate {
public block: BlockEntity
public name: string
public includingParent: boolean
public accessedVia: LogseqReferenceAccessType
private _initialized: boolean
constructor(
block: BlockEntity, args: {
name?: string,
includingParent?: boolean,
accessedVia: LogseqReferenceAccessType,
}) {
this._initialized = false
this.block = block
this.name = PropertiesUtils.getProperty(
this.block, PropertiesUtils.templateProperty).text || args.name || ''
this.accessedVia = args.accessedVia
if (args.includingParent !== undefined)
this.includingParent = args.includingParent
else {
// 1) template accessed via property (== 'name')
// → it has properties where `template-including-parent` can be placed
// → defaultIncludingParent = false
// 2) same rule is for templates accessed via page (== 'page')
// 3) but when template accessed via non-template block (== 'block')
// → properties may not exist
// → defaultIncludingParent = true
const defaultIncludingParent = this.accessedVia === 'block'
const prop = PropertiesUtils.getProperty(this.block, PropertiesUtils.includingParentProperty)
const value = prop.refs.length ? prop.refs[0] : prop.text
this.includingParent = coerceToBool(
value, {
defaultForEmpty: defaultIncludingParent,
defaultForUncoercible: defaultIncludingParent,
}) as boolean
}
}
async init() {
if (this._initialized)
return
await walkBlockTree(this.block as IBlockNode, async (b) => {
// remove id prop from every block
PropertiesUtils.deleteProperty(b as BlockEntity, PropertiesUtils.idProperty)
// unwrap triple back-ticks block: special case for long templates
const [ start, end ] = [ /^```.*?\n/u, /\n```$/u ]
const matchStart = b.content.match(start)
const matchEnd = b.content.match(end)
if (matchStart && matchEnd)
b.content = b.content.slice(matchStart[0].length, -matchEnd[0].length)
})
if (this.includingParent) {
PropertiesUtils.deleteProperty(this.block, PropertiesUtils.templateProperty)
PropertiesUtils.deleteProperty(this.block, PropertiesUtils.includingParentProperty)
if (this.accessedVia === 'page') {
PropertiesUtils.deleteProperty(this.block, PropertiesUtils.titleProperty)
PropertiesUtils.deleteProperty(this.block, PropertiesUtils.filtersProperty)
}
}
this._initialized = true
}
checkInit() {
if (!this._initialized)
throw Error('Assertion Error: Template instance should be initialized before any use')
}
toString() {
return `Template("${this.name}"${this.includingParent ? " with parent" : ""})`
}
isEmpty(): boolean {
this.checkInit()
const hasChildren = this.block.children && this.block.children.length !== 0
if (!this.includingParent)
return !hasChildren
return !hasChildren && !this.block.content.trim()
}
async render(context: ILogseqContext): Promise<IBlockNode> {
this.checkInit()
console.info(p`Rendering ${this}`)
const blockContext = BlockContext.createFromEntity(this.block)
context.template = new Context({
name: this.name,
includingParent: this.includingParent,
block: blockContext,
props: blockContext.props,
propsRefs: blockContext.propsRefs,
}) as unknown as ILogseqContext['template']
const contextObj = new Context(context)
const renderContext = {
...getTemplateTagsContext(contextObj as unknown as ILogseqContext),
c: contextObj,
}
const renderrer = await RenderingSyntax.autoSelect(this.block as IBlockNode)
return await walkBlockTree(this.block as IBlockNode, async (b, lvl) => {
if (lvl === 0 && !this.includingParent)
return ''
// @ts-expect-error
renderContext.c.self = BlockContext.createFromEntity(
b as BlockEntity, {
page: context.block.page,
level: lvl,
})
return renderrer.renderStringAsync(b.content, renderContext)
})
}
getArgProperties() {
return PropertiesUtils.getProperties(this.block, ArgsContext.propertyPrefix).values
}
}
export class InlineTemplate implements ITemplate {
public name: string = '__inline__'
public body: string
constructor(body: string) {
this.body = body
}
isEmpty(): boolean {
return !this.body
}
toString() {
return `InlineTemplate("${this.body}")`
}
async render(context: ILogseqContext): Promise<IBlockNode> {
console.info(p`Rendering ${this}`)
context.template = new Context({
name: this.name,
includingParent: true,
block: BlockContext.empty(),
props: Context.empty(),
propsRefs: Context.empty(),
}) as unknown as ILogseqContext['template']
const contextObj = new Context({
...context,
self: BlockContext.empty(),
})
const renderContext = {
...getTemplateTagsContext(contextObj as unknown as ILogseqContext),
c: contextObj,
}
const renderrer = RenderingSyntax.latest()
const body = '`` ' + this.body + ' ``'
return {
content: await renderrer.renderStringAsync(body, renderContext),
children: [],
}
}
getArgProperties() {
return {}
}
}