Skip to content

feat: Migrate utilities from UrlContextProvider to Zustand stores (resolves #269). #286

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

zzxthehappiest
Copy link
Contributor

Description

#269

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title, OR this isn't a
    breaking change.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

Copy link

coderabbitai bot commented May 21, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@@ -43,7 +43,7 @@ interface ViewStoreActions {
filterLogs: (filter: LogLevelFilter) => void;

loadPageByAction: (navAction: NavigationAction) => void;
updateIsPrettified: (newIsPrettified: boolean) => void;
setIsPrettified: (newIsPrettified: boolean) => void;
Copy link
Member

Choose a reason for hiding this comment

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

(i understand this is a WIP PR and the changes are not finalized yet)

for all Zustand store actions that do not simply change the value of a state, we prefer naming them with a updatePrefix. @coderabbitai create an issue for adding this in the dev docs

Copy link

Choose a reason for hiding this comment

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

🧩 Analysis chain

@junhaoliao I've created an issue to document the Zustand store action naming conventions in the development documentation. The issue captures your point that actions which do more than simply change a state value should use an updatePrefix, while simple setters can use the setPrefix.


🏁 Script executed:

#!/bin/bash
# Create an issue for documenting Zustand store action naming conventions
gh issue create \
  --title "Document Zustand store action naming conventions in dev docs" \
  --body "## Background

When implementing Zustand store actions, we follow these naming conventions:

- Use \`setX\` for actions that simply change the value of a state
- Use \`updateX\` for actions that do more than simply changing a value (e.g., perform additional logic, make API calls, update multiple states)

## Task

Add this naming convention to the development documentation to ensure consistent implementation across the codebase.

## Example

\`\`\`typescript
// Example of a simple setter (use 'set' prefix)
setPageNum: (newPageNum: number) => {
  set({pageNum: newPageNum});
}

// Example of a complex action (use 'update' prefix)
updateIsPrettified: (newIsPrettified: boolean) => {
  // Has additional logic beyond just setting the value
  if (newIsPrettified === get().isPrettified) {
    return;
  }
  set({isPrettified: newIsPrettified});
  
  // Performs other actions...
  setUiState(UI_STATE.FAST_LOADING);
  // ...
}
\`\`\`

## References

Related PR: ${GITHUB_PR_URL:-https://github.com/y-scope/yscope-log-viewer/pull/286}
" \
  --assignee "junhaoliao"

Length of output: 1196


@junhaoliao I've created an issue to document the Zustand store action naming conventions in the development documentation. You can find it here: #289


🧬 Code Graph Analysis Results

Relevant snippets for understanding src/stores/viewStore.ts and the user comment about naming conventions for Zustand store actions:


From src/typings/common.ts (line 10)

Nullable
  • Likely a type alias for nullable types used in the store, e.g., Nullable<T> = T | null.

From src/typings/states.ts (line 106)

UI_STATE
  • Enum or constants representing UI states such as READY, FAST_LOADING, etc., used in the store to manage UI state transitions.

From src/typings/notifications.ts (line 36)

DO_NOT_TIMEOUT_VALUE
  • Constant used for notification timeout duration indicating no timeout, used in error pop-ups in the store.

From src/stores/contextStore.ts (line 35)

CONTEXT_STORE_DEFAULT
  • Default values for the context store, including logEventNum, referenced in useViewStore for default event number.

From src/typings/logs.ts (lines 51 and 56)

LogLevelFilter
LOG_LEVEL
  • Types and constants for log filtering and log levels, used in filterLogs action.

From src/contexts/UrlContextProvider.tsx (line 285)

updateWindowUrlHashParams
  • Function to update URL hash parameters, called in updatePageData action.

From src/utils/actions.ts (lines 107 and 112)

ACTION_NAME
NavigationAction
  • Constants and types defining navigation action codes and their structure, used in loadPageByAction and getPageNumCursor.

From src/typings/worker.ts (lines 100, 102, 105, 107, 110)

CURSOR_CODE
EVENT_POSITION_ON_PAGE
BeginLineNumToLogEventNumMap
CursorType
PageData
  • Types and constants related to cursor codes, event positions, page data, and mappings used extensively in the store for pagination and log data management.

From src/services/LogFileManagerProxy.ts (lines 65-68)

startQuery (queryString: string, isRegex: boolean, isCaseSensitive: boolean): void {
    const logFileManager = this.#getLogFileManager();
    logFileManager.startQuery({queryString, isRegex, isCaseSensitive});
}
  • Method called in filterLogs action to start a log query.

From src/services/LogFileManager/index.ts (lines 356-386)

startQuery ({queryString, isRegex, isCaseSensitive}: QueryArgs): void {
    this.#queryId++;
    this.#queryCount = 0;

    // Send an empty query result with 0 progress to the render to init the results variable
    // because there could be results sent by previous task before `startQuery()` runs.
    this.#onQueryResults(0, new Map());

    // If the query string is empty, or there are no logs, return
    if ("" === queryString || 0 === this.#numEvents) {
        return;
    }

    // Construct query RegExp
    const regexPattern = isRegex ?
        queryString :
        queryString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    const regexFlags = isCaseSensitive ?
        "" :
        "i";

    try {
        const queryRegex = new RegExp(regexPattern, regexFlags);
        this.#queryChunkAndScheduleNext(this.#queryId, 0, queryRegex);
    } catch (e) {
        if (e instanceof SyntaxError) {
            console.error("Invalid regular expression:", e);
        }
        throw e;
    }
}
  • Implementation details of startQuery used by the proxy store, relevant to filterLogs action.

From src/services/LogFileManager/index.ts (lines 492-514)

#getCursorData (cursor: CursorType, numActiveEvents: number): CursorData {
    const {code, args} = cursor;
    switch (code) {
        case CURSOR_CODE.PAGE_NUM:
            return getPageNumCursorData(
                args.pageNum,
                args.eventPositionOnPage,
                numActiveEvents,
                this.#pageSize,
            );
        case CURSOR_CODE.LAST_EVENT:
            return getLastEventCursorData(numActiveEvents, this.#pageSize);
        case CURSOR_CODE.EVENT_NUM:
            return getEventNumCursorData(
                args.eventNum,
                numActiveEvents,
                this.#pageSize,
                this.#decoder.getFilteredLogEventMap(),
            );
        default:
            throw new Error(`Unsupported cursor type: ${code}`);
    }
}
  • Method related to cursor data retrieval, relevant to cursor handling in loadPageByAction and setIsPrettified.

These snippets provide context on types, constants, and external functions used in the viewStore.ts file, especially for actions that perform more complex logic than simple state updates, which relates to the user comment about naming conventions for such actions.


✏️ Learnings added
Learnt from: junhaoliao
PR: y-scope/yscope-log-viewer#286
File: src/stores/viewStore.ts:46-46
Timestamp: 2025-05-21T20:08:19.176Z
Learning: For Zustand store actions, use `setX` for functions that simply change the value of a state, and use `updateX` for functions that do more than just set a value (e.g., perform additional logic, make API calls, update multiple states).

Learnt from: junhaoliao
PR: y-scope/yscope-log-viewer#286
File: src/stores/viewStore.ts:46-46
Timestamp: 2025-05-21T20:08:19.176Z
Learning: For Zustand store actions, use `setX` for functions that simply change the value of a state, and use `updateX` for functions that do more than just set a value (e.g., perform additional logic, make API calls, update multiple states).

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@junhaoliao
Copy link
Member

@zzxthehappiest feel free to use #293 as a reference, where we replaced the NotificationConextProvider with a Zustand store

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants