lodash#noop TypeScript Examples

The following examples show how to use lodash#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: Multitoggle.tsx    From nextclade with MIT License 6 votes vote down vote up
export function Multitoggle({ values, value, onChange, itemWidth = 45, ...restProps }: MultitoggleProps) {
  const { selectionLeftPercent, selectionWidthPx, totalWidth } = useMemo(() => {
    return {
      selectionLeftPercent: (values.indexOf(value) / values.length) * 100,
      selectionWidthPx: itemWidth,
      totalWidth: itemWidth * values.length,
    }
  }, [itemWidth, value, values])

  return (
    <Switch $width={totalWidth} {...restProps}>
      {values.map((val) => {
        return (
          <span key={val}>
            <SwitchRadio type="radio" name="switch" checked={val === value} onChange={noop} />
            <ClickableLabel value={val} onChange={onChange} itemWidth={itemWidth} />
          </span>
        )
      })}
      <SwitchSelection $leftPercent={selectionLeftPercent} $widthPx={selectionWidthPx} />
    </Switch>
  )
}
Example #2
Source File: drag.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
DragableList = ({
  dataSource,
  handleSort,
  prefixCls: customPrefixCls,
  wrapStyle,
  width,
  height,
  onSelect = noop,
  onRemove = noop,
  selected,
}: any) => {
  const prefixCls = usePrefixCls('list-legacy', customPrefixCls);
  const [data, setData] = useState(dataSource);

  useEffect(() => {
    setData(dataSource);
  }, [dataSource]);

  const innerHandleSort = (steps: any) => {
    const combineDashbord = unionBy(steps, dataSource, 'value');
    if (handleSort) {
      handleSort(combineDashbord);
    }
    setData(combineDashbord);
  };

  return (
    <div className={`${prefixCls}-wrapper`} style={{ ...wrapStyle, width, height }}>
      <Sortable
        collection={data}
        onSorted={innerHandleSort}
        template={<SelectedItem selected={selected} onSelect={onSelect} onRemove={onRemove} collapsed={false} />}
      />
    </div>
  );
}
Example #3
Source File: fixture.ts    From ts-di-starter with MIT License 6 votes vote down vote up
createFixture = () => {
  sinon.restore();

  const config = { port: 9001, stripeWebhookSecret: 'foo', slackSigningSecret: 'foo' };
  const services = { limiters: {}, responseBuilder: { wrap: (func) => func } } as any;
  const middleware = ServiceManager.buildExpressMiddleware(config as any, {} as any, services);
  const controllers = ServiceManager.buildExpressControllers(config as any, {} as any, services);

  return {
    config,
    start: noop,
    stop: noop,
    expressMiddleware: traverseObject(middleware, true),
    expressControllers: traverseObject(controllers, false),
    clients: {},
  };
}
Example #4
Source File: developHelper.ts    From next-core with GNU General Public License v3.0 6 votes vote down vote up
developHelper = {
  asyncProcessBrick(brickConf: BrickConf): Promise<void> {
    return asyncProcessBrick(
      brickConf,
      brickTemplateRegistry,
      _dev_only_getTemplatePackages()
    );
  },
  LocationContext,
  mountTree,
  unmountTree,
  afterMountTree,
  getBrickPackages: _dev_only_getBrickPackages,
  getTemplatePackages: _dev_only_getTemplatePackages,
  getStoryboards: _dev_only_getStoryboards,
  loadEditorBricks: _dev_only_loadEditorBricks,
  loadDynamicBricksInBrickConf: _dev_only_loadDynamicBricksInBrickConf,
  getFakeKernel: _dev_only_getFakeKernel,
  /** @deprecated Keep it for backward-compatibility. */
  checkoutTplContext: noop,
  updateStoryboard: _dev_only_updateStoryboard,
  updateTemplatePreviewSettings: _dev_only_updateTemplatePreviewSettings,
  updateSnippetPreviewSettings: _dev_only_updateSnippetPreviewSettings,
}
Example #5
Source File: interval.ts    From qiankun with MIT License 6 votes vote down vote up
/**
 * 定时器 patch,设置定时器时自动记录定时器 id,清除定时器时自动删除已清除的定时器 id,释放 patch 时自动清除所有未被清除的定时器,并恢复定时器方法
 * @param global = windowProxy
 */
export default function patch(global: Window) {
  let intervals: number[] = [];

  // 清除定时器,并从 intervals 中清除已经清除的 定时器 id
  global.clearInterval = (intervalId: number) => {
    intervals = intervals.filter(id => id !== intervalId);
    return rawWindowClearInterval(intervalId);
  };

  // 设置定时器,并记录定时器的 id
  global.setInterval = (handler: Function, timeout?: number, ...args: any[]) => {
    const intervalId = rawWindowInterval(handler, timeout, ...args);
    intervals = [...intervals, intervalId];
    return intervalId;
  };

  // 清除所有的定时器,并恢复定时器方法
  return function free() {
    intervals.forEach(id => global.clearInterval(id));
    global.setInterval = rawWindowInterval;
    global.clearInterval = rawWindowClearInterval;

    return noop;
  };
}
Example #6
Source File: module.ts    From redux-with-domain with MIT License 6 votes vote down vote up
// internal API for create KOP module
export default function createModule(
  namespace: string,
  pkg: ModuleOption,
  type: symbol
) {
  const module = initModule(pkg, namespace, type) as any

  initInitialState(module, pkg)

  initSelectors(module, pkg, namespace, DEFAULT_MODULE)

  const { actions, effects, _reducers, event } = initActions(
    module,
    pkg,
    namespace,
    DEFAULT_MODULE,
    noop
  )

  module.actions = actions

  if (effects) {
    module.effects = effects
  }

  module._reducers = _reducers
  module.event = event

  return module
}
Example #7
Source File: mock.tsx    From pancake-toolkit with GNU General Public License v3.0 6 votes vote down vote up
ItemsMock: DropdownMenuItems[] = [
  {
    label: "Exchange",
    href: "/swap",
  },
  {
    label: "Liquidity",
    href: "/pool",
  },
  {
    label: "LP Migration",
    href: "https://v1exchange.pancakeswap.finance/#/migrate",
    type: DropdownMenuItemType.EXTERNAL_LINK,
  },
  {
    type: DropdownMenuItemType.DIVIDER,
  },
  {
    label: "Disconnect",
    onClick: noop,
    type: DropdownMenuItemType.BUTTON,
  },
]
Example #8
Source File: index.stories.tsx    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
Default.args = {
  items: footerLinks,
  isDark: true,
  toggleTheme: noop,
  langs,
  setLang: noop,
  currentLang: "EN",
  vvsPriceUsd: 0.023158668932877668,
  buyVvsLabel: "Buy VVS",
};
Example #9
Source File: Form.stories.tsx    From frontend.ro with MIT License 6 votes vote down vote up
Components = () => (
  <Form withStyles onSubmit={noop}>
    <section>
      <h4> Checkbox </h4>
      <Checkbox>
        Are you sure?
      </Checkbox>
    </section>
    <section>
      <h4> Input with icon </h4>
      <InputWithIcon type="text">
        <FontAwesomeIcon icon={faCheck} />
      </InputWithIcon>
    </section>
    <section>
      <h4> Password reveal </h4>
      <PasswordReveal />
    </section>
  </Form>
)
Example #10
Source File: mock.tsx    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
ItemsMock: DropdownMenuItems[] = [
  {
    label: "Exchange",
    href: "/swap",
  },
  {
    label: "Liquidity",
    href: "/pool",
  },
  {
    label: "LP Migration",
    href: "https://v1exchange.vvs.finance/#/migrate",
    type: DropdownMenuItemType.EXTERNAL_LINK,
  },
  {
    type: DropdownMenuItemType.DIVIDER,
  },
  {
    label: "Disconnect",
    onClick: noop,
    type: DropdownMenuItemType.BUTTON,
  },
]
Example #11
Source File: MetricAssignmentsPanel.test.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
test('throws an error when some metrics not resolvable', () => {
  const metrics = Fixtures.createMetrics(1)
  const experiment = Fixtures.createExperimentFull()
  const experimentReloadRef: React.MutableRefObject<() => void> = { current: noop }

  // Note: This console.error spy is mainly used to suppress the output that the
  // `render` function outputs.
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  const consoleErrorSpy = jest.spyOn(global.console, 'error').mockImplementation(() => {})
  try {
    render(<MetricAssignmentsPanel {...{ experiment, metrics, experimentReloadRef }} />)
    expect(false).toBe(true) // Should never be reached
  } catch (err) {
    expect(consoleErrorSpy).toHaveBeenCalled()
  } finally {
    consoleErrorSpy.mockRestore()
  }
})
Example #12
Source File: index.stories.tsx    From pancake-toolkit with GNU General Public License v3.0 6 votes vote down vote up
Default.args = {
  items: footerLinks,
  isDark: true,
  toggleTheme: noop,
  langs,
  setLang: noop,
  currentLang: "EN",
  cakePriceUsd: 0.023158668932877668,
  buyCakeLabel: "Buy CAKE",
};
Example #13
Source File: for-own-right.spec.ts    From s-libs with MIT License 5 votes vote down vote up
describe('forOwnRight()', () => {
  //
  // stolen from https://github.com/lodash/lodash
  //

  it('can exit early when iterating arrays', () => {
    const spy = jasmine.createSpy().and.returnValue(false);
    forOwnRight([1, 2, 3], spy);
    expectSingleCallAndReset(spy, 3, '2');
  });

  it('can exit early when iterating objects', () => {
    const spy = jasmine.createSpy().and.returnValue(false);
    forOwnRight({ a: 1, b: 2, c: 3 }, spy);
    expect(spy).toHaveBeenCalledTimes(1);
  });

  it('should iterate over `length` properties', () => {
    const logger = jasmine.createSpy();

    forOwnRight({ 0: 'zero', 1: 'one', length: 2 }, logger);

    expect(logger.calls.allArgs()).toContain([2, 'length']);
  });

  it('should provide correct iteratee arguments', () => {
    const spy = jasmine.createSpy();
    forOwnRight([1, 2, 3], spy);
    expect(spy.calls.first().args).toEqual([3, '2']);
  });

  it('should treat sparse arrays as dense', () => {
    const array = [1];
    array[2] = 3;
    const spy = jasmine.createSpy();

    forOwnRight(array, spy);

    expectCallsAndReset(spy, [3, '2'], [1, '0']);
  });

  it('should return the collection', () => {
    const array = [1, 2, 3];

    expect(forOwnRight(array, noop)).toBe(array);
  });

  it('should ignore changes to `length`', () => {
    const array = [1];
    const spy = jasmine.createSpy().and.callFake(() => {
      array.push(2);
      return true;
    });

    forOwnRight(array, spy);

    expect(spy).toHaveBeenCalledTimes(1);
  });

  it('should ignore added `object` properties', () => {
    const object: any = { a: 1 };
    const spy = jasmine.createSpy().and.callFake(() => {
      object.b = 2;
      return true;
    });

    forOwnRight(object, spy);

    expect(spy).toHaveBeenCalledTimes(1);
  });
});
Example #14
Source File: ConclusionsPanel.test.tsx    From abacus with GNU General Public License v2.0 5 votes vote down vote up
experimentReloadRef: React.MutableRefObject<() => void> = { current: noop }
Example #15
Source File: option.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
SelectOption = (props: OptionProps) => {
  const {
    isSelected = false,
    className = '',
    isMultiple = false,
    allowDuplicate = false,
    disabled = false,
    style,
    hasGroupIcon,
    showGroupCheckBox,
    onSelect,
    onClick,
    option,
    getPopupContainer,
    placement,
    title,
    children,
  } = props;

  const prefixCls = usePrefixCls('select-legacy');
  const ref = useRef(null);
  const handleSelect = useCallback(
    (e: React.MouseEvent<HTMLDivElement>) => {
      e.stopPropagation();
      e.preventDefault();
      if (onSelect) {
        onSelect(option);
      }
      if (onClick) {
        onClick(option);
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [option]
  );

  const renderContent = () => (
    <div
      className={classnames(`${prefixCls}-option`, className, {
        multiple: isMultiple,
        selected: isSelected,
        indented: hasGroupIcon,
        disabled,
      })}
      style={style}
      onClick={disabled ? undefined : handleSelect}
      title={title}
      ref={ref}
      aria-hidden="true"
    >
      {showGroupCheckBox && <span style={{ width: 25 }} />}
      {isMultiple && !allowDuplicate && (
        <Checkbox style={{ fontSize: 0 }} checked={isSelected} disabled={disabled} onChange={noop} />
      )}
      {children}
    </div>
  );

  if (option.tooltip) {
    return (
      <Tooltip title={option.tooltip} placement={placement} getContainer={getPopupContainer}>
        {renderContent()}
      </Tooltip>
    );
  }

  return renderContent();
}
Example #16
Source File: apis.ts    From qiankun with MIT License 5 votes vote down vote up
/**
 * 注册微应用,基于路由配置
 * @param apps = [
 *  {
 *    name: 'react16',
 *    entry: '//localhost:7100',
 *    container: '#subapp-viewport',
 *    loader,
 *    activeRule: '/react16'
 *  },
 *  ...
 * ]
 * @param lifeCycles = { ...各个生命周期方法对象 }
 */
export function registerMicroApps<T extends object = {}>(
  apps: Array<RegistrableApp<T>>,
  lifeCycles?: FrameworkLifeCycles<T>,
) {
  // 防止微应用重复注册,得到所有没有被注册的微应用列表
  const unregisteredApps = apps.filter(app => !microApps.some(registeredApp => registeredApp.name === app.name));

  // 所有的微应用 = 已注册 + 未注册的(将要被注册的)
  microApps = [...microApps, ...unregisteredApps];

  // 注册每一个微应用
  unregisteredApps.forEach(app => {
    // 注册时提供的微应用基本信息
    const { name, activeRule, loader = noop, props, ...appConfig } = app;

    // 调用 single-spa 的 registerApplication 方法注册微应用
    registerApplication({
      // 微应用名称
      name,
      // 微应用的加载方法,Promise<生命周期方法组成的对象>
      app: async () => {
        // 加载微应用时主应用显示 loading 状态
        loader(true);
        // 这句可以忽略,目的是在 single-spa 执行这个加载方法时让出线程,让其它微应用的加载方法都开始执行
        await frameworkStartedDefer.promise;

        // 核心、精髓、难点所在,负责加载微应用,然后一大堆处理,返回 bootstrap、mount、unmount、update 这个几个生命周期
        const { mount, ...otherMicroAppConfigs } = await loadApp(
          // 微应用的配置信息
          { name, props, ...appConfig },
          // start 方法执行时设置的配置对象
          frameworkConfiguration,
          // 注册微应用时提供的全局生命周期对象
          lifeCycles,
        );

        return {
          mount: [async () => loader(true), ...toArray(mount), async () => loader(false)],
          ...otherMicroAppConfigs,
        };
      },
      // 微应用的激活条件
      activeWhen: activeRule,
      // 传递给微应用的 props
      customProps: props,
    });
  });
}
Example #17
Source File: useApproveConfirmTransaction.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
useApproveConfirmTransaction = ({
  onApprove,
  onConfirm,
  onRequiresApproval,
  onSuccess = noop,
  onApproveSuccess = noop,
}: ApproveConfirmTransaction) => {
  const { t } = useTranslation()
  const { account } = useWeb3React()
  const [state, dispatch] = useReducer(reducer, initialState)
  const handlePreApprove = useRef(onRequiresApproval)
  const { toastError } = useToast()

  // Check if approval is necessary, re-check if account changes
  useEffect(() => {
    if (account && handlePreApprove.current) {
      handlePreApprove.current().then((result) => {
        if (result) {
          dispatch({ type: 'requires_approval' })
        }
      })
    }
  }, [account, handlePreApprove, dispatch])

  return {
    isApproving: state.approvalState === 'loading',
    isApproved: state.approvalState === 'success',
    isConfirming: state.confirmState === 'loading',
    isConfirmed: state.confirmState === 'success',
    handleApprove: async () => {
      try {
        const tx = await onApprove()
        dispatch({ type: 'approve_sending' })
        const receipt = await tx.wait()
        if (receipt.status) {
          dispatch({ type: 'approve_receipt' })
          onApproveSuccess({ state, receipt })
        }
      } catch (error) {
        dispatch({ type: 'approve_error' })
        toastError(t('Error'), t('Please try again. Confirm the transaction and make sure you are paying enough gas!'))
      }
    },
    handleConfirm: async () => {
      dispatch({ type: 'confirm_sending' })
      try {
        const tx = await onConfirm()
        const receipt = await tx.wait()
        if (receipt.status) {
          dispatch({ type: 'confirm_receipt' })
          onSuccess({ state, receipt })
        }
      } catch (error) {
        dispatch({ type: 'confirm_error' })
        toastError(t('Error'), t('Please try again. Confirm the transaction and make sure you are paying enough gas!'))
      }
    },
  }
}
Example #18
Source File: dynamicAppend.ts    From qiankun with MIT License 5 votes vote down vote up
/**
 * 多例模式下增强 createElement 方法,让其除了具有创建元素功能之外,还可以劫持创建 script、link、style 这三个元素的情况
 * @param appName 微应用名称
 * @param appWrapperGetter 
 * @param singular 
 * @param proxy 
 * @param dynamicStyleSheetElements 
 */
function patchDocumentCreateElement(
  appName: string,
  appWrapperGetter: () => HTMLElement | ShadowRoot,
  singular: boolean,
  proxy: Window,
  dynamicStyleSheetElements: HTMLStyleElement[],
) {
  // 如果是单例模式直接 return
  if (singular) {
    return noop;
  }

  // 以微应用运行时的 proxy 为 key,存储该微应用的一些信息,比如 名称、proxy、微应用模版、自定义样式表等
  proxyContainerInfoMapper.set(proxy, { appName, proxy, appWrapperGetter, dynamicStyleSheetElements, singular });

  // 第一个微应用初始化时会执行这段,增强 createElement 方法,让其除了可以创建元素之外,还可以劫持 script、link、style 三个标签的创建动作
  if (Document.prototype.createElement === rawDocumentCreateElement) {
    Document.prototype.createElement = function createElement<K extends keyof HTMLElementTagNameMap>(
      this: Document,
      tagName: K,
      options?: ElementCreationOptions,
    ): HTMLElement {
      // 创建元素
      const element = rawDocumentCreateElement.call(this, tagName, options);
      // 劫持 script、link、style 三种标签
      if (isHijackingTag(tagName)) {
        // 下面这段似乎没啥用,因为没发现有哪个地方执行设置,proxyContainerInfoMapper.set(this[attachDocProxySysbol])
        // 获取这个东西的值,然后将该值添加到 element 对象上,以 attachElementContainerSymbol 为 key
        const proxyContainerInfo = proxyContainerInfoMapper.get(this[attachDocProxySymbol]);
        if (proxyContainerInfo) {
          Object.defineProperty(element, attachElementContainerSymbol, {
            value: proxyContainerInfo,
            enumerable: false,
          });
        }
      }

      // 返回创建的元素
      return element;
    };
  }

  // 后续的微应用初始化时直接返回该函数,负责还原 createElement 方法
  return function unpatch(recoverPrototype: boolean) {
    proxyContainerInfoMapper.delete(proxy);
    if (recoverPrototype) {
      Document.prototype.createElement = rawDocumentCreateElement;
    }
  };
}
Example #19
Source File: config.ts    From pancake-toolkit with GNU General Public License v3.0 5 votes vote down vote up
userMenulinks: DropdownMenuItems[] = [
  {
    label: "Wallet",
    onClick: noop,
    type: DropdownMenuItemType.BUTTON,
  },
  {
    label: "Transactions",
    type: DropdownMenuItemType.BUTTON,
  },
  {
    type: DropdownMenuItemType.DIVIDER,
  },
  {
    type: DropdownMenuItemType.BUTTON,
    disabled: true,
    label: "Dashboard",
  },
  {
    type: DropdownMenuItemType.BUTTON,
    disabled: true,
    label: "Portfolio",
  },
  {
    label: "Profile",
    href: "/profile",
  },
  {
    type: DropdownMenuItemType.EXTERNAL_LINK,
    href: "https://pancakeswap.finance",
    label: "Link",
  },
  {
    type: DropdownMenuItemType.DIVIDER,
  },
  {
    type: DropdownMenuItemType.BUTTON,
    onClick: noop,
    label: "Disconnect",
  },
]
Example #20
Source File: windowListener.ts    From qiankun with MIT License 5 votes vote down vote up
/**
 * 监听器 patch,添加事件监听时自动记录事件的回调函数,移除时自动删除事件的回调函数,释放 patch 时自动删除所有的事件监听,并恢复监听函数
 * @param global windowProxy
 */
export default function patch(global: WindowProxy) {
  // 记录各个事件的回调函数
  const listenerMap = new Map<string, EventListenerOrEventListenerObject[]>();

  // 设置监听器
  global.addEventListener = (
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: boolean | AddEventListenerOptions,
  ) => {
    // 从 listenerMap 中获取已经存在的该事件的回调函数
    const listeners = listenerMap.get(type) || [];
    // 保存该事件的所有回调函数
    listenerMap.set(type, [...listeners, listener]);
    // 设置监听
    return rawAddEventListener.call(window, type, listener, options);
  };

  // 移除监听器
  global.removeEventListener = (
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: boolean | AddEventListenerOptions,
  ) => {
    // 从 listenerMap 中移除该事件的指定回调函数
    const storedTypeListeners = listenerMap.get(type);
    if (storedTypeListeners && storedTypeListeners.length && storedTypeListeners.indexOf(listener) !== -1) {
      storedTypeListeners.splice(storedTypeListeners.indexOf(listener), 1);
    }
    // 移除事件监听
    return rawRemoveEventListener.call(window, type, listener, options);
  };

  // 释放 patch,移除所有的事件监听
  return function free() {
    // 移除所有的事件监听
    listenerMap.forEach((listeners, type) =>
      [...listeners].forEach(listener => global.removeEventListener(type, listener)),
    );
    // 恢复监听函数
    global.addEventListener = rawAddEventListener;
    global.removeEventListener = rawRemoveEventListener;

    return noop;
  };
}
Example #21
Source File: config.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
userMenulinks: DropdownMenuItems[] = [
  {
    label: "Wallet",
    onClick: noop,
    type: DropdownMenuItemType.BUTTON,
  },
  {
    label: "Transactions",
    type: DropdownMenuItemType.BUTTON,
  },
  {
    type: DropdownMenuItemType.DIVIDER,
  },
  {
    type: DropdownMenuItemType.BUTTON,
    disabled: true,
    label: "Dashboard",
  },
  {
    type: DropdownMenuItemType.BUTTON,
    disabled: true,
    label: "Portfolio",
  },
  {
    label: "Profile",
    href: "/profile",
  },
  {
    type: DropdownMenuItemType.EXTERNAL_LINK,
    href: "https://vvs.finance",
    label: "Link",
  },
  {
    type: DropdownMenuItemType.DIVIDER,
  },
  {
    type: DropdownMenuItemType.BUTTON,
    onClick: noop,
    label: "Disconnect",
  },
]
Example #22
Source File: Plausible.tsx    From nextclade with MIT License 5 votes vote down vote up
export function usePlausible() {
  return get(window, 'plausible', noop) as PlausibleHookResult
}
Example #23
Source File: index.stories.tsx    From pancake-toolkit with GNU General Public License v3.0 5 votes vote down vote up
Default.args = {
  toggleTheme: noop,
  isDark: false,
};
Example #24
Source File: Group.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
public static defaultProps = {
    onSelect: noop,
    style: {},
  };
Example #25
Source File: ExperimentDetails.test.tsx    From abacus with GNU General Public License v2.0 5 votes vote down vote up
experimentReloadRef: React.MutableRefObject<() => void> = { current: noop }
Example #26
Source File: Highlight.tsx    From frontend.ro with MIT License 5 votes vote down vote up
export default function Highlight({
  language, code, withCopy = true, className, onHighlight = noop, variant = 'default', textWrap = 'scroll',
}: Props) {
  const highlightModule = useRef<HLJSApi>(null);
  const preRef = useRef<HTMLPreElement>(null);

  useEffect(() => {
    import('~/services/highlight').then((module) => {
      highlightModule.current = module.default;
      highlightCode();
    });
  }, []);

  useEffect(() => {
    if (!highlightModule.current) {
      // This should only happen once, until the above
      // `useEffect` finishes to load the Highlight library.
      return;
    }

    // After each highlight the <code> element is deleted
    // and replaced with styled <span> elements. We have to
    // re-create it.
    const codeEl = document.createElement('code');

    // Using `document.createTextNode` to correctly escape HTML code
    codeEl.appendChild(document.createTextNode(code));
    preRef.current.innerHTML = null;
    preRef.current.appendChild(codeEl);

    highlightCode();
  }, [code]);

  const highlightCode = () => {
    if (!preRef.current) {
      console.warn('Highlight.highlightCode: expected `preRef.current` to be populated.');
      return;
    }

    highlightModule.current.highlightElement(preRef.current);
    onHighlight();
  };

  return (
    <div className={`${styles.highlight} ${styles[variant]} ${className}`}>
      <pre
        ref={preRef}
        className={`
          ${language}
          ${textWrap === 'wrap' ? styles['pre--wrap'] : ''}
        `}
      >
        <code>
          {code}
        </code>
      </pre>
      {withCopy && <CopyButton code={code} />}
    </div>
  );
}
Example #27
Source File: download-ui5-resources.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
log = silent ? noop : (_: string) => console.log(_)
Example #28
Source File: drill-down-spec.tsx    From S2 with MIT License 5 votes vote down vote up
describe('Spread Sheet Drill Down Tests', () => {
  let container: HTMLDivElement;
  beforeEach(() => {
    container = getContainer();
  });

  afterEach(() => {
    container?.remove();
  });

  test('should render drill down icon', () => {
    let s2Instance: SpreadSheet = null;

    // 首次 render
    act(() => {
      ReactDOM.render(
        <SheetComponent
          options={s2Options}
          dataCfg={mockDataConfig}
          getSpreadSheet={(instance) => {
            s2Instance = instance;
          }}
          partDrillDown={partDrillDownParams}
        />,
        container,
      );
    });
    expect(findDrillDownIcon(s2Instance)).toBeDefined();

    // mock drill down
    s2Instance.store.set('drillDownIdPathMap', new Map());
    s2Instance.store.set('drillItemsNum', EXPECT_DRILL_ITEMS_NUM);

    // update options.headerActionIcons
    act(() => {
      ReactDOM.render(
        <SheetComponent
          options={{
            ...s2Options,
            headerActionIcons: [
              {
                iconNames: ['SortDown'],
                belongsCell: 'colCell',
                displayCondition: (meta: Node) => {
                  return meta.isLeaf;
                },
                action: noop,
              },
            ],
          }}
          dataCfg={mockDataConfig}
          getSpreadSheet={(instance) => {
            s2Instance = instance;
          }}
          partDrillDown={partDrillDownParams}
        />,
        container,
      );
    });
    expect(findDrillDownIcon(s2Instance)).toBeDefined();

    // render new headerActionIcons should not clear data
    expect(s2Instance.store.get('drillItemsNum')).toEqual(
      EXPECT_DRILL_ITEMS_NUM,
    );
  });
});
Example #29
Source File: template.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
public static defaultProps = {
    onRemove: noop,
  };