Taskpaper 3 – toggle collapse/expansion of selected item(s)

Toggle collapse selected item(s).kmmacros (20.9 KB)

JavaScript source (TaskPaper JSContext + JXA):

(() => {
  'use strict';

  // TASKPAPER 3 CONTEXT ----------------------------------
  const tpJSContext = (editor, options) => {

    // tp3Main :: () -> Either MesssageString ResultString
    const tp3Main = () => {

      const items = editor.selection.selectedItems;

      return bindLR(
        items.length > 0 ? (
          Right(items)
        ) : Left('No item(s) selected in TaskPaper 3'),
        xs => {
          const k = editor.isCollapsed(xs[0]) ? (
            'Expanded'
          ) : 'Collapsed';
          return (
            editor['set' + k](xs),
            Right(k)
          );
        }
      );
    };

    // GENERIC --------------------------------------------

    // Left :: a -> Either a b
    const Left = x => ({
      type: 'Either',
      Left: x
    });

    // Right :: b -> Either a b
    const Right = x => ({
      type: 'Either',
      Right: x
    });

    // bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
    const bindLR = (m, mf) =>
      m.Right !== undefined ? (
        mf(m.Right)
      ) : m;

    // TP3 MAIN -------------------------------------------
    return tp3Main();
  };


  // JXA CONTEXT-------------------------------------------

  // jxaMain :: () -> Either MessageString ResultString
  const jxaMain = () => {
    const
      ds = Application('TaskPaper')
      .documents,
      lrResult = bindLR(
        ds.length > 0 ? (
          Right(ds.at(0))
        ) : Left('No TP3 documents open'),
        d => d.evaluate({
          script: tpJSContext.toString(),
          withOptions: {}
        })
      );
    return lrResult.Right || lrResult.Left;
  };

  // GENERIC ----------------------------------------------

  // Left :: a -> Either a b
  const Left = x => ({
    type: 'Either',
    Left: x
  });

  // Right :: b -> Either a b
  const Right = x => ({
    type: 'Either',
    Right: x
  });

  // bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
  const bindLR = (m, mf) =>
    m.Right !== undefined ? (
      mf(m.Right)
    ) : m;

  // JXA MAIN ----------------------------------------------------------------
  return jxaMain();
})();
1 Like