Skip to content

feat: loading and spinner component with directive - #5587

Merged
mynetfan merged 3 commits into
vbenjs:mainfrom
mynetfan:feat/v-loading
Feb 23, 2025
Merged

mynetfan merged 3 commits into
vbenjs:mainfrom
mynetfan:feat/v-loading

Conversation

@mynetfan

@mynetfan mynetfan commented Feb 23, 2025 •

Copy link
Copy Markdown
Collaborator

Description

添加loading和spinner组件,以及对应的vue指令

close #5507

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features

    • Introduced new loading and spinning indicators to enhance visual feedback during asynchronous operations.
    • Added interactive loading and spinner components that now render only when activated.
    • Launched an example route and demo page showcasing these new UI features.
  • Refactor

    • Updated component behavior for a more responsive and intuitive loading experience.

* 添加loading和spinner组件,以及对应的vue指令
@mynetfan
mynetfan requested review from a team, anncwb and vince292007 as code owners February 23, 2025 03:13
@changeset-bot

changeset-bot Bot commented Feb 23, 2025 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 5ff5626

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Feb 23, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update introduces new Vue directives for handling loading and spinning states across multiple applications. The changes update bootstrap files to register the new directives and adjust import statements accordingly. Additionally, the UI kit components for spinner and loading have been modified to change their initial rendering behaviors. The common UI package now exports these directives and components, and a new example route and view are added to showcase the loading functionality. Directive definitions include lifecycle hooks for mounting, updating, and unmounting the custom loading/spinner components.

Changes

File(s) Change Summary
apps/web-antd/src/bootstrap.ts, apps/web-naive/src/bootstrap.ts, playground/src/bootstrap.ts Updated import statements to include registerLoadingDirective; registered both loading and spinning directives using app.
apps/web-ele/src/bootstrap.ts Added import and registration for spinningDirective; provided a commented option for loading directive registration.
packages/@core/ui-kit/.../spinner/{loading.vue, spinner.vue} Modified spinner components: set renderSpinner initial state to false, added conditional rendering, and removed/adjusted class bindings.
packages/effects/common-ui/src/components/index.ts Added export statement to re-export entities from the loading module.
packages/effects/common-ui/src/components/loading/directive.ts Introduced new Vue directives loadingDirective and spinningDirective with lifecycle hooks (mounted, updated, unmounted) and helper options extraction.
packages/effects/common-ui/src/components/loading/index.ts Exported all entities from the directive module and added default exports for Loading and Spinner components.
packages/effects/common-ui/src/components/loading/{loading.vue, spinner.vue} Added new Vue components Loading and Spinner using TypeScript and Vben components, with props and tailored template structures.
playground/src/router/routes/modules/examples.ts Added a new route for the loading example with defined name, path, component, and metadata.
playground/src/views/examples/loading/index.vue Introduced a new example Vue component demonstrating usage of the Loading and Spinner components with interactive state management.

Possibly related PRs

Suggested labels

feature

Suggested reviewers

  • anncwb
  • vince292007

Poem

I'm a hopping rabbit with a coding cheer,
Introducing loading and spinning far and near,
Directives now guide the UI with grace,
Spinners and loaders set a brisk pace,
In every line of code, I leave a trace,
Hop on and explore this innovative space!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9e09f6e and 5ff5626.

📒 Files selected for processing (1)
  • packages/effects/common-ui/src/components/loading/directive.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/effects/common-ui/src/components/loading/directive.ts
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Check (ubuntu-latest)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🔭 Outside diff range comments (1)
packages/@core/ui-kit/shadcn-ui/src/components/spinner/loading.vue (1)

37-59: 🛠️ Refactor suggestion

Add error handling for timer cleanup.

The watch effect should clean up the timer in its stop function to prevent memory leaks.

 watch(
   () => props.spinning,
   (show) => {
     if (!show) {
       showSpinner.value = false;
       clearTimeout(timer.value);
       return;
     }

     timer.value = setTimeout(() => {
       showSpinner.value = true;
       if (showSpinner.value) {
         renderSpinner.value = true;
       }
     }, props.minLoadingTime);
   },
   {
     immediate: true,
+    onStop() {
+      clearTimeout(timer.value);
+    },
   },
 );
🧹 Nitpick comments (7)
packages/effects/common-ui/src/components/loading/spinner.vue (1)

10-10: Consider making min-height configurable.

The hardcoded min-h-20 class might not be suitable for all use cases. Consider making it a prop to allow customization.

packages/effects/common-ui/src/components/loading/loading.vue (1)

11-11: Consider making min-height configurable.

The hardcoded min-h-20 class might not be suitable for all use cases. Consider making it a prop to allow customization.

packages/effects/common-ui/src/components/loading/directive.ts (2)

38-46: Improve type safety in getOptions function.

The function should explicitly type its return value and validate the object properties.

Consider this improvement:

-function getOptions(binding: DirectiveBinding) {
+interface LoadingOptions {
+  spinning: boolean;
+  [key: string]: unknown;
+}
+
+function getOptions(binding: DirectiveBinding): LoadingOptions {
   if (binding.value === undefined) {
     return { spinning: true };
   } else if (typeof binding.value === 'boolean') {
     return { spinning: binding.value };
   } else {
-    return { ...binding.value };
+    return { spinning: true, ...binding.value };
   }
 }

10-74: Reduce code duplication between directives.

The loading and spinning directives share identical logic but operate on different components and symbols.

Consider creating a factory function:

function createLoadingDirective(
  component: typeof VbenLoading | typeof VbenSpinner,
  instanceKey: symbol
): Directive {
  return {
    mounted(el, binding) {
      const instance = h(component, getOptions(binding));
      render(instance, el);
      el.classList.add('spinner-parent--relative');
      el[instanceKey] = instance;
    },
    unmounted(el) {
      const instance = el[instanceKey];
      el.classList.remove('spinner-parent--relative');
      render(null, el);
      instance.el.remove();
      el[instanceKey] = null;
    },
    updated(el, binding) {
      const instance = el[instanceKey];
      const options = getOptions(binding);
      if (options && instance?.component) {
        Object.keys(options).forEach((key) => {
          instance.component.props[key] = options[key];
        });
        instance.component.update();
      }
    },
  };
}

export const loadingDirective = createLoadingDirective(
  VbenLoading,
  LOADING_INSTANCE_KEY
);
export const spinningDirective = createLoadingDirective(
  VbenSpinner,
  SPINNER_INSTANCE_KEY
);
packages/@core/ui-kit/shadcn-ui/src/components/spinner/loading.vue (1)

32-34: Consider using computed property for state derivation.

The showSpinner and renderSpinner refs are tightly coupled. Consider using a computed property for renderSpinner to derive its state from showSpinner, which would make the state management more predictable and reduce the chance of state synchronization issues.

-const showSpinner = ref(false);
-const renderSpinner = ref(false);
+const showSpinner = ref(false);
+const renderSpinner = computed(() => showSpinner.value);
packages/@core/ui-kit/shadcn-ui/src/components/spinner/spinner.vue (1)

27-29: Consider extracting shared loading logic.

The spinner component shares significant logic with the loading component. Consider extracting the common functionality into a composable.

// useLoading.ts
export function useLoading(props: { spinning: boolean, minLoadingTime: number }) {
  const showSpinner = ref(false);
  const renderSpinner = computed(() => showSpinner.value);
  const timer = ref<ReturnType<typeof setTimeout>>();

  watch(
    () => props.spinning,
    (show) => {
      if (!show) {
        showSpinner.value = false;
        clearTimeout(timer.value);
        return;
      }

      timer.value = setTimeout(() => {
        showSpinner.value = true;
      }, props.minLoadingTime);
    },
    {
      immediate: true,
      onStop() {
        clearTimeout(timer.value);
      },
    },
  );

  return {
    showSpinner,
    renderSpinner,
  };
}
playground/src/views/examples/loading/index.vue (1)

8-12: Consider using a single state manager.

Multiple similar state variables could be consolidated into a single state manager for better maintainability.

-const spinning = refAutoReset(false, 3000);
-const loading = refAutoReset(false, 3000);
-const spinningV = refAutoReset(false, 3000);
-const loadingV = refAutoReset(false, 3000);
+const loadingStates = reactive({
+  spinning: refAutoReset(false, 3000),
+  loading: refAutoReset(false, 3000),
+  spinningV: refAutoReset(false, 3000),
+  loadingV: refAutoReset(false, 3000),
+});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eba3720 and fa59335.

📒 Files selected for processing (13)
  • apps/web-antd/src/bootstrap.ts (2 hunks)
  • apps/web-ele/src/bootstrap.ts (2 hunks)
  • apps/web-naive/src/bootstrap.ts (2 hunks)
  • packages/@core/ui-kit/shadcn-ui/src/components/spinner/loading.vue (3 hunks)
  • packages/@core/ui-kit/shadcn-ui/src/components/spinner/spinner.vue (2 hunks)
  • packages/effects/common-ui/src/components/index.ts (1 hunks)
  • packages/effects/common-ui/src/components/loading/directive.ts (1 hunks)
  • packages/effects/common-ui/src/components/loading/index.ts (1 hunks)
  • packages/effects/common-ui/src/components/loading/loading.vue (1 hunks)
  • packages/effects/common-ui/src/components/loading/spinner.vue (1 hunks)
  • playground/src/bootstrap.ts (2 hunks)
  • playground/src/router/routes/modules/examples.ts (1 hunks)
  • playground/src/views/examples/loading/index.vue (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/effects/common-ui/src/components/loading/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Check (ubuntu-latest)
🔇 Additional comments (5)
packages/effects/common-ui/src/components/index.ts (1)

8-8: LGTM!

The export statement follows the established pattern and correctly exposes the loading components.

apps/web-naive/src/bootstrap.ts (1)

4-8: LGTM!

The import and registration of directives follow Vue.js best practices and are well-documented.

Also applies to: 38-41

apps/web-antd/src/bootstrap.ts (1)

4-8: LGTM! Clean implementation of directive registration.

The changes properly integrate the loading and spinning directives with clear comments and appropriate placement in the bootstrap sequence.

Also applies to: 38-41

playground/src/bootstrap.ts (1)

4-8: LGTM! Consistent implementation across applications.

The changes maintain consistency with the web-antd implementation, ensuring uniform directive availability.

Also applies to: 39-42

apps/web-ele/src/bootstrap.ts (1)

4-4: LGTM! Well-documented directive choices.

The implementation provides flexibility by:

  • Using Element Plus's loading directive by default
  • Offering Vben's loading directive as an alternative
  • Cleanly integrating the spinning directive

Also applies to: 36-40

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (4)
packages/effects/common-ui/src/components/loading/directive.ts (4)

21-27: ⚠️ Potential issue

Fix potential memory leak in unmount hook.

The unmount hook should call render(null, el) to properly cleanup the VNode before removing the element.

Apply this fix:

  unmounted(el) {
    const instance = el[LOADING_INSTANCE_KEY];
    el.classList.remove(CLASS_NAME_RELATIVE);
+   render(null, el);
    instance.el.remove();

    el[LOADING_INSTANCE_KEY] = null;
  },

29-38: ⚠️ Potential issue

Add error handling in updated hook.

The updated hook should handle potential errors during props update.

Apply this fix:

  updated(el, binding) {
    const instance = el[LOADING_INSTANCE_KEY];
    const options = getOptions(binding);
    if (options && instance?.component) {
+     try {
        Object.keys(options).forEach((key) => {
          instance.component.props[key] = options[key];
        });
        instance.component.update();
+     } catch (error) {
+       console.error('Failed to update loading component:', error);
+     }
    }
  },

59-65: ⚠️ Potential issue

Fix potential memory leak in unmount hook.

The unmount hook should call render(null, el) to properly cleanup the VNode before removing the element.

Apply this fix:

  unmounted(el) {
    const instance = el[SPINNER_INSTANCE_KEY];
    el.classList.remove(CLASS_NAME_RELATIVE);
+   render(null, el);
    instance.el.remove();

    el[SPINNER_INSTANCE_KEY] = null;
  },

67-76: ⚠️ Potential issue

Add error handling in updated hook.

The updated hook should handle potential errors during props update.

Apply this fix:

  updated(el, binding) {
    const instance = el[SPINNER_INSTANCE_KEY];
    const options = getOptions(binding);
    if (options && instance?.component) {
+     try {
        Object.keys(options).forEach((key) => {
          instance.component.props[key] = options[key];
        });
        instance.component.update();
+     } catch (error) {
+       console.error('Failed to update spinner component:', error);
+     }
    }
  },
🧹 Nitpick comments (3)
apps/web-ele/src/bootstrap.ts (1)

36-40: Consider documenting the potential directive conflict.

The registration logic is correct, and the comment explains the configuration. However, it would be helpful to document the potential conflict between Element Plus's and Vben's v-loading directives in the codebase's documentation to help future maintainers understand why only one should be enabled.

packages/effects/common-ui/src/components/loading/directive.ts (2)

41-49: Add type validation for object values.

Consider adding type validation to ensure object values contain valid props for the components.

Apply this enhancement:

  function getOptions(binding: DirectiveBinding) {
    if (binding.value === undefined) {
      return { spinning: true };
    } else if (typeof binding.value === 'boolean') {
      return { spinning: binding.value };
    } else {
+     const value = binding.value as Record<string, unknown>;
+     // Add validation for known props
+     const validProps = ['spinning', 'size', 'text'];
+     Object.keys(value).forEach((key) => {
+       if (!validProps.includes(key)) {
+         console.warn(`Unknown prop '${key}' passed to loading/spinner component`);
+       }
+     });
      return { ...binding.value };
    }
  }

91-116: Improve style injection to handle duplicates.

The style injection should check for existing styles to prevent duplicates during hot reloads or multiple registrations.

Apply this enhancement:

  export function registerLoadingDirective(
    app: App,
    params?: loadingDirectiveParams,
  ) {
-   const style = document.createElement('style');
-   style.id = CLASS_NAME_RELATIVE;
-   style.innerHTML = `
-     .${CLASS_NAME_RELATIVE} {
-       position: relative !important;
-     }
-   `;
-   document.head.append(style);
+   // Check if style already exists
+   if (!document.getElementById(CLASS_NAME_RELATIVE)) {
+     const style = document.createElement('style');
+     style.id = CLASS_NAME_RELATIVE;
+     style.innerHTML = `
+       .${CLASS_NAME_RELATIVE} {
+         position: relative !important;
+       }
+     `;
+     document.head.append(style);
+   }

    if (params?.loading !== false) {
      app.directive(
        isString(params?.loading) ? params.loading : 'loading',
        loadingDirective,
      );
    }
    if (params?.spinning !== false) {
      app.directive(
        isString(params?.spinning) ? params.spinning : 'spinning',
        spinningDirective,
      );
    }
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa59335 and 9e09f6e.

📒 Files selected for processing (7)
  • apps/web-antd/src/bootstrap.ts (2 hunks)
  • apps/web-ele/src/bootstrap.ts (2 hunks)
  • apps/web-naive/src/bootstrap.ts (2 hunks)
  • packages/effects/common-ui/src/components/loading/directive.ts (1 hunks)
  • packages/effects/common-ui/src/components/loading/loading.vue (1 hunks)
  • packages/effects/common-ui/src/components/loading/spinner.vue (1 hunks)
  • playground/src/bootstrap.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • playground/src/bootstrap.ts
  • apps/web-antd/src/bootstrap.ts
  • packages/effects/common-ui/src/components/loading/loading.vue
  • packages/effects/common-ui/src/components/loading/spinner.vue
  • apps/web-naive/src/bootstrap.ts
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Check (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
apps/web-ele/src/bootstrap.ts (1)

4-4: LGTM!

The import statement is correctly placed and follows naming conventions.

packages/effects/common-ui/src/components/loading/directive.ts (1)

1-12: LGTM!

The imports are well-organized, and the use of symbols for instance keys prevents naming conflicts. The CSS class name is properly defined as a constant for reusability.

@mynetfan
mynetfan merged commit 579b1b4 into vbenjs:main Feb 23, 2025
@mynetfan
mynetfan deleted the feat/v-loading branch February 23, 2025 04:41
@github-actions github-actions Bot locked and limited conversation to collaborators Mar 26, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FEATURE: loading和spinner组件支持useLoading用法

1 participant