LSPlugin.core.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. import EventEmitter from 'eventemitter3'
  2. import {
  3. deepMerge,
  4. setupInjectedStyle,
  5. genID,
  6. setupInjectedUI,
  7. deferred,
  8. invokeHostExportedApi,
  9. isObject,
  10. withFileProtocol,
  11. getSDKPathRoot,
  12. PROTOCOL_FILE,
  13. URL_LSP,
  14. safetyPathJoin,
  15. path,
  16. safetyPathNormalize,
  17. mergeSettingsWithSchema,
  18. IS_DEV,
  19. cleanInjectedScripts,
  20. safeSnakeCase,
  21. injectTheme,
  22. cleanInjectedUI,
  23. } from './helpers'
  24. import * as pluginHelpers from './helpers'
  25. import Debug from 'debug'
  26. import {
  27. LSPluginCaller,
  28. LSPMSG_READY,
  29. LSPMSG_SYNC,
  30. LSPMSG,
  31. LSPMSG_SETTINGS,
  32. LSPMSG_ERROR_TAG,
  33. LSPMSG_BEFORE_UNLOAD,
  34. AWAIT_LSPMSGFn,
  35. } from './LSPlugin.caller'
  36. import {
  37. ILSPluginThemeManager,
  38. LegacyTheme,
  39. LSPluginPkgConfig,
  40. SettingSchemaDesc,
  41. StyleOptions,
  42. StyleString,
  43. Theme,
  44. ThemeMode,
  45. UIContainerAttrs,
  46. UIOptions,
  47. } from './LSPlugin'
  48. const debug = Debug('LSPlugin:core')
  49. const DIR_PLUGINS = 'plugins'
  50. declare global {
  51. interface Window {
  52. LSPluginCore: LSPluginCore
  53. }
  54. }
  55. type DeferredActor = ReturnType<typeof deferred>
  56. interface LSPluginCoreOptions {
  57. dotConfigRoot: string
  58. }
  59. /**
  60. * User settings
  61. */
  62. class PluginSettings extends EventEmitter<'change' | 'reset'> {
  63. private _settings: Record<string, any> = {
  64. disabled: false,
  65. }
  66. constructor(
  67. private readonly _userPluginSettings: any,
  68. private _schema?: SettingSchemaDesc[]
  69. ) {
  70. super()
  71. Object.assign(this._settings, _userPluginSettings)
  72. }
  73. get<T = any>(k: string): T {
  74. return this._settings[k]
  75. }
  76. set(k: string | Record<string, any>, v?: any) {
  77. const o = deepMerge({}, this._settings)
  78. if (typeof k === 'string') {
  79. if (this._settings[k] == v) return
  80. this._settings[k] = v
  81. } else if (isObject(k)) {
  82. deepMerge(this._settings, k)
  83. } else {
  84. return
  85. }
  86. this.emit('change', Object.assign({}, this._settings), o)
  87. }
  88. set settings(value: Record<string, any>) {
  89. this._settings = value
  90. }
  91. get settings(): Record<string, any> {
  92. return this._settings
  93. }
  94. setSchema(schema: SettingSchemaDesc[], syncSettings?: boolean) {
  95. this._schema = schema
  96. if (syncSettings) {
  97. const _settings = this._settings
  98. this._settings = mergeSettingsWithSchema(_settings, schema)
  99. this.emit('change', this._settings, _settings)
  100. }
  101. }
  102. reset() {
  103. const o = this.settings
  104. const val = {}
  105. if (this._schema) {
  106. // TODO: generated by schema
  107. }
  108. this.settings = val
  109. this.emit('reset', val, o)
  110. }
  111. toJSON() {
  112. return this._settings
  113. }
  114. }
  115. class PluginLogger extends EventEmitter<'change'> {
  116. private _logs: Array<[type: string, payload: any]> = []
  117. constructor(private readonly _tag: string) {
  118. super()
  119. }
  120. write(type: string, payload: any[], inConsole?: boolean) {
  121. if (payload?.length && (true === payload[payload.length - 1])) {
  122. inConsole = true
  123. payload.pop()
  124. }
  125. const msg = payload.reduce((ac, it) => {
  126. if (it && it instanceof Error) {
  127. ac += `${it.message} ${it.stack}`
  128. } else {
  129. ac += it.toString()
  130. }
  131. return ac
  132. }, `[${this._tag}][${new Date().toLocaleTimeString()}] `)
  133. this._logs.push([type, msg])
  134. if (inConsole) {
  135. console?.['ERROR' === type ? 'error' : 'debug'](`${type}: ${msg}`)
  136. }
  137. this.emit('change')
  138. }
  139. clear() {
  140. this._logs = []
  141. this.emit('change')
  142. }
  143. info(...args: any[]) {
  144. this.write('INFO', args)
  145. }
  146. error(...args: any[]) {
  147. this.write('ERROR', args)
  148. }
  149. warn(...args: any[]) {
  150. this.write('WARN', args)
  151. }
  152. toJSON() {
  153. return this._logs
  154. }
  155. }
  156. interface UserPreferences {
  157. theme: LegacyTheme
  158. themes: {
  159. mode: ThemeMode
  160. light: Theme
  161. dark: Theme
  162. }
  163. externals: string[] // external plugin locations
  164. }
  165. interface PluginLocalOptions {
  166. key?: string // Unique from Logseq Plugin Store
  167. entry: string // Plugin main file
  168. url: string // Plugin package absolute fs location
  169. name: string
  170. version: string
  171. mode: 'shadow' | 'iframe'
  172. settingsSchema?: SettingSchemaDesc[]
  173. settings?: PluginSettings
  174. logger?: PluginLogger
  175. effect?: boolean
  176. theme?: boolean
  177. [key: string]: any
  178. }
  179. interface PluginLocalSDKMetadata {
  180. version: string
  181. [key: string]: any
  182. }
  183. type PluginLocalUrl = Pick<PluginLocalOptions, 'url'> & { [key: string]: any }
  184. type RegisterPluginOpts = PluginLocalOptions | PluginLocalUrl
  185. type PluginLocalIdentity = string
  186. enum PluginLocalLoadStatus {
  187. LOADING = 'loading',
  188. UNLOADING = 'unloading',
  189. LOADED = 'loaded',
  190. UNLOADED = 'unload',
  191. ERROR = 'error',
  192. }
  193. function initUserSettingsHandlers(pluginLocal: PluginLocal) {
  194. const _ = (label: string): any => `settings:${label}`
  195. // settings:schema
  196. pluginLocal.on(
  197. _('schema'),
  198. ({ schema, isSync }: { schema: SettingSchemaDesc[]; isSync?: boolean }) => {
  199. pluginLocal.settingsSchema = schema
  200. pluginLocal.settings?.setSchema(schema, isSync)
  201. }
  202. )
  203. // settings:update
  204. pluginLocal.on(_('update'), (attrs) => {
  205. if (!attrs) return
  206. pluginLocal.settings?.set(attrs)
  207. })
  208. // settings:visible:changed
  209. pluginLocal.on(_('visible:changed'), (payload) => {
  210. const visible = payload?.visible
  211. invokeHostExportedApi(
  212. 'set_focused_settings',
  213. visible ? pluginLocal.id : null
  214. )
  215. })
  216. }
  217. function initMainUIHandlers(pluginLocal: PluginLocal) {
  218. const _ = (label: string): any => `main-ui:${label}`
  219. // main-ui:visible
  220. pluginLocal.on(_('visible'), ({ visible, toggle, cursor, autoFocus }) => {
  221. const el = pluginLocal.getMainUIContainer()
  222. el?.classList[toggle ? 'toggle' : visible ? 'add' : 'remove']('visible')
  223. // pluginLocal.caller!.callUserModel(LSPMSG, { type: _('visible'), payload: visible })
  224. // auto focus frame
  225. if (visible) {
  226. if (!pluginLocal.shadow && el && autoFocus !== false) {
  227. el.querySelector('iframe')?.contentWindow?.focus()
  228. }
  229. } else {
  230. // @ts-expect-error set activeElement back to `body`
  231. el.ownerDocument.activeElement.blur()
  232. }
  233. if (cursor) {
  234. invokeHostExportedApi('restore_editing_cursor')
  235. }
  236. })
  237. // main-ui:attrs
  238. pluginLocal.on(_('attrs'), (attrs: Partial<UIContainerAttrs>) => {
  239. const el = pluginLocal.getMainUIContainer()
  240. Object.entries(attrs).forEach(([k, v]) => {
  241. el?.setAttribute(k, v)
  242. if (k === 'draggable' && v) {
  243. pluginLocal._dispose(
  244. pluginLocal._setupDraggableContainer(el, {
  245. title: pluginLocal.options.name,
  246. close: () => {
  247. pluginLocal.caller.call('sys:ui:visible', { toggle: true })
  248. },
  249. })
  250. )
  251. }
  252. if (k === 'resizable' && v) {
  253. pluginLocal._dispose(pluginLocal._setupResizableContainer(el))
  254. }
  255. })
  256. })
  257. // main-ui:style
  258. pluginLocal.on(_('style'), (style: Record<string, any>) => {
  259. const el = pluginLocal.getMainUIContainer()
  260. const isInitedLayout = !!el.dataset.inited_layout
  261. Object.entries(style).forEach(([k, v]) => {
  262. if (
  263. isInitedLayout &&
  264. ['left', 'top', 'bottom', 'right', 'width', 'height'].includes(k)
  265. ) {
  266. return
  267. }
  268. el.style[k] = v
  269. })
  270. })
  271. }
  272. function initProviderHandlers(pluginLocal: PluginLocal) {
  273. const _ = (label: string): any => `provider:${label}`
  274. let themed = false
  275. // provider:theme
  276. pluginLocal.on(_('theme'), (theme: Theme) => {
  277. pluginLocal.themeMgr.registerTheme(pluginLocal.id, theme)
  278. if (!themed) {
  279. pluginLocal._dispose(() => {
  280. pluginLocal.themeMgr.unregisterTheme(pluginLocal.id)
  281. })
  282. themed = true
  283. }
  284. })
  285. // provider:style
  286. pluginLocal.on(_('style'), (style: StyleString | StyleOptions) => {
  287. let key: string | undefined
  288. if (typeof style !== 'string') {
  289. key = style.key
  290. style = style.style
  291. }
  292. if (!style || !style.trim()) return
  293. pluginLocal._dispose(
  294. setupInjectedStyle(style, {
  295. 'data-injected-style': key ? `${key}-${pluginLocal.id}` : '',
  296. 'data-ref': pluginLocal.id,
  297. })
  298. )
  299. })
  300. // provider:ui
  301. pluginLocal.on(_('ui'), (ui: UIOptions) => {
  302. pluginLocal._onHostMounted(() => {
  303. pluginLocal._dispose(
  304. setupInjectedUI.call(
  305. pluginLocal,
  306. ui,
  307. Object.assign(
  308. {
  309. 'data-ref': pluginLocal.id,
  310. },
  311. ui.attrs || {}
  312. ),
  313. ({ el, float }) => {
  314. if (!float) return
  315. const identity = el.dataset.identity
  316. pluginLocal.layoutCore.move_container_to_top(identity)
  317. }
  318. )
  319. )
  320. })
  321. })
  322. }
  323. function initApiProxyHandlers(pluginLocal: PluginLocal) {
  324. const _ = (label: string): any => `api:${label}`
  325. pluginLocal.on(_('call'), async (payload) => {
  326. let ret: any
  327. try {
  328. ret = await invokeHostExportedApi.apply(pluginLocal, [
  329. payload.method,
  330. ...payload.args,
  331. ])
  332. } catch (e) {
  333. ret = {
  334. [LSPMSG_ERROR_TAG]: e,
  335. }
  336. }
  337. const { _sync } = payload
  338. if (pluginLocal.shadow) {
  339. if (payload.actor) {
  340. payload.actor.resolve(ret)
  341. }
  342. return
  343. }
  344. if (_sync != null) {
  345. const reply = (result: any) => {
  346. pluginLocal.caller?.callUserModel(LSPMSG_SYNC, {
  347. result,
  348. _sync,
  349. })
  350. }
  351. Promise.resolve(ret).then(reply, reply)
  352. }
  353. })
  354. }
  355. function convertToLSPResource(fullUrl: string, dotPluginRoot: string) {
  356. if (dotPluginRoot && fullUrl.startsWith(PROTOCOL_FILE + dotPluginRoot)) {
  357. fullUrl = safetyPathJoin(
  358. URL_LSP,
  359. fullUrl.substr(PROTOCOL_FILE.length + dotPluginRoot.length)
  360. )
  361. }
  362. return fullUrl
  363. }
  364. class IllegalPluginPackageError extends Error {
  365. constructor(message: string) {
  366. super(message)
  367. this.name = IllegalPluginPackageError.name
  368. }
  369. }
  370. class ExistedImportedPluginPackageError extends Error {
  371. constructor(message: string) {
  372. super(message)
  373. this.name = ExistedImportedPluginPackageError.name
  374. }
  375. }
  376. /**
  377. * Host plugin for local
  378. */
  379. class PluginLocal extends EventEmitter<'loaded'
  380. | 'unloaded'
  381. | 'beforeunload'
  382. | 'error'
  383. | string> {
  384. private _sdk: Partial<PluginLocalSDKMetadata> = {}
  385. private _disposes: Array<() => Promise<any>> = []
  386. private _id: PluginLocalIdentity
  387. private _status: PluginLocalLoadStatus = PluginLocalLoadStatus.UNLOADED
  388. private _loadErr?: Error
  389. private _localRoot?: string
  390. private _dotSettingsFile?: string
  391. private _caller?: LSPluginCaller
  392. /**
  393. * @param _options
  394. * @param _themeMgr
  395. * @param _ctx
  396. */
  397. constructor(
  398. private _options: PluginLocalOptions,
  399. private readonly _themeMgr: ILSPluginThemeManager,
  400. private readonly _ctx: LSPluginCore
  401. ) {
  402. super()
  403. this._id = _options.key || genID()
  404. initUserSettingsHandlers(this)
  405. initMainUIHandlers(this)
  406. initProviderHandlers(this)
  407. initApiProxyHandlers(this)
  408. }
  409. async _setupUserSettings(reload?: boolean) {
  410. const { _options } = this
  411. const logger = (_options.logger = new PluginLogger('Loader'))
  412. if (_options.settings && !reload) {
  413. return
  414. }
  415. try {
  416. const loadFreshSettings = () =>
  417. invokeHostExportedApi('load_plugin_user_settings', this.id)
  418. const [userSettingsFilePath, userSettings] = await loadFreshSettings()
  419. this._dotSettingsFile = userSettingsFilePath
  420. let settings = _options.settings
  421. if (!settings) {
  422. settings = _options.settings = new PluginSettings(userSettings)
  423. }
  424. if (reload) {
  425. settings.settings = userSettings
  426. return
  427. }
  428. const handler = async (a, b) => {
  429. debug('Settings changed', this.debugTag, a)
  430. if (!a.disabled && b.disabled) {
  431. // Enable plugin
  432. const [, freshSettings] = await loadFreshSettings()
  433. freshSettings.disabled = false
  434. a = Object.assign(a, freshSettings)
  435. settings.settings = a
  436. await this.load()
  437. }
  438. if (a.disabled && !b.disabled) {
  439. // Disable plugin
  440. const [, freshSettings] = await loadFreshSettings()
  441. freshSettings.disabled = true
  442. a = Object.assign(a, freshSettings)
  443. await this.unload()
  444. }
  445. if (a) {
  446. invokeHostExportedApi('save_plugin_user_settings', this.id, a)
  447. }
  448. }
  449. // observe settings
  450. settings.on('change', handler)
  451. return () => {}
  452. } catch (e) {
  453. debug('[load plugin user settings Error]', e)
  454. logger?.error(e)
  455. }
  456. }
  457. getMainUIContainer(): HTMLElement | undefined {
  458. if (this.shadow) {
  459. return this.caller?._getSandboxShadowContainer()
  460. }
  461. return this.caller?._getSandboxIframeContainer()
  462. }
  463. _resolveResourceFullUrl(filePath: string, localRoot?: string) {
  464. if (!filePath?.trim()) return
  465. localRoot = localRoot || this._localRoot
  466. const reg = /^(http|file)/
  467. if (!reg.test(filePath)) {
  468. const url = path.join(localRoot, filePath)
  469. filePath = reg.test(url) ? url : PROTOCOL_FILE + url
  470. }
  471. return !this.options.effect && this.isInstalledInDotRoot
  472. ? convertToLSPResource(filePath, this.dotPluginsRoot)
  473. : filePath
  474. }
  475. async _preparePackageConfigs() {
  476. const { url } = this._options
  477. let pkg: any
  478. try {
  479. if (!url) {
  480. throw new Error('Can not resolve package config location')
  481. }
  482. debug('prepare package root', url)
  483. pkg = await invokeHostExportedApi('load_plugin_config', url)
  484. if (!pkg || ((pkg = JSON.parse(pkg)), !pkg)) {
  485. throw new Error(`Parse package config error #${url}/package.json`)
  486. }
  487. } catch (e) {
  488. throw new IllegalPluginPackageError(e.message)
  489. }
  490. const localRoot = (this._localRoot = safetyPathNormalize(url))
  491. const logseq: Partial<LSPluginPkgConfig> = pkg.logseq || {}
  492. // Pick legal attrs
  493. ;[
  494. 'name',
  495. 'author',
  496. 'repository',
  497. 'version',
  498. 'description',
  499. 'repo',
  500. 'title',
  501. 'effect',
  502. 'sponsors',
  503. ]
  504. .concat(!this.isInstalledInDotRoot ? ['devEntry'] : [])
  505. .forEach((k) => {
  506. this._options[k] = pkg[k]
  507. })
  508. const validateEntry = (main) => main && /\.(js|html)$/.test(main)
  509. // Entry from main
  510. const entry = logseq.entry || logseq.main || pkg.main
  511. if (validateEntry(entry)) {
  512. // Theme has no main
  513. this._options.entry = this._resolveResourceFullUrl(entry, localRoot)
  514. this._options.devEntry = logseq.devEntry
  515. if (logseq.mode) {
  516. this._options.mode = logseq.mode
  517. }
  518. }
  519. const title = logseq.title || pkg.title
  520. const icon = logseq.icon || pkg.icon
  521. this._options.title = title
  522. this._options.icon = icon && this._resolveResourceFullUrl(icon)
  523. this._options.theme = Boolean(logseq.theme || !!logseq.themes)
  524. // TODO: strategy for Logseq plugins center
  525. if (this.isInstalledInDotRoot) {
  526. this._id = path.basename(localRoot)
  527. } else {
  528. if (logseq.id) {
  529. this._id = logseq.id
  530. } else {
  531. logseq.id = this.id
  532. try {
  533. await invokeHostExportedApi('save_plugin_config', url, {
  534. ...pkg,
  535. logseq,
  536. })
  537. } catch (e) {
  538. debug('[save plugin ID Error] ', e)
  539. }
  540. }
  541. }
  542. // Validate id
  543. const { registeredPlugins, isRegistering } = this._ctx
  544. if (isRegistering && registeredPlugins.has(this.id)) {
  545. throw new ExistedImportedPluginPackageError('Registered plugin package Error')
  546. }
  547. return async () => {
  548. try {
  549. // 0. Install Themes
  550. const themes = logseq.themes
  551. if (themes) {
  552. await this._loadConfigThemes(
  553. Array.isArray(themes) ? themes : [themes]
  554. )
  555. }
  556. } catch (e) {
  557. debug('[prepare package effect Error]', e)
  558. }
  559. }
  560. }
  561. async _tryToNormalizeEntry() {
  562. let { entry, settings, devEntry } = this.options
  563. devEntry = devEntry || settings?.get('_devEntry')
  564. if (devEntry) {
  565. this._options.entry = devEntry
  566. return
  567. }
  568. if (!entry.endsWith('.js')) return
  569. let dirPathInstalled = null
  570. let tmp_file_method = 'write_user_tmp_file'
  571. if (this.isInstalledInDotRoot) {
  572. tmp_file_method = 'write_dotdir_file'
  573. dirPathInstalled = this._localRoot.replace(this.dotPluginsRoot, '')
  574. dirPathInstalled = path.join(DIR_PLUGINS, dirPathInstalled)
  575. }
  576. const tag = new Date().getDay()
  577. const sdkPathRoot = await getSDKPathRoot()
  578. const entryPath = await invokeHostExportedApi(
  579. tmp_file_method,
  580. `${this._id}_index.html`,
  581. `<!doctype html>
  582. <html lang="en">
  583. <head>
  584. <meta charset="UTF-8">
  585. <title>logseq plugin entry</title>
  586. ${
  587. IS_DEV
  588. ? `<script src="${sdkPathRoot}/lsplugin.user.js?v=${tag}"></script>`
  589. : `<script src="https://cdn.jsdelivr.net/npm/@logseq/libs/dist/lsplugin.user.min.js?v=${tag}"></script>`
  590. }
  591. </head>
  592. <body>
  593. <div id="app"></div>
  594. <script src="${entry}"></script>
  595. </body>
  596. </html>`,
  597. dirPathInstalled
  598. )
  599. entry = convertToLSPResource(
  600. withFileProtocol(path.normalize(entryPath)),
  601. this.dotPluginsRoot
  602. )
  603. this._options.entry = entry
  604. }
  605. async _loadConfigThemes(themes: Theme[]) {
  606. themes.forEach((options) => {
  607. if (!options.url) return
  608. if (!options.url.startsWith('http') && this._localRoot) {
  609. options.url = path.join(this._localRoot, options.url)
  610. // file:// for native
  611. if (!options.url.startsWith('file:')) {
  612. options.url = 'assets://' + options.url
  613. }
  614. }
  615. this.emit('provider:theme', options)
  616. })
  617. }
  618. async _loadLayoutsData(): Promise<Record<string, any>> {
  619. const key = this.id + '_layouts'
  620. const [, layouts] = await invokeHostExportedApi(
  621. 'load_plugin_user_settings',
  622. key
  623. )
  624. return layouts || {}
  625. }
  626. async _saveLayoutsData(data) {
  627. const key = this.id + '_layouts'
  628. await invokeHostExportedApi('save_plugin_user_settings', key, data)
  629. }
  630. async _persistMainUILayoutData(e: {
  631. width: number
  632. height: number
  633. left: number
  634. top: number
  635. }) {
  636. const layouts = await this._loadLayoutsData()
  637. layouts.$$0 = e
  638. await this._saveLayoutsData(layouts)
  639. }
  640. _setupDraggableContainer(
  641. el: HTMLElement,
  642. opts: Partial<{ key: string; title: string; close: () => void }> = {}
  643. ): () => void {
  644. const ds = el.dataset
  645. if (ds.inited_draggable) return
  646. if (!ds.identity) {
  647. ds.identity = 'dd-' + genID()
  648. }
  649. const isInjectedUI = !!opts.key
  650. const handle = document.createElement('div')
  651. handle.classList.add('draggable-handle')
  652. handle.innerHTML = `
  653. <div class="th">
  654. <div class="l"><h3>${opts.title || ''}</h3></div>
  655. <div class="r">
  656. <a class="button x"><i class="ti ti-x"></i></a>
  657. </div>
  658. </div>
  659. `
  660. handle.querySelector('.x').addEventListener(
  661. 'click',
  662. (e) => {
  663. opts?.close?.()
  664. e.stopPropagation()
  665. },
  666. false
  667. )
  668. handle.addEventListener(
  669. 'mousedown',
  670. (e) => {
  671. const target = e.target as HTMLElement
  672. if (target?.closest('.r')) {
  673. e.stopPropagation()
  674. e.preventDefault()
  675. }
  676. },
  677. false
  678. )
  679. el.prepend(handle)
  680. // move to top
  681. el.addEventListener(
  682. 'mousedown',
  683. (e) => {
  684. this.layoutCore.move_container_to_top(ds.identity)
  685. },
  686. true
  687. )
  688. const setTitle = (title) => {
  689. handle.querySelector('h3').textContent = title
  690. }
  691. const dispose = this.layoutCore.setup_draggable_container_BANG_(
  692. el,
  693. !isInjectedUI ? this._persistMainUILayoutData.bind(this) : () => {}
  694. )
  695. ds.inited_draggable = 'true'
  696. if (opts.title) {
  697. setTitle(opts.title)
  698. }
  699. // click outside
  700. let removeOutsideListener = null
  701. if (ds.close === 'outside') {
  702. const handler = (e) => {
  703. const target = e.target
  704. if (!el.contains(target)) {
  705. opts.close()
  706. }
  707. }
  708. document.addEventListener('click', handler, false)
  709. removeOutsideListener = () => {
  710. document.removeEventListener('click', handler)
  711. }
  712. }
  713. return () => {
  714. dispose()
  715. removeOutsideListener?.()
  716. }
  717. }
  718. _setupResizableContainer(el: HTMLElement, key?: string): () => void {
  719. const ds = el.dataset
  720. if (ds.inited_resizable) return
  721. if (!ds.identity) {
  722. ds.identity = 'dd-' + genID()
  723. }
  724. const handle = document.createElement('div')
  725. handle.classList.add('resizable-handle')
  726. el.prepend(handle)
  727. // @ts-expect-error
  728. const layoutCore = window.frontend.modules.layout.core
  729. const dispose = layoutCore.setup_resizable_container_BANG_(
  730. el,
  731. !key ? this._persistMainUILayoutData.bind(this) : () => {}
  732. )
  733. ds.inited_resizable = 'true'
  734. return dispose
  735. }
  736. async load(
  737. opts?: Partial<{
  738. indicator: DeferredActor
  739. reload: boolean
  740. }>
  741. ) {
  742. if (this.pending) {
  743. return
  744. }
  745. this._status = PluginLocalLoadStatus.LOADING
  746. this._loadErr = undefined
  747. try {
  748. // if (!this.options.entry) { // Themes package no entry field
  749. // }
  750. const installPackageThemes = await this._preparePackageConfigs()
  751. this._dispose(await this._setupUserSettings(opts?.reload))
  752. if (!this.disabled) {
  753. await installPackageThemes.call(null)
  754. }
  755. if (this.disabled || !this.options.entry) {
  756. return
  757. }
  758. await this._tryToNormalizeEntry()
  759. this._caller = new LSPluginCaller(this)
  760. await this._caller.connectToChild()
  761. const readyFn = () => {
  762. this._caller?.callUserModel(LSPMSG_READY, { pid: this.id })
  763. }
  764. if (opts?.indicator) {
  765. opts.indicator.promise.then(readyFn)
  766. } else {
  767. readyFn()
  768. }
  769. this._dispose(async () => {
  770. await this._caller?.destroy()
  771. })
  772. this._dispose(cleanInjectedScripts.bind(this))
  773. } catch (e) {
  774. this.logger?.error('[Load Plugin]', e, true)
  775. this.dispose().catch(null)
  776. this._status = PluginLocalLoadStatus.ERROR
  777. this._loadErr = e
  778. } finally {
  779. if (!this._loadErr) {
  780. if (this.disabled) {
  781. this._status = PluginLocalLoadStatus.UNLOADED
  782. } else {
  783. this._status = PluginLocalLoadStatus.LOADED
  784. }
  785. }
  786. }
  787. }
  788. async reload() {
  789. if (this.pending) {
  790. return
  791. }
  792. this._ctx.emit('beforereload', this)
  793. await this.unload()
  794. await this.load({ reload: true })
  795. this._ctx.emit('reloaded', this)
  796. }
  797. /**
  798. * @param unregister If true delete plugin files
  799. */
  800. async unload(unregister: boolean = false) {
  801. if (this.pending) {
  802. return
  803. }
  804. if (unregister) {
  805. await this.unload()
  806. if (this.isInstalledInDotRoot) {
  807. this._ctx.emit('unlink-plugin', this.id)
  808. }
  809. return
  810. }
  811. try {
  812. this._status = PluginLocalLoadStatus.UNLOADING
  813. const eventBeforeUnload = { unregister }
  814. // sync call
  815. try {
  816. await this._caller?.callUserModel(
  817. AWAIT_LSPMSGFn(LSPMSG_BEFORE_UNLOAD),
  818. eventBeforeUnload
  819. )
  820. this.emit('beforeunload', eventBeforeUnload)
  821. } catch (e) {
  822. console.error('[beforeunload Error]', e)
  823. }
  824. await this.dispose()
  825. this.emit('unloaded')
  826. } catch (e) {
  827. debug('[plugin unload Error]', e)
  828. return false
  829. } finally {
  830. this._status = PluginLocalLoadStatus.UNLOADED
  831. }
  832. }
  833. private async dispose() {
  834. for (const fn of this._disposes) {
  835. try {
  836. fn && (await fn())
  837. } catch (e) {
  838. console.error(this.debugTag, 'dispose Error', e)
  839. }
  840. }
  841. // clear
  842. this._disposes = []
  843. }
  844. _dispose(fn: any) {
  845. if (!fn) return
  846. this._disposes.push(fn)
  847. }
  848. _onHostMounted(callback: () => void) {
  849. const actor = this._ctx.hostMountedActor
  850. if (!actor || actor.settled) {
  851. callback()
  852. } else {
  853. actor?.promise.then(callback)
  854. }
  855. }
  856. get layoutCore(): any {
  857. // @ts-expect-error
  858. return window.frontend.modules.layout.core
  859. }
  860. get isInstalledInDotRoot() {
  861. const dotRoot = this.dotConfigRoot
  862. const plgRoot = this.localRoot
  863. return dotRoot && plgRoot && plgRoot.startsWith(dotRoot)
  864. }
  865. get loaded() {
  866. return this._status === PluginLocalLoadStatus.LOADED
  867. }
  868. get pending() {
  869. return [
  870. PluginLocalLoadStatus.LOADING,
  871. PluginLocalLoadStatus.UNLOADING,
  872. ].includes(this._status)
  873. }
  874. get status(): PluginLocalLoadStatus {
  875. return this._status
  876. }
  877. get settings() {
  878. return this.options.settings
  879. }
  880. set settingsSchema(schema: SettingSchemaDesc[]) {
  881. this._options.settingsSchema = schema
  882. }
  883. get settingsSchema() {
  884. return this.options.settingsSchema
  885. }
  886. get logger() {
  887. return this.options.logger
  888. }
  889. get disabled() {
  890. return this.settings?.get('disabled')
  891. }
  892. get caller() {
  893. return this._caller
  894. }
  895. get id(): string {
  896. return this._id
  897. }
  898. get shadow(): boolean {
  899. return this.options.mode === 'shadow'
  900. }
  901. get options(): PluginLocalOptions {
  902. return this._options
  903. }
  904. get themeMgr(): ILSPluginThemeManager {
  905. return this._themeMgr
  906. }
  907. get debugTag() {
  908. const name = this._options?.name
  909. return `#${this._id} ${name ?? ''}`
  910. }
  911. get localRoot(): string {
  912. return this._localRoot || this._options.url
  913. }
  914. get loadErr(): Error | undefined {
  915. return this._loadErr
  916. }
  917. get dotConfigRoot() {
  918. return path.normalize(this._ctx.options.dotConfigRoot)
  919. }
  920. get dotSettingsFile(): string | undefined {
  921. return this._dotSettingsFile
  922. }
  923. get dotPluginsRoot() {
  924. return path.join(this.dotConfigRoot, DIR_PLUGINS)
  925. }
  926. get sdk(): Partial<PluginLocalSDKMetadata> {
  927. return this._sdk
  928. }
  929. set sdk(value: Partial<PluginLocalSDKMetadata>) {
  930. this._sdk = value
  931. }
  932. toJSON() {
  933. const json = { ...this.options } as any
  934. json.id = this.id
  935. json.err = this.loadErr
  936. json.usf = this.dotSettingsFile
  937. json.iir = this.isInstalledInDotRoot
  938. json.lsr = this._resolveResourceFullUrl('/')
  939. return json
  940. }
  941. }
  942. /**
  943. * Host plugin core
  944. */
  945. class LSPluginCore
  946. extends EventEmitter<'beforeenable'
  947. | 'enabled'
  948. | 'beforedisable'
  949. | 'disabled'
  950. | 'registered'
  951. | 'error'
  952. | 'unregistered'
  953. | 'ready'
  954. | 'themes-changed'
  955. | 'theme-selected'
  956. | 'reset-custom-theme'
  957. | 'settings-changed'
  958. | 'unlink-plugin'
  959. | 'beforereload'
  960. | 'reloaded'>
  961. implements ILSPluginThemeManager {
  962. private _isRegistering = false
  963. private _readyIndicator?: DeferredActor
  964. private readonly _hostMountedActor: DeferredActor = deferred()
  965. private readonly _userPreferences: UserPreferences = {
  966. theme: null,
  967. themes: {
  968. mode: 'light',
  969. light: null,
  970. dark: null,
  971. },
  972. externals: [],
  973. }
  974. private readonly _registeredThemes = new Map<PluginLocalIdentity, Theme[]>()
  975. private readonly _registeredPlugins = new Map<PluginLocalIdentity,
  976. PluginLocal>()
  977. private _currentTheme: {
  978. pid: PluginLocalIdentity
  979. opt: Theme | LegacyTheme
  980. eject: () => void
  981. }
  982. /**
  983. * @param _options
  984. */
  985. constructor(private readonly _options: Partial<LSPluginCoreOptions>) {
  986. super()
  987. }
  988. async loadUserPreferences() {
  989. try {
  990. const settings = await invokeHostExportedApi('load_user_preferences')
  991. if (settings) {
  992. Object.assign(this._userPreferences, settings)
  993. }
  994. } catch (e) {
  995. debug('[load user preferences Error]', e)
  996. }
  997. }
  998. async saveUserPreferences(settings: Partial<UserPreferences>) {
  999. try {
  1000. if (settings) {
  1001. Object.assign(this._userPreferences, settings)
  1002. }
  1003. await invokeHostExportedApi(
  1004. 'save_user_preferences',
  1005. this._userPreferences
  1006. )
  1007. } catch (e) {
  1008. debug('[save user preferences Error]', e)
  1009. }
  1010. }
  1011. /**
  1012. * Activate the user preferences.
  1013. *
  1014. * Steps:
  1015. *
  1016. * 1. Load the custom theme.
  1017. *
  1018. * @memberof LSPluginCore
  1019. */
  1020. async activateUserPreferences() {
  1021. const { theme: legacyTheme, themes } = this._userPreferences
  1022. const currentTheme = themes[themes.mode]
  1023. // If there is currently a theme that has been set
  1024. if (currentTheme) {
  1025. await this.selectTheme(currentTheme, { effect: false })
  1026. } else if (legacyTheme) {
  1027. // Otherwise compatible with older versions
  1028. await this.selectTheme(legacyTheme, { effect: false })
  1029. }
  1030. }
  1031. /**
  1032. * @param plugins
  1033. * @param initial
  1034. */
  1035. async register(
  1036. plugins: RegisterPluginOpts[] | RegisterPluginOpts,
  1037. initial = false
  1038. ) {
  1039. if (!Array.isArray(plugins)) {
  1040. await this.register([plugins])
  1041. return
  1042. }
  1043. const perfTable = new Map<string,
  1044. { o: PluginLocal; s: number; e: number }>()
  1045. const debugPerfInfo = () => {
  1046. const data: any = Array.from(perfTable.values()).reduce((ac, it) => {
  1047. const { id, options, status, disabled } = it.o
  1048. if (disabled !== true &&
  1049. (options.entry || (!options.name && !options.entry))) {
  1050. ac[id] = {
  1051. name: options.name,
  1052. entry: options.entry,
  1053. status: status,
  1054. enabled:
  1055. typeof disabled === 'boolean' ? (!disabled ? '🟢' : '⚫️') : '🔴',
  1056. perf: !it.e ? it.o.loadErr : `${(it.e - it.s).toFixed(2)}ms`,
  1057. }
  1058. }
  1059. return ac
  1060. }, {})
  1061. console.table(data)
  1062. }
  1063. // @ts-expect-error
  1064. window.__debugPluginsPerfInfo = debugPerfInfo
  1065. try {
  1066. this._isRegistering = true
  1067. const userConfigRoot = this._options.dotConfigRoot
  1068. const readyIndicator = (this._readyIndicator = deferred())
  1069. await this.loadUserPreferences()
  1070. let externals = new Set(this._userPreferences.externals)
  1071. // valid externals
  1072. if (externals?.size) {
  1073. try {
  1074. const validatedExternals: Record<string, boolean> = await invokeHostExportedApi(
  1075. 'validate_external_plugins', [...externals]
  1076. )
  1077. externals = new Set([...Object.entries(validatedExternals)].reduce(
  1078. (a, [k, v]) => {
  1079. if (v) {
  1080. a.push(k)
  1081. }
  1082. return a
  1083. }, []))
  1084. } catch (e) {
  1085. console.error('[validatedExternals Error]', e)
  1086. }
  1087. }
  1088. if (initial) {
  1089. plugins = plugins.concat(
  1090. [...externals]
  1091. .filter((url) => {
  1092. return (
  1093. !plugins.length ||
  1094. (plugins as RegisterPluginOpts[]).every(
  1095. (p) => !p.entry && p.url !== url
  1096. )
  1097. )
  1098. })
  1099. .map((url) => ({ url }))
  1100. )
  1101. }
  1102. for (const pluginOptions of plugins) {
  1103. const { url } = pluginOptions as PluginLocalOptions
  1104. const pluginLocal = new PluginLocal(
  1105. pluginOptions as PluginLocalOptions,
  1106. this,
  1107. this
  1108. )
  1109. const perfInfo = { o: pluginLocal, s: performance.now(), e: 0 }
  1110. perfTable.set(url, perfInfo)
  1111. await pluginLocal.load({ indicator: readyIndicator })
  1112. perfInfo.e = performance.now()
  1113. const { loadErr } = pluginLocal
  1114. if (loadErr) {
  1115. debug('[Failed LOAD Plugin] #', pluginOptions)
  1116. this.emit('error', loadErr)
  1117. if (
  1118. loadErr instanceof IllegalPluginPackageError ||
  1119. loadErr instanceof ExistedImportedPluginPackageError
  1120. ) {
  1121. // TODO: notify global log system?
  1122. continue
  1123. }
  1124. }
  1125. pluginLocal.settings?.on('change', (a) => {
  1126. this.emit('settings-changed', pluginLocal.id, a)
  1127. pluginLocal.caller?.callUserModel(LSPMSG_SETTINGS, { payload: a })
  1128. })
  1129. this._registeredPlugins.set(pluginLocal.id, pluginLocal)
  1130. this.emit('registered', pluginLocal)
  1131. // external plugins
  1132. if (!pluginLocal.isInstalledInDotRoot) {
  1133. externals.add(url)
  1134. }
  1135. }
  1136. await this.saveUserPreferences({ externals: Array.from(externals) })
  1137. await this.activateUserPreferences()
  1138. readyIndicator.resolve('ready')
  1139. } catch (e) {
  1140. console.error(e)
  1141. } finally {
  1142. this._isRegistering = false
  1143. this.emit('ready', perfTable)
  1144. debugPerfInfo()
  1145. }
  1146. }
  1147. async reload(plugins: PluginLocalIdentity[] | PluginLocalIdentity) {
  1148. if (!Array.isArray(plugins)) {
  1149. await this.reload([plugins])
  1150. return
  1151. }
  1152. for (const identity of plugins) {
  1153. try {
  1154. const p = this.ensurePlugin(identity)
  1155. await p.reload()
  1156. } catch (e) {
  1157. debug(e)
  1158. }
  1159. }
  1160. }
  1161. async unregister(plugins: PluginLocalIdentity[] | PluginLocalIdentity) {
  1162. if (!Array.isArray(plugins)) {
  1163. await this.unregister([plugins])
  1164. return
  1165. }
  1166. const unregisteredExternals: string[] = []
  1167. for (const identity of plugins) {
  1168. const p = this.ensurePlugin(identity)
  1169. if (!p.isInstalledInDotRoot) {
  1170. unregisteredExternals.push(p.options.url)
  1171. }
  1172. await p.unload(true)
  1173. this._registeredPlugins.delete(identity)
  1174. this.emit('unregistered', identity)
  1175. }
  1176. const externals = this._userPreferences.externals
  1177. if (externals.length && unregisteredExternals.length) {
  1178. await this.saveUserPreferences({
  1179. externals: externals.filter((it) => {
  1180. return !unregisteredExternals.includes(it)
  1181. }),
  1182. })
  1183. }
  1184. }
  1185. async enable(plugin: PluginLocalIdentity) {
  1186. const p = this.ensurePlugin(plugin)
  1187. if (p.pending) return
  1188. this.emit('beforeenable')
  1189. p.settings?.set('disabled', false)
  1190. this.emit('enabled', p.id)
  1191. }
  1192. async disable(plugin: PluginLocalIdentity) {
  1193. const p = this.ensurePlugin(plugin)
  1194. if (p.pending) return
  1195. this.emit('beforedisable')
  1196. p.settings?.set('disabled', true)
  1197. this.emit('disabled', p.id)
  1198. }
  1199. async _hook(ns: string, type: string, payload?: any, pid?: string) {
  1200. const hook = `${ns}:${safeSnakeCase(type)}`
  1201. const isDbChangedHook = hook === 'hook:db:changed'
  1202. const isDbBlockChangeHook = hook.startsWith('hook:db:block')
  1203. const act = (p: PluginLocal) => {
  1204. debug(`[call hook][#${p.id}]`, ns, type)
  1205. p.caller?.callUserModel(LSPMSG, {
  1206. ns,
  1207. type: safeSnakeCase(type),
  1208. payload,
  1209. })
  1210. }
  1211. for (const [_, p] of this._registeredPlugins) {
  1212. if (p.options.theme || p.disabled) {
  1213. continue
  1214. }
  1215. if (!pid) {
  1216. // compatible for old SDK < 0.0.2
  1217. const sdkVersion = p.sdk?.version
  1218. // TODO: remove optimization after few releases
  1219. if (!sdkVersion) {
  1220. if (isDbChangedHook || isDbBlockChangeHook) {
  1221. continue
  1222. } else {
  1223. act(p)
  1224. }
  1225. }
  1226. if (
  1227. sdkVersion &&
  1228. invokeHostExportedApi('should_exec_plugin_hook', p.id, hook)
  1229. ) {
  1230. act(p)
  1231. }
  1232. } else if (pid === p.id) {
  1233. act(p)
  1234. break
  1235. }
  1236. }
  1237. }
  1238. async hookApp(type: string, payload?: any, pid?: string) {
  1239. return await this._hook('hook:app', type, payload, pid)
  1240. }
  1241. async hookEditor(type: string, payload?: any, pid?: string) {
  1242. return await this._hook('hook:editor', type, payload, pid)
  1243. }
  1244. async hookDb(type: string, payload?: any, pid?: string) {
  1245. return await this._hook('hook:db', type, payload, pid)
  1246. }
  1247. ensurePlugin(plugin: PluginLocalIdentity | PluginLocal) {
  1248. if (plugin instanceof PluginLocal) {
  1249. return plugin
  1250. }
  1251. const p = this._registeredPlugins.get(plugin)
  1252. if (!p) {
  1253. throw new Error(`plugin #${plugin} not existed.`)
  1254. }
  1255. return p
  1256. }
  1257. hostMounted() {
  1258. this._hostMountedActor.resolve()
  1259. }
  1260. _forceCleanInjectedUI(id: string) {
  1261. if (!id) return
  1262. return cleanInjectedUI(id)
  1263. }
  1264. get registeredPlugins(): Map<PluginLocalIdentity, PluginLocal> {
  1265. return this._registeredPlugins
  1266. }
  1267. get options() {
  1268. return this._options
  1269. }
  1270. get readyIndicator(): DeferredActor | undefined {
  1271. return this._readyIndicator
  1272. }
  1273. get hostMountedActor(): DeferredActor {
  1274. return this._hostMountedActor
  1275. }
  1276. get isRegistering(): boolean {
  1277. return this._isRegistering
  1278. }
  1279. get themes() {
  1280. return this._registeredThemes
  1281. }
  1282. async registerTheme(id: PluginLocalIdentity, opt: Theme): Promise<void> {
  1283. debug('Register theme #', id, opt)
  1284. if (!id) return
  1285. let themes: Theme[] = this._registeredThemes.get(id)!
  1286. if (!themes) {
  1287. this._registeredThemes.set(id, (themes = []))
  1288. }
  1289. themes.push(opt)
  1290. this.emit('themes-changed', this.themes, { id, ...opt })
  1291. }
  1292. async selectTheme(
  1293. theme: Theme | LegacyTheme,
  1294. options: {
  1295. effect?: boolean
  1296. emit?: boolean
  1297. } = {}
  1298. ) {
  1299. const { effect, emit } = Object.assign(
  1300. {},
  1301. { effect: true, emit: true },
  1302. options
  1303. )
  1304. // Clear current theme before injecting.
  1305. if (this._currentTheme) {
  1306. this._currentTheme.eject()
  1307. }
  1308. // Detect if it is the default theme (no url).
  1309. if (!theme.url) {
  1310. this._currentTheme = null
  1311. } else {
  1312. const ejectTheme = injectTheme(theme.url)
  1313. this._currentTheme = {
  1314. pid: theme.pid,
  1315. opt: theme,
  1316. eject: ejectTheme,
  1317. }
  1318. }
  1319. if (effect) {
  1320. await this.saveUserPreferences(
  1321. theme.mode
  1322. ? {
  1323. themes: {
  1324. ...this._userPreferences.themes,
  1325. mode: theme.mode,
  1326. [theme.mode]: theme,
  1327. },
  1328. }
  1329. : { theme: theme }
  1330. )
  1331. }
  1332. if (emit) {
  1333. this.emit('theme-selected', theme)
  1334. }
  1335. }
  1336. async unregisterTheme(id: PluginLocalIdentity, effect = true) {
  1337. debug('Unregister theme #', id)
  1338. if (!this._registeredThemes.has(id)) {
  1339. return
  1340. }
  1341. this._registeredThemes.delete(id)
  1342. this.emit('themes-changed', this.themes, { id })
  1343. if (effect && this._currentTheme?.pid === id) {
  1344. this._currentTheme.eject()
  1345. this._currentTheme = null
  1346. const { theme, themes } = this._userPreferences
  1347. await this.saveUserPreferences({
  1348. theme: theme?.pid === id ? null : theme,
  1349. themes: {
  1350. ...themes,
  1351. light: themes.light?.pid === id ? null : themes.light,
  1352. dark: themes.dark?.pid === id ? null : themes.dark,
  1353. },
  1354. })
  1355. // Reset current theme if it is unregistered
  1356. this.emit('reset-custom-theme', this._userPreferences.themes)
  1357. }
  1358. }
  1359. }
  1360. function setupPluginCore(options: any) {
  1361. const pluginCore = new LSPluginCore(options)
  1362. debug('=== 🔗 Setup Logseq Plugin System 🔗 ===')
  1363. window.LSPluginCore = pluginCore
  1364. }
  1365. export { PluginLocal, pluginHelpers, setupPluginCore }