html/src/insert.js
/**
 * Insert annotation elements for matches within a book's HTML content.
 * @param {InsertOptions} opt
 * @return {InsertInfo}
 */
Insert annotation elements for matches within a book's HTML content.
Insert annotation elements for matches within a book ' s HTML content .
function insert(opt) {
  const { action, mode, matches, type = 'annotation', key } = opt;
  let { html } = opt;
  const _action = action(key, type);
  const wrap = (() => {
    switch (mode) {
      case INSERT_MODES.WRAP.LINK:
        return [`<a class="xy-${type}" href="${_action}">`, `</a>`];
      case INSERT_MODES.WRAP.ONCLICK:
        return [`<span class="xy-${type}" onclick="${_action}">`, `</span>`];
      case INSERT_MODES.REFERENCE.LINK:
        return [
          ``,
          `<a class="xy-${type}" href="${_action}"><sup>xy</sup></a>`
        ];
      case INSERT_MODES.REFERENCE.ONCLICK:
        return [
          ``,
          `<span class="xy-${type}" onclick="${action(
            type,
            key
          )}"><sup>xy</sup></span>`
        ];
      default:
        throw 'Invalid `mode`';
    }
  })();
  const wrapLength = wrap[0].length + wrap[1].length;
  const inserts = [];
  let offset = 0;
  matches.forEach(match => {
    const start = match.start + offset;
    const end = match.end + offset;
    html =
      html.substring(0, start) +
      wrap[0] +
      html.substring(start, end) +
      wrap[1] +
      html.substring(end);
    offset += wrapLength;
    inserts.push(end);
  });
  return { html, wrapLength, inserts };
}
function insert ( opt ) { const { action , mode , matches , type = 'annotation' , key } = opt ; let { html } = opt ; const _action = action ( key , type ) ; const wrap = ( ( ) => { switch ( mode ) { case INSERT_MODES . WRAP . LINK : return [ ` ${ type } ${ _action } ` , ` ` ] ; case INSERT_MODES . WRAP . ONCLICK : return [ ` ${ type } ${ _action } ` , ` ` ] ; case INSERT_MODES . REFERENCE . LINK : return [ ` ` , ` ${ type } ${ _action } ` ] ; case INSERT_MODES . REFERENCE . ONCLICK : return [ ` ` , ` ${ type } ${ action ( type , key ) } ` ] ; default : throw 'Invalid `mode`' ; } } ) ( ) ; const wrapLength = wrap [ 0 ] . length + wrap [ 1 ] . length ; const inserts = [ ] ; let offset = 0 ; matches . forEach ( match => { const start = match . start + offset ; const end = match . end + offset ; html = html . substring ( 0 , start ) + wrap [ 0 ] + html . substring ( start , end ) + wrap [ 1 ] + html . substring ( end ) ; offset += wrapLength ; inserts . push ( end ) ; } ) ; return { html , wrapLength , inserts } ; }
Insert annotation elements for matches within a book's HTML content.
Insert annotation elements for matches within a book ' s HTML content .
/** @type {string} */ // Offset required since we're manipulating the HTML and therefore // changing the length / indexes /** @type {number} */ /** @type {number} */