lsx-context.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import {
  2. OptionParser,
  3. type ParseRangeResult,
  4. } from '@growi/core/dist/remark-plugins';
  5. export class LsxContext {
  6. pagePath: string;
  7. options?: Record<string, string | undefined>;
  8. constructor(pagePath: string, options: Record<string, string | undefined>) {
  9. this.pagePath = pagePath;
  10. // remove undefined keys
  11. Object.keys(options).forEach(
  12. (key) => options[key] === undefined && delete options[key],
  13. );
  14. this.options = options;
  15. }
  16. getOptDepth(): ParseRangeResult | null {
  17. if (this.options?.depth == null) {
  18. return null;
  19. }
  20. return OptionParser.parseRange(this.options.depth);
  21. }
  22. getStringifiedAttributes(separator = ', '): string {
  23. const attributeStrs = [`prefix=${this.pagePath}`];
  24. if (this.options != null) {
  25. const optionEntries = Object.entries(this.options).sort();
  26. attributeStrs.push(
  27. ...optionEntries.map(([key, val]) => `${key}=${val || 'true'}`),
  28. );
  29. }
  30. return attributeStrs.join(separator);
  31. }
  32. /**
  33. * for printing errors
  34. * @returns
  35. */
  36. toString(): string {
  37. return `$lsx(${this.getStringifiedAttributes()})`;
  38. }
  39. }