Skip to content

Improve safeInsertRule function #84

Open
@chonlatit-tpit

Description

We found the error from our monitoring tools.

Error:
input-otp could not insert CSS rule: [data-input-otp]:autofill { background: transparent !important; color: transparent !important; border-color: transparent !important; opacity: 0 !important; box-shadow: none !important; -webkit-box-shadow: none !important; -webkit-text-fill-color: transparent !important; }

We think the error come from this file/line.

function safeInsertRule(sheet: CSSStyleSheet, rule: string) {
try {
sheet.insertRule(rule)
} catch {
console.error('input-otp could not insert CSS rule:', rule)
}
}

We would like to improve this by follow code.

function safeInsertRule(sheet: CSSStyleSheet, rule: string) {
  if (!sheet || typeof rule !== 'string') {
    console.error('Invalid parameters for safeInsertRule:', { sheet, rule });
    return;
  }
  
  try {
    sheet.insertRule(rule);
  } catch (error) {
    console.error('input-otp could not insert CSS rule:', rule, error);
    // Fallback mechanism: Append the rule directly to the style element
    const styleElement = sheet.ownerNode as HTMLStyleElement;
    if (styleElement) {
      styleElement.appendChild(document.createTextNode(rule));
    }
  }
}

Explanation of Improvements
Detailed Error Logging: Captures and logs the specific error message.
Fallback Mechanism: Provides an alternative way to insert the rule if the primary method fails.
Parameter Validation: Ensures that the parameters are valid before attempting to insert the rule.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions