{"size": 841, "ext": "js", "max_stars_repo_path": "src/packages/Aditor/plugins/LinkPlugin/setLinkText.js", "max_stars_repo_name": "YacheLee/Aditor", "max_stars_repo_stars_event_min_datetime": "2020-05-04T00:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T06:21:54.000Z", "max_issues_repo_path": "src/packages/Aditor/plugins/LinkPlugin/setLinkText.js", "max_issues_repo_name": "YacheLee/Aditor", "max_issues_repo_issues_event_min_datetime": "2020-04-27T11:05:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T10:42:20.000Z", "max_forks_repo_path": "src/packages/Aditor/plugins/LinkPlugin/setLinkText.js", "max_forks_repo_name": "YacheLee/Aditor", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 9, "max_issues_count": 2, "max_forks_count": null, "avg_line_length": 25.4848484848, "max_line_length": 70, "alphanum_fraction": 0.6028537455}
import filter from './filter';

function isLinkAtPos(pos) {
  return (state) => {
    const node = state.doc.nodeAt(pos);
    return !!node && state.schema.marks.link.isInSet(node.marks);
  };
}

function setLinkText(text, pos, to) {
  return filter(isLinkAtPos(pos), (state, dispatch) => {
    const $pos = state.doc.resolve(pos);
    const node = state.doc.nodeAt(pos);
    const mark = state.schema.marks.link.isInSet(node.marks);
    if (node && text.length > 0 && text !== node.text) {
      const rightBound =
        to && pos !== to ? to : pos - $pos.textOffset + node.nodeSize;
      const { tr } = state;

      tr.insertText(text, pos, rightBound);
      tr.addMark(pos, pos + text.length, mark);

      if (dispatch) {
        dispatch(tr);
      }
      return true;
    }
    return false;
  });
}

export default setLinkText;
