Skip to content
quarry Artifact [cbcf89a3d1]
Login

Artifact [cbcf89a3d1]

Artifact cbcf89a3d1467ea4743cfdd4c8a7b50413ba65deff7b0ff701dfc644719fd362:


package web

import (
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
)

// Datastar 1.0.3 reads an attribute's plugin from the name up to the
// first colon, so a key spelled with a hyphen names a plugin that does
// not exist and the attribute is dropped without a word: data-on-submit
// never submits, data-class-dirty never marks the form. And a plugin
// that requires a key throws on a bare one, which the browser reports
// to the exceptions page: data-on="true" on the Git mirror section did.
// The plugins whose own names carry a hyphen are the exceptions.
var datastarHyphenPlugins = map[string]bool{
	"on-intersect": true, "on-interval": true, "on-signal-patch": true, "json-signals": true,
}

// Plain data attributes that share a plugin's prefix on purpose: read by
// the page's own script, and ignored by Datastar for the reason above.
var notDatastar = map[string]bool{
	"data-ref-repo": true, "data-ref-kind": true,
}

var (
	hyphenKey = regexp.MustCompile(`data-(on|attr|bind|class|computed|indicator|ref|signals|style|text|show|effect|init)-[a-z][a-z0-9_.-]*`)
	bareOn    = regexp.MustCompile(`data-on=`)
)

func TestDatastarAttributesAreSpelledSoTheyRun(t *testing.T) {
	files, err := filepath.Glob("*.go")
	if err != nil {
		t.Fatal(err)
	}
	for _, f := range files {
		if strings.HasSuffix(f, "_test.go") {
			continue
		}
		src, err := os.ReadFile(f)
		if err != nil {
			t.Fatal(err)
		}
		for i, line := range strings.Split(string(src), "\n") {
			for _, m := range hyphenKey.FindAllString(line, -1) {
				name := strings.SplitN(strings.TrimPrefix(m, "data-"), "__", 2)[0]
				if datastarHyphenPlugins[name] || notDatastar[m] {
					continue
				}
				t.Errorf("FAIL %s:%d: %s is a key spelled with a hyphen, which Datastar ignores; write it with a colon", f, i+1, m)
			}
			if bareOn.MatchString(line) {
				t.Errorf("FAIL %s:%d: data-on with no event throws in Datastar; name the event, or use another attribute", f, i+1)
			}
		}
	}
}