Skip to content

Instantly share code, notes, and snippets.

@mekefly
Last active October 19, 2022 13:58
Show Gist options
  • Save mekefly/50bdfe776eed72a509e9380e957c4cfe to your computer and use it in GitHub Desktop.
Save mekefly/50bdfe776eed72a509e9380e957c4cfe to your computer and use it in GitHub Desktop.
quickAddTodoList脚本.md

🧲 相关:

[[quickAddTodoList脚本安装方法]]

🗓️ 创建日期: [[2022-10-19#21:33]]


效果

教程见quickAddTodoList脚本安装方法.md · GitHub

源码

/*
教程见[quickAddTodoList脚本安装方法.md · GitHub](https://gist.github.com/f4bc00fe0323b6a3e6a2af47dbf39dea)

推荐安装插件:
quickAdd  obsidian://show-plugin?id=quickadd
kanban obsidian://show-plugin?id=obsidian-kanban

当前脚本编写时插件版本
kanban: 1.4.6
quickAdd:0.5.5

template
```markdown
## 开始

- [ ] 将会在这条前面添加当前文档标题
- [ ] 这是一条任物

## 已完成的

**完成**
- [x] 将会在这条前面添加当前文档标题
- [x] 添加时将全部为完成的状态
```
 */

const CONFIG_PATH = "quickAddTodoListConfig.json";

module.exports = async (params) => {
  const { obsidian, app } = params;

  const vaultConfigDir = app.vault.configDir;
  const vaultBasePath = app.vault.adapter.basePath;

  const vaultManage = new obsidian.FileSystemAdapter(vaultBasePath);

  const options = { ...params, vaultManage };

  try {
    Object.assign(options, await getConfig(params, vaultManage));
  } catch (error) {
    new obsidian.Notice("添加失败");
    console.log(`quickAdd > quickAddKanban: ${error.message}`);
    return;
  }

  await insertIntoFile(options);

  new obsidian.Notice("这篇笔记已添加到您的看板");
  console.log("add completed");
};

async function insertIntoFile(options) {
  const { vaultManage } = options;
  const text = await vaultManage.read(options.filePath);

  const link = createLinkToActive(options);

  const newText = insertIntoText(text, options.titleName, link);

  await vaultManage.write(options.filePath, newText);
}

/**
 *
 *
 * @param {string} text
 * @param {string} titleName
 * @param {string} context
 * @return {string}
 */
function insertIntoText(text, titleName, context) {
  titleName = titleName.trim();

  const rows = text.split("\n");
  let index = 0;
  while (index < rows.length && index >= 0) {
    const item = rows[index];
    if (item.startsWith(`## ${titleName}`)) {
      index += 2;

      if (
        rows[index].includes("**完成**") ||
        rows[index].toLowerCase().includes("**completed**")
      ) {
        rows.splice(index + 1, 0, `- [x] ${context}`);
      } else {
        rows.splice(index, 0, `- [ ] ${context}`);
      }
      return rows.join("\n");
    }
    index++;
  }

  throw new Error(`${titleName} is Not Found,Are you sure he exists?`);
}

/**
 *
 *
 * @param {*} params
 * @param {*} vaultManage
 * @return {{filePath:string, titleName:string}}
 */
async function getConfig(params, vaultManage) {
  const {
    app,
    quickAddApi: { yesNoPrompt },
  } = params;
  const fullConfigPath = `${app.vault.configDir}/${CONFIG_PATH}`;
  const activeFilePath = app.workspace.lastActiveFile.path;

  let configJson;
  //read json
  try {
    configJson = await vaultManage.read(fullConfigPath);
  } catch (e) {
    return await askForANewConfiguration(
      "❓ You haven't configured,Do you want to create a new configuration?"
    );
  }

  let config;
  try {
    config = JSON.parse(configJson);
  } catch (error) {
    return await askForANewConfiguration(
      "❓ Error in configuration file,Do you want to create a new configuration?"
    );
  }

  await assertExistence("titleName");
  await assertExistence("filePath");

  if (activeFilePath === config.filePath) {
    return await askForANewConfiguration(
      "❓ Do you want to create a new configuration?"
    );
  }
  return config;

  async function assertExistence(name) {
    if (!config[name]) {
      return await askForANewConfiguration(
        `❓ ${name} not Found,Do you want to create a new configuration?`
      );
    }
  }

  async function askForANewConfiguration(message, throwError = true) {
    const value = await yesNoPrompt("new configuration?", message);

    if (value)
      return await newConfiguration(params, fullConfigPath, vaultManage);

    if (throwError) {
      throw new Error("Not running");
    }
  }
}

/**
 *
 *
 * @param {*} params
 * @param {*} fullConfigPath
 * @param {*} vaultManage
 * @return {{filePath:string, titleName:string}}
 */
async function newConfiguration(params, fullConfigPath, vaultManage) {
  const config = {};
  config.filePath = (
    await params.quickAddApi.suggester(
      (file) => file.path,
      params.app.vault.getMarkdownFiles()
    )
  ).path;

  config.titleName = await params.quickAddApi.inputPrompt(
    "✏️ After which title do you want to add?"
  );
  await vaultManage.write(fullConfigPath, JSON.stringify(config));
  return config;
}

/**
 * create link
 * @param {*} options
 * @return {string}
 */
function createLinkToActive(options) {
  const { filePath, app } = options;
  const activeFile = app.workspace.lastActiveFile;
  return app.fileManager.generateMarkdownLink(activeFile, filePath);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment