Skip to content

Consolidate marketplace content scripts with factory function #36

Description

@vertefra

Problem

contents/amazon.tsx and contents/walmart.tsx contain nearly identical code:

  • Same getStyle implementation
  • Same getOverlayAnchor implementation
  • Same App component structure
  • Only differences are marketplace-specific config values

Solution

Create a factory function to generate content scripts:

// contents/createMarketplaceContent.ts
import type { PlasmoCSConfig, PlasmoGetOverlayAnchor, PlasmoGetStyle } from "plasmo"
import styleText from "data-text:~style.css"
import { BaseProductApp } from "~/components/BaseProductApp"

interface MarketplaceConfig {
  matches: string[]
  urlMatches: RegExp[]
  getProductId: (url: string) => string | null
  marketplace: string
}

export const createMarketplaceContent = (config: MarketplaceConfig) => {
  return {
    config: { matches: config.matches } as PlasmoCSConfig,
    
    getStyle: (() => {
      const style = document.createElement("style")
      style.textContent = styleText
      return style
    }) as PlasmoGetStyle,
    
    getOverlayAnchor: (() => document.body) as PlasmoGetOverlayAnchor,
    
    App: () => (
      <BaseProductApp
        urlMatches={config.urlMatches}
        getProductId={config.getProductId}
        marketplace={config.marketplace}
      />
    )
  }
}

Then each marketplace file becomes:

// contents/amazon.tsx
import { createMarketplaceContent } from "./createMarketplaceContent"

const getAmazonProductId = (url: string): string | null => {
  const dpMatch = url.match(/\/dp\/([A-Z0-9]+)/)
  const gpMatch = url.match(/\/gp\/product\/([A-Z0-9]+)/)
  return dpMatch?.[1] || gpMatch?.[1] || null
}

const { config, getStyle, getOverlayAnchor, App } = createMarketplaceContent({
  matches: ["*://*.amazon.com/*"],
  urlMatches: [/\/dp\/|\/gp\/product\//],
  getProductId: getAmazonProductId,
  marketplace: "amazon"
})

export { config, getStyle, getOverlayAnchor }
export default App

Impact

  • Reduces duplicate code
  • Makes adding new marketplaces easier
  • Ensures consistency across marketplaces

Priority

High

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions