Skip to content

Commit c596d89

Browse files
committed
feat: adds Fallbacks when query finds to suitable blocks
This change also fixes error linting
1 parent b450c42 commit c596d89

File tree

1 file changed

+151
-126
lines changed

1 file changed

+151
-126
lines changed

index.ts

Lines changed: 151 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,41 @@
11
import '@logseq/libs';
2-
import SettingSchemaDesc from '@logseq/libs/dist/LSPlugin.user';
3-
// import axios from "axios";
2+
import { BlockEntity, BlockIdentity, SettingSchemaDesc } from "@logseq/libs/dist/LSPlugin.user"
43

5-
const pluginName = ["logseq-interstitial", "Logseq Interstitial"]
4+
const pluginName = ["logseq-interstitial", "Logseq Interstitial"]
65
const markupChoices = ["markdown", "orgmode"]
76
const markupHeadMrk = ["#", "*"]
87
const markupTimeMrk = ["**", "*"]
9-
const settingsTemplate:SettingSchemaDesc[] = [{
10-
key: "defaultTitle",
11-
type: 'boolean',
12-
default: false,
13-
title: "Insert Header by default?",
14-
description: "If true, \"<mod> t\" will insert a header, otherwise only the (bold) timestamp.",
15-
},
16-
{
17-
key: "boldText",
18-
type: 'boolean',
19-
default: true,
20-
title: "Create a bold timestamp? (If not a header)",
21-
description: "Insert a bold timestamp. Not for header or custom text.",
22-
},
23-
{
24-
key: "markup",
25-
type: 'enum',
26-
enumChoices: markupChoices,
27-
enumPicker: 'radio',
28-
default: markupChoices[0],
29-
title: "What markup language to use?",
30-
description: "Markdown or Org-mode.",
31-
},
32-
{
33-
key: "level",
34-
type: 'number',
35-
default: 3,
36-
title: "Title level?",
37-
description: "Insert timestamped heading level, default to 3 (### HH:MM title)",
38-
},
39-
{
8+
const settingsTemplate: SettingSchemaDesc[] = [{
9+
key: "defaultTitle",
10+
type: 'boolean',
11+
default: false,
12+
title: "Insert Header by default?",
13+
description: "If true, \"<mod> t\" will insert a header, otherwise only the (bold) timestamp.",
14+
},
15+
{
16+
key: "boldText",
17+
type: 'boolean',
18+
default: true,
19+
title: "Create a bold timestamp? (If not a header)",
20+
description: "Insert a bold timestamp. Not for header or custom text.",
21+
},
22+
{
23+
key: "markup",
24+
type: 'enum',
25+
enumChoices: markupChoices,
26+
enumPicker: 'radio',
27+
default: markupChoices[0],
28+
title: "What markup language to use?",
29+
description: "Markdown or Org-mode.",
30+
},
31+
{
32+
key: "level",
33+
type: 'number',
34+
default: 3,
35+
title: "Title level?",
36+
description: "Insert timestamped heading level, default to 3 (### HH:MM title)",
37+
},
38+
{
4039
key: "cstTime",
4140
type: 'string',
4241
default: "",
@@ -57,39 +56,41 @@ const settingsTemplate:SettingSchemaDesc[] = [{
5756
description: "Enter your desired keyboard shortcut for the command",
5857
default: "mod+t"
5958
},
60-
{
59+
{
6160
key: "KeyboardShortcut_h",
6261
type: "string",
6362
title: "Keyboard Shortcut 2",
6463
description: "Enter your desired keyboard shortcut for the command",
6564
default: "mod+shift+t"
6665
}
6766
]
68-
async function updateBlock(block,insertHeader) {
69-
// true = header - false = timestamp
67+
async function updateBlock(block: BlockEntity, insertHeader: boolean) {
68+
if (!logseq?.settings) {
69+
throw new Error("logseq.settings is not defined!");
70+
}
7071
//prefixB
71-
let prefix = markupHeadMrk[markupChoices.indexOf(logseq.settings.markup)].repeat(logseq.settings.level)
72+
let prefix = markupHeadMrk[markupChoices.indexOf(logseq.settings.markup)].repeat(logseq.settings.level)
7273
const prefixB = (insertHeader) ? prefix : ""
7374

7475
//timeB
7576
const today = new Date();
76-
const time = String(today.getHours()).padStart((logseq.settings.padHour) ? 2 : 1, '0') +
77-
":" +
78-
String(today.getMinutes()).padStart(2, '0')
77+
const time = String(today.getHours()).padStart((logseq.settings.padHour) ? 2 : 1, '0') +
78+
":" +
79+
String(today.getMinutes()).padStart(2, '0')
7980
// Don't bold time if header of if logseq.settings.boldText=false
80-
const timePrefix = (insertHeader || ! logseq.settings.boldText) ? "" : markupTimeMrk[markupChoices.indexOf(logseq.settings.markup)]
81-
const timeHolder = (logseq.settings.cstTime)
82-
? logseq.settings.cstTime
83-
: timePrefix + "<time>" + timePrefix
81+
const timePrefix = (insertHeader || !logseq.settings.boldText) ? "" : markupTimeMrk[markupChoices.indexOf(logseq.settings.markup)]
82+
const timeHolder = (logseq.settings.cstTime)
83+
? logseq.settings.cstTime
84+
: timePrefix + "<time>" + timePrefix
8485
const reTime = new RegExp("<time>")
8586
const timeB = timeHolder.replace(reTime, time)
8687

8788
//contentB
88-
prefix = prefix.replace(/\*/g,"\\*") //fix regex
89-
const re = new RegExp(`^${(prefix === "*" ) ? "\*" : prefix}{1,6}\s+`)
89+
prefix = prefix.replace(/\*/g, "\\*") //fix regex
90+
const re = new RegExp(`^${(prefix === "*") ? "\*" : prefix}{1,6}\s+`)
9091
let contentB = re.test(block.content)
91-
? block.content.replace(re, '')
92-
: block.content;
92+
? block.content.replace(re, '')
93+
: block.content;
9394

9495
// const mdHeader = "#".repeat(logseq.settings.level)
9596

@@ -101,82 +102,86 @@ async function updateBlock(block,insertHeader) {
101102
// const timePrefix = (logseq.settings.markup) ? markupTimeMrk[logseq.settings.markup] : false
102103
// let timestamp = (logseq.settings.defaultTitle) ? " <time> " : timePrefix + "<time>" + timePrefix + " "
103104
// const re2 =
104-
105+
105106
// let prefix = simple ? linePrefix.repeat(logseq.settings.level) : ''
106107

107108
await logseq.Editor.updateBlock(
108-
block.uuid,
109-
`${prefixB} ${timeB} ${contentB} `
110-
);
109+
block.uuid,
110+
`${prefixB} ${timeB} ${contentB} `
111+
);
111112
}
112113

113-
async function insertInterstitional(simple) {
114+
async function insertInterstitional(simple: boolean) {
114115
// true = header - false = timestamp
115116
const selected = await logseq.Editor.getSelectedBlocks();
116117
if (selected && selected.length > 1) {
117118
for (let block of selected) {
118-
updateBlock(block, simple)
119-
}
119+
updateBlock(block, simple)
120+
}
120121
} else {
121122
const block = await logseq.Editor.getCurrentBlock();
122123
if (block?.uuid) {
123-
updateBlock(block, simple)
124+
updateBlock(block, simple)
124125
}
125126
}
126127
}
127128

128129
function journalDate() {
129130
//hardcoded yesterday
130-
let date = (function(d){ d.setDate(d.getDate()-1); return d})(new Date)
131-
return parseInt(`${date.getFullYear()}${("0" + (date.getMonth()+1)).slice(-2)}${("0" + date.getDate()).slice(-2)}`,10)
131+
let date = (function(d) { d.setDate(d.getDate() - 1); return d })(new Date)
132+
return parseInt(`${date.getFullYear()}${("0" + (date.getMonth() + 1)).slice(-2)}${("0" + date.getDate()).slice(-2)}`, 10)
132133
}
133134

134-
async function parseQuery(randomQuery,queryTag){
135-
// https://stackoverflow.com/questions/19156148/i-want-to-remove-double-quotes-from-a-string
135+
async function parseQuery(randomQuery: string, queryTag: string) {
136136
let query = `[:find (pull ?b [*])
137137
:where
138138
[?b :block/path-refs [:block/name "${queryTag.toLowerCase().trim().replace(/^["'](.+(?=["']$))["']$/, '$1')}"]]]`
139-
if ( randomQuery == "yesterday" ) {
139+
if (randomQuery == "yesterday") {
140140
query = `[:find (pull ?b [*])
141141
:where
142142
[?b :block/path-refs [:block/name "${queryTag.toLowerCase().trim().replace(/^["'](.+(?=["']$))["']$/, '$1')}"]]
143143
[?b :block/page ?p]
144144
[?p :block/journal? true]
145145
[?p :block/journal-day ${journalDate()}]]`
146146
}
147-
try {
148-
let results = await logseq.DB.datascriptQuery(query)
149-
//Let this be, it won't hurt even if there's only one hit
150-
let flattenedResults = results.map((mappedQuery) => ({
147+
try {
148+
let results = await logseq.DB.datascriptQuery(query)
149+
if (results.length === 0) {
150+
return 'no_message'
151+
}
152+
let flattenedResults = results.map((mappedQuery: any) => ({
151153
uuid: mappedQuery[0].uuid,
152154
}))
153-
let index = Math.floor(Math.random()*flattenedResults.length)
154-
const origBlock = await logseq.Editor.getBlock(flattenedResults[index].uuid, {
155-
includeChildren: true,
156-
});
157-
// return `((${flattenedResults[index].uuid}))`
155+
let index = Math.floor(Math.random() * flattenedResults.length)
156+
158157
return flattenedResults[index].uuid
159-
} catch (error) {return false}
158+
} catch (error) { return false }
160159
}
161160

162-
async function onTemplate(uuid){
161+
async function onTemplate(uuid: number | BlockIdentity) {
163162
//is block(uuid) on a template?
164163
//returns boolean
165164
try {
166-
const block = await logseq.Editor.getBlock(uuid, {includeChildren: false})
167-
const checkTPL = (block.properties && block.properties.template != undefined) ? true : false
168-
const checkPRT = (block.parent != null && block.parent.id !== block.page.id) ? true : false
165+
const block = await logseq.Editor.getBlock(uuid, { includeChildren: false })
166+
if (block === null) {
167+
throw new Error("No block found!");
168+
}
169+
const checkTPL = (block.properties?.template != undefined) ? true : false
170+
const checkPRT = (block.parent != null && block.parent.id !== block.page.id) ? true : false
169171

170172
if (checkTPL === false && checkPRT === false) return false
171-
if (checkTPL === true ) return true
172-
return await onTemplate(block.parent.id)
173+
if (checkTPL === true) return true
174+
return await onTemplate(block.parent.id)
173175

174176
} catch (error) { console.log(error) }
175177
}
176178

177179
const main = async () => {
178180
console.log(`Plugin: ${pluginName[1]} loaded`)
179181
logseq.useSettingsSchema(settingsTemplate)
182+
if (!logseq?.settings) {
183+
throw new Error("logseq.settings is not defined!");
184+
}
180185

181186
logseq.Editor.registerSlashCommand('Interstitial: Create Random Quote', async () => {
182187
await logseq.Editor.insertAtEditingCursor(`{{renderer :interstitial, random, quote}} `);
@@ -188,78 +193,98 @@ const main = async () => {
188193

189194
logseq.App.onMacroRendererSlotted(async ({ slot, payload }) => {
190195
try {
191-
var [type, randomQ , tagQ ] = payload.arguments
196+
var [type, randomQ, tagQ] = payload.arguments
192197
if (type !== ':interstitial') return
193198

194199
//is the block on a template?
195-
const templYN = await onTemplate(payload.uuid)
196-
const uuid = await parseQuery( randomQ, tagQ)
200+
const templYN = await onTemplate(payload.uuid)
201+
const uuid = await parseQuery(randomQ, tagQ)
197202
// parseQuery returns false if no uuid can be found
198203
const msg = uuid ? `<span style="color: green">{{renderer ${payload.arguments} }}</span> (will run with template)` : `<span style="color: red">{{renderer ${payload.arguments} }}</span> (wrong tag?)`
199204

200-
if (templYN === true || uuid === false) {
201-
await logseq.provideUI({
205+
if (templYN === true || uuid === false) {
206+
logseq.provideUI({
202207
key: "interstitial",
203208
slot,
204209
template: `${msg}`,
205210
reset: true,
206211
style: { flex: 1 },
207212
})
208-
return
213+
return
209214
}
210-
else {
215+
else {
211216
const nblock = await logseq.Editor.getBlock(uuid);
212-
if (!nblock.properties?.id) { logseq.Editor.upsertBlockProperty(nblock.uuid, "id", nblock.uuid); }
213-
await logseq.Editor.updateBlock(payload.uuid, `((${uuid}))`)
214-
}
217+
218+
if (nblock === null) {
219+
let content: string
220+
switch (tagQ) {
221+
case "ntnds":
222+
content = "You had nothing to say"
223+
break;
224+
case "quote":
225+
const response = await fetch('https://zenquotes.io/api/today');
226+
const quote = await response.json();
227+
content = quote["h"];
228+
break;
229+
default:
230+
content = "Nothing Found"
231+
break;
232+
}
233+
await logseq.Editor.updateBlock(payload.uuid, content)
234+
} else {
235+
logseq.Editor.upsertBlockProperty(nblock.uuid, "id", nblock.uuid);
236+
await logseq.Editor.updateBlock(payload.uuid, `((${uuid}))`)
237+
}
238+
}
215239
} catch (error) { console.log(error) }
216240
})
217241

218242
const registerKeyTitle = () => logseq.App.registerCommandPalette(
219-
{
220-
key: `interstial-time-stamp_l`,
221-
label: `Insert interstitial line`,
222-
keybinding: {
223-
mode: 'global',
224-
binding: logseq.settings.KeyboardShortcut_l.toLowerCase()
225-
},
243+
{
244+
key: `interstial-time-stamp_l`,
245+
label: `Insert interstitial line`,
246+
keybinding: {
247+
mode: 'global',
248+
binding: logseq.settings?.KeyboardShortcut_l.toLowerCase()
226249
},
227-
async () => {
228-
// true = header - false = timestamp
229-
await insertInterstitional(logseq.settings.defaultTitle ? true : false);
230-
}
231-
);
250+
},
251+
async () => {
252+
// true = header - false = timestamp
253+
await insertInterstitional(logseq.settings?.defaultTitle ? true : false);
254+
}
255+
);
232256

233-
const registerKeyHeading = () => logseq.App.registerCommandPalette(
234-
{
235-
key: `interstial-time-stamp_h`,
236-
label: `Insert interstitial heading`,
237-
keybinding: {
238-
mode: 'global',
239-
binding: logseq.settings.KeyboardShortcut_h.toLowerCase()
240-
},
257+
const registerKeyHeading = () => logseq.App.registerCommandPalette(
258+
{
259+
key: `interstial-time-stamp_h`,
260+
label: `Insert interstitial heading`,
261+
keybinding: {
262+
mode: 'global',
263+
binding: logseq.settings?.KeyboardShortcut_h.toLowerCase()
241264
},
242-
async () => {
243-
// true = header - false = timestamp
244-
await insertInterstitional(logseq.settings.defaultTitle ? false : true);
245-
}
246-
);
247-
248-
function unreg(setKey) {
249-
//unregister keybindings
250-
const re:RegExp=/^KeyboardShortcut(.*)/
251-
if (re.test(setKey.key)) {
252-
const key=re.exec(setKey.key)
253-
// console.log("DB2", `interstial-time-stamp${key[1]}`)
254-
logseq.App.unregister_plugin_simple_command(`${logseq.baseInfo.id}/interstial-time-stamp${key[1]}`)
265+
},
266+
async () => {
267+
// true = header - false = timestamp
268+
await insertInterstitional(logseq.settings?.defaultTitle ? false : true);
269+
}
270+
);
271+
272+
function unreg(setKey: SettingSchemaDesc ) {
273+
//unregister keybindings
274+
const re: RegExp = /^KeyboardShortcut(.*)/
275+
if (re.test(setKey.key)) {
276+
const key = re.exec(setKey.key)
277+
if (key !== null) {
278+
logseq.App.unregister_plugin_simple_command(`${logseq.baseInfo.id}/interstial-time-stamp${key[1]}`)
255279
}
256280
}
281+
}
257282

258-
logseq.onSettingsChanged((_updated) => {
259-
settingsTemplate.forEach((x, i) => unreg(x))
260-
registerKeyHeading()
261-
registerKeyTitle()
262-
});
283+
logseq.onSettingsChanged((_updated) => {
284+
settingsTemplate.forEach((x, _) => unreg(x))
285+
registerKeyHeading()
286+
registerKeyTitle()
287+
});
263288
}
264289

265290
logseq.ready(main).catch(console.error);

0 commit comments

Comments
 (0)