lodash-es#noop TypeScript Examples

The following examples show how to use lodash-es#noop. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: drag.ts    From LogicFlow with Apache License 2.0 6 votes vote down vote up
constructor({
    onDragStart = noop,
    onDraging = noop,
    onDragEnd = noop,
    eventType = '',
    eventCenter = null,
    step = 1,
    isStopPropagation = true,
    model = null,
  }) {
    this.onDragStart = onDragStart;
    this.onDraging = onDraging;
    this.onDragEnd = onDragEnd;
    this.step = step;
    this.isStopPropagation = isStopPropagation;
    this.eventType = eventType;
    this.eventCenter = eventCenter;
    this.model = model;
  }
Example #2
Source File: drag.ts    From LogicFlow with Apache License 2.0 5 votes vote down vote up
function createDrag({
  onDragStart = noop,
  onDraging = noop,
  onDragEnd = noop,
  step = 1,
  isStopPropagation = true,
}) {
  let isDraging = false;
  let isStartDraging = false;
  let startX = 0;
  let startY = 0;
  let sumDeltaX = 0;
  let sumDeltaY = 0;
  function handleMouseMove(e: MouseEvent) {
    if (isStopPropagation) e.stopPropagation();
    if (!isStartDraging) return;
    isDraging = true;
    sumDeltaX += e.clientX - startX;
    sumDeltaY += e.clientY - startY;
    startX = e.clientX;
    startY = e.clientY;
    if (Math.abs(sumDeltaX) > step || Math.abs(sumDeltaY) > step) {
      const remainderX = sumDeltaX % step;
      const remainderY = sumDeltaY % step;
      const deltaX = sumDeltaX - remainderX;
      const deltaY = sumDeltaY - remainderY;
      sumDeltaX = remainderX;
      sumDeltaY = remainderY;
      onDraging({ deltaX, deltaY, event: e });
    }
  }

  function handleMouseUp(e: MouseEvent) {
    if (isStopPropagation) e.stopPropagation();
    isStartDraging = false;
    DOC.removeEventListener('mousemove', handleMouseMove, false);
    DOC.removeEventListener('mouseup', handleMouseUp, false);
    if (!isDraging) return;
    isDraging = false;
    return onDragEnd({ event: e });
  }

  function handleMouseDown(e: MouseEvent) {
    if (e.button !== LEFT_MOUSE_BUTTON_CODE) return;
    if (isStopPropagation) e.stopPropagation();

    isStartDraging = true;
    startX = e.clientX;
    startY = e.clientY;

    DOC.addEventListener('mousemove', handleMouseMove, false);
    DOC.addEventListener('mouseup', handleMouseUp, false);
    return onDragStart({ event: e });
  }

  return handleMouseDown;
}
Example #3
Source File: rich-editor.tsx    From bext with MIT License 5 votes vote down vote up
RichEditor: FC<{
  defaultHtml?: string;
  defaultReadOnly?: boolean;
  onChange?: (html: string) => void;
  className?: string;
}> = (props) => {
  const ref = useRef<HTMLDivElement>(null);
  const getProps = useMemoizedFn(() => props);

  useEffect(() => {
    const { defaultHtml, defaultReadOnly } = getProps();
    if (ref.current) {
      ref.current.innerHTML = defaultHtml || '';
      const quill = new Quill(ref.current, {
        theme: 'snow',
        modules: {
          toolbar: defaultReadOnly
            ? false
            : [
                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                [{ size: ['small', false, 'large', 'huge'] }],
                [
                  { align: [] },
                  'bold',
                  'italic',
                  'underline',
                  'strike',
                  'blockquote',
                  'code-block',
                ],
                [
                  { list: 'ordered' },
                  { list: 'bullet' },
                  { script: 'sub' },
                  { script: 'super' },
                ],
                [{ indent: '-1' }, { indent: '+1' }],
                [{ color: [] }, { background: [] }],
                ['link', 'image'],
                ['clean'],
              ],
        },
        readOnly: defaultReadOnly,
        bounds: ref.current,
      });

      const toolbar = quill.getModule('toolbar');
      if (toolbar) {
        const originImageHandler = toolbar.handlers.image;
        toolbar.handlers.image = function (...args: any[]) {
          if (confirm('选择文件(确定)/输入图片链接(取消)')) {
            originImageHandler?.call(this, ...args);
            return;
          }

          const url = prompt('请输入图片链接');
          const range = quill.getSelection();
          if (url && range) {
            quill.insertEmbed(range.index, 'image', url, Quill.sources.USER);
          }
        };
      }

      const handler = () => {
        const el = ref.current?.querySelector('.ql-editor') as HTMLDivElement;
        getProps()?.onChange?.(el.innerHTML || '');
      };
      quill.on('text-change', handler);
      return () => quill.off('text-change', handler);
    }
    return noop;
  }, []);

  return <div ref={ref} className={props.className} />;
}
Example #4
Source File: functions.spec.ts    From s-libs with MIT License 5 votes vote down vote up
describe('functions()', () => {
  it('does not include constructors', () => {
    class MyClass {
      a = 1;

      b(): number {
        return 2;
      }
    }
    expect(functions(MyClass.prototype)).toEqual(['b']);
  });

  it("doesn't call getters (production bug)", () => {
    class Gotcha {
      get error(): never {
        throw new Error('called getter');
      }
    }
    expect(() => {
      functions(Gotcha.prototype);
    }).not.toThrowError();
  });

  //
  // stolen from https://github.com/lodash/lodash
  //

  it('should return the function names of an object', () => {
    const object = { a: 'a', b: identity, c: /x/u, d: noop };
    expect(functions(object).sort()).toEqual(['b', 'd']);
  });

  it('should not include inherited functions', () => {
    function Foo(this: any): void {
      this.a = identity;
      this.b = 'b';
    }
    Foo.prototype.c = noop;

    expect(functions(new (Foo as any)())).toEqual(['a']);
  });

  it('should return an array', () => {
    const array = [1, 2, 3];
    const actual = functions(array);
    expect(isArray(actual)).toBe(true);
    expect(actual as any).not.toBe(array);
  });
});
Example #5
Source File: transform.spec.ts    From s-libs with MIT License 5 votes vote down vote up
describe('transform', () => {
  //
  // stolen from https://github.com/lodash/lodash
  //

  it('should support an `accumulator` value', () => {
    const array = [1, 2, 3];
    const object = { a: 1, b: 2, c: 3 };

    const squareAndPush = (result: number[], value: number): void => {
      result.push(value ** 2);
    };
    expect(transform(array, squareAndPush, [] as number[])).toEqual([1, 4, 9]);
    expect(transform(object, squareAndPush, [] as number[])).toEqual([1, 4, 9]);

    const squareAndSet = (
      result: ObjectWith<number>,
      value: number,
      key: number | string,
    ): void => {
      result[key] = value ** 2;
    };
    expect(transform(array, squareAndSet, {})).toEqual({ 0: 1, 1: 4, 2: 9 });
    expect(transform(object, squareAndSet, {})).toEqual({ a: 1, b: 4, c: 9 });

    testAccumulatorReturned([]);
    testAccumulatorReturned({});
    testAccumulatorReturned(null);

    function testAccumulatorReturned(accumulator: any): void {
      expect(transform(array, noop, accumulator)).toBe(accumulator);
      expect(transform(object, noop, accumulator)).toBe(accumulator);
      expect(transform(undefined, identity, accumulator)).toBe(accumulator);
    }
  });

  it('should create an empty object when given a falsey `object`', () => {
    expect(transform(undefined, identity)).toEqual({});
  });

  it('should provide correct `iteratee` arguments when transforming an array', () => {
    const spy = jasmine.createSpy();
    const object = [1, 2, 3];
    expect(transform(object, spy)).not.toBe(object);
    expect(spy.calls.first().args).toEqual([jasmine.anything(), 1, 0]);
  });

  it('should provide correct `iteratee` arguments when transforming an object', () => {
    const spy = jasmine.createSpy();
    const object = { a: 1, b: 2, c: 3 };
    expect(transform(object, spy)).not.toBe(object);
    expect(spy.calls.first().args).toEqual([jasmine.anything(), 1, 'a']);
  });

  it('can exit early when iterating arrays', () => {
    const array = [1, 2, 3];
    const values: number[] = [];

    transform(array, (_accumulator, value) => {
      values.push(value);
      return false;
    });

    expect(values).toEqual([1]);
  });

  it('can exit early when iterating arrays', () => {
    const object = { a: 1, b: 2, c: 3 };
    const values: number[] = [];

    transform(object, (_accumulator, value) => {
      values.push(value);
      return false;
    });

    expect(values).toEqual([1]);
  });
});
Example #6
Source File: onInitialize.ts    From github-deploy-center with MIT License 4 votes vote down vote up
onInitializeOvermind = ({
  state,
  effects: { storage },
  reaction,
}: Context) => {
  function sync<T>(
    getState: (state: AppState) => T,
    onValueLoaded: (value: T) => void,
    options: { nested: boolean },
    onValueChanged: (value: T) => void = noop
  ) {
    const key = getState.toString().replace(/^.*?\./, 'gdc.')
    reaction(
      getState,
      (data) => {
        onValueChanged(data)
        storage.save(key, data)
      },
      {
        nested: options.nested,
      }
    )
    const value = storage.load(key)
    if (value) {
      onValueLoaded(value)
    }
  }

  sync(
    (state) => state.token,
    (token) => {
      state.token = token || ''
    },
    { nested: false },
    (token) => {
      graphQLApi.setToken(token)
      restApi.setToken(token)
    }
  )

  sync(
    (state) => state.applicationsById,
    (data) => {
      state.applicationsById = pipe(
        ApplicationsByIdCodec.decode(data),
        getOrElse((e) => {
          console.error(e)
          return {}
        })
      )
    },
    { nested: true }
  )

  sync(
    (state) => state.selectedApplicationId,
    (id) => (state.selectedApplicationId = id),
    { nested: false }
  )

  sync(
    (state) => state.appSettings,
    (data) => {
      state.appSettings = pipe(
        AppSettingsCodec.decode(data),
        getOrElse((e) => {
          console.error(e)
          return defaultAppSettings
        })
      )
    },
    { nested: true }
  )

  sync(
    (state) => state.pendingDeployments,
    (data) => {
      state.pendingDeployments = pipe(
        PendingDeploymentsCodec.decode(data),
        getOrElse((e) => {
          console.error(e)
          return {} as Record<string, string>
        }),
        (data) => mapValues(data, (date) => dayjs(date))
      )
    },
    { nested: true }
  )
}