Skip to content

Commit

Permalink
feat: optimize load speed
Browse files Browse the repository at this point in the history
  • Loading branch information
haydenull committed Apr 4, 2022
1 parent dd8f542 commit 70e18e0
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 48 deletions.
25 changes: 12 additions & 13 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type { IScheduleValue } from './components/ModifySchedule'
import dayjs, { Dayjs } from 'dayjs'
import { genSchedule, genScheduleWithCalendarMap, getSchedules, modifyTimeInfo } from './util/schedule'
import { ICustomCalendar, ISettingsForm } from './util/type'
import { moveBlockToNewPage, updateBlock } from './util/logseq'
import { getPageData, moveBlockToNewPage, updateBlock } from './util/logseq'
import { getDefaultCalendarOptions, getInitalSettings } from './util/baseInfo'
import 'tui-calendar/dist/tui-calendar.css'
import './App.css'
Expand Down Expand Up @@ -89,11 +89,11 @@ const App: React.FC<{ env: string }> = ({ env }) => {
const rawData: any = raw
const { id: pageId, originalName } = rawData?.page || {}
let pageName = originalName
// // datascriptQuery 查询出的 block, 没有详细的 page 属性, 需要手动查询
// if (!pageName) {
// const page = await logseq.Editor.getPage(pageId)
// pageName = page?.originalName
// }
// datascriptQuery 查询出的 block, 没有详细的 page 属性, 需要手动查询
if (!pageName) {
const page = await getPageData({ id: pageId })
pageName = page?.originalName
}
const { uuid: blockUuid } = await logseq.Editor.getBlock(rawData.id) || { uuid: '' }
logseq.Editor.scrollToBlockInPage(pageName, blockUuid)
logseq.hideMainUI()
Expand Down Expand Up @@ -126,14 +126,8 @@ const App: React.FC<{ env: string }> = ({ env }) => {
if (calendar) {
calendar.clear()

const debugStart = Date.now()
console.log('=== App debug start ===', debugStart)
const schedules = await getSchedules()
console.log('=== App debug end ===', Date.now() - debugStart)
const debugCalendarStart = Date.now()
console.log('=== App debug calendar start ===', debugStart)
setCalendarSchedules(schedules)
console.log('=== App debug calendar end ===', Date.now() - debugCalendarStart)
calendar.createSchedules(schedules)
const { subscriptionList } = await getInitalSettings()
const subscriptionSchedules = await getSubCalendarSchedules(subscriptionList)
Expand Down Expand Up @@ -349,7 +343,12 @@ const App: React.FC<{ env: string }> = ({ env }) => {
// update journal schedule
const marker = schedule?.raw?.marker
const _content = schedule?.isAllDay ? false : `${marker} ` + modifyTimeInfo(schedule?.raw?.content?.replace(new RegExp(`^${marker} `), ''), dayjs(schedule?.start).format('HH:mm'), dayjs(schedule?.end).format('HH:mm'))
if (changes.start && !dayjs(changes.start).isSame(dayjs(String(schedule?.raw?.page?.journalDay), 'YYYYMMDD'), 'day')) {
let journalDay = schedule?.raw?.page?.journalDay
if (!journalDay) {
const page = await getPageData(schedule?.raw?.page?.id)
journalDay = page?.journalDay
}
if (changes.start && !dayjs(changes.start).isSame(dayjs(String(journalDay), 'YYYYMMDD'), 'day')) {
// if the start day is different from the original start day, then execute move operation
console.log('[faiz:] === move journal schedule')
const { preferredDateFormat } = await logseq.App.getUserConfigs()
Expand Down
3 changes: 2 additions & 1 deletion src/components/CreateCalendarModal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Form, Input, Modal, Radio } from 'antd'
import { getPageData } from '../util/logseq';

const CreateCalendarModal: React.FC<{
visible: boolean
Expand All @@ -8,7 +9,7 @@ const CreateCalendarModal: React.FC<{
const [form] = Form.useForm()

const createAgendaPage = async (name) => {
const page = await logseq.Editor.getPage(name)
const page = await getPageData({ originalName: name })
console.log('[faiz:] === createAgendaPage getPage', page)
if (page) {
logseq.App.showMsg('The page with the same name already exists\nPlease add properties to the page manually\nagenda:: true', 'error')
Expand Down
14 changes: 3 additions & 11 deletions src/components/ModifySchedule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import dayjs, { Dayjs } from 'dayjs'
import { PageEntity } from '@logseq/libs/dist/LSPlugin.user'
import Calendar from 'tui-calendar'
import type { ICustomCalendar, ISettingsForm } from '../util/type'
import { genSchedule, modifyTimeInfo, removeTimeInfo } from '../util/schedule'
import { moveBlockToNewPage, updateBlock } from '../util/logseq'
import { genSchedule, getAgendaCalendars, modifyTimeInfo, removeTimeInfo } from '../util/schedule'
import { getPageData, moveBlockToNewPage, updateBlock } from '../util/logseq'
import { format } from 'date-fns'

export type IScheduleForm = {
Expand Down Expand Up @@ -172,15 +172,7 @@ const ModifySchedule: React.FC<{

useEffect(() => {
const { calendarList } = logseq.settings as unknown as ISettingsForm
const calendarPagePromises = calendarList.map(calendar => logseq.Editor.getPage(calendar.id))
Promise.all(calendarPagePromises).then((pages: (PageEntity | null)[]) => {
const agendaPages = pages
.map((page, index) => {
if (!page) return page
if ((page as any)?.properties?.agenda !== true) return null
return calendarList[index]
})
.filter(function<T>(item: T | null): item is T { return Boolean(item) })
getAgendaCalendars().then(agendaPages => {
// if (agendaPages?.length <= 0) return logseq.App.showMsg('No agenda page found\nYou can create an agenda calendar first', 'warning')
setAgendaCalendars([calendarList[0]].concat(agendaPages))
})
Expand Down
35 changes: 33 additions & 2 deletions src/util/logseq.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const updateBlock = async (blockId: number | string, content: string | fa
}

export const moveBlockToNewPage = async (blockId: number, pageName: string, content?: string | false, properties?: Record<string, any>) => {
const block = await logseq.Editor.getBlock(blockId)
const block = await getBlockData({ id: blockId })
if (!block) return logseq.App.showMsg('moveBlockToNewPage: Block not found', 'error')
const page = await logseq.Editor.createPage(pageName)
if (!page) return logseq.App.showMsg('Create page failed', 'error')
Expand All @@ -23,6 +23,37 @@ export const moveBlockToNewPage = async (blockId: number, pageName: string, cont
sibling: true,
properties: properties || block?.properties,
})
if (newBlock) return await logseq.Editor.getBlock(newBlock.uuid)
if (newBlock) return await getBlockData({ uuid: newBlock.uuid })
return logseq.App.showMsg('Failed to move block to new page')
}

// https://logseq.github.io/plugins/interfaces/IEditorProxy.html#getBlock
const blockDataCacheMap = new Map()
export const getBlockData = async (params: { id?: number; uuid?: string }, useCache = false) => {
const { id, uuid } = params
const key = id || uuid
if (!key) return Promise.reject(new Error('getBlockData: id or uuid is required'))
if (useCache && blockDataCacheMap.has(key)) return blockDataCacheMap.get(key)
const block = await logseq.Editor.getBlock(key)
if (!block) return null
const { id: _id, uuid: _uuid } = block
blockDataCacheMap.set(_id, block)
blockDataCacheMap.set(_uuid, block)
return block
}

// https://logseq.github.io/plugins/interfaces/IEditorProxy.html#getPage
const pageDataCacheMap = new Map()
export const getPageData = async (srcPage: { id?: number; uuid?: string; originalName?: string }, opts?: Partial<{ includeChildren: boolean }>, useCache = false) => {
const { id, uuid, originalName } = srcPage
const key = id || uuid || originalName
if (!key) return Promise.reject(new Error('getPageData: id, uuid or pageOriginalName is required'))
if (useCache && pageDataCacheMap.has(key)) return pageDataCacheMap.get(key)
const page = await logseq.Editor.getPage(key, opts)
if (!page) return null
const { id: _id, uuid: _uuid, originalName: _originName } = page
pageDataCacheMap.set(_id, page)
pageDataCacheMap.set(_uuid, page)
pageDataCacheMap.set(_originName, page)
return page
}
72 changes: 51 additions & 21 deletions src/util/schedule.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { ISchedule } from 'tui-calendar'
import { flattenDeep, get } from 'lodash'
import { flattenDeep, get, has } from 'lodash'
import { endOfDay, formatISO, isAfter, parse, parseISO, startOfDay } from 'date-fns'
import dayjs from 'dayjs'
import { getInitalSettings } from './baseInfo'
import { ICategory, IQueryWithCalendar, ISettingsForm } from './type'
import { DEFAULT_BLOCK_DEADLINE_DATE_FORMAT, DEFAULT_JOURNAL_FORMAT, DEFAULT_SETTINGS, TIME_REG } from './constants'
import { getBlockData, getPageData } from './logseq'
import { PageEntity } from '@logseq/libs/dist/LSPlugin'

export const getSchedules = async () => {
const agendaCalendars = await getAgendaCalendars()
const agendaCalendarIds = agendaCalendars.map(calendar => calendar.id)

// console.log('[faiz:] === getSchedules start ===', logseq.settings, getInitalSettings())
let calendarSchedules:ISchedule[] = []

Expand Down Expand Up @@ -90,21 +95,19 @@ export const getSchedules = async () => {
calendarConfig,
defaultDuration,
isAllDay: !isMilestone && !hasTime && !_isOverdue,
isReadOnly: !supportEdit(block, calendarConfig.id, agendaCalendarIds),
})
// show overdue tasks in today
return _isOverdue
? [
schedule,
await genSchedule({
{
...schedule,
id: `overdue-${schedule.id}`,
start: dayjs().startOf('day').toISOString(),
end: dayjs().endOf('day').toISOString(),
blockData: block,
category: _category,
calendarConfig,
defaultDuration,
isAllDay: false,
}),
},
]
: schedule
})
Expand Down Expand Up @@ -215,7 +218,7 @@ export const fillBlockReference = async (blockContent: string) => {
if (BLOCK_REFERENCE_REG.test(blockContent)) {
const uuid = BLOCK_REFERENCE_REG.exec(blockContent)?.[0]?.replace('((', '')?.replace('))', '')
if (uuid) {
const referenceData = await logseq.Editor.getBlock(uuid)
const referenceData = await getBlockData({ uuid }, true)
return blockContent.replace(BLOCK_REFERENCE_REG, referenceData?.content || '')
}
}
Expand All @@ -237,31 +240,42 @@ export async function genSchedule(params: {

const { id, blockData, category = 'time', start, end, calendarConfig, isAllDay, defaultDuration, isReadOnly } = params
const debugStartTime = Date.now()
console.log('[faiz:debug] === debug start', debugStartTime)
if (!blockData?.id) {
// 单个耗时在5-7秒,整体耗时8秒
const block = await logseq.Editor.getBlock(blockData.uuid?.$uuid$)
const block = await getBlockData({ uuid: blockData.uuid?.$uuid$ }, true)
if (block) blockData.id = block.id
}
console.log('[faiz:debug] === debug end', Date.now() - debugStartTime)

// 耗时1s左右
const page = await logseq.Editor.getPage(blockData?.page?.id)
let page = blockData?.page
if (has(page, 'id') && has(page, 'name') && has(page, 'original-name')) {
page = {
id: page.id,
journalDay: page['journal-day'],
journal: page['journal?'],
name: page['name'],
originalName: page['original-name'],
}
}
// else {
// // 耗时1s左右
// page = await getPageData({ id: blockData?.page?.id })
// }
blockData.page = page

let title = blockData.content
// 单个耗时在5-7秒,整体耗时11秒
blockData.fullContent = await fillBlockReference(blockData.content)
blockData.fullContent = blockData.content

const title = blockData.fullContent
.split('\n')[0]
?.replace(new RegExp(`^${blockData.marker} `), '')
?.replace(TIME_REG, '')
?.trim?.()
// 单个耗时在5-7秒,整体耗时11秒
// title = await fillBlockReference(title)
title = title?.split('\n')[0]
const isDone = blockData.marker === 'DONE'

function supportEdit() {
if (blockData.page?.properties?.agenda === true) return true
if (blockData?.page?.journalDay && !blockData?.scheduled && !blockData?.deadline) return true
if (blockData?.page?.['journal-day'] && !blockData?.scheduled && !blockData?.deadline) return true
return false
}
const isSupportEdit = isReadOnly === undefined ? supportEdit() : !isReadOnly
Expand All @@ -278,9 +292,7 @@ export async function genSchedule(params: {
id: id || String(blockData.id),
calendarId: calendarConfig.id,
title: isDone ? `✅${title}` : title,
// 耗时11s左右
// body: await fillBlockReference(blockData.content),
body: blockData.content,
body: blockData.fullContent,
category,
dueDateClass: '',
start,
Expand All @@ -307,4 +319,22 @@ export const genScheduleWithCalendarMap = (schedules: ISchedule[]) => {
res.get(key)?.push(schedule)
})
return res
}

export const getAgendaCalendars = async () => {
const { calendarList } = logseq.settings as unknown as ISettingsForm
const calendarPagePromises = calendarList.map(calendar => getPageData({ originalName: calendar.id }))
const res = await Promise.all(calendarPagePromises)
return res.map((page, index) => {
if (!page) return null
if ((page as any)?.properties?.agenda !== true) return null
return calendarList[index]
})
.filter(function<T>(item: T | null): item is T { return Boolean(item) })
}

export const supportEdit = (blockData, calendarId, agendaCalendarIds) => {
if (agendaCalendarIds.includes(calendarId)) return true
if (blockData?.page?.['journal-day'] && !blockData?.scheduled && !blockData?.deadline) return true
return false
}

0 comments on commit 70e18e0

Please sign in to comment.