LSPlugin.Experiments.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { LSPluginUser } from '../LSPlugin.user'
  2. import { PluginLocal } from '../LSPlugin.core'
  3. import { safeSnakeCase } from '../helpers'
  4. /**
  5. * WARN: These are some experience features and may be adjusted at any time.
  6. * These unofficial plugins that use these APIs are temporarily
  7. * not supported on the Marketplace.
  8. */
  9. export class LSPluginExperiments {
  10. constructor(private ctx: LSPluginUser) {}
  11. get React(): unknown {
  12. return this.ensureHostScope().React
  13. }
  14. get ReactDOM(): unknown {
  15. return this.ensureHostScope().ReactDOM
  16. }
  17. get pluginLocal(): PluginLocal {
  18. return this.ensureHostScope().LSPluginCore.ensurePlugin(
  19. this.ctx.baseInfo.id
  20. )
  21. }
  22. public invokeExperMethod(type: string, ...args: Array<any>) {
  23. const host = this.ensureHostScope()
  24. type = safeSnakeCase(type)?.toLowerCase()
  25. return host.logseq.api['exper_' + type]?.apply(host, args)
  26. }
  27. async loadScripts(...scripts: Array<string>) {
  28. scripts = scripts.map((it) => {
  29. if (!it?.startsWith('http')) {
  30. return this.ctx.resolveResourceFullUrl(it)
  31. }
  32. return it
  33. })
  34. scripts.unshift(this.ctx.baseInfo.id)
  35. await this.invokeExperMethod('loadScripts', ...scripts)
  36. }
  37. registerFencedCodeRenderer(
  38. type: string,
  39. opts: {
  40. edit?: boolean
  41. before?: () => Promise<void>
  42. subs?: Array<string>
  43. render: (props: { content: string }) => any
  44. }
  45. ) {
  46. return this.ensureHostScope().logseq.api.exper_register_fenced_code_renderer(
  47. this.ctx.baseInfo.id,
  48. type,
  49. opts
  50. )
  51. }
  52. registerExtensionsEnhancer<T = any>(
  53. type: 'katex',
  54. enhancer: (v: T) => Promise<any>
  55. ) {
  56. const host = this.ensureHostScope()
  57. switch (type) {
  58. case 'katex':
  59. if (host.katex) {
  60. enhancer(host.katex).catch(console.error)
  61. }
  62. break
  63. default:
  64. }
  65. return host.logseq.api.exper_register_extensions_enhancer(
  66. this.ctx.baseInfo.id,
  67. type, enhancer
  68. )
  69. }
  70. ensureHostScope(): any {
  71. if (window === top) {
  72. throw new Error('Can not access host scope!')
  73. }
  74. return top
  75. }
  76. }