ronantakizawa/codereview-bench huggingface dataset:
Repository: element-plus/element-plus
File: packages/components/mention/src/mention-dropdown.vue (Vue)

Code before:
}

const scrollToOption = (option: MentionOption) => {
  const { options } = props

  const index = options.findIndex((item) => item.value === option.value)
  const target = optionRefs.value?.[index]

  if (target) {
    const menu = dropdownRef.value?.querySelector?.(
      `.${ns.be('dropdown', 'wrap')}`
    )
    if (menu) {
      scrollIntoView(menu as HTMLElement, target)
    }
  }
  scrollbarRef.value?.handleScroll()
}

const resetHoveringIndex = () => {
  if (filteredAllDisabled.value || props.options.length === 0) {
    hoveringIndex.value = -1
  } else {
    // Find the first non-disabled option
    const firstEnabledIndex = props.options.findIndex((item) => !item.disabled)
    hoveringIndex.value = firstEnabledIndex !== -1 ? firstEnabledIndex : -1
  }
}

watch(() => props.options, resetHoveringIndex, {
  immediate: true,
})

defineExpose({
  hoveringIndex,
  navigateOptions,
  selectHoverOption,
  hoverOption,
})
</script>


Review comment (suggestion):
```suggestion
    hoveringIndex.value = props.options.findIndex((item) => !item.disabled)
```

Code after:
}

const scrollToOption = (option: MentionOption) => {
  const { options } = props

  const index = options.findIndex((item) => item.value === option.value)
  const target = optionRefs.value?.[index]

  if (target) {
    const menu = dropdownRef.value?.querySelector?.(
      `.${ns.be('dropdown', 'wrap')}`
    )
    if (menu) {
      scrollIntoView(menu as HTMLElement, target)
    }
  }
  scrollbarRef.value?.handleScroll()
}

const resetHoveringIndex = () => {
  if (filteredAllDisabled.value || props.options.length === 0) {
    hoveringIndex.value = -1
  } else {
    hoveringIndex.value = props.options.findIndex((item) => !item.disabled)
  }
}

watch(() => props.options, resetHoveringIndex, {
  immediate: true,
})

defineExpose({
  hoveringIndex,
  navigateOptions,
  selectHoverOption,
  hoverOption,
})
</script>
Repository: element-plus/element-plus
File: packages/components/mention/__tests__/mention.test.tsx (TypeScript)

Code before:
      value: 'btea',
    },
  ]

  const optionsWithDisabled = [
    {
      id: 'Fuphoenixes',
      name: 'Fuphoenixes',
      unable: true,
    },
    {
      id: 'kooriookami',
      name: 'kooriookami',
      unable: false,
    },
    {
      id: 'Jeremy',
      name: 'Jeremy',
      unable: true,
    },
    {
      id: 'btea',
      name: 'btea',
      unable: false,
    },
  ]

  test('should work with `options` prop', async () => {
    const wrapper = mount(Mention, {
      attachTo: document.body,
      props: { options },
    })

    wrapper.find('input').element.focus()
    wrapper.find('input').setValue('@')

    vi.advanceTimersByTime(150)
    await nextTick()
    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)
    expect(document.querySelectorAll('.el-mention-dropdown__item').length).toBe(
      4
    )
  })

  test('should work with `type` prop', async () => {
    const wrapper = mount(Mention, {
      attachTo: document.body,
      props: { options },
    })

    expect(wrapper.find('input').exists()).toBe(true)

Review comment (suggestion):
```suggestion
  const optionsWithDisabled = options.map((item, index) => ({
    ...item,
    disabled: !(index & 1),
  }))
```

Code after:
      value: 'btea',
    },
  ]

  const optionsWithDisabled = options.map((item, index) => ({
    ...item,
    disabled: !(index & 1),
  }))

  test('should work with `options` prop', async () => {
    const wrapper = mount(Mention, {
      attachTo: document.body,
      props: { options },
    })

    wrapper.find('input').element.focus()
    wrapper.find('input').setValue('@')

    vi.advanceTimersByTime(150)
    await nextTick()
    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)
    expect(document.querySelectorAll('.el-mention-dropdown__item').length).toBe(
      4
    )
  })

  test('should work with `type` prop', async () => {
    const wrapper = mount(Mention, {
      attachTo: document.body,
      props: { options },
    })

    expect(wrapper.find('input').exists()).toBe(true)

    await wrapper.setProps({ type: 'text' })
    expect(wrapper.find('input').exists()).toBe(true)

    await wrapper.setProps({ type: 'textarea' })
    expect(wrapper.find('textarea').exists()).toBe(true)
  })

  test('should work with `loading` prop', async () => {
    const wrapper = mount(Mention, {
      attachTo: document.body,
      props: { options, loading: true },
    })

    wrapper.find('input').element.focus()
    await wrapper.find('input').setValue('@')
    vi.advanceTimersByTime(150)
    await nextTick()
Repository: element-plus/element-plus
File: packages/components/mention/__tests__/mention.test.tsx (TypeScript)

Code before:

    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)

    await inputEl.trigger('keydown', {
      code: EVENT_CODE.enter,
      key: EVENT_CODE.enter,
    })
    await nextTick()

    expect(inputEl.element.value).toBe('@kooriookami ')
  })

  test('should not select disabled option when pressing enter', async () => {
    const props = { value: 'id', label: 'name', disabled: 'unable' }

    const wrapper = mount(Mention, {
      attachTo: document.body,
      props: {
        modelValue: '',
        options: optionsWithDisabled,
        props,
        'onUpdate:modelValue': (val: string) => {
          wrapper.setProps({ modelValue: val })
        },
      },
    })

    const inputEl = wrapper.find('input')
    inputEl.element.focus()
    await inputEl.setValue('@')

    vi.advanceTimersByTime(150)
    await nextTick()

    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)

    const dropdown = wrapper.findComponent({ name: 'ElMentionDropdown' })
    const dropdownVm = dropdown.vm as any
    dropdownVm.hoveringIndex = 0

    await nextTick()

    const dropdownItems = document.querySelectorAll(
      '.el-mention-dropdown__item'
    )
    expect(dropdownItems[0].classList.contains('is-hovering')).toBe(true)
    expect(dropdownItems[0].classList.contains('is-disabled')).toBe(true)

    await inputEl.trigger('keydown', {
      code: EVENT_CODE.enter,
      key: EVENT_CODE.enter,

Review comment (suggestion):
```suggestion
    const model = ref('')
    const wrapper = mount(
      () => <Mention v-model={model.value} options={optionsWithDisabled} />,
      { attachTo: document.body }
    )
```

Code after:
    await inputEl.setValue('@')

    vi.advanceTimersByTime(150)
    await nextTick()

    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)

    const dropdown = wrapper.findComponent({ name: 'ElMentionDropdown' })
    const dropdownVm = dropdown.vm as any
    dropdownVm.hoveringIndex = 0

    await nextTick()

    const dropdownItems = document.querySelectorAll(
      '.el-mention-dropdown__item'
    )
    expect(dropdownItems[0].classList.contains('is-hovering')).toBe(true)
    expect(dropdownItems[0].classList.contains('is-disabled')).toBe(true)

    await inputEl.trigger('keydown', {
      code: EVENT_CODE.enter,
      key: EVENT_CODE.enter,
    })
    await nextTick()

    expect(inputEl.element.value).toBe('@')
    expect(model.value).toBe('@')
  })
})
Repository: element-plus/element-plus
File: packages/components/mention/__tests__/mention.test.tsx (TypeScript)

Code before:

    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)

    await inputEl.trigger('keydown', {
      code: EVENT_CODE.enter,
      key: EVENT_CODE.enter,
    })
    await nextTick()

    expect(inputEl.element.value).toBe('@kooriookami ')
  })

  test('should not select disabled option when pressing enter', async () => {
    const props = { value: 'id', label: 'name', disabled: 'unable' }

    const wrapper = mount(Mention, {
      attachTo: document.body,
      props: {
        modelValue: '',
        options: optionsWithDisabled,
        props,
        'onUpdate:modelValue': (val: string) => {
          wrapper.setProps({ modelValue: val })
        },
      },
    })

    const inputEl = wrapper.find('input')
    inputEl.element.focus()
    await inputEl.setValue('@')

    vi.advanceTimersByTime(150)
    await nextTick()

    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)

    const dropdown = wrapper.findComponent({ name: 'ElMentionDropdown' })
    const dropdownVm = dropdown.vm as any
    dropdownVm.hoveringIndex = 0

    await nextTick()

    const dropdownItems = document.querySelectorAll(
      '.el-mention-dropdown__item'
    )
    expect(dropdownItems[0].classList.contains('is-hovering')).toBe(true)
    expect(dropdownItems[0].classList.contains('is-disabled')).toBe(true)

    await inputEl.trigger('keydown', {
      code: EVENT_CODE.enter,
      key: EVENT_CODE.enter,

Review comment (suggestion):
```suggestion
    expect(inputEl.element.value).toBe('@')
    expect(model.value).toBe('@')
```

Code after:
    await inputEl.setValue('@')

    vi.advanceTimersByTime(150)
    await nextTick()

    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)

    const dropdown = wrapper.findComponent({ name: 'ElMentionDropdown' })
    const dropdownVm = dropdown.vm as any
    dropdownVm.hoveringIndex = 0

    await nextTick()

    const dropdownItems = document.querySelectorAll(
      '.el-mention-dropdown__item'
    )
    expect(dropdownItems[0].classList.contains('is-hovering')).toBe(true)
    expect(dropdownItems[0].classList.contains('is-disabled')).toBe(true)

    await inputEl.trigger('keydown', {
      code: EVENT_CODE.enter,
      key: EVENT_CODE.enter,
    })
    await nextTick()

    expect(inputEl.element.value).toBe('@')
    expect(model.value).toBe('@')
  })
})
Repository: element-plus/element-plus
File: packages/components/mention/__tests__/mention.test.tsx (TypeScript)

Code before:
      x: 100,
      top: 100,
      y: 100,
    })
    mockBoundingClientRect(inputEl, {
      width: 298,
      height: 30,
      left: 111,
      x: 111,
      top: 101,
      y: 101,
    })

    inputEl.focus()
    await wrapper.find('input').setValue('@')
    vi.advanceTimersByTime(150)
    await nextTick()

    const cursorStyles = wrapper
      .find('.el-tooltip__trigger')
      .attributes('style')

    expect(cursorStyles).toContain('left: 125px')
    expect(cursorStyles).toContain('top: 108px')

    vi.restoreAllMocks()
  })

  test('should select first non-disabled option when pressing enter', async () => {
    const props = { value: 'id', label: 'name', disabled: 'unable' }

    const wrapper = mount(Mention, {
      attachTo: document.body,
      props: {
        modelValue: '',
        options: optionsWithDisabled,
        props,
        'onUpdate:modelValue': (val: string) => {
          wrapper.setProps({ modelValue: val })
        },
      },
    })

    const inputEl = wrapper.find('input')
    inputEl.element.focus()
    await inputEl.setValue('@')

    vi.advanceTimersByTime(150)
    await nextTick()

    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)

Review comment (suggestion):
```suggestion

    const dropdown = wrapper.findComponent({ name: 'ElMentionDropdown' })
    const dropdownVm = dropdown.vm as any
    expect(dropdownVm.hoveringIndex).toBe(1)

```

Code after:
    const cursorStyles = wrapper
      .find('.el-tooltip__trigger')
      .attributes('style')

    expect(cursorStyles).toContain('left: 125px')
    expect(cursorStyles).toContain('top: 108px')

    vi.restoreAllMocks()
  })

  test('should select first non-disabled option when pressing enter', async () => {
    const model = ref('')
    const wrapper = mount(
      () => <Mention v-model={model.value} options={optionsWithDisabled} />,
      { attachTo: document.body }
    )

    const inputEl = wrapper.find('input')
    inputEl.element.focus()
    await inputEl.setValue('@')

    vi.advanceTimersByTime(150)
    await nextTick()

    expect(document.querySelector('.el-mention-dropdown')).not.toEqual(null)

    const dropdown = wrapper.findComponent({ name: 'ElMentionDropdown' })
    const dropdownVm = dropdown.vm as any
    expect(dropdownVm.hoveringIndex).toBe(1)

    await inputEl.trigger('keydown', {
      code: EVENT_CODE.enter,
      key: EVENT_CODE.enter,
    })
    await nextTick()

    expect(inputEl.element.value).toBe('@kooriookami ')
    expect(model.value).toBe('@kooriookami ')
  })

  test('should not select disabled option when pressing enter', async () => {
    const model = ref('')
    const wrapper = mount(
      () => <Mention v-model={model.value} options={optionsWithDisabled} />,
      { attachTo: document.body }
    )

    const inputEl = wrapper.find('input')
    inputEl.element.focus()
    await inputEl.setValue('@')
Repository: encode/httpx
File: tests/client/test_proxies.py (Python)

Code before:
    client = client_class()
    request = httpx.Request(method="GET", url=url)
    transport = client._transport_for_url(request)

    if expected is None:
        assert transport == client._transport
    else:
        assert transport.proxy_origin == url_to_origin(expected)


@pytest.mark.parametrize(
    ["proxies", "expected_scheme"],
    [
        ({"http": "http://127.0.0.1"}, ["http://"]),
        ({"https": "http://127.0.0.1"}, ["https://"]),
        ({"all": "http://127.0.0.1"}, ["all://"]),
    ],
)
def test_for_deprecated_proxy_params(proxies, expected_scheme):
    with pytest.deprecated_call() as block:
        httpx.AsyncClient(proxies=proxies)

    warning_message = str(block.pop(DeprecationWarning))

    for scheme in expected_scheme:
        assert scheme in warning_message


Review comment (suggestion):
Could this be simplified to this by converting `expected_scheme` to a plain string?

```suggestion
    assert expected_scheme in warning_message
```

Code after:
    client = client_class()
    request = httpx.Request(method="GET", url=url)
    transport = client._transport_for_url(request)

    if expected is None:
        assert transport == client._transport
    else:
        assert transport.proxy_origin == url_to_origin(expected)


@pytest.mark.parametrize(
    ["proxies", "expected_scheme"],
    [
        ({"http": "http://127.0.0.1"}, "http://"),
        ({"https": "http://127.0.0.1"}, "https://"),
        ({"all": "http://127.0.0.1"}, "all://"),
    ],
)
def test_for_deprecated_proxy_params(proxies, expected_scheme):
    with pytest.deprecated_call() as block:
        httpx.AsyncClient(proxies=proxies)

    warning_message = str(block.pop(DeprecationWarning))

    assert expected_scheme in warning_message
Repository: encode/httpx
File: tests/client/test_proxies.py (Python)

Code before:
            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "*"},
            None,
        ),
    ],
)
@pytest.mark.parametrize("client_class", [httpx.Client, httpx.AsyncClient])
def test_proxies_environ(monkeypatch, client_class, url, env, expected):
    for name, value in env.items():
        monkeypatch.setenv(name, value)

    client = client_class()
    request = httpx.Request(method="GET", url=url)
    transport = client._transport_for_url(request)

    if expected is None:
        assert transport == client._transport
    else:
        assert transport.proxy_origin == url_to_origin(expected)


@pytest.mark.parametrize(
    ["proxies", "expected_scheme"],
    [
        ({"http": "http://127.0.0.1"}, ["http://"]),
        ({"https": "http://127.0.0.1"}, ["https://"]),
        ({"all": "http://127.0.0.1"}, ["all://"]),
    ],
)
def test_for_deprecated_proxy_params(proxies, expected_scheme):
    with pytest.deprecated_call() as block:
        httpx.AsyncClient(proxies=proxies)

    warning_message = str(block.pop(DeprecationWarning))

    assert expected_scheme in warning_message


Review comment (suggestion):
```suggestion
        ({"http": "http://127.0.0.1"}, "http://"),
        ({"https": "http://127.0.0.1"}, "https://"),
        ({"all": "http://127.0.0.1"}, "all://"),
```

Code after:
            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "*"},
            None,
        ),
    ],
)
@pytest.mark.parametrize("client_class", [httpx.Client, httpx.AsyncClient])
def test_proxies_environ(monkeypatch, client_class, url, env, expected):
    for name, value in env.items():
        monkeypatch.setenv(name, value)

    client = client_class()
    request = httpx.Request(method="GET", url=url)
    transport = client._transport_for_url(request)

    if expected is None:
        assert transport == client._transport
    else:
        assert transport.proxy_origin == url_to_origin(expected)


@pytest.mark.parametrize(
    ["proxies", "expected_scheme"],
    [
        ({"http": "http://127.0.0.1"}, "http://"),
        ({"https": "http://127.0.0.1"}, "https://"),
        ({"all": "http://127.0.0.1"}, "all://"),
    ],
)
def test_for_deprecated_proxy_params(proxies, expected_scheme):
    with pytest.deprecated_call() as block:
        httpx.AsyncClient(proxies=proxies)

    warning_message = str(block.pop(DeprecationWarning))

    assert expected_scheme in warning_message
Repository: encode/httpx
File: httpx/_client.py (Python)

Code before:
    CertTypes,
    CookieTypes,
    HeaderTypes,
    ProxiesTypes,
    QueryParamTypes,
    RequestData,
    RequestFiles,
    TimeoutTypes,
    URLTypes,
    VerifyTypes,
)
from ._utils import (
    NetRCInfo,
    URLPattern,
    get_environment_proxies,
    get_logger,
    same_origin,
    warn_deprecated,
)

logger = get_logger(__name__)

KEEPALIVE_EXPIRY = 5.0


def check_not_closed(method: typing.Callable) -> typing.Callable:
    @functools.wraps(method)
    def wrapper(
        self: "BaseClient", *args: typing.Any, **kwargs: typing.Any
    ) -> typing.Any:
        if self.is_closed:
            raise RuntimeError(f"{self!r} is closed. We cannot use the closed client!")
        return method(self, *args, **kwargs)

    return wrapper


class BaseClient:
    def __init__(
        self,
        *,
        auth: AuthTypes = None,
        params: QueryParamTypes = None,
        headers: HeaderTypes = None,
        cookies: CookieTypes = None,
        timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
        max_redirects: int = DEFAULT_MAX_REDIRECTS,
        base_url: URLTypes = "",
        trust_env: bool = True,
    ):
        self._base_url = self._enforce_trailing_slash(URL(base_url))

Review comment (suggestion):
I'd prefer for us *not* to use a decorator style.
I'll use inline comments below to walk through the alternative...


Code after:
    AuthTypes,
    CertTypes,
    CookieTypes,
    HeaderTypes,
    ProxiesTypes,
    QueryParamTypes,
    RequestData,
    RequestFiles,
    TimeoutTypes,
    URLTypes,
    VerifyTypes,
)
from ._utils import (
    NetRCInfo,
    URLPattern,
    get_environment_proxies,
    get_logger,
    same_origin,
    warn_deprecated,
)

logger = get_logger(__name__)

KEEPALIVE_EXPIRY = 5.0


class BaseClient:
    def __init__(
        self,
        *,
        auth: AuthTypes = None,
        params: QueryParamTypes = None,
        headers: HeaderTypes = None,
        cookies: CookieTypes = None,
        timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
        max_redirects: int = DEFAULT_MAX_REDIRECTS,
        base_url: URLTypes = "",
        trust_env: bool = True,
    ):
        self._base_url = self._enforce_trailing_slash(URL(base_url))

        self._auth = self._build_auth(auth)
        self._params = QueryParams(params)
        self._headers = Headers(headers)
        self._cookies = Cookies(cookies)
        self._timeout = Timeout(timeout)
        self.max_redirects = max_redirects
        self._trust_env = trust_env
        self._netrc = NetRCInfo()
        self._is_closed = True
Repository: encode/httpx
File: httpx/_client.py (Python)

Code before:
        url: URLTypes,
        *,
        params: QueryParamTypes = None,
        headers: HeaderTypes = None,
        cookies: CookieTypes = None,
        auth: typing.Union[AuthTypes, UnsetType] = UNSET,
        allow_redirects: bool = True,
        timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,
    ) -> Response:
        """
        Send a `DELETE` request.

        **Parameters**: See `httpx.request`.
        """
        return self.request(
            "DELETE",
            url,
            params=params,
            headers=headers,
            cookies=cookies,
            auth=auth,
            allow_redirects=allow_redirects,
            timeout=timeout,
        )

    @check_not_closed
    def close(self) -> None:
        """
        Close transport and proxies.
        """
        self._transport.close()
        for proxy in self._proxies.values():
            if proxy is not None:
                proxy.close()

        self._is_closed = True

    def __enter__(self) -> "Client":
        return self

    def __exit__(
        self,
        exc_type: typing.Type[BaseException] = None,
        exc_value: BaseException = None,
        traceback: TracebackType = None,
    ) -> None:
        self.close()


class AsyncClient(BaseClient):
    """

Review comment (suggestion):
Could we instead just let things pass silently if the client is already closed, and `.close()` is called again?
So...

```python
if not self._is_closed:
    self._transport.close()
    for proxy in self._proxies.values():
        if proxy is not None:
            proxy.close()

Code after:
        url: URLTypes,
        *,
        params: QueryParamTypes = None,
        headers: HeaderTypes = None,
        cookies: CookieTypes = None,
        auth: typing.Union[AuthTypes, UnsetType] = UNSET,
        allow_redirects: bool = True,
        timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,
    ) -> Response:
        """
        Send a `DELETE` request.

        **Parameters**: See `httpx.request`.
        """
        return self.request(
            "DELETE",
            url,
            params=params,
            headers=headers,
            cookies=cookies,
            auth=auth,
            allow_redirects=allow_redirects,
            timeout=timeout,
        )

    def close(self) -> None:
        """
        Close transport and proxies.
        """
        if not self.is_closed:
            self._is_closed = True

            self._transport.close()
            for proxy in self._proxies.values():
                if proxy is not None:
                    proxy.close()

    def __enter__(self) -> "Client":
        self._transport.__enter__()
        for proxy in self._proxies.values():
            if proxy is not None:
                proxy.__enter__()
        self._is_closed = False
        return self

    def __exit__(
        self,
        exc_type: typing.Type[BaseException] = None,
        exc_value: BaseException = None,
        traceback: TracebackType = None,
    ) -> None: