guilhermerodz / input-otp

One time passcode Input. Accessible & unstyled.

Home Page:https://input-otp.rodz.dev

Repository from Github https://github.comguilhermerodz/input-otpRepository from Github https://github.comguilhermerodz/input-otp

Improve safeInsertRule function

chonlatit-tpit opened this issue · comments

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.