Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add toggle all feature to CheckboxSetField #73

Open
McManning opened this issue Apr 24, 2023 · 0 comments
Open

Add toggle all feature to CheckboxSetField #73

McManning opened this issue Apr 24, 2023 · 0 comments
Assignees
Labels
enhancement New feature or request v5-alpha

Comments

@McManning
Copy link
Contributor

I find myself having to manually implement a toggle all checkbox as part of a set. This would be a good candidate for a feature option.

Here's my current implementation for a component that selects from a list of groups:

import { useGroupList } from "@/hooks/useGroupList"
import { CheckboxField, CheckboxSetField, Item } from "@osuresearch/ui";
import React, { useState } from "react";

export type GroupSelectFieldProps = {
  value?: string[]
  onChange: (ids: string[] | undefined) => void

  selectAllLabel: React.ReactNode
}

/**
 * Allows the user to select one or more groups from
 * the list of all groups they have access to.
 */
export function GroupSelectField({ value, selectAllLabel, onChange }: GroupSelectFieldProps) {
  const { groups, loading, error } = useGroupList();

  if (!groups) {
    return null;
  }

  const handleChange = (ids?: string[]) => {
    onChange(ids);
  }

  const hasSelection = value && value.length > 0;
  const hasPartialSelection = hasSelection && value.length !== groups.length;

  const toggleAll = (on?: boolean) => {
    if (hasSelection && value.length === groups.length) {
      onChange(undefined);
    }
    else {
      onChange(groups.map((g) => g.id));
    }
  }

  return (
    <div>
      <CheckboxField
        name="all-groups"
        value={value ? value.length > 0 : false}
        isIndeterminate={hasPartialSelection}
        onChange={toggleAll}
        label={selectAllLabel}
      />
      <CheckboxSetField pt="sm" pl="xl" name="groups" value={value ?? []} onChange={handleChange} aria-label="Select one or more groups">
        {groups.map((group) =>
          <Item key={group.id}>{group.id}</Item>
        )}
      </CheckboxSetField>
    </div>
  )
}

Visually it looks something like the following:

image

@McManning McManning added enhancement New feature or request v5-alpha labels Apr 24, 2023
@McManning McManning self-assigned this Apr 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request v5-alpha
Projects
None yet
Development

No branches or pull requests

1 participant