Beispiel #1
0
function decorate(item) {
  item = Object.assign({}, item, {
    _text: utils.makeTextHtml(item.text, item.mode === 'find' ? item.solutions : item.selections)
  })

  if (item.mode === 'highlight') {
    const solutions = cloneDeep(item.solutions)

    solutions.forEach(solution => {
      let answers = []
      solution.answers.forEach(answer => {
        answers.push(Object.assign({}, answer, {_answerId: makeId()}))
      })
      solution.answers = answers
    })

    const colors = cloneDeep(item.colors)

    colors.forEach(color => {
      color._autoOpen = false
    })

    item = Object.assign({}, item, {solutions, colors})
  }

  //setting true positions here
  let toSort = item.mode === 'find' ? item.solutions : item.selections

  if (!toSort) {
    return item
  }

  toSort = cloneDeep(toSort)
  toSort.sort((a, b) => a.begin - b.begin)
  let idx = 0

  toSort.forEach(element => {
    //this is where the word really start
    let begin = utils.getHtmlLength(element) * idx + element.begin + utils.getFirstSpan(element).length
    let selection = utils.getSelectionText(item, element.selectionId || element.id)
    element._displayedBegin = begin
    element._displayedEnd = begin + selection.length
    idx++
  })

  const newData = item.mode === 'find' ? {solutions: toSort} : {selections: toSort}

  item = Object.assign({}, item, newData)

  return item
}
Beispiel #2
0
export const getSlider = state => {
  let permission = state.auth.permission
  let slider = clone(state.slider)
  let menus = slider.menus
  filterMenus(menus, permission, menuRelPermission)
  return slider
}
Beispiel #3
0
 this._onMessage = function(msg) {
   // Skip if message is not addressing this document
   if (msg.documentId !== this.documentId) {
     return false;
   }
   // clone the msg to make sure that the original does not get altered
   msg = cloneDeep(msg);
   switch (msg.type) {
     case 'syncDone':
       this.syncDone(msg);
       break;
     case 'syncError':
       this.syncError(msg);
       break;
     case 'update':
       this.update(msg);
       break;
     case 'disconnectDone':
       this.disconnectDone(msg);
       break;
     case 'error':
       this.error(msg);
       break;
     default:
       console.error('CollabSession: unsupported message', msg.type, msg);
       return false;
   }
   return true;
 };
 this.apply = function(op) {
   if (op.type === ObjectOperation.NOP) return;
   else if (op.type === ObjectOperation.CREATE) {
     // clone here as the operations value must not be changed
     this.super.create.call(this, cloneDeep(op.val));
   } else if (op.type === ObjectOperation.DELETE) {
     this.super.delete.call(this, op.val.id);
   } else if (op.type === ObjectOperation.UPDATE) {
     var oldVal = this.get(op.path);
     var diff = op.diff;
     if (op.propertyType === 'array') {
       if (! (diff instanceof ArrayOperation) ) {
         diff = ArrayOperation.fromJSON(diff);
       }
       // array ops work inplace
       diff.apply(oldVal);
     } else if (op.propertyType === 'string') {
       if (! (diff instanceof TextOperation) ) {
         diff = TextOperation.fromJSON(diff);
       }
       var newVal = diff.apply(oldVal);
       this.super.set.call(this, op.path, newVal);
     } else {
       throw new Error("Unsupported type for operational update.");
     }
   } else if (op.type === ObjectOperation.SET) {
     this.super.set.call(this, op.path, op.val);
   } else {
     throw new Error("Illegal state.");
   }
   this.emit('operation:applied', op, this);
 };
function byId(state = {}, action) {
  switch (action.type) {
    case ENTRIES_LOADED: {
      const nextState = { ...state };
      action.payload.forEach(entry => {
        nextState[entry.id] = entry;
      });
      return nextState;
    }
    case ENTRIES_UPDATE:
      return {
        ...state,
        [action.payload.id]: clone(action.payload)
      };
    case ENTRIES_CREATE:
      return {
        ...state,
        [action.payload.id]: action.payload
      };
    case ENTRIES_DELETE: {
      const nextState = { ...state };
      delete nextState[action.payload];
      return nextState;
    }
    default:
      return state;
  }
}
Beispiel #6
0
/**
 * Asynchronously normalizes an object shaped like a post. Works on a copy of the post and does not mutate the original post.
 * @param  {object} post A post shaped object, generally returned by the API
 * @param {array} transforms An array of transforms to perform. Each transformation should be a function
 * that takes a post and a node-style callback. It should mutate the post and call the callback when complete.
 * @param {function} callback A node-style callback, invoked when the transformation is complete, or when the first error occurs.
 * If successful, the callback is invoked with `(null, theMutatedPost)`
 */
function normalizePost( post, transforms, callback ) {
	if ( ! callback ) {
		throw new Error( 'must supply a callback' );
	}
	if ( ! post || ! transforms ) {
		debug( 'no post or no transform' );
		callback( null, post );
		return;
	}

	let normalizedPost = cloneDeep( post ),
		postDebug = debugForPost( post );

	postDebug( 'running transforms' );

	async.eachSeries(
		transforms, function( transform, transformCallback ) {
			postDebug( 'running transform ' + ( transform.name || 'anonymous' ) );
			transform( normalizedPost, transformCallback );
		}, function( err ) {
			postDebug( 'transforms complete' );
			if ( err ) {
				callback( err );
			} else {
				callback( null, normalizedPost );
			}
		}
	);
}
Beispiel #7
0
    it('does not mutate the entities', () => {
      const data = getNormalizedEntities();
      const normalizedEntities = cloneDeep(data.entities);

      denormalize('1', data.entities, articleSchema);
      expect(normalizedEntities).to.be.eql(data.entities);
    });
 /**
  * 设置对话的自定义属性
  * @since 3.2.0
  * @param {String} key 属性的键名,'x' 对应 Conversation 表中的 x 列,支持使用 'x.y.z' 来修改对象的部分字段。
  * @param {Any} value 属性的值
  * @return {Conversation} self
  * @example
  *
  * // 设置对话的 color 属性
  * conversation.set('color', {
  *   text: '#000',
  *   background: '#DDD',
  * });
  * // 设置对话的 color.text 属性
  * conversation.set('color.text', '#333');
  */
 set(key, value) {
   this._debug(`set [${key}]: ${value}`);
   const pendingAttributes = internal(this).pendingAttributes;
   const pendingKeys = Object.keys(pendingAttributes);
   // suppose pendingAttributes = { 'a.b': {} }
   // set 'a' or 'a.b': delete 'a.b'
   const re = new RegExp(`^${key}`);
   const childKeys = pendingKeys.filter(re.test.bind(re));
   childKeys.forEach((k) => {
     delete pendingAttributes[k];
   });
   if (childKeys.length) {
     pendingAttributes[key] = value;
   } else {
     // set 'a.c': nothing to do
     // set 'a.b.c.d': assign c: { d: {} } to 'a.b'
     // CAUTION: non-standard API, provided by core-js
     const parentKey = Array.find(pendingKeys, k => key.indexOf(k) === 0); // 'a.b'
     if (parentKey) {
       setValue(pendingAttributes[parentKey], key.slice(parentKey.length + 1), value);
     } else {
       pendingAttributes[key] = value;
     }
   }
   // build currentAttributes
   internal(this).currentAttributes = Object.keys(pendingAttributes)
     .reduce(
       (target, k) => setValue(target, k, pendingAttributes[k]),
       cloneDeep(this._attributes)
     );
   return this;
 }
Beispiel #9
0
export const moveArrayItem = (state, namePrefix, srcInd, targetInd) => {
  let tmpState = cloneDeep(state);
  let arr = eval(`tmpState.${namePrefix}`);
  if (!_.isArray(arr)) return tmpState.metadata;
  arr.splice(targetInd, 0, arr.splice(srcInd, 1)[0]);
  return tmpState.metadata;
};
Beispiel #10
0
    it("does not mutate the entities", () => {
      const data = getNormalizedEntities()
      const normalizedEntities = cloneDeep(data.entities)

      denormalize("1", data.entities, articleSchema)
      expect(normalizedEntities).to.be.eql(data.entities);
    });
  saveSearch(destination) {
    const { items } = this.getStorageObject();

    const found = find(items, oldItem =>
      isEqual(
        getNameLabel(destination.item.properties),
        getNameLabel(oldItem.item.properties),
      ),
    );

    const timestamp = moment().unix();
    if (found != null) {
      found.count += 1;
      found.lastUpdated = timestamp;
      found.item = cloneDeep(destination.item);
    } else {
      items.push({
        count: 1,
        lastUpdated: timestamp,
        ...destination,
      });
    }

    setOldSearchesStorage({
      version: STORE_VERSION,
      items: orderBy(items, 'count', 'desc'),
    });

    this.emitChange(destination);
  }
test('Check revision  - good', t => {
  const rq = cloneDeep(req);
  rq.params.revision = 123;

  return utils.revision(rq).then(result => {
    t.true(result, 'Good revision type returns true');
  });
});
test('No revision - good', t => {
  const rq = cloneDeep(req);
  delete rq.params.revision;

  return utils.revision(rq).then(result => {
    t.true(result, 'Nonexistent revision returns true');
  });
});
Beispiel #14
0
  [ANNOUNCE_ADD]: (state, action) => {
    const newState = cloneDeep(state)

    // add new announce to the list
    newState.posts.push(action.announce)

    return newState
  },
Beispiel #15
0
function CreateAndSetObject(newState) {
    if (newState.now in newState) {
        return newState;
    }
    newState[newState.now] = cloneDeep(sampleObject);
    newState.total += newState[newState.now].periods.length;
    return newState;
}
test('Check revision id-not blank', t => {
  const rq = cloneDeep(req);

  return utils.revision(rq).catch(err => {
    t.is(typeof err, 'string', 'Blank revision fails');
    t.is(err, 'Revision must be a number', 'Should fail with a message');
  });
});
Beispiel #17
0
export const addField = (state, namePrefix) => {
  let tmpState = cloneDeep(state);
  let field = eval(`tmpState.${namePrefix}`);
  if (field === undefined) return tmpState.metadata;
  if (_.isArray(field)) field.push('');
  else field['New field ' + state.new_field_count] = '';
  return tmpState.metadata;
};
test('Check revision id-not missing', t => {
  const rq = cloneDeep(req);
  delete rq.params.revision;

  return utils.revision(rq).catch(err => {
    t.is(typeof err, 'string', 'Non-number revision fails');
    t.is(err, 'Revision must be a number', 'Should fail with a message');
  });
});
test('Type exists in all types', t => {
  const rq = cloneDeep(req);

  return utils.type(rq).then(result => {
    t.is(typeof result, 'object', 'Existing type returns an object');
    t.is(result.id, 'services', 'Type object contains merged content type');
    t.true(Array.isArray(result.attributes), 'Type object contains attribute array');
  });
});
test('Check type exists in CMS', t => {
  const rq = cloneDeep(req);
  rq.params.type = 'foo';

  return utils.type(rq).catch(err => {
    t.is(typeof err, 'string', 'Non-existent type fails');
    t.is(err, 'Content Type \'foo\' not found', 'Should fail with message');
  });
});
test('Check type is string', t => {
  const rq = cloneDeep(req);
  rq.params.type = [];

  return utils.type(rq).catch(err => {
    t.is(typeof err, 'string', 'Non-string fails');
    t.is(err, 'Content Type \'(no type given)\' not found', 'error message');
  });
});
Beispiel #22
0
 forEach(defaultChildren, (child) => {
   const childId = getId(data);
   changes[childId] = Object.assign(cloneDeep(child), {
     parent: sourceId,
     id: childId
   });
   changes[sourceId].children = changes[sourceId].children || [];
   changes[sourceId].children.push(childId);
 });
test('URL checks type exists in CMS', t => {
  const rq = cloneDeep(req);
  rq.params.type = 'foo';

  return middleware(rq, {}, next).then(err => {
    t.is(err.message, 'Content Type \'foo\' not found', 'Should fail with error object');
    t.is(err.safe, '/content', 'Should have a safe url');
    t.is(err.status, 404, 'Should be a 404');
  });
});
test('URL checks id is uuid', t => {
  const rq = cloneDeep(req);
  rq.params.id = 'foo';

  return middleware(rq, {}, next).then(err => {
    t.is(err.message, 'Content ID must be in UUID format', 'Should fail with message');
    t.is(err.safe, '/content', 'Should have a safe url');
    t.is(err.status, 404, 'Should be a 404');
  });
});
test('URL checks id, moves on when missing', t => {
  const rq = cloneDeep(req);
  delete rq.params.id;

  return middleware(rq, {}, next).then(() => {
    t.pass();
  }).catch(() => {
    t.fail();
  });
});
test('URL checks type has existing workflow in CMS', t => {
  const rq = cloneDeep(req);
  rq.content.types[0].workflow = 'foo';

  return middleware(rq, {}, next).then(err => {
    t.is(err.message, 'Workflow \'foo\' for Content Type \'Services\' not found', 'Should fail with message');
    t.is(err.safe, '/content', 'Should have a safe url');
    t.is(err.status, 404, 'Should be a 404');
  });
});
module.exports = function prepareCircularViewData(sequenceData) {
    var clonedSeqData = cloneDeep(sequenceData)
    annotationTypes.forEach(function(annotationType){
        if (annotationType !== 'cutsites') {
            var maxYOffset = getYOffsetsForPotentiallyCircularRanges(clonedSeqData[annotationType]).maxYOffset;
            clonedSeqData[annotationType].maxYOffset = maxYOffset;
        }
    });
    return clonedSeqData;
}
test('URL checks revision is number', t => {
  const rq = cloneDeep(req);
  rq.params.id = uuid.v4();
  rq.params.revision = 'foo';

  return middleware(rq, {}, next).then(err => {
    t.is(err.message, 'Revision must be a number', 'Should fail with message');
    t.is(err.safe, '/content', 'Should have a safe url');
    t.is(err.status, 404, 'Should be a 404');
  });
});
Beispiel #29
0
  [ANNOUNCE_FORM_UPDATE]: (state, action) => {
    const newData = cloneDeep(state.data)
    set(newData, action.prop, action.value)

    return {
      validating: false,
      pendingChanges: true,
      errors: validate(newData),
      data: newData
    }
  }
test('URL works with CMS as it is configured', t => {
  const rq2 = cloneDeep(req);
  rq2.params.id = uuid.v4();
  rq2.params.revision = 2345;

  return middleware(rq2, {}, next).then(() => {
    t.pass();
  }).catch(() => {
    t.fail();
  });
});