Skip to content

Commit

Permalink
fix(tags): when template tag & add docs
Browse files Browse the repository at this point in the history
  • Loading branch information
stdword committed Feb 17, 2024
1 parent 5a72905 commit 3b83f1d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
30 changes: 28 additions & 2 deletions docs/reference__tags.md
Expand Up @@ -139,8 +139,6 @@ empty array
<!-- tabs:end -->


### `when TODO` :id=when
TODO

### `bool` :id=bool
Checks whether the string is `true`, `false` or non-boolean.
Expand Down Expand Up @@ -170,6 +168,34 @@ null
<!-- tabs:end -->



### `when` :id=when
If the object is empty (in JavaScript way) return `fallback`, otherwise return `result` (which can be based on object value).

`when(obj, result, fallback = '')`
- `obj`: value to check the emptyness
- `result`: value for non-empty case
- Can contain `$1`, `${}`, `${_}`: these values will be replaces with object itself
- `fallback`: value for empty case (default: `''`)

<!-- tabs:start -->
#### ***Template***
This is ` ``when(c.page.day, 'journal page for $1 day', 'page')`` ` \
Root namespace: ` ``when(c.page.name.split('/').at(0), '$1')`` `

#### ***Rendered***
*In journal page:*
This is journal page for 2023-08-12 Sat
Root namespace: 2023-08-12 Sat

*In logseq/plugins page:*
This is journal page
Root namespace: logseq

<!-- tabs:end -->



### `fill TODO` :id=fill
TODO

Expand Down
14 changes: 7 additions & 7 deletions src/tags.ts
Expand Up @@ -246,27 +246,27 @@ function empty(obj: any, fallback: any = '') {

return obj
}
function when(obj: any, result: string | any, fallback: string | any = ''): string {
function bool(value: string, fallback: any = '') {
if (typeof value !== 'string')
return fallback
return coerceStringToBool(value) ?? fallback
}
function when(obj: any, result: any, fallback: any = '') {
const condition = !!obj

if (condition) {
if (typeof result !== 'string')
return _asString(result)
return result

const strObj = _asString(obj)
return _asString(result)
return result
.replaceAll('${_}', strObj)
.replaceAll('${}', strObj)
.replaceAll('$1', strObj)
}

return _asString(fallback)
}
return fallback
}
function fill(
value: string | number,
char: string,
Expand Down Expand Up @@ -533,7 +533,7 @@ export function getTemplateTagsContext(context: ILogseqContext) {

return new Context({
ref, bref, tag, embed,
empty, when, fill, zeros, spaces,
empty, bool, when, fill, zeros, spaces,

yesterday: datesContext.yesterday,
today: datesContext.today,
Expand Down Expand Up @@ -570,5 +570,5 @@ export function getTemplateTagsContext(context: ILogseqContext) {
}

export const _private = {
ref, tag, embed, empty, when, fill, zeros, spaces,
ref, tag, embed, empty, bool, when, fill, zeros, spaces,
}

0 comments on commit 3b83f1d

Please sign in to comment.