@johnmorrisdotca/kyogijo-stadiums
abbreviate AFL_GROUNDS Arena ARENA_IDS arenaById arenaByName arenaByWikidata ArenaCapacity arenaCourtIn ArenaData ArenaName arenaNameIn arenaOfficialName arenaOfVenue arenaRinkIn ARENAS arenasByName ArenaSize ArenaSource arenaSourceUrl ArrowsLayer ArtisticPlan AthleticsFieldEvent AthleticsInfield AthleticsRace AthleticsStyle AthleticsTrackLook AxesOptions Background BACKGROUND_OPACITY BACKGROUND_PATTERNS BackgroundFit BackgroundOptions BackgroundPattern Bandwidth BaseballLeague BaseballRead BaseballSituation BasketballLeague Board BOARD_CLEAR BOARD_POSITIONS BoardBox BoardOptions BoardPoint BoardPosition bowlInside Box BudoScore BudoSport BudoStyle capitals chooseLeague COLOR_PROPERTIES Colors Comet conferenceOf ContourLayer contrastOf convertLength COURT_THEMES CourtFigures CourtMarks CourtStyle CoverQuirk CrowdOptions CrowdShape crowdStands CrowdStands DeckLook DelaunayLayer describe Detail DiamondFigures DirectionOptions DivePlan DivingPlatform dojo Dojo DojoSpec drawBadge drawDojo drawKyogijo drawLayers drawScore drawSurface DRIVE_CODES DriveLeg DriveRead DriveResult DugoutSide EmblemDrawOptions EmblemId EmblemRef EmblemRenderer EmblemStyleName ERA_CURRENT ERA_SOURCES ERA_SPORTS EraChange eraChanges eraRange EraRules EraRulesOf EraSource EraSpan EraSport eraStates Family FAMILY_OF Feature FEATURE_INFO FEATURES Fence fenceFor FIELD_SPORTS FieldArea FieldGoalPlan FieldOutline fieldPlan FieldPlan FieldShape FieldSport FieldStyle fitLines FittedLines FlagRenderer FlagRequest FlagShape FlowLayer footballIn FootballLeague FootballRead FootballRules FootballSituation Formation FormationLayer FormationPlayer FormationPosition FormationSport formatTime frameMatrix GoalInfo GoalStyle GRIDIRON_GROUNDS Ground GROUND_IDS groundById groundByName groundByWikidata GroundCompetition GroundData GroundName groundNameIn groundOfficialName GROUNDS groundsByName groundsHosting GroundSource groundSourceUrl GroundTournament groupOf HARDWOOD_SMALL HardwoodOptions hasHistory HEAT_RAMP_NAMES HEAT_RAMPS HeatBase HeatBins HeatDatum HeatLabels HeatLegend HeatmapLayer HeatRamp HeatRampName HeatStatistic HexbinLayer HexOrientation HillQuirk HockeyLeague HockeyRead HockeySituation HOME_FIRST HOME_FIRST_LEAGUES homeSideFor HullLayer inkOn isFieldSport isPoolSport isPortrait isUnit KYOGIJO_ATHLETICS_STYLE KYOGIJO_BACKGROUND_STYLE KYOGIJO_BUDO_STYLE KYOGIJO_COURTS_STYLE KYOGIJO_CROWD_STYLE KYOGIJO_CURLING_STYLE KYOGIJO_FEATURE_STYLE KYOGIJO_FIELDS_STYLE KYOGIJO_HARDWOOD_STYLE KYOGIJO_HEAT_STYLE KYOGIJO_LOOK_STYLE KYOGIJO_MARK_STYLE KYOGIJO_NOTE_STYLE KYOGIJO_PAGEANT_MOTION KYOGIJO_PAGEANT_STYLE KYOGIJO_POOL_STYLE KYOGIJO_SITUATION_STYLE KYOGIJO_SKATING_STYLE KYOGIJO_STRINGS KYOGIJO_STYLE KYOGIJO_TEAM_STYLE KYOGIJO_TRACK_STYLE KYOGIJO_WALLS_STYLE KyogijoWords LanePlan Language Layer LayerBase LayerKind layerTable LayerTeam League LEAGUE_SOURCES leagueAt LeagueAt leagueById LeagueChange leagueChanges leagueFigures leagueIds LEAGUES leagueSeason leagueSize LeagueSource LeagueSpan LedBoardOptions LedBoardPattern LegendLayer LIGHT_COLORS LIGHT_PRESETS LIGHTING_PRESETS LightingOptions LightingPreset LineDash LineDatum LinesLayer LineStyle LineupLayer LineupPlayer LineWidth Look LOOK_NAMES LOOK_PAIRS LookGroup LookName lookPalette LookPalette LookPaletteKey LOOKS lookStyle luminance MarkDatum MarkShape MlbRules MoveDatum Named NbaRules NetStyle NetworkLayer NetworkNode NhlRules officialName Orientation OUTCOMES OutcomeStyle outlinePath outlinePoints OverhangQuirk PaceOptions PageantOptions PageantStyle Paint Park PARK_IDS parkById parkByName parkByWikidata ParkData ParkDugouts parkNameIn parkOfficialName ParkPeriod ParkPeriodData parkPointsIn ParkQuirk parkQuirksIn PARKS parksByName ParkSource parkSourceUrl parkUnit ParkWall ParkWallData parkWallsIn parseTime PassDatum PlaceAlias placeBoard PlaceNameKind plainName planVenue PlayerDatum PointDatum PointQuirk PointsLayer PointStyle PoloPlan POOL_SPORTS PoolKind PoolLook poolPlan PoolPlan PoolRace PoolSection PoolSport PoolStyle QuirkKind QuirkName QuirkOptions RaceShow rampColour RangeBox RangeInfo RangeName RangeNamed RANGES readSituation RealVenue RealVenueData Reducer rescale Rescaler resolveLighting rgbOf RinkFigures Rope RopeColour rulesFor safeColour safeLogo safePicture Scale ScoreOptions seasonLabel ShootoutAttempt ShootoutRound Side Situation SituationContext SituationRead SituationTeam situationText Size SkatingDiscipline SkatingFurniture SkatingInfield SkatingRace SkatingStyle SOCCER SOCCER_PITCH_IDS SOCCER_PITCHES SOCCER_PROVIDER_IDS SOCCER_PROVIDERS soccerFrame SoccerFrame soccerLandmarks soccerPitchClass SoccerPitchClass SoccerPitchId SoccerProvider SoccerProviderId SoccerSize soccerSpec SoccerSpec SonarLayer Sport SPORTS StandGap StandOutline StandRing StandSector StatisticName statusLabel statusText StatusWord StripePattern SURFACE_UNITS SurfaceOptions Swimmer SwimmerStatus swimPlan SwimPlan TableOptions Tatami Team TeamMark TextDatum TextLayer TextStyle textWidth Theme Unit UNITS useEmblems useFlags VARIANTS VENUE_ATTRIBUTION VENUE_CONFERENCES VENUE_DIVISIONS VENUE_IDS VenueBasis venueBowl venueById venueByWikidata VenueConference VenueDivision VenueItem venueLayout VenueLayout VenueOptions venueOrientation VenueOrientation VenueOsm VenuePlan VenuePool venueRink VenueRoof VENUES venuesIn venuesInConference VERSION VoronoiLayer WALL_SEATS WallOptions WallPlace WaterJump winnerOf ZONE_SET_IDS ZONE_SETS ZoneSetId ZonesLayer
function abbreviate
abbreviate(name: string): string
A short form of a name: its initials when it has several words, else its first letters. Japanese names give their first two or three characters.
This is a guess at a label, not a code. For a national team it is often not the code the sport uses: "Spain" gives SPA, where FIFA's three-letter code is ESP ("Germany" gives GER, which happens to match; "Netherlands" gives NET, FIFA's is NED). Pass each team's abbr yourself (the FIFA, World Rugby or ICC code your data carries); the package bundles no table of country codes.
const AFL_GROUNDS
AFL_GROUNDS: readonly AflGround[]
The grounds whose length and width the AFL's venue pages print (read 2026-10-13), each within the Laws' range. The AFL's page for Adelaide Oval prints 190 by 125 m, a length beyond the 185 m the Laws allow, so that ground is not here.
type Arena
type Arena = ArenaData;
An arena as the package holds it: the data, with the sizes in the unit they were published in (see arenaRinkIn and arenaCourtIn for them in feet).
const ARENA_IDS
ARENA_IDS: readonly string[]
The keys of ARENAS, in the order of the data: the arenas in use first, then those of the past.
function arenaById
arenaById: (id: string | undefined) => Arena | undefined
The arena with a key, or undefined.
function arenaByName
arenaByName: (name: string | undefined) => Arena | undefined
The arena a name belongs to (the best match when several answer to it), or undefined.
function arenaByWikidata
arenaByWikidata: (wikidata: string | undefined) => Arena | undefined
The arena whose Wikidata item is Q894567, or undefined.
type ArenaCapacity
interface ArenaCapacity { hockey?: number; basketball?: number; }
The seats an arena holds for each sport, as the infobox of its article gives them. For hockey it is the figure of the article's current configuration: the latest dated ice-hockey figure, or the only one (Wikidata's P1083 carries no sport qualifier, so it is not used). An earlier figure is kept in the arena's note. Basketball is still the first figure the infobox gives.
function arenaCourtIn
arenaCourtIn: (arena: Arena | undefined, year?: number) => { length: number; width: number; } | undefined
The size of an arena's court in feet, in a year or today, when the sources publish one that differs from the NBA's 94 by 50 feet; else undefined.
type ArenaData
interface ArenaData { /** The key: `boston-garden`. */ id: string; /** The Wikidata item of the arena (`Q894567`), the key to join an arena to other data. */ wikidata: string; /** The everyday name in English (`Boston Garden`, `TD Garden`); the title of the English article is one of the `aliases`. */ name: string; /** Names the arena had for some years, in order of time: where two share a year the later one is the n…
An arena as the data gives it: the rink and the court are the sizes published where they differ from the league's.
type ArenaName
interface ArenaName { name: string; from: number; to: number; }
A name an arena had for some years, first to last.
function arenaNameIn
arenaNameIn(arena: Arena, year?: number, language?: Language): string
The name an arena had in a year (the name of the time in English; in Japanese there is one name for every year).
function arenaOfficialName
arenaOfficialName(arena: Arena, language?: Language, year?: number): string | undefined
The name an arena officially has in a language, when it is not the everyday name; else undefined.
function arenaOfVenue
arenaOfVenue: (venue: RealVenue) => Arena
The arena a venue is of.
function arenaRinkIn
arenaRinkIn: (arena: Arena | undefined, year?: number) => { length: number; width: number; } | undefined
The size of an arena's rink in feet, in a year or today (the latest), when the sources publish one that differs from the NHL's; else undefined and the NHL's 200 by 85 feet is the rink.
Example
import { arenaById, arenaRinkIn } from "@johnmorrisdotca/kyogijo-stadiums/arenas";
console.log(arenaRinkIn(arenaById("boston-garden")!), arenaRinkIn(arenaById("matthews-arena")!, 1926), arenaRinkIn(arenaById("td-garden")!));
// { length: 190.9, width: 83 } { length: 220, width: 90 } undefined
const ARENAS
ARENAS: Readonly<Record<string, import("/home/runner/work/kyogijo-stadiums/kyogijo-stadiums/src/arenas.core").ArenaData>>
Every arena by its key: the homes of the NHL's, the NBA's, the WNBA's and the PWHL's clubs, today's and the old ones, each with where it stands, when it was in use, its names, its seats for each sport and, where the sources publish one that differs from the league's, the size of its rink or its court.
Example
import { ARENAS } from "@johnmorrisdotca/kyogijo-stadiums/arenas";
const garden = ARENAS["boston-garden"];
console.log(garden.name, garden.city, garden.from, garden.to, garden.capacity?.hockey);
// Boston Garden Boston 1928 1995 14448
function arenasByName
arenasByName: (name: string | undefined) => Arena[]
The arenas that answer to a name, best match first (see placesByName): the everyday names, then the official and cited names, then the former names and the nicknames.
type ArenaSize
interface ArenaSize { length: number; width: number; unit: "ft" | "m"; /** The first and the last year it had this size, where the source gives them. */ from?: number; to?: number; /** Where it was read: the article and its revision, and in a few words what it says (not a copied passage). */ source: string; }
A published size of an ice rink or a basketball court, in the unit it was published in, with where it was read and, if the source dates it, the years it had that size.
type ArenaSource
interface ArenaSource { title: string; revision: number; }
Where an arena's facts were read: an article of Wikipedia at a revision.
function arenaSourceUrl
arenaSourceUrl(source: ArenaSource, language?: "en" | "ja"): string
The address of the revision of an article that an arena's facts were read from.
type ArrowsLayer
interface ArrowsLayer extends LayerBase { kind: "arrows"; data: readonly LineDatum[]; style?: LineStyle; }
type ArtisticPlan
interface ArtisticPlan extends Common { sport: "artisticswimming"; area: "olympic" | "minimum"; length: number; width: number; /** For the minimum area: the deep part, in metres from the left wall and the top wall, and its size. */ deep: { x: number; y: number; length: number; width: number } | undefined; }
An artistic swimming area to draw.
type AthleticsFieldEvent
type AthleticsFieldEvent = "high-jump" | "pole-vault" | "long-jump" | "triple-jump" | "shot-put" | "discus-throw" | "hammer-throw" | "javelin-throw";
The field events a drawing can mark in the infield, and alone at a large scale (layout).
type AthleticsInfield
type AthleticsInfield = "pitch" | "grass" | "none";
What lies inside the track: the soccer pitch the package draws (pitch), plain mown grass, or nothing but the track's own surface.
type AthleticsRace
type AthleticsRace = | "60m" | "60m-hurdles" | "100m" | "100m-hurdles" | "110m-hurdles" | "200m" | "400m" | "400m-hurdles" | "800m" | "1000m" | "1500m" | "mile" | "2000m" | "3000m" | "5000m" | "10000m" | "2000m-steeplechase" | "3000m-steeplechase" | "4x100m" | "4x400m";
The races a drawing can mark: where each starts, how it is staggered or curved, its hurdles or its exchange zones. A race is named by its distance, in kebab case.
type AthleticsStyle
interface AthleticsStyle { /** The lanes of the oval: 4 to 9 outdoors (8 by default; the Manual says nine is the most there should be), 4 to 6 on the indoor track (6 by default). */ lanes?: number; /** The lanes of the straight that runs on beyond the oval's, 6 to 10 (the oval's number by default), as the straight of a 10-lane stadium is built (Manual 2.2.2). */ straightLanes?: number; /** The colour of the track: `…
What an athletics drawing takes beyond a surface: the number of lanes, the colour of the track, what is in the infield, which races and which field events are marked. Every part is optional; the standard 400 m track of World Athletics, with eight lanes, a red track, a soccer pitch inside it and every field event in its usual place, is drawn without any.
type AthleticsTrackLook
type AthleticsTrackLook = "red" | "blue" | "terracotta" | "green";
The colour of the track: Mondo red (the usual), Berlin's blue (the 2009 World Championships), the terracotta of a club track, or green. A colour of your own is colors.surface... or colors.track.
type AxesOptions
interface AxesOptions { /** A frame of `FRAMES` (or one of your own) for the sport: the ticks are its numbers. The surface's own (feet, or `units`) when missing. */ frame?: string | Frame; /** The distance between ticks, or the values to put one at, for both axes or for `x` and `y` each. A round step that gives about eight ticks when missing. */ ticks?: number | readonly number[] | { x?: number | readonly number[]; …
The axes of axes: a frame, where the ticks stand and whether they are numbered.
type Background
type Background = BackgroundPattern | "none" | BackgroundOptions;
A ground: a pattern's name, "none", or the options in full.
const BACKGROUND_OPACITY
BACKGROUND_OPACITY: Readonly<Record<BackgroundPattern, number>>
The opacity each pattern is drawn at when opacity says nothing.
const BACKGROUND_PATTERNS
BACKGROUND_PATTERNS: readonly BackgroundPattern[]
The patterns, in the order a menu lists them.
type BackgroundFit
type BackgroundFit = "cover" | "contain" | "stretch";
How a photograph fills the ground: cover fills it and cuts what overhangs, contain shows all of it, stretch fills it out of shape.
type BackgroundOptions
interface BackgroundOptions { /** A pattern drawn over the ground, in a low opacity. */ pattern?: BackgroundPattern; /** A colour under the pattern and the photograph (a hex colour, `rgb()`, `hsl()`, a name or `var(--name)`). Without it the ground keeps its own colour. */ color?: string; /** The opacity of the pattern, 0 to 1. Each pattern has its own subtle one. */ opacity?: number; /** The size of the pattern's ti…
A ground in full. Every part is optional; with none, there is no ground.
type BackgroundPattern
type BackgroundPattern = "felt" | "grass" | "wood" | "ice" | "paper" | "grid" | "dots";
The patterns: a tile of shapes repeated over the ground.
type Bandwidth
type Bandwidth = number | readonly [number, number] | "scott";
The shape of a density's bandwidth.
type BaseballLeague
type BaseballLeague = LeagueBase<"baseball", DiamondFigures> & { game: "baseball" | "softball" };
A league with a diamond of its own.
type BaseballRead
interface BaseballRead { kind: "baseball"; bases?: [boolean, boolean, boolean]; outs?: number; inning?: number; half?: "top" | "bottom"; balls?: number; strikes?: number; }
Baseball, read.
type BaseballSituation
interface BaseballSituation { /** The runners: `[first, second, third]`, `true` for a base with a runner on it. */ bases?: readonly [boolean, boolean, boolean] | readonly boolean[]; /** The outs, 0 to 3. */ outs?: number; /** The inning, 1 or more. */ inning?: number; /** `top` (the visitors bat) or `bottom` (the home team bats). */ half?: "top" | "bottom"; /** The count: balls 0 to 3 (four is a walk and is not a co…
Baseball's situation (softball and NPB too).
type BasketballLeague
type BasketballLeague = LeagueBase<"basketball", CourtFigures>;
A league with a basketball court of its own.
type Board
interface Board { kind: "springboard" | "platform"; height: number; /** The plummet: x from the pool wall the boards stand at, y across from the top wall. */ x: number; y: number; length: number; width: number; }
One board of a diving well: a springboard or a platform, with its plummet (metres from the wall, then across from the top) and its size.
const BOARD_CLEAR
BOARD_CLEAR: 0.34
The share of a drawing's width and of its height that is kept clear round its middle: a board placed by name does not reach into it, so the middle of the playing area, where the score's panel stands, is never covered.
const BOARD_POSITIONS
BOARD_POSITIONS: readonly BoardPosition[]
The positions, in the order a menu lists them.
type BoardBox
interface BoardBox { x: number; y: number; w: number; h: number; }
A box: a drawing's viewBox, or the place a board takes in it.
type BoardOptions
interface BoardOptions { /** The board, as SVG text (`<svg …>…</svg>`): the string `resultsBoard`, `boutBoard` or `broadcastMedalTable` of Taisen Brackets gives. It is written as an image, so nothing in it can run and its styles stay in it. Anything else is ignored. */ svg: string; /** The board's own width and height, the numbers its maker gives (`resultsBoardSize`, `boutBoardSize`, `broadcastMedalSize`): they give…
A board over a drawing.
type BoardPoint
interface BoardPoint { x: number; y: number; anchor?: "start" | "center"; }
A place of your own: the board's top left corner (or, with anchor: "center", its middle) at this share of the drawing's width (x) and height (y), 0 to 1. The board may then cover the middle of the surface: you asked for it.
type BoardPosition
type BoardPosition = "top" | "bottom" | "side" | "left" | "corner" | "top-left" | "top-right" | "bottom-left" | "bottom-right";
Where a board goes. top and bottom are centred on the drawing's top and bottom edge, side is at the right edge, centred, left the same at the left, corner is the top right corner, and the four corners by their names.
function bowlInside
bowlInside(plan: VenuePlan): boolean
Whether the bowl lies inside the building: every corner of every tier's outer edge is inside the footprint.
type Box
interface Box { x: number; y: number; w: number; h: number; }
An axis-aligned box, in feet.
type BudoScore
interface BudoScore { /** Judo, karate: the number of ippon (judo: 1 ends the contest; the IJF's scoreboard writes 100). */ ippon?: number; /** Judo (10 on the scoreboard), karate (2 points). Two waza-ari are ippon in judo. */ wazaari?: number; /** Judo (1 on the scoreboard), karate (1 point). */ yuko?: number; /** Judo: the shido, three of which are hansoku-make. Karate: the warnings (chui), up to three. */ shido?:…
What each team has scored, as the sport counts it. Every part is optional; what is not given is left out of the board.
type BudoSport
type BudoSport = "judo" | "karate" | "kendo" | "sumo" | "kyudo" | "dojo";
The budō: the contest areas of judo and karate, the kendo shiai-jo, the sumo dohyō, the kyūdōjō, and a dojo of tatami.
type BudoStyle
interface BudoStyle { /** A named look: the colours of the mats and of the floor. Judo: `yellow-red` (the IJF's own, the default), `yellow-blue`, `blue-grey`, `green-beige` (the traditional tatami), `green-red` (green mats with a red danger zone) and `black-red`. Karate: `blue-red` (the default), `blue-black`, `green-beige`. Kendo: `wood` (the default), `blond`. Sumo: `clay`. Kyūdō: `wood`. Dojo: `green-beige` (the …
What a budō drawing takes beyond a surface. Every part is optional: a judo contest area is the IJF's of 10 m with a safety area of 4 m, a karate area the WKF's kumite square, a kendo shiai-jo of 10 m, a dohyō of the Japan Sumo Association and a kyūdōjō of 28 m with five shooters, drawn without any.
function capitals
capitals(text: string): string
The text in capitals when it has Latin letters; any other text is left as it is.
function chooseLeague
chooseLeague(o: Pick<SurfaceOptions, "sport" | "league"> & Partial<Pick<SurfaceOptions, "budo">>): { sport: Sport; league: League | undefined; }
Which league the options ask for: the league, and the sport it is drawn as. No league is the sport's own. A league the sport's own (nba for nba) is the sport as it is drawn without one; one of the football leagues that is a sport of its own (cfl) is that sport. A league of another family, or one that does not exist, is an error that says what to use.
Example
import { chooseLeague } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
console.log(chooseLeague({ sport: "nba", league: "fiba" }).league?.name.en, chooseLeague({ sport: "nfl", league: "cfl" }).sport);
// FIBA basketball court cfl
const COLOR_PROPERTIES
COLOR_PROPERTIES: Readonly<Record<keyof Colors, string>>
The CSS custom property each colour of Colors sets.
type Colors
interface Colors { /** The ground round the surface. */ apron?: string; /** The playing surface: turf, ice, wood, outfield grass. */ surface?: string; /** The second tone of mown stripes and of a worn floor. */ surfaceAlt?: string; /** Painted lines. */ line?: string; /** Hockey's blue lines and the centre circle. */ blue?: string; /** Hockey's red lines, creases and face-off circles. */ red?: string; /** The boards…
The colours of the drawing. Each key is a CSS custom property, --ky-<key in kebab case>, set on the svg. Any CSS colour that is a hex colour, rgb(), hsl(), a colour name or var(--name) is drawn; anything else is ignored.
type Comet
interface Comet { /** The opacity at the start, 0 to 1. 0.05 by default. */ from?: number; /** Draw it as a shape that thickens towards the end, not as a stroke of one width. */ taper?: boolean; }
The look of a comet: a line that fades in along its length, and may also thicken.
function conferenceOf
conferenceOf: (division: VenueDivision) => VenueConference
The conference a division of the NHL is in.
type ContourLayer
interface ContourLayer extends HeatBase { kind: "contour"; /** The kernel's width, in the layer's units (one number, or one for each axis), or `scott` (the default: Scott's rule, each axis's spread times n^(-1/6)). */ bandwidth?: Bandwidth; /** A multiple of the bandwidth: under 1 follows the data more closely, over 1 smooths it. 1 by default. */ smooth?: number; /** The grid the density is computed on, nodes across…
A kernel density estimate of the marks, drawn as filled bands or lines (hockey_rink's contour and contourf, mplsoccer's kdeplot).
function contrastOf
contrastOf(a: string | undefined, b: string | undefined): number | undefined
The contrast ratio of two colours (WCAG 2.2): 1 to 21, or undefined when a colour cannot be read without a browser.
function convertLength
convertLength(value: number, from: Unit, to: Unit): number
A length in another unit.
Example
import { convertLength } from "@johnmorrisdotca/kyogijo-stadiums/geometry";
console.log(convertLength(100, "yd", "ft"), convertLength(200, "ft", "m").toFixed(2));
// 300 60.96
const COURT_THEMES
COURT_THEMES: Readonly<Record<"night" | "maple" | "twoTone" | "sunburst" | "tournament", CourtStyle>>
Five looks for a basketball court, made of plain colours and no one's marks, to start from: the paint, the border, the wood and the words on the baselines are the parts a court's design is made of. Pass one as court, or spread it and change a part.
Example
import { COURT_THEMES, drawKyogijo } from "@johnmorrisdotca/kyogijo-stadiums";
const svg = drawKyogijo({ sport: "nba", court: { ...COURT_THEMES.twoTone, baselineText: "HARBOUR CITY" } });
console.log(svg.includes("--ky-key:#1e4f8f"));
// true
type CourtFigures
interface CourtFigures { /** Baseline to baseline, inside the lines. */ length: number; /** Sideline to sideline, inside the lines. */ width: number; /** The free-throw lane (restricted area), side to side. */ laneWidth: number; /** A lane that is wider at the baseline than at the free-throw line (a trapezoid): its width at the baseline. */ laneEndWidth?: number; /** The free-throw line, from the baseline. */ freeTh…
The figures of a basketball court. Lengths, in the unit of the table they are in.
type CourtMarks
interface CourtMarks { /** The marks that divide the free-throw lane, from the baseline. The first is the block. */ lane: number[]; /** The lower defensive box's marks: from the lane, from the baseline, and how long; or none. */ box: { fromLane: number; fromBaseline: number; length: number } | null; /** The marks 28 feet from the baseline on the sidelines: where, and how long. */ sideline: { fromBaseline: number; le…
The small marks the NBA's court diagram has along the lane and the sidelines, drawn in the full detail. Lengths.
type CourtStyle
interface CourtStyle { /** The wood: the floor's main tone. */ wood?: string; /** The second tone of the planks. */ woodAlt?: string; /** The ground outside the court. */ apron?: string; /** The ring between the court's lines and the apron, the out-of-bounds border. */ border?: string; /** The paint of both keys. */ key?: string; /** The paint of the left key, over `key`. */ keyLeft?: string; /** The paint of the ri…
The look of a basketball court. Every part is optional, and each falls back to the theme's.
type CoverQuirk
interface CoverQuirk extends QuirkBase { kind: "ivy" | "basket"; from: number; to: number; }
Ivy on the wall, or a basket on top of it, along a stretch of the fence.
type CrowdOptions
interface CrowdOptions { /** * The venue: `bowl` (stands on every side), `sides` (the long sides only), `horseshoe` (three sides, the open end at the right, or at the left with `open: "left"`; a * ballpark's outfield with a gap at the batter's eye) or `grandstand` (a ballpark's infield stands only). Each sport has its usual one. */ shape?: CrowdShape; /** * The stands of the arena's real venue, for an NHL `arena` th…
The stands and the crowd round a surface (crowd). Every part is optional. true is the sport's usual venue, 85 percent full, with an away end, drawn in detail. See docs/crowd.md.
type CrowdShape
type CrowdShape = "bowl" | "sides" | "horseshoe" | "grandstand";
The shape of a venue's stands round the playing surface.
function crowdStands
crowdStands(o: SurfaceOptions): CrowdStands | undefined
The stands round a surface as data: the rings of seats with their outlines, heights and rake, the blocks of visitors and the places left open, in feet in the surface's wide frame, so that another view (a 3D one) can raise them. undefined when the options ask for no crowd (or for a special game, which has none).
Example
import { crowdStands } from "@johnmorrisdotca/kyogijo-stadiums";
const stands = crowdStands({ sport: "soccer", crowd: true });
console.log(stands?.rings.map((ring) => ring.id).join(" "), stands?.shape, stands?.stadium);
// lower upper bowl purpose
type CrowdStands
interface CrowdStands { sport: Sport; shape: CrowdShape; /** The stadium a soccer pitch stands in: `purpose` (its own), `nfl` or `cfl` (a gridiron's), or nothing for another sport. */ stadium?: "purpose" | "nfl" | "cfl"; /** The playing surface, in the wide frame. */ box: Box; /** * The floor round the playing surface, where the surface draws more than its box (a court's run-off, a track's sprint straight, runways a…
The stands round a surface as data.
type DeckLook
type DeckLook = "plain" | "tiled";
How the deck is painted: one colour, or in tiles.
type DelaunayLayer
interface DelaunayLayer extends PlayersBase { kind: "delaunay"; /** One triangulation for each team (`team`, the default) or one for all the players. */ by?: "team" | "all"; /** Fill the triangles, not only draw their edges. */ triangles?: boolean; }
The Delaunay triangulation of the players: triangles whose circle holds no other player, a mesh of near neighbours.
function describe
describe(o: SurfaceOptions | ScoreOptions): { title: string; description: string; }
A drawing's title and description, in a language.
type Detail
type Detail = "full" | "simple";
How much of the surface's markings are drawn. simple leaves out the small ones, such as hash marks.
type DiamondFigures
interface DiamondFigures { /** The distance between bases (the side of the square). */ base: number; /** The side of a base. */ baseSize: number; /** The front of the pitcher's plate, from the back point of home plate. */ pitcher: number; /** The pitcher's plate: how long (across) and how deep. */ pitchersPlate: { width: number; depth: number }; /** The mound's radius, or a softball pitcher's circle's. */ moundRadiu…
The figures of a diamond. Lengths, in the unit of the table they are in.
type DirectionOptions
interface DirectionOptions { /** The end the home team attacks, as the surface is drawn wide: `left` or `right`. In the first period, unless `period` says another. */ home?: Side; /** The end the away team attacks. */ away?: Side; /** * The period the arrows are for. The teams change ends by the sport's rule (hockey after every period, football after the first and the third quarters, * basketball at the half), so `h…
Which way a team attacks, and in which period, for the arrow of direction.
type DivePlan
interface DivePlan extends Common { sport: "diving"; length: number; width: number; boards: Board[]; /** The metres behind the wall that the stands reach, for the view. */ behind: number; }
A diving well to draw.
type DivingPlatform
type DivingPlatform = 1 | 3 | 5 | 7.5 | 10;
The boards of a diving well that can be asked for.
function dojo
dojo(spec?: DojoSpec): Dojo
A dojo (道場): the floor in mats, laid as real tatami units, with the walls, doors, windows, shrine and kamiza. mats is the floor: a number is its area in jō (8, 12, 20, 50, 100 and 200 give the usual shapes), [across, along] the whole mats across and along, { width, length, unit } a size in metres, feet, mats or jō; pattern is how it is laid (traditional: no four corners meet; competition, checker, border).
Example
import { dojo } from "@johnmorrisdotca/kyogijo-stadiums/budo";
const d = dojo({ jo: 20 });
console.log(d.jo, d.width.toFixed(2), d.length.toFixed(2), d.counts.full, d.counts.half, d.pattern);
// 20 7.28 4.55 18 4 traditional
type Dojo
interface Dojo { /** The spec it was made from. */ spec: DojoSpec; /** The mat standard: a league of the `dojo` sport (`chukyoma`, `kyoma`, `edoma`, `danchima`, `judo-2x1`) and the mat's size in metres. */ standard: string; mat: { length: number; width: number }; /** The floor in metres: its width (x, the longer side) and its length (y). */ width: number; length: number; /** The floor's area in jō: the area over the…
A dojo made from a spec: the floor as data.
type DojoSpec
interface DojoSpec { /** * The floor. A number is its area in jō (畳): 8, 12, 20, 50, 100 or 200 give the usual shapes. `[across, along]` is the number of whole mats across the floor and along it * (`[5, 4]` is 20 jō). `{ width, length, unit }` is a size in metres (the default), feet, `mat` (as the array) or `jo`. 20 jō by default. */ mats?: DojoSize; /** The area in jō, as `mats: 20` says it. */ jo?: number; /** `tr…
A dojo (道場): the floor in mats, laid out as real tatami units, and what stands round it. Every part is optional: 20 jō of traditional mats with the kamiza at the north, no walls. dojo() makes its plan, and drawKyogijo({ sport: "dojo", dojo }) draws it.
function drawBadge
drawBadge(options: ScoreOptions): string
Draw a score as one compact strip, for a list. The same as drawScore with size: "badge".
function drawDojo
drawDojo(spec?: DojoSpec, more?: Partial<SurfaceOptions>): string
Draw a dojo: drawKyogijo with the spec as the options' dojo, and any other option the caller gives.
function drawKyogijo
drawKyogijo(o: SurfaceOptions | ScoreOptions): string
Draw a surface, or a score on a surface, as an SVG string. With home and away it is a score; without them, the bare surface. The same options always give the same string.
Example
import { drawKyogijo } from "@johnmorrisdotca/kyogijo-stadiums";
const svg = drawKyogijo({
sport: "nhl",
away: { name: "USA", abbr: "USA", score: 3, color: "#1c3f7a" },
home: { name: "Canada", abbr: "CAN", score: 2, color: "#d52b1e" },
status: "final-ot",
});
console.log(svg.startsWith("<svg"), svg.includes("USA"));
// true true
function drawLayers
drawLayers(options: SurfaceOptions | ScoreOptions, layers: readonly Layer[]): string
The layers of a drawing as one SVG group, in the surface's own frame, for a caller who composes the drawing's parts. Put it inside the surface's group (the one with the quarter turn, when the drawing is tall) and the marks lie on the surface, cut to its outline, with the text still upright. The same options and layers always give the same string; drawKyogijo draws exactly this when it is given layers.
Example
import { drawLayers } from "@johnmorrisdotca/kyogijo-stadiums";
const group = drawLayers({ sport: "nhl", id: "rink" }, [
{ kind: "points", name: "shots", data: [{ x: 169, y: 20.5, outcome: "goal", team: "home" }, { x: 150, y: 40, outcome: "shot", team: "home" }] },
]);
console.log(group.startsWith('<g class="ky-layers"'), group.includes("2 shots"));
// true true
function drawScore
drawScore(options: ScoreOptions): string
Draw a score on a surface.
function drawSurface
drawSurface(options: SurfaceOptions): string
Draw a bare surface. The same as drawKyogijo without teams.
const DRIVE_CODES
DRIVE_CODES: Readonly<Record<DriveResult, string>>
The short code each drive result is written with at the head of its arrow.
type DriveLeg
interface DriveLeg { /** The team that had the ball. The team in possession when missing. */ team?: SituationTeam; /** Yards from the team's own goal line where it began. */ from: number; /** Yards from the team's own goal line where it ended. */ to: number; /** How it ended. */ result?: DriveResult; }
One drive of a drive chart: where it started and where it ended, in yards from the team's own goal line (0 the goal line it defends, 100 the one it attacks; 110 on the CFL's field), and how it ended.
type DriveRead
interface DriveRead { team: SituationTeam; from: number; to: number; result?: DriveResult; toward: "left" | "right"; }
A drive, read: in yards from the team's own goal line, and the end it heads for.
type DriveResult
type DriveResult = "touchdown" | "field-goal" | "missed-field-goal" | "punt" | "turnover" | "interception" | "fumble" | "downs" | "safety" | "end-of-half";
How a drive of a football game ended.
type DugoutSide
type DugoutSide = "first" | "third";
The sides of the field a dugout is on: along the first base line or the third.
type EmblemDrawOptions
interface EmblemDrawOptions { style?: EmblemStyleName; /** The colour of the emblem's main part: a crest takes the team's colour. */ tint?: string; /** A second colour: a crest's band. */ accent?: string; /** The letters of a crest, up to three. */ initials?: string; /** `inherit`, `auto` (by the device's setting), `light` or `dark`. */ theme?: "inherit" | "auto" | "light" | "dark"; size?: number; }
What kyogijo asks of a renderer. It is a subset of dougu-sports' EmblemOptions.
type EmblemId
type EmblemId = Known<DouguId>;
The ids of dougu-sports' emblems ("trophy:cup", "crest:shield"), when that package is installed, so that an editor completes them; any other string otherwise. An id may end in /metal, /line or /color, and a trophy or an award may be written without its group ("cup"). Nothing is imported at run time.
type EmblemRef
type EmblemRef = EmblemId | `${EmblemId}/${EmblemStyleName}` | (string & {});
An emblem as a logo, a mark or a pageant's emblem is given: its id, with or without a style, or any string (an address, a data address or an SVG document).
type EmblemRenderer
type EmblemRenderer = (id: string, options?: EmblemDrawOptions) => string;
A function that draws an emblem from its id as a document of SVG, and throws for an id it does not know: renderEmblem of @johnmorrisdotca/dougu-sports/emblems is one. The id may end in /metal, /line or /color, and the renderer reads that suffix.
type EmblemStyleName
type EmblemStyleName = "metal" | "line" | "color";
The styles an emblem is drawn in: full colour with metallic gradients, one outline in the page's ink, or flat fills.
const ERA_CURRENT
ERA_CURRENT: 2026
The season whose rules are "today's", and the one a drawing without a year shows: the data were last checked in 2026. A change scheduled for a later season is planned and is drawn only when that season is asked for.
const ERA_SOURCES
ERA_SOURCES: Readonly<Record<string, EraSource>>
Every page a change was read from, by id. Wikipedia is cited by revision, for facts only.
const ERA_SPORTS
ERA_SPORTS: readonly EraSport[]
The sports with a history, in the order a menu lists them.
type EraChange
interface EraChange { /** `nhl.trapezoid.2005`. */ id: string; sport: EraSport; /** The marking's name: a key of the sport's rules. */ feature: string; /** The first season, or `null` for the state the sport started with. */ from: number | null; value: unknown; what: string; ja: string; sources: string[]; planned: boolean; approx: boolean; }
A change in the markings: one span of one marking that started in some season.
function eraChanges
eraChanges(sport: EraSport): EraChange[]
Every change of a sport's markings, in season order: what moved, from which season, in a sentence in English and in Japanese, and the sources that say so. The state a sport started with is not a change and is left out (see eraStates).
Example
import { eraChanges } from "@johnmorrisdotca/kyogijo-stadiums/eras";
const nhl = eraChanges("nhl");
console.log(nhl.length, nhl[0].id, nhl[0].from);
// 12 nhl.centreLine.1943 1943
function eraRange
eraRange(sport: EraSport): { from: number; to: number; }
The seasons a sport's history is drawn for: from the league's first to today's, or to a planned season when one is announced.
type EraRules
interface EraRules<S extends EraSport = EraSport> { sport: S; /** The season asked for (the year it starts in); today's when none was. */ year: number; /** Its name: `1979–80`. */ season: string; /** The markings. Every one is in feet, except the mound's height in inches. */ rules: EraRulesOf[S]; /** The states in force that are not today's, each as the change that began it (a marking in `gaps` is not listed). */ di…
The markings in force in a season, with what differs from today's and what is not known.
type EraRulesOf
interface EraRulesOf { nhl: NhlRules; nba: NbaRules; nfl: FootballRules; cfl: FootballRules; mlb: MlbRules; }
The rules of a sport in a season.
type EraSource
interface EraSource { id: string; /** The page: the article's title for Wikipedia, else the page's own. */ title: string; /** Who publishes it. */ by: string; /** For Wikipedia (CC BY-SA 4.0): the revision of the article, so that the figure can be checked. */ revision?: number; url: string; /** What was taken from it. */ note?: string; }
Where a change was read.
type EraSpan
interface EraSpan<T> { /** The first season it was in force, or `null` for "from the start" (the state the earliest season of the sport had). */ from: number | null; value: T; /** What it was, in a sentence. */ what: string; /** The same in Japanese. */ ja: string; /** Keys of `ERA_SOURCES`; at least one. */ sources: string[]; /** A rule announced for a season that has not been played yet. It is drawn only when that…
One state of a marking, from a season on.
type EraSport
type EraSport = "nfl" | "cfl" | "nhl" | "nba" | "mlb";
The sports whose markings have a history here. The IFAF's surface is 2021's and has none.
function eraStates
eraStates(sport: EraSport): EraChange[]
The state each marking of a sport started with: the spans that begin "from the start".
type Family
type Family = "basketball" | "hockey" | "football" | "baseball" | "curling" | "tennis" | "volleyball" | "badminton" | "pickleball" | "tabletennis" | "padel" | "squash" | "racquetball" | "sepaktakraw" | "teqball" | "roundnet" | "netball" | "lacrosse" | "rugby" | "afl" | "gaelic" | "cricket" | "fieldhockey" | "handball" | "athletics" | "skating" | "judo" | "karate" | "kendo" | "sumo" | "kyudo" | "dojo" | "mma" | "boxi…
The families of surface a league is a variant of.
const FAMILY_OF
FAMILY_OF: Readonly<Record<Sport, Family | undefined>>
The family of surface each sport draws; soccer's variants are its pitches (pitch), not leagues.
type Feature
interface Feature { /** What a caller names it by: `blue-lines`. */ name: string; /** * What its colour is given to: the custom properties the part is painted with (`--ky-red`), or a CSS property (`stroke`) for a part the stylesheet paints in a * colour that is not a property. */ props: readonly string[]; /** What it is, for the docs. */ about: string; }
A part of a surface that can be coloured on its own.
const FEATURE_INFO
FEATURE_INFO: Readonly<Record<string, readonly Feature[]>>
The features of each sport, with what each colours. A sport whose surface has none named (one added since) is missing here.
const FEATURES
FEATURES: Readonly<Record<string, readonly string[]>>
The names of the features of each sport: the keys featureColors takes. Football's three fields have the same, and so have the five net sports.
Example
import { FEATURES } from "@johnmorrisdotca/kyogijo-stadiums";
console.log(FEATURES.nhl.includes("blue-lines"), FEATURES.nfl.length);
// true 12
type Fence
interface Fence { left: number; leftCenter: number; center: number; rightCenter: number; right: number; }
The distances to a ballpark's fence in feet, at the foul lines, between and in the middle.
function fenceFor
fenceFor(park: Park | undefined, fence: Partial<Fence> | undefined, year?: number, generic?: readonly FencePoint[]): FencePoint[]
The fence points a drawing uses: a park's (as it stood in year, when the park has dated fences), with any of the five usual distances in fence laid over them, or the usual 330, 375, 400, 375 and 330 feet of a generic field (or the generic points a league's rules give).
const FIELD_SPORTS
FIELD_SPORTS: readonly FieldSport[]
The field sports, in the order a menu lists them.
type FieldArea
interface Area extends Named { cls: "ky-area" | "ky-zone" | "ky-dirt" | "ky-key" | "ky-boards" | AthleticsArea | SkatingArea | BudoArea; /** Fill the path's insides by the even-odd rule: a ring (the track between its kerb and its outer edge). */ evenodd?: boolean; /** A rectangle `[x0, y0, x1, y1]`, an ellipse's centre and radii, a path of your own, or a frame: the ring between a rounded rectangle and the one `thick…
A painted area, under the lines: a rectangle or an ellipse filled with a class of the stylesheet (ky-area, the tint of a goal area, or ky-zone).
type FieldGoalPlan
interface GoalPlan { end: "left" | "right"; x: number; y: number; width: number; depth: number; out: 1 | -1; }
One goal: where the middle of its mouth stands on the goal line, how wide it is, how deep, and which way it opens' back is (out: -1 behind a left goal line).
type FieldOutline
type Outline = { kind: "rect"; radius?: number } | { kind: "ellipse" } | { kind: "oval"; a: number; half: number };
The shape of the playing surface itself: a rectangle (its corners rounded, as a floor's are), an ellipse (a cricket ground), or an oval cut at each end by a straight line, as an Australian football ground is: the ellipse of semi-axes a along the ground and half the width across, cut where it is half either side of the middle.
function fieldPlan
fieldPlan(o: Pick<SurfaceOptions, "sport" | "league" | "field" | "units" | "detail">): FieldPlan
The plan the options ask for. A league picks the rulebook (the sport's own first one by default); field a size within its range and the sport's own parameters; detail: "simple" leaves out the small marks.
type FieldPlan
interface FieldPlan { sport: FieldSport; /** The id of the league (rulebook) it follows. */ league: string; /** The length and the width of the playing surface in feet, as the box the drawing is laid out in (a rugby field's includes the in-goal areas). */ length: number; width: number; outline: Outline; /** The ground round the surface by default, in feet. */ margin: number; /** The width the ordinary line is painte…
What a builder of a sport knows of its surface.
type FieldShape
type Shape = LineShape | ArcShape | RingShape | BoxShape | PolyShape | DotShape | BarShape | PathShape;
Every shape that is a marking.
type FieldSport
type FieldSport = "lacrosse" | "rugby" | "afl" | "gaelic" | "cricket" | "fieldhockey" | "handball";
The field sports: lacrosse (the field and the box), rugby (union and league), Australian football, Gaelic football and hurling, cricket, field hockey and team handball.
type FieldStyle
interface FieldStyle { /** The length of the surface (rugby: try line to try line; Australian football: goal line to goal line; Gaelic games, hockey, handball, lacrosse: end line to end line) and its width, in `units`: within the league's range; a size outside it is an error that says the range. The greatest the rules allow by default. */ length?: number; width?: number; /** Rugby: how deep each in-goal area is, wit…
The size and the variants of a field sport's surface (lacrosse, rugby, Australian football, Gaelic games, cricket, field hockey, handball): a size within the range the league's rulebook allows (length, width, in units, feet by default), and the sport's own parameters. Every part is optional.
function fitLines
fitLines(name: string, maxWidth: number, maxHeight: number, maxSize: number): FittedLines
Set a name in the biggest size that fits a box, on one line or, at a space, on two.
Example
import { fitLines } from "@johnmorrisdotca/kyogijo-stadiums";
console.log(fitLines("GOLDEN STATE WARRIORS", 40, 12, 8).lines);
// [ 'GOLDEN STATE', 'WARRIORS' ]
type FittedLines
interface FittedLines { lines: string[]; size: number; width: number; height: number; }
The lines a name is set in, the font size that fits them, and the width of the widest.
type FlagRenderer
type FlagRenderer = (code: string, request: FlagRequest) => string | null | undefined;
A function from a country code and a request to an SVG string, or null or undefined for a code it has no flag for. It must be synchronous: a drawing is a pure function of its options. @johnmorrisdotca/hata's flag() is asynchronous, so load the flags first (await flag(code, { shape: "round" }) for each code) and pass a lookup.
type FlagRequest
interface FlagRequest { shape: FlagShape; /** The width in pixels the flag is drawn at, nominally (a drawing scales, so this is the size of a typical use): the diameter of a round flag. */ size: number; /** `light` or `dark` for a drawing in that look, else `inherit`. */ theme: "inherit" | "light" | "dark"; }
What a drawing asks a flags renderer for.
type FlagShape
type FlagShape = "round" | "square" | "rect";
How a flag is framed: round for a circle, square as wide as it is tall, rect in its own proportions.
type FlowLayer
interface FlowLayer extends LayerBase { kind: "flow"; data: readonly MoveDatum[]; /** The grid: a number of cells across the surface's longer side (square cells, 12 by default), `[across, down]`, or `{ x, y }` as for a heat map. */ bins?: number | readonly [number, number]; /** Leave out a cell with fewer movements than this. 2 by default. */ minCount?: number; /** The length of an arrow: `mean` (the default: in pro…
The average direction of the movements in each cell of a grid, as an arrow (a quiver plot).
function footballIn
footballIn(sport: "nfl" | "cfl" | "ifaf", year?: number): FootballSpec
A football field's spec in a season: the NFL's or the CFL's as FOOTBALL has it today, with the length, the end zones, the hash marks and the goal posts of that season. The IFAF's has no history and is returned as it is.
Example
import { footballIn } from "@johnmorrisdotca/kyogijo-stadiums/eras";
console.log(footballIn("cfl", 1985).endZone / 3, footballIn("cfl", 1986).endZone / 3, footballIn("nfl", 1960).hash / 3);
// 25 20 20
type FootballLeague
type FootballLeague = LeagueBase<"football", FootballFigures>;
A league with a football field of its own.
type FootballRead
interface FootballRead { kind: "football"; yards: number; downs: number; ballOn?: number; toGo?: number | "goal"; down?: number; possession?: SituationTeam; /** The end zone the offence heads for. */ toward: "left" | "right"; redZone: boolean; drive: DriveRead[]; }
Football, read.
type FootballRules
interface FootballRules { /** Goal line to goal line. */ length: number; /** The depth of each end zone. */ endZone: number; /** The hash marks' distance from each sideline, or `null` before there were hash marks. */ hash: number | null; /** Where the goal posts stand. */ posts: "goal-line" | "end-line"; /** Two poles joined by a crossbar (`h`), or one curved support behind the crossbar (`slingshot`). */ postShape: …
A football field's markings in a season: the NFL's or the CFL's. Lengths are feet.
type FootballSituation
interface FootballSituation { /** The ball, in yards from the offence's own goal line: 35 is its own 35, 88 the opponent's 12. 0 to 100 (0 to 110 on the CFL's field). */ ballOn?: number; /** The yards to a first down, or `"goal"` when the goal line is nearer than the first-down line. */ toGo?: number | "goal"; /** The down, 1 to 4 (1 to 3 on the CFL's field). */ down?: number; /** The team with the ball. */ possessi…
Football's situation (NFL, CFL, IFAF and the leagues of other rulebooks). The CFL has three downs and a field of 110 yards with end zones of 20.
type Formation
interface Formation { id: string; sport: FormationSport; /** The frame the positions are in: `opta` for soccer, `nhl-api`, `nba-stats`, `nfl-tracking`, `retrosheet`. */ frame: string; name: { en: string; ja: string }; /** What the formation is, in a sentence: the side of the ball, the strategy. */ about: { en: string; ja: string }; positions: readonly FormationPosition[]; /** Places beside the surface's play that a …
A formation: where each position stands. Points in the numbers of a registered frame, for a team that attacks the right end of the surface as it is drawn wide (a football formation: the offence going right, with the ball at midfield).
type FormationLayer
interface FormationLayer extends LayerBase { kind: "formation"; /** The id of a formation in `FORMATIONS` (`4-4-2`), or a formation of your own. */ formation: string | Formation; /** The team that colours the marks (`home`, `away`). */ team?: LayerTeam; /** Players for some or all of the positions. */ data?: readonly FormationPlayer[]; /** What is written in a mark: the `position`'s id (the default without players),…
A formation drawn on the surface: a labelled mark for each position, with the players on them when data has some.
type FormationPlayer
interface FormationPlayer extends MarkDatum { /** The id of the position the player stands on. */ position: string; number?: string | number; name?: string; }
A player to stand on a position.
type FormationPosition
interface FormationPosition { /** The position's id: `GK`, `LB`, `QB`. Unique within a formation. */ id: string; x: number; y: number; /** How big the mark of a lineup is here, against the others: 1 by default. A second line's marks are smaller. */ size?: number; }
A named place of a formation, in the numbers of the formation's frame (see Formation).
type FormationSport
type FormationSport = "soccer" | "nhl" | "nba" | "nfl" | "mlb" | "rugby" | "afl" | "cricket" | "volleyball" | "handball" | "waterpolo" | "fieldhockey" | "netball";
The sports that have formations.
function formatTime
formatTime(seconds: number): string
A time in seconds as swimming writes it, to the hundredth: 26.12, 1:46.91, 14:31.02. A time that rounds to the next minute carries into it.
Example
import { formatTime } from "@johnmorrisdotca/kyogijo-stadiums/replay";
console.log(formatTime(26.121), formatTime(106.9), formatTime(59.996));
// 26.12 1:46.90 1:00.00
function frameMatrix
frameMatrix(f: SoccerFrame, spec: Pick<SoccerSpec, "length" | "width">): [number, number, number, number, number, number]
The matrix [a, b, c, d, e, f] of an SVG transform that turns a provider's numbers into metres on a pitch of this size, the left goal line at x 0 and the top touchline at y 0. A group with this transform takes the provider's raw x and y: that is the ky-data group in a drawing made with pitchType.
type GoalInfo
interface GoalInfo { sport: Sport; /** The end the goal is at: `left` or `right`, as the surface is drawn wide. */ end: Side; /** The middle of the goal's mouth on the goal line (the base of a basket's backboard). */ x: number; y: number; /** The width of the mouth, across the surface. */ width: number; /** How far the goal reaches from `x` (a net's depth behind the goal line, a basket's arm and rim out from its bac…
Where a goal stands, for a function of your own that draws it (goalMarkup) and for goalMarkup's built-in styles. Every number is in feet, in the drawing's own wide frame (x along the surface from the left, y across it from the top), whatever units the options use.
type GoalStyle
type GoalStyle = "box" | "line" | "strip" | "none";
How a goal is drawn, seen from above. A soccer goal: the net as a box behind the goal line, a line on it, a solid strip, or not at all. A hockey net: the same four (box is the open frame behind the goal line, strip a filled net). A basketball basket: box is the backboard, its arm and the rim, line the backboard only, strip a solid backboard and a filled rim, none neither. A football field's posts: box is the crossbar with its stem, line the crossbar alone, strip bolder posts, none no posts.
const GRIDIRON_GROUNDS
GRIDIRON_GROUNDS: Readonly<Record<string, "nfl" | "cfl">>
The grounds of the package that are the home of an NFL or a CFL club, where a soccer pitch stands inside a gridiron's stands. From each ground's article.
type Ground
interface Ground extends Omit<GroundData, "pitch"> { /** The pitch, goal line to goal line and touchline to touchline, in metres to the centimetre. */ pitch: { length: number; width: number }; /** The unit the article published the size in; `m` for a ground at the default size. */ pitchUnit: "m" | "yd"; }
A ground, with its pitch in metres: the published size, or the international 105 by 68 m of a ground that has none.
const GROUND_IDS
GROUND_IDS: readonly string[]
The keys of GROUNDS: the men's World Cup final venues in order of the tournaments, the other venues of 2026, the Women's final venues not among them, then club grounds.
function groundById
groundById: (id: string | undefined) => Ground | undefined
The ground with a key, or undefined.
function groundByName
groundByName: (name: string | undefined) => Ground | undefined
The ground a name belongs to (see groundsByName; the best match when several answer to it), or undefined.
function groundByWikidata
groundByWikidata: (wikidata: string | undefined) => Ground | undefined
The ground whose Wikidata item is Q155174, or undefined.
type GroundCompetition
type GroundCompetition = "world-cup" | "womens-world-cup";
The competitions a ground can have staged: the men's World Cup and the Women's.
type GroundData
interface GroundData { /** The key: `maracana`. */ id: string; /** The Wikidata item of the ground (`Q155174`), the key to join a ground to other data. */ wikidata: string; /** The everyday name in English, the one English sports media use (`Reliant Stadium`, `San Siro`); the title of the English article is one of the `aliases`. */ name: string; /** * Names the ground had for some years, in order of time: where two …
A soccer ground as the data gives it: the pitch is the size the article publishes, in the unit it publishes it in.
type GroundName
interface GroundName { name: string; from: number; to: number; }
A name a ground had for some years, first to last.
function groundNameIn
groundNameIn(ground: Ground, year?: number, language?: Language): string
A ground's name in a year: the name it had then, or its everyday name, in English. In Japanese there is one name for every year.
Example
import { GROUNDS, groundNameIn } from "@johnmorrisdotca/kyogijo-stadiums/grounds";
console.log(groundNameIn(GROUNDS["soccer-city"], 2010), "/", groundNameIn(GROUNDS["soccer-city"], 2012));
// Soccer City / FNB Stadium
function groundOfficialName
groundOfficialName(ground: Ground, language?: Language, year?: number): string | undefined
The name a ground officially has in a language, when it is not the everyday name (Parc Olympique Lyonnais for Groupama Stadium), in the year given or today; else undefined.
const GROUNDS
GROUNDS: Readonly<Record<string, Ground>>
Every ground by its key: the venues of the men's World Cup finals and of the 2026 tournament, of the Women's World Cup finals, and well-known club grounds, each with its pitch at its own size where the English article publishes one.
Example
import { GROUNDS, GROUND_IDS } from "@johnmorrisdotca/kyogijo-stadiums/grounds";
const { name, city, pitch, pitchSize } = GROUNDS["old-trafford"];
console.log(name, city, pitch.length, pitch.width, pitchSize, GROUND_IDS.length);
// Old Trafford Manchester 105 68 published 64
function groundsByName
groundsByName: (name: string | undefined) => Ground[]
The grounds that answer to a name, best match first: the everyday names, then the official and cited names, the sponsors' and the names the ground had in some years, then the former names and the nicknames. A name is compared without case, accents, spaces or punctuation, in full-width or half-width, and in Japanese with hiragana or katakana and with or without the long vowel mark.
Example
import { groundByName, groundsByName } from "@johnmorrisdotca/kyogijo-stadiums/grounds";
console.log(groundByName("Giuseppe Meazza Stadium")?.id, groundByName("日産スタジアム")?.id, groundByName("Estadio Jornalista Mario Filho")?.id, groundsByName("stadium australia").length);
// san-siro nissan-stadium-yokohama maracana 1
function groundsHosting
groundsHosting: (competition: GroundCompetition, year: number) => Ground[]
The grounds of this list that staged matches of a World Cup, in the order of GROUND_IDS.
type GroundSource
interface GroundSource { title: string; revision: number; }
Where a ground's facts were read: an article of Wikipedia at a revision.
function groundSourceUrl
groundSourceUrl(source: GroundSource, language?: "en" | "ja"): string
The address of the revision of an article that a ground's facts were read from.
type GroundTournament
interface GroundTournament { competition: GroundCompetition; year: number; /** The final was played here. */ final?: true; }
A tournament a ground staged matches of.
function groupOf
groupOf: (sport: Sport | string) => Group | undefined
The group a sport is painted with, or undefined for a surface with no palette of its own (it takes the look's base).
const HARDWOOD_SMALL
HARDWOOD_SMALL: 480
The width in pixels under which a drawing is a thumbnail, and its boards a blur: the auto detail is plain below it.
type HardwoodOptions
interface HardwoodOptions { /** The seed of the boards' lengths and tones and of the grain: the same seed always gives the same floor. 1 by default. */ seed?: number; /** * How much is drawn. `fine`: the boards' seams and ends, the grain, the baskets' soft shadows, the table and the benches. `plain`: broad boards and one shadow, for a * thumbnail. `auto` (the default) is `plain` when the drawing has `detail: "simple…
The options of a hardwood floor. Every part is optional.
function hasHistory
hasHistory: (league: League | undefined) => boolean
True when a league has markings a source dates, so that year changes its drawing.
const HEAT_RAMP_NAMES
HEAT_RAMP_NAMES: readonly HeatRampName[]
Names of the built-in ramps.
const HEAT_RAMPS
HEAT_RAMPS: Readonly<Record<HeatRampName, HeatRampDef>>
The built-in ramps. On a light page a sequential ramp runs from a pale colour to a dark one, because the more there is the more ink it takes; on a dark page it runs from near the ground to a bright one, because the more there is the more light it gives. A diverging ramp has its neutral middle at the ground's colour and its two ends at full strength.
type HeatBase
interface HeatBase extends LayerBase { data: readonly HeatDatum[]; /** What each cell or zone shows: `count` (the default), `sum`, `mean`, `median`, `max` or `min` of the marks' `value`, `percent` (a share of all the marks, 0 to 100), `rate` (the percent of the marks whose `outcome` is a success; see `success`) or a function `(values, { count, hits, total }) => number | null`. */ statistic?: HeatStatistic; /** The s…
What the heat layers take beyond a layer's places.
type HeatBins
interface HeatBins { /** A number of bins across, or a list of edges in the layer's coordinates. */ x?: number | readonly number[]; y?: number | readonly number[]; }
Bins on a grid: a number of bins, or the edges between them.
type HeatDatum
interface HeatDatum extends MarkDatum { x: number | null; y: number | null; }
A point to count: where it is, and optionally a number it carries (value: a distance, an expected-goals figure, a speed) and an outcome (made, goal) for the rate statistic.
type HeatLabels
interface HeatLabels { /** What to write, a line each: the `value`, the `name` of a zone, the `count` of marks in it, its `share` of all of them (a percent) or the `ratio` of hits to marks (`13/31`). The value by default. */ show?: readonly ("value" | "name" | "count" | "share" | "ratio")[]; /** Decimal places of the value. A whole number for a count, and one place for a percent below 10, by default. */ decimals?: n…
Where to write the number of a cell or zone, and which.
type HeatLegend
interface HeatLegend { /** Where it sits on the surface: `bottom` (the middle of the lower edge) by default, or a corner. A ballpark's default is its lower right, outside the foul lines. */ position?: "bottom" | "top" | "bottom-left" | "bottom-right" | "top-left" | "top-right"; /** The legend's heading. The name of the statistic by default. */ title?: string; /** About how many ticks. 5 by default. */ ticks?: number…
A colour bar with ticks, drawn on the surface.
type HeatmapLayer
interface HeatmapLayer extends HeatBase { kind: "heatmap"; /** The bins. A number is how many across the surface's longer side, with square cells; `[across, down]` for both; or `{ x, y }` each a count or edges. About 24 across by default. */ bins?: number | readonly [number, number] | HeatBins; /** Grid only part of the surface, in the layer's coordinates: the attacking half, say. The whole surface by default. */ ex…
A binned statistic on a grid laid over the surface (hockey_rink's heatmap, mplsoccer's bin_statistic with heatmap).
type HeatRamp
type HeatRamp = HeatRampName | readonly string[] | { light: readonly string[]; dark?: readonly string[] };
A ramp for a layer: the name of a built-in one, a list of colour stops (the same on a light and a dark page), or a light and a dark list. Stops are anything safeColour accepts.
type HeatRampName
type HeatRampName = "ember" | "ocean" | "mono" | "balance" | "tide";
The built-in ramps. The sequential ones go from the least to the most; the diverging ones from the lowest through a neutral middle to the highest.
type HeatStatistic
type HeatStatistic = StatisticName | Reducer;
A statistic: a name, or a function of a bin's values (the median is the median of them; a function gets them all).
type HexbinLayer
interface HexbinLayer extends HeatBase { kind: "hexbin"; /** The distance from a hexagon's centre to its corner, in the layer's units. A twenty-eighth of the surface's length by default. */ size?: number; /** A corner up (`pointy`, the default) or an edge up (`flat`). */ orientation?: HexOrientation; }
A binned statistic on hexagons (hockey_rink's and mplsoccer's hexbin).
type HexOrientation
type HexOrientation = "pointy" | "flat";
How a hexagon sits: a corner up (pointy) or an edge up (flat).
type HillQuirk
interface HillQuirk extends QuirkBase { kind: "hill"; angle: number; feet: number; width_ft: number; slope_deg?: number; }
An incline in the field: against the fence at an angle and a distance, as wide as the article says (width_ft), and as steep as it says.
type HockeyLeague
type HockeyLeague = LeagueBase<"hockey", RinkFigures>;
A league with an ice rink of its own.
type HockeyRead
interface HockeyRead { kind: "hockey"; /** The skaters, when known. */ away?: number; home?: number; /** The team that is attacking (more skaters, or the goalkeeper pulled, or the other team of a delayed penalty), and the end it heads for. */ attacker?: SituationTeam; toward?: "left" | "right"; /** The attacker's skaters and the other team's, in that order, when both are known. */ strength?: [number, number]; /** Mo…
Hockey, read.
type HockeySituation
interface HockeySituation { /** The visitors' skaters on the ice, a whole number from 3 to 6. */ awaySkaters?: number; /** The home team's skaters on the ice. */ homeSkaters?: number; /** The time left on the penalty (or the power play), as `m:ss` or `m:ss.s`, or a whole number of seconds. Written beside the strength. */ clock?: string | number; /** A net with no goalkeeper in it: `"home"` or `"away"` for the team t…
Hockey's situation. The skaters are the players on the ice without the goalkeeper, 3 to 6 (a goalkeeper pulled for an extra attacker is a team with 6). A strength that is 5 against 5 with nothing else to say draws nothing. See docs/situation.md.
const HOME_FIRST
HOME_FIRST: Readonly<Record<Sport, boolean>>
Whether each sport lists the home team first by default. true puts the home team on the left, false on the right. A league can differ from its sport (see HOME_FIRST_LEAGUES); an explicit homeSide always wins over both.
const HOME_FIRST_LEAGUES
HOME_FIRST_LEAGUES: Readonly<Partial<Record<Sport, Readonly<Record<string, boolean>>>>>
The leagues whose convention is not their sport's: the international federation's lacrosse lists the home team first.
function homeSideFor
homeSideFor(sport: Sport, league?: string): Side
The side the home team is on by default for a sport, and a league of it when it has a convention of its own: left (home first) or right (away first).
type HullLayer
interface HullLayer extends PlayersBase { kind: "hull"; /** One hull for each team (`team`, the default) or one for all the players. */ by?: "team" | "all"; }
The convex hull of the players: the smallest convex shape that holds them, for each team.
function inkOn
inkOn(color: string | undefined): string
White or near-black, whichever reads better on the colour. White when the colour cannot be read.
function isFieldSport
isFieldSport: (sport: string) => sport is FieldSport
True for a sport whose surface is a field sport's.
function isPoolSport
isPoolSport: (sport: unknown) => sport is PoolSport
True for a sport whose surface is a pool.
function isPortrait
isPortrait(o: Pick<SurfaceOptions, "orientation" | "aspect"> & { sport?: SurfaceOptions["sport"]; }): boolean
True when a drawing with these options lies in portrait.
function isUnit
isUnit: (unit: unknown) => unit is Unit
True when unit is one of the six.
const KYOGIJO_ATHLETICS_STYLE
KYOGIJO_ATHLETICS_STYLE: string
The rules of an athletics drawing's colours. A drawing that names its track (athletics.track) has its data-track, whose rules come after a look's so that the track wins.
const KYOGIJO_BACKGROUND_STYLE
KYOGIJO_BACKGROUND_STYLE: string
The rules of a ground, written into a drawing that has one (and in KYOGIJO_STYLE, for a page that supplies the stylesheet): the pattern's ink and light.
const KYOGIJO_BUDO_STYLE
KYOGIJO_BUDO_STYLE: string
Every budō sport's rules and every look, for a page that draws with style: "none" and supplies the stylesheet itself.
const KYOGIJO_COURTS_STYLE
KYOGIJO_COURTS_STYLE: string
Every net sport's rules and every look, for a page that draws with style: "none" and supplies the stylesheet itself.
const KYOGIJO_CROWD_STYLE
KYOGIJO_CROWD_STYLE: string
The rules of the stands and the crowd, written into a drawing that has one (and in KYOGIJO_STYLE, for a page that supplies the stylesheet), light and dark.
const KYOGIJO_CURLING_STYLE
KYOGIJO_CURLING_STYLE: string
The rules of a curling sheet and its board: the ice and the lines, the house in its colours (--ky-rg-o, -m, -i and -b for the 12-foot band, the 8-foot, the 4-foot and the button), the hacks, the free guard zone, the pebble, the hammer and the board's grid. Kept apart so that a drawing of another sport does not carry them: a curling drawing writes them in after the base rules, and KYOGIJO_STYLE has them for a page.
const KYOGIJO_FEATURE_STYLE
KYOGIJO_FEATURE_STYLE: string
The rules of every named feature: a colour in --ky-f-<name> on the drawing goes to the part. A drawing that colours a feature carries the rules it needs; a page that draws with style: "none" puts this in once.
const KYOGIJO_FIELDS_STYLE
KYOGIJO_FIELDS_STYLE: string
The rules of every field sport's colours, for a page that draws with style: "none" and supplies the stylesheet itself.
const KYOGIJO_HARDWOOD_STYLE
KYOGIJO_HARDWOOD_STYLE: string
The rules of the hardwood floor's classes, written into a drawing that has one (and in KYOGIJO_STYLE, for a page that supplies the stylesheet).
const KYOGIJO_HEAT_STYLE
KYOGIJO_HEAT_STYLE: string
The rules of the heat layers (the ground under a heat map, its zones' and bands' outlines and the legend), kept apart so that a drawing without one does not carry them: a drawing that has a heat layer writes them in beside the layer, and KYOGIJO_STYLE has them for a page.
const KYOGIJO_LOOK_STYLE
KYOGIJO_LOOK_STYLE: string
The stylesheet of every look, for a page that draws with style: "none".
const KYOGIJO_MARK_STYLE
KYOGIJO_MARK_STYLE: string
The rules of a round team mark: the disc under the picture (the team's colour, or a plain one), the white ring and the hairline outside it, and the initials. The colours are custom properties with fallbacks (--ky-mark-ring, --ky-mark-edge, --ky-mark-plain), so a page can set them. A drawing with a round mark writes these rules in; KYOGIJO_STYLE has them for a page that draws with style: "none".
const KYOGIJO_NOTE_STYLE
KYOGIJO_NOTE_STYLE: string
The rules of the annotations (the arrows of direction, the axes of axes and the labels and leaders of landmarks): words in the ink of the page with an outline in the apron's colour, thin leaders, and the arrows in the home and away colours. A drawing that has an annotation writes them in; KYOGIJO_STYLE has them for a page.
const KYOGIJO_PAGEANT_MOTION
KYOGIJO_PAGEANT_MOTION: string
The entrance (animate: "unfurl" or "fade"), in CSS only, and only for a reader who has not asked for less motion: a carpet rolls out from its own end, a stage and the emblem grow, and fade brings each in. The end state is the drawing's own, so a reader who has asked for less sees it at once, and a renderer that reads no CSS animation (the canvas, the PNG) draws it finished. The second team's picture and then the emblem come a little later.
const KYOGIJO_PAGEANT_STYLE
KYOGIJO_PAGEANT_STYLE: string
The pageant's colours, light and dark.
const KYOGIJO_POOL_STYLE
KYOGIJO_POOL_STYLE: string
The rules of every pool, for a page that draws with style: "none" and supplies the stylesheet itself.
const KYOGIJO_SITUATION_STYLE
KYOGIJO_SITUATION_STYLE: string
The situation's colours and shapes.
const KYOGIJO_SKATING_STYLE
KYOGIJO_SKATING_STYLE: string
The rules of a skating drawing's colours.
const KYOGIJO_STRINGS
KYOGIJO_STRINGS: Record<Language, KyogijoWords>
The words of the package, by language. Each language is a file of its own (strings.en.ts, strings.ja.ts), and an entry holds the languages it was given: every entry but the lean district imports strings.ts, which holds both, as it always did; the lean district (district-lean) holds none until loadStrings(language) has read the language it is about to draw in. Reading a language that is not held throws, naming the call that holds it.
const KYOGIJO_STYLE
KYOGIJO_STYLE: string
Every rule of the package, for a page that draws with style: "none" and supplies the stylesheet itself.
const KYOGIJO_TEAM_STYLE
KYOGIJO_TEAM_STYLE: string
The rules of the team layers (the cells, triangles and hulls, the roses of a sonar, the arrows of a flow field and the marks of a formation), kept apart like the heat layers' so that a drawing without one does not carry them: a drawing that has one writes them in beside the layer, and KYOGIJO_STYLE has them for a page.
const KYOGIJO_TRACK_STYLE
KYOGIJO_TRACK_STYLE: string
The rules of every named track, for a page that draws with style: "none".
const KYOGIJO_WALLS_STYLE
KYOGIJO_WALLS_STYLE: string
The rules of a ballpark's walls and quirks (walls and quirks): the four shades of the wall bands (--ky-wall-1 to -4, from under 10 feet to 30 and over), the hill, the overhang, the ivy, the poles and bullpens, the backstop's bar, the dugouts, the names and the legend. Kept apart so that a drawing without them does not carry them: a drawing that has them writes them in after the base rules, and KYOGIJO_STYLE has them for a page.
type KyogijoWords
interface KyogijoWords { /** The name of each surface. */ surface: Record<Sport, string>; /** What each surface is, for the description: a sentence fragment. */ about: Record<Sport, string>; /** The standard statuses. */ status: Record<"final" | "final-ot" | "final-so" | "final-aet" | "final-pens" | "live" | "half" | "extra-time" | "extra-end" | "penalties" | "postponed" | "tiebreak" | "match-tiebreak" | "retired" |…
The words the drawing says itself, in English and Japanese.
type LanePlan
interface LanePlan { number: number; y: number; top: number; bottom: number; }
A lane: its number, the middle of its marking on the floor, and its two edges, in metres from the top wall.
type Language
type Language = "en" | "ja";
The language of the words the drawing says itself: its title, its description and its status labels.
type Layer
type Layer = PointsLayer | LinesLayer | ArrowsLayer | TextLayer | HeatmapLayer | HexbinLayer | ZonesLayer | ContourLayer | LegendLayer | NetworkLayer | FormationLayer | LineupLayer | VoronoiLayer | DelaunayLayer | HullLayer | FlowLayer | SonarLayer;
A layer of data on a surface.
type LayerBase
interface LayerBase { /** A name for the layer in ids and in the page; letters, digits and hyphens. */ id?: string; /** What the marks are, for the summary: `shots`, `passes`. */ name?: string; /** The accessible title of the layer. Made from the count and `name` when missing, such as "24 shots". */ title?: string; /** The accessible description. Made from the counts by outcome and team when missing. */ description?…
What every layer takes.
type LayerKind
type LayerKind = Layer["kind"];
The kinds of layer.
function layerTable
layerTable(layers: readonly Layer[], options?: TableOptions): string
An HTML table for each layer: the data the drawing shows, as text, for a screen reader or for a page that wants its numbers. The coordinates are the ones given (in the layer's frame and unit), and a caption says which. Hidden layers are in it too. Every cell is escaped.
Example
import { layerTable } from "@johnmorrisdotca/kyogijo-stadiums";
const html = layerTable([{ kind: "points", name: "shots", from: "nhl-api", data: [{ x: 69, y: 22, outcome: "goal", title: "Goal, 2nd period" }] }]);
console.log(html.includes("<th scope=\"col\">Outcome</th>"), html.includes("Goal, 2nd period"));
// true true
type LayerTeam
type LayerTeam = "home" | "away" | (string & {});
Which team a mark belongs to: home or away take the layer's team colours (--ky-layer-home, --ky-layer-away); any other text is a mark of no team.
type League
type League = BasketballLeague | HockeyLeague | FootballLeague | BaseballLeague | CurlingLeague | NetLeague | LacrosseLeague | RugbyLeague | AflLeague | GaelicLeague | CricketLeague | FieldHockeyLeague | HandballLeague | AthleticsLeague | SkatingLeague | BudoLeague;
A league: a variant of a family of surface.
const LEAGUE_SOURCES
LEAGUE_SOURCES: Readonly<Record<string, Readonly<LeagueSource>>>
Every document a league's figures were read from, by id.
function leagueAt
leagueAt(sport: Sport, id: string, year?: number): LeagueAt
A league's figures as they were in a season. Without a year, or for a league with no dated history, they are the rulebook's as it is now.
Example
import { leagueAt } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
console.log(leagueAt("nba", "ncaa-men", 2010).differences.map((change) => change.id));
// [ 'ncaa-men.restricted.start' ]
type LeagueAt
interface LeagueAt<L extends League = League> { league: L; /** The season asked for, or `undefined` for today's. */ year: number | undefined; /** The figures in the unit the league keeps them in. */ figures: L["dimensions"]; /** The markings that differ from today's. */ differences: LeagueChange[]; /** Markings whose history starts later than the season asked for (the first cited state is used). */ gaps: string[]; }
The league's figures in a season: the rulebook's as it is now, with each marking that has a dated history as it stood then.
function leagueById
leagueById(sport: Sport, id: string): League | undefined
A league by its sport and id, or undefined.
type LeagueChange
interface LeagueChange { /** `ncaa-men.threePoint.2019`. */ id: string; league: string; /** The marking's name: a key of the league's dimensions. */ feature: string; /** The first season, or `null` for the state before the first change that is cited. */ from: number | null; value: unknown; what: string; ja: string; sources: string[]; }
One change of a league's markings: a state of one marking from a season on.
function leagueChanges
leagueChanges(sport: Sport, id: string): LeagueChange[]
Every change a source dates in a league's markings, in season order, each with a sentence in English and in Japanese and its sources. A league with no cited history has none (a drawing with a year is then the league's rulebook as it is now).
Example
import { leagueChanges } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
console.log(leagueChanges("nba", "ncaa-men").map((change) => change.id));
function leagueFigures
leagueFigures(league: League): [string, string][]
The key figures of a league in words, each in the unit its rulebook uses: for a table of the leagues (docs/variants.md) and for a test that holds the drawing to the rulebook.
Example
import { LEAGUES, leagueFigures } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
const fiba = LEAGUES.nba.find((league) => league.id === "fiba")!;
console.log(leagueFigures(fiba).slice(0, 2).map(([name, value]) => `${name}: ${value}`).join("; "));
// court: 28 m by 15 m; lane: 4.9 m wide
function leagueIds
leagueIds: (sport: Sport) => string[]
The ids of a sport's leagues.
const LEAGUES
LEAGUES: Readonly<Record<Sport, readonly League[]>>
The leagues each sport can draw, in the order a menu lists them, the sport's own first (the three football sports share their list, the football leagues). Soccer and the pools have none.
function leagueSeason
leagueSeason(family: Family, year: number): string
The name of a season as the family writes it: 1979–80 for basketball and hockey, which play across the new year, else 1979.
function leagueSize
leagueSize(sport: Sport, id: string, unit?: Unit): { length: number; width: number; unit: Unit; }
The length and the width of a league's surface in a unit (the league's own when none is given): a football field with its end zones, end line to end line. A diamond has no fixed size, its fence is its size.
Example
import { leagueSize } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
console.log(leagueSize("nba", "nba"));
// { length: 94, width: 50, unit: 'ft' }
type LeagueSource
interface LeagueSource { id: string; /** The document: "NCAA Men's and Women's Basketball Rules and Interpretations". */ title: string; /** Who publishes it. */ by: string; /** The edition: a season or a year. */ edition: string; /** The address it was read at, on the date in `read`. */ url: string; /** The date it was read (yyyy-mm-dd). */ read: string; /** What was taken from it. */ note?: string; }
A rulebook (or a page that publishes its figures).
type LeagueSpan
interface LeagueSpan<T> { /** The first season it was in force, or `null` for the state before the first change that is cited. */ from: number | null; value: T; /** What it was, in a sentence. */ what: string; /** The same in Japanese. */ ja: string; /** Keys of `LEAGUE_SOURCES`; at least one. */ sources: string[]; }
The state of one marking from a season on, in a league's own history: the season it began, what it was, and its sources.
type LedBoardOptions
interface LedBoardOptions { /** The ribbon boards along the fascia between the levels (the front of the single level of a hall that has one). On by default. */ ribbon?: boolean; /** The scoreboard hung over the middle of the playing surface, four sided, with a ring of display under it. On by default, and left out of a ballpark (whose scoreboard stands behind the outfield). */ scoreboard?: boolean; /** One to three c…
The LED boards of a venue (crowd.boards, or venue.boards of the 3D view): the ribbon boards along the fascia between the seating levels, and a scoreboard hung over the playing surface. The content is generic: bands of colour, abstract patterns and a plain score, never a logo, a sponsor or text from a real board. true is both, in the package's own colours. Off by default.
type LedBoardPattern
type LedBoardPattern = "bands" | "blocks" | "chevrons" | "waves";
The patterns a ribbon board shows: bands (two bands of colour, in panels), blocks (a block of colour to a panel), chevrons (arrows running along it) or waves.
type LegendLayer
interface LegendLayer extends Omit<LayerBase, "from" | "attacking" | "surfaceSize" | "anchors" | "limits"> { kind: "legend"; for?: string; ramp?: HeatRamp; domain?: readonly [number, number]; center?: number; steps?: number; position?: HeatLegend["position"]; ticks?: number; /** The opacity of the legend, 0 to 1. */ opacity?: number; /** Size and place the legend against this part of the surface, as `HeatLegend.regi…
A colour bar on its own: for another layer (for, the id of an earlier or later heat layer) or with a ramp and a domain of its own.
const LIGHT_COLORS
LIGHT_COLORS: { readonly white: "#fff6e6"; readonly amber: "#ffb830"; readonly purple: "#9b4dff"; readonly magenta: "#ff2bd6"; readonly blue: "#2b7bff"; readonly cyan: "#27d6ff"; }
The named colours of light: wash, aisles and colors take these by name (ours, a little saturated, for a light seen on dark).
const LIGHT_PRESETS
LIGHT_PRESETS: Readonly<Record<LightingPreset, LightPreset>>
The named lightings. night: the calm dim house with small lights along the aisles. game: white light, the house half lit, a pool of light round the surface. lightsDown: the house nearly black, a white beam down each aisle. intro: the house dark, the home team's colour washed over the surface and the visitors' (the second colour) in the beams. concert: warm amber beams and a purple surface. (The celebration of the plan, colours chasing round the bowl, is a later one.)
const LIGHTING_PRESETS
LIGHTING_PRESETS: readonly LightingPreset[]
type LightingOptions
type LightingOptions = LightingPreset | boolean | { preset?: LightingPreset; colors?: readonly string[]; aisles?: string; wash?: string };
type LightingPreset
type LightingPreset = "night" | "game" | "lightsDown" | "intro" | "concert";
The lighting of a venue (crowd.lighting in the plan, venue.lighting in the 3D view): a named preset (LIGHT_PRESETS), true (the night), or { preset, colors, aisles, wash }. "night" dims the house, lights the playing surface and shows small lights along the aisles and stairs, the ribbon boards and the scoreboard glowing, the exits and the concourse rim softly lit. "game" is white light with the house half lit. "lightsDown" is a show's house: nearly black, each stair aisle lit from above as a beam with a soft falloff on the steps either side, the rails and the front of every step edged with light. "intro" is the same house with the home team's colour washed over the surface and the visitors' in the beams (the teams' colours where the options have them, else blue and amber); "concert" has warm amber beams and a purple surface. colors are one or two colours that stand for the home and the visitors (before the options' teams); wash colours the playing surface with a light (a CSS colour, or white, amber, purple, magenta, blue, cyan; the markings stay visible) and aisles the beams, and both win over the preset's. false is no lighting. Off by default.
type LineDash
type LineDash = "solid" | "dashed" | "dotted" | "dash-dot" | readonly number[];
How lines are dashed: solid, dashed, dotted, dash-dot, or dash and gap lengths of your own, in units.
type LineDatum
interface LineDatum extends MarkDatum { x?: number | null; y?: number | null; x2?: number | null; y2?: number | null; /** A path through several points, `[x, y]` each, in place of `x`, `y`, `x2` and `y2`. */ points?: readonly (readonly [number, number])[]; /** How far the line bows, as a fraction of its length. Positive bows to the right of the way it goes as the surface is drawn wide. */ curve?: number; /** Make th…
A line or an arrow: from (x, y) to (x2, y2), or through points.
type LinesLayer
interface LinesLayer extends LayerBase { kind: "lines"; data: readonly LineDatum[]; style?: LineStyle; }
type LineStyle
interface LineStyle { /** The width of the stroke in the layer's units, or a scale from `value`. */ width?: number | Scale; scale?: number; color?: Paint; opacity?: number; /** `auto` (the default) dashes the lines of a hollow outcome. */ dash?: "auto" | "solid" | "dashed" | "dotted"; /** How far lines bow, as a fraction of their length. */ curve?: number; /** Draw lines as waves, for a carry: `true` for the usual w…
How lines and arrows look.
type LineupLayer
interface LineupLayer extends LayerBase { kind: "lineup"; /** `home` (the default) or `away`: the team's colour, and the end it attacks (the right for `home`, the left for `away`) unless `attacking` says. A football lineup's `side` is only the colour: the offence goes right unless `attacking` says, and a defence faces it. Baseball's fielders do not turn. */ side?: "home" | "away"; /** The id of a formation in `FORMA…
A team's lineup drawn on the surface: its players placed by position code in a named formation, as discs or jerseys, each with its number in the mark and its name under it. Two teams are two layers, one for each side. A lineup is not cut to the surface's outline (a fielder at the foul line keeps his whole jersey) unless clip is "surface".
type LineupPlayer
interface LineupPlayer extends MarkDatum { /** The position's code: `GK`, `SS`, `C`, `QB`, `9`, `P4` (a volleyball court's zone). The formation's own ids, and the usual short ones (`CB` for a centre-back of either side, `D` for a defenceman, `OF` for an outfielder), as `LINEUP_CODES` lists. */ pos: string | number; name?: string; number?: string | number; /** A flag or crest for a small badge on the mark: an SVG as …
A player of a lineup, placed by a position's code: nothing else about where he stands is needed.
type LineWidth
type LineWidth = number | { scale: number } | { width: number };
The width of the lines: a multiple of the width they are drawn at (2, or { scale: 2 }), or an absolute width in units ({ width: 0.5 }).
type Look
interface Look { /** What it is for, in a sentence. */ about: string; light: Mode; dark: Mode; }
A named look.
const LOOK_NAMES
LOOK_NAMES: readonly LookName[]
The names of the looks, in the order a menu lists them.
const LOOK_PAIRS
LOOK_PAIRS: Readonly<Record<Group | "all", readonly (readonly [PaletteKey, PaletteKey, number])[]>>
The pairs of a palette that must read: what is painted on what, as [ink, ground, least contrast] (WCAG 2.2's 3:1 for a line, 4.5:1 for text). The words of the drawing are on the apron; a line is on the surface and, where its sport paints them under it, on the second tone of the mowing or planks, the key, the dirt, the infield and the foul ground.
type LookGroup
type Group = "football" | "nhl" | "nba" | "mlb" | "soccer" | "curling" | "net" | "pool" | "athletics";
The surfaces that are painted alike: football's three fields are one.
type LookName
type LookName = "grass" | "night" | "chalkboard" | "blueprint" | "print" | "broadcast" | "high-contrast" | "line-drawing";
The looks a drawing can have, alongside court (a basketball court's own). See LOOKS.
function lookPalette
lookPalette(look: LookName, mode: "light" | "dark", sport: Sport | string): Palette
A look's palette for a sport in one mode: the look's base with what the sport's group changes.
type LookPalette
type Palette = Partial<Record<PaletteKey, string>>;
Colours by part.
type LookPaletteKey
type PaletteKey = | "ink" | "line" | "apron" | "surface" | "alt" | "zone" | "boards" | "red" | "blue" | "dirt" | "foul" | "infield" | "crease" | "key" | "court" | "post" | "pylon" | "rgo" | "rgm" | "rgi" | "rgb" | "hog" | "hack" | "fgz" | "pebble" | "free" | "net" | "area" | "ropeg" | "ropeb" | "ropey" | "roper" | "ropew" | "pad" | "block" | "track" | "sand" | "mat" | "water" | "concrete" | "trackpad" | "markY" | "m…
The parts of a palette, each a custom property of the stylesheet.
const LOOKS
LOOKS: Readonly<Record<LookName, Look>>
The named looks. Each is a light and a dark palette for every sport, as custom properties on .kyogijo[data-palette="<name>"]; pass one as look.
Example
import { LOOKS, drawKyogijo } from "@johnmorrisdotca/kyogijo-stadiums";
const svg = drawKyogijo({ sport: "nhl", look: "chalkboard" });
console.log(Object.keys(LOOKS).length, svg.includes('data-palette="chalkboard"'));
// 8 true
function lookStyle
lookStyle(name: LookName): string
The stylesheet of one look, light and dark, at no weight. A drawing with a look carries its look's.
function luminance
luminance(rgb: [number, number, number]): number
The relative luminance of a colour, 0 (black) to 1 (white).
type MarkDatum
interface MarkDatum { /** Your id for the mark: written on it as `data-mark-id`, so that a listener can link it to a row of your table. The mark's index is written when there is none. */ id?: string | number; /** The tooltip, and what a screen reader reads for the mark. */ title?: string; /** `home`, `away` or another team. */ team?: LayerTeam; /** What happened, as a word of your own (`goal`, `miss`, `complete`). T…
What every mark can carry.
type MarkShape
type MarkShape = "circle" | "square" | "triangle" | "diamond" | "cross" | "x" | "star";
The shapes a point can be drawn as. A team's logo is logo.
type MlbRules
interface MlbRules { /** The side of first, second and third base, in feet (home plate is not a base of this size). */ baseSize: number; /** * Where the pitcher throws from: a chalked box whose front edge is `distance` from the back point of home plate, with its * `width` and `depth`, or (from 1893) the rubber, whose front edge is `distance` from it. */ pitcher: { kind: "box" | "plate"; distance: number; width: numb…
The baseball field's markings in a season. Lengths are feet, the mound's height inches.
type MoveDatum
interface MoveDatum extends MarkDatum { x: number | null; y: number | null; x2?: number | null; y2?: number | null; dx?: number | null; dy?: number | null; /** The mover, for a sonar of each player. */ id?: string | number; name?: string; number?: string | number; }
A movement: from (x, y) to (x2, y2), or the vector (dx, dy) from (x, y).
type Named
interface Named { en: string; ja: string; }
The words of a league in both languages.
type NbaRules
interface NbaRules { /** The width of the free-throw lane. */ keyWidth: number; /** The three-point arc's radius from the basket (the corners stay at 22 feet), or none. */ threePoint: { radius: number } | null; /** The restricted area (the no-charge arc) under each basket. */ restrictedArea: boolean; }
The NBA court's markings in a season. Lengths are feet.
type NetStyle
interface NetStyle { /** A named look: for tennis `hard-blue` (the default), `hard-green`, `clay` or `grass`; volleyball `wood` (the default for indoors) or `blue`, and `sand` for the beach; badminton `green` (the default), `blue` or `wood`; pickleball `blue-green` (the default), `green` or `red`; table tennis `blue` (the default) or `green`; padel `blue` (the default), `green` or `terracotta`; squash `wood` (the de…
The look and the variants of a net sport's court (tennis, volleyball, badminton, pickleball, table tennis, padel, squash, racquetball, sepak takraw, teqball, roundnet and netball). Every part is optional. The lines and the sizes are the rulebook's whatever the look; a look is the colour of the ground and of the surface.
type NetworkLayer
interface NetworkLayer extends LayerBase { kind: "network"; data: readonly PassDatum[]; /** Places of your own for some players, over the averages. */ nodes?: readonly NetworkNode[]; /** Leave out links of fewer passes than this. 1 by default. */ minPasses?: number; /** Draw a link for each direction, bowed apart and with a head, and not one for the pair. */ directed?: boolean; /** The width of a node (a share of th…
A pass network: a node for each player at the average place of the passes he made and received, sized by touches, and a link for each pair sized by passes.
type NetworkNode
interface NetworkNode { id: string | number; x: number; y: number; team?: LayerTeam; name?: string; number?: string | number; }
A player of a pass network whose place is given and not worked out from the passes.
type NhlRules
interface NhlRules { /** The centre red line across the middle of the ice. */ centreLine: boolean; /** The goal line's distance from the end boards. */ goalLine: number; /** The blue line's distance from the end boards. */ blueLine: number; /** The goaltender's trapezoid behind the net, or none. */ trapezoid: { atGoalLine: number; atBoards: number } | null; /** The gap between the two hash marks beside an end-zone f…
The NHL rink's markings in a season. Lengths are feet.
function officialName
officialName(place: PlaceNames, language: Language, shown?: string, year?: number): string | undefined
The name a place officially has, in a language, when it is not the everyday name: the official alias in that language that stands in year (without a year, the one that stands today). In English, where there is none in English, a name in the place's own language that is written in Latin letters stands for it (Estadio Banorte). undefined when there is none or when it is the name shown.
Example
import { PARKS, officialName } from "@johnmorrisdotca/kyogijo-stadiums/parks";
const koshien = PARKS["hanshin-koshien-stadium"];
console.log(officialName(koshien, "en"), "/", officialName(koshien, "ja"));
// Hanshin Koshien Stadium / 阪神甲子園球場
type Orientation
type Orientation = "landscape" | "portrait" | "auto";
How the surface lies. landscape is wide, with the teams left and right; portrait is tall, turned a quarter, with the teams top and bottom and every word still upright. auto follows aspect (the container's width over its height), and the helpers for the browser measure the container and draw again when it changes.
const OUTCOMES
OUTCOMES: Readonly<Record<string, OutcomeStyle>>
How the standard outcomes look. A word that is not here draws as a filled mark; style.outcomes of a layer adds words and changes these. A hollow point is drawn open and a hollow line is dashed, so that an outcome is never told by colour alone.
type OutcomeStyle
interface OutcomeStyle { /** Draw a point hollow and a line dashed. */ hollow?: boolean; /** A shape for this outcome, over the layer's. */ shape?: MarkShape; /** A multiple of the mark's size: 1.4 makes a goal stand out. */ scale?: number; }
How an outcome looks: a hollow mark (or a dashed line) is a miss, a failed pass or a shot that did not score.
function outlinePath
outlinePath(o: Outline, reverse?: boolean): string
An outline as a path, drawn clockwise, or counter-clockwise when reverse (a hole in a band that is filled with the non-zero rule).
function outlinePoints
outlinePoints(o: Outline): Pt[]
An outline as points, for a view that raises the stands: arcs are cut into steps of about 7.5 degrees.
type OverhangQuirk
interface OverhangQuirk extends QuirkBase { kind: "overhang"; from: number; to: number; depth_ft: number; }
A stand that hangs over the fence into the field by depth_ft, along a stretch of it.
type PaceOptions
interface PaceOptions { /** Write the pace in seconds per 100 m on each bar. On by default. */ labels?: boolean; }
The split pace bars drawn in the lanes: each split of a race as a bar whose length is the share of the lane that split is, and whose colour is its pace against the field's.
type PageantOptions
interface PageantOptions { /** `carpet` (the default) or `stage`. */ style?: PageantStyle; /** A carpet's border band: `dark` (the default), `team` (each team's colour), or a colour. */ border?: "dark" | "team" | (string & {}); /** A carpet's border band as a share of its shorter side, 0.02 to 0.15. 0.06 by default. */ borderWidth?: number; /** A carpet's fabric: a gentle, fixed wave of light and shade over it. On b…
The pageant: each team's flag or logo laid out large over its own half of the surface, as a stadium lays giant flags and crests on the pitch for a final's ceremony, and an emblem or a trophy in the centre circle. Give pageant: "carpet", "stage" or true (a carpet), or these options. Off by default, and a drawing without it is the same text as before. It needs a score (home and away) and the full or compact size.
type PageantStyle
type PageantStyle = "carpet" | "stage";
How a pageant lays out each team's picture: carpet is its flag or logo laid flat over its half, as a rectangle with a border; stage is its crest on a large round disc with a ring.
type Paint
type Paint = | string | { by: "team"; home?: string; away?: string; other?: string } | { by: "value"; stops: readonly string[]; domain?: readonly [number, number]; missing?: string } | { by: "outcome"; colors: Readonly<Record<string, string>>; other?: string };
A colour, or a rule for choosing one. A text is any colour safeColour accepts. by: "team" uses the home and away colours of the layer, by: "value" runs through stops as a datum's value goes from the least to the greatest of the domain, and by: "outcome" looks the datum's outcome up in colors. A colour a datum carries itself (color) always wins.
type Park
interface Park extends Omit<ParkData, "points" | "unit" | "periods" | "walls"> { /** [angle from dead centre, distance in feet]. */ points: FencePoint[]; periods?: ParkPeriod[]; /** How high the fence stands along stretches of it, in feet. */ walls?: ParkWall[]; }
A ballpark, with its fence in feet.
const PARK_IDS
PARK_IDS: readonly string[]
The keys of PARKS: the current MLB parks, then the past ones by their first season, then the NPB's, each in the order of the sources.
function parkById
parkById: (id: string | undefined) => Park | undefined
The park with a key, or undefined.
function parkByName
parkByName: (name: string | undefined) => Park | undefined
The park a name belongs to (see parksByName; the best match when several answer to it), or undefined.
function parkByWikidata
parkByWikidata: (wikidata: string | undefined) => Park | undefined
The park whose Wikidata item is Q49136, or undefined.
type ParkData
interface ParkData { /** The key: `fenway-park`. */ id: string; /** The Wikidata item of the ground (`Q49136`), the key to join a park to other data. */ wikidata: string; /** The everyday name in English, the one English sports media use (`Koshien Stadium`, `Oracle Park`); the title of the Wikipedia article is one of the `aliases`. */ name: string; /** The everyday name in Japanese (`甲子園球場`, `マツダスタジアム`), as Japanese…
A ballpark's fence as the figures give it.
type ParkDugouts
interface ParkDugouts { home?: DugoutSide; visitors?: DugoutSide; }
Which dugout is on which line, where the article says.
function parkNameIn
parkNameIn: (park: Park, language?: Language) => string
A park's name in a language: the everyday name in English, or in Japanese.
function parkOfficialName
parkOfficialName: (park: Park, language?: Language, year?: number) => string | undefined
The name a park officially has in a language, when it is not the everyday name (Hanshin Koshien Stadium for Koshien Stadium), in the year given or today; else undefined.
type ParkPeriod
interface ParkPeriod { from: number; to: number; points: FencePoint[]; }
A fence of some seasons, in feet.
type ParkPeriodData
interface ParkPeriodData { from: number; to: number; /** [angle from dead centre, distance in the park's unit], from the left field line to the right. */ points: [number, number][]; }
A fence that stood for some seasons of a past park: the figures an article dates, from the first season to the last.
function parkPointsIn
parkPointsIn(park: Park, year: number | undefined): FencePoint[]
A park's fence in a season: the period that names the season, else the park's last fence.
type ParkQuirk
type ParkQuirk = HillQuirk | OverhangQuirk | PointQuirk | CoverQuirk;
A quirk of a ballpark that its article describes with figures.
function parkQuirksIn
parkQuirksIn(park: Park, year?: number): ParkQuirk[]
The quirks a park has in a season: those the article dates for that season, else those of today.
const PARKS
PARKS: Readonly<Record<string, Park>>
Every park by its key: the thirty current MLB ballparks, forty-three past ones, the twelve NPB home parks, and eight secondary or past NPB grounds.
function parksByName
parksByName: (name: string | undefined) => Park[]
The parks that answer to a name, best match first: the everyday names, then the official and cited names and the sponsors', then the former names and the nicknames. A name is compared without case, accents, spaces or punctuation, in full-width or half-width, and in Japanese with hiragana or katakana and with or without the long vowel mark.
Example
import { parksByName } from "@johnmorrisdotca/kyogijo-stadiums/parks";
console.log(parksByName("Camden Yards")[0]?.id, parksByName("甲子園")[0]?.id, parksByName("ハマスタ")[0]?.id);
// oriole-park-at-camden-yards hanshin-koshien-stadium yokohama-stadium
type ParkSource
interface ParkSource { title: string; revision: number; }
Where a park's figures were read: an article of Wikipedia at a revision.
function parkSourceUrl
parkSourceUrl(source: ParkSource, language?: "en" | "ja"): string
The address of the revision of an article that a park's figures were read from.
function parkUnit
parkUnit: (id: string | undefined) => Unit | undefined
The unit a park's figures were published in: metres for the parks of Japan (converted to feet once, in PARKS), feet for the rest. undefined for a key that is not a park.
type ParkWall
interface ParkWall extends Omit<ParkWallData, "height"> { height_ft: number; }
A stretch of the fence and how high it stands, in feet.
type ParkWallData
interface ParkWallData { /** The stretch's angles from dead centre: the left field line is -45 and the right field line 45 (our reading of the article's words, see docs/references.md). */ from: number; to: number; /** The height of the wall in the park's unit. */ height: number; /** A name the wall has in the article (`Green Monster`); a wall without one is named by its place in the field. */ label?: string; /** Whe…
A stretch of the fence and how high it stands, as the figures give it (the height in the park's unit).
function parkWallsIn
parkWallsIn(park: Park, year?: number): ParkWall[]
The stretches of fence a park has in a season, with their heights in feet: the heights the article dates for that season, else those of today.
function parseTime
parseTime(value: unknown): number | undefined
A time in seconds from a number or from text: 26.12, "26.12", "1:46.91". undefined when it is neither.
type PassDatum
interface PassDatum extends MarkDatum { /** The id of the passer and of the receiver (a number or a name; the same id is the same player). */ from: string | number; to: string | number; /** Where the pass was made from, and where it was received. */ x?: number | null; y?: number | null; x2?: number | null; y2?: number | null; /** The names for the labels and the table, by id. The last one given for an id is used. */…
A pass: who passed to whom, from where to where. The places are the passer's and, if given, the receiver's.
type PlaceAlias
interface PlaceAlias { name: string; /** The language of the name: `en`, `ja`, `es`, `de`... */ lang: string; kind: PlaceNameKind; /** The first and the last year the name was in use, where a source dates it. */ from?: number; to?: number; /** Where the name was read: an article and its revision, or a Wikidata item and property (`Wikidata Q49136 P1448`). */ source?: string; /** For a `wikipedia` alias, the revision …
Another name of a place: a title, an earlier or a sponsor's name, a nickname.
function placeBoard
placeBoard(board: ResolvedBoard, view: BoardBox): BoardBox
The place a board takes in a box. A named position keeps to its edge and takes the share asked for, unless that would reach into the middle (BOARD_CLEAR of the box's width and height, centred): then the board is made smaller, down to nothing in a box too small to hold one, and never moved. cover lifts that, and a point of your own is never held to it. The board keeps its own shape, and stays inside the box.
type PlaceNameKind
type PlaceNameKind = "official" | "wikipedia" | "sponsor" | "former" | "nickname";
What an alias is. official is the name the owner or operator gives it (when it is not the everyday one), wikipedia the title of an article that is cited, sponsor a naming-rights name, former an earlier name and nickname a short form or a name people use.
function plainName
plainName(text: string): string
A name made fit to compare: width, case, accents, kana (hiragana is katakana), the old and new forms of the same sound (ヂ, ヅ, ヴ), the long vowel mark and every space, dot and mark of punctuation put aside, so that Estádio Maracanã and estadio maracana are one name, as are ヤンキー・スタジアム and ヤンキースタジアム.
function planVenue
planVenue(venue: RealVenue, rink?: Box): VenuePlan
The plan of a venue's bowl: the building's outline turned so that the rink lies along x, a first row round the rink as an NHL arena has it, the largest bowl-shaped outline that fits the building round the middle of its main hall, and between the two the tiers, the outer edge of each placed so that its band holds the share of the venue's seats the sources give it (at SEAT_AREAS square feet a seat), with a walk between the tiers. The bowl is as long and wide as the building lets it be and as round at the corners as a bowl is; the rest is the building's.
Example
import { planVenue, venueById } from "@johnmorrisdotca/kyogijo-stadiums/venues";
const plan = planVenue(venueById("honda-center")!);
console.log(plan.orientation.basis, plan.seats.map((t) => t.tier).join(" "), plan.total);
// building lower upper 17174
type PlayerDatum
interface PlayerDatum extends MarkDatum { x: number | null; y: number | null; /** The player's id, name and shirt number, for a label and for the table. */ id?: string | number; name?: string; number?: string | number; }
A player at a place. team (home, away or another) is what colours the player's cell, triangles and hull.
type PointDatum
interface PointDatum extends MarkDatum { x: number | null; y: number | null; /** A shape for this mark alone, or `logo` for the logo of its team (or its own `logo`). */ shape?: MarkShape | "logo"; /** The width of the mark, in the layer's units. */ size?: number; /** The address of a logo, for the shape `logo`. */ logo?: string; }
A point to mark.
type PointQuirk
interface PointQuirk extends QuirkBase { kind: "pole" | "flagpole" | "bullpen"; angle: number; feet: number; /** The height of a pole, where the article gives it. */ height_ft?: number; /** Whose bullpen it is, where the article says. */ side?: "home" | "visitors"; }
A foul pole, a flagpole or a bullpen at an angle and a distance from home plate.
type PointsLayer
interface PointsLayer extends LayerBase { kind: "points"; data: readonly PointDatum[]; style?: PointStyle; }
type PointStyle
interface PointStyle { shape?: MarkShape | "logo"; /** The width of a mark in the layer's units, or a scale from `value`. A default that follows the size of the surface. */ size?: number | Scale; /** A multiple of the default size. */ scale?: number; /** The colour of the fill. The home and away colours for marks that carry a team, the layer colour for the rest. */ fill?: Paint; /** The colour of the edge. A pale or…
How points look.
type PoloPlan
interface PoloPlan extends Common { sport: "waterpolo"; length: number; width: number; /** The side of the official table, as the field lies wide. */ table: "top" | "bottom"; }
A water polo field to draw.
const POOL_SPORTS
POOL_SPORTS: readonly PoolSport[]
The sports of the pool, in the order a menu lists them.
type PoolKind
type PoolKind = "competition" | "warm-up";
The swimming pool of a competition, or a warm-up pool: the same lanes and ropes, without the starting blocks, the flags and the false start rope.
type PoolLook
type PoolLook = "flat" | "water" | "tiled";
How the water is painted: flat (the default) is one clean colour; water lays a faint, seeded pattern of light on it, deeper blue at the middle of a long pool; tiled shows the tiles of the floor through the water as well.
function poolPlan
poolPlan(o: Pick<SurfaceOptions, "sport" | "pool">): PoolPlan
The pool the options ask for, of the sport's kind.
type PoolPlan
type PoolPlan = SwimPlan | PoloPlan | DivePlan | ArtisticPlan;
type PoolRace
interface PoolRace { /** The name of the event: "Women's 200 m butterfly, final". */ event?: string; /** The distance in metres. Worked out from the splits (the number of splits times the distance between them) when it is missing, else the length of the course. */ distance?: number; /** The metres between two splits: 50 in a long course pool and 25 in a short course one, unless this says another. */ splitEvery?: num…
A race: the event, its distance, and the swimmers in their lanes.
type PoolSection
interface PoolSection { /** The water's depth in metres. The rules' least for the pool: 2.5 for a 50 m pool, 2.0 for a 25 m one. */ depth?: number; /** How much taller than long the section is drawn. 2.5 by default; the section is not to scale otherwise. */ exaggerate?: number; }
A side section of a swimming pool: its depth profile, the blocks, the flags and the false start rope.
type PoolSport
type PoolSport = "swimming" | "waterpolo" | "diving" | "artisticswimming";
The sports of the pool: the swimming pool, the water polo field, the diving well and the artistic swimming area.
type PoolStyle
interface PoolStyle { /** Swimming: `long` (50 m, the default) or `short` (25 m). */ course?: "long" | "short"; /** Swimming: the lanes, 1 to 10. 8 by default. Ten lanes are numbered 0 to 9. */ lanes?: number; /** Swimming: a temporary pool (26 m wide, ten lanes of 2.5 m) in place of a permanent one (25 m, lanes 0 and 9 of 2.4 m). Only for a ten-lane pool. */ temporary?: boolean; /** Swimming: `competition` (the def…
The look, the size and the data of a pool. Every part is optional. The sport (swimming, waterpolo, diving, artisticswimming) says which pool it is; the parts that belong to one pool are said so in their descriptions.
type QuirkKind
type QuirkKind = "hill" | "overhang" | "pole" | "flagpole" | "bullpen" | "ivy" | "basket";
What a quirk of a ballpark is.
type QuirkName
type QuirkName = "hill" | "overhang" | "pole" | "flagpole" | "bullpen" | "ivy" | "basket" | "backstop" | "dugouts";
The things in a ballpark that quirks draws besides the walls.
type QuirkOptions
interface QuirkOptions { /** Only these; all of the park's by default. */ only?: readonly QuirkName[]; /** Write each quirk's name beside it. */ labels?: boolean; }
Which quirks of a ballpark are drawn (quirks), and whether they carry their names.
type RaceShow
interface RaceShow { names?: boolean; flags?: boolean; results?: boolean; reaction?: boolean; splits?: boolean; medals?: boolean; seeds?: boolean; }
What the labels of a race show. Everything that has data is shown unless it says false.
function rampColour
rampColour(stops: readonly string[], t: number): string | undefined
A colour a fraction t (0 to 1) of the way through stops, as a hex colour, or the nearest stop when one cannot be read without a browser (var(--x), a name that is not a common one). Stops that are not colours are ignored; with none left, undefined.
type RangeBox
interface RangeBox { x0: number; x1: number; y0: number; y1: number; /** A frame of `FRAMES` (or one of your own) the numbers are in. The surface's own when missing. */ frame?: string | Frame; /** The end the box's points are attacking, for a frame whose numbers belong to the team's attack (see `toSurface`). */ attacking?: Side; }
A box of your own to crop to: the corners x0, y0 and x1, y1, in the drawing's frame (feet, or units: x along the surface from the left, y across it from the top; a ballpark's x is across the field and its y minus the distance out from home plate), or, with frame, in that frame's own numbers and unit.
type RangeInfo
interface RangeInfo { id: RangeName; end?: Side; /** The leagues the range is for, when only some of the sport's have it (rugby union's 22 and rugby league's 20-metre area; the fielding circle of the ICC's grounds). Every league when missing. */ leagues?: readonly string[]; }
One range of a sport: its name, and the end it is at by default when it is at an end (left or right, as the surface is drawn wide). A range with no end is in the middle or is the whole of something.
type RangeName
type RangeName = | "red-zone" | "between-the-20s" | "end-zone" | "field-of-play" | "own-half" | "opponent-half" | "offensive-zone" | "defensive-zone" | "neutral-zone" | "half" | "half-court" | "paint" | "final-third" | "defensive-third" | "middle-third" | "penalty-area" | "infield" | "outfield" | "sheet" | "house" | "folded" | "in-goal" | "twenty-two" | "twenty" | "crease" | "forward-fifty" | "centre-square" | "larg…
The parts of a surface a drawing can be cropped to (range). Football: red-zone, between-the-20s, end-zone, field-of-play, own-half, opponent-half. Hockey: offensive-zone, defensive-zone, neutral-zone, half. Basketball: half-court, paint. Soccer: half, final-third, defensive-third, middle-third, penalty-area. Baseball: infield, outfield. The net sports: half-court. Curling: sheet, half, house, folded. Rugby: half, twenty-two (union) or twenty (league), in-goal. Lacrosse: half, crease. Australian football: half, forward-fifty, centre-square. Gaelic games: half, large-rectangle. Cricket: pitch, circle. Field hockey: half, circle, twenty-three. Handball: half, goal-area. Swimming: half, pool-end. Water polo: half, goal-area. Diving: springboards, platforms. Artistic swimming: half, centre-stage. Judo and karate: contest-area, start. Sumo: ring. Kyudo: shajo, yamichi, azuchi. Dojo: kamiza, half. Athletics: bend, home-straight, back-straight, finish, start, infield, a field event (high-jump, pole-vault, long-jump, triple-jump, shot-put, discus-throw, hammer-throw, javelin-throw) and water-jump. RANGES lists them for each sport.
type RangeNamed
interface RangeNamed { name: RangeName; /** The end of the surface the range is at, as the surface is drawn wide: `left` or `right` (a curling sheet's also `top` and `bottom`: the left end and the right). Each range has its own default (`RANGES`); a range with no end ignores it. */ end?: SheetEnd; }
A named range at the end of your choice: { name: "offensive-zone", end: "left" } is the offensive zone of a team that attacks the left.
const RANGES
RANGES: Readonly<Record<Sport, readonly RangeInfo[]>>
The named ranges of each sport, in the order a menu lists them: { id, end }, with end the end the range is at when range gives none (left or right, as the surface is drawn wide; a range with no end is in the middle or is the whole of something and ignores one). Offensive ranges are at the right by default, as a frame's numbers are for a team that attacks the right (see toSurface); defensive and own ranges at the left; the others, such as a half, at the left, as a curling sheet's house is.
function readSituation
readSituation(situation: unknown, ctx: SituationContext): SituationRead | undefined
The situation a drawing's options ask for, decided: which team attacks and which end, what is lit. undefined when the options have none, when the sport has no situation (only hockey, baseball and football do), or when nothing in it is a value the sport can have.
type RealVenue
interface RealVenue extends RealVenueData { osm: VenueOsm; }
A venue: its facts and what OpenStreetMap gave.
type RealVenueData
interface RealVenueData { /** The key of the arena in `ARENAS`: `honda-center`. */ id: string; /** The Wikidata item of the arena. */ wikidata: string; division: VenueDivision; /** The English Wikipedia article the facts that are not Wikidata's were read from, at a revision. */ en: ArenaSource; seats: { /** The seats for ice hockey: Wikidata's where its item gives a figure for ice hockey (`wikidata`), else the artic…
The facts of a venue: the seats and the number of seating levels and the kind of roof, each with what a source says. No text of an article is kept.
type Reducer
type Reducer = (values: readonly number[], info: BinInfo) => number | null;
A custom statistic: the finite values of a bin's samples (an empty list when none had one), and the bin's counts. Return null for a bin that has no value.
function rescale
rescale(from: SoccerProviderId | SoccerFrame, to: SoccerProviderId | SoccerFrame, pitch?: PitchMetres): Rescaler
The map from one coordinate system to another, piecewise linear between the landmarks (it is built on piecewise of @johnmorrisdotca/kyogijo-stadiums/frames), so that a point on a line of the pitch (the goal line, the goal area, the penalty mark, the penalty area, the halfway line, the touchline, the posts) lands on the same line in the other system. Between two landmarks the map is linear; beyond the goal lines and the touchlines (a ball out of play) it runs on along the last piece. Give a pitch size in metres for a provider whose numbers follow the pitch (Tracab, SkillCorner, Second Spectrum, Metrica, international). The same map, through the surface and in feet, is convert of the frames module.
Example
import { rescale } from "@johnmorrisdotca/kyogijo-stadiums";
const toStatsBomb = rescale("opta", "statsbomb");
// The middle of Opta's penalty-box line, 17 units from the goal line, is on StatsBomb's, 18 yards from it.
const [x, y] = toStatsBomb(100 - 17, 50);
console.log(x, y);
// 102 40
type Rescaler
interface Rescaler { (x: number, y: number): [number, number]; /** Only the x of a point. */ x(value: number): number; /** Only the y of a point. */ y(value: number): number; /** The map the other way: from the second provider's coordinates to the first's. */ inverse: Rescaler; from: SoccerFrame; to: SoccerFrame; }
A map from one provider's coordinates to another's.
function resolveLighting
resolveLighting(ask: LightingOptions | undefined | null, team?: { home?: string; away?: string; }): Lighting | undefined
The lighting an option asks for: a preset's name, true for the first (night), or { preset, colors, aisles, wash }, or undefined for none (false, nothing, an unknown name). A colour comes from, in order: wash or aisles, colors (the first is what the preset's home is, the second its away), the teams' colours (team), the preset's own.
function rgbOf
rgbOf(value: string | undefined): [number, number, number] | undefined
The red, green and blue of a colour, when it can be read without a browser (a hex colour, rgb() or a common name).
type RinkFigures
interface RinkFigures { /** End boards to end boards. */ length: number; width: number; /** The radius of the boards' corners. */ cornerRadius: number; /** The goal line, from the end boards. */ goalLine: number; /** The blue lines, from the end boards. */ blueLine: number; /** The face-off circles' radius. */ circleRadius: number; /** An end-zone face-off spot, from the goal line, and from the rink's long axis. */ …
The figures of an ice rink. Lengths, in the unit of the table they are in.
type Rope
interface Rope { y: number; colour: RopeColour; }
A lane rope: where it lies across the pool (metres from the top wall) and its colour.
type RopeColour
type RopeColour = "green" | "blue" | "yellow";
The colours of the ropes of a pool, by name.
function rulesFor
rulesFor<S extends EraSport>(sport: S, year?: number): EraRules<S>
The markings of a sport's surface in a season: what the rule books and the leagues had painted on it then. Without a year it is today's (ERA_CURRENT). A season is named by the year it starts in (1979 is the 1979–80 season). differences lists what is not as it is today, gaps the markings that no source covers for the season, and approx those whose measure is not cited.
Example
import { rulesFor } from "@johnmorrisdotca/kyogijo-stadiums/eras";
const nba = rulesFor("nba", 1995);
console.log(nba.season, nba.rules.threePoint, nba.rules.restrictedArea, nba.differences.length);
// 1995–96 { radius: 22 } false 2
function safeColour
safeColour(value: unknown): string | undefined
The colour as it may be written into a style attribute, or undefined. A hex colour, rgb(), rgba(), hsl(), hsla(), a colour name or var(--name) is drawn; anything else is ignored, so nothing from a form or an address can end the attribute or add a rule.
Example
import { safeColour } from "@johnmorrisdotca/kyogijo-stadiums";
console.log(safeColour("#1f5fa8"), safeColour("red;fill:url(x)"));
// #1f5fa8 undefined
function safeLogo
safeLogo(value: unknown, context?: EmblemContext): string | undefined
A logo as it may be written into an image's href, or undefined. An https: or http: address, a relative path, an image data: address, an SVG document as text (written as an image, which cannot run scripts), or, with a renderer of emblems plugged in, the id of an emblem ("trophy:cup", "medal:gold", "sport:nhl", "crest:shield", a trophy or award by its short name such as "cup", with /line for the outline style), drawn for an image with the outline in dark or pale ink by the device's setting. The second argument gives a crest the team's colours and letters. With a renderer, a name that is an emblem's id is the emblem, not a file of that name: write ./cup for the file. Without one, an id is an address like any other, and "trophy:cup" is refused.
Example
import { safeLogo } from "@johnmorrisdotca/kyogijo-stadiums";
console.log(safeLogo("https://example.com/gulls.svg"), safeLogo("javascript:alert(1)"));
// https://example.com/gulls.svg undefined
function safePicture
safePicture(value: unknown): string | undefined
A picture's address as it may be written into an image's href, or undefined (what safeLogo checks after it has looked for an emblem's id). An https: or http: address, a relative path, an image data: address, or an SVG document as text (written as an image, which cannot run scripts).
Example
import { safePicture } from "@johnmorrisdotca/kyogijo-stadiums";
console.log(safePicture("https://example.com/gulls.svg"), safePicture("javascript:alert(1)"));
// https://example.com/gulls.svg undefined
type Scale
interface Scale { domain?: readonly [number, number]; range: readonly [number, number]; /** For a size: scale the area and not the width, so that twice the value covers twice the ground. On by default. */ area?: boolean; }
A number mapped to another range: domain is the values (the data's least and greatest when missing) and range what they become.
type ScoreOptions
interface ScoreOptions extends SurfaceOptions { home: Team; away: Team; /** `full` (the default), `compact` or `badge`. */ size?: Size; /** The state of the game: a `StatusWord`, or text such as "2nd period" or "Bottom 9th". */ status?: StatusWord | (string & {}); /** The competition and round: "Cup Final, Game 7". */ competition?: string; /** The date, as it is to be written. */ date?: string; /** A line of text fo…
What a score drawing takes beyond a surface.
function seasonLabel
seasonLabel(sport: EraSport, year: number): string
The name of a season as the sport writes it: 1979–80 for the NHL and the NBA, which play across the new year, and 1974 for the NFL, the CFL and baseball. The year is the one the season starts in.
Example
import { seasonLabel } from "@johnmorrisdotca/kyogijo-stadiums/eras";
console.log(seasonLabel("nba", 1979), seasonLabel("nhl", 1999), seasonLabel("nfl", 1974));
// 1979–80 1999–00 1974
type ShootoutAttempt
type ShootoutAttempt = boolean | null | undefined;
One shootout attempt: true a goal (●), false a miss or a save (○), null or left out one not yet taken.
type ShootoutRound
type ShootoutRound = readonly [away: ShootoutAttempt, home: ShootoutAttempt];
One round of a shootout: the visitors' attempt and then the home team's, as the NHL's shootout is shot (the visitors shoot first).
type Side
type Side = "left" | "right";
A side of the drawing as the eye sees it. Which side the home team is on follows the sport (see homeSideFor) unless homeSide says otherwise.
type Situation
type Situation = HockeySituation | BaseballSituation | FootballSituation;
A game's situation: the sport decides which of the three it is.
type SituationContext
interface SituationContext { /** The sport as drawn (`chooseLeague(o).sport`): `nhl`, `mlb`, `nfl`, `cfl` or `ifaf`; a situation is for these only. */ sport: Sport; /** The side the home team's banner is on. */ homeSide: Side; /** The attack arrows' options, which say which end each team attacks. */ direction?: DirectionOptions; /** The football field: the yards between the goal lines and the downs a team has. */ fo…
What a reading needs to know of the drawing it is for.
type SituationRead
type SituationRead = HockeyRead | BaseballRead | FootballRead;
A situation, read.
type SituationTeam
type SituationTeam = "home" | "away";
A team of the game: the home team or the visitors.
function situationText
situationText(options: { sport: Sport; league?: string; homeSide?: Side; direction?: DirectionOptions; language?: Language; situation?: Situation; }, language?: Language): string | undefined
The short label of a situation as the drawing writes it: hockey's 5v4 PP 1:42, baseball's Top 7 · 2 out · 3-2, football's 3rd & 7. undefined when there is none to write.
Example
import { situationText } from "@johnmorrisdotca/kyogijo-stadiums";
console.log(situationText({ sport: "nhl", situation: { awaySkaters: 5, homeSkaters: 4, clock: "1:42" } }));
console.log(situationText({ sport: "mlb", situation: { inning: 7, half: "top", outs: 2, balls: 3, strikes: 2 } }));
console.log(situationText({ sport: "nfl", situation: { ballOn: 88, down: 3, toGo: 7 } }));
// 5v4 PP 1:42
// Top 7 · 2 out · 3-2
// 3rd & 7 · OPP 12
type Size
type Size = "full" | "compact" | "badge";
The size of a score drawing: the surface with the score on it, the surface with a strip under it, or one strip.
type SkatingDiscipline
type SkatingDiscipline = "long-track" | "short-track" | "figure";
The disciplines a drawing can be of: the standard 400 m speed skating track, the short track oval or the figure skating rink. league says it too: isu-long-track, isu-short-track, isu-figure.
type SkatingFurniture
type SkatingFurniture = "judges" | "referee" | "technical-panel" | "kiss-and-cry";
The things that stand at the rink of a figure skating competition: the judges and the referee at the rinkboard, the technical panel, and the kiss and cry.
type SkatingInfield
type SkatingInfield = "floor" | "ice";
What lies inside the long track: the ice of the warm-up lane carried on to the infield, or the floor of the arena.
type SkatingRace
type SkatingRace = LongTrackRace | ShortTrackRace;
Every race a drawing can mark.
type SkatingStyle
interface SkatingStyle { /** Long track: the radius of the inner edge of the inner lane, 25 m to 26 m (25 m by default). The straight follows, so that a lap is 400 m. */ innerRadius?: number; /** Long track: the width of the outer lane, 4 m or more (4 m by default). */ laneWidth?: number; /** Long track: the warm-up lane inside the competition lanes. On by default. */ warmUp?: boolean; /** Long track: what lies insi…
What a skating drawing takes beyond a surface. Every part is optional: the standard 400 m track with an inner radius of 25 m, two lanes of 4 m, the warm-up lane, the blocks and the padding is drawn without any, and so are the short track's standard oval with its five tracks and the figure skating rink of 60 m by 30 m.
const SOCCER
SOCCER: { readonly goalWidth: 7.32; readonly goalHeight: 2.44; readonly goalAreaReach: 5.5; readonly penaltyReach: 16.5; readonly spot: 11; readonly centreRadius: 9.15; readonly arcRadius: 9.15; readonly cornerRadius: 1; readonly flagHeight: 1.5; readonly limits: { readonly length: readonly [90, 120]; readonly width: readonly [45, 90]; readonly internationalLength: readonly [100, 110]; readonly internationalWidth: r…
Law 1 of the IFAB Laws of the Game (2025/26), the markings of a full pitch: the goal area reaches 5.5 m from the posts and into the field, the penalty area 16.5 m, the penalty mark is 11 m from the goal line, the arcs and the centre circle have a radius of 9.15 m, the corner arc 1 m; the goal is 7.32 m between the posts and 2.44 m high; the lines are at most 12 cm wide. The Laws give yards beside each (6, 18, 12, 10 and 8 yards and 8 feet).
const SOCCER_PITCH_IDS
SOCCER_PITCH_IDS: readonly SoccerPitchId[]
The ids of the presets, in the order a menu lists them.
const SOCCER_PITCHES
SOCCER_PITCHES: Readonly<Record<SoccerPitchId, SoccerSpec>>
The presets: the international pitch of 105 by 68 m (the Laws' usual, the Premier League's and UEFA's categories 3 and 4), the least size the MLS requires (110 by 70 yards) and the NCAA's best (120 by 75 yards), the least and most the Laws allow, the FA's 9-, 7- and 5-a-side pitches and FIFA's futsal court. Each is a full SoccerSpec.
Example
import { SOCCER_PITCHES } from "@johnmorrisdotca/kyogijo-stadiums";
const { length, width, name } = SOCCER_PITCHES.fifa;
console.log(name, length, width);
// International (FIFA) 105 68
const SOCCER_PROVIDER_IDS
SOCCER_PROVIDER_IDS: readonly SoccerProviderId[]
The ids of the providers, in the order a menu lists them.
const SOCCER_PROVIDERS
SOCCER_PROVIDERS: Readonly<Record<SoccerProviderId, SoccerProvider>>
The providers. Where a provider's own page gives the figures (StatsBomb's and Wyscout's diagrams, Impect's glossary, Metrica's and SkillCorner's READMEs) they are those; Opta's, Tracab's and Second Spectrum's specifications are not public, so theirs are the figures the open-source libraries mplsoccer, ggsoccer and kloppy agree on, which docs/sources.md says.
function soccerFrame
soccerFrame(frame: SoccerProviderId | SoccerFrame | string | undefined, pitch?: PitchMetres): SoccerFrame | undefined
The frame of a provider (by id), or a frame of your own as it is, for a pitch of this size in metres (which matters only to a provider whose numbers follow the pitch). An id that is not a provider, or a frame that cannot be drawn, gives undefined.
Example
import { soccerFrame } from "@johnmorrisdotca/kyogijo-stadiums";
const opta = soccerFrame("opta");
console.log(opta?.xRight, opta?.yTop);
// 100 100
type SoccerFrame
interface SoccerFrame { id: string; name: string; /** The unit of the numbers, for people. */ unit: string; xLeft: number; xRight: number; yTop: number; yBottom: number; /** How far the penalty area reaches from the goal line, and half its width. */ penaltyDepth: number; penaltyHalfWidth: number; /** How far the goal area reaches, and half its width. */ goalAreaDepth: number; goalAreaHalfWidth: number; /** The penal…
A pitch as a data provider writes it down. Everything is in the provider's own unit.
xLeft and xRight are x at the two goal lines, with the team attacking left to right; yTop and yBottom are y at the touchlines as they lie in a picture with the first at the top. So the frame says both where the origin is and which way y runs: Opta (y up) has yTop: 100, yBottom: 0; StatsBomb (y down) has yTop: 0, yBottom: 80. The depths are measured from the goal line along x, the half widths from the middle of the pitch along y.
function soccerLandmarks
soccerLandmarks(f: SoccerFrame): { x: number[]; y: number[]; }
Where the landmarks of a frame stand on each axis, in its units, from the left goal line to the right and from the top touchline to the bottom.
function soccerPitchClass
soccerPitchClass(length: number, width: number): SoccerPitchClass
Where a pitch of this size stands under Law 1: international (100 to 110 m by 64 to 75 m, for international matches), within-laws (90 to 120 m by 45 to 90 m, and the touchline longer than the goal line) or outside-laws.
Example
import { soccerPitchClass } from "@johnmorrisdotca/kyogijo-stadiums";
console.log(soccerPitchClass(105, 68), soccerPitchClass(95, 60), soccerPitchClass(60, 40));
// international within-laws outside-laws
type SoccerPitchClass
type SoccerPitchClass = "international" | "within-laws" | "outside-laws";
Which of the Laws' ranges a length and a width fall in.
type SoccerPitchId
type SoccerPitchId = "fifa" | "uefa" | "mls" | "ncaa" | "law-min" | "law-max" | "9-a-side" | "7-a-side" | "5-a-side" | "futsal";
The ids of the presets.
type SoccerProvider
interface SoccerProvider { id: SoccerProviderId; name: string; /** The unit of its numbers, for people. */ unit: string; /** The unit as the frames registry names it. */ frameUnit: FrameUnit; /** Where (0, 0) lies, in words. */ origin: string; /** True when its extents follow the size of the pitch (Tracab's centimetres from the centre): the frame is made for a size. */ sized: boolean; /** The page of the provider's …
A provider: its name, the page its figures were read from, and its frame (which for some depends on the size of the pitch).
type SoccerProviderId
type SoccerProviderId = "opta" | "statsbomb" | "wyscout" | "tracab" | "metrica" | "skillcorner" | "secondspectrum" | "impect" | "uefa" | "international";
The providers, by the id the options use.
type SoccerSize
interface SoccerSize { length: number; width: number; /** `m` (the default), `yd`, `ft`, `in`, `cm` or `mm`. */ unit?: "m" | "yd" | "ft" | "in" | "cm" | "mm"; }
A pitch given by size: any positive length and width, in metres, yards or feet.
function soccerSpec
soccerSpec(pitch?: SoccerPitchId | SoccerSize | string, defaultUnit?: NonNullable<SoccerSize["unit"]>): SoccerSpec
The pitch an option asks for: a preset's id, or a size. An unknown id, or a size that is not a positive number (or is more than 400 m), gives the international pitch. A size has the Laws' markings of a full pitch, sized to fit: the areas are never wider than the pitch.
Example
import { soccerSpec } from "@johnmorrisdotca/kyogijo-stadiums";
const pitch = soccerSpec({ length: 110, width: 70, unit: "yd" });
console.log(pitch.length.toFixed(2), pitch.width.toFixed(2));
// 100.58 64.01
type SoccerSpec
interface SoccerSpec { id: string; /** The name written in the title. */ name: string; format: SoccerFormat; /** Goal line to goal line (the touchline). */ length: number; /** Touchline to touchline (the goal line). */ width: number; /** The penalty area: how far it reaches into the field from the goal line, and its width along the goal line. */ penaltyDepth: number; penaltyWidth: number; /** The goal area (the six-…
A pitch: its size and every marking. All lengths in metres.
type SonarLayer
interface SonarLayer extends LayerBase { kind: "sonar"; data: readonly MoveDatum[]; /** What a rose is of: `all` (one rose, at the middle of the movements' starts; the default), `player` (one for each `id`, at the average start of his), `grid` (one for each cell of a grid) or `zone` (one for each zone of `zones`). */ by?: "all" | "player" | "grid" | "zone"; /** How many directions a rose is cut into. 12 by default. …
A rose for each group of movements: how many go in each direction, or how long they are on average.
type Sport
type Sport = "nfl" | "cfl" | "ifaf" | "nhl" | "nba" | "mlb" | "soccer" | "curling" | "tennis" | "volleyball" | "badminton" | "pickleball" | "tabletennis" | "padel" | "squash" | "racquetball" | "sepaktakraw" | "teqball" | "roundnet" | "netball" | PoolSport | FieldSport | "athletics" | "skating" | BudoSport | CombatSport;
The surfaces: three football fields, a rink, a court, a ballpark, a soccer pitch, a curling sheet, twelve net, racket and court sports (tennis, volleyball, badminton, pickleball, table tennis, padel, squash, racquetball, sepak takraw, teqball, roundnet and netball), four pools (swimming, water polo, diving and artistic swimming), seven field sports (lacrosse, rugby, Australian football, Gaelic football and hurling, cricket, field hockey and handball) and the athletics stadium (the 400 m track with its infield, and the covered 200 m track).
const SPORTS
SPORTS: readonly Sport[]
The sports that can be drawn, in the order a menu lists them.
type StandGap
interface StandGap { kind: "tunnel" | "bench" | "media" | "camera"; box: [x0: number, y0: number, x1: number, y1: number]; }
A place left open or built on: a tunnel through the lower stands, a bench, the camera platform of the media side. A box in the wide frame.
type StandOutline
type Outline = | { kind: "rrect"; x0: number; y0: number; x1: number; y1: number; r: number } | { kind: "ellipse"; cx: number; cy: number; rx: number; ry: number } | { kind: "poly"; points: Pt[] };
The outline of a part of the stands, in feet in the surface's wide frame: a rectangle with rounded corners, an ellipse, or a polygon.
type StandRing
interface StandRing { /** `lower`, `middle`, `upper`, `courtside`, `grandstand` or `bleachers`, with the tier's number where a ring has parts. */ id: string; tier: "courtside" | "gallery" | "lower" | "middle" | "upper" | "grandstand" | "bleachers" | "wall"; /** The band is `region` less `hole` (nothing for a polygon that is the band itself). */ region: Outline; /** Further pieces of the band that are apart from `reg…
A tier of the stands: a band of seats between two outlines.
type StandSector
interface StandSector { ring: string; kind: "away" | "tifo-home" | "tifo-away" | "closed"; points: Pt[]; }
A block of the stands that is not the home fans': the visitors', or a card display. A polygon in the wide frame.
type StatisticName
type StatisticName = "count" | "sum" | "mean" | "median" | "percent" | "max" | "min" | "rate";
The statistics of a bin. percent is each bin's share of all the samples (0 to 100); rate is the share of a bin's samples that are hits (0 to 100).
function statusLabel
statusLabel(status: string | undefined, language?: Language): string | undefined
The words of a status in a language: a standard one is translated, any other text is kept as it is.
function statusText
statusText(o: Pick<ScoreOptions, "home" | "away" | "status" | "homeSide"> & Partial<Pick<ScoreOptions, "sport" | "league">>, language?: Language): string | undefined
The words of a status, with the penalty shoot-out beside them when both teams have one: "Final/AET", or "Final · 4-2 pens" (the shoot-out score in the order of the drawing's sides: the home team's first when it is on the left, which is the default for soccer and the other sports that list the home team first). Pass sport (and league) for the sport's default; with neither, the away team's is first unless homeSide is left.
type StatusWord
type StatusWord = "final" | "final-ot" | "final-so" | "final-aet" | "final-pens" | "live" | "half" | "extra-time" | "extra-end" | "penalties" | "postponed" | "tiebreak" | "match-tiebreak" | "retired" | "walkover";
The standard words of a status. end-6 (or "End 6") is a curling end, set-3 a set and game-2 a game, innings-2 (or "Innings 2") a cricket innings. Any other text is written as it is.
type StripePattern
type StripePattern = "bands" | "wide" | "narrow" | "lengthwise" | "checks" | "diagonal" | "diamonds" | "circles" | "rings" | "fan" | "none";
How grass is mown: bands across the surface (the usual), wide ones or narrow ones, along it, in checks, on the diagonal, in diamonds (the checks turned 45 degrees: a ballpark outfield's crosshatch, its sides along the foul lines), in rings round the middle (circles), or none. A ballpark is mown in rings by default (arcs about home plate) and may also be mown in a fan (wedges out from home plate). A football field and a ballpark take the same options as a soccer pitch; a surface that is not grass ignores them.
const SURFACE_UNITS
SURFACE_UNITS: Readonly<Record<Sport, Unit>>
The unit each surface's rulebook states its dimensions in: the NFL's and the CFL's fields in yards (and the IFAF's, which follows them), the NHL's rink, the NBA's court and the baseball field in feet, a soccer pitch in metres (the Laws'), a tennis court, a pickleball court and a racquetball court in feet (the ITF's, USA Pickleball's and the IRF's), a volleyball court, a badminton court, a table, a padel court, a squash court, a sepak takraw court, a teqball court, a roundnet court and a netball court in metres (FIVB's, BWF's, ITTF's, FIP's, World Squash's, ISTAF's, FITEQ's, the International Roundnet Federation's and World Netball's), a curling sheet in metres (World Curling's rules give metres with feet beside them; Curling Canada's give feet first, and its league curling-canada has feet), a rugby field, an Australian football ground, a Gaelic field, a hockey pitch and a handball court in metres (the rulebooks'), a swimming pool, a water polo field, a diving well and an artistic swimming area in metres (World Aquatics') and a cricket ground in yards (the Laws' and the ICC's; the NLL's box floor and the PLL's and the NCAA men's fields are in the leagues' own feet and yards). A Japanese park's fence is measured in metres and converted once: see parkUnit.
type SurfaceOptions
interface SurfaceOptions { sport: Sport; /** `auto` (the default), `light` or `dark`. */ theme?: Theme; /** `landscape` (the default), `portrait` or `auto`. */ orientation?: Orientation; /** For `orientation: "auto"`: the container's width over its height. Without it `auto` draws landscape. */ aspect?: number; /** Give the parts of the drawing `part` names (`surface`, `plate`, `away`, `home`, `score`), for styling i…
What every drawing takes.
type Swimmer
interface Swimmer { /** The lane, as the pool numbers them (1 to 8, or 0 to 9 in a ten-lane pool). */ lane: number; name: string; /** A short form for the label: the country's three letters, or a club's. */ abbr?: string; /** The flag or crest, drawn small beside the name. */ flag?: string; /** A country code (`CA`, `jp`) for the flag, drawn by the renderer of flags plugged in with `useFlags` (or the drawing's `flag…
One swimmer in a lane: who is in it, and, once the race is swum, what happened. The caller passes the flag (an https: address, an image data: address or an SVG document as text, held to the rules of a team's logo); the package bundles no flags. Times are seconds (26.12) or text ("1:46.91").
type SwimmerStatus
type SwimmerStatus = "dq" | "dns" | "dnf";
Why a swimmer has no time.
function swimPlan
swimPlan(o: Pick<SurfaceOptions, "pool" | "sport">, defaults?: Partial<Pick<VenuePool, "course" | "kind" | "lanes">>): SwimPlan
The swimming pool the options ask for: pool.course (long, 50 m, or short, 25 m) and pool.lanes (8 by default). The width is the rules' for that many lanes: 25 m for eight in a 50 m pool (Part Two 15.6.1), 25 m for ten with lanes 0 and 9 of 2.4 m (Part Two 15.6.2.1), or 26 m for a temporary pool (Part Two 15.6.2.2), and lanes of 2.5 m with spaces of 0.5 m for the other pools.
type SwimPlan
interface SwimPlan extends Common { sport: "swimming"; kind: PoolKind; course: "long" | "short"; /** The length between the touch panels and the width across the lanes and the spaces, in metres. */ length: number; width: number; /** The lanes from the top of the drawing down: lane 1 (or 0) is at the bottom, on the right when one faces the course from the start (Part Two 15.8.6). */ lanes: LanePlan[]; /** The metres …
A swimming pool to draw.
type TableOptions
interface TableOptions { language?: "en" | "ja"; /** The most rows to write for one layer. 500 by default; the caption says when rows are left out. */ maxRows?: number; /** A class for each table. `ky-table` by default. */ className?: string; /** The drawing's options (at least `sport`, and `park`, `pitch`, `units` and `language` where they apply): needed for the tables of heat maps, hexagon maps, zone charts and co…
What layerTable takes.
type Tatami
type Tatami = Piece;
One mat of a dojo's floor, or a part of one, in metres from the floor's top left corner.
type Team
interface Team { /** The name, as it is to be written: "Canada". */ name: string; /** A short form, three letters or so, for the score and the badge. Taken from the name when missing. */ abbr?: string; /** The score. A number, or text such as "–" before the game. */ score?: number | string; /** * A country code (`CA`, `jp`, `GB-ENG`) for the team's flag, drawn by the renderer of flags plugged in with `useFlags` (or …
One team of a score.
type TeamMark
type TeamMark = "plain" | "round";
The shape of a team's mark: its logo as it is (plain), or clipped to a circle with a ring (round).
type TextDatum
interface TextDatum extends MarkDatum { x: number | null; y: number | null; text: string | number; /** The height of the letters, in the layer's units. */ size?: number; /** Turn the text this many degrees, clockwise, as the eye sees it. The text stays upright when the surface is turned. */ rotate?: number; anchor?: "start" | "middle" | "end"; }
A word or a number to write.
type TextLayer
interface TextLayer extends LayerBase { kind: "text"; data: readonly TextDatum[]; style?: TextStyle; }
type TextStyle
interface TextStyle { /** The height of the letters in the layer's units. A default that follows the size of the surface. */ size?: number; color?: Paint; weight?: number; anchor?: "start" | "middle" | "end"; /** Outline the letters in the halo colour (`--ky-halo`) so that they read on any ground. On by default. */ halo?: boolean; opacity?: number; }
How text looks.
function textWidth
textWidth(text: string, bold?: boolean): number
An estimate of the width of a string, in ems. Characters of Japanese and other full-width scripts are one em.
type Theme
type Theme = "auto" | "light" | "dark";
auto follows the device's light or dark setting (and data-theme on the page's root), the others force one.
type Unit
type Unit = "ft" | "in" | "yd" | "m" | "cm" | "mm";
A unit of length: feet, inches, yards, metres, centimetres or millimetres.
const UNITS
UNITS: readonly Unit[]
The units, from the largest used for a field to the smallest.
function useEmblems
useEmblems(render: EmblemRenderer | undefined): void
Plug a renderer of ready-made emblems into kyogijo, for every drawing on the page: after this logo: "crest:shield" and emblem: "trophy:hockey-cup" are drawn. Call it once, at start-up. Without one, an id is an address and is refused. useEmblems(undefined) unplugs it.
Example
import { useEmblems } from "@johnmorrisdotca/kyogijo-stadiums";
import { renderEmblem } from "@johnmorrisdotca/dougu-sports/emblems";
useEmblems(renderEmblem);
function useFlags
useFlags(render: FlagRenderer | undefined): void
Plug a renderer of country flags into kyogijo, for every drawing on the page: after this a team's flag: "CA" is drawn. Call it once, at start-up. Without one a team's flag is ignored and its logo (or its initials) is drawn. useFlags(undefined) unplugs it.
Example
import { useFlags } from "@johnmorrisdotca/kyogijo-stadiums";
const loaded = { round: { CA: "<svg viewBox='0 0 1 1'>...</svg>" } } as Record<string, Record<string, string>>;
useFlags((code, { shape }) => loaded[shape]?.[code.toUpperCase()]);
const VARIANTS
VARIANTS: readonly League[]
Every league of every family, once each.
const VENUE_ATTRIBUTION
VENUE_ATTRIBUTION: "(c) OpenStreetMap contributors, ODbL 1.0, openstreetmap.org/copyright"
The credit the ODbL asks for, wherever a drawing made from OpenStreetMap's data is shown.
const VENUE_CONFERENCES
VENUE_CONFERENCES: { readonly western: readonly ["pacific", "central"]; readonly eastern: readonly ["atlantic", "metropolitan"]; }
The NHL's two conferences, and the divisions of each.
const VENUE_DIVISIONS
VENUE_DIVISIONS: readonly ["pacific", "central", "atlantic", "metropolitan"]
The NHL's divisions, in the order of the league's own listing: the Western Conference's two, then the Eastern's. A division none of whose arenas has a venue yet has no venues in venuesIn.
const VENUE_IDS
VENUE_IDS: readonly string[]
The keys of VENUES, in the order of the data.
type VenueBasis
type VenueBasis = "documented" | "plausible";
How a fact is known: documented is what a source cited with it says; plausible is ours, for a bowl no source describes.
function venueBowl
venueBowl: (venue: RealVenue, rink?: Box) => RealBowl
The stands of a venue for layoutOf and the 3D view, round a rink: planVenue's bowl.
function venueById
venueById: (id: string | undefined) => RealVenue | undefined
The venue of an arena (by its key in ARENAS), or undefined for an arena that has none. A venue that has not been read yet (the lean district reads them with loadVenueDataFor) throws, saying so.
function venueByWikidata
venueByWikidata: (wikidata: string | undefined) => RealVenue | undefined
The venue whose arena is the Wikidata item Q774138, or undefined.
type VenueConference
type VenueConference = keyof typeof VENUE_CONFERENCES;
type VenueDivision
type VenueDivision = (typeof VENUE_DIVISIONS)[number];
type VenueItem
interface VenueItem { pool: VenuePool; plan: PoolPlan; x: number; y: number; }
One pool of a hall: its plan and where its water's top left corner is, in metres from the corner of the water of the whole hall.
function venueLayout
venueLayout(style: PoolStyle): VenueLayout | undefined
The pools of a hall (pool.venue) laid out to scale. A pool with an x and a y stands there; the others are set in rows, left to right, each apart metres (10, the distance the rules prefer between a swimming pool and a diving well, Part Two 15.15.1; never less than the 8 they require) from the one before, and a new row when a row would be longer than 125 m.
type VenueLayout
interface VenueLayout { items: VenueItem[]; width: number; height: number; apart: number; labels: boolean; seating: boolean; /** How far the pools' fixtures reach beyond the box, in metres. */ reach: { left: number; right: number; top: number; bottom: number }; }
A hall laid out: its pools, and the size of the box round their water, in metres.
type VenueOptions
interface VenueOptions { pools: readonly VenuePool[]; /** The metres between two pools. 10 (the preferred distance of the rules) by default. */ apart?: number; /** Write each pool's name on the plan. On by default. */ labels?: boolean; /** Draw the seating for spectators along the top of the hall. On by default. */ seating?: boolean; }
A natatorium: several pools in one hall, to scale, kept the distance the rules ask of a swimming pool and a diving well.
function venueOrientation
venueOrientation: (venue: RealVenue) => VenueOrientation
How the rink lies in a venue's building (see VenueOsm.axis).
type VenueOrientation
interface VenueOrientation { heading: number; /** `mapped`: from the ice OpenStreetMap maps in the building. `building`: from the building's long axis, which a rink usually follows (an inference). `none`: the building is near round, nothing is known, the plan has north at the top. */ basis: "mapped" | "building" | "none"; north: number; }
How the rink lies in the building: its long side's heading (degrees clockwise from north, 0 to under 180), how that is known, and the way north points on the page (degrees clockwise from the top).
type VenueOsm
interface VenueOsm { /** The element the outline is: `way/120623151`. */ source: string; /** The day it was read and the time of the OpenStreetMap data the answer was made from. */ read: string; base: string; licence: "ODbL-1.0"; attribution: string; /** The building's height in metres, where OpenStreetMap maps one. */ height?: number; /** The building's outline as `[longitude, latitude]`, not repeating its first po…
What OpenStreetMap gave of a venue: ODbL 1.0 data, "(c) OpenStreetMap contributors".
type VenuePlan
interface VenuePlan { venue: RealVenue; orientation: VenueOrientation; /** The rink, in the drawing's frame. */ box: Box; /** The building's outline in feet, in the drawing's frame (the rink along x, in the middle of the building's box). */ footprint: Pt[]; /** The stands for `layoutOf`: tiers, first row, ground, and the building and roof. */ bowl: RealBowl; /** The seats the bowl's tiers hold, by tier, and in all: …
The plan of a venue: its building in the drawing's frame, the bowl fitted inside, and how it lies.
type VenuePool
interface VenuePool { sport: PoolSport; /** A name for the plan's label. The pool's own by default. */ name?: string; /** For a swimming pool: its course and kind (`short` and `warm-up` for a warm-up pool). */ course?: "long" | "short"; kind?: PoolKind; lanes?: number; x?: number; y?: number; }
One pool of a natatorium: which pool it is, and where, in metres from the hall's top left corner. A pool with no place is put by the layout.
function venueRink
venueRink(venue: RealVenue): Box
The rink's box as the drawing has it: the arena's own where its sources publish a size, else the NHL's.
type VenueRoof
type VenueRoof = "fixed" | "saddle" | "barrel";
The kinds of roof the venues have: fixed is a lid over the bowl, saddle a roof that rises at two opposite points of its rim and falls at the two between (the Scotiabank Saddledome's), barrel a barrel vault along the rink, a round arch over its short axis (the American Airlines Center's).
const VENUES
VENUES: Readonly<Record<string, RealVenue>>
The real venues held for the drawing, by key: every venue in the entries that have always had them (the full table, venues.all.ts, fills it), and in the lean district the venues loadVenueDataFor has read. Do not write to it.
Example
import { VENUES } from "@johnmorrisdotca/kyogijo-stadiums/venues";
console.log(VENUES["honda-center"].seats.hockey);
// 17174
function venuesIn
venuesIn: (division: VenueDivision) => RealVenue[]
The venues of a division of the NHL, in the order of the data.
function venuesInConference
venuesInConference: (conference: VenueConference) => RealVenue[]
The venues of a conference of the NHL, division by division, in the order of the data.
const VERSION
VERSION: "0.64.0"
The package's version: the same as package.json's, and a test holds them to each other.
type VoronoiLayer
interface VoronoiLayer extends PlayersBase { kind: "voronoi"; }
The part of the surface nearest each player, coloured by team: who controls the space (the Voronoi diagram of the players, clipped to the surface).
const WALL_SEATS
WALL_SEATS: Readonly<Record<string, string>>
The walls the package knows have seats on top of them, by park and the wall's label: Fenway Park's Green Monster (the Monster seats, 2003).
type WallOptions
interface WallOptions { /** A key under the drawing for the shades: under 10 feet, 10 to 20, 20 to 30 and 30 and over (the same in metres for a drawing in metres). */ legend?: boolean; /** Write each wall's name or place and its height beside it. */ labels?: boolean; }
How a ballpark's walls are drawn (walls).
type WallPlace
type WallPlace = "outfield" | "left" | "leftCenter" | "center" | "deadCenter" | "rightCenter" | "right" | "leftToCenter" | "centerToRight" | "leftCorner" | "rightCorner";
Where a stretch of wall stands, in words: a key of the words of ballpark.sections (left, leftCorner, deadCenter, centerToRight...).
type WaterJump
type WaterJump = "inside" | "outside" | "none";
Where the steeplechase's water jump is: inside the second bend, outside it, or not drawn.
function winnerOf
winnerOf(o: Pick<ScoreOptions, "home" | "away" | "status" | "winner"> & { sport?: Sport; }): "home" | "away" | "none"
Who is ahead in a score drawing, as the drawing's emphasis. auto (the default) picks the leader once the status is a final one; leader picks the leader of any game; a level game has none unless both teams have a penalty shoot-out score (penalties) and the shoot-out was not level; a score that is not a number has none.
const ZONE_SET_IDS
ZONE_SET_IDS: readonly ZoneSetId[]
const ZONE_SETS
ZONE_SETS: Readonly<Record<ZoneSetId, { sports: readonly Sport[]; title: string; source: string; }>>
Every zone set, with the sports it is for, the source of its definition and its title.
type ZoneSetId
type ZoneSetId = "field-thirds" | "cricket-ground" | "soccer-positional" | "soccer-thirds" | "soccer-channels" | "soccer-18" | "nba-shot" | "nhl-slot" | "nhl-home-plate" | "baseball-spray" | "baseball-retrosheet" | "football-pass" | "athletics-track" | "skating-track" | "budo-areas" | "curling-house" | "net-court" | "wall-court" | "roundnet-rings" | "pool-lanes" | "water-polo-areas" | "pool-thirds";
The zone sets.
type ZonesLayer
interface ZonesLayer extends HeatBase { kind: "zones"; /** The set of zones: `soccer-positional`, `soccer-thirds`, `soccer-channels`, `soccer-18`, `nba-shot`, `nhl-slot`, `nhl-home-plate`, `baseball-spray`, `baseball-retrosheet` or `football-pass`. */ zones: ZoneSetId; /** The way the team attacks as the surface is drawn wide: names the sides and counts the soccer bands from the team's own end. `right` by default. *…
A statistic by named zone of the surface.
@johnmorrisdotca/kyogijo-stadiums/layers
ArrowsLayer Bandwidth Bin binGrid BinInfo buildZoneSet clipNearer Comet ContourLayer contourRings convexHull delaunay DelaunayLayer Density densityAt densityGrid drawLayers FlowLayer Formation FORMATION_IDS formationById FormationLayer FormationPlayer FormationPosition FORMATIONS formationsOf FormationSport Grid HEAT_RAMP_NAMES HEAT_RAMPS HeatBase HeatBins HeatDatum HeatLabels HeatLegend HeatmapLayer HeatRamp HeatRampName HeatStatistic hexAt HexBin HexbinLayer hexBins hexCentre hexCorners HexOrientation HullLayer KYOGIJO_HEAT_STYLE KYOGIJO_TEAM_STYLE Layer LayerBase LayerKind layerTable LayerTeam LegendLayer LineDatum LinesLayer LineStyle LINEUP_CODES LineupLayer LineupPlayer MarkDatum MarkShape massThresholds median MoveDatum Named neighbours NetworkLayer NetworkNode niceTicks OUTCOMES OutcomeStyle Outline outlineOf Paint PassDatum PlayerDatum PointDatum PointsLayer PointStyle polygonArea polygonCentroid POSITION_NAMES positionName Pt rampColour reduceBin Reducer RenderedLayers renderLayers resolveRamp Sample Scale scottBandwidth SonarLayer StatisticName TableOptions TextDatum TextLayer TextStyle Triangulation triangulationEdges uniformEdges voronoiCells VoronoiLayer ZONE_SET_IDS ZONE_SETS ZoneContext ZoneSet ZoneSetId ZoneShape ZonesLayer
type ArrowsLayer
interface ArrowsLayer extends LayerBase { kind: "arrows"; data: readonly LineDatum[]; style?: LineStyle; }
type Bandwidth
type Bandwidth = number | readonly [number, number] | "scott";
The shape of a density's bandwidth.
type Bin
interface Bin { n: number; hits: number; sum: number; nv: number; low: number; high: number; values: number[] | undefined; }
One bin's accumulator.
function binGrid
binGrid(samples: readonly Sample[], xEdges: readonly number[], yEdges: readonly number[], keepValues?: boolean): Grid
Count samples into the rectangles between two lists of edges (binned_statistic_2d's job). A sample outside the edges is counted as outside.
type BinInfo
interface BinInfo { /** How many samples fell in the bin. */ count: number; /** How many of them were hits. */ hits: number; /** How many samples were binned in all. */ total: number; }
What a bin holds, and what a custom reducer is told.
function buildZoneSet
buildZoneSet(id: ZoneSetId, ctx: ZoneContext): ZoneSet
The zones of a set on the surface the context describes. Throws for a set that is not for the surface's sport.
function clipNearer
clipNearer(polygon: readonly Pt[], a: Pt, b: Pt): Pt[]
A convex polygon cut to the side of the line that is nearer a than b (Sutherland and Hodgman's clip against one half plane).
type Comet
interface Comet { /** The opacity at the start, 0 to 1. 0.05 by default. */ from?: number; /** Draw it as a shape that thickens towards the end, not as a stroke of one width. */ taper?: boolean; }
The look of a comet: a line that fades in along its length, and may also thicken.
type ContourLayer
interface ContourLayer extends HeatBase { kind: "contour"; /** The kernel's width, in the layer's units (one number, or one for each axis), or `scott` (the default: Scott's rule, each axis's spread times n^(-1/6)). */ bandwidth?: Bandwidth; /** A multiple of the bandwidth: under 1 follows the data more closely, over 1 smooths it. 1 by default. */ smooth?: number; /** The grid the density is computed on, nodes across…
A kernel density estimate of the marks, drawn as filled bands or lines (hockey_rink's contour and contourf, mplsoccer's kdeplot).
function contourRings
contourRings(d: Density, level: number): Pt[][]
The closed rings that bound the part of a density at or above level, by marching squares. The grid is padded with a border of nodes below every level, so every ring closes (a region that reaches the box's edge is closed just beyond it). The rings are in the density's own coordinates; a ring that bounds a hole runs the other way, so that an even-odd fill leaves the hole empty.
function convexHull
convexHull(points: readonly Pt[]): Pt[]
The convex hull of some points: its corners in order, counter-clockwise with y up (clockwise on a page, where y is down), starting at the least x. A point on an edge of the hull is not a corner. The same point twice is one. With no points the hull is empty, with one it is that point, and with two or with all on a line it is the two ends.
Example
import { convexHull } from "@johnmorrisdotca/kyogijo-stadiums/layers";
console.log(convexHull([[0, 0], [4, 0], [2, 0], [4, 3], [1, 1], [0, 3]]));
// [ [ 0, 0 ], [ 4, 0 ], [ 4, 3 ], [ 0, 3 ] ]
function delaunay
delaunay(input: readonly Pt[]): Triangulation
The Delaunay triangulation of some points: triangles whose circumcircle holds no other point, which cover the points' convex hull. Bowyer and Watson's method: each point is added by removing the triangles whose circumcircle holds it and joining it to the edge of the hole. The hull is kept by "ghost" triangles (an edge and a point at infinity) in place of a big triangle round everything, so that a point on or beyond the hull is handled exactly and no sliver of the hull is lost. Points are added from the least x, so the answer does not depend on the order given (up to which of four points on one circle are joined). Points that are not finite numbers are not allowed; a repeated point is one point.
Example
import { delaunay } from "@johnmorrisdotca/kyogijo-stadiums/layers";
const t = delaunay([[0, 0], [10, 0], [5, 8], [5, 3]]);
console.log(t.points.length, t.triangles.length / 3);
// 4 3
type DelaunayLayer
interface DelaunayLayer extends PlayersBase { kind: "delaunay"; /** One triangulation for each team (`team`, the default) or one for all the players. */ by?: "team" | "all"; /** Fill the triangles, not only draw their edges. */ triangles?: boolean; }
The Delaunay triangulation of the players: triangles whose circle holds no other player, a mesh of near neighbours.
type Density
interface Density { nx: number; ny: number; x: readonly [number, number]; y: readonly [number, number]; /** Row by row from the top: `z[j * nx + i]` at node `i`, `j`. The density integrates to 1 over the plane (per square of the samples' unit). */ z: Float64Array; /** The bandwidths used, in the samples' unit. */ bandwidth: [number, number]; max: number; }
A density on a grid of nodes, nx by ny, spaced evenly from the first to the last of x and of y.
function densityAt
densityAt(d: Density, x: number, y: number): number
The density's value at (x, y), by bilinear interpolation between the four nodes round it (0 outside the grid).
function densityGrid
densityGrid(samples: readonly Sample[], box: { x: readonly [number, number]; y: readonly [number, number]; }, nx: number, ny: number, bandwidth: readonly [number, number], weights?: readonly number[]): Density
A Gaussian kernel density estimate of weighted samples on a grid of nodes. A sample adds a bell of the given bandwidth to every node within four bandwidths of it (the bell's tail beyond is under a thousandth of its height), so the cost is the number of samples times a window of nodes and not the whole grid. The density is not folded back at the edges: what lies beyond the box is lost.
function drawLayers
drawLayers(options: SurfaceOptions | ScoreOptions, layers: readonly Layer[]): string
The layers of a drawing as one SVG group, in the surface's own frame, for a caller who composes the drawing's parts. Put it inside the surface's group (the one with the quarter turn, when the drawing is tall) and the marks lie on the surface, cut to its outline, with the text still upright. The same options and layers always give the same string; drawKyogijo draws exactly this when it is given layers.
Example
import { drawLayers } from "@johnmorrisdotca/kyogijo-stadiums";
const group = drawLayers({ sport: "nhl", id: "rink" }, [
{ kind: "points", name: "shots", data: [{ x: 169, y: 20.5, outcome: "goal", team: "home" }, { x: 150, y: 40, outcome: "shot", team: "home" }] },
]);
console.log(group.startsWith('<g class="ky-layers"'), group.includes("2 shots"));
// true true
type FlowLayer
interface FlowLayer extends LayerBase { kind: "flow"; data: readonly MoveDatum[]; /** The grid: a number of cells across the surface's longer side (square cells, 12 by default), `[across, down]`, or `{ x, y }` as for a heat map. */ bins?: number | readonly [number, number]; /** Leave out a cell with fewer movements than this. 2 by default. */ minCount?: number; /** The length of an arrow: `mean` (the default: in pro…
The average direction of the movements in each cell of a grid, as an arrow (a quiver plot).
type Formation
interface Formation { id: string; sport: FormationSport; /** The frame the positions are in: `opta` for soccer, `nhl-api`, `nba-stats`, `nfl-tracking`, `retrosheet`. */ frame: string; name: { en: string; ja: string }; /** What the formation is, in a sentence: the side of the ball, the strategy. */ about: { en: string; ja: string }; positions: readonly FormationPosition[]; /** Places beside the surface's play that a …
A formation: where each position stands. Points in the numbers of a registered frame, for a team that attacks the right end of the surface as it is drawn wide (a football formation: the offence going right, with the ball at midfield).
const FORMATION_IDS
FORMATION_IDS: readonly string[]
The ids of the formations, in the order of the table.
function formationById
formationById(id: string): Formation
A formation by id, or an error that lists the ids.
type FormationLayer
interface FormationLayer extends LayerBase { kind: "formation"; /** The id of a formation in `FORMATIONS` (`4-4-2`), or a formation of your own. */ formation: string | Formation; /** The team that colours the marks (`home`, `away`). */ team?: LayerTeam; /** Players for some or all of the positions. */ data?: readonly FormationPlayer[]; /** What is written in a mark: the `position`'s id (the default without players),…
A formation drawn on the surface: a labelled mark for each position, with the players on them when data has some.
type FormationPlayer
interface FormationPlayer extends MarkDatum { /** The id of the position the player stands on. */ position: string; number?: string | number; name?: string; }
A player to stand on a position.
type FormationPosition
interface FormationPosition { /** The position's id: `GK`, `LB`, `QB`. Unique within a formation. */ id: string; x: number; y: number; /** How big the mark of a lineup is here, against the others: 1 by default. A second line's marks are smaller. */ size?: number; }
A named place of a formation, in the numbers of the formation's frame (see Formation).
const FORMATIONS
FORMATIONS: Readonly<Record<string, Formation>>
The formations, by id.
function formationsOf
formationsOf: (sport: FormationSport) => Formation[]
The formations of one sport.
type FormationSport
type FormationSport = "soccer" | "nhl" | "nba" | "nfl" | "mlb" | "rugby" | "afl" | "cricket" | "volleyball" | "handball" | "waterpolo" | "fieldhockey" | "netball";
The sports that have formations.
type Grid
interface Grid { xEdges: number[]; yEdges: number[]; /** Row by row from the top: `bins[row * nx + column]`. */ bins: Bin[]; nx: number; ny: number; /** Samples that fell inside the grid, and the number that fell outside it. */ total: number; outside: number; }
A grid of bins.
const HEAT_RAMP_NAMES
HEAT_RAMP_NAMES: readonly HeatRampName[]
Names of the built-in ramps.
const HEAT_RAMPS
HEAT_RAMPS: Readonly<Record<HeatRampName, HeatRampDef>>
The built-in ramps. On a light page a sequential ramp runs from a pale colour to a dark one, because the more there is the more ink it takes; on a dark page it runs from near the ground to a bright one, because the more there is the more light it gives. A diverging ramp has its neutral middle at the ground's colour and its two ends at full strength.
type HeatBase
interface HeatBase extends LayerBase { data: readonly HeatDatum[]; /** What each cell or zone shows: `count` (the default), `sum`, `mean`, `median`, `max` or `min` of the marks' `value`, `percent` (a share of all the marks, 0 to 100), `rate` (the percent of the marks whose `outcome` is a success; see `success`) or a function `(values, { count, hits, total }) => number | null`. */ statistic?: HeatStatistic; /** The s…
What the heat layers take beyond a layer's places.
type HeatBins
interface HeatBins { /** A number of bins across, or a list of edges in the layer's coordinates. */ x?: number | readonly number[]; y?: number | readonly number[]; }
Bins on a grid: a number of bins, or the edges between them.
type HeatDatum
interface HeatDatum extends MarkDatum { x: number | null; y: number | null; }
A point to count: where it is, and optionally a number it carries (value: a distance, an expected-goals figure, a speed) and an outcome (made, goal) for the rate statistic.
type HeatLabels
interface HeatLabels { /** What to write, a line each: the `value`, the `name` of a zone, the `count` of marks in it, its `share` of all of them (a percent) or the `ratio` of hits to marks (`13/31`). The value by default. */ show?: readonly ("value" | "name" | "count" | "share" | "ratio")[]; /** Decimal places of the value. A whole number for a count, and one place for a percent below 10, by default. */ decimals?: n…
Where to write the number of a cell or zone, and which.
type HeatLegend
interface HeatLegend { /** Where it sits on the surface: `bottom` (the middle of the lower edge) by default, or a corner. A ballpark's default is its lower right, outside the foul lines. */ position?: "bottom" | "top" | "bottom-left" | "bottom-right" | "top-left" | "top-right"; /** The legend's heading. The name of the statistic by default. */ title?: string; /** About how many ticks. 5 by default. */ ticks?: number…
A colour bar with ticks, drawn on the surface.
type HeatmapLayer
interface HeatmapLayer extends HeatBase { kind: "heatmap"; /** The bins. A number is how many across the surface's longer side, with square cells; `[across, down]` for both; or `{ x, y }` each a count or edges. About 24 across by default. */ bins?: number | readonly [number, number] | HeatBins; /** Grid only part of the surface, in the layer's coordinates: the attacking half, say. The whole surface by default. */ ex…
A binned statistic on a grid laid over the surface (hockey_rink's heatmap, mplsoccer's bin_statistic with heatmap).
type HeatRamp
type HeatRamp = HeatRampName | readonly string[] | { light: readonly string[]; dark?: readonly string[] };
A ramp for a layer: the name of a built-in one, a list of colour stops (the same on a light and a dark page), or a light and a dark list. Stops are anything safeColour accepts.
type HeatRampName
type HeatRampName = "ember" | "ocean" | "mono" | "balance" | "tide";
The built-in ramps. The sequential ones go from the least to the most; the diverging ones from the lowest through a neutral middle to the highest.
type HeatStatistic
type HeatStatistic = StatisticName | Reducer;
A statistic: a name, or a function of a bin's values (the median is the median of them; a function gets them all).
function hexAt
hexAt(x: number, y: number, size: number, orientation: HexOrientation, ox?: number, oy?: number): [number, number]
The hexagon (axial q, r) that holds (x, y) on a grid of hexagons of circumradius size whose (0, 0) hexagon is centred at (ox, oy).
type HexBin
interface HexBin { q: number; r: number; cx: number; cy: number; bin: Bin; }
A hexagon with the bin it holds.
type HexbinLayer
interface HexbinLayer extends HeatBase { kind: "hexbin"; /** The distance from a hexagon's centre to its corner, in the layer's units. A twenty-eighth of the surface's length by default. */ size?: number; /** A corner up (`pointy`, the default) or an edge up (`flat`). */ orientation?: HexOrientation; }
A binned statistic on hexagons (hockey_rink's and mplsoccer's hexbin).
function hexBins
hexBins(samples: readonly Sample[], size: number, orientation: HexOrientation, origin: readonly [number, number], keepValues?: boolean): { cells: HexBin[]; total: number; }
Count samples into hexagons. The hexagons that hold at least one sample are returned, in the order of their rows (top to bottom, left to right).
function hexCentre
hexCentre(q: number, r: number, size: number, orientation: HexOrientation, ox?: number, oy?: number): [number, number]
The centre of hexagon (q, r).
function hexCorners
hexCorners(size: number, orientation: HexOrientation): [number, number][]
The six corners of a hexagon of circumradius size, as offsets from its centre, clockwise from the right (flat) or the lower right (pointy), with y down.
type HexOrientation
type HexOrientation = "pointy" | "flat";
How a hexagon sits: a corner up (pointy) or an edge up (flat).
type HullLayer
interface HullLayer extends PlayersBase { kind: "hull"; /** One hull for each team (`team`, the default) or one for all the players. */ by?: "team" | "all"; }
The convex hull of the players: the smallest convex shape that holds them, for each team.
const KYOGIJO_HEAT_STYLE
KYOGIJO_HEAT_STYLE: string
The rules of the heat layers (the ground under a heat map, its zones' and bands' outlines and the legend), kept apart so that a drawing without one does not carry them: a drawing that has a heat layer writes them in beside the layer, and KYOGIJO_STYLE has them for a page.
const KYOGIJO_TEAM_STYLE
KYOGIJO_TEAM_STYLE: string
The rules of the team layers (the cells, triangles and hulls, the roses of a sonar, the arrows of a flow field and the marks of a formation), kept apart like the heat layers' so that a drawing without one does not carry them: a drawing that has one writes them in beside the layer, and KYOGIJO_STYLE has them for a page.
type Layer
type Layer = PointsLayer | LinesLayer | ArrowsLayer | TextLayer | HeatmapLayer | HexbinLayer | ZonesLayer | ContourLayer | LegendLayer | NetworkLayer | FormationLayer | LineupLayer | VoronoiLayer | DelaunayLayer | HullLayer | FlowLayer | SonarLayer;
A layer of data on a surface.
type LayerBase
interface LayerBase { /** A name for the layer in ids and in the page; letters, digits and hyphens. */ id?: string; /** What the marks are, for the summary: `shots`, `passes`. */ name?: string; /** The accessible title of the layer. Made from the count and `name` when missing, such as "24 shots". */ title?: string; /** The accessible description. Made from the counts by outcome and team when missing. */ description?…
What every layer takes.
type LayerKind
type LayerKind = Layer["kind"];
The kinds of layer.
function layerTable
layerTable(layers: readonly Layer[], options?: TableOptions): string
An HTML table for each layer: the data the drawing shows, as text, for a screen reader or for a page that wants its numbers. The coordinates are the ones given (in the layer's frame and unit), and a caption says which. Hidden layers are in it too. Every cell is escaped.
Example
import { layerTable } from "@johnmorrisdotca/kyogijo-stadiums";
const html = layerTable([{ kind: "points", name: "shots", from: "nhl-api", data: [{ x: 69, y: 22, outcome: "goal", title: "Goal, 2nd period" }] }]);
console.log(html.includes("<th scope=\"col\">Outcome</th>"), html.includes("Goal, 2nd period"));
// true true
type LayerTeam
type LayerTeam = "home" | "away" | (string & {});
Which team a mark belongs to: home or away take the layer's team colours (--ky-layer-home, --ky-layer-away); any other text is a mark of no team.
type LegendLayer
interface LegendLayer extends Omit<LayerBase, "from" | "attacking" | "surfaceSize" | "anchors" | "limits"> { kind: "legend"; for?: string; ramp?: HeatRamp; domain?: readonly [number, number]; center?: number; steps?: number; position?: HeatLegend["position"]; ticks?: number; /** The opacity of the legend, 0 to 1. */ opacity?: number; /** Size and place the legend against this part of the surface, as `HeatLegend.regi…
A colour bar on its own: for another layer (for, the id of an earlier or later heat layer) or with a ramp and a domain of its own.
type LineDatum
interface LineDatum extends MarkDatum { x?: number | null; y?: number | null; x2?: number | null; y2?: number | null; /** A path through several points, `[x, y]` each, in place of `x`, `y`, `x2` and `y2`. */ points?: readonly (readonly [number, number])[]; /** How far the line bows, as a fraction of its length. Positive bows to the right of the way it goes as the surface is drawn wide. */ curve?: number; /** Make th…
A line or an arrow: from (x, y) to (x2, y2), or through points.
type LinesLayer
interface LinesLayer extends LayerBase { kind: "lines"; data: readonly LineDatum[]; style?: LineStyle; }
type LineStyle
interface LineStyle { /** The width of the stroke in the layer's units, or a scale from `value`. */ width?: number | Scale; scale?: number; color?: Paint; opacity?: number; /** `auto` (the default) dashes the lines of a hollow outcome. */ dash?: "auto" | "solid" | "dashed" | "dotted"; /** How far lines bow, as a fraction of their length. */ curve?: number; /** Draw lines as waves, for a carry: `true` for the usual w…
How lines and arrows look.
const LINEUP_CODES
LINEUP_CODES: Readonly<Record<FormationSport, Readonly<Record<string, readonly string[]>>>>
The positions a short code may stand for, by sport, in the order a player takes them: a code that is also an id of the formation is that place first.
type LineupLayer
interface LineupLayer extends LayerBase { kind: "lineup"; /** `home` (the default) or `away`: the team's colour, and the end it attacks (the right for `home`, the left for `away`) unless `attacking` says. A football lineup's `side` is only the colour: the offence goes right unless `attacking` says, and a defence faces it. Baseball's fielders do not turn. */ side?: "home" | "away"; /** The id of a formation in `FORMA…
A team's lineup drawn on the surface: its players placed by position code in a named formation, as discs or jerseys, each with its number in the mark and its name under it. Two teams are two layers, one for each side. A lineup is not cut to the surface's outline (a fielder at the foul line keeps his whole jersey) unless clip is "surface".
type LineupPlayer
interface LineupPlayer extends MarkDatum { /** The position's code: `GK`, `SS`, `C`, `QB`, `9`, `P4` (a volleyball court's zone). The formation's own ids, and the usual short ones (`CB` for a centre-back of either side, `D` for a defenceman, `OF` for an outfielder), as `LINEUP_CODES` lists. */ pos: string | number; name?: string; number?: string | number; /** A flag or crest for a small badge on the mark: an SVG as …
A player of a lineup, placed by a position's code: nothing else about where he stands is needed.
type MarkDatum
interface MarkDatum { /** Your id for the mark: written on it as `data-mark-id`, so that a listener can link it to a row of your table. The mark's index is written when there is none. */ id?: string | number; /** The tooltip, and what a screen reader reads for the mark. */ title?: string; /** `home`, `away` or another team. */ team?: LayerTeam; /** What happened, as a word of your own (`goal`, `miss`, `complete`). T…
What every mark can carry.
type MarkShape
type MarkShape = "circle" | "square" | "triangle" | "diamond" | "cross" | "x" | "star";
The shapes a point can be drawn as. A team's logo is logo.
function massThresholds
massThresholds(d: Density, masses: readonly number[]): number[]
The densities that bound the smallest regions holding the given shares of the mass (the highest-density regions), for a density on a grid: masses of 0.5 gives the density above which half of the mass lies.
function median
median(values: readonly number[]): number
The median of a list that is not empty.
type MoveDatum
interface MoveDatum extends MarkDatum { x: number | null; y: number | null; x2?: number | null; y2?: number | null; dx?: number | null; dy?: number | null; /** The mover, for a sonar of each player. */ id?: string | number; name?: string; number?: string | number; }
A movement: from (x, y) to (x2, y2), or the vector (dx, dy) from (x, y).
type Named
interface Named { en: string; ja: string; }
A name in both languages.
function neighbours
neighbours(t: Triangulation): number[][]
For each distinct point of a triangulation, the points it shares a triangle edge with, in increasing order.
type NetworkLayer
interface NetworkLayer extends LayerBase { kind: "network"; data: readonly PassDatum[]; /** Places of your own for some players, over the averages. */ nodes?: readonly NetworkNode[]; /** Leave out links of fewer passes than this. 1 by default. */ minPasses?: number; /** Draw a link for each direction, bowed apart and with a head, and not one for the pair. */ directed?: boolean; /** The width of a node (a share of th…
A pass network: a node for each player at the average place of the passes he made and received, sized by touches, and a link for each pair sized by passes.
type NetworkNode
interface NetworkNode { id: string | number; x: number; y: number; team?: LayerTeam; name?: string; number?: string | number; }
A player of a pass network whose place is given and not worked out from the passes.
function niceTicks
niceTicks(low: number, high: number, count?: number): number[]
"Nice" tick values: about count of them, at 1, 2, 2.5 or 5 times a power of ten, covering [low, high] within it.
const OUTCOMES
OUTCOMES: Readonly<Record<string, OutcomeStyle>>
How the standard outcomes look. A word that is not here draws as a filled mark; style.outcomes of a layer adds words and changes these. A hollow point is drawn open and a hollow line is dashed, so that an outcome is never told by colour alone.
type OutcomeStyle
interface OutcomeStyle { /** Draw a point hollow and a line dashed. */ hollow?: boolean; /** A shape for this outcome, over the layer's. */ shape?: MarkShape; /** A multiple of the mark's size: 1.4 makes a goal stand out. */ scale?: number; }
How an outcome looks: a hollow mark (or a dashed line) is a miss, a failed pass or a shot that did not score.
type Outline
interface Outline { /** The path of the playing surface's edge: the boards for a rink, the lines of a court, the fence and the foul lines for a ballpark. */ d: string; box: { x: number; y: number; w: number; h: number }; /** True when a point (in the drawing's frame, feet) is on the surface, or on its edge. */ contains(x: number, y: number): boolean; }
A surface's outline as a path, with the box round it.
function outlineOf
outlineOf(o: Pick<SurfaceOptions, "sport" | "park" | "fence" | "units" | "pitch" | "league" | "year" | "sheet" | "net"> & Partial<Pick<SurfaceOptions, "field" | "detail" | "pool" | "athletics" | "skating" | "budo" | "dojo" | "arena">>): Outline
The outline of the surface the options draw.
type Paint
type Paint = | string | { by: "team"; home?: string; away?: string; other?: string } | { by: "value"; stops: readonly string[]; domain?: readonly [number, number]; missing?: string } | { by: "outcome"; colors: Readonly<Record<string, string>>; other?: string };
A colour, or a rule for choosing one. A text is any colour safeColour accepts. by: "team" uses the home and away colours of the layer, by: "value" runs through stops as a datum's value goes from the least to the greatest of the domain, and by: "outcome" looks the datum's outcome up in colors. A colour a datum carries itself (color) always wins.
type PassDatum
interface PassDatum extends MarkDatum { /** The id of the passer and of the receiver (a number or a name; the same id is the same player). */ from: string | number; to: string | number; /** Where the pass was made from, and where it was received. */ x?: number | null; y?: number | null; x2?: number | null; y2?: number | null; /** The names for the labels and the table, by id. The last one given for an id is used. */…
A pass: who passed to whom, from where to where. The places are the passer's and, if given, the receiver's.
type PlayerDatum
interface PlayerDatum extends MarkDatum { x: number | null; y: number | null; /** The player's id, name and shirt number, for a label and for the table. */ id?: string | number; name?: string; number?: string | number; }
A player at a place. team (home, away or another) is what colours the player's cell, triangles and hull.
type PointDatum
interface PointDatum extends MarkDatum { x: number | null; y: number | null; /** A shape for this mark alone, or `logo` for the logo of its team (or its own `logo`). */ shape?: MarkShape | "logo"; /** The width of the mark, in the layer's units. */ size?: number; /** The address of a logo, for the shape `logo`. */ logo?: string; }
A point to mark.
type PointsLayer
interface PointsLayer extends LayerBase { kind: "points"; data: readonly PointDatum[]; style?: PointStyle; }
type PointStyle
interface PointStyle { shape?: MarkShape | "logo"; /** The width of a mark in the layer's units, or a scale from `value`. A default that follows the size of the surface. */ size?: number | Scale; /** A multiple of the default size. */ scale?: number; /** The colour of the fill. The home and away colours for marks that carry a team, the layer colour for the rest. */ fill?: Paint; /** The colour of the edge. A pale or…
How points look.
function polygonArea
polygonArea(polygon: readonly Pt[]): number
The area of a polygon given by its corners (any orientation); 0 for fewer than three.
function polygonCentroid
polygonCentroid(polygon: readonly Pt[]): Pt | undefined
The centre of mass of a polygon's area, or the mean of its corners when it has none (a point, a line). undefined for no corners.
const POSITION_NAMES
POSITION_NAMES: Readonly<Record<FormationSport, Readonly<Record<string, Named>>>>
The names of the positions of each sport, by the id a formation uses for them.
function positionName
positionName(sport: FormationSport, id: string, language: "en" | "ja"): string
The name of a position in a language: the sport's name for its id, or the id itself when the sport has none.
type Pt
type Pt = readonly [number, number];
A place, [x, y].
function rampColour
rampColour(stops: readonly string[], t: number): string | undefined
A colour a fraction t (0 to 1) of the way through stops, as a hex colour, or the nearest stop when one cannot be read without a browser (var(--x), a name that is not a common one). Stops that are not colours are ignored; with none left, undefined.
function reduceBin
reduceBin(statistic: StatisticName | Reducer, bin: Bin, total: number): number | null
The value of a bin under a statistic, or null when it has none (an empty bin; a mean of samples that carry no value).
type Reducer
type Reducer = (values: readonly number[], info: BinInfo) => number | null;
A custom statistic: the finite values of a bin's samples (an empty list when none had one), and the bin's counts. Return null for a bin that has no value.
type RenderedLayers
interface RenderedLayers { svg: string; summaries: string[]; }
The layers, drawn, and a sentence for each.
function renderLayers
renderLayers(o: SurfaceOptions | ScoreOptions, layers: readonly Layer[] | undefined, turned?: boolean, range?: Box, upright?: number, zone?: Env["zone"]): RenderedLayers
The layers of a drawing as markup, and a sentence for each. turned says whether the surface group is turned a quarter.
function resolveRamp
resolveRamp(ramp: HeatRamp | undefined, fallback?: HeatRampName): ResolvedRamp
The ramp a layer asks for; ember when it asks for none (fallback for a diverging statistic).
type Sample
interface Sample { x: number; y: number; value?: number | null; hit?: boolean; /** Which input it was, for a caller who wants its tooltip. */ index?: number; }
A point to count: where it is, a number it carries (optional) and whether it counts as a success (a goal, a made shot).
type Scale
interface Scale { domain?: readonly [number, number]; range: readonly [number, number]; /** For a size: scale the area and not the width, so that twice the value covers twice the ground. On by default. */ area?: boolean; }
A number mapped to another range: domain is the values (the data's least and greatest when missing) and range what they become.
function scottBandwidth
scottBandwidth(xs: readonly number[], ys: readonly number[], weights?: readonly number[]): [number, number]
Scott's rule for a density in two dimensions: each axis's bandwidth is its standard deviation times n^(-1/6), with n the number of samples (the effective number, when they have weights). In the same units as the samples. Silverman's rule is the same number in two dimensions.
type SonarLayer
interface SonarLayer extends LayerBase { kind: "sonar"; data: readonly MoveDatum[]; /** What a rose is of: `all` (one rose, at the middle of the movements' starts; the default), `player` (one for each `id`, at the average start of his), `grid` (one for each cell of a grid) or `zone` (one for each zone of `zones`). */ by?: "all" | "player" | "grid" | "zone"; /** How many directions a rose is cut into. 12 by default. …
A rose for each group of movements: how many go in each direction, or how long they are on average.
type StatisticName
type StatisticName = "count" | "sum" | "mean" | "median" | "percent" | "max" | "min" | "rate";
The statistics of a bin. percent is each bin's share of all the samples (0 to 100); rate is the share of a bin's samples that are hits (0 to 100).
type TableOptions
interface TableOptions { language?: "en" | "ja"; /** The most rows to write for one layer. 500 by default; the caption says when rows are left out. */ maxRows?: number; /** A class for each table. `ky-table` by default. */ className?: string; /** The drawing's options (at least `sport`, and `park`, `pitch`, `units` and `language` where they apply): needed for the tables of heat maps, hexagon maps, zone charts and co…
What layerTable takes.
type TextDatum
interface TextDatum extends MarkDatum { x: number | null; y: number | null; text: string | number; /** The height of the letters, in the layer's units. */ size?: number; /** Turn the text this many degrees, clockwise, as the eye sees it. The text stays upright when the surface is turned. */ rotate?: number; anchor?: "start" | "middle" | "end"; }
A word or a number to write.
type TextLayer
interface TextLayer extends LayerBase { kind: "text"; data: readonly TextDatum[]; style?: TextStyle; }
type TextStyle
interface TextStyle { /** The height of the letters in the layer's units. A default that follows the size of the surface. */ size?: number; color?: Paint; weight?: number; anchor?: "start" | "middle" | "end"; /** Outline the letters in the halo colour (`--ky-halo`) so that they read on any ground. On by default. */ halo?: boolean; opacity?: number; }
How text looks.
type Triangulation
interface Triangulation { /** The distinct points, in the order they were first given. */ points: Pt[]; /** Three indices into `points` for each triangle, flat: `triangles[3 * k]`, `[3 * k + 1]`, `[3 * k + 2]`. Empty for fewer than three points and for points all on a line. */ triangles: number[]; /** For each input point, the index in `points` of the point it is (a repeated point is the first one). */ of: number[];…
A triangulation: the distinct points, the triangles as triples of indices into them (counter-clockwise with y up), and where each input point went.
function triangulationEdges
triangulationEdges(t: Triangulation): [number, number][]
The edges of a triangulation, each once, as pairs of indices into its points with the smaller first, in order.
function uniformEdges
uniformEdges(a: number, b: number, n: number): number[]
n equal steps from a to b, as the n + 1 edges that bound them.
function voronoiCells
voronoiCells(points: readonly Pt[], box: { x: number; y: number; w: number; h: number; }): Pt[][]
The Voronoi cells of some points inside a box: for each input point, the corners of the part of the box nearer to it than to any other point, in order. The cells tile the box. A point given twice has the cell on its first appearance and an empty one on its second. With one point the cell is the box; with points all on a line the cells are strips. The neighbours that cut a cell are the triangulation's, so a cell is made from a handful of cuts and not from every other point.
Example
import { voronoiCells } from "@johnmorrisdotca/kyogijo-stadiums/layers";
const cells = voronoiCells([[2, 5], [8, 5]], { x: 0, y: 0, w: 10, h: 10 });
console.log(cells[0].length, cells[1].map((p) => p.join(",")).join(" "));
// 4 5,0 10,0 10,10 5,10
type VoronoiLayer
interface VoronoiLayer extends PlayersBase { kind: "voronoi"; }
The part of the surface nearest each player, coloured by team: who controls the space (the Voronoi diagram of the players, clipped to the surface).
const ZONE_SET_IDS
ZONE_SET_IDS: readonly ZoneSetId[]
const ZONE_SETS
ZONE_SETS: Readonly<Record<ZoneSetId, { sports: readonly Sport[]; title: string; source: string; }>>
Every zone set, with the sports it is for, the source of its definition and its title.
type ZoneContext
interface ZoneContext { o: Pick<SurfaceOptions, "sport" | "pitch" | "units"> & Partial<Pick<SurfaceOptions, "league" | "net" | "field" | "pool" | "athletics" | "skating" | "budo" | "dojo">>; outline: Outline; /** The way the team attacks as the surface is drawn wide: names the sides and counts the bands from the team's own end. `right` by default. */ direction: "left" | "right"; /** `left` or `right` for one end of …
What a zone set needs to know about the drawing and the layer.
type ZoneSet
interface ZoneSet { id: ZoneSetId; zones: ZoneShape[]; /** The index of the zone a point belongs to, or -1 when it is in none. */ which(x: number, y: number): number; }
A set of zones. Where zones overlap, the later one is on top, and a point belongs to the last zone that has it.
type ZoneSetId
type ZoneSetId = "field-thirds" | "cricket-ground" | "soccer-positional" | "soccer-thirds" | "soccer-channels" | "soccer-18" | "nba-shot" | "nhl-slot" | "nhl-home-plate" | "baseball-spray" | "baseball-retrosheet" | "football-pass" | "athletics-track" | "skating-track" | "budo-areas" | "curling-house" | "net-court" | "wall-court" | "roundnet-rings" | "pool-lanes" | "water-polo-areas" | "pool-thirds";
The zone sets.
type ZoneShape
interface ZoneShape { /** A name for the zone in the data (`restricted-area`, `wing-left-3`), the same in every language. */ id: string; /** The name to show, in the drawing's language. */ name: string; /** The zone's outline as a path, in the drawing's frame (feet). */ d: string; /** Where its label goes. */ label: Pt; /** About how wide and how high a label can be without leaving the zone, in feet. */ room?: Pt; /…
One zone: its shape on the surface and whether a point lies in it.
type ZonesLayer
interface ZonesLayer extends HeatBase { kind: "zones"; /** The set of zones: `soccer-positional`, `soccer-thirds`, `soccer-channels`, `soccer-18`, `nba-shot`, `nhl-slot`, `nhl-home-plate`, `baseball-spray`, `baseball-retrosheet` or `football-pass`. */ zones: ZoneSetId; /** The way the team attacks as the surface is drawn wide: names the sides and counts the soccer bands from the team's own end. `right` by default. *…
A statistic by named zone of the surface.
@johnmorrisdotca/kyogijo-stadiums/leagues
AFL_GROUND AFL_GROUNDS AFL_LEAGUES AflFigures AflGround AflLeague aflOf ATHLETICS_LEAGUES AthleticsFigures AthleticsLeague BADMINTON_LEAGUES BadmintonFigures BadmintonLeague BaseballLeague BasketballLeague BWF_BADMINTON chooseLeague CourtFigures CourtMarks courtOf CRICKET_LEAGUES CricketFigures CricketLeague cricketOf CURLING_CANADA_SHEET CURLING_LEAGUES CurlingLeague DiamondFigures diamondOf Family FAMILY_OF FIELD_HOCKEY_LEAGUES FieldHockeyFigures FieldHockeyLeague fieldHockeyOf fieldOf FIH_PITCH FIP_PADEL FITEQ_TEQBALL FIVB_BEACH FIVB_INDOOR fixed FootballLeague FreeZone FreeZones GAA_FOOTBALL_FIELD GAA_HURLING_FIELD GAELIC_LEAGUES GaelicFigures GaelicLeague gaelicOf HANDBALL_LEAGUES HandballFigures HandballLeague handballOf hasHistory HockeyLeague ICC_MEN_GROUND ICC_WOMEN_GROUND IHF_COURT IRF_RACQUETBALL IRF_ROUNDNET IRL_FIELD ISTAF_SEPAK_TAKRAW ITF_TENNIS ITTF_TABLE LACROSSE_LEAGUES LacrosseFigures LacrosseLeague lacrosseOf League LEAGUE_SOURCES leagueAt LeagueAt leagueAtOf leagueById LeagueChange leagueChanges leagueFigures leagueIds LEAGUES leagueSeason leagueSize LeagueSource LeagueSpan MCC_GROUND MLB_DIAMOND Named NBA_COURT NCAA_MEN_FIELD NCAA_WOMEN_FIELD NETBALL_LEAGUES NetballFigures NetballLeague NetFigures NetLeague netOf NetSport NHL_RINK NLL_FLOOR NRL_FIELD PADEL_LEAGUES PadelFigures PadelLeague PICKLEBALL_LEAGUES PickleballFigures PickleballLeague PLL_FIELD RACQUETBALL_LEAGUES RacquetballFigures RacquetballLeague RinkFigures rinkOf ROUNDNET_LEAGUES RoundnetFigures RoundnetLeague RUGBY_LEAGUES RugbyFigures RugbyLeague rugbyOf SEPAK_TAKRAW_LEAGUES SepakTakrawFigures SepakTakrawLeague SheetFigures sheetOf span Span SQUASH_LEAGUES SquashFigures SquashLeague TABLE_TENNIS_LEAGUES TableTennisFigures TableTennisLeague TENNIS_LEAGUES TennisFigures TennisLeague TEQBALL_LEAGUES TeqballFigures TeqballLeague USAP_PICKLEBALL VARIANTS VOLLEYBALL_LEAGUES VolleyballFigures VolleyballLeague WA_SHORT_STAGGER_TABLE WA_SHORT_TRACK WA_STAGGER_TABLE WA_STANDARD_TRACK WCF_SHEET WN_NETBALL WORLD_BOX_FLOOR WORLD_MEN_FIELD WORLD_RUGBY_FIELD WORLD_WOMEN_FIELD WPV_SITTING WSF_SQUASH WSF_SQUASH_DOUBLES WSF_SQUASH_WIDE
const AFL_GROUND
AFL_GROUND: AflFigures
Law 3 of the Laws of Australian Football 2026: oval, 135 to 185 m long and 110 to 155 m wide; goal posts 6.4 m apart and behind posts 6.4 m on each side of them, in a line (3.3.1); the goal square 9 m deep from each goal post (3.4); the centre square 50 by 50 m, the Centre Circle 3 m across and the Ten Metre Circle 10 m (3.5); a Fifty Metre Arc at each end, 50 m from the middle of the goal line (the definition, and Diagram 1). The length is measured as the Playing Surface is defined, inside the Boundary Line, Goal Line and Behind Line, so from goal line to goal line. The size drawn is the MCG's (160 by 141 m, its venue page). The Laws print no line width: 0.1 m is drawn.
const AFL_GROUNDS
AFL_GROUNDS: readonly AflGround[]
The grounds whose length and width the AFL's venue pages print (read 2026-10-13), each within the Laws' range. The AFL's page for Adelaide Oval prints 190 by 125 m, a length beyond the 185 m the Laws allow, so that ground is not here.
const AFL_LEAGUES
AFL_LEAGUES: readonly AflLeague[]
The AFL league: the Laws' ground.
type AflFigures
interface AflFigures { /** The Playing Surface's length (goal line to goal line) and width, as the Laws allow; the size drawn is the MCG's. */ length: Span; width: Span; /** The goal posts' distance apart, and the behind posts' distance from each goal post on either side. */ goalPosts: number; behindPosts: number; /** The goal square: the depth of the two lines drawn at right angles to the goal line from each goal p…
The figures of the ground, in the unit of the table they are in.
type AflGround
interface AflGround { id: string; name: { en: string; ja: string }; /** Metres, as the venue's page prints them: length by width. */ length: number; width: number; /** The page it was read on (a key of `LEAGUE_SOURCES`). */ source: string; /** What else is published, when it disagrees. */ note?: string; }
A ground the AFL publishes the size of.
type AflLeague
type AflLeague = LeagueBase<"afl", AflFigures>;
The league with the Laws' ground.
function aflOf
aflOf: (league: AflLeague) => AflSpec
The Australian football ground, in feet.
const ATHLETICS_LEAGUES
ATHLETICS_LEAGUES: readonly AthleticsLeague[]
The athletics leagues: the outdoor track (the sport's own) and the covered one.
type AthleticsFigures
interface AthleticsFigures { /** The length of each straight (the distance between the centres of the semicircles, for the outdoor track's). */ straight: number; /** The radius of each bend at the inside of the track, where the kerb is. */ radius: number; /** The width of a lane, the line on its right included. */ lane: number; /** The least, the most and the drawn number of lanes of the oval. */ lanes: { min: numbe…
The figures of an oval track, in metres.
type AthleticsLeague
type AthleticsLeague = LeagueBase<"athletics", AthleticsFigures>;
A league with an athletics track of its own.
const BADMINTON_LEAGUES
BADMINTON_LEAGUES: readonly BadmintonLeague[]
The badminton leagues: the BWF's.
type BadmintonFigures
interface BadmintonFigures { /** Back boundary line to back boundary line, to the outside of the lines. */ length: number; /** The doubles court's width. The singles sidelines are inside it. */ width: number; /** The lines are 40 mm wide. */ lineWidth: number; /** A singles side line's outside edge is this far inside the doubles side line's. */ singlesInset: number; /** The doubles long service line: its outside edg…
A badminton court, from Law 1 of the BWF's Laws of Badminton and its Diagram A. Metres.
type BadmintonLeague
type BadmintonLeague = LeagueBase<"badminton", BadmintonFigures>;
type BaseballLeague
type BaseballLeague = LeagueBase<"baseball", DiamondFigures> & { game: "baseball" | "softball" };
A league with a diamond of its own.
type BasketballLeague
type BasketballLeague = LeagueBase<"basketball", CourtFigures>;
A league with a basketball court of its own.
const BWF_BADMINTON
BWF_BADMINTON: BadmintonFigures
The BWF's court, from Law 1 of the Laws of Badminton (as amended 26 April 2025) and its Diagram A, in metres: 13.40 by 6.10 m, lines 40 mm wide; the singles side lines 460 mm inside the doubles side lines (so 5.18 m apart, outside to outside); the short service lines 1.98 m from the net; the doubles long service lines 760 mm inside the back boundary lines; the net 1.524 m high at the centre and 1.55 m over the doubles side lines, 760 mm deep and at least 6.1 m wide; the posts 1.55 m high, on the doubles side lines. The space round the court is from the BWF's Specifications for International Standard Facilities (5.3.4, 2.1.3 and 2.2.3 of the Statutes): at least 2 m clear behind the baselines and 1.5 m from the side lines.
function chooseLeague
chooseLeague(o: Pick<SurfaceOptions, "sport" | "league"> & Partial<Pick<SurfaceOptions, "budo">>): { sport: Sport; league: League | undefined; }
Which league the options ask for: the league, and the sport it is drawn as. No league is the sport's own. A league the sport's own (nba for nba) is the sport as it is drawn without one; one of the football leagues that is a sport of its own (cfl) is that sport. A league of another family, or one that does not exist, is an error that says what to use.
Example
import { chooseLeague } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
console.log(chooseLeague({ sport: "nba", league: "fiba" }).league?.name.en, chooseLeague({ sport: "nfl", league: "cfl" }).sport);
// FIBA basketball court cfl
type CourtFigures
interface CourtFigures { /** Baseline to baseline, inside the lines. */ length: number; /** Sideline to sideline, inside the lines. */ width: number; /** The free-throw lane (restricted area), side to side. */ laneWidth: number; /** A lane that is wider at the baseline than at the free-throw line (a trapezoid): its width at the baseline. */ laneEndWidth?: number; /** The free-throw line, from the baseline. */ freeTh…
The figures of a basketball court. Lengths, in the unit of the table they are in.
type CourtMarks
interface CourtMarks { /** The marks that divide the free-throw lane, from the baseline. The first is the block. */ lane: number[]; /** The lower defensive box's marks: from the lane, from the baseline, and how long; or none. */ box: { fromLane: number; fromBaseline: number; length: number } | null; /** The marks 28 feet from the baseline on the sidelines: where, and how long. */ sideline: { fromBaseline: number; le…
The small marks the NBA's court diagram has along the lane and the sidelines, drawn in the full detail. Lengths.
function courtOf
courtOf: (league: BasketballLeague, year?: number) => CourtSpec
A basketball court of a league in a season, in feet.
const CRICKET_LEAGUES
CRICKET_LEAGUES: readonly CricketLeague[]
The cricket leagues: the ICC men's conditions first (the ground with the 30-yard circle), then the women's and the Laws.
type CricketFigures
interface CricketFigures { /** The pitch: its length (the distance between the bowling creases, which are its ends) and its width (5 feet either side of the line of the middle stumps). */ pitchLength: number; pitchWidth: number; /** The bowling crease's length; the popping crease's distance in front of it; how far the popping crease is marked either side of the line of the middle stumps (the creases are unlimited in…
The figures of the ground, in the unit of the table they are in (yards).
type CricketLeague
type CricketLeague = LeagueBase<"cricket", CricketFigures>;
A league with a cricket ground of its own.
function cricketOf
cricketOf: (league: CricketLeague) => CricketSpec
A cricket ground of a league, in feet.
const CURLING_CANADA_SHEET
CURLING_CANADA_SHEET: SheetFigures
Curling Canada's sheet, from Rule 3 of the Rules of Curling for General Play (September 2022 to August 2026), in feet as it prints them: 146 to 150 feet from backboard to backboard and 14 ft 2 in to 15 ft 7 in wide; 114 feet from tee to tee; the back line 6 feet from the tee; the hog line's inside edge 21 feet from it; the circles of 6, 4 and 2 feet and a button of at least 6 inches; the centre line 12 feet beyond each tee and the hacks' back edges there, each at most 8 inches long and its inside edge at most 3 inches from the centre line. The book prints no hack line and no courtesy line. Its hack width is not printed; World Curling's 6 inches is drawn.
const CURLING_LEAGUES
CURLING_LEAGUES: readonly CurlingLeague[]
The curling leagues, World Curling's first.
type CurlingLeague
type CurlingLeague = LeagueBase<"curling", SheetFigures>;
A league with a curling sheet of its own.
type DiamondFigures
interface DiamondFigures { /** The distance between bases (the side of the square). */ base: number; /** The side of a base. */ baseSize: number; /** The front of the pitcher's plate, from the back point of home plate. */ pitcher: number; /** The pitcher's plate: how long (across) and how deep. */ pitchersPlate: { width: number; depth: number }; /** The mound's radius, or a softball pitcher's circle's. */ moundRadiu…
The figures of a diamond. Lengths, in the unit of the table they are in.
function diamondOf
diamondOf: (league: BaseballLeague, year?: number) => DiamondSpec
A diamond of a league in a season, in feet.
type Family
type Family = "basketball" | "hockey" | "football" | "baseball" | "curling" | "tennis" | "volleyball" | "badminton" | "pickleball" | "tabletennis" | "padel" | "squash" | "racquetball" | "sepaktakraw" | "teqball" | "roundnet" | "netball" | "lacrosse" | "rugby" | "afl" | "gaelic" | "cricket" | "fieldhockey" | "handball" | "athletics" | "skating" | "judo" | "karate" | "kendo" | "sumo" | "kyudo" | "dojo" | "mma" | "boxi…
The families of surface a league is a variant of.
const FAMILY_OF
FAMILY_OF: Readonly<Record<Sport, Family | undefined>>
The family of surface each sport draws; soccer's variants are its pitches (pitch), not leagues.
const FIELD_HOCKEY_LEAGUES
FIELD_HOCKEY_LEAGUES: readonly FieldHockeyLeague[]
The field hockey leagues.
type FieldHockeyFigures
interface FieldHockeyFigures { length: Span; width: Span; /** The width of the lines. */ lineWidth: number; /** The distance from the back-line to the 22.90 m lines (the 23-metre lines), edge to edge. */ twentyThree: number; /** The goal-posts' inside distance, the height under the crossbar, and the net's depth at the ground (the least the rules allow). */ goalWidth: number; goalHeight: number; goalDepth: number; /*…
The figures of the pitch, in the unit of the table they are in.
type FieldHockeyLeague
type FieldHockeyLeague = LeagueBase<"fieldhockey", FieldHockeyFigures>;
A league with a hockey pitch of its own.
function fieldHockeyOf
fieldHockeyOf: (league: FieldHockeyLeague) => FieldHockeySpec
A field hockey pitch, in feet.
function fieldOf
fieldOf: (league: FootballLeague, year?: number) => FootballSpec
A football field of a league in a season: the spec, in feet.
const FIH_PITCH
FIH_PITCH: FieldHockeyFigures
The FIH's pitch, from the Rules of Hockey (effective 1 March 2026), Field and Equipment Specifications 1.1 to 1.8: 91.40 by 55.00 m; lines 75 mm; the 22.90 m lines (1.3e); the circle (1.4): a 3.66 m line whose outside edge is 14.63 m from the back-line, continued by quarter-circles centred on the inside front corners of the posts; the broken line 5 m outside it, solid sections of 300 mm and gaps of 3 m (1.4d); the penalty spot 150 mm across, its centre 6.40 m from the inner edge of the goal-line (Rule 1; 6.475 m from the outer edge, 1.3i); the goal 3.66 m between the posts and 2.14 m under the crossbar (1.5d), its net at least 1.20 m deep at the ground (1.5e); marks of 300 mm outside the pitch at 5 and 10 m from the goal-posts (1.3g); flag-posts of 1.20 to 1.50 m (1.8).
const FIP_PADEL
FIP_PADEL: PadelFigures
The FIP's padel court, from "The court" (dimensions, net, enclosures) in the Rules of Padel (review of application 1 January 2026), in metres: 10 by 20 m inside the walls; the service lines 6.95 m from the net on either side, the central service line between the net and each, extending at least 20 cm beyond it; lines 5 cm wide; the net 10 m long, 0.88 m high at the centre and 0.92 m at the ends, on posts at most 1.05 m high whose outer side is the side limit of the court; the court enclosed, the end walls 4 m high (3 m of wall and 1 m of metal fence) and each side wall, at both ends, 4 m long and 3 m high with metal fence between.
const FITEQ_TEQBALL
FITEQ_TEQBALL: TeqballFigures
The FITEQ's teqball court and table, from sections 1 and 2 of the Official Rules and Regulations of Teqball (2026), in metres: a table 3,000 mm long and 1,500 mm wide (1,700 mm with the net), 900 mm high with the net; a net 1,700 mm wide, 20 mm thick and 140 mm high; the table in the exact middle of a court of at least 12 m (the sides parallel to the net) by 16 m, the net parallel to the shorter sides; the halfway line across the middle, and a service line on each side 3.5 m from the middle of the table, each 20 to 50 mm wide; court surrounds 500 to 1,500 mm high.
const FIVB_BEACH
FIVB_BEACH: VolleyballFigures
The FIVB's beach court, from Rules 1 and 2 of the Official Beach Volleyball Rules 2025-2028, in metres: 16 by 8 m inside a free zone of at least 3 m (at least 5 m in the FIVB's competitions); lines 5 cm wide inside the dimensions and no centre line; the service zone 8 m wide; the net 8.5 m long and 1 m wide, at the same heights; the posts 0.70 to 1.00 m outside the side lines, 1 m in the FIVB's competitions.
const FIVB_INDOOR
FIVB_INDOOR: VolleyballFigures
The FIVB's indoor court, from Rules 1 and 2 of the Official Volleyball Rules 2025-2028, in metres as it prints them: 18 by 9 m inside a free zone of at least 3 m (5 m beside the side lines and 6.5 m behind the end lines in the FIVB's competitions); lines 5 cm wide inside the dimensions; the attack line's rear edge 3 m from the axis of the centre line and, in the FIVB's competitions, extended by five 15 cm lines 20 cm apart to 1.75 m; the service zone 9 m wide, limited by two 15 cm lines 20 cm behind the end line; the net 1 m wide and 9.50 to 10 m long, 2.43 m (men) or 2.24 m (women) high; each antenna 1.80 m long and 10 mm across, at the outer edge of a side band; the posts 0.50 to 1.00 m outside the side lines, 1 m in the FIVB's competitions.
function fixed
fixed: (value: number) => Span
A size the rules fix: a range of one.
type FreeZone
type FreeZone = { side: number; end: number } | null;
The ground round a court that a rulebook gives a figure for: beside the sidelines and behind the end lines. null when it gives none.
type FreeZones
interface FreeZones { official: FreeZone; least: FreeZone; }
The two figures a rulebook can give for the ground round its court: what it asks of its own competitions, and the least it allows or recommends.
const GAA_HURLING_FIELD
GAA_HURLING_FIELD: GaelicFigures
The field for hurling, the same field: the 65 m lines (marked "Hurling") and no football arc or penalty point.
const GAELIC_LEAGUES
GAELIC_LEAGUES: readonly GaelicLeague[]
The Gaelic leagues, football first.
type GaelicFigures
interface GaelicFigures { /** `football` or `hurling`. */ code: "football" | "hurling"; /** End line to end line, and across; the size drawn is the greatest. */ length: Span; width: Span; /** The lines across the field, in metres from each end line: 13, 20, 45 and, for hurling, 65. */ lines: number[]; /** The posts' distance apart and the crossbar's height above the ground. */ postsApart: number; crossbar: number; /…
The figures of the field, in the unit of the table they are in. null is what a code does not have.
type GaelicLeague
type GaelicLeague = LeagueBase<"gaelic", GaelicFigures>;
A league with a Gaelic field of its own.
function gaelicOf
gaelicOf: (league: GaelicLeague) => GaelicSpec
A Gaelic games field of a league (football or hurling), in feet.
const HANDBALL_LEAGUES
HANDBALL_LEAGUES: readonly HandballLeague[]
The handball leagues.
type HandballFigures
interface HandballFigures { length: Span; width: Span; /** The goal: inside width and height, and the depth of its net behind the goal line (at the ground). */ goalWidth: number; goalHeight: number; goalDepth: number; /** The goal-area line (6 m): its straight part's length, and its distance from the rear edge of the goal line to its front edge; the arcs' radius is that distance. */ areaLine: number; areaDistance: n…
The figures of the court, in the unit of the table they are in.
type HandballLeague
type HandballLeague = LeagueBase<"handball", HandballFigures>;
A league with a handball court of its own.
function handballOf
handballOf: (league: HandballLeague) => HandballSpec
A handball court, in feet.
function hasHistory
hasHistory: (league: League | undefined) => boolean
True when a league has markings a source dates, so that year changes its drawing.
type HockeyLeague
type HockeyLeague = LeagueBase<"hockey", RinkFigures>;
A league with an ice rink of its own.
const ICC_MEN_GROUND
ICC_MEN_GROUND: CricketFigures
The ICC men's playing conditions (effective from October 2026): the Laws' pitch and creases (6.1, 7.2 to 7.4, 8.1), the popping crease marked at least 25 ft either side (7.3), a boundary no longer than 90 yards and not shorter than 65 yards from the centre of the pitch (19.1.3), and the two semicircles of 30 yards about the middle stumps, linked by two parallel lines (28.7.2.1). 75 yards is drawn.
const ICC_WOMEN_GROUND
ICC_WOMEN_GROUND: CricketFigures
The ICC women's playing conditions (ODI, effective from October 2026): a boundary of 60 to 70 yards (19.1.3) and semicircles of 25.15 yards (23 m, 28.7.2.1). 65 yards is drawn.
const IHF_COURT
IHF_COURT: HandballFigures
The IHF's court, from Rule 1 of the Rules of the Game for Indoor Handball (1 July 2025): 40 by 20 m (1:1); the goal 3 m wide and 2 m high (1:2); lines 5 cm, the goal line between the posts 8 cm (1:3); the goal-area line a 3 m line 6 m from the goal line with quarter circles of 6 m about the posts' rear inner corners (1:4); the free-throw line broken, 3 m outside it, segments and spaces of 15 cm (1:5); the 7-metre line 1 m long (1:6); the 4-metre line 15 cm long (1:7); the throw-off area 4 m across (1:9); the substitution line 4.5 m from the centre line, ended by a mark 15 cm either side of the side line (1:10). The net's 1.1 m depth at the ground is from the Guidelines for Playing Courts and Goals (V h), which are not part of the rules.
const IRF_RACQUETBALL
IRF_RACQUETBALL: RacquetballFigures
The IRF's racquetball court, from Rule 2.1 of the Official Rules 2026-2028 and Section Three of the Court Specifications (2025), in feet as they are printed: 20 feet wide, 40 feet long and 20 feet high; lines 1 to 1 1/2 inches wide (1 1/2 inches, bright red, recommended); the back edge of the short line 20 feet from the back wall; the front edge of the service line 5 feet in front of the short line's back edge; a service box's line 18 inches from the side wall and a drive serve line 3 feet from it (to the edge nearest the centre); the receiving line's back edge 5 feet behind the short line's back edge, a broken line of two 21 inch ends and sixteen 6 inch lines between 6 inch spaces; the back wall at least 12 feet high, with the out-of-court line's upper edge at 12 feet.
const IRF_ROUNDNET
IRF_ROUNDNET: RoundnetFigures
The International Roundnet Federation's court, from Rules 1.1.2 and 1.2.1 to 1.2.4 (adopted 21 October 2022), in metres: a set 91.4 cm across and 20.3 cm high; a court of at least 10 by 10 m (33 by 33 feet) recommended, with no out of bounds; a serving line drawn as a circle 2.6 m (8.5 feet) from the centre of the set, 2.13 m (7 feet) from its edge; a no hit zone line drawn as a circle 90 cm (3 feet) from the centre; a mark at each of the four service positions, 90 degrees apart.
const IRL_FIELD
IRL_FIELD: RugbyFigures
The IRL's field, from Section 1 of the International Laws of the Game (2024): 100 m between the goal lines, 68 m wide, in-goal 6 to 11 m (8 m, the NRL's, is drawn), goal posts 5.5 m apart with the crossbar 3 m up, a line across the field at every 10 m from each goal line to the half-way line. The book prints no line width and no red lines: the NRL's 15 cm is drawn, in white.
const ISTAF_SEPAK_TAKRAW
ISTAF_SEPAK_TAKRAW: SepakTakrawFigures
The ISTAF's court, from Laws 1 to 3 of the Law of the Game (2013, dated 9 December 2013), in metres: 13.40 by 6.10 m; the boundary lines at most 0.04 m wide, drawn inwards; a centre line 0.02 m wide; a quarter circle of 0.9 m radius at each end of the centre line; a service circle of 0.3 m radius on each side, its centre 2.45 m from the back line and 3.05 m from the sidelines, its line 0.04 m wide; a free zone of 3.0 m; the posts 0.3 m outside the sidelines, in line with the centre line, 1.55 m (men) or 1.45 m (women) high; the net 0.7 m wide and at least 6.1 m long, 1.52 m (men) or 1.42 m (women) high at the centre.
const ITF_TENNIS
ITF_TENNIS: TennisFigures
The ITF's court, from Rule 1 of the Rules of Tennis (2026) and its Appendix X, in feet as the ITF prints them: 78 feet long, 27 feet wide for singles and 36 feet for doubles; the net 3 feet 6 inches at the posts and 3 feet at the centre; the centres of the net posts 3 feet outside the doubles court and the centres of singles sticks 3 feet outside the singles court; the service lines 21 feet from the net; the centre mark 4 inches long and the centre service line 2 inches wide; the other lines 1 to 2 inches wide and the baselines up to 4 inches; posts at most 6 inches square, singles sticks 3. Appendix X recommends 21 feet behind the baselines and 12 feet beside the sidelines for international competitions, 18 and 10 for clubs.
const ITTF_TABLE
ITTF_TABLE: TableTennisFigures
The ITTF's table, from Laws 2.1 and 2.2 of the Laws of Table Tennis (the 2026 statutes), in metres: 2.74 by 1.525 m and 76 cm above the floor; a white side line and end line 2 cm wide, a white centre line 3 mm wide; the net 15.25 cm above the playing surface, hung from posts 15.25 cm high whose outside limits are 15.25 cm outside the side lines. The playing area round it is the ITTF's Regulations for International Competitions, 3.2.3 (ITTF Statutes 2026, chapter 3): a space of 14 m by 7 m by 5 m (8 m by 6 m for wheelchair events, 10 m by 5 m for Masters events), enclosed by surrounds 50 cm to 100 cm high, all of one dark colour, with the umpires' chairs and tables inside it.
const LACROSSE_LEAGUES
LACROSSE_LEAGUES: readonly LacrosseLeague[]
The lacrosse leagues: World Lacrosse's men's field first, which is what a drawing has without a league.
type LacrosseFigures
interface LacrosseFigures { /** `box` (a floor with boards), or the field of the `men`'s game, the `women`'s or the `pll`'s. */ kind: "box" | "men" | "women" | "pll"; length: Span; width: Span; lineWidth: number; /** The goal line's distance from the end line (the end boards on a floor). */ goalLine: number; /** The goal's opening, and the depth of the net behind the goal line. */ goalWidth: number; goalHeight: numb…
The figures of a lacrosse surface, in the unit of the table they are in. null is what a game does not mark.
type LacrosseLeague
type LacrosseLeague = LeagueBase<"lacrosse", LacrosseFigures>;
A league with a lacrosse surface of its own.
function lacrosseOf
lacrosseOf: (league: LacrosseLeague) => LacrosseSpec
A lacrosse surface of a league, in feet (the box floor, or a field). These have no history; a year is ignored.
type League
type League = BasketballLeague | HockeyLeague | FootballLeague | BaseballLeague | CurlingLeague | NetLeague | LacrosseLeague | RugbyLeague | AflLeague | GaelicLeague | CricketLeague | FieldHockeyLeague | HandballLeague | AthleticsLeague | SkatingLeague | BudoLeague;
A league: a variant of a family of surface.
const LEAGUE_SOURCES
LEAGUE_SOURCES: Readonly<Record<string, Readonly<LeagueSource>>>
Every document a league's figures were read from, by id.
function leagueAt
leagueAt(sport: Sport, id: string, year?: number): LeagueAt
A league's figures as they were in a season. Without a year, or for a league with no dated history, they are the rulebook's as it is now.
Example
import { leagueAt } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
console.log(leagueAt("nba", "ncaa-men", 2010).differences.map((change) => change.id));
// [ 'ncaa-men.restricted.start' ]
type LeagueAt
interface LeagueAt<L extends League = League> { league: L; /** The season asked for, or `undefined` for today's. */ year: number | undefined; /** The figures in the unit the league keeps them in. */ figures: L["dimensions"]; /** The markings that differ from today's. */ differences: LeagueChange[]; /** Markings whose history starts later than the season asked for (the first cited state is used). */ gaps: string[]; }
The league's figures in a season: the rulebook's as it is now, with each marking that has a dated history as it stood then.
function leagueAtOf
leagueAtOf<L extends League>(league: L, year?: number): LeagueAt<L>
leagueAt for a league already in hand.
function leagueById
leagueById(sport: Sport, id: string): League | undefined
A league by its sport and id, or undefined.
type LeagueChange
interface LeagueChange { /** `ncaa-men.threePoint.2019`. */ id: string; league: string; /** The marking's name: a key of the league's dimensions. */ feature: string; /** The first season, or `null` for the state before the first change that is cited. */ from: number | null; value: unknown; what: string; ja: string; sources: string[]; }
One change of a league's markings: a state of one marking from a season on.
function leagueChanges
leagueChanges(sport: Sport, id: string): LeagueChange[]
Every change a source dates in a league's markings, in season order, each with a sentence in English and in Japanese and its sources. A league with no cited history has none (a drawing with a year is then the league's rulebook as it is now).
Example
import { leagueChanges } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
console.log(leagueChanges("nba", "ncaa-men").map((change) => change.id));
function leagueFigures
leagueFigures(league: League): [string, string][]
The key figures of a league in words, each in the unit its rulebook uses: for a table of the leagues (docs/variants.md) and for a test that holds the drawing to the rulebook.
Example
import { LEAGUES, leagueFigures } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
const fiba = LEAGUES.nba.find((league) => league.id === "fiba")!;
console.log(leagueFigures(fiba).slice(0, 2).map(([name, value]) => `${name}: ${value}`).join("; "));
// court: 28 m by 15 m; lane: 4.9 m wide
function leagueIds
leagueIds: (sport: Sport) => string[]
The ids of a sport's leagues.
const LEAGUES
LEAGUES: Readonly<Record<Sport, readonly League[]>>
The leagues each sport can draw, in the order a menu lists them, the sport's own first (the three football sports share their list, the football leagues). Soccer and the pools have none.
function leagueSeason
leagueSeason(family: Family, year: number): string
The name of a season as the family writes it: 1979–80 for basketball and hockey, which play across the new year, else 1979.
function leagueSize
leagueSize(sport: Sport, id: string, unit?: Unit): { length: number; width: number; unit: Unit; }
The length and the width of a league's surface in a unit (the league's own when none is given): a football field with its end zones, end line to end line. A diamond has no fixed size, its fence is its size.
Example
import { leagueSize } from "@johnmorrisdotca/kyogijo-stadiums/leagues";
console.log(leagueSize("nba", "nba"));
// { length: 94, width: 50, unit: 'ft' }
type LeagueSource
interface LeagueSource { id: string; /** The document: "NCAA Men's and Women's Basketball Rules and Interpretations". */ title: string; /** Who publishes it. */ by: string; /** The edition: a season or a year. */ edition: string; /** The address it was read at, on the date in `read`. */ url: string; /** The date it was read (yyyy-mm-dd). */ read: string; /** What was taken from it. */ note?: string; }
A rulebook (or a page that publishes its figures).
type LeagueSpan
interface LeagueSpan<T> { /** The first season it was in force, or `null` for the state before the first change that is cited. */ from: number | null; value: T; /** What it was, in a sentence. */ what: string; /** The same in Japanese. */ ja: string; /** Keys of `LEAGUE_SOURCES`; at least one. */ sources: string[]; }
The state of one marking from a season on, in a league's own history: the season it began, what it was, and its sources.
const MCC_GROUND
MCC_GROUND: CricketFigures
The Laws of Cricket (MCC, 2017 Code, 4th Edition 2026): the pitch 22 yards by 10 feet (6.1); the bowling crease 8 ft 8 in (7.2); the popping crease 4 ft in front of it and marked at least 6 ft either side of the line of the middle stumps (7.3); the return creases 4 ft 4 in either side of that line (inside edges), marked 8 ft behind the popping crease (7.4); a set of wickets 9 in wide (8.1). No boundary size and no circle: the Laws have none (19), so the boundary is any size, 75 yards by default. The Laws print no width for the creases: 2 inches is drawn.
const MLB_DIAMOND
MLB_DIAMOND: DiamondFigures
The baseball field of the Official Baseball Rules, from MLB (geometry.ts).
type Named
interface Named { en: string; ja: string; }
The words of a league in both languages.
const NBA_COURT
NBA_COURT: CourtFigures
The NBA court today, from NBA (geometry.ts). Rule 1 of the NBA rulebook.
const NCAA_MEN_FIELD
NCAA_MEN_FIELD: LacrosseFigures
The NCAA's men's field (NCAA Men's Lacrosse Rules and Interpretations, 2027 and 2028, Rule 1): 110 by 60 yards (1-2); the goal 6 ft by 6 ft, 15 yards from each end line (1-3); the net fastened 7 ft behind the centre of the goal (1-5); a crease of 9 ft radius and a goal mouth of 6 ft radius (1-4); the attack-area line 40 yards long, 20 yards from the goal line, joined to the end lines (1-6); the defensive-area line 20 yards from the goal line, sideline to sideline (1-7); wing lines 20 yards from the centre, 10 yards each side of the centre line (1-8); the goal line and goal mouth 2 in wide, the centre line 4 in (1-2).
const NCAA_WOMEN_FIELD
NCAA_WOMEN_FIELD: LacrosseFigures
The NCAA's women's field (NCAA Women's Lacrosse Rules, 2026 and 2027, Rule 1): 101 to 110 m by 55 to 64 m, the optimal 110 by 60 m with the goals 92 m apart, 9 m behind each goal line (1-1); the goal 1.83 m by 1.83 m with the net 2.1 m behind the goal line (1-18); a goal circle of 2.6 m radius (1-21); a restraining line 27 m from each goal line (1-4); a centre circle of 9 m radius and a 3 m line through the centre (1-5); an arc of 8 m and a fan of 12 m from the goal circle, the arc ending at lines at 45 degrees to the goal line extended and the fan at the goal line extended (1-6); lines 5 to 10.1 cm, the goal line 5 cm (1-3).
const NETBALL_LEAGUES
NETBALL_LEAGUES: readonly NetballLeague[]
The netball leagues: World Netball's.
type NetballFigures
interface NetballFigures { /** The side lines' length, and the goal lines'. */ length: number; width: number; /** All lines are 50 mm wide. */ lineWidth: number; /** The centre circle's diameter, and the goal circle's radius (a semicircle centred on the middle of the outside of the goal line). */ centreCircle: number; goalCircle: number; /** A goalpost's height, the greatest diameter of its pole, and its ring: the i…
A netball court, from Rule 1 of World Netball's Rules of Netball (2024 edition). Metres.
type NetballLeague
type NetballLeague = LeagueBase<"netball", NetballFigures>;
type NetFigures
type NetFigures = TennisFigures | VolleyballFigures | BadmintonFigures | PickleballFigures | TableTennisFigures | PadelFigures | SquashFigures | RacquetballFigures | SepakTakrawFigures | TeqballFigures | RoundnetFigures | NetballFigures;
The figures of any net sport's court.
type NetLeague
type NetLeague = TennisLeague | VolleyballLeague | BadmintonLeague | PickleballLeague | TableTennisLeague | PadelLeague | SquashLeague | RacquetballLeague | SepakTakrawLeague | TeqballLeague | RoundnetLeague | NetballLeague;
A league with a net sport's court.
function netOf
netOf: <L extends NetLeague>(league: L) => L["dimensions"]
A net sport's court of a league (tennis, volleyball, beach and sitting volleyball, badminton, pickleball, table tennis, padel, squash, racquetball, sepak takraw, teqball, roundnet and netball), in feet. These courts have no history; a year is ignored.
type NetSport
type NetSport = "tennis" | "volleyball" | "badminton" | "pickleball" | "tabletennis" | "padel" | "squash" | "racquetball" | "sepaktakraw" | "teqball" | "roundnet" | "netball";
The sports of these courts.
const NHL_RINK
NHL_RINK: RinkFigures
The NHL rink today, from NHL (geometry.ts). Rule 1 of the NHL rulebook.
const NLL_FLOOR
NLL_FLOOR: LacrosseFigures
The NLL's floor (Official Rules 2025-26, Section 1 and Diagram A): 180 to 200 ft long and 85 wide, corners of 28 ft radius (the diagram's labels); the goal 4 ft 9 in apart and 4 ft high, the goal line 12 ft from the end boards (2.1), poles of 4 ft 6 in behind (2.2); the crease a circle of 9 ft 3 in radius cut by a line 1 ft behind the goal line (3.1); restraining lines 42 ft 6 in from the centre line (1.5); the centre face-off circle of 11 ft radius with a dotted circle of 17 in (6.1); corner face-off spots 5 yards from the boards and 5 yards inside the restraining lines (6.2). The NLL's book prints no line width: World Lacrosse's 2 in is drawn.
const NRL_FIELD
NRL_FIELD: RugbyFigures
The NRL's field, from Section 1 and Section 18 of the Rugby League Laws of the Game, International Level (2023 edition): 100 m between the goal lines, 68 m wide, in-goal areas 68 by 8 m, goal posts 5.5 m apart and 16 m high, lines 15 cm wide, white, at every 10 m from each goal line to the half-way line, those at 20 m and 40 m red; scrum lines 10 m and 20 m in from each touchline (10 cm). The section also prints a media line 1.5 m outside each touchline, which is not drawn: it gives no length. The crossbar's height, 3 m, is the plan's label in Section 1.
const PADEL_LEAGUES
PADEL_LEAGUES: readonly PadelLeague[]
The padel leagues: the FIP's.
type PadelFigures
interface PadelFigures { /** Interior length and width (a 0.5% tolerance). */ length: number; width: number; /** All lines are 5 cm wide. */ lineWidth: number; /** The service lines are this far from the net, on either side. */ serviceLine: number; /** The central service line runs from the net and extends at least this far beyond the service line. */ centreOverrun: number; net: { /** The net's length, its height at…
A padel court, from "The court" in the FIP's Rules of Padel (review of application 1 January 2026). Metres. The court is measured inside its walls, so it has no lines round it: the enclosure is its boundary.
type PadelLeague
type PadelLeague = LeagueBase<"padel", PadelFigures>;
const PICKLEBALL_LEAGUES
PICKLEBALL_LEAGUES: readonly PickleballLeague[]
The pickleball leagues: USA Pickleball's.
type PickleballFigures
interface PickleballFigures { length: number; width: number; /** The non-volley zone: each of its lines is this far from the net, to its outside edge. */ nonVolley: number; /** All lines are 2 inches wide. */ lineWidth: number; net: { /** The net's height at the sidelines and at the centre. */ heightSides: number; heightCentre: number; /** From the inside of one post to the inside of the other (so each stands 1 foot…
A pickleball court, from Section 3 of the USA Pickleball rulebook. Feet.
type PickleballLeague
type PickleballLeague = LeagueBase<"pickleball", PickleballFigures>;
const PLL_FIELD
PLL_FIELD: LacrosseFigures
The PLL's field (2024 PLL Rulebook, Section II, the newest book found): 100 by 60 yards (A); the goal 6 ft by 6 ft, 15 yards from each end line (C, D); a crease of 9 ft radius (E); the two-point arc 13 yards from the middle of the goal line at the goal line extended, parallel to the sideline until it is 15 yards from it, then an arc of 15 yards, and two straight lines from the goal line extended to the end line (G); wing lines 19 yards from the centre, 10 yards each side (H); the centre line and the arc 4 in wide, the goal lines 2 in (A). The net is "approximately seven feet" back (F).
const RACQUETBALL_LEAGUES
RACQUETBALL_LEAGUES: readonly RacquetballLeague[]
The racquetball leagues: the IRF's.
type RacquetballFigures
interface RacquetballFigures { length: number; width: number; /** The lines are 1 to 1 1/2 inches wide: 1 1/2 inches is the recommended width. */ lineWidth: number; /** The back edge of the short line is this far from the back wall (midway between the walls). */ shortLine: number; /** The front edge of the service line is this far in front of the short line's back edge. */ serviceLine: number; /** The edge of a serv…
A racquetball court, from Rule 2.1 of the International Racquetball Federation's Official Rules 2026-2028 and its Court Specifications (2025). Feet.
type RacquetballLeague
type RacquetballLeague = LeagueBase<"racquetball", RacquetballFigures>;
type RinkFigures
interface RinkFigures { /** End boards to end boards. */ length: number; width: number; /** The radius of the boards' corners. */ cornerRadius: number; /** The goal line, from the end boards. */ goalLine: number; /** The blue lines, from the end boards. */ blueLine: number; /** The face-off circles' radius. */ circleRadius: number; /** An end-zone face-off spot, from the goal line, and from the rink's long axis. */ …
The figures of an ice rink. Lengths, in the unit of the table they are in.
function rinkOf
rinkOf: (league: HockeyLeague, year?: number) => RinkSpec
An ice rink of a league in a season, in feet.
const ROUNDNET_LEAGUES
ROUNDNET_LEAGUES: readonly RoundnetLeague[]
The roundnet leagues: the International Roundnet Federation's.
type RoundnetFigures
interface RoundnetFigures { /** The recommended least court; there are no out of bounds. */ length: number; width: number; /** The set: its diameter and its height. */ set: { diameter: number; height: number }; /** The serving line is a circle this far from the centre of the set; the no hit zone line, another. */ servingRadius: number; noHitRadius: number; /** The distance from the edge of the set to the service lin…
A roundnet court, from Chapter 1 of the International Roundnet Federation's Rules (adopted 21 October 2022). Metres.
type RoundnetLeague
type RoundnetLeague = LeagueBase<"roundnet", RoundnetFigures>;
const RUGBY_LEAGUES
RUGBY_LEAGUES: readonly RugbyLeague[]
The rugby leagues, World Rugby's first.
type RugbyFigures
interface RugbyFigures { /** `union` or `league`: the lines each code marks differ. */ code: "union" | "league"; /** Try line to try line (goal line to goal line), and across. */ length: Span; width: Span; /** The depth of each in-goal area, try line to dead-ball line. */ inGoal: Span; /** The width of the lines, as drawn at true width. */ lineWidth: number; /** The goal posts: apart, and the crossbar's top edge abo…
The figures of a rugby field. Lengths, in the unit of the table they are in. null and [] are what a code does not have.
type RugbyLeague
type RugbyLeague = LeagueBase<"rugby", RugbyFigures>;
A league with a rugby field of its own.
function rugbyOf
rugbyOf: (league: RugbyLeague) => RugbySpec
A rugby field of a league, in feet.
const SEPAK_TAKRAW_LEAGUES
SEPAK_TAKRAW_LEAGUES: readonly SepakTakrawLeague[]
The sepak takraw leagues: the ISTAF's.
type SepakTakrawFigures
interface SepakTakrawFigures { length: number; width: number; /** The boundary lines are at most this wide, drawn inwards; the service circle's is the same. */ lineWidth: number; /** The centre line, under the net. */ centreLine: number; /** The quarter circles at the ends of the centre line: their radius. */ quarterCircle: number; /** The service circles: their radius, and their centre's distance from the back line…
A sepak takraw court, from Laws 1 to 3 of the ISTAF's Law of the Game (2013). Metres.
type SepakTakrawLeague
type SepakTakrawLeague = LeagueBase<"sepaktakraw", SepakTakrawFigures>;
type SheetFigures
interface SheetFigures { /** The sheet as drawn: backboard to backboard (inside edges), and sideline to sideline. The greatest the rules allow. */ length: number; width: number; /** The least length and the least width the rules allow. The greatest are `length` and `width`. */ lengthMin: number; widthMin: number; /** Each tee line's centre, from the middle of the sheet. */ teeFromMiddle: number; /** The back line's …
The figures of a curling sheet. Lengths, in the unit of the table they are in.
function sheetOf
sheetOf: (league?: CurlingLeague) => SheetSpec
A curling sheet of a league, in feet. A sheet has no history; a year is ignored.
function span
span: (min: number, max: number, drawn?: number) => Span
A range of sizes; the drawn size is the greatest the rules allow unless another is said.
type Span
interface Span { min: number; max: number; drawn: number; }
A length the rules allow between a least and a greatest, with the one that is drawn, all in the league's unit.
const SQUASH_LEAGUES
SQUASH_LEAGUES: readonly SquashLeague[]
The squash leagues: World Squash's singles court, its doubles court and its international competition width doubles court.
type SquashFigures
interface SquashFigures { length: number; width: number; /** All court markings are 50 mm wide. */ lineWidth: number; /** The nearest edge of the short line is this far from the back wall. */ shortLine: number; /** A service box is a square of this many metres inside its lines. */ serviceBox: number; /** Heights on the walls: to the top of the tin, to the lower edge of the service line and of the front wall line, an…
A squash court, from the World Squash Federation's Specifications for Squash Courts (28 November 2017), clauses 4 and 5 and Appendices 1 and 2. Metres. The court is measured between the playing surfaces of its walls, so it has no lines round it; the front wall's lines are heights.
type SquashLeague
type SquashLeague = LeagueBase<"squash", SquashFigures>;
const TABLE_TENNIS_LEAGUES
TABLE_TENNIS_LEAGUES: readonly TableTennisLeague[]
The table tennis leagues: the ITTF's.
type TableTennisFigures
interface TableTennisFigures { length: number; width: number; /** The height of the playing surface above the floor. */ height: number; /** The white side lines and end lines are 2 cm wide, the centre line 3 mm. */ edgeLine: number; centreLine: number; net: { /** The top of the net above the playing surface, and the height of the posts. */ height: number; postHeight: number; /** The outside limits of a post are this…
A table tennis table, from Laws 2.1 and 2.2 of the ITTF's Laws of Table Tennis. Metres.
type TableTennisLeague
type TableTennisLeague = LeagueBase<"tabletennis", TableTennisFigures>;
const TENNIS_LEAGUES
TENNIS_LEAGUES: readonly TennisLeague[]
The tennis leagues: the ITF's. The ATP and the WTA play by the ITF's rules.
type TennisFigures
interface TennisFigures { /** Baseline to baseline, to the outside of the lines. */ length: number; /** The singles court's width, and the doubles court's. */ widthSingles: number; widthDoubles: number; /** The service lines: each is this far from the net, to its outside edge. */ serviceLine: number; /** The width of the lines: 1 to 2 inches (the greatest is drawn); a baseline may be up to 4 inches. */ lineWidth: nu…
A tennis court, from Rule 1 of the ITF's Rules of Tennis and its Appendix X. Feet, as the ITF prints them first.
type TennisLeague
type TennisLeague = LeagueBase<"tennis", TennisFigures>;
const TEQBALL_LEAGUES
TEQBALL_LEAGUES: readonly TeqballLeague[]
The teqball leagues: the FITEQ's.
type TeqballFigures
interface TeqballFigures { /** The least court: the sides parallel to the net are `width` long, the other two `length`. */ length: number; width: number; table: { /** The table's length, its width without the net and with it, and its height with the net. */ length: number; width: number; widthWithNet: number; height: number; }; /** The net: its width, thickness and height above the table. */ net: { width: number; th…
A teqball court and table, from sections 1 and 2 of the FITEQ's Official Rules and Regulations of Teqball (2026). Metres.
type TeqballLeague
type TeqballLeague = LeagueBase<"teqball", TeqballFigures>;
const USAP_PICKLEBALL
USAP_PICKLEBALL: PickleballFigures
USA Pickleball's court, from Section 3 of the 2026 rulebook, in feet as it prints them: 20 by 44 feet to the outside edge of the lines (3.A.1, 3.A.2); the non-volley zone 7 feet from the net (3.A.4.c); all lines 2 inches wide (3.A.4.e); the posts 22 feet apart, inside to inside, and at most 3 inches across (3.B.2); the net at least 21 feet 9 inches long (3.B.3), 36 inches high at the sidelines (3.B.6) and 34 inches at the centre (3.B.7); a playing surface of at least 30 by 60 feet, 34 by 64 feet recommended for tournaments (3.A.3).
const VARIANTS
VARIANTS: readonly League[]
Every league of every family, once each.
const VOLLEYBALL_LEAGUES
VOLLEYBALL_LEAGUES: readonly VolleyballLeague[]
The volleyball leagues: the FIVB's indoor court, its beach court, and World ParaVolley's sitting volleyball court.
type VolleyballFigures
interface VolleyballFigures { length: number; width: number; /** All lines are 5 cm wide and drawn inside the dimensions of the court. */ lineWidth: number; /** Indoors: the axis of the centre line is the middle of the court; the attack line's rear edge is this far from it. Beach volleyball has neither. */ attackLine: number | null; /** The broken lines that extend each attack line outside the side lines, in the FIV…
A volleyball or beach volleyball court, from Rules 1 and 2 of the FIVB's rules. Metres.
type VolleyballLeague
type VolleyballLeague = LeagueBase<"volleyball", VolleyballFigures>;
const WA_SHORT_STAGGER_TABLE
WA_SHORT_STAGGER_TABLE: Readonly<Record<"two-bends" | "three-bends" | "one-bend", readonly number[]>>
The staggers of the lanes of the 200 m Standard Short Track (Marking Plan, 1 January 2026), in metres measured 0.20 m out from the lane line, for lanes 2 to 6. The first row serves the 200 m, 400 m, 800 m, 4 x 400 m and 4 x 800 m (two bends in lanes), the second the 4 x 200 m (three bends in lanes), the third the second leg of the 4 x 200 m (one bend).
const WA_SHORT_TRACK
WA_SHORT_TRACK: AthleticsFigures
The 200 m Standard Short Track (Marking Plan for the World Athletics Standard Short Track, 1 January 2026; Rules 41 to 44): the bends have a construction radius of 17.205 m at the kerb and the centres of the banked bends are 44.983 m apart; lanes are 1.000 m wide on the oval and 1.220 m on the infield straight, four to six of them (Rule 43: 0.90 to 1.22 m, a minimum of four lanes and a maximum of six); the bends are banked at 10.000 degrees. The plan's own transitions (the ascending and descending sections) are drawn here as one circular bend of the same radius, which is ours.
const WA_STAGGER_TABLE
WA_STAGGER_TABLE: Readonly<Record<"200m" | "400m" | "800m" | "4x400m", readonly number[]>>
The staggers of the lanes of the 400 m Standard Track as the Manual prints them (Table 2.2.1.6a), in metres on the running line, for lanes 2 to 8: 200 m, 400 m, 800 m and 4 x 400 m.
const WA_STANDARD_TRACK
WA_STANDARD_TRACK: AthleticsFigures
The 400 m Standard Track (Manual 2.2.1.1, Table 2.2.1.1): two semicircles of 36.50 m radius at the kerb joined by two straights of 84.39 m, lanes 1.22 m wide including the 50 mm line on the right (Rule 14.4), the running line 0.30 m outside the kerb in lane 1 and 0.20 m outside the line on the left in every other lane (Rule 14.2), eight lanes at least for the big competitions (Rule 14.5) and nine at the most (Manual 2.2.1.1). A straight of at least six lanes runs on beyond the oval's with a starting area of 3 m and a run-out of 17 m (Manual 2.2.2.1), and has no most (2.2.2.1). The safety zones are 1.00 m wide (2.2.1.5). The kerb is drawn 0.05 m wide, the narrowest the rules allow (Rule 14.1: 50 to 250 mm).
const WCF_SHEET
WCF_SHEET: SheetFigures
World Curling's sheet, from R1 of The Rules of Curling and Rules of Competition (1 September 2026), in metres as it prints them: the sheet is at least 45.720 m long (146 ft, 44.501 m, in an existing facility) and at most 4.750 m wide (at least 4.420 m); each tee line is 17.375 m from the middle; the back line's outside edge is 1.829 m from the tee, the hog line's inside edge 6.401 m; the circles have radii of 1.829, 1.219 and 0.610 m and the button at least 0.152 m; the hog line is 102 mm wide, the others at most 13 mm; the centre line runs 3.658 m beyond each tee; the hack line is 457 mm long; the courtesy lines are 152 mm long and 1.219 m outside the hog lines; each hack's inside edge is 76 mm from the middle of the centre line, at most 152 mm wide and 203 mm in front of its line.
const WN_NETBALL
WN_NETBALL: NetballFigures
World Netball's court, from Rule 1 (Technical specifications, Court and related areas, items 2 to 8, 13 and 14) of the Rules of Netball (2024 edition), in metres: 30.5 m (100 feet) by 15.25 m (50 feet); two transverse lines dividing it into three equal areas; a centre circle 0.9 m (3 feet) across; at each end a goal circle, a semicircle of radius 4.9 m (16 feet) centred on the middle of the outside of the goal line; lines 50 mm wide; a court surround 3.05 m (10 feet) on every side; a goalpost at the middle of each goal line, its pole 65 to 100 mm across and 3.05 m high, the back of the pole at the outer edge of the goal line, with a ring of 380 mm inside diameter made of 15 mm rod, on a bar 150 mm long projecting from the pole.
const WORLD_BOX_FLOOR
WORLD_BOX_FLOOR: LacrosseFigures
World Lacrosse's box floor (Box Lacrosse Official Playing Rules 2026-2028, v2.0): the diagram's 200 ft by 85 ft, the same crease (1.1.7), goals (1.2.1), restraining lines (1.1.5) and face-off circles (1.1.9) as the NLL's, all lines 2 in (1.1.3). Its Rule 1.2.2 says "25 m from the midline", which does not fit the feet.
const WORLD_MEN_FIELD
WORLD_MEN_FIELD: LacrosseFigures
World Lacrosse's men's field (Men's Field Lacrosse Official Playing Rules 2025-2027, v1.1): 91.4 to 100 m long and 50 to 60 m wide (1.1); goal posts 1.83 m apart and 1.83 m high, 12 m from each end line (2.1, 2.2); the net's anchor 2.1 m behind the goal line (4.1); the crease a circle of 3 m radius (3.1); the goal area lines 22 m from the goal line (5.1); wing lines 18 m from the centre, extending 10 m either side of the centre line (7.1); lines 5 cm, the centre line 10 cm (12.1). The centre is an X or a 10 cm square (6.1).
const WORLD_RUGBY_FIELD
WORLD_RUGBY_FIELD: RugbyFigures
World Rugby's field, from Law 1 of the Laws of the Game, Rugby Union, 2026: the field of play 94 to 100 m between the try lines and 68 to 70 m wide; each in-goal 6 to 22 m deep (10 m is drawn: the Laws name none); the 22-metre lines 22 m from the try lines; the 10-metre dash lines 10 m either side of the half-way line; dash lines 5 m and 15 m from the touchlines and 5 m from the try lines, each dash 5 m; the half-way mark 0.5 m long; the goal posts 5.6 m apart on the try line, the crossbar 3 m to its top edge; flags 2 m outside the touchlines. Law 1 gives no width for the lines: 0.1 m is drawn.
const WORLD_WOMEN_FIELD
WORLD_WOMEN_FIELD: LacrosseFigures
World Lacrosse's women's field (Women's Field Lacrosse Official Playing Rules 2025-2026, v1.1): 91.4 to 100 m by 50 to 60 m (1.A.2); the goal line 12 m from each end line and 1.83 m long (1.A.5); a goal circle of 3 m radius (1.A.8); the 15 m marking area, a semicircle from the middle of the goal line to each goal line extended (1.A.6); the 11 m marking area, with a line from where the goal line extended meets the goal circle at 45 degrees to it out to the 11 m radius (1.A.7); restraining lines 22 m from each goal line (1.A.9); the centre line 3 m long (1.A.10) and the centre circle 9 m in radius (1.A.11); lines 5 to 10 cm (1.A.2). The book prints no depth for the net: the men's 2.1 m is drawn.
const WPV_SITTING
WPV_SITTING: VolleyballFigures
The World ParaVolley's sitting volleyball court, from Rules 1 and 2 of the Official Sitting Volleyball Rules 2025-2028, in metres: 10 by 6 m inside a free zone of at least 3 m (4 m beside the side lines and 6 m behind the end lines in World ParaVolley, World and Official Competitions); lines 5 cm wide inside the dimensions; the attack line's rear edge 2 m from the axis of the centre line and, in those competitions, extended by five 15 cm lines 20 cm apart to 1.75 m; the service zone 6 m wide, limited by two 15 cm lines 20 cm behind the end line; the net 0.80 m wide and 6.5 to 7 m long, 1.15 m (men) or 1.05 m (women) high; each antenna 1.60 m long and 10 mm across; the posts 0.5 to 1.0 m outside the side lines, 1 m in those competitions.
const WSF_SQUASH
WSF_SQUASH: SquashFigures
World Squash's singles court, from clauses 4.01 and 5 and Appendix 1 of its Specifications for Squash Courts (28 November 2017), in metres: 9.75 by 6.40 m between the playing surfaces; markings 50 mm wide; the nearest edge of the short line 4.26 m from the back wall; each service box a square of 1.60 m inside its lines; on the front wall the top of the tin 480 mm up, the lower edge of the service line 1.78 m and of the front wall line 4.57 m, and on the back wall the back wall line 2.13 m.
const WSF_SQUASH_DOUBLES
WSF_SQUASH_DOUBLES: SquashFigures
World Squash's doubles court (Appendix 2, clause 4.02): 7.62 m wide, the rest as the singles court.
const WSF_SQUASH_WIDE
WSF_SQUASH_WIDE: SquashFigures
World Squash's international competition width doubles court (Appendix 2 note 8, clause 4.03): 8.42 m wide, with the top of the tin 330 mm up, for WSF recognised World and Regional events and the Commonwealth Games.
@johnmorrisdotca/kyogijo-stadiums/district
buildDistrictTurn CIRCUIT_INDEX circuitPointIn circuitsHeld ContextArea ContextLandmark describeDistrict DISTRICT_IDS DISTRICT_MARGIN DISTRICT_MODES DistrictCircuit DistrictGate districtId districtMember DistrictMember DistrictMode DistrictOptions DistrictPart DistrictPlaced DistrictPlan districtPresets DistrictRaceDrawOptions DistrictRaceOptions DistrictRaceSettings districtRing districtTurnMarkup DistrictTurnSettings DistrictVenueInput drawDistrict drawDistrictRace frameOf Gate GATE_FACTS GATE_VENUES GateBasis GateFact gateName hasOutside isDistrictId isOutsideLevel KODOKAN KODOKAN_DOJO KODOKAN_FLOOR_HEIGHT KODOKAN_FLOOR_IDS KODOKAN_FLOORS KODOKAN_ROOM_HEIGHT KodokanFloor kodokanLevel kodokanMember KodokanRoom KYOGIJO_DISTRICT_STYLE KyogijoDistrict KyogijoRace LANDMARK_SHAPES LandmarkShape loadCircuits metresText mountDistrict mountDistrictRace mountDistrictTurn OUTSIDE_DENSITY OUTSIDE_LEVELS OUTSIDE_REACH OUTSIDE_ROOM OUTSIDE_VENUES outsideCount outsideCrowd OutsideCrowd OutsideFrame OutsideLevel outsideLevelOf OutsideOptions OutsideStats PERSON_METRES PlacedLandmark PlacedPart planDistrict RaceState rasterOutside scaleOf unknownVenues VENUE_ATTRIBUTION venueGates WALK_CELL WALK_IDS walkable WalkData walkMask WalkMask
function buildDistrictTurn
buildDistrictTurn(options: DistrictOptions, settings?: DistrictTurnSettings): TurnModel
A district as a 3D model: the floor is the district's flat plan with each venue's building only, and on it stands each venue as it stands on its own (turned about the middle of its surface and moved to its place in the district), with a name over each where the district has labels. A TurnModel like any other: turnMarkupOf and mountDistrictTurn make a view of it.
const CIRCUIT_INDEX
CIRCUIT_INDEX: Readonly<Record<string, { en: string; ja: string; }>>
Every circuit's key and its names in English and Japanese (Wikidata's labels), in the order of CIRCUITS.
function circuitPointIn
circuitPointIn(placed: Pick<DistrictCircuit, "at" | "angle">, p: Pt): Pt
A point of a circuit's own plan (feet, circuitPlan) where the district puts it: for a page that draws something on the lap (a race's cars) in a district's frame.
function circuitsHeld
circuitsHeld: () => boolean
Whether the circuits are held (the district entry, or the lean district after loadCircuits()).
type ContextArea
interface ContextArea { key: string; name: { en: string; ja: string }; /** The middle of the area, `[longitude, latitude]`: the point the rows' coordinates are measured from. */ origin: readonly [number, number]; /** How far from the middle the data reaches, in metres. */ radius: number; /** The step the coordinates and the heights are counted in, in metres (a half). */ grid: number; /** A building this tall, in met…
An area of context round a district: ONE coordinate frame (the origin, the grid step and the radius, in metres east and north of the origin) and separate layers laid in it, each with its own source and licence. A layer an area lacks is simply not drawn. The rows of each layer, all in grid steps from the origin: - buildings: the height and the rise of the roof (0 for a flat one), then the first point (east, north) and each step to the next. - streets: the kind (0 a carriageway at street level, 1 one on a viaduct or a bridge, 2 a railway, 3 a sidewalk or a path) and the width in grid steps, then the first point and each step to the next, a line. - landCover: the class (0 water, 1 green, 2 wood), then the first point and each step to the next, an outline (a hole is an outline of its own, filled even-odd). - trees: one row: the first tree's east, north and crown radius, then each next tree's step in east and north from the one before and its crown radius.
type ContextLandmark
interface ContextLandmark { key: string; /** The Wikidata item its names come from. */ wikidata: string; name: { en: string; ja: string }; shape: LandmarkShape; /** The OpenStreetMap element its outline is, `way/<id>`. */ source: string; /** Its outline, metres east and north of the area's origin. */ ring: readonly (readonly [number, number])[]; /** Its height over the ground, in metres. */ height: number; /** A dom…
A landmark of an area, as its data holds it: - dome: a sphere cut by the ground (the Sphere), width across at its widest and height tall; its outline is its footprint, and the building the area has there is the dome's own. - wheel: a big wheel standing upright along the long way of its outline (OpenStreetMap maps the High Roller's footprint), width across, its top height over the ground. - fountains: a row of jets along the long way of the water its outline is, reaching up to height (the most a published figure says they reach); the water is the area's land cover. - named: a name over the buildings inside its outline (they are the area's own, standing at their own heights), at height, the top of the tallest.
function describeDistrict
describeDistrict(options: DistrictOptions, plan?: DistrictPlan): { title: string; description: string; }
The title and the description of a district, in its language: what is drawn, where each venue stands from the first, how far apart they are, and the credit.
const DISTRICT_IDS
DISTRICT_IDS: readonly string[]
Every key a district can be asked for: the arenas of VENUES and the stadiums of STADIUMS.
const DISTRICT_MARGIN
DISTRICT_MARGIN: Readonly<Record<DistrictMode, number>>
The margin round the buildings, as a share of the longer side of the district: tight for neighbours, wide for a city's grid and names.
const DISTRICT_MODES
DISTRICT_MODES: readonly DistrictMode[]
type DistrictCircuit
interface DistrictCircuit { plan: CircuitPlan; /** Where the circuit's own origin (the middle of its plan) is in the district's frame, in feet. */ at: Pt; /** The degrees the circuit's plan is turned clockwise to lie in the district (its heading less a quarter turn, and the map's turn). */ angle: number; /** The outline of everything it draws on the ground (its plan's box), and of its pit building, in the district's…
A circuit placed in a district: its own plan (feet round its own middle, its long side along x), and where that middle is put and how far the plan is turned to lie as it does in the world.
type DistrictGate
interface DistrictGate { key: string; venue: string; name: { en: string; ja: string }; at: Pt; angle: number; basis: "documented" | "plausible"; }
A gate placed in a district: where it is on its venue's outline in the plan's frame, in feet, and the way it faces on the page, in degrees clockwise from the top.
function districtId
districtId: (options: DistrictOptions) => string
The id of a district's drawing: the option's, or a hash of the options.
function districtMember
districtMember(input: DistrictVenueInput, language?: Language, floor?: number): DistrictMember
A venue of a district, from its key: rogers-arena (an arena), bc-place or bc-place:soccer (a stadium in its first configuration or the one named). Throws for a key no venue has, and says which keys there are.
Example
import { districtMember } from "@johnmorrisdotca/kyogijo-stadiums/district";
const member = districtMember("bc-place:soccer");
console.log(member.key, member.kind, member.seats);
// bc-place:soccer stadium 52497
type DistrictMember
interface DistrictMember { /** The key of the venue and the configuration, unique in a district: `rogers-arena`, `bc-place:soccer`. */ key: string; id: string; kind: "arena" | "stadium" | "park" | "hall"; config?: StadiumConfigId; /** The name in both languages. */ name: { en: string; ja: string }; /** The building's outline, `[longitude, latitude]`. */ ring: readonly (readonly [number, number])[]; /** The middle of…
A venue of a district as the district needs it: what it is called, where it stands, how it lies, and how it is drawn.
type DistrictMode
type DistrictMode = "neighbours" | "city";
How a district is fitted: neighbours tight round venues that stand close together, city at the real distances between venues that are kilometres apart.
type DistrictOptions
interface DistrictOptions { /** The venues, by key: any key of `VENUES` (the arenas) and `STADIUMS` (the stadiums); at least one, unless the district has a `circuit`. */ venues: readonly DistrictVenueInput[]; /** * A race circuit laid on the same ground (a key of `CIRCUIT_IDS`: `las-vegas`): its lap, pit lane, ground and pit building where OpenStreetMap maps them, under the venues, turned as it lies; in 3D its pit b…
What can be asked of a district.
type DistrictPart
interface DistrictPart { key: string; options: SurfaceOptions; /** The middle of the surface, \`[longitude, latitude]\`. */ centre: readonly [number, number]; /** The compass heading of the surface's x axis, 0 to under 180. */ heading: number; /** How high its floor stands above the ground, in feet. */ elevation?: number; /** Which part of the surface's room is drawn: `room` (the floor, the walls and what stands on …
One surface of a venue that has several (DistrictMember.parts): what it is drawn from, where it stands, how it lies and how high its floor is.
type DistrictPlaced
interface DistrictPlaced { member: DistrictMember; /** The middle of the surface. */ at: Pt; /** The degrees the venue's own drawing (its field along x) is turned clockwise to lie as it does in the world. */ angle: number; /** The surfaces of the venue as the plan places them (one, unless the venue has `parts`). */ parts: PlacedPart[]; /** The building's outline. */ footprint: Pt[]; /** Its convex hull, which the de…
type DistrictPlan
interface DistrictPlan { options: DistrictOptions; mode: DistrictMode; /** The degrees the map is turned clockwise (0 has north at the top). */ turn: number; /** The way north points on the page, degrees clockwise from the top. */ north: number; members: DistrictPlaced[]; /** The buildings round the venues that the options' `context` brings, placed in the frame; `undefined` without it. */ context: ContextPlan | unde…
What a district is: its venues placed, the box that fits them, and how the map lies.
function districtPresets
districtPresets(plan: Pick<DistrictPlan, "turn">): PresetTable
The four viewpoints of a district, turned with the map: the main camera looks from the south over the district (north at the top of the page), the end-on view from the west and the low corner from the south-west.
type DistrictRaceDrawOptions
type DistrictRaceDrawOptions = DistrictRaceOptions & { t?: number };
A race on a district's ground at a moment: the district's and the race's options, and the seconds from the start (0, the grid, by default).
type DistrictRaceOptions
type DistrictRaceOptions = DistrictOptions & { circuit: string } & Omit<RaceOptions, "circuit">;
What a race on a district's ground is drawn from: the district's options, its circuit named, and the race's (seed, laps, cars).
type DistrictRaceSettings
type DistrictRaceSettings = RaceViewSettings & { turn?: DistrictTurnSettings };
How a race on a district's ground is shown and played: as a circuit's race, with the district's 3D view's settings (its viewpoint, the walls and roofs of its venues, its quality).
function districtRing
districtRing(input: DistrictVenueInput): DistrictMember["ring"]
The outline of a venue's building, as districtMember(input).ring has it, read without the venue's records: a crowd outside keeps out of every building the ground has, and the buildings of venues that are not shown need no names. Throws as districtMember does for a key no venue has.
function districtTurnMarkup
districtTurnMarkup(options: DistrictOptions, settings?: DistrictTurnSettings): string
A district as the markup of a 3D view, still until a page's script makes it turn: pure, so a server can make it.
type DistrictTurnSettings
type DistrictTurnSettings = TurnSettings;
What can be asked of a district's 3D view beyond a surface's: roof and roofOpen for every venue that has one (as venue: { roof, roofOpen } of a single venue's view).
type DistrictVenueInput
type DistrictVenueInput = string | { id: string; config?: StadiumConfigId };
A venue of a district: its key, and for a stadium the configuration it is drawn in (cfl or soccer; the first it has where none is given; a ballpark's is mlb and a hall's boxing). "bc-place:soccer" is the same as { id: "bc-place", config: "soccer" }.
function drawDistrict
drawDistrict(options: DistrictOptions, plan?: DistrictPlan, drawing?: (member: DistrictMember, index: number, part: number): string) => string
The plan of a district as one SVG: the ground, a grid and a scale, a north arrow, and each venue's own drawing (its stands, or its building only for stands: false) put where it stands and turned as it lies, with a name beside each where labels says. drawing is how each venue is drawn; the 3D view gives it the building-only floor.
Example
import { drawDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district";
const svg = drawDistrict({ venues: ["bc-place", "rogers-arena"] });
console.log(svg.includes("ky-district"), svg.includes("ky-cr-shell"));
// true true
function drawDistrictRace
drawDistrictRace(options: DistrictRaceDrawOptions, given?: CircuitRace): string
A race on a district's ground at a moment, as one SVG string: the district's plan with a dot for each car where the race has it then, on the circuit where the district lays it, in its team's colour with the position it holds written on it. The race is the simulation the options make (made-up cars, from a seed), or the one given (from a feed, raceFromFeed).
Example
import { drawDistrictRace } from "@johnmorrisdotca/kyogijo-stadiums/district";
const svg = drawDistrictRace({ venues: ["t-mobile-arena"], circuit: "las-vegas", laps: 3, cars: 6, t: 120 });
console.log(svg.match(/class="ky-ci-car"/g)!.length, svg.includes('data-circuit="las-vegas"'));
// 6 true
function frameOf
frameOf(view: { x: number; y: number; w: number; h: number; }, width: number): OutsideFrame
The frame of a buffer that covers a view box of the plan (feet) in width pixels, as high as the box's shape makes it.
type Gate
interface Gate { /** `bc-place:south`: the venue's id and the gate's. */ key: string; venue: string; id: string; name: { en: string; ja: string }; /** Where it stands on the outline, `[longitude, latitude]`. */ at: LonLat; /** The bearing of its outward normal, degrees clockwise from north: the way a queue at it runs. */ bearing: number; basis: GateBasis; read: string; }
A gate, placed on a venue's outline.
const GATE_FACTS
GATE_FACTS: Readonly<Record<string, readonly GateFact[]>>
The facts of each venue's gates. BC Place: the English Wikipedia article (revision 1372065649) says a tear in the old roof was "close to Gate G on the south side where the roof meets the top of the concrete bowl", so there is a Gate G on the south side (documented); the other seven are ours, one to each side of the building, on the street sides the brief names (Pacific Boulevard to the south, Robson and Beatty Streets). Rogers Arena: the brief's corner entrance plazas on the Pat Quinn Way side, the south front and the two south corners, and one at the north-west, all ours.
const GATE_VENUES
GATE_VENUES: readonly string[]
The ids of the venues that have gates.
type GateBasis
type GateBasis = "documented" | "plausible";
How a gate is known: documented is what a source cited with it says; plausible is ours.
type GateFact
interface GateFact { /** A key that is the same on every run: `south`, `south-west-corner`. */ id: string; /** The bearing of the gate's outward normal, degrees clockwise from north, 0 to under 360. */ bearing: number; /** The name where a source gives one (`Gate G`); a plain description of where it is otherwise. */ name?: { en: string; ja: string }; basis: GateBasis; read: string; }
What is said of a venue's gate: the way it faces, and what is read from where.
function gateName
gateName(fact: GateFact, language: "en" | "ja"): string
The name of a gate in a language: the source's where there is one, else its side (South-west gate).
function hasOutside
hasOutside: (plan: Pick<DistrictPlan, "members">) => boolean
Whether a plan has a crowd to show: some venue of it stands on a mask.
function isDistrictId
isDistrictId: (id: string) => boolean
Whether a key is a venue a district can place.
function isOutsideLevel
isOutsideLevel: (level: unknown) => level is OutsideLevel
Whether a number is one of the levels.
const KODOKAN
KODOKAN: { readonly floorHeight: number; readonly roomHeight: 11.2; readonly mats: 420; readonly seats: 900; readonly source: "bldg_ec4aa7a9-f8cb-4abb-af0c-a2cef6d06dd8"; readonly read: "2026-10-22"; readonly ring: readonly [readonly [139.753281, 35.707485], readonly [139.753287, 35.707464], readonly [139.753659, 35.707456], readonly [139.753548, 35.707846], readonly [139.753502, 35.707837], readonly [139.753496, 35…
Where the Kodokan's building stands and what it is: for tests and pages that say it.
const KODOKAN_DOJO
KODOKAN_DOJO: DojoSpec
The main dojo as the district draws it: the atlas's floor and fittings, with no wood round the mats (the 4 metres the atlas draws would not stand inside the real building).
const KODOKAN_FLOOR_HEIGHT
KODOKAN_FLOOR_HEIGHT: number
The height of the main dojo's floor above the ground, in metres: the 7th floor, six storeys up at the building's own storey height (its height over its storeys, 5.4 metres), and no higher than leaves the room under the roof.
const KODOKAN_FLOOR_IDS
KODOKAN_FLOOR_IDS: readonly number[]
The floors a district can be asked for: 0 (the basement) to 8.
const KODOKAN_FLOORS
KODOKAN_FLOORS: readonly KodokanFloor[]
The floors, from the basement up. The Kodokan's floor guide (施設のご案内, docs/district.md) lists 8F to B1; its 1F entry is empty, so the 1st floor is English Wikipedia's.
const KODOKAN_ROOM_HEIGHT
KODOKAN_ROOM_HEIGHT: 11.2
How high the room stands, floor to the top of its lid, in metres: the 3D build's own figure (walls of 4.5 metres, the gallery level with their tops, the lid over it), two storeys of the building. Ours.
type KodokanFloor
interface KodokanFloor { /** 0 is the basement, 1 to 8 the floors above the ground. */ floor: number; label: { en: string; ja: string }; /** What the floor guide lists on it, in each language (a floor with no entry of its own says what a second source says, `else`). */ lists: { en: string; ja: string }; rooms: KodokanRoom[]; /** What the view draws: the `rooms` the guide counts, the `great-dojo`, its `gallery`, only…
A floor of the Kodokan International Judo Center, the new building: its label, what the Kodokan's own floor guide lists on it, what is drawn there, and where the words come from.
function kodokanLevel
kodokanLevel: (floor: number) => number
The height of a floor's level above the ground, in metres: the building's height over its storeys, for each floor under it (ours: the storeys are not all one height).
function kodokanMember
kodokanMember(language: Language, floor?: number): DistrictMember
The Kodokan as a member of a district. With a floor, it is that floor of the building: the 7th is the great dojo, the 8th its gallery, the 5th and 6th their dojos as the floor guide counts them (laid out by us), the others plain floor plates; the basement is under the ground and draws nothing. Throws for a floor that is not 0 to 8.
type KodokanRoom
interface KodokanRoom { id: string; name: { en: string; ja: string }; /** Mats, in jō: the guide's count; `null` where it gives none (the special dojo: drawn at 40 jō, ours). */ mats: number | null; /** The count the room is drawn at: the guide's, or ours where it gives none. */ drawn: number; }
A room of a floor of the Kodokan: what the Kodokan's floor guide calls it, its count of jō where the guide gives one, and whether the room is drawn from that count or is ours.
const KYOGIJO_DISTRICT_STYLE
KYOGIJO_DISTRICT_STYLE: "\n:where(.ky-district){--ky-dist-ground:#e1e4da;--ky-dist-grid:rgba(40,46,42,.16);--ky-dist-ink:#1f2320;--ky-dist-halo:rgba(255,255,255,.9);--ky-dist-people:#c2410c;--ky-dist-b0:#d1d4cb;--ky-dist-b1:#c3c7be;--ky-dist-b2:#b2b7ae;--ky-dist-b3:#9ea49b;--ky-dist-bline:rgba(40,46,42,.28);--ky-dist-road:#cbcfc4;--ky-dist-deck:#bdc2b7;--ky-dist-walk:#eef0e8;--ky-dist-rail:#8b9288;--ky-dist-gate:#1f…
The colours and the type of a district's drawing, light and dark. Defaults sit in :where(), so a page's own rule wins.
type KyogijoDistrict
interface KyogijoDistrict { readonly mode: "2d"; /** Draw again with other options (venues, fit, theme, level): the container's contents are replaced. */ update(options: DistrictOptions): void; /** Show another level of the crowd outside at once, without drawing the plan again. A district with no crowd does nothing. */ setOutside(level: OutsideLevel): void; /** What the crowd's last paint cost, in milliseconds, how …
What mountDistrict gives back.
type KyogijoRace
interface KyogijoRace<O = RaceViewOptions, V = CircuitOptions> { /** The race it plays. */ readonly race: CircuitRace; /** The 3D view, when the race is on one. */ readonly turn: KyogijoTurn<V> | undefined; /** The places in the bar for the buttons of other features (the follow camera, the sound): empty elements that show only while they hold something. */ readonly slots: ReplayBarSlots; state(): RaceState; /** The …
What mountCircuitRace gives back (and mountDistrictRace, with a district's options and 3D view).
const LANDMARK_SHAPES
LANDMARK_SHAPES: readonly LandmarkShape[]
type LandmarkShape
type LandmarkShape = "dome" | "wheel" | "fountains" | "named";
How a landmark is drawn.
function loadCircuits
loadCircuits(): Promise<void>
Read the circuits for the lean district (district-lean), which carries none until it is asked: after this a district's circuit option can name any of them. The district entry has them already. Asking again gives the same promise.
Example
``ts no-run import { loadCircuits, planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district-lean"; await loadCircuits(); planDistrict({ venues: [], circuit: "las-vegas" }); ``
function metresText
metresText: (metres: number) => string
The distance a scale says, as it is read: metres under a kilometre, else kilometres.
function mountDistrict
mountDistrict(host: HTMLElement, options: DistrictOptions): KyogijoDistrict
Mount a district's plan in a container, with the crowd outside over it when options.outside asks for one.
Example
``ts no-run import { mountDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district"; const plan = mountDistrict(document.querySelector("#city")!, { venues: ["bc-place", "rogers-arena"], outside: { level: 50 } }); plan.setOutside(100); ``
function mountDistrictRace
mountDistrictRace(host: HTMLElement, options: DistrictRaceOptions, settings?: DistrictRaceSettings): KyogijoRace<DistrictRaceOptions, DistrictOptions>
Mount a race on a district's ground in a page: the district flat (or in 3D, with its venues, its landmarks and the circuit's pit building standing) with a dot for each car on the circuit, and the race's clock, controls and timing board, as mountCircuitRace has them. It does nothing until it is played, and nothing while it is paused, hidden or out of sight; in 3D the view's turn and the race share one frame. The lean district reads the circuits first (await loadCircuits()), with the venues' records and the area round them as for any district.
Example
``ts no-run import { mountDistrictRace } from "@johnmorrisdotca/kyogijo-stadiums/district"; const race = mountDistrictRace(document.querySelector("#strip")!, { venues: ["t-mobile-arena"], circuit: "las-vegas", labels: true }, { view: "3d", speed: 10 }); race.play(); ``
function mountDistrictTurn
mountDistrictTurn(host: HTMLElement, options: DistrictOptions, settings?: DistrictTurnSettings): KyogijoTurn<DistrictOptions>
Mount a district as a 3D view in a container: the same view as mountKyogijoTurn's, with the controls, the pointer, the keys and the auto-turn of every 3D view, over the district's plan with each venue standing on it.
Example
``ts no-run import { mountDistrictTurn } from "@johnmorrisdotca/kyogijo-stadiums/district"; const view = mountDistrictTurn(document.querySelector("#city")!, { venues: ["bc-place", "rogers-arena"] }, { preset: "broadcast" }); view.set({ yaw: 40 }); ``
const OUTSIDE_DENSITY
OUTSIDE_DENSITY: 3
The most people to a square metre of walkable ground in the list at 100 percent: a crowd standing close, short of a crush.
const OUTSIDE_LEVELS
OUTSIDE_LEVELS: readonly [0, 25, 50, 75, 100]
The crowds outside there are: a share of the venues' seats, in percent.
const OUTSIDE_REACH
OUTSIDE_REACH: 60
The distance from a venue's building at which the crowd has thinned to half what it is at the wall, in metres.
const OUTSIDE_ROOM
OUTSIDE_ROOM: 160
The ground kept round the buildings for the crowd outside, in metres, when a district asks for one.
const OUTSIDE_VENUES
OUTSIDE_VENUES: readonly string[]
The ids of the venues there is a walkable mask round.
function outsideCount
outsideCount: (crowd: Pick<OutsideCrowd, "count">, level: OutsideLevel) => number
How many people of the list stand outside at a level: the list is ordered, so these are its first.
function outsideCrowd
outsideCrowd(plan: DistrictPlan): OutsideCrowd | undefined
The crowd outside a plan's venues, in the plan's frame: the people of every venue of the plan that stands on a mask (each with its seats as the plan has them), worked out once and kept. undefined where no venue of the plan has a mask. The crowd is the same list whatever level is shown: outsideCount says how many of its first people stand at a level. The district entry holds the data of every mask; the lean district holds a mask's data only after loadOutside(venues) has read it, and throws, saying so, where it is asked for a crowd before.
Example
import { planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district";
import { outsideCount, outsideCrowd } from "@johnmorrisdotca/kyogijo-stadiums/district";
const crowd = outsideCrowd(planDistrict({ venues: ["bc-place", "rogers-arena"] }))!;
console.log(crowd.venues.map((v) => `${v.key} ${v.placed}`).join(", "), outsideCount(crowd, 50));
// bc-place:cfl 54500, rogers-arena 18871 36686
type OutsideCrowd
interface OutsideCrowd { /** The mask the crowd stands on. */ mask: string; venues: { key: string; seats: number; placed: number }[]; /** The people, in order: venues interleaved, so that a prefix holds each venue's share. */ x: Float32Array; y: Float32Array; /** The index in `venues` of each person's venue. */ venue: Uint8Array; /** How many people the list holds. */ count: number; }
The people of one district, in the plan's frame: where each stands (feet, as the plan's drawing has them), which venue's crowd it is, and how many the venues' seats asked for and the walkable ground could hold.
type OutsideFrame
interface OutsideFrame { width: number; height: number; x0: number; y0: number; scale: number; }
Where the crowd's pixels lie: a buffer width by height, with (x0, y0) the plan's feet at its top left corner and scale its pixels to a foot.
type OutsideLevel
type OutsideLevel = (typeof OUTSIDE_LEVELS)[number];
function outsideLevelOf
outsideLevelOf(options: { outside?: OutsideOptions; } | undefined): OutsideLevel
The level an options object asks for: 0 when it asks for none. Throws for a level that is not one of OUTSIDE_LEVELS.
type OutsideOptions
interface OutsideOptions { /** The share of the venues' seats standing outside, in percent: 0 (the default, nobody), 25, 50, 75 or 100. */ level?: OutsideLevel; }
What can be asked of the crowd outside a district (DistrictOptions.outside). Off by default.
type OutsideStats
interface OutsideStats { people: number; /** `dots` when a person is wider than a pixel and a fifth, else `density`. */ mode: "dots" | "density"; /** Pixels stamped, counting each time a person lands on one. */ stamps: number; }
What painting a level cost and drew: for the docs and the tests to quote.
const PERSON_METRES
PERSON_METRES: 0.55
A person's width in metres.
type PlacedLandmark
interface PlacedLandmark { key: string; name: { en: string; ja: string }; shape: LandmarkShape; ring: Pt[]; at: Pt; /** Where its name stands: over its middle, or a named landmark's tallest building. */ label: Pt; height: number; width?: number; along: Pt; }
A landmark placed in a district's frame: its outline in feet (x to the right, y down the page), its middle, its height and width in feet, and for a wheel or fountains the unit direction its long way runs.
type PlacedPart
interface PlacedPart { part: DistrictPart; /** The middle of the surface, and the degrees its drawing is turned clockwise, as for the venue's own. */ at: Pt; angle: number; }
A venue placed in the district: where its surface's middle is, how far its drawing is turned, and where its building stands, all in feet in the district's frame (x to the right, y down the page).
function planDistrict
planDistrict(options: DistrictOptions): DistrictPlan
The plan of a district: each venue's surface placed where it is on the ground (the distance and the direction between middles come from the coordinates of OpenStreetMap's outlines, to a metre or so) and turned so that its long side points where it does in the world, and the frame that fits them. A venue whose orientation is not known (an arena the building gives no axis for) is placed with its rink east-west, as it is drawn alone.
Example
import { planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district";
const plan = planDistrict({ venues: ["bc-place", "rogers-arena"] });
console.log(plan.mode, plan.members.length, Math.round(plan.between[0].metres));
// neighbours 2 264
type RaceState
interface RaceState { t: number; duration: number; playing: boolean; ended: boolean; speed: number; loop: boolean; markers: boolean; labels: boolean; tower: boolean; overlay: boolean; /** What the camera follows, and whether the reader's own turn or zoom of a 3D view holds it until it is resumed. */ follow: RaceFollowMode; followHeld: boolean; motion: "smooth" | "step"; }
What a race's view is doing.
function rasterOutside
rasterOutside(crowd: OutsideCrowd, level: OutsideLevel, frame: OutsideFrame, ink: readonly [number, number, number]): { rgba: Uint8ClampedArray; stats: OutsideStats; }
The people of a crowd at a level (its first outsideCount) as RGBA bytes in a frame, in one colour with the alpha that says how many stand on each pixel. ink is [red, green, blue]. It gives the bytes and what it drew.
function scaleOf
scaleOf(view: { w: number; }): number
A length in metres worth drawing as a scale: the largest of 50, 100, 200, 500, 1000, 2000, 5000 that is not more than a fifth of the plan's width.
function unknownVenues
unknownVenues: (venues: readonly DistrictVenueInput[]) => string[]
The venues a district was asked for that the package has no key for: none when it can be drawn.
const VENUE_ATTRIBUTION
VENUE_ATTRIBUTION: "(c) OpenStreetMap contributors, ODbL 1.0, openstreetmap.org/copyright"
The credit the ODbL asks for, wherever a drawing made from OpenStreetMap's data is shown.
function venueGates
venueGates(id: string): Gate[]
The gates of a venue (bc-place, rogers-arena), each on the building's outline where a ray from the middle of the surface at its bearing meets it; empty for a venue with none. A gate whose ray misses the outline is left out (none does for the venues here: a test holds it).
Example
import { venueGates } from "@johnmorrisdotca/kyogijo-stadiums/district";
const gates = venueGates("bc-place");
console.log(gates.length, gates.filter((g) => g.basis === "documented").map((g) => g.name.en).join(", "));
// 8 Gate G
const WALK_CELL
WALK_CELL: 0.5
The side of a cell of the mask, in metres: half a metre, finer than the narrowest path and a person's width.
const WALK_IDS
WALK_IDS: readonly string[]
The districts there are masks for.
function walkable
walkable(mask: WalkMask, x: number, y: number): boolean
Whether a point (metres east and north of the mask's origin) is in a walkable cell.
type WalkData
interface WalkData { /** The raw file the data was made from, and the day it was read and the time of OpenStreetMap's data. */ source: string; read: string; base: string; licence: "ODbL-1.0"; attribution: string; /** The venues the district was made for: the keys of `VENUES` and `STADIUMS` with the configuration, as a district names them. */ venues: readonly string[]; /** The `[longitude, latitude]` the metres are m…
What a district's mask is made from, as walk.data.ts holds it: lines ([width in tenths of a metre, first point, steps...]) and areas (rings, the first the outside, in whole quarter-metres).
function walkMask
walkMask(id: string, extras: WalkExtras): WalkMask
The mask of a district, rasterised from the district's data (walk/<district>.data.ts, held by loadOutside or by the full table; and kept for the next call): the walkable areas and the paths at their width, the apron round each venue, then the carriageways, cycle tracks, railways, water and buildings cut out of them, and the venues' own buildings last. A person stands in a cell with value 1, and nowhere else.
type WalkMask
interface WalkMask { id: string; origin: LonLat; cell: number; x0: number; y0: number; width: number; height: number; cells: Uint8Array; /** How many cells are walkable. */ walkable: number; }
The grid of a mask: cells[row * width + column] is 1 where a person may stand. Cell (0, 0) has its corner at (x0, y0) metres east and north of origin.
@johnmorrisdotca/kyogijo-stadiums/district-lean
AREA_KEYS areaKeysFor Arena buildDistrictTurn CIRCUIT_INDEX circuitPointIn circuitsHeld CITYCTX_VENUES ContextArea ContextLandmark describeDistrict DISTRICT_IDS DISTRICT_MARGIN DISTRICT_MODES DistrictCircuit DistrictGate districtId districtMember DistrictMember DistrictMode DistrictOptions DistrictPart DistrictPlaced DistrictPlan districtPresets DistrictRaceDrawOptions DistrictRaceOptions DistrictRaceSettings districtRing districtTurnMarkup DistrictTurnSettings DistrictVenueInput drawDistrict drawDistrictRace frameOf Gate GATE_FACTS GATE_VENUES GateBasis GateFact gateName Ground hasOutside isDistrictId isOutsideLevel isQuality KODOKAN KODOKAN_DOJO KODOKAN_FLOOR_HEIGHT KODOKAN_FLOOR_IDS KODOKAN_FLOORS KODOKAN_ROOM_HEIGHT KodokanFloor kodokanLevel kodokanMember KodokanRoom KYOGIJO_DISTRICT_STYLE KyogijoDistrict KyogijoRace LANDMARK_SHAPES LandmarkShape loadArea loadAreasFor loadArena loadCircuits loadGround loadOutside loadPark loadStrings loadVenueDataFor metresText mountDistrict mountDistrictRace mountDistrictTurn OUTSIDE_DENSITY OUTSIDE_LEVELS OUTSIDE_REACH OUTSIDE_ROOM OUTSIDE_VENUES outsideCount outsideCrowd OutsideCrowd OutsideFrame OutsideLevel outsideLevelOf OutsideOptions OutsideStats Park PERSON_METRES PlacedLandmark PlacedPart planDistrict QUALITIES Quality QUALITY_TIERS QualityTier RaceState rasterOutside RealStadium scaleOf STADIUM_IDS stadiumById StadiumConfigId STADIUMS TOKYO_VENUES unknownVenues VENUE_ATTRIBUTION VenueDataKeys venueDataKeysFor venueGates venueName WALK_CELL WALK_IDS walkable WalkData walkMask WalkMask
const AREA_KEYS
AREA_KEYS: readonly string[]
The key of every area there is data for, in the order a district draws them: each is one file.
function areaKeysFor
areaKeysFor(venues: readonly string[], circuit?: string): string[]
The keys of the areas that go with some venues, in the order to draw them: downtown Vancouver's buildings and streets and its water, green and trees for BC Place and Rogers Arena; Seattle's SoDo for Lumen Field and T-Mobile Park, Seattle Center's for Climate Pledge Arena, and the city's own for a district that holds venues of both (they are three kilometres apart, so the detail of either would be a speck); Tokyo Dome City's for Tokyo Dome, Korakuen Hall and the Kodokan, which take it before any other; Las Vegas's for T-Mobile Arena and for the Las Vegas Strip Circuit (circuit, a district's circuit). A venue of none of these has no area.
Example
import { areaKeysFor } from "@johnmorrisdotca/kyogijo-stadiums/areas";
console.log(areaKeysFor(["bc-place:cfl", "rogers-arena"]));
// [ 'vancouver', 'vancouver-nature' ]
type Arena
type Arena = ArenaData;
An arena as the package holds it: the data, with the sizes in the unit they were published in (see arenaRinkIn and arenaCourtIn for them in feet).
function buildDistrictTurn
buildDistrictTurn(options: DistrictOptions, settings?: DistrictTurnSettings): TurnModel
A district as a 3D model: the floor is the district's flat plan with each venue's building only, and on it stands each venue as it stands on its own (turned about the middle of its surface and moved to its place in the district), with a name over each where the district has labels. A TurnModel like any other: turnMarkupOf and mountDistrictTurn make a view of it.
const CIRCUIT_INDEX
CIRCUIT_INDEX: Readonly<Record<string, { en: string; ja: string; }>>
Every circuit's key and its names in English and Japanese (Wikidata's labels), in the order of CIRCUITS.
function circuitPointIn
circuitPointIn(placed: Pick<DistrictCircuit, "at" | "angle">, p: Pt): Pt
A point of a circuit's own plan (feet, circuitPlan) where the district puts it: for a page that draws something on the lap (a race's cars) in a district's frame.
function circuitsHeld
circuitsHeld: () => boolean
Whether the circuits are held (the district entry, or the lean district after loadCircuits()).
const CITYCTX_VENUES
CITYCTX_VENUES: Readonly<{ vancouver: string[]; sodo: string[]; center: string[]; }>
The venues each area of Vancouver and Seattle is drawn round, by their ids (the part of a district's key before the colon).
type ContextArea
interface ContextArea { key: string; name: { en: string; ja: string }; /** The middle of the area, `[longitude, latitude]`: the point the rows' coordinates are measured from. */ origin: readonly [number, number]; /** How far from the middle the data reaches, in metres. */ radius: number; /** The step the coordinates and the heights are counted in, in metres (a half). */ grid: number; /** A building this tall, in met…
An area of context round a district: ONE coordinate frame (the origin, the grid step and the radius, in metres east and north of the origin) and separate layers laid in it, each with its own source and licence. A layer an area lacks is simply not drawn. The rows of each layer, all in grid steps from the origin: - buildings: the height and the rise of the roof (0 for a flat one), then the first point (east, north) and each step to the next. - streets: the kind (0 a carriageway at street level, 1 one on a viaduct or a bridge, 2 a railway, 3 a sidewalk or a path) and the width in grid steps, then the first point and each step to the next, a line. - landCover: the class (0 water, 1 green, 2 wood), then the first point and each step to the next, an outline (a hole is an outline of its own, filled even-odd). - trees: one row: the first tree's east, north and crown radius, then each next tree's step in east and north from the one before and its crown radius.
type ContextLandmark
interface ContextLandmark { key: string; /** The Wikidata item its names come from. */ wikidata: string; name: { en: string; ja: string }; shape: LandmarkShape; /** The OpenStreetMap element its outline is, `way/<id>`. */ source: string; /** Its outline, metres east and north of the area's origin. */ ring: readonly (readonly [number, number])[]; /** Its height over the ground, in metres. */ height: number; /** A dom…
A landmark of an area, as its data holds it: - dome: a sphere cut by the ground (the Sphere), width across at its widest and height tall; its outline is its footprint, and the building the area has there is the dome's own. - wheel: a big wheel standing upright along the long way of its outline (OpenStreetMap maps the High Roller's footprint), width across, its top height over the ground. - fountains: a row of jets along the long way of the water its outline is, reaching up to height (the most a published figure says they reach); the water is the area's land cover. - named: a name over the buildings inside its outline (they are the area's own, standing at their own heights), at height, the top of the tallest.
function describeDistrict
describeDistrict(options: DistrictOptions, plan?: DistrictPlan): { title: string; description: string; }
The title and the description of a district, in its language: what is drawn, where each venue stands from the first, how far apart they are, and the credit.
const DISTRICT_IDS
DISTRICT_IDS: readonly string[]
Every key a district can be asked for: the arenas of VENUES and the stadiums of STADIUMS.
const DISTRICT_MARGIN
DISTRICT_MARGIN: Readonly<Record<DistrictMode, number>>
The margin round the buildings, as a share of the longer side of the district: tight for neighbours, wide for a city's grid and names.
const DISTRICT_MODES
DISTRICT_MODES: readonly DistrictMode[]
type DistrictCircuit
interface DistrictCircuit { plan: CircuitPlan; /** Where the circuit's own origin (the middle of its plan) is in the district's frame, in feet. */ at: Pt; /** The degrees the circuit's plan is turned clockwise to lie in the district (its heading less a quarter turn, and the map's turn). */ angle: number; /** The outline of everything it draws on the ground (its plan's box), and of its pit building, in the district's…
A circuit placed in a district: its own plan (feet round its own middle, its long side along x), and where that middle is put and how far the plan is turned to lie as it does in the world.
type DistrictGate
interface DistrictGate { key: string; venue: string; name: { en: string; ja: string }; at: Pt; angle: number; basis: "documented" | "plausible"; }
A gate placed in a district: where it is on its venue's outline in the plan's frame, in feet, and the way it faces on the page, in degrees clockwise from the top.
function districtId
districtId: (options: DistrictOptions) => string
The id of a district's drawing: the option's, or a hash of the options.
function districtMember
districtMember(input: DistrictVenueInput, language?: Language, floor?: number): DistrictMember
A venue of a district, from its key: rogers-arena (an arena), bc-place or bc-place:soccer (a stadium in its first configuration or the one named). Throws for a key no venue has, and says which keys there are.
Example
import { districtMember } from "@johnmorrisdotca/kyogijo-stadiums/district";
const member = districtMember("bc-place:soccer");
console.log(member.key, member.kind, member.seats);
// bc-place:soccer stadium 52497
type DistrictMember
interface DistrictMember { /** The key of the venue and the configuration, unique in a district: `rogers-arena`, `bc-place:soccer`. */ key: string; id: string; kind: "arena" | "stadium" | "park" | "hall"; config?: StadiumConfigId; /** The name in both languages. */ name: { en: string; ja: string }; /** The building's outline, `[longitude, latitude]`. */ ring: readonly (readonly [number, number])[]; /** The middle of…
A venue of a district as the district needs it: what it is called, where it stands, how it lies, and how it is drawn.
type DistrictMode
type DistrictMode = "neighbours" | "city";
How a district is fitted: neighbours tight round venues that stand close together, city at the real distances between venues that are kilometres apart.
type DistrictOptions
interface DistrictOptions { /** The venues, by key: any key of `VENUES` (the arenas) and `STADIUMS` (the stadiums); at least one, unless the district has a `circuit`. */ venues: readonly DistrictVenueInput[]; /** * A race circuit laid on the same ground (a key of `CIRCUIT_IDS`: `las-vegas`): its lap, pit lane, ground and pit building where OpenStreetMap maps them, under the venues, turned as it lies; in 3D its pit b…
What can be asked of a district.
type DistrictPart
interface DistrictPart { key: string; options: SurfaceOptions; /** The middle of the surface, \`[longitude, latitude]\`. */ centre: readonly [number, number]; /** The compass heading of the surface's x axis, 0 to under 180. */ heading: number; /** How high its floor stands above the ground, in feet. */ elevation?: number; /** Which part of the surface's room is drawn: `room` (the floor, the walls and what stands on …
One surface of a venue that has several (DistrictMember.parts): what it is drawn from, where it stands, how it lies and how high its floor is.
type DistrictPlaced
interface DistrictPlaced { member: DistrictMember; /** The middle of the surface. */ at: Pt; /** The degrees the venue's own drawing (its field along x) is turned clockwise to lie as it does in the world. */ angle: number; /** The surfaces of the venue as the plan places them (one, unless the venue has `parts`). */ parts: PlacedPart[]; /** The building's outline. */ footprint: Pt[]; /** Its convex hull, which the de…
type DistrictPlan
interface DistrictPlan { options: DistrictOptions; mode: DistrictMode; /** The degrees the map is turned clockwise (0 has north at the top). */ turn: number; /** The way north points on the page, degrees clockwise from the top. */ north: number; members: DistrictPlaced[]; /** The buildings round the venues that the options' `context` brings, placed in the frame; `undefined` without it. */ context: ContextPlan | unde…
What a district is: its venues placed, the box that fits them, and how the map lies.
function districtPresets
districtPresets(plan: Pick<DistrictPlan, "turn">): PresetTable
The four viewpoints of a district, turned with the map: the main camera looks from the south over the district (north at the top of the page), the end-on view from the west and the low corner from the south-west.
type DistrictRaceDrawOptions
type DistrictRaceDrawOptions = DistrictRaceOptions & { t?: number };
A race on a district's ground at a moment: the district's and the race's options, and the seconds from the start (0, the grid, by default).
type DistrictRaceOptions
type DistrictRaceOptions = DistrictOptions & { circuit: string } & Omit<RaceOptions, "circuit">;
What a race on a district's ground is drawn from: the district's options, its circuit named, and the race's (seed, laps, cars).
type DistrictRaceSettings
type DistrictRaceSettings = RaceViewSettings & { turn?: DistrictTurnSettings };
How a race on a district's ground is shown and played: as a circuit's race, with the district's 3D view's settings (its viewpoint, the walls and roofs of its venues, its quality).
function districtRing
districtRing(input: DistrictVenueInput): DistrictMember["ring"]
The outline of a venue's building, as districtMember(input).ring has it, read without the venue's records: a crowd outside keeps out of every building the ground has, and the buildings of venues that are not shown need no names. Throws as districtMember does for a key no venue has.
function districtTurnMarkup
districtTurnMarkup(options: DistrictOptions, settings?: DistrictTurnSettings): string
A district as the markup of a 3D view, still until a page's script makes it turn: pure, so a server can make it.
type DistrictTurnSettings
type DistrictTurnSettings = TurnSettings;
What can be asked of a district's 3D view beyond a surface's: roof and roofOpen for every venue that has one (as venue: { roof, roofOpen } of a single venue's view).
type DistrictVenueInput
type DistrictVenueInput = string | { id: string; config?: StadiumConfigId };
A venue of a district: its key, and for a stadium the configuration it is drawn in (cfl or soccer; the first it has where none is given; a ballpark's is mlb and a hall's boxing). "bc-place:soccer" is the same as { id: "bc-place", config: "soccer" }.
function drawDistrict
drawDistrict(options: DistrictOptions, plan?: DistrictPlan, drawing?: (member: DistrictMember, index: number, part: number): string) => string
The plan of a district as one SVG: the ground, a grid and a scale, a north arrow, and each venue's own drawing (its stands, or its building only for stands: false) put where it stands and turned as it lies, with a name beside each where labels says. drawing is how each venue is drawn; the 3D view gives it the building-only floor.
Example
import { drawDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district";
const svg = drawDistrict({ venues: ["bc-place", "rogers-arena"] });
console.log(svg.includes("ky-district"), svg.includes("ky-cr-shell"));
// true true
function drawDistrictRace
drawDistrictRace(options: DistrictRaceDrawOptions, given?: CircuitRace): string
A race on a district's ground at a moment, as one SVG string: the district's plan with a dot for each car where the race has it then, on the circuit where the district lays it, in its team's colour with the position it holds written on it. The race is the simulation the options make (made-up cars, from a seed), or the one given (from a feed, raceFromFeed).
Example
import { drawDistrictRace } from "@johnmorrisdotca/kyogijo-stadiums/district";
const svg = drawDistrictRace({ venues: ["t-mobile-arena"], circuit: "las-vegas", laps: 3, cars: 6, t: 120 });
console.log(svg.match(/class="ky-ci-car"/g)!.length, svg.includes('data-circuit="las-vegas"'));
// 6 true
function frameOf
frameOf(view: { x: number; y: number; w: number; h: number; }, width: number): OutsideFrame
The frame of a buffer that covers a view box of the plan (feet) in width pixels, as high as the box's shape makes it.
type Gate
interface Gate { /** `bc-place:south`: the venue's id and the gate's. */ key: string; venue: string; id: string; name: { en: string; ja: string }; /** Where it stands on the outline, `[longitude, latitude]`. */ at: LonLat; /** The bearing of its outward normal, degrees clockwise from north: the way a queue at it runs. */ bearing: number; basis: GateBasis; read: string; }
A gate, placed on a venue's outline.
const GATE_FACTS
GATE_FACTS: Readonly<Record<string, readonly GateFact[]>>
The facts of each venue's gates. BC Place: the English Wikipedia article (revision 1372065649) says a tear in the old roof was "close to Gate G on the south side where the roof meets the top of the concrete bowl", so there is a Gate G on the south side (documented); the other seven are ours, one to each side of the building, on the street sides the brief names (Pacific Boulevard to the south, Robson and Beatty Streets). Rogers Arena: the brief's corner entrance plazas on the Pat Quinn Way side, the south front and the two south corners, and one at the north-west, all ours.
const GATE_VENUES
GATE_VENUES: readonly string[]
The ids of the venues that have gates.
type GateBasis
type GateBasis = "documented" | "plausible";
How a gate is known: documented is what a source cited with it says; plausible is ours.
type GateFact
interface GateFact { /** A key that is the same on every run: `south`, `south-west-corner`. */ id: string; /** The bearing of the gate's outward normal, degrees clockwise from north, 0 to under 360. */ bearing: number; /** The name where a source gives one (`Gate G`); a plain description of where it is otherwise. */ name?: { en: string; ja: string }; basis: GateBasis; read: string; }
What is said of a venue's gate: the way it faces, and what is read from where.
function gateName
gateName(fact: GateFact, language: "en" | "ja"): string
The name of a gate in a language: the source's where there is one, else its side (South-west gate).
type Ground
interface Ground extends Omit<GroundData, "pitch"> { /** The pitch, goal line to goal line and touchline to touchline, in metres to the centimetre. */ pitch: { length: number; width: number }; /** The unit the article published the size in; `m` for a ground at the default size. */ pitchUnit: "m" | "yd"; }
A ground, with its pitch in metres: the published size, or the international 105 by 68 m of a ground that has none.
function hasOutside
hasOutside: (plan: Pick<DistrictPlan, "members">) => boolean
Whether a plan has a crowd to show: some venue of it stands on a mask.
function isDistrictId
isDistrictId: (id: string) => boolean
Whether a key is a venue a district can place.
function isOutsideLevel
isOutsideLevel: (level: unknown) => level is OutsideLevel
Whether a number is one of the levels.
function isQuality
isQuality: (value: unknown) => value is Quality
Whether a value is one of the qualities.
const KODOKAN
KODOKAN: { readonly floorHeight: number; readonly roomHeight: 11.2; readonly mats: 420; readonly seats: 900; readonly source: "bldg_ec4aa7a9-f8cb-4abb-af0c-a2cef6d06dd8"; readonly read: "2026-10-22"; readonly ring: readonly [readonly [139.753281, 35.707485], readonly [139.753287, 35.707464], readonly [139.753659, 35.707456], readonly [139.753548, 35.707846], readonly [139.753502, 35.707837], readonly [139.753496, 35…
Where the Kodokan's building stands and what it is: for tests and pages that say it.
const KODOKAN_DOJO
KODOKAN_DOJO: DojoSpec
The main dojo as the district draws it: the atlas's floor and fittings, with no wood round the mats (the 4 metres the atlas draws would not stand inside the real building).
const KODOKAN_FLOOR_HEIGHT
KODOKAN_FLOOR_HEIGHT: number
The height of the main dojo's floor above the ground, in metres: the 7th floor, six storeys up at the building's own storey height (its height over its storeys, 5.4 metres), and no higher than leaves the room under the roof.
const KODOKAN_FLOOR_IDS
KODOKAN_FLOOR_IDS: readonly number[]
The floors a district can be asked for: 0 (the basement) to 8.
const KODOKAN_FLOORS
KODOKAN_FLOORS: readonly KodokanFloor[]
The floors, from the basement up. The Kodokan's floor guide (施設のご案内, docs/district.md) lists 8F to B1; its 1F entry is empty, so the 1st floor is English Wikipedia's.
const KODOKAN_ROOM_HEIGHT
KODOKAN_ROOM_HEIGHT: 11.2
How high the room stands, floor to the top of its lid, in metres: the 3D build's own figure (walls of 4.5 metres, the gallery level with their tops, the lid over it), two storeys of the building. Ours.
type KodokanFloor
interface KodokanFloor { /** 0 is the basement, 1 to 8 the floors above the ground. */ floor: number; label: { en: string; ja: string }; /** What the floor guide lists on it, in each language (a floor with no entry of its own says what a second source says, `else`). */ lists: { en: string; ja: string }; rooms: KodokanRoom[]; /** What the view draws: the `rooms` the guide counts, the `great-dojo`, its `gallery`, only…
A floor of the Kodokan International Judo Center, the new building: its label, what the Kodokan's own floor guide lists on it, what is drawn there, and where the words come from.
function kodokanLevel
kodokanLevel: (floor: number) => number
The height of a floor's level above the ground, in metres: the building's height over its storeys, for each floor under it (ours: the storeys are not all one height).
function kodokanMember
kodokanMember(language: Language, floor?: number): DistrictMember
The Kodokan as a member of a district. With a floor, it is that floor of the building: the 7th is the great dojo, the 8th its gallery, the 5th and 6th their dojos as the floor guide counts them (laid out by us), the others plain floor plates; the basement is under the ground and draws nothing. Throws for a floor that is not 0 to 8.
type KodokanRoom
interface KodokanRoom { id: string; name: { en: string; ja: string }; /** Mats, in jō: the guide's count; `null` where it gives none (the special dojo: drawn at 40 jō, ours). */ mats: number | null; /** The count the room is drawn at: the guide's, or ours where it gives none. */ drawn: number; }
A room of a floor of the Kodokan: what the Kodokan's floor guide calls it, its count of jō where the guide gives one, and whether the room is drawn from that count or is ours.
const KYOGIJO_DISTRICT_STYLE
KYOGIJO_DISTRICT_STYLE: "\n:where(.ky-district){--ky-dist-ground:#e1e4da;--ky-dist-grid:rgba(40,46,42,.16);--ky-dist-ink:#1f2320;--ky-dist-halo:rgba(255,255,255,.9);--ky-dist-people:#c2410c;--ky-dist-b0:#d1d4cb;--ky-dist-b1:#c3c7be;--ky-dist-b2:#b2b7ae;--ky-dist-b3:#9ea49b;--ky-dist-bline:rgba(40,46,42,.28);--ky-dist-road:#cbcfc4;--ky-dist-deck:#bdc2b7;--ky-dist-walk:#eef0e8;--ky-dist-rail:#8b9288;--ky-dist-gate:#1f…
The colours and the type of a district's drawing, light and dark. Defaults sit in :where(), so a page's own rule wins.
type KyogijoDistrict
interface KyogijoDistrict { readonly mode: "2d"; /** Draw again with other options (venues, fit, theme, level): the container's contents are replaced. */ update(options: DistrictOptions): void; /** Show another level of the crowd outside at once, without drawing the plan again. A district with no crowd does nothing. */ setOutside(level: OutsideLevel): void; /** What the crowd's last paint cost, in milliseconds, how …
What mountDistrict gives back.
type KyogijoRace
interface KyogijoRace<O = RaceViewOptions, V = CircuitOptions> { /** The race it plays. */ readonly race: CircuitRace; /** The 3D view, when the race is on one. */ readonly turn: KyogijoTurn<V> | undefined; /** The places in the bar for the buttons of other features (the follow camera, the sound): empty elements that show only while they hold something. */ readonly slots: ReplayBarSlots; state(): RaceState; /** The …
What mountCircuitRace gives back (and mountDistrictRace, with a district's options and 3D view).
const LANDMARK_SHAPES
LANDMARK_SHAPES: readonly LandmarkShape[]
type LandmarkShape
type LandmarkShape = "dome" | "wheel" | "fountains" | "named";
How a landmark is drawn.
function loadArea
loadArea(key: string): Promise<ContextArea>
One area by its key (AREA_KEYS), read from its own file the first time and kept after: asking again gives the same promise. A key that is not an area rejects, naming the keys there are.
Example
import { loadArea } from "@johnmorrisdotca/kyogijo-stadiums/areas";
const area = await loadArea("seattle-sodo");
console.log(area.key, area.radius);
function loadAreasFor
loadAreasFor(venues: readonly string[], circuit?: string): Promise<ContextArea[]>
The areas that go with some venues, for a district's context option, each read from its own file and no other: what contextFor of the cityctx entry gives, and Tokyo Dome City's too, without carrying every area's data to get them.
Example
import { loadAreasFor } from "@johnmorrisdotca/kyogijo-stadiums/areas";
import { planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district";
const venues = ["bc-place:cfl", "rogers-arena"];
const plan = planDistrict({ venues, context: await loadAreasFor(venues) });
console.log(plan.context?.attribution.en.length);
function loadArena
loadArena: (id: string) => Promise<Arena>
An arena by its key, read from its own file the first time and held for the drawing after: asking again gives the same promise. A key that is not an arena rejects, naming the keys there are.
Example
import { loadArena } from "@johnmorrisdotca/kyogijo-stadiums/venue-data";
const arena = await loadArena("rogers-arena");
console.log(arena.name, arena.city);
// Rogers Arena Vancouver
function loadCircuits
loadCircuits(): Promise<void>
Read the circuits for the lean district (district-lean), which carries none until it is asked: after this a district's circuit option can name any of them. The district entry has them already. Asking again gives the same promise.
Example
``ts no-run import { loadCircuits, planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district-lean"; await loadCircuits(); planDistrict({ venues: [], circuit: "las-vegas" }); ``
function loadGround
loadGround: (id: string) => Promise<Ground>
A ground by its key, read from its own file the first time and held for the drawing after (see loadArena).
function loadOutside
loadOutside(venues: readonly string[]): Promise<void>
The walkable ground the crowd outside some venues stands on, read from its file and held for the drawing: await it before planDistrict, drawDistrict, mountDistrict or mountDistrictTurn of the lean district with outside asked for (the district entry holds every district's data and needs no call), and the outline of each arena of the ground (the crowd keeps out of the buildings of the venues that are not shown too). It reads nothing for venues that no mask names, so a page may call it for every choice of venues; asking again reads nothing.
Example
import { loadOutside, loadVenueDataFor, outsideCrowd, planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district-lean";
const venues = ["bc-place:cfl", "rogers-arena"];
await Promise.all([loadVenueDataFor(venues), loadOutside(venues)]);
console.log(outsideCrowd(planDistrict({ venues, outside: { level: 25 } }))?.venues.length);
// 2
function loadPark
loadPark: (id: string) => Promise<Park>
A park by its key, read from its own file the first time and held for the drawing after (see loadArena).
function loadStrings
loadStrings(language: Language): Promise<void>
The words of a language, read from the file of that language (the first time) and held for the drawing: await it before the first call of the lean district that draws in the language, and again when the language changes (a language whose words are held is not read twice, and asking again gives the same promise). The entries that hold both languages need no call, and it does nothing there. A language there is no file for rejects.
Example
import { drawDistrict, loadStrings, loadVenueDataFor } from "@johnmorrisdotca/kyogijo-stadiums/district-lean";
const venues = ["rogers-arena"];
await Promise.all([loadVenueDataFor(venues), loadStrings("ja")]);
console.log(drawDistrict({ venues, language: "ja" }).includes("ロジャーズ"));
// true
function loadVenueDataFor
loadVenueDataFor(venues: readonly string[]): Promise<void>
The records of the venues a page is about to draw, each read from its own file (an arena of the NHL's real venue from its own two) and no other, and held for the drawing: what planDistrict, drawDistrict and mountDistrictTurn of the lean district read. Await it before the first call and again when the venues change; a venue whose records are held is not read twice.
Example
import { loadVenueDataFor, planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district-lean";
const venues = ["bc-place:cfl", "rogers-arena"];
await loadVenueDataFor(venues);
console.log(planDistrict({ venues }).members.length);
// 2
function metresText
metresText: (metres: number) => string
The distance a scale says, as it is read: metres under a kilometre, else kilometres.
function mountDistrict
mountDistrict(host: HTMLElement, options: DistrictOptions): KyogijoDistrict
Mount a district's plan in a container, with the crowd outside over it when options.outside asks for one.
Example
``ts no-run import { mountDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district"; const plan = mountDistrict(document.querySelector("#city")!, { venues: ["bc-place", "rogers-arena"], outside: { level: 50 } }); plan.setOutside(100); ``
function mountDistrictRace
mountDistrictRace(host: HTMLElement, options: DistrictRaceOptions, settings?: DistrictRaceSettings): KyogijoRace<DistrictRaceOptions, DistrictOptions>
Mount a race on a district's ground in a page: the district flat (or in 3D, with its venues, its landmarks and the circuit's pit building standing) with a dot for each car on the circuit, and the race's clock, controls and timing board, as mountCircuitRace has them. It does nothing until it is played, and nothing while it is paused, hidden or out of sight; in 3D the view's turn and the race share one frame. The lean district reads the circuits first (await loadCircuits()), with the venues' records and the area round them as for any district.
Example
``ts no-run import { mountDistrictRace } from "@johnmorrisdotca/kyogijo-stadiums/district"; const race = mountDistrictRace(document.querySelector("#strip")!, { venues: ["t-mobile-arena"], circuit: "las-vegas", labels: true }, { view: "3d", speed: 10 }); race.play(); ``
function mountDistrictTurn
mountDistrictTurn(host: HTMLElement, options: DistrictOptions, settings?: DistrictTurnSettings): KyogijoTurn<DistrictOptions>
Mount a district as a 3D view in a container: the same view as mountKyogijoTurn's, with the controls, the pointer, the keys and the auto-turn of every 3D view, over the district's plan with each venue standing on it.
Example
``ts no-run import { mountDistrictTurn } from "@johnmorrisdotca/kyogijo-stadiums/district"; const view = mountDistrictTurn(document.querySelector("#city")!, { venues: ["bc-place", "rogers-arena"] }, { preset: "broadcast" }); view.set({ yaw: 40 }); ``
const OUTSIDE_DENSITY
OUTSIDE_DENSITY: 3
The most people to a square metre of walkable ground in the list at 100 percent: a crowd standing close, short of a crush.
const OUTSIDE_LEVELS
OUTSIDE_LEVELS: readonly [0, 25, 50, 75, 100]
The crowds outside there are: a share of the venues' seats, in percent.
const OUTSIDE_REACH
OUTSIDE_REACH: 60
The distance from a venue's building at which the crowd has thinned to half what it is at the wall, in metres.
const OUTSIDE_ROOM
OUTSIDE_ROOM: 160
The ground kept round the buildings for the crowd outside, in metres, when a district asks for one.
const OUTSIDE_VENUES
OUTSIDE_VENUES: readonly string[]
The ids of the venues there is a walkable mask round.
function outsideCount
outsideCount: (crowd: Pick<OutsideCrowd, "count">, level: OutsideLevel) => number
How many people of the list stand outside at a level: the list is ordered, so these are its first.
function outsideCrowd
outsideCrowd(plan: DistrictPlan): OutsideCrowd | undefined
The crowd outside a plan's venues, in the plan's frame: the people of every venue of the plan that stands on a mask (each with its seats as the plan has them), worked out once and kept. undefined where no venue of the plan has a mask. The crowd is the same list whatever level is shown: outsideCount says how many of its first people stand at a level. The district entry holds the data of every mask; the lean district holds a mask's data only after loadOutside(venues) has read it, and throws, saying so, where it is asked for a crowd before.
Example
import { planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district";
import { outsideCount, outsideCrowd } from "@johnmorrisdotca/kyogijo-stadiums/district";
const crowd = outsideCrowd(planDistrict({ venues: ["bc-place", "rogers-arena"] }))!;
console.log(crowd.venues.map((v) => `${v.key} ${v.placed}`).join(", "), outsideCount(crowd, 50));
// bc-place:cfl 54500, rogers-arena 18871 36686
type OutsideCrowd
interface OutsideCrowd { /** The mask the crowd stands on. */ mask: string; venues: { key: string; seats: number; placed: number }[]; /** The people, in order: venues interleaved, so that a prefix holds each venue's share. */ x: Float32Array; y: Float32Array; /** The index in `venues` of each person's venue. */ venue: Uint8Array; /** How many people the list holds. */ count: number; }
The people of one district, in the plan's frame: where each stands (feet, as the plan's drawing has them), which venue's crowd it is, and how many the venues' seats asked for and the walkable ground could hold.
type OutsideFrame
interface OutsideFrame { width: number; height: number; x0: number; y0: number; scale: number; }
Where the crowd's pixels lie: a buffer width by height, with (x0, y0) the plan's feet at its top left corner and scale its pixels to a foot.
type OutsideLevel
type OutsideLevel = (typeof OUTSIDE_LEVELS)[number];
function outsideLevelOf
outsideLevelOf(options: { outside?: OutsideOptions; } | undefined): OutsideLevel
The level an options object asks for: 0 when it asks for none. Throws for a level that is not one of OUTSIDE_LEVELS.
type OutsideOptions
interface OutsideOptions { /** The share of the venues' seats standing outside, in percent: 0 (the default, nobody), 25, 50, 75 or 100. */ level?: OutsideLevel; }
What can be asked of the crowd outside a district (DistrictOptions.outside). Off by default.
type OutsideStats
interface OutsideStats { people: number; /** `dots` when a person is wider than a pixel and a fifth, else `density`. */ mode: "dots" | "density"; /** Pixels stamped, counting each time a person lands on one. */ stamps: number; }
What painting a level cost and drew: for the docs and the tests to quote.
type Park
interface Park extends Omit<ParkData, "points" | "unit" | "periods" | "walls"> { /** [angle from dead centre, distance in feet]. */ points: FencePoint[]; periods?: ParkPeriod[]; /** How high the fence stands along stretches of it, in feet. */ walls?: ParkWall[]; }
A ballpark, with its fence in feet.
const PERSON_METRES
PERSON_METRES: 0.55
A person's width in metres.
type PlacedLandmark
interface PlacedLandmark { key: string; name: { en: string; ja: string }; shape: LandmarkShape; ring: Pt[]; at: Pt; /** Where its name stands: over its middle, or a named landmark's tallest building. */ label: Pt; height: number; width?: number; along: Pt; }
A landmark placed in a district's frame: its outline in feet (x to the right, y down the page), its middle, its height and width in feet, and for a wheel or fountains the unit direction its long way runs.
type PlacedPart
interface PlacedPart { part: DistrictPart; /** The middle of the surface, and the degrees its drawing is turned clockwise, as for the venue's own. */ at: Pt; angle: number; }
A venue placed in the district: where its surface's middle is, how far its drawing is turned, and where its building stands, all in feet in the district's frame (x to the right, y down the page).
function planDistrict
planDistrict(options: DistrictOptions): DistrictPlan
The plan of a district: each venue's surface placed where it is on the ground (the distance and the direction between middles come from the coordinates of OpenStreetMap's outlines, to a metre or so) and turned so that its long side points where it does in the world, and the frame that fits them. A venue whose orientation is not known (an arena the building gives no axis for) is placed with its rink east-west, as it is drawn alone.
Example
import { planDistrict } from "@johnmorrisdotca/kyogijo-stadiums/district";
const plan = planDistrict({ venues: ["bc-place", "rogers-arena"] });
console.log(plan.mode, plan.members.length, Math.round(plan.between[0].metres));
// neighbours 2 264
const QUALITIES
QUALITIES: readonly Quality[]
The values a page can ask for: auto and the tiers.
type Quality
type Quality = "auto" | QualityTier;
What a view is asked for: one tier, or auto, which chooses by the frames the view makes.
const QUALITY_TIERS
QUALITY_TIERS: readonly QualityTier[]
The tiers, highest first: a step down is one place later in this list.
type QualityTier
type QualityTier = "high" | "medium" | "low";
The tiers of detail, from the most to the least.
type RaceState
interface RaceState { t: number; duration: number; playing: boolean; ended: boolean; speed: number; loop: boolean; markers: boolean; labels: boolean; tower: boolean; overlay: boolean; /** What the camera follows, and whether the reader's own turn or zoom of a 3D view holds it until it is resumed. */ follow: RaceFollowMode; followHeld: boolean; motion: "smooth" | "step"; }
What a race's view is doing.
function rasterOutside
rasterOutside(crowd: OutsideCrowd, level: OutsideLevel, frame: OutsideFrame, ink: readonly [number, number, number]): { rgba: Uint8ClampedArray; stats: OutsideStats; }
The people of a crowd at a level (its first outsideCount) as RGBA bytes in a frame, in one colour with the alpha that says how many stand on each pixel. ink is [red, green, blue]. It gives the bytes and what it drew.
type RealStadium
interface RealStadium extends RealStadiumData { osm: StadiumOsm; }
A stadium: its facts and what OpenStreetMap gave.
function scaleOf
scaleOf(view: { w: number; }): number
A length in metres worth drawing as a scale: the largest of 50, 100, 200, 500, 1000, 2000, 5000 that is not more than a fifth of the plan's width.
const STADIUM_IDS
STADIUM_IDS: readonly string[]
The keys of STADIUMS, in the order of the data.
function stadiumById
stadiumById: (id: string | undefined) => RealStadium | undefined
The stadium with a key, or undefined.
type StadiumConfigId
type StadiumConfigId = "cfl" | "nfl" | "soccer" | "mlb" | "boxing" | "nba";
The configurations of a stadium: the field the seats are counted for. cfl and nfl are the football fields of the two leagues, soccer a soccer pitch, mlb a baseball field, boxing a boxing ring in a hall, nba a basketball court in a hall (an arena that stages basketball, Barclays Center).
const STADIUMS
STADIUMS: Readonly<Record<string, RealStadium>>
The stadiums by key.
const TOKYO_VENUES
TOKYO_VENUES: readonly string[]
The venues of Tokyo Dome City, round which Project PLATEAU's buildings are drawn (the Kodokan stands a little way off, inside the area).
function unknownVenues
unknownVenues: (venues: readonly DistrictVenueInput[]) => string[]
The venues a district was asked for that the package has no key for: none when it can be drawn.
const VENUE_ATTRIBUTION
VENUE_ATTRIBUTION: "(c) OpenStreetMap contributors, ODbL 1.0, openstreetmap.org/copyright"
The credit the ODbL asks for, wherever a drawing made from OpenStreetMap's data is shown.
type VenueDataKeys
interface VenueDataKeys { arenas: string[]; parks: string[]; grounds: string[]; }
The keys of the arenas, parks and grounds whose records the drawing of some venues reads.
function venueDataKeysFor
venueDataKeysFor(venues: readonly string[]): VenueDataKeys
The records the drawing of some venues of a district reads, by kind: an arena's own, a ballpark's park, a stadium's ground, and nothing for a hall (which carries its own names) or the Kodokan. The keys are a district's (rogers-arena, bc-place:cfl).
Example
import { venueDataKeysFor } from "@johnmorrisdotca/kyogijo-stadiums/venue-data";
console.log(venueDataKeysFor(["rogers-arena", "bc-place:cfl", "t-mobile-park:mlb"]));
// {
// arenas: [ 'rogers-arena' ],
// parks: [ 't-mobile-park' ],
// grounds: [ 'bc-place' ]
// }
function venueGates
venueGates(id: string): Gate[]
The gates of a venue (bc-place, rogers-arena), each on the building's outline where a ray from the middle of the surface at its bearing meets it; empty for a venue with none. A gate whose ray misses the outline is left out (none does for the venues here: a test holds it).
Example
import { venueGates } from "@johnmorrisdotca/kyogijo-stadiums/district";
const gates = venueGates("bc-place");
console.log(gates.length, gates.filter((g) => g.basis === "documented").map((g) => g.name.en).join(", "));
// 8 Gate G
function venueName
venueName(key: string, language?: Language): string | undefined
The name of a venue of a district in a language, from the lists of names alone: no record is read, so a page can list every venue to choose from and read only the records of those chosen. It is the name districtMember(key, language).name[language] gives. undefined for a key that is not a venue of a district.
Example
import { venueName } from "@johnmorrisdotca/kyogijo-stadiums/venue-data";
console.log(venueName("rogers-arena", "en"), venueName("bc-place:cfl", "ja"));
// Rogers Arena BCプレイス
const WALK_CELL
WALK_CELL: 0.5
The side of a cell of the mask, in metres: half a metre, finer than the narrowest path and a person's width.
const WALK_IDS
WALK_IDS: readonly string[]
The districts there are masks for.
function walkable
walkable(mask: WalkMask, x: number, y: number): boolean
Whether a point (metres east and north of the mask's origin) is in a walkable cell.
type WalkData
interface WalkData { /** The raw file the data was made from, and the day it was read and the time of OpenStreetMap's data. */ source: string; read: string; base: string; licence: "ODbL-1.0"; attribution: string; /** The venues the district was made for: the keys of `VENUES` and `STADIUMS` with the configuration, as a district names them. */ venues: readonly string[]; /** The `[longitude, latitude]` the metres are m…
What a district's mask is made from, as walk.data.ts holds it: lines ([width in tenths of a metre, first point, steps...]) and areas (rings, the first the outside, in whole quarter-metres).
function walkMask
walkMask(id: string, extras: WalkExtras): WalkMask
The mask of a district, rasterised from the district's data (walk/<district>.data.ts, held by loadOutside or by the full table; and kept for the next call): the walkable areas and the paths at their width, the apron round each venue, then the carriageways, cycle tracks, railways, water and buildings cut out of them, and the venues' own buildings last. A person stands in a cell with value 1, and nowhere else.
type WalkMask
interface WalkMask { id: string; origin: LonLat; cell: number; x0: number; y0: number; width: number; height: number; cells: Uint8Array; /** How many cells are walkable. */ walkable: number; }
The grid of a mask: cells[row * width + column] is 1 where a person may stand. Cell (0, 0) has its corner at (x0, y0) metres east and north of origin.
@johnmorrisdotca/kyogijo-stadiums/charts
Ball Chart ChartOptions CURLING_COLORS CURLING_HIT_TYPES CurlingEndRecord CurlingEndScore curlingEndStats CurlingEndStats curlingFreeGuards CurlingGuardEnd CurlingGuards curlingGuardScores CurlingGuardScores curlingHammers CurlingHammerStats curlingHeat CurlingHeatOptions CurlingHeatTotals curlingInPlay CurlingInPlay curlingIsHit CurlingOptions curlingScore CurlingShot CurlingShotLine curlingShotStats CurlingShotStats CurlingSide CurlingStealStats CurlingStone CurlingStoneResult curlingStones CurlingTeamEnds CurlingTotals GoalMouth GoalMouthOptions KeyItem mlbSprayChart MlbSprayOptions MlbTotals NbaShot nbaShotChart NbaShotOptions NbaTotals NflPass nflPassChart NflPassOptions NflTotals NhlShot nhlShotMap NhlShotOptions NhlTotals passNetwork PassNetworkOptions PassNetworkPass PassNetworkTotals SoccerChart soccerGoalMouth SoccerShot soccerShotMap SoccerShotOptions SoccerTotals SplitRow splitsChart SplitsOptions SplitsTotals SwimmerSplits ZoneTotal
type Ball
interface Ball { /** Your id for the shot, written on its mark as `data-mark-id`. */ id?: string | number; x?: number | null; y?: number | null; /** A Retrosheet hit-location code in place of `x` and `y`. */ zone?: string; /** What happened: `single`, `double`, `triple`, `home run`, `out`, or the words of Statcast's `events` (`home_run`, `field_out`) or the usual short forms (`1B`, `HR`). Any other word is drawn as …
A ball in play. Give x and y in the frame, or for Retrosheet a zone (the location code, 8D).
type Chart
interface Chart<Totals = Record<string, never>> { /** The drawing's options: the sport, the layers, the language, a title and what the chart needs of the surface (the park and the season of a spray chart, the half of a pitch). Pass them to `drawKyogijo`, `drawSurface`, `mountKyogijo` or `kyogijoProps`; change any of them first if you like. */ options: SurfaceOptions; /** The layers, the same list as `options.layers`…
What every chart gives back: the layers and the drawing options to put them on, a sentence, the totals, and the ways to draw them.
type ChartOptions
interface ChartOptions { /** The language of the chart's words: its title, its key, the labels of its zones and its table. English by default. */ language?: Language; /** A prefix for the ids inside the drawing. Made from the chart when missing, so that two charts on a page do not share ids. */ id?: string; /** Draw the key (what each mark is) in the margin above the surface. On by default. */ key?: boolean; /** Dra…
The options every chart takes.
const CURLING_COLORS
CURLING_COLORS: { readonly home: "#cf2e2e"; readonly away: "#f2c230"; }
The colours of the two teams' stones, the handles' colours of a game: red and yellow.
const CURLING_HIT_TYPES
CURLING_HIT_TYPES: readonly string[]
The shot types that are hits: a stone thrown to take out another. Any other type is not a hit, unless the shot says hit.
type CurlingEndRecord
interface CurlingEndRecord { /** The number of the end, from 1. */ end: number; home: number; away: number; /** The team with the hammer, and the team that scored (`null` for a blank end). */ hammer: CurlingSide | null; scoring: CurlingSide | null; points: number; blank: boolean; /** The team without the hammer scored. */ steal: boolean; /** The team with the hammer scored exactly one point (it was forced to take on…
One end, worked out.
type CurlingEndScore
interface CurlingEndScore { home: number; away: number; hammer?: CurlingSide; }
What a team scored in an end: one team scores in an end and the other has nothing, or neither does (a blank end). hammer is the team that threw last, when the record says.
function curlingEndStats
curlingEndStats(ends: readonly CurlingEndScore[], options?: { hammer?: CurlingSide; }): CurlingEndStats
The ends of a game: for each end who scored and how many, who had the hammer, whether it was a blank end, a steal or a forced one; and for each team its hammer efficiency (points per end with the hammer), how often it scored, blanked, was held to one or was stolen from with the hammer, and how often it stole without it. Each end is what each team scored in it (one of them nothing: an end is scored by one team, so two scores in an end are an error), as a score board's ends give it; hammer is the team that threw last in the first end, or each end names its own.
Example
import { curlingEndStats } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const game = curlingEndStats(
[{ home: 2, away: 0 }, { home: 0, away: 1 }, { home: 0, away: 1 }, { home: 1, away: 0 }, { home: 0, away: 2 }],
{ hammer: "home" },
);
console.log(game.home.points, game.away.points, game.home.withHammer.efficiency, game.away.withoutHammer.steals);
// 3 4 1 1
type CurlingEndStats
interface CurlingEndStats { ends: number; /** Ends in which neither team scored. */ blanks: number; records: CurlingEndRecord[]; home: CurlingTeamEnds; away: CurlingTeamEnds; }
What curlingEndStats gives back.
function curlingFreeGuards
curlingFreeGuards(stones: readonly CurlingStone[], options?: { units?: CurlingOptions["units"]; width?: number; }): CurlingGuards
The free guards of a layout. A free guard is a stone in play that is between the tee line and the hog line and is not in the house (the free guard zone, World Curling R6 and Curling Canada Rule 12): its centre is nearer the hog line than the tee line, and no part of it is within the 12-foot circle. Stones out of play are not counted. Places are feet from the button (in units), as curlingScore takes them.
Example
import { curlingFreeGuards } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const guards = curlingFreeGuards([
{ x: 0.2, y: -11, team: "home" },
{ x: -2, y: -16, team: "away" },
{ x: 0.5, y: 0.5, team: "home" },
{ x: 3, y: -19, team: "away" },
]);
console.log(guards.home, guards.away, guards.indices);
// 1 2 [ 0, 1, 3 ]
type CurlingGuardEnd
interface CurlingGuardEnd { hammerGuards: number; otherGuards: number; hammerPoints: number; otherPoints: number; }
One end for the free guard analysis: the free guards each team had after the first four stones of the end (or whenever the caller counts them), and the points each scored.
type CurlingGuards
interface CurlingGuards { home: number; away: number; /** The places in the list given of the stones that are free guards. */ indices: number[]; /** A team that is not `home` or `away` is counted under its name. */ others: Record<string, number>; }
The free guards of a layout: how many each team has, and which stones they are.
function curlingGuardScores
curlingGuardScores(ends: readonly CurlingGuardEnd[], options?: { bands?: readonly number[]; blanks?: boolean; }): CurlingGuardScores
How many points each team scored against how many free guards each had out: the free guard analysis (does the team with the hammer score more when it has put guards out, does the team without it score more when it has?). The guards are put in bands, 0, 1-2 and 3+ by default (bands are the lowest number of each band). blanks: false leaves the blank ends out of the hammer team's averages, as a team that blanks an end has chosen to score nothing.
Example
import { curlingGuardScores } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const table = curlingGuardScores([
{ hammerGuards: 0, otherGuards: 1, hammerPoints: 1, otherPoints: 0 },
{ hammerGuards: 2, otherGuards: 0, hammerPoints: 2, otherPoints: 0 },
{ hammerGuards: 1, otherGuards: 2, hammerPoints: 0, otherPoints: 1 },
]);
console.log(table.bands.join(" "), table.hammer.map((b) => b.average ?? "-").join(" "));
// 0 1-2 3+ 1 1 -
type CurlingGuardScores
interface CurlingGuardScores { /** The names of the bands of guards: `0`, `1-2` and `3+` by default. */ bands: string[]; /** For each band of guards the hammer team had: the ends, and the average points the hammer team scored in them. */ hammer: { band: string; ends: number; average: number | null }[]; /** The same for the guards the team without the hammer had and the points it scored. */ other: { band: string; end…
What curlingGuardScores gives back.
function curlingHammers
curlingHammers(ends: readonly CurlingEndScore[], first: CurlingSide): CurlingSide[]
The team with the hammer in each end. The team that scored in an end gives up the hammer: the other team has it in the next end. After a blank end the same team keeps it. An end that names its own hammer is taken as it says, and the rule goes on from there. first is the team with the hammer in the first end.
Example
import { curlingHammers } from "@johnmorrisdotca/kyogijo-stadiums/charts";
console.log(curlingHammers([{ home: 2, away: 0 }, { home: 0, away: 0 }, { home: 0, away: 1 }, { home: 1, away: 0 }], "home"));
// [ 'home', 'away', 'away', 'home' ]
type CurlingHammerStats
interface CurlingHammerStats { /** Ends with the hammer. */ ends: number; /** Ends in which the team scored, and its points in them. */ scored: number; points: number; /** Ends it blanked (to keep the hammer), ends it was stolen from, ends it scored exactly one, two or more, and three or more. */ blanked: number; stolen: number; forced: number; multi: number; big: number; /** Points per end with the hammer, the meas…
How a team did in the ends it had the hammer.
function curlingHeat
curlingHeat(stones: readonly CurlingStone[], options?: CurlingHeatOptions): Chart<CurlingHeatTotals> & { key: KeyItem[]; }
A heat chart of the stones of many ends on a house: where they came to rest, counted into cells (heatmap, hexbin), a density (contour), the zones of the house (zones) or drawn as translucent discs in their team's colours (discs). Only stones in play are drawn, as curlingScore judges them. team keeps one team's stones, and only the free guards or the stones in the house, so that "where do the guards of the team with the hammer end up" is one call. Places are feet from the button, as for curlingStones; give the stones of every end together. The totals say how many stones were drawn, the free guards and the stones in the house for each team, and the share in each zone.
Example
import { curlingHeat } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const stones = [
{ x: 0.3, y: 0.2, team: "home" },
{ x: -1.1, y: 0.9, team: "away" },
{ x: 0.1, y: -14, team: "away" },
{ x: 2.4, y: -17, team: "home" },
{ x: 0, y: -10, team: "home" },
];
const chart = curlingHeat(stones, { only: "guards", view: "discs" });
console.log(chart.totals.drawn, chart.totals.guards, chart.totals.house);
// 3 { home: 2, away: 1 } { home: 1, away: 1 }
type CurlingHeatOptions
interface CurlingHeatOptions extends ChartOptions { /** The house the stones are at: the `left` one (the top house of a tall drawing, the default) or the `right`. */ house?: "left" | "right"; /** The unit of the stones' places: feet by default. */ units?: Unit; /** Only this team's stones. Both by default. */ team?: "home" | "away"; /** Which stones: `all` of those in play (the default), `guards` (the free guards on…
What curlingHeat takes.
type CurlingHeatTotals
interface CurlingHeatTotals { /** Stones with a place, and the stones in play among them. */ stones: number; inPlay: number; /** The stones drawn: in play, and of the team and the kind asked for. */ drawn: number; /** Of those in play, the free guards and the stones in the house, for each team. */ guards: { home: number; away: number }; house: { home: number; away: number }; /** Each zone of the house and the free g…
The numbers behind a heat chart of stones.
function curlingInPlay
curlingInPlay(layouts: readonly (readonly CurlingStone[])[], options?: { units?: CurlingOptions["units"]; width?: number; }): CurlingInPlay
The stones in play after each throw of an end, from the layout after each throw (curlingScore's rules: a stone that touches a sideline, does not come to rest beyond the hog line or has wholly crossed the back line is out). The most stones in play is the measure of how crowded an end got.
Example
import { curlingInPlay } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const end = curlingInPlay([
[{ x: 0, y: -12, team: "home" }],
[{ x: 0, y: -12, team: "home" }, { x: 1, y: 0, team: "away" }],
[{ x: 1, y: 0, team: "away" }],
]);
console.log(end.counts, end.max, end.at);
// [ 1, 2, 1 ] 2 1
type CurlingInPlay
interface CurlingInPlay { /** Stones in play in each layout, in the order given (after each throw). */ counts: number[]; /** The most stones in play at any time of the end, and the first layout that had that many. */ max: number; at: number; }
The stones in play in each layout of an end, and the most there were.
function curlingIsHit
curlingIsHit(shot: CurlingShot): boolean
True for a shot that is a hit: it says so, or its type is one of CURLING_HIT_TYPES.
type CurlingOptions
interface CurlingOptions extends ChartOptions { /** The number of the end, for the title: `6` gives "End 6". */ end?: number; /** The team that has the hammer, the last stone of the end. It is named in the summary. */ hammer?: "home" | "away"; /** The teams' names, for the summary and the stones' tooltips. */ names?: { home?: string; away?: string }; /** The house the stones are at: the `left` one (the top house of …
What curlingStones takes.
function curlingScore
curlingScore(stones: readonly CurlingStone[], options?: { units?: CurlingOptions["units"]; width?: number; }): CurlingTotals
Judge the stones of an end by the rules. A stone is out of play, and taken off the sheet, when it touches a sideline, when it does not come to rest wholly beyond the hog line, or when it has wholly crossed the back line. A stone with any part within 6 feet of the button (in or touching the house) can score; the team with the stone nearest the button scores one point for each of its stones that are nearer than every stone of the other team. Stones as near as each other are equal, and equal stones do not count: if the two nearest are of different teams and as near, the end is blank. Places are feet from the button (in units, feet by default), x across and y along.
Example
import { curlingScore } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const end = curlingScore([
{ x: 0.3, y: 0.2, team: "home" },
{ x: -1.5, y: 1, team: "home" },
{ x: 2, y: -2, team: "away" },
]);
console.log(end.scoring, end.points, end.shot);
// home 2 0
type CurlingShot
interface CurlingShot { team?: CurlingSide | (string & {}); /** The kind of shot, as the summary names it: `draw`, `take-out`, `guard`, `clearing`, `hit and roll`... */ type?: string; /** How well it was played, 0 to 4 (World Curling's scale). A shot without a score is counted in the types and left out of the percentage. */ score?: number | null; hit?: boolean; }
One shot, as a shot-by-shot summary gives it: who threw it, what kind it was, and how it was scored from 0 to 4 (4 is the perfect shot). hit says whether it was a hit, when the type does not.
type CurlingShotLine
interface CurlingShotLine { shots: number; /** Shots with a score, and the points they earned out of 4 each. */ scored: number; points: number; /** The shot percentage: the points as a percent of the most they could earn, 4 for each scored shot. */ percent: number | null; hits: number; /** Percent of the shots that were hits. */ hitRate: number | null; }
A group of shots: how many, how many were scored, and the shot percentage.
function curlingShotStats
curlingShotStats(shots: readonly CurlingShot[]): CurlingShotStats
The shots of a game, by team and by type: the shot percentage (the points earned, 0 to 4 for each shot, as a percent of 4 for each scored shot, the way World Curling's shot-by-shot summaries and broadcasts count it), the hit rate, and how often each type of shot was played. A score outside 0 to 4 is an error.
Example
import { curlingShotStats } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const shots = curlingShotStats([
{ team: "home", type: "draw", score: 4 },
{ team: "home", type: "take-out", score: 3 },
{ team: "away", type: "Hit and Roll", score: 2 },
{ team: "away", type: "guard", score: 4 },
]);
console.log(shots.percent, shots.teams.home.percent, shots.hitRate, shots.types[0].type);
// 81.3 87.5 50 draw
type CurlingShotStats
interface CurlingShotStats extends CurlingShotLine { /** For each team (as the shots name it). */ teams: Record<string, CurlingShotLine>; /** For each type of shot, most played first: the line, and its share of all the shots as a percent. */ types: (CurlingShotLine & { type: string; share: number | null })[]; /** Shots that were not scored, and shots with no place in `teams` or `types` because they name none. */ uns…
What curlingShotStats gives back.
type CurlingSide
type CurlingSide = "home" | "away";
A team of a game, as the stones and the board name them.
type CurlingStealStats
interface CurlingStealStats { ends: number; /** Ends in which it scored (stole), and its points in them. */ steals: number; points: number; /** Percent of its ends without the hammer in which it stole. */ stealRate: number | null; }
How a team did in the ends it had no hammer.
type CurlingStone
interface CurlingStone { x: number | null; y: number | null; /** The team that threw it: `home` or `away` take the two stone colours (red and yellow by default). */ team?: LayerTeam; /** Its number among its team's eight, 1 to 8, written on the stone. */ number?: number; /** The tooltip of the stone and its line in the table. Made from the team, the number and the distance when missing. */ title?: string; }
A stone at rest, as its place on the sheet: feet from the button of the house it was played to (the curling frame), x across the sheet (positive to the thrower's right) and y along it (positive towards the back line).
type CurlingStoneResult
interface CurlingStoneResult { /** The place of the stone in the list given. */ index: number; /** Its centre's distance from the button, in feet. */ distance: number; /** In play: it did not touch a sideline, and it stands wholly beyond the hog line and not wholly beyond the back line. */ inPlay: boolean; /** Any part of it is within 6 feet of the button (in or touching the house), so that it can score. */ inHouse:…
One stone as the chart judged it.
function curlingStones
curlingStones(stones: readonly CurlingStone[], options?: CurlingOptions): Chart<CurlingTotals> & { key: KeyItem[]; }
A chart of the stones of an end on the house: each stone as seen from above (grey granite and its team's handle, with its number), the stones that score ringed and the shot rock, the nearest, ringed twice, and the score of the end under the rules (curlingScore). It shows the half of the sheet from the hog line to the back line, with the free guard zone shaded, at the house on the left (the top of a tall drawing) or the right. Stones out of play are taken off, as the rules take them. layerTable and chart.table() list every stone with its distance from the button.
Example
import { curlingStones } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const chart = curlingStones(
[
{ x: 0.4, y: 0.3, team: "home", number: 8 },
{ x: -1.2, y: -0.8, team: "home", number: 6 },
{ x: 1.9, y: 1.1, team: "away", number: 7 },
{ x: 0, y: -12, team: "away", number: 3 },
],
{ end: 6, hammer: "home", names: { home: "Canada", away: "Japan" } },
);
console.log(chart.totals.points, chart.totals.scoring, chart.title);
// 2 home Curling stones, End 6
type CurlingTeamEnds
interface CurlingTeamEnds { points: number; /** Ends in which the team scored. */ endsScored: number; withHammer: CurlingHammerStats; withoutHammer: CurlingStealStats; }
One team's ends.
type CurlingTotals
interface CurlingTotals { /** Stones with a place. */ stones: number; /** In play, and out of play (removed, so not drawn). */ inPlay: number; out: number; /** The stones that score, and the points. */ counting: number; points: number; /** The team that scores, or `null` for a blank end. */ scoring: string | null; /** The shot rock's place in the list given, or `null`. */ shot: number | null; /** No one scores: no s…
The numbers behind a curling chart.
type GoalMouth
interface GoalMouth { /** The drawing as an SVG string. */ svg: string; /** The layers of the marks, in the frame of the goal (`x` across from the centre, `y` the height, in metres), if you want to draw them another way. */ layers: Layer[]; /** The shots that had a place across the goal and the ones that did not. */ placed: number; skipped: number; /** The table of the shots with their place across the goal (`x` acr…
The goal-mouth view: a small drawing of the goal frame seen from the front, with where each shot crossed the goal line.
type GoalMouthOptions
interface GoalMouthOptions { language?: Language; id?: string; /** The unit of `goalY` and `goalZ`: `m` (the default), `yd` or `ft`. */ unit?: "m" | "yd" | "ft"; /** The size of the goal in metres: the Laws' 7.32 by 2.44 by default. */ goal?: { width: number; height: number }; /** Size the marks by expected goals. On when any shot has one. */ xg?: boolean; xgMax?: number; theme?: SurfaceOptions["theme"]; style?: Sur…
The options of the goal-mouth view.
type KeyItem
interface KeyItem { /** The outcome the mark stands for (`made`, `goal`). */ outcome: string; /** What the mark is called, in the chart's language. */ label: string; shape: MarkShape; /** Drawn open (a miss, a save) and not filled. */ hollow: boolean; }
One entry of a chart's key: a mark and what it means. A chart lists its own in key.
function mlbSprayChart
mlbSprayChart(balls: readonly Ball[], options?: MlbSprayOptions): Chart<MlbTotals> & { key: KeyItem[]; }
A spray chart for baseball from batted-ball data: where each ball came down, on the ballpark of that season (park and year, past parks included, each with the fence it had then), each hit type in its own mark (a single a small circle, a double a diamond, a triple a triangle, a home run a star, an out an open circle), the balls that came down beyond the fence drawn beyond it, and if asked the spray zones (pull, centre and opposite by infield and outfield, by the side the batter bats from). Balls come as Statcast's hc_x and hc_y (mlbam), as feet from home plate (retrosheet) or as Retrosheet's hit-location codes.
Example
import { mlbSprayChart } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const chart = mlbSprayChart(
[
{ x: 125.4, y: 90, type: "single" },
{ x: 60, y: 60, type: "home_run" },
{ x: 150, y: 120, type: "field_out" },
{ zone: "8D", type: "double" },
],
{ park: "polo-grounds", year: 1915, bats: "R", zones: true },
);
console.log(chart.totals.balls, chart.totals.types["home run"], chart.options.park, chart.options.year);
console.log(chart.draw().includes("Polo Grounds"));
// 4 1 polo-grounds 1915
// true
type MlbSprayOptions
interface MlbSprayOptions extends ChartOptions { /** The frame the balls are in: `mlbam` (the default; Statcast's `hc_x` and `hc_y`), `retrosheet` (feet from home plate, or zone codes), or another frame of the field. */ from?: Frame | string; /** The ballpark: a key of `PARKS`, past parks included. The generic field when missing. */ park?: string; /** The season: a past park is drawn with the fence it had in it (`po…
What mlbSprayChart takes.
type MlbTotals
interface MlbTotals { balls: number; /** Balls by type: `single`, `double`, `triple`, `home run`, `out`, and any other word given. */ types: Record<string, number>; /** Balls that came down beyond the fence of the park in that season. */ beyondFence: number; skipped: number; /** The zones, when the chart has them: the balls in each and, for a hit rate, the hits. */ zones: ZoneTotal[]; }
The numbers behind a spray chart.
type NbaShot
interface NbaShot { /** Your id for the shot, written on its mark as `data-mark-id`. */ id?: string | number; x: number | null; y: number | null; /** True for a shot that went in. Or give `outcome`. */ made?: boolean; /** `made` or `missed`, in place of `made`. */ outcome?: "made" | "missed" | (string & {}); /** A number to carry with the shot (a distance, a value over average). */ value?: number | null; team?: Laye…
A shot as stats.nba.com's shot chart gives it: LOC_X and LOC_Y and whether it went in.
function nbaShotChart
nbaShotChart(shots: readonly NbaShot[], options?: NbaShotOptions): Chart<NbaTotals> & { key: KeyItem[]; }
A shot chart for the NBA from stats.nba.com's shot data: each shot as a mark (filled when it went in, an open x when it missed), and the six shot zones coloured by their field-goal percentage, with the percentage and made over taken written on each, a legend and a table. Give league (the league's percentage) and the zones are coloured by how far they are above or below it, on a diverging ramp.
Example
import { nbaShotChart } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const chart = nbaShotChart(
[
{ x: 0, y: 12, made: true },
{ x: -231, y: 18, made: false },
{ x: 120, y: 140, made: true },
{ x: -30, y: 70, made: true },
],
{ league: 46, minShots: 1 },
);
console.log(chart.totals.shots, chart.totals.made, chart.layers.map((layer) => layer.kind).join(" "));
console.log(chart.draw().startsWith("<svg"), chart.table().includes("Restricted area"));
// 4 3 zones points points text
// true true
type NbaShotOptions
interface NbaShotOptions extends ChartOptions { /** The frame the shots are in: `nba-stats` (the default), or another frame of the court. */ from?: Frame | string; /** The basket the shots were taken at: `right` (the default; the shot chart puts every shot at the right basket) or `left`. */ end?: "left" | "right"; /** Count the shots into the six shot zones (restricted area, in the paint, mid-range, both corner thre…
What nbaShotChart takes.
type NbaTotals
interface NbaTotals { shots: number; made: number; /** The percent that went in, one decimal, or null with no shots. */ percent: number | null; /** Rows left out for want of a place. */ skipped: number; zones: ZoneTotal[]; }
The numbers behind an NBA shot chart.
type NflPass
interface NflPass { /** Your id for the shot, written on its mark as `data-mark-id`. */ id?: string | number; /** Where the ball came down or was caught, in the frame. */ x: number | null; y: number | null; /** Where it was thrown from. With it a pass can be drawn as an arrow. */ fromX?: number | null; fromY?: number | null; /** `complete`, `incomplete`, `touchdown` or `interception`. */ outcome?: "complete" | "inco…
A pass. The destination is x and y; the passer's place is fromX and fromY when you have it.
function nflPassChart
nflPassChart(passes: readonly NflPass[], options?: NflPassOptions): Chart<NflTotals> & { key: KeyItem[]; }
A pass chart for the NFL from tracking data: where each pass came down as a mark (a completion filled, an incompletion open, a touchdown a star, an interception an x), the line of scrimmage, and the pass grid (short and deep by left, middle and right) coloured by completion percentage with the air yards of each pass in its table. The offence goes to the right whichever way direction says it went in the data.
Example
import { nflPassChart } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const chart = nflPassChart(
[
{ x: 72, y: 26, outcome: "complete" },
{ x: 88, y: 14, outcome: "incomplete" },
{ x: 104, y: 30, outcome: "touchdown" },
],
{ los: 65, minPasses: 1 },
);
console.log(chart.totals.passes, chart.totals.complete, chart.totals.airYards);
// 3 2 23
type NflPassOptions
interface NflPassOptions extends ChartOptions { /** The frame the passes are in: `nfl-tracking` (the default; yards, the end zones counted) or another frame of the field. */ from?: Frame | string; /** The line of scrimmage, in the frame's numbers along the field (60 for midfield in `nfl-tracking`). Midfield by default. */ los?: number; /** The way the offence goes in the frame's numbers: `right` (the default) or `le…
What nflPassChart takes.
type NflTotals
interface NflTotals { passes: number; complete: number; touchdowns: number; interceptions: number; /** The percent that were caught (touchdowns included), one decimal, or null with no passes. */ percent: number | null; /** The mean air yards of the passes that have a place, or null. */ airYards: number | null; skipped: number; zones: ZoneTotal[]; }
The numbers behind a pass chart.
type NhlShot
interface NhlShot { /** Your id for the shot, written on its mark as `data-mark-id`. */ id?: string | number; x: number | null; y: number | null; /** `goal`, `saved` (a shot on goal), `missed`, `blocked`, or `shot` for an attempt of no known result. */ outcome?: "goal" | "saved" | "missed" | "blocked" | "shot" | (string & {}); /** True for a goal, in place of `outcome`. */ goal?: boolean; /** The chance the shot had…
A shot as the NHL's play-by-play gives it.
function nhlShotMap
nhlShotMap(shots: readonly NhlShot[], options?: NhlShotOptions): Chart<NhlTotals> & { key: KeyItem[]; }
A shot map for the NHL from play-by-play shots: each shot a mark (a goal a star, a save an open circle, a miss an open x, a block an open triangle) sized by its chance of scoring, with an optional count of the shots into the slot zones or hexagons, a legend, a key and a table. With fold the shots at the left end are turned a half turn, so that every shot is at the right end.
Example
import { nhlShotMap } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const chart = nhlShotMap(
[
{ x: 75, y: 4, outcome: "goal", xg: 0.31 },
{ x: -60, y: -12, outcome: "saved", xg: 0.07 },
{ x: 40, y: 20, outcome: "missed", xg: 0.03 },
],
{ fold: true, zones: true },
);
console.log(chart.totals.shots, chart.totals.goals, chart.totals.xg);
console.log(chart.layers.map((layer) => layer.id).join(" "));
// 3 1 0.41
// zones shots key-marks key-text
type NhlShotOptions
interface NhlShotOptions extends ChartOptions { /** The frame the shots are in: `nhl-api` (the default), `hockeytech`, or another frame of the rink. */ from?: Frame | string; /** Turn the shots at the left end a half turn so that all of them are at the right end: one half of the rink, every shot. Off by default. */ fold?: boolean; /** `xg` sizes each mark by its chance of scoring (the area of the mark follows `xg`);…
What nhlShotMap takes.
type NhlTotals
interface NhlTotals { shots: number; goals: number; /** The sum of the shots' chances, two decimals, or null when no shot has one. */ xg: number | null; skipped: number; /** The zones, when the chart has them. */ zones: ZoneTotal[]; /** Shots and goals by team, when the shots name one. */ teams: Record<string, { shots: number; goals: number; xg: number | null }>; }
The numbers behind a hockey shot map.
function passNetwork
passNetwork(passes: readonly PassNetworkPass[], options?: PassNetworkOptions): Chart<PassNetworkTotals> & { key: KeyItem[]; }
A pass network for soccer: a node for each player at the average place of the passes he made and received, sized by touches, and a link for each pair of players, wider and darker the more passes there were between them. Links of fewer than minPasses passes (3) are left out. The numbers behind it are in totals, and table() lists the players and the links as text.
Example
import { passNetwork } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const passes = [
{ from: 4, to: 8, x: 30, y: 40, x2: 45, y2: 55, team: "home" },
{ from: 8, to: 4, x: 45, y: 55, x2: 32, y2: 42, team: "home" },
{ from: 4, to: 8, x: 31, y: 41, x2: 46, y2: 54, team: "home" },
{ from: 8, to: 9, x: 46, y: 54, x2: 70, y2: 50, team: "home" },
];
const chart = passNetwork(passes, { provider: "opta", minPasses: 2 });
console.log(chart.totals.passes, chart.totals.players, chart.totals.links, chart.totals.strongest);
// 4 3 1 { from: '4', to: '8', passes: 3 }
type PassNetworkOptions
interface PassNetworkOptions extends ChartOptions { /** The provider the passes are in (`opta`, `statsbomb`, `wyscout`, ...): the pitch is drawn in its numbers. Or a `Frame` of your own. `international` (metres) by default. */ provider?: SoccerProviderId | Frame; /** The end the passes attack, in the provider's numbers: `right` (the default) or `left`. */ attacking?: "left" | "right"; /** Leave out links of fewer pa…
What passNetwork takes.
type PassNetworkPass
type PassNetworkPass = PassDatum;
A pass of a pass network: who made it and who received it, from where to where.
type PassNetworkTotals
interface PassNetworkTotals { /** Passes counted, and rows left out for want of a passer or a receiver. */ passes: number; skipped: number; /** Players with a place, and links drawn (those of at least `minPasses` passes). */ players: number; links: number; /** The player with most touches, or null with none. */ busiest: { id: string | number; name: string; touches: number } | null; /** The link with most passes, or …
The numbers behind a pass network.
type SoccerChart
interface SoccerChart extends Chart<SoccerTotals> { /** The goal-mouth view of the shots that have `goalY` and `goalZ`: a small drawing of the goal frame, seen from the front, with where each shot crossed the goal line. */ goalMouth(options?: GoalMouthOptions): GoalMouth; }
A soccer shot map: the chart, and the goal-mouth view of the same shots.
function soccerGoalMouth
soccerGoalMouth(shots: readonly SoccerShot[], options?: GoalMouthOptions): GoalMouth
The goal-mouth view of soccer shots: a small drawing of the goal frame seen from the front (the shooter's left on the left), with where each shot crossed the goal line, across from the centre of the goal (goalY, positive to the shooter's right) and up from the ground (goalZ). A shot wide or high of the frame is drawn beside or above it; a block has no place across the goal and is left out, and the count says how many were.
Example
import { soccerGoalMouth } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const view = soccerGoalMouth([
{ x: 100, y: 40, outcome: "goal", goalY: 0.8, goalZ: 1.9, xg: 0.2 },
{ x: 90, y: 40, outcome: "missed", goalY: -4.6, goalZ: 1.2 },
{ x: 85, y: 30, outcome: "blocked" },
]);
console.log(view.placed, view.skipped, view.svg.includes("Goal mouth"));
// 2 1 true
type SoccerShot
interface SoccerShot { /** Your id for the shot, written on its mark as `data-mark-id`. */ id?: string | number; x: number | null; y: number | null; /** `goal`, `saved`, `blocked`, `missed` or `post`. */ outcome?: "goal" | "saved" | "blocked" | "missed" | "post" | (string & {}); /** True for a goal, in place of `outcome`. */ goal?: boolean; /** Expected goals, 0 to 1. */ xg?: number | null; /** Where the shot crosse…
A shot. The place is in the provider's frame; goalY and goalZ say where it crossed the goal line.
function soccerShotMap
soccerShotMap(shots: readonly SoccerShot[], options?: SoccerShotOptions): SoccerChart & { key: ReturnType<typeof keyItems>; }
A shot map for soccer: each shot on the pitch (all of it, or the half the shots attack) in a data provider's own numbers, sized by its expected goals, a goal a filled star and the rest open marks (a save a circle, a miss an x, a block a triangle, the post a diamond), with the expected-goals total, a key and a table. goalMouth() of the result is the goal-mouth view of the same shots.
Example
import { soccerShotMap } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const chart = soccerShotMap(
[
{ x: 104, y: 36, outcome: "goal", xg: 0.31, goalY: -1.2, goalZ: 0.6 },
{ x: 98, y: 50, outcome: "saved", xg: 0.08, goalY: 2.4, goalZ: 1.1 },
{ x: 90, y: 30, outcome: "missed", xg: 0.04, goalY: 5, goalZ: 0.5 },
],
{ provider: "statsbomb", half: true, goalUnit: "yd" },
);
console.log(chart.totals.shots, chart.totals.goals, chart.totals.xg, chart.options.half);
console.log(chart.goalMouth().svg.startsWith("<svg"), chart.goalMouth().placed);
// 3 1 0.43 right
// true 3
type SoccerShotOptions
interface SoccerShotOptions extends ChartOptions { /** The provider the shots are in (`opta`, `statsbomb`, `wyscout`, ...): the pitch is drawn in its numbers and the marks use them. Or a `Frame` of your own, for a pitch drawn as usual. `international` (metres) by default. */ provider?: SoccerProviderId | Frame; /** Show only the half the shots attack: `true` for the right half (the default for `attacking: "right"`),…
What soccerShotMap takes.
type SoccerTotals
interface SoccerTotals { shots: number; goals: number; /** The sum of the shots' expected goals, two decimals, or null when none has one. */ xg: number | null; skipped: number; teams: Record<string, { shots: number; goals: number; xg: number | null }>; }
The numbers behind a soccer shot map.
type SplitRow
interface SplitRow { /** The distance at which the split ends, in metres of the race. */ distance: number; /** The seconds of the split itself, and the cumulative time at its end. */ seconds: number; cumulative: number; /** Seconds per 100 m. */ pace: number; }
One split of a swimmer: the metres it covers, the seconds it took, and its pace.
function splitsChart
splitsChart(race: PoolRace, options?: SplitsOptions): Chart<SplitsTotals>
The splits of a race as a chart: pace bars in the lanes of a pool (pool.race.pace), a title, a sentence that sums it up, the numbers (totals) and an HTML table of every split for a reader who cannot see the drawing. The splits are cumulative times, one every 50 m (every 25 m in a short course pool) unless the race says another distance.
Example
import { splitsChart } from "@johnmorrisdotca/kyogijo-stadiums/charts";
const chart = splitsChart({
distance: 100,
swimmers: [
{ lane: 4, name: "A. Swimmer", splits: [25.1, 52.4] },
{ lane: 5, name: "B. Swimmer", splits: [25.6, 52.9] },
],
});
console.log(chart.totals.fastest?.name, chart.totals.fastest?.pace, chart.draw().startsWith("<svg"));
// A. Swimmer 50.2 true
type SplitsOptions
interface SplitsOptions extends ChartOptions { /** The pool: the course (`short` for 25 m), the lanes, the look of the water and the deck. */ pool?: Omit<PoolStyle, "race">; /** Write each bar's time on it. On by default. */ labels?: boolean; }
What a splits chart takes beyond a chart's own options.
type SplitsTotals
interface SplitsTotals { swimmers: number; /** The metres of the race and the metres between splits. */ distance: number; splitEvery: number; /** The swimmers' splits, in the order down the pool. */ rows: SwimmerSplits[]; /** The fastest split of the field: whose it is, which one (from 1) and its pace; undefined with no splits. */ fastest: { lane: number; name: string; split: number; seconds: number; pace: number } …
The numbers behind a splits chart.
type SwimmerSplits
interface SwimmerSplits { lane: number; name: string; splits: SplitRow[]; }
What a swimmer's splits come to.
type ZoneTotal
interface ZoneTotal { id: string; name: string; taken: number; made: number; /** The percent that went in, one decimal, or null for a zone with no shots. */ percent: number | null; }
One zone of a chart: its name, the shots in it and the share that went in.
@johnmorrisdotca/kyogijo-stadiums/replay
ActiveEvent activeEvents addDeadTime alongPool boardClock clampShot createReplay deadSeconds DeadStop DeadTimeRules describeEvent distanceAt drawFrame eventsBetween FOLLOW_LIMITS FOLLOW_MODES FollowBox followCamera FollowCamera FollowInput FollowLimits followMode FollowMode followShot FollowShot followStop followWindow formatTime frameOf HOCKEY_BLUE_LINE HOCKEY_DEAD_TIME HOCKEY_DOTS HOCKEY_PENALTY_MINUTES HOCKEY_RULES HockeyCall hockeyFaceoffDot hockeyFormation hockeyPenaltyBox hockeyPenaltyEnds hockeyPenaltyKind HockeyPenaltyKind HockeyRole HockeyServed HockeyStop HockeyStopAt hockeyStopOf interpolate isHockeyDot parseTime penaltiesAt possession Possession Progress progressOf RaceReplayOptions raceTimeline REPLAY_SPEED_RANGE REPLAY_SPEEDS replayBoard ReplayBoardState ReplayChange replayClock ReplayController ReplayEvent ReplayEventKind replayEvents ReplayFrame replayGameClock ReplayGameClock replayGameTime replayInfo replayLayers ReplayLook ReplayObject replayPenalties ReplayPenalty ReplayPeriod replayPeriods ReplayReason ReplaySettings replaySnapshot ReplaySnapshot ReplayState ReplayStoppage replayStoppages replaySummary replayTable ReplayTeam ReplayTimeline replayTimes ReplayTrail restartsBetween ServedPenalty springStep stoppageAt trails zoomFor
type ActiveEvent
interface ActiveEvent { /** Its place in the timeline's `events`. */ index: number; event: ReplayEvent; x?: number; y?: number; x2?: number; y2?: number; }
An event that is on the surface now, with its places worked out.
function activeEvents
activeEvents(timeline: ReplayTimeline, t: number, hold?: number, smooth?: boolean | number): ActiveEvent[]
The events that are on the surface at a time: from the moment of each until hold seconds after it ends (3 by default), with their places worked out.
Example
import { activeEvents } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const ball = { id: "ball", team: "ball" as const, x: 10, y: 10 };
const timeline = { frames: [{ t: 0, objects: [ball] }, { t: 10, objects: [ball] }], events: [{ t: 4, kind: "goal", team: "home" as const }] };
console.log(activeEvents(timeline, 3).length, activeEvents(timeline, 5).map((a) => a.event.kind).join(), activeEvents(timeline, 9).length);
// 0 goal 0
function addDeadTime
addDeadTime(timeline: ReplayTimeline, stops: readonly DeadStop[], rules: DeadTimeRules): ReplayTimeline
Write stoppages into a timeline. The timeline given has each stoppage as an instant: the play up to t, then at until the restart (the players in their places, the puck on the dot). Each is opened into the dead time the rules give: the puck stays where it stopped for a moment and is then out of sight, the players stand a moment (a goal is celebrated) and then go to their places at the rules' speed or slower (all getting there together, the farthest at the rules' speed), a player going off goes to the bench and the one coming on comes from it, and they stand in their places a moment before the restart. Everything after is moved on by the dead time; the periods with it (each keeps its length on the game clock), the events, the stoppages already there and the penalties. Pure.
function alongPool
alongPool(d: number, length: number): number
The place along the pool, in metres from the starting wall, of a swimmer who has swum d metres in a pool of length: down the first length, back the next.
function boardClock
boardClock(seconds: number): string
Seconds on a board's clock, 19:20. A board has two digits of minutes, so more than 99:59 is shown as 99:59.
function clampShot
clampShot(shot: FollowShot, box: FollowBox, maxZoom?: number): FollowShot
A shot held to the limits: its zoom from 1 to maxZoom, and its frame on the surface (the middle moved in until no side of the frame is off it).
function createReplay
createReplay(timeline: ReplayTimeline, settings?: ReplaySettings): ReplayController
The controller of a replay: a state machine over a timeline's clock. It plays, pauses, seeks, steps by a frame, changes speed, loops, and says which events went by in each move so that they can be announced. It never reads a clock or the page: advance(seconds) is how time passes.
Example
import { createReplay } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const frames = [0, 1, 2, 3, 4].map((t) => ({ t, objects: [{ id: "ball", team: "ball" as const, x: t * 10, y: 0 }] }));
const replay = createReplay({ frames, events: [{ t: 2, kind: "goal" }] }, { speed: 2 });
replay.play();
replay.advance(1.5);
console.log(replay.state().t, replay.state().playing);
replay.advance(5);
console.log(replay.state().t, replay.state().playing, replay.state().ended);
// 3 true
// 4 false true
function deadSeconds
deadSeconds(timeline: ReplayTimeline, from: number, to: number): number
The seconds of a span of the timeline's clock that were dead: the parts of it in stoppages.
type DeadStop
interface DeadStop { t: number; /** The time on the timeline given of the restart's frame: `t` and `until` are moved apart by the dead time, what was between them is left out, and the instant between them becomes part of the stoppage. 0.04 seconds after `t` by default. */ until?: number; reason: string; /** Where play starts again. */ x?: number; y?: number; team?: "home" | "away"; }
A stoppage to write into a timeline: play stops at t; the timeline's frames from until on (the players in their places, the puck on the dot) are the restart.
type DeadTimeRules
interface DeadTimeRules { /** The fastest a player goes to his place, in the timeline's units a second. */ speed: number; /** Seconds after play stops before anyone heads for the restart: a goal is celebrated, a whistle is a moment. */ pause(reason: string): number; /** Seconds after play stops that the dead ball or puck is still seen where it stopped; then it is out of sight until the restart. */ shown(reason: stri…
How a sport's dead time goes: the speed the players go at and how long each part lasts, by the reason for the stoppage.
function describeEvent
describeEvent(event: ReplayEvent, language?: Language, start?: number): string
What is said of an event, for a live region and a tooltip: its label, else the word for its kind and its team, then the time.
Example
import { describeEvent } from "@johnmorrisdotca/kyogijo-stadiums/replay";
console.log(describeEvent({ t: 72, kind: "goal", team: "home" }));
console.log(describeEvent({ t: 72, kind: "goal", team: "home" }, "ja"));
// Goal, home, 1:12
// ホームのゴール、1分12秒
function distanceAt
distanceAt(progress: Progress, t: number): number
The metres a swimmer has swum t seconds after the signal, by straight lines between the points of progress; before the reaction it is 0, after the last it stays.
function drawFrame
drawFrame(options: SurfaceOptions | ScoreOptions, timeline: ReplayTimeline, t: number, look?: ReplayLook): string
One frame of a replay as an SVG string: the drawing drawKyogijo makes of options, with the players, their numbers, the ball and its trail, and the events that are on the surface at t, laid on it as data layers. The same options, timeline and time always give the same string. Without an id the drawing's ids come from the options and the timeline, not from the time, so that every frame of a replay has the same ids.
Example
import { drawFrame } from "@johnmorrisdotca/kyogijo-stadiums/replay";
import type { ReplayTimeline } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const timeline: ReplayTimeline = {
from: "nhl-api",
frames: [0, 1, 2].map((t) => ({ t, objects: [
{ id: "h1", team: "home", number: 9, x: 10 + t * 12, y: 5 },
{ id: "a1", team: "away", number: 4, x: 40 - t * 5, y: -8 },
{ id: "puck", team: "puck", x: 10 + t * 12, y: 5 },
] })),
events: [{ t: 2, kind: "goal", team: "home", x: 34, y: 5 }],
};
const svg = drawFrame({ sport: "nhl" }, timeline, 1.5);
console.log(svg.startsWith("<svg"), svg === drawFrame({ sport: "nhl" }, timeline, 1.5), svg.includes("Shirt numbers"));
// true true true
function eventsBetween
eventsBetween(timeline: ReplayTimeline, from: number, to: number): ReplayEvent[]
The events with a time in (from, to], for the live region: what went by while the clock moved from from to to.
const FOLLOW_LIMITS
FOLLOW_LIMITS: Readonly<FollowLimits>
The camera's limits by default: no closer than two and a half times, the puck followed at twice, the five nearest players, settling in about a second and a half.
const FOLLOW_MODES
FOLLOW_MODES: readonly FollowMode[]
The modes, in the order the controls list them after "off".
type FollowBox
interface FollowBox { x: number; y: number; w: number; h: number; }
A rectangle in the drawing's own feet.
function followCamera
followCamera(limits?: Partial<FollowLimits>): FollowCamera
The camera that follows the play: it eases toward followShot with a critically damped spring on the middle and on the zoom (the zoom eased as its logarithm, so a zoom in and a zoom out take the same time), holds still while the shot moves less than a dead zone, and is kept on the surface, never closer than the limit, with the puck inside the frame. When the play is still it comes to rest and stays exactly there.
Example
import { followCamera } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const camera = followCamera();
const input = { box: { x: 0, y: 0, w: 200, h: 85 }, objects: [{ team: "puck" as const, x: 180, y: 40 }] };
const first = camera.update("puck", input, 1 / 60);
let shot = first;
for (let i = 0; i < 600; i += 1) shot = camera.update("puck", input, 1 / 60);
console.log(first.zoom < 1.01, shot);
// true { x: 150, y: 40, zoom: 2 }
type FollowCamera
interface FollowCamera { /** Move toward the shot the play asks for: by `dt` seconds of the spring, or at once (`dt` undefined). Gives where it is now. */ update(mode: FollowMode, input: FollowInput, dt?: number): FollowShot; /** Where it is now. */ shot(): FollowShot | undefined; /** Whether it is at rest on the whole surface: `off`, and nothing left to ease back. */ resting(): boolean; /** Forget where it was: the…
What followCamera gives back.
type FollowInput
interface FollowInput { objects: readonly Pick<ReplayObject, "team" | "x" | "y">[]; box: FollowBox; /** The faceoff dot while the play is stopped (see `followStop`): the camera goes there. */ stop?: readonly [number, number]; }
What the shot is worked out from at a moment: the objects in the drawing's feet, the surface, and the faceoff dot when the play is stopped.
type FollowLimits
interface FollowLimits { /** The closest the camera comes: the frame is never smaller than the surface over this. */ maxZoom: number; /** The zoom of `puck`. */ puckZoom: number; /** How many of the players nearest the puck the action is framed round. */ near: number; /** The room left round the action, a share of the surface's length on each side. */ pad: number; /** A move of the shot smaller than this share of th…
How the camera frames and moves. Shares are of the surface's length (its longer side).
function followMode
followMode: (value: unknown) => FollowMode
A mode from anything: action and puck are themselves, everything else is off.
type FollowMode
type FollowMode = "off" | "action" | "puck";
What the camera follows: nothing (the whole surface), the action (the players near the puck or ball, and it), or the puck or ball alone.
function followShot
followShot(mode: FollowMode, input: FollowInput, limits?: Partial<FollowLimits>): FollowShot
The shot the play asks for at a moment. action frames the puck (or the ball) and the near players nearest it, with pad round them, never closer than maxZoom: when they bunch at one end it closes in, and when they spread it pulls back. puck puts the puck in the middle at puckZoom. A stopped play (stop) frames the faceoff dot as closely as the limits allow. The frame is always on the surface and always holds the puck. Without a puck the action is the players' middle; with nothing at all it is the whole surface.
Example
import { followShot } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const box = { x: 0, y: 0, w: 200, h: 85 };
const objects = [{ team: "puck" as const, x: 170, y: 40 }, { team: "home" as const, x: 165, y: 30 }, { team: "away" as const, x: 175, y: 50 }];
const action = followShot("action", { objects, box });
console.log(Math.round(action.x), action.y, Math.round(action.zoom * 100) / 100);
console.log(followShot("puck", { objects, box }));
// 148 40 1.93
// { x: 150, y: 40, zoom: 2 }
type FollowShot
interface FollowShot { x: number; y: number; zoom: number; }
Where the camera looks: the middle of the frame, in the drawing's feet, and how much it magnifies the surface (1 is the whole of it: the frame is the surface's size over zoom).
function followStop
followStop(timeline: ReplayTimeline, t: number): [number, number] | undefined
The faceoff dot, in the timeline's frame, while the play is stopped at t: from a whistle or a goal until the next faceoff event that has a place (x and y), the place of that faceoff. undefined while the play goes on, and always for a timeline with no faceoff events: the camera then follows the puck through the stoppage as at any other time.
Example
import { followStop } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const timeline = { frames: [{ t: 0, objects: [] }, { t: 30, objects: [] }], events: [{ t: 10, kind: "whistle" }, { t: 20, kind: "faceoff", x: 69, y: 22 }] };
console.log(followStop(timeline, 5), followStop(timeline, 15), followStop(timeline, 25));
// undefined [ 69, 22 ] undefined
function followWindow
followWindow(shot: FollowShot, box: FollowBox, view: FollowBox, map?: (p: [number, number]): [number, number], maxZoom?: number) => FollowBox
The part of a flat drawing to show for a shot: a rectangle in the drawing's viewBox units, of the viewBox's shape, round the shot's middle, inside the viewBox, and never smaller than the shot's frame. map takes a point of the surface's frame to the viewBox's (a surface laid tall is turned a quarter in its drawing).
Example
import { followWindow } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const box = { x: 0, y: 0, w: 200, h: 85 };
const view = { x: -8, y: -8, w: 216, h: 101 };
console.log(followWindow({ x: 100, y: 42.5, zoom: 1 }, box, view));
console.log(followWindow({ x: 160, y: 42.5, zoom: 2.5 }, box, view));
// { x: -8, y: -8, w: 216, h: 101 }
// { x: 120, y: 23.8, w: 80, h: 37.41 }
function formatTime
formatTime(seconds: number): string
A time in seconds as swimming writes it, to the hundredth: 26.12, 1:46.91, 14:31.02. A time that rounds to the next minute carries into it.
Example
import { formatTime } from "@johnmorrisdotca/kyogijo-stadiums/replay";
console.log(formatTime(26.121), formatTime(106.9), formatTime(59.996));
// 26.12 1:46.90 1:00.00
function frameOf
frameOf: (shot: FollowShot, box: FollowBox) => FollowBox
The frame a shot shows: the surface's size over the zoom, round the middle.
const HOCKEY_BLUE_LINE
HOCKEY_BLUE_LINE: 25
The blue lines are 25 feet either side of centre: past one, play is in an end zone.
const HOCKEY_DEAD_TIME
HOCKEY_DEAD_TIME: { readonly speed: 18; readonly pause: { readonly goal: 2.5; readonly other: 0.6; }; readonly shown: { readonly goal: 2.5; readonly other: 1.2; }; readonly least: 2; readonly hold: 1; readonly lineUp: 1.5; readonly bench: Record<"home" | "away", readonly [number, number]>; }
The speeds and seconds of hockey's dead time in a replay, and where each side's bench is.
const HOCKEY_DOTS
HOCKEY_DOTS: readonly (readonly [number, number])[]
The nine face-off spots, feet from centre ice (NHL Rule 1.9): centre, the four in the neutral zone (5 feet outside the blue lines, 44 feet apart) and the four in the end zones (20 feet out from the goal lines, 44 feet apart).
const HOCKEY_PENALTY_MINUTES
HOCKEY_PENALTY_MINUTES: { readonly minor: 2; readonly "bench-minor": 2; readonly "double-minor": 4; readonly major: 5; readonly misconduct: 10; }
The kinds of penalty, and their minutes on the game clock (NHL Rules 16 to 21: a minor 2, a double minor 4, a major 5, a misconduct 10; a bench minor is a minor served by a player the coach names).
const HOCKEY_RULES
HOCKEY_RULES: DeadTimeRules
Hockey's dead time as addDeadTime reads it: the puck is the dead one, and a player going off or coming on goes by his side's bench.
type HockeyCall
interface HockeyCall { team: "home" | "away"; kind: HockeyPenaltyKind; at: number; }
A call of a penalty, on the game clock: when (seconds of game played since the start), against which side, what kind.
function hockeyFaceoffDot
hockeyFaceoffDot(stop: HockeyStopAt): readonly [number, number]
The face-off spot play starts again at after a stoppage, by NHL rule: centre ice after a goal and at the start of a period; after a save or a frozen puck, the end-zone spot of that end on the side the puck was (the nearest spot in the zone); after icing and after a penalty, an end-zone spot of the end the offending side defends (Rules 81 and 76); after offside, the neutral-zone spot just outside the zone the offending side attacks (Rule 83); after any other whistle, the nearest spot in the zone where play stopped (an end-zone spot in an end, a neutral-zone spot between the blue lines, never centre ice). An end-zone spot's side is the side of the rink the puck was on.
Example
import { hockeyFaceoffDot } from "@johnmorrisdotca/kyogijo-stadiums/replay";
console.log(hockeyFaceoffDot({ reason: "goal", x: 88, y: 2 }).join(), hockeyFaceoffDot({ reason: "save", x: 60, y: -18 }).join());
console.log(hockeyFaceoffDot({ reason: "icing", x: 80, y: 30, defends: -1 }).join(), hockeyFaceoffDot({ reason: "offside", x: 26, y: 5, defends: -1 }).join());
// 0,0 69,-22
// -69,22 20,22
function hockeyFormation
hockeyFormation(dot: readonly [number, number], attacks: 1 | -1): Record<HockeyRole, [number, number]>
Where a side lines up for a face-off at a spot (NHL Rule 76), as [x, y] in feet from centre ice: attacks is the end it attacks (1 for the right). The centre stands on the dot a step back on his own side; the wingers on their own side of the circle's hash marks, outside it; the defence behind them (at the blue line when the spot is in the end the side attacks, in front of its own net when it is in its own end, a stride back from the wingers at centre and in the neutral zone); the goaltender in the crease. A left winger is on the left of a player facing the end his side attacks.
Example
import { hockeyFormation } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const at = hockeyFormation([0, 0], 1);
console.log(at.C.join(), at.LW.join(), at.G.join());
// -2.5,0 -5,17 -85,0
function hockeyPenaltyBox
hockeyPenaltyBox(team: "home" | "away"): readonly [number, number]
Where a side's penalty box is, the seat its penalized player sits on, in the nhl-api frame: across the ice from the players' benches (NHL Rule 1: the two penalty boxes on the side opposite the benches, one each side of the off-ice officials' box at centre), the home side's on the left, behind the boards. A stand-in for the rink's own figures (the benches and boxes of the rink, KYOGIJO- STADIUMS-47) until they are in the package: then this reads them, and nothing that calls it changes.
function hockeyPenaltyEnds
hockeyPenaltyEnds(calls: readonly HockeyCall[], goals: readonly { team: "home" | "away"; at: number; }[]): HockeyServed[]
How a game's penalties are served, by NHL rule, all on the game clock (seconds played since the start): each penalty's player sits from the call; a minor is 2 minutes, a double minor 4, a major 5 and a misconduct 10; his side plays a skater short (not for a misconduct, served by a substitute, nor for coincidental penalties, called on both sides at once and as many each, which leave the strength even); a side is never more than two short, so a third penalty's time waits for one of the first two to end; a goal by the side with more skaters ends the scored-on side's minor with the least time left (a double minor loses the part it is in; a major is served in full). Pure.
Example
import { hockeyPenaltyEnds } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const calls = [{ team: "away" as const, kind: "minor" as const, at: 100 }, { team: "home" as const, kind: "major" as const, at: 400 }];
const goals = [{ team: "home" as const, at: 160 }, { team: "away" as const, at: 500 }];
console.log(hockeyPenaltyEnds(calls, goals).map((s) => `${s.from}-${s.to} ${s.short} ${s.byGoal}`).join(", "));
// 100-160 true true, 400-700 true false
function hockeyPenaltyKind
hockeyPenaltyKind(typeCode?: string, duration?: number): HockeyPenaltyKind | undefined
The kind of a penalty of an NHL-style play-by-play (details.typeCode and details.duration of a penalty): MIN a minor (4 minutes of it a double minor), BEN a bench minor, MAJ a major, MIS and GMIS a misconduct; else by its minutes. undefined for a penalty shot or a match penalty, which this rule set does not play.
Example
import { hockeyPenaltyKind } from "@johnmorrisdotca/kyogijo-stadiums/replay";
console.log(hockeyPenaltyKind("MIN", 2), hockeyPenaltyKind("MIN", 4), hockeyPenaltyKind("BEN", 2), hockeyPenaltyKind("MAJ", 5), hockeyPenaltyKind("MIS", 10), hockeyPenaltyKind("PS", 0));
// minor double-minor bench-minor major misconduct undefined
type HockeyPenaltyKind
type HockeyPenaltyKind = keyof typeof HOCKEY_PENALTY_MINUTES;
type HockeyRole
type HockeyRole = "C" | "LW" | "RW" | "LD" | "RD" | "G";
The places of a face-off's line-up.
type HockeyServed
interface HockeyServed { /** When its time begins: the call, or, for a side already two short, when one of those ends (it never plays with fewer than three skaters). */ from: number; /** When the player leaves the box: his time ran out, or a power-play goal ended his minor. */ to: number; short: boolean; /** Ended by a power-play goal. */ byGoal: boolean; }
When a penalty's time begins and ends on the game clock, and whether its side plays short.
type HockeyStop
type HockeyStop = "goal" | "save" | "frozen" | "icing" | "offside" | "penalty" | "whistle" | "period-start" | "period-end";
Why play stopped, in hockey: each says where it starts again.
type HockeyStopAt
interface HockeyStopAt { reason: HockeyStop | string; /** Where play stopped: the puck's place, or for a save the place the shot came from. Centre ice when not given. */ x?: number; y?: number; /** For icing, offside and a penalty: the end the side it was called against defends, as the sign of its goal line's x (-1 for the left end, 1 for the right). */ defends?: 1 | -1; }
Where play stopped and why, to say where it starts again.
function hockeyStopOf
hockeyStopOf(typeDescKey: string, reason?: string): HockeyStop | undefined
The stoppage a play of an NHL-style play-by-play is (typeDescKey and, for a stoppage, details.reason): goal, penalty, the rule set's word for the stoppage's reason, or undefined for a play that does not stop play (a shot, a hit, a delayed penalty, which play goes on through until the side it is against touches the puck).
Example
import { hockeyStopOf } from "@johnmorrisdotca/kyogijo-stadiums/replay";
console.log(hockeyStopOf("stoppage", "icing"), hockeyStopOf("stoppage", "puck-in-netting"), hockeyStopOf("goal"), hockeyStopOf("delayed-penalty"));
// icing whistle goal undefined
function interpolate
interpolate(timeline: ReplayTimeline, t: number, options?: { smooth?: boolean | number; }): ReplayObject[]
Where everything is at a time: each object of the frame at or before t placed between that frame and the next, in a straight line or, with smooth, along a curve through the frames. An object in both frames moves; one only in the earlier frame stays put until the next; one only in the later frame appears when its frame comes. t is held to the first and last moments. The objects keep the order of their first appearance.
Example
import { interpolate } from "@johnmorrisdotca/kyogijo-stadiums/replay";
import type { ReplayTimeline } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const timeline: ReplayTimeline = { frames: [
{ t: 0, objects: [{ id: "ball", team: "ball", x: 100, y: 40 }] },
{ t: 2, objects: [{ id: "ball", team: "ball", x: 140, y: 20 }] },
] };
console.log(interpolate(timeline, 0.5).map((o) => `${o.id} ${o.x} ${o.y}`).join());
// ball 110 35
function isHockeyDot
isHockeyDot: (x: number, y: number) => boolean
Is a place one of the nine face-off spots (to a tenth of a foot)?
function parseTime
parseTime(value: unknown): number | undefined
A time in seconds from a number or from text: 26.12, "26.12", "1:46.91". undefined when it is neither.
function penaltiesAt
penaltiesAt(timeline: ReplayTimeline, t: number): { served: ServedPenalty[]; strength: [number, number]; }
The penalties being served at t (the player is in the box: from the call to his end) with the game seconds left of each, and each side's skaters on the ice: five, less one for each penalty that makes it play short, never fewer than three. A penalty's time left is the game clock from now to its end (it runs only while the game clock does), or, with no end or one a power-play goal brought early (endedBy: "goal"), its minutes from the drop after the call. Pure.
Example
import { penaltiesAt } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const timeline = {
frames: [{ t: 0, objects: [] }, { t: 60, objects: [] }],
periods: [{ start: 0, end: 60, length: 1200 }],
penalties: [{ team: "away" as const, by: "a4", start: 10, end: 16, minutes: 2 }],
};
const at = penaltiesAt(timeline, 12);
console.log(at.strength, at.served.map((s) => `${s.penalty.by} ${s.left}`), penaltiesAt(timeline, 16).strength);
// [ 5, 4 ] [ 'a4 80' ] [ 5, 5 ]
function possession
possession(timeline: ReplayTimeline, t: number): Possession | undefined
Who has the ball at a time, when the data says: the possession of the latest frame at or before t that has one. undefined when no frame says, or when the latest says nobody does (null).
Example
import { possession } from "@johnmorrisdotca/kyogijo-stadiums/replay";
import type { ReplayTimeline } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const timeline: ReplayTimeline = { frames: [
{ t: 0, possession: "h7", objects: [{ id: "h7", team: "home", x: 1, y: 1 }, { id: "ball", team: "ball", x: 1, y: 1 }] },
{ t: 1, possession: null, objects: [{ id: "h7", team: "home", x: 2, y: 1 }, { id: "ball", team: "ball", x: 5, y: 1 }] },
] };
console.log(possession(timeline, 0.5), possession(timeline, 1));
// { holder: 'h7', team: 'home' } undefined
type Possession
interface Possession { holder?: string; team?: "home" | "away"; }
Who has the ball, when the data says.
type Progress
interface Progress { /** Distance in metres against the seconds after the signal; the first point is the reaction time at 0 m. */ points: [number, number][]; /** Whether the swimmer is a swimmer in the water at all (a swimmer who did not start stays on the block). */ swims: boolean; }
The marks of a swimmer's progress: the seconds after the start signal at which the swimmer has swum each distance, from the splits (and the final time).
function progressOf
progressOf(row: RaceRow, distance: number, every: number, reaction: number): Progress
The progress of one row over a race of distance metres with a split every every metres.
type RaceReplayOptions
interface RaceReplayOptions { /** Frames a second. 10 by default. */ fps?: number; /** Seconds of waiting before the start signal and of staying on after the last touch. 1.5 and 3 by default. */ lead?: number; tail?: number; /** The language of the events' words. English by default. */ language?: Language; /** The reaction time of a swimmer that has none, in seconds. 0.7 by default. */ reaction?: number; /** How far…
What a race replay is made with.
function raceTimeline
raceTimeline(options: Pick<SurfaceOptions, "pool">, replay?: RaceReplayOptions): ReplayTimeline & { events: ReplayEvent[]; }
The replay of a race by lane. Give the options of a swimming drawing ({ pool: { race } }, with a course and lanes if they are not the 50 m pool's of eight): each swimmer with splits is played back from them. The timeline is in the pool's frame (from: "swimming") in metres; its events are the turns at the walls and the finish, each with the swimmer's name and, at the finish, the time.
Example
import { raceTimeline, drawFrame } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const pool = { race: { distance: 100, swimmers: [{ lane: 4, name: "A. Swimmer", splits: [26, 54.2] }, { lane: 5, name: "B. Swimmer", splits: [26.4, 55] }] } };
const timeline = raceTimeline({ pool });
console.log(timeline.frames.length > 100, timeline.events.map((e) => e.kind).join(), drawFrame({ sport: "swimming", pool }, timeline, 20).startsWith("<svg"));
// true start,turn,turn,finish,finish true
const REPLAY_SPEED_RANGE
REPLAY_SPEED_RANGE: readonly [number, number]
The slowest and the fastest speed of play.
const REPLAY_SPEEDS
REPLAY_SPEEDS: readonly number[]
The speeds the controls offer. Any speed from the least to the greatest is allowed.
function replayBoard
replayBoard(timeline: ReplayTimeline, t: number): ReplayBoardState
The scoreboard of a replay at a time t, in seconds on the timeline's clock. The score is the goals at or before it; the period and the clock are the game clock's (replayGameClock): the clock runs through the period from its full length to nothing, or from nothing up when the timeline counts up, and stands still in a stoppage. A period with a length of its own runs its clock through that many seconds however long it lasts on the timeline, so a game re-timed to minutes can read like the real one. A timeline with penalties adds each side's strength and the penalties being served, with their time left (penaltiesAt).
Example
import { replayBoard } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const frames = [0, 60, 120].map((t) => ({ t, objects: [{ id: "puck", team: "puck" as const, x: 0, y: 0 }] }));
const timeline = {
frames,
events: [{ t: 30, kind: "goal", team: "home" as const }],
periods: [{ start: 0, end: 60, length: 1200 }, { start: 60, end: 120, length: 1200 }],
};
const at = (t: number) => JSON.stringify(replayBoard(timeline, t));
console.log(at(0));
console.log(at(30));
console.log(at(90));
// {"score":[0,0],"period":1,"clock":"20:00"}
// {"score":[1,0],"period":1,"clock":"10:00"}
// {"score":[1,0],"period":2,"clock":"10:00"}
type ReplayBoardState
interface ReplayBoardState { /** The goals so far: the events of kind `goal` at or before the time, by `team`. */ score: [number, number]; /** The period's number, or `undefined` when the timeline has no periods. */ period?: number; /** The game clock as it is written, `19:20`: the time left in the period, or the time gone when the timeline counts `up`. Whole seconds, so it changes once a second of game time at most…
The board at a time.
type ReplayChange
interface ReplayChange { state: Readonly<ReplayState>; reason: ReplayReason; /** The events that went by in this move (moving forward only), for the live region. */ crossed: readonly ReplayEvent[]; }
What a listener of the controller is told.
function replayClock
replayClock(seconds: number): string
Seconds as a clock, 0:12 or 1:05:09.
type ReplayController
interface ReplayController { /** A copy of the state now. */ state(): Readonly<ReplayState>; /** Start playing, from the start if it stopped at the end. In step mode, play moves one step and never plays by itself. */ play(): void; pause(): void; toggle(): void; /** Go to a time, in seconds on the timeline's clock; held to the first and last moments. */ seek(t: number): void; /** Pause and go to the next frame (1) or…
What createReplay gives back.
type ReplayEvent
interface ReplayEvent { /** Seconds, on the same clock as the frames. */ t: number; kind: ReplayEventKind; /** The team it belongs to; it colours the mark. */ team?: "home" | "away"; /** Where it began, in the timeline's frame; else the place of the object `by` at `t`; else the ball's or the puck's at `t`. */ x?: number; y?: number; /** Where it ended (a pass's receiver, a shot's end), in the timeline's frame; else …
Something that happened at a time: a pass, a shot, a goal, a whistle.
type ReplayEventKind
type ReplayEventKind = "pass" | "shot" | "goal" | "whistle" | (string & {});
The standard kinds of event. Any other word is an event of your own; its label is what is said.
function replayEvents
replayEvents(timeline: ReplayTimeline): readonly ReplayEvent[]
The events of a timeline, in time order: each one a copy, those without a time or a kind left out.
type ReplayFrame
interface ReplayFrame { /** Seconds. The frames of a timeline run forward in time (they are sorted if they do not). */ t: number; objects: readonly ReplayObject[]; /** * Who has the ball or the puck, when the data says: the `id` of an object, or `home` or `away` for a team without a named player. * `null` says nobody does (a loose ball, a pass in flight). It holds until a later frame says otherwise. */ possession?: …
The positions at one time.
function replayGameClock
replayGameClock(timeline: ReplayTimeline, t: number): ReplayGameClock
The game clock at a time t on the replay's clock: the period it is in (the last that has begun; the first, before any has) and how much of it has been played. The game clock runs only while play is on: it stands still in each of the timeline's stoppages, while the replay's clock moves on through it. A period's length is spread over the seconds of it that are not in a stoppage, so a game re-timed to minutes reads like the real one. Pure.
Example
import { replayGameClock } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const timeline = {
frames: [{ t: 0, objects: [] }, { t: 70, objects: [] }],
periods: [{ start: 0, end: 70, length: 1200 }],
stoppages: [{ start: 30, end: 40, reason: "goal" }],
};
const at = (t: number) => { const c = replayGameClock(timeline, t); return `${c.played} ${c.running}`; };
console.log(at(15), at(30), at(35), at(40), at(55));
// 300 true 600 false 600 false 600 true 900 true
type ReplayGameClock
interface ReplayGameClock { /** The period's number, or `undefined` when the timeline has no periods. */ period?: number; /** Seconds of the period played on the game clock, and seconds left of it. */ played: number; left: number; /** `false` in a stoppage (and before a period has begun or after it has ended): the game clock is standing still. */ running: boolean; /** The stoppage the time is in, when it is in one. …
The game clock at a time on the replay's clock.
function replayGameTime
replayGameTime(timeline: ReplayTimeline, t: number): number
The game time at t on the replay's clock: the seconds of game clock played since the first period began (the lengths of the periods before, and what has been played of this one). It stands still in a stoppage, as the game clock does: a penalty's two minutes are two minutes of it.
function replayInfo
replayInfo(timeline: ReplayTimeline): { start: number; end: number; duration: number; frames: number; objects: number; events: number; step: number; }
The first and last moments of a timeline, how long it is, how many frames and objects it has, and the usual gap between frames, all in seconds.
function replayLayers
replayLayers(timeline: ReplayTimeline, t: number, look?: ReplayLook, language?: Language): Layer[]
The data layers of one frame, to put in a drawing's layers (after your own): the trails, the events' marks, the players with their numbers, the ball.
type ReplayLook
interface ReplayLook { /** Seconds of trail behind the objects named in `trailOf`; 0 for none. 2 by default. */ trail?: number; /** Whose trail is drawn. The ball and the puck by default. */ trailOf?: readonly ReplayTeam[]; /** Round the corners of the path between frames: `true` for a Catmull-Rom curve through the frames, or a share from 0 (straight lines, the default) to 1. */ smooth?: boolean | number; /** Second…
How a frame is drawn.
type ReplayObject
interface ReplayObject { /** Who it is, the same in every frame it is in: `h7`, `ball`. */ id: string; team: ReplayTeam; /** Where it is, in the timeline's frame (`from`) and unit. */ x: number; y: number; /** A name for the tooltip: "Rivera". */ label?: string; /** A shirt number, written on the mark of a player. */ number?: number | string; }
One tracked object in one frame of the data.
function replayPenalties
replayPenalties(timeline: ReplayTimeline): readonly ReplayPenalty[]
type ReplayPenalty
interface ReplayPenalty { team: "home" | "away"; /** The player who serves it: the id of his object, which the frames put in the box. */ by?: string; start: number; /** When he leaves the box. Without it, the penalty runs for its `minutes` of game clock from the drop after the call. */ end?: number; /** Its length on the game clock: 2 for a minor, 4 for a double minor, 5 for a major, 10 for a misconduct. */ minutes:…
A penalty: a player in the penalty box from start (the call, a stoppage) to end (when he leaves it: his time ran out on the game clock, or a power-play goal ended a minor), in seconds on the timeline's clock. His side plays a skater short in that time unless short is false (a misconduct, or coincidental penalties, which leave the strength even).
type ReplayPeriod
interface ReplayPeriod { /** The period's number as the board writes it. Its place in the list (1 for the first) when missing. */ number?: number; /** Where it begins and ends, in seconds on the timeline's clock. */ start: number; end: number; /** How long the period is on the game clock, in seconds, when the replay is re-timed (a made-up game played in minutes: 1200 for a hockey period). The board's clock runs thro…
A period of the game (or a half, a quarter, an inning) on the timeline's clock: what a scoreboard on the surface shows as the period and counts its clock in.
function replayPeriods
replayPeriods(timeline: ReplayTimeline): readonly (ReplayPeriod & { number?: number; })[]
The periods of a timeline in order, each with its number; the whole replay as one period with no number when it gives none.
type ReplayReason
type ReplayReason = "play" | "pause" | "seek" | "step" | "tick" | "speed" | "loop" | "motion" | "follow";
Why the controller told its listeners.
type ReplaySettings
interface ReplaySettings extends ReplayLook { /** The speed of play: 0.25 to 4. 1 by default. */ speed?: number; /** Start again at the end. */ loop?: boolean; /** Play when the replay is attached. Ignored for a reader who prefers reduced motion, and while the page is hidden. */ autoplay?: boolean; /** The bar of controls under the drawing (play, step, speed, loop, position). On by default; the keyboard works withou…
What the controller and the controls can be told, over how a frame is drawn.
function replaySnapshot
replaySnapshot(timeline: ReplayTimeline, t: number, look?: ReplayLook): ReplaySnapshot
What is on the surface at a time: the objects, the trails behind the ones look.trailOf names, and the events.
type ReplaySnapshot
interface ReplaySnapshot { t: number; objects: ReplayObject[]; trails: ReplayTrail[]; events: ActiveEvent[]; }
The same frame of a timeline always draws the same layers: this is what a frame is, before it is drawn.
type ReplayState
interface ReplayState { /** Seconds on the timeline's clock. */ t: number; /** The first and last moments of the timeline. */ start: number; end: number; playing: boolean; /** Stopped at the end (and not looping). */ ended: boolean; speed: number; loop: boolean; /** `step` for a reader who prefers reduced motion: play moves a step, never by itself. */ motion: "smooth" | "step"; /** What the camera follows, and wheth…
What the controller is doing.
type ReplayStoppage
interface ReplayStoppage { /** When play stopped. */ start: number; /** When play starts again: the game clock runs from here. */ end: number; /** Why: a word of the sport's rule set (in hockey `goal`, `save`, `frozen`, `icing`, `offside`, `penalty`, `whistle`, `period-start`, `period-end`), or one of your own. */ reason?: string; /** Where play starts again (the face-off dot), in the timeline's frame. */ x?: number…
A stoppage: play is dead from start to end (the drop of the puck, a throw-in, a snap), in seconds on the timeline's clock. The game clock stands still in it while the replay's own clock (the slider) moves on: the players skate to their places for the restart, and the ball or the puck is dead.
function replayStoppages
replayStoppages(timeline: ReplayTimeline): readonly ReplayStoppage[]
The stoppages of a timeline, in order, each checked: a start and an end that are numbers, the end not before the start. Ones that overlap are joined. Read once and kept.
Example
import { replayStoppages } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const frames = [{ t: 0, objects: [] }];
console.log(replayStoppages({ frames, stoppages: [{ start: 9, end: 12 }, { start: 2, end: 5, reason: "goal" }, { start: 4, end: 6 }, { start: 8, end: 7 }] }));
// [ { start: 2, end: 6, reason: 'goal' }, { start: 9, end: 12 } ]
function replaySummary
replaySummary(timeline: ReplayTimeline, language?: Language): string
The sentence a replay adds to the drawing's description: its length, what it tracks and how many events it holds. It does not change with the time.
function replayTable
replayTable(timeline: ReplayTimeline, options?: { language?: Language; className?: string; }): string
The events of a timeline as an HTML table, for a reader who cannot see the drawing: the time, the kind, the team and what is said of it. Every cell is escaped.
Example
import { replayTable } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const html = replayTable({ frames: [{ t: 0, objects: [] }], events: [{ t: 12, kind: "goal", team: "home", label: "Goal, Rivera" }] });
console.log(html.includes("<td>0:12</td>"), html.includes("Goal, Rivera"));
// true true
type ReplayTeam
type ReplayTeam = "home" | "away" | "ball" | "puck" | "official";
What a tracked object is. home and away are players; the rest are drawn smaller and in the layer's plain colours.
type ReplayTimeline
interface ReplayTimeline { /** The positions, from the first moment to the last. */ frames: readonly ReplayFrame[]; /** What happened, by time. */ events?: readonly ReplayEvent[]; /** The frame the positions are in (a name in `FRAMES`, or a `Frame`), as for a layer. Without it they are the surface's own: feet from the top left of the surface as drawn wide. */ from?: Frame | string; /** The unit of the positions, as …
Tracking data over time on a surface. Do not change a timeline after it has been used: make a new one.
function replayTimes
replayTimes(timeline: ReplayTimeline): readonly number[]
The times of the frames, and of the events, in order: the moments a step can land on.
type ReplayTrail
interface ReplayTrail { id: string; team: ReplayTeam; /** The places over the last seconds, oldest first, the last the object's place now. */ points: [number, number][]; }
A tracked object at a moment, and the trail behind it.
function restartsBetween
restartsBetween(timeline: ReplayTimeline, from: number, to: number): readonly ReplayStoppage[]
The restarts that went by while the clock moved from from to to ((from, to]): the stoppages whose end, the drop of the puck, is in it. What a page plays the drop's sound on, as it plays the horn on a goal of eventsBetween.
type ServedPenalty
interface ServedPenalty { penalty: ReplayPenalty; left: number; }
A penalty being served at a time, and its game seconds left.
function springStep
springStep(at: number, speed: number, goal: number, dt: number, omega: number): [number, number]
One step of a critically damped spring toward goal: where it is and how fast it goes after dt seconds. It never overshoots and never rings, and a long step lands nearer, never past.
Example
import { springStep } from "@johnmorrisdotca/kyogijo-stadiums/replay";
let [x, v] = [0, 0];
for (let i = 0; i < 60; i += 1) [x, v] = springStep(x, v, 10, 1 / 60, 4);
console.log(Math.round(x * 100) / 100, x < 10);
// 9.08 true
function stoppageAt
stoppageAt(timeline: ReplayTimeline, t: number): ReplayStoppage | undefined
The stoppage a time is in (from its start, up to but not at its end, when play starts again), or undefined while play is on.
function trails
trails(timeline: ReplayTimeline, t: number, seconds: number, options?: { teams?: readonly ReplayTeam[]; ids?: readonly string[]; smooth?: boolean | number; }): ReplayTrail[]
The path each object took over the last seconds before t, oldest place first and ending at its place at t: the frames in between, and the places at the two ends. Only objects that are there at t have a trail, and it begins after the last frame the object was not in (a dead puck out of sight). teams and ids choose whose; all by default.
Example
import { trails } from "@johnmorrisdotca/kyogijo-stadiums/replay";
import type { ReplayTimeline } from "@johnmorrisdotca/kyogijo-stadiums/replay";
const timeline: ReplayTimeline = { frames: [0, 1, 2, 3].map((t) => ({ t, objects: [{ id: "puck", team: "puck", x: t * 10, y: 0 }] })) };
console.log(trails(timeline, 3, 2)[0].points.map((point) => point[0]).join());
// 10,20,30
function zoomFor
zoomFor(zoom: number, room: number, maxZoom?: number): number
How much a view magnifies for a shot's zoom, when the view at 1 shows more than the surface (room times it: the margin round a flat drawing, the stands round a 3D one). At a zoom of 1 the view is as it was; at maxZoom the frame fills it; in between the two are joined smoothly, and the view never shows less than the frame.
@johnmorrisdotca/kyogijo-stadiums/turn
Box3 buildTurn cameraMatrix clampView createGovernor CURLING_PRESETS depthOf describeUprights discSize drag eyeDistance FeedReplay FeedReplayOptions fit floorOptions Governor GOVERNOR_TUNING GovernorTuning handheld heightUnit House isQuality keepOnFloor KYOGIJO_TURN_STYLE KyogijoTurn Layout layoutOf LedBoardOptions LedBoardPattern LIGHT_COLORS LIGHT_PRESETS Lighting LIGHTING_PRESETS LightingOptions LightingPreset LightPreset LONG_PRESETS Mat4 matrix3d mountKyogijoTurn mountTurn multiply NET_PRESETS nudge openingView PartKind PITCH_MAX Placement Plane planeMarkup planeMatrix planesOf presetOf presetsFor presetView project QUALITIES Quality QUALITY_TIERS qualityOf QualityTier rasterOf ReplayCall ReplayFollow ReplayFollowOptions replayTurnModel resolveLighting ROOF step STEP TIER_PROFILES tierOf TierProfile TURN_DEFAULT TURN_PRESET_NAMES TURN_PRESETS turnDirection TurnDirection turnMarkup turnMarkupOf TurnModel TurnPreset TurnReplayLook TurnReplayModel TurnReplaySettings TurnSettings turnSupported TurnToward TurnView Upright UprightKind UprightOptions Uprights uprightsFor V3 Venue VenueBuild VenueSettings WASH ZOOM_MAX ZOOM_MIN
type Box3
interface Box3 { x0: number; y0: number; x1: number; y1: number; z0: number; z1: number; }
A box in the scene, in pixels from the scene's middle, the floor at z0 and the highest thing at z1.
function buildTurn
buildTurn(options: SurfaceOptions | ScoreOptions, settings?: TurnSettings): TurnModel
Work out a 3D view from the options of a drawing.
function cameraMatrix
cameraMatrix(view: TurnView, at: Placement, distance: number, focus?: readonly [number, number] | readonly [number, number, number]): number[]
The matrix that puts a point of the scene on the screen for a view in a placement: the scene (whose middle is the origin) is scaled, turned about the vertical, tipped back, shifted to where the fit puts it, and seen with a perspective distance pixels deep. This is project's arithmetic as one matrix, so that an element can be given its whole place in one matrix3d and need no 3D context of the browser's: a browser that draws nested 3D layers flat still draws it right. focus, a point of the floor in the scene's pixels from its middle, is put where the middle would be (and, by its third number from 0 to 1, that share of the way to the container's middle): the camera looks at it, and turns and tips about it.
function clampView
clampView(view: TurnView, fallback?: TurnView): TurnView
A view held to what the controls allow: the pitch from overhead to 84 degrees, the zoom from half to four times. A number that is not one is left as it was.
function createGovernor
createGovernor(start: QualityTier, tuning?: Partial<GovernorTuning>): Governor
The governor of a view that turns. It keeps a window of frame intervals; when their mean is over budget it steps one tier down, and when the mean has been steady for wait it tries one tier up. A try that goes over budget is taken back, and every step down within thirty seconds of a step up doubles the wait (up to maxUpAfterMs), so a device on the edge between two tiers settles on the lower one and stays there. A step up that holds (steady for settleMs after it) leaves the wait as it was.
const CURLING_PRESETS
CURLING_PRESETS: Readonly<Record<TurnPreset, TurnView>>
The same four for a curling sheet, which is ten times as long as it is wide: from the side it is a strip across the box, so the broadcast and the corner views stay nearly square on to it, and the end view looks along it.
function depthOf
depthOf(point: readonly [number, number, number], view: TurnView, at: Placement): number
How far a point is from the eye's plane after the scene is turned and tipped, in pixels towards the eye: bigger is nearer. Planes are drawn far first.
function describeUprights
describeUprights(o: SurfaceOptions, uprights: Uprights, language?: Language): string
What stands on the surface, in a sentence, with heights: for a reader who cannot see the 3D view. An empty string when nothing stands on it.
function discSize
discSize(area: { w: number; h: number; }, look?: ReplayLook): number
The size of a disc, in feet: a share of the playing surface's diagonal (the area the view is fitted to, not the ground or the building round it), so that it reads on a rink and on a pitch alike (about 6.5 feet on a hockey rink, 12 on a soccer pitch), times the look's scale. It is a mark, not a person: its size says nothing of a player's height.
function drag
drag(view: TurnView, dx: number, dy: number, tilt?: boolean, degreesPerPixel?: number): TurnView
The view after a drag of the pointer by (dx, dy) pixels, degreesPerPixel apart: the surface is taken hold of, so a drag to the right carries the side nearest the eye to the right (the yaw falls) and a drag down tips the top toward the eye (the pitch falls).
function eyeDistance
eyeDistance: (w: number, h: number, lens?: number) => number
How far the eye is from the screen, in pixels, for a container: a long lens, so that the floor keeps its shape and the heights lean a little. The lens is long enough that the nearer end of a floor is hardly larger than the farther one: with a short lens (it was 1.7) the floor swelled by up to a quarter as its near end swung toward the eye in a turn.
type FeedReplay
type FeedReplay = KyogijoReplay & { feed: FeedGame };
A replay of a feed: the replay's controller, and the game the feed was read into.
type FeedReplayOptions
interface FeedReplayOptions { format?: FeedFormat; settings?: ReplaySettings; base?: string; signal?: AbortSignal; fetch?: (input: string, init?: RequestInit) => Promise<Response>; }
What a feed played from an address can be told: its format, the replay's settings, and for a test the function that fetches.
function fit
fit(b: Box3, view: TurnView, w: number, h: number, distance: number, pad?: number): Placement
The placement that fits the scene in a container of width w and height h pixels, centred, with pad of its width and height left round it. It fits the scene at every turn about the vertical at the view's pitch, not at the view's own turn (its yaw is not used): the scale and the place are one for the whole circle, so that turning never zooms in and out or sways, and nothing is cut off at any angle. (A turn used to fit each angle alone, so a long floor was drawn up to 1.8 times as large side-on as end-on.) Tipping the view still rescales it, since the extent of the scene on the screen changes with the pitch. The perspective bends the sum, so it is found by a few rounds of scaling and re-centring; six is plenty.
function floorOptions
floorOptions(options: SurfaceOptions | ScoreOptions): SurfaceOptions | ScoreOptions
The options with what makes the floor of a 3D view: the whole surface, lying wide, at its full size.
type Governor
interface Governor { /** The tier now. */ readonly tier: QualityTier; /** Give it the time since the last frame and the time now; it gives the new tier when it steps, else `undefined`. */ frame(interval: number, now: number): QualityTier | undefined; /** The interval of the display, in milliseconds, as the page measured it with nothing else going on (16.7 for 60 Hz, 33.3 for a phone in a power-saving mode): a displa…
What the governor does with a frame.
const GOVERNOR_TUNING
GOVERNOR_TUNING: GovernorTuning
type GovernorTuning
interface GovernorTuning { /** The frames in a window it keeps (the oldest are dropped past twice this), and the fewest it judges: a window is also at least `settleMs` long, so a view at 60 frames a second judges 42 frames and one at 6 frames a second judges 8. */ frames: number; minFrames: number; settleMs: number; /** The first frames after the view is mounted are slow whatever it holds (scripts are still compilin…
How the governor judges the frames. Times are in milliseconds.
function handheld
handheld(win: { matchMedia?: (query: string): { matches: boolean; }; screen?: { width: number; height: number; }; innerWidth?: number; } | null | undefined) => boolean
What decides whether the device is a phone or a tablet: it has a coarse pointer, or its screen is small. It is asked of the page's own window, never of the browser's name.
function heightUnit
heightUnit(o: Pick<SurfaceOptions, "sport" | "league" | "units">): Unit
The unit the heights are said in: the options' own, else the rulebook's of the sport.
type House
type House = "half" | "dim" | "dark";
How dark the house is: half (a light veil, the game's), dim (the night's) or dark (a show's).
function isQuality
isQuality: (value: unknown) => value is Quality
Whether a value is one of the qualities.
function keepOnFloor
keepOnFloor: (group: Pick<ReplayGroup, "id">) => boolean
Whether a group of the replay stays on the floor of a 3D view: the trails, the passes, the shots, the goals and the ball do, and the players, their numbers and the officials stand up.
const KYOGIJO_TURN_STYLE
KYOGIJO_TURN_STYLE: string
The 3D view's stylesheet: the colours of what stands on the surface, in light and dark, and the rules that lay the scene out. Like the drawing's own, the defaults are in :where(), which has no weight, so a page's own rule always wins; the colours are custom properties (--ky-up-*) a page can set.
type KyogijoTurn
interface KyogijoTurn<O = SurfaceOptions | ScoreOptions> { /** `3d`, or `flat` where the browser cannot draw the 3D view (or there is nothing to turn): the flat drawing is shown and the rest of this does nothing. */ readonly mode: "3d" | "flat"; /** The view now: where it is going if it is gliding. */ view(): TurnView; /** Turn to a view (the parts of it given): it glides there unless `glide` is false or the reader …
What mountKyogijoTurn gives back. O is what update takes: the options of a drawing, or (for mountMultiTurn) of a tournament layout.
type Layout
interface Layout { at: Placement; /** The floor, then the planes in the model's order. A plane that `cull` says is turned away has `""` here. */ transforms: string[]; /** The stack of each: 0 for the ground of a hall, 1 for the floor, then the planes far to near from 2. */ stack: number[]; /** How much of each is left: 1 for all but the walls that are between the eye and the surface, which are cut away as the view i…
Where everything is for a view in a container: the placement, the matrix of each element and its place in the stack.
function layoutOf
layoutOf(model: TurnModel, view: TurnView, width: number, height: number, lens?: number, cull?: boolean, raster?: Raster, focus?: readonly [number, number] | readonly [number, number, number]): Layout
Work a view out in a container width by height pixels. With cull, the faces of a closed solid that are turned away from the eye (Plane.cull) are left out: they have no transform and no place in the stack, and culled says which, so that a page need not write them at all; without it every plane is laid out, as a still picture needs. raster is the share of its size an element is made at (rasterOf): each element's matrix widens it back, so that the picture is the same and the layers hold raster squared as many pixels.
type LedBoardOptions
interface LedBoardOptions { /** The ribbon boards along the fascia between the levels (the front of the single level of a hall that has one). On by default. */ ribbon?: boolean; /** The scoreboard hung over the middle of the playing surface, four sided, with a ring of display under it. On by default, and left out of a ballpark (whose scoreboard stands behind the outfield). */ scoreboard?: boolean; /** One to three c…
The LED boards of a venue (crowd.boards, or venue.boards of the 3D view): the ribbon boards along the fascia between the seating levels, and a scoreboard hung over the playing surface. The content is generic: bands of colour, abstract patterns and a plain score, never a logo, a sponsor or text from a real board. true is both, in the package's own colours. Off by default.
type LedBoardPattern
type LedBoardPattern = "bands" | "blocks" | "chevrons" | "waves";
The patterns a ribbon board shows: bands (two bands of colour, in panels), blocks (a block of colour to a panel), chevrons (arrows running along it) or waves.
const LIGHT_COLORS
LIGHT_COLORS: { readonly white: "#fff6e6"; readonly amber: "#ffb830"; readonly purple: "#9b4dff"; readonly magenta: "#ff2bd6"; readonly blue: "#2b7bff"; readonly cyan: "#27d6ff"; }
The named colours of light: wash, aisles and colors take these by name (ours, a little saturated, for a light seen on dark).
const LIGHT_PRESETS
LIGHT_PRESETS: Readonly<Record<LightingPreset, LightPreset>>
The named lightings. night: the calm dim house with small lights along the aisles. game: white light, the house half lit, a pool of light round the surface. lightsDown: the house nearly black, a white beam down each aisle. intro: the house dark, the home team's colour washed over the surface and the visitors' (the second colour) in the beams. concert: warm amber beams and a purple surface. (The celebration of the plan, colours chasing round the bowl, is a later one.)
type Lighting
interface Lighting { preset: LightingPreset; house: House; aisles: "none" | "dots" | "beams"; pool: boolean; /** The colour of the beams. */ beam: string; /** The surface's colour of light (none for the surface as it is). */ wash: string | undefined; }
The lighting as asked, with every part's value.
const LIGHTING_PRESETS
LIGHTING_PRESETS: readonly LightingPreset[]
type LightingOptions
type LightingOptions = LightingPreset | boolean | { preset?: LightingPreset; colors?: readonly string[]; aisles?: string; wash?: string };
type LightingPreset
type LightingPreset = "night" | "game" | "lightsDown" | "intro" | "concert";
The lighting of a venue (crowd.lighting in the plan, venue.lighting in the 3D view): a named preset (LIGHT_PRESETS), true (the night), or { preset, colors, aisles, wash }. "night" dims the house, lights the playing surface and shows small lights along the aisles and stairs, the ribbon boards and the scoreboard glowing, the exits and the concourse rim softly lit. "game" is white light with the house half lit. "lightsDown" is a show's house: nearly black, each stair aisle lit from above as a beam with a soft falloff on the steps either side, the rails and the front of every step edged with light. "intro" is the same house with the home team's colour washed over the surface and the visitors' in the beams (the teams' colours where the options have them, else blue and amber); "concert" has warm amber beams and a purple surface. colors are one or two colours that stand for the home and the visitors (before the options' teams); wash colours the playing surface with a light (a CSS colour, or white, amber, purple, magenta, blue, cyan; the markings stay visible) and aisles the beams, and both win over the preset's. false is no lighting. Off by default.
type LightPreset
interface LightPreset { house: House; aisles: "none" | "dots" | "beams"; pool: boolean; wash?: keyof typeof LIGHT_COLORS | "home" | "away"; beam?: keyof typeof LIGHT_COLORS | "home" | "away"; /** What `home` and `away` are where the options name no team colour. */ fallback?: { home: keyof typeof LIGHT_COLORS; away: keyof typeof LIGHT_COLORS }; }
A named lighting. house is how dark the stands are; aisles how the aisles are lit (none, small dots, or a beam of light from above down each); pool whether a pool of light lies on the floor round the surface; wash and beam are the colours of the light on the surface and of the beams: a colour (a name of LIGHT_COLORS), or home and away, the teams' colours where the options have them (crowd.home and crowd.away, the colours of a score's teams), else fallback's.
const LONG_PRESETS
LONG_PRESETS: Readonly<Record<TurnPreset, TurnView>>
The same four for a long, narrow surface (a football field, a hockey rink): turned less, because a diagonal view would shrink it in the box.
type Mat4
type Mat4 = readonly number[];
A 4 by 4 matrix, as CSS writes it in matrix3d: sixteen numbers, a column after a column.
function matrix3d
matrix3d: (m: Mat4) => string
A matrix as the CSS transform that applies it.
function mountKyogijoTurn
mountKyogijoTurn(host: HTMLElement, options: SurfaceOptions | ScoreOptions, settings?: TurnSettings): KyogijoTurn
Mount a surface as a 3D view in a container, over the static drawing it would otherwise hold: the drawing is the floor, tilted and turned by the pointer, the touch, the wheel and the keys, with what stands on the surface (a net and its posts, a basket, a goal, the posts of a football field) standing on it.
Example
``ts no-run import { mountKyogijoTurn } from "@johnmorrisdotca/kyogijo-stadiums/turn"; const view = mountKyogijoTurn(document.querySelector("#court")!, { sport: "volleyball", home: { name: "Japan", score: 3 }, away: { name: "USA", score: 2 } }, { preset: "end" }); view.preset("corner"); view.set({ yaw: 60, pitch: 40 }); ``
function mountTurn
mountTurn<O>(host: HTMLElement, options: O, settings: TurnSettings, build: (options: O, settings: TurnSettings): TurnModel, replayable?: boolean, lend?: (internals: TurnInternals) => void) => KyogijoTurn<O>
Mount any 3D model (mountKyogijoTurn is this with the model of one surface; mountMultiTurn with a tournament layout's): build makes the model from what update is given, and the rest, the controls, the pointer, the keys and the auto-turn, is the same.
function multiply
multiply(a: Mat4, b: Mat4): number[]
Two matrices as one: b first, then a.
const NET_PRESETS
NET_PRESETS: Readonly<Record<TurnPreset, TurnView>>
The same four for the net sports, whose net runs across the court: seen from the side line it is a stick, so the broadcast view stands high behind an end line, as a television camera does, and the end-on view is lower behind it. The corner view is the same.
function nudge
nudge(view: TurnView, toward: TurnToward, amount: number): TurnView
The view after a step of amount degrees toward a side, the way a drag toward that side takes the view: left and right carry the near side to the left and to the right (the yaw rises and falls), up tips the surface as a drag up does and down as a drag down does (the pitch rises and falls). The arrow keys and the four turn buttons are this, so that a drag, a key and a button toward one side all move the surface the same way.
function openingView
openingView: (settings: Pick<TurnSettings, "preset" | "view">, sport?: string | PresetTable) => TurnView
The view a set of settings opens on.
type PartKind
type PartKind = "mast" | "post" | "net" | "tape" | "antenna" | "board" | "glass" | "rim" | "stanchion" | "frame" | "goal" | "flag" | "stump" | "leg" | "table" | "pylon" | "wall" | "screen" | "pole" | "ground" | "target" | "seats" | "concourse" | "fascia" | "roof" | "banner" | "platform" | "rail" | "matedge" | "shrine" | "surround" | "chair" | "desk" | "card" | "sign" | "apron" | "bench" | "floor" | "ribbon" | "hung-…
What a plane is a part of: it is the class of its element (ky-up-<kind>) and what a test finds it by.
const PITCH_MAX
PITCH_MAX: 84
type Placement
interface Placement { k: number; tx: number; ty: number; }
How a view is placed in a container: the scale (at a zoom of 1) that fits the scene, and where the middle of what is seen falls.
type Plane
interface Plane { /** A name that says what it is and where: `net`, `post-left`, `goal-right-back`. */ id: string; kind: PartKind; o: V3; u: V3; v: V3; svg: string; /** * A plane that turns to face the eye, about the vertical through its middle: a scoreboard is read from wherever the view is. `u` and `v` give its size and its * place as it lies at a yaw of 0; `v` must be vertical. */ billboard?: boolean; /** * A bil…
One flat rectangle. Its own x runs along u (its whole length) and its own y along v; o is the corner both start from. svg is what is drawn on it, in feet along u and v.
function planeMarkup
planeMarkup(p: Plane, scale: number, transform: string, stack: number, fade?: number, raster?: number): string
One plane as an element: its box in pixels and the SVG drawn on it in feet.
function planeMatrix
planeMatrix(p: Plane, scale: number, centre?: readonly [number, number]): number[]
The matrix that stands a plane in the scene, before the camera: its x along u, its y along v, its corner o, in pixels from the middle of the scene (centre, in feet).
function planesOf
planesOf: (u: Pick<Uprights, "items">) => Plane[]
All the planes of all the things.
function presetOf
presetOf(view: TurnView, sport?: string | PresetTable): TurnPreset | undefined
The name of the viewpoint a view is in a sport, or undefined when it is none of them (it has been turned by hand).
function presetsFor
presetsFor: (sport?: string | PresetTable) => PresetTable
The four viewpoints of a sport, or the table itself when it is given one (a tournament layout has its own).
function presetView
presetView: (name: string | undefined, sport?: string | PresetTable) => TurnView | undefined
The view a viewpoint name stands for in a sport, or undefined for a name that is not one.
function project
project(point: readonly [number, number, number], view: TurnView, at: Placement, distance: number): [number, number, number]
Where a point of the scene falls on the screen, in pixels from the middle of the container, when the scene is placed as given and the eye is distance pixels away.
const QUALITIES
QUALITIES: readonly Quality[]
The values a page can ask for: auto and the tiers.
type Quality
type Quality = "auto" | QualityTier;
What a view is asked for: one tier, or auto, which chooses by the frames the view makes.
const QUALITY_TIERS
QUALITY_TIERS: readonly QualityTier[]
The tiers, highest first: a step down is one place later in this list.
function qualityOf
qualityOf: (value: unknown, fallback?: Quality) => Quality
A quality from whatever a page or an address gave: the same if it is one, else fallback.
type QualityTier
type QualityTier = "high" | "medium" | "low";
The tiers of detail, from the most to the least.
function rasterOf
rasterOf(quality: Quality, tier: QualityTier, dpr: number, isHandheld: boolean): number
The share of its size a layer is made at, from the device's pixel ratio dpr: a layer is made share times as wide and as high in CSS pixels and turned back to its size by its matrix, so that it holds share squared as many device pixels, as far as the engine keeps a layer's pixels to its own box (the layers of a district at a ratio of 3 are hundreds of megabytes, which a phone's browser does not always keep). An engine that draws a layer again at the scale its matrix has (Chromium does) makes the same pixels from it, so there it changes nothing, and the sizes this package reports are the boxes times the ratio squared, not what an engine allocates. 1 when the ratio is within the cap. The mode auto caps a handheld at 2 even at high; a tier asked for by name is exactly that tier's, and high asked for by name is the device's own ratio, as it always was.
type ReplayCall
interface ReplayCall { (timeline: ReplayTimeline, settings?: ReplaySettings): KyogijoReplay; /** * Fetch a feed from an address, by the reader's browser (no server of ours, no cookie, nothing kept), read it (`readFeed`: kyogijo's open timeline, or an NHL-style play-by-play) and play it. Rejects with a * `FeedError` that says what was wrong: a server that does not let the page read it (`cors`), a status (`http`), an …
A mount's or a view's replay: play a timeline, or a feed from an address.
type ReplayFollow
interface ReplayFollow { replay(): KyogijoReplay | undefined; state(): FeedFollowState; stop(): void; }
A replay that follows a feed live: the replay playing now (a new one on each answer that changed), the follow's state, and stop, which stops asking and leaves the replay.
type ReplayFollowOptions
interface ReplayFollowOptions extends FeedReplayOptions { /** Seconds between asks: 15 by default, never less than 10. */ every?: number; /** Each new answer, after it is played. */ onGame?: (game: FeedGame, replay: KyogijoReplay) => void; onError?: (error: FeedError) => void; onState?: (state: FeedFollowState) => void; /** The document whose visibility it follows: the page's by default. */ doc?: Document; }
What a live follow can be told, beyond FeedReplayOptions.
function replayTurnModel
replayTurnModel(model: TurnModel, timeline: ReplayTimeline, t: number, look?: TurnReplayLook): TurnReplayModel
A 3D view's model with a replay on it at a time: the floor drawn as the replay's frame (without the players when they stand), and a disc for each player and official the timeline tracks, after the model's own planes. One that is not on the surface at the time is still a plane, and says so (on), so that the elements stay the same while it plays. Pure.
function resolveLighting
resolveLighting(ask: LightingOptions | undefined | null, team?: { home?: string; away?: string; }): Lighting | undefined
The lighting an option asks for: a preset's name, true for the first (night), or { preset, colors, aisles, wash }, or undefined for none (false, nothing, an unknown name). A colour comes from, in order: wash or aisles, colors (the first is what the preset's home is, the second its away), the teams' colours (team), the preset's own.
const ROOF
ROOF: { readonly clearance: 26; readonly canopyReach: 0.62; readonly canopyDrop: 6; readonly lidRise: 26; }
How far the roof stands over the top row at its edge, in feet (ours: no rule gives it), and how far it reaches over the seats.
function step
step(view: TurnView, change: { yaw?: number; pitch?: number; zoom?: number; }): TurnView
The view after a step of a key or a button.
const STEP
STEP: { readonly yaw: 6; readonly yawBig: 24; readonly pitch: 4; readonly pitchBig: 12; readonly zoom: 1.2; }
The steps of the keys and the buttons, in degrees, and the factor of a zoom step. A held Shift takes the larger.
const TIER_PROFILES
TIER_PROFILES: Record<QualityTier, TierProfile>
The profile of each tier. high leaves everything as it always was (the cap on a handheld's pixel ratio is the mode auto's and is made in rasterOf).
function tierOf
tierOf: (quality: Quality | undefined) => QualityTier
The tier a view with no frames to go by is drawn at: the tier asked for, and high for auto (a page made on a server, a first draw).
type TierProfile
interface TierProfile { tier: QualityTier; /** The most buildings of a district's context that stand up as blocks in the 3D view (the tallest and widest first); the rest are the floor's flat footprints, which every tier draws. */ blocks: number; /** The share of the context's trees that are drawn, 0 to 1. */ trees: number; /** A venue whose longest side is under this share of the plan's longest side is drawn as its …
What a tier draws.
const TURN_DEFAULT
TURN_DEFAULT: TurnPreset
The view a mount opens on.
const TURN_PRESET_NAMES
TURN_PRESET_NAMES: readonly TurnPreset[]
const TURN_PRESETS
TURN_PRESETS: Readonly<Record<TurnPreset, TurnView>>
The four viewpoints. overhead looks straight down; broadcast is the main camera, high on one side line and turned a little towards the near end so that the boards, the nets and the goals show their faces; end stands behind an end line, along the surface, which is where a net, a goal or a basket is best seen; corner is low, from a corner, with the nearest net or goal in front.
function turnDirection
turnDirection(value: unknown): TurnDirection
A direction from anything: "clockwise" is clockwise, and everything else is the default, "counterclockwise".
type TurnDirection
type TurnDirection = "clockwise" | "counterclockwise";
Which way the auto-turn goes, seen from above. "counterclockwise" is how it has always turned: the near side swings to the viewer's right. "clockwise" is the other way: the near side swings to the left. A drag, the keys and the buttons are not reversed.
function turnMarkup
turnMarkup(options: SurfaceOptions | ScoreOptions, settings?: TurnSettings): string
A surface as a 3D view, as markup: the flat drawing for a floor, what stands on it as planes, and the controls under it. Pure, so it can be made on a server; it is a still picture until mountKyogijoTurn (or the element) makes it turn in a page.
Example
import { turnMarkup } from "@johnmorrisdotca/kyogijo-stadiums/turn";
const html = turnMarkup({ sport: "volleyball" }, { preset: "end" });
console.log(html.includes("ky-turn"), html.includes('data-part="net"'));
// true true
function turnMarkupOf
turnMarkupOf(model: TurnModel, settings?: TurnSettings, raster?: Raster): string
The 3D view of a model as markup, laid out for settings.size; a page's script then makes it turn.
type TurnModel
interface TurnModel { id: string; language: Language; /** The options the floor is drawn from: the whole surface, lying wide. */ options: SurfaceOptions | ScoreOptions; title: string; /** What the drawing says, and then what stands on it. */ description: string; /** The sentence about what stands on the surface, or an empty string. */ standing: string; /** The floor: the markup of the flat drawing. */ floor: string;…
Everything a 3D view is made of.
type TurnPreset
type TurnPreset = "overhead" | "broadcast" | "end" | "corner";
The named viewpoints.
type TurnReplayLook
interface TurnReplayLook extends ReplayLook { stand?: boolean; /** `false` leaves a scoreboard hung over the surface as the options made it; by default it shows the replay's score, period and clock (`replayBoard`). */ board?: boolean; }
The settings a 3D replay takes beyond the flat replay's look: stand: false keeps the players flat on the floor, as the flat replay draws them.
type TurnReplayModel
interface TurnReplayModel { model: TurnModel; /** The disc of each one standing, by id, and whether it is on the surface at the time. */ discs: Map<string, { plane: Plane; on: boolean }>; /** The disc's size, in feet. */ size: number; /** The options the floor was drawn with, its `id` among them. */ floorOptions: SurfaceOptions | ScoreOptions; /** What the hung scoreboard shows at the time, when the model has one an…
A replay laid on a 3D view's model: what replayTurnModel gives back.
type TurnReplaySettings
type TurnReplaySettings = ReplaySettings & TurnReplayLook;
Settings of a replay on a 3D view: the flat replay's, and stand.
type TurnSettings
interface TurnSettings { /** The viewpoint it opens on: `overhead`, `broadcast`, `end` or `corner` (the default). */ preset?: TurnPreset; /** An exact opening view, laid over the preset's. */ view?: Partial<TurnView>; /** Whether the buttons under the view are drawn (a row of viewpoints, turn, raise, zoom and reset). True when left out; the keys and the pointer work either way. */ controls?: boolean; /** What stands…
What can be asked of a 3D view.
function turnSupported
turnSupported(win?: { CSS?: { supports?: (property: string, value: string): boolean; } | null; } | undefined) => boolean
True where the page can draw a plane in 3D by one matrix3d: that is, nearly everywhere with a stylesheet.
type TurnToward
type TurnToward = "left" | "right" | "up" | "down";
A side a key, a button or a drag takes the surface toward.
type TurnView
interface TurnView { yaw: number; pitch: number; zoom: number; }
How the scene is looked at: turned about the vertical (degrees, clockwise as the eye sees the floor), tipped back from straight overhead (degrees), and magnified.
type Upright
interface Upright { id: string; kind: UprightKind; /** Where it stands on the surface, in feet. */ at: readonly [number, number]; /** The height of its top above the surface, in feet. */ height: number; /** A second height worth saying (a net's height at the centre, a post's crossbar), in feet. */ low?: number; planes: Plane[]; /** What a scoreboard hung over the surface was made from, so that a replay can draw its …
A thing that stands on the surface: where, how high, and the planes it is made of.
type UprightKind
type UprightKind = "scoreboard" | "net" | "antennae" | "goalposts" | "netposts" | "hoop" | "goal" | "boards" | "stumps" | "pylons" | "flags" | "fence" | "backstop" | "foul-poles" | "table-legs" | "walls" | "starting-blocks" | "backstroke-flags" | "false-start-rope" | "springboards" | "platforms" | "judges-stand" | "hurdles" | "steeplechase" | "high-jump" | "pole-vault" | "cage" | "padding" | "rink-boards" | "mound" …
What stands on the surface as a thing a reader would name: a net, a basket, a goal, a pair of posts.
type UprightOptions
interface UprightOptions { /** Volleyball: the net at the men's height (2.43 m, the default) or the women's (2.24 m). */ netHeight?: "men" | "women"; /** Where the score of a score drawing goes: `board` (the default) hangs it up as a scoreboard (over the middle of a court or a rink, behind an end of a field) and takes the panel off the floor; `floor` leaves it on the floor. */ score?: "board" | "floor"; /** Leave th…
What can be asked of the uprights.
type Uprights
interface Uprights { items: Upright[]; /** How far the surface itself stands over the ground, in feet: a table tennis table's top, 0 on every other surface. */ lift: number; /** The thinnest line or strip drawn on this surface, in feet. */ thin: number; /** The playing surface itself in feet, the part the view is fitted to (the ground round it may run out of the picture): `undefined` for a surface with no uprights, …
What stands on a surface.
function uprightsFor
uprightsFor(o: SurfaceOptions, settings?: UprightOptions): Uprights
What stands on the surface the options draw: nothing on a curling sheet, which is flat.
type V3
type V3 = readonly [number, number, number];
A point or a direction: x, y, z in feet.
type Venue
interface Venue { items: Upright[]; defs: string; /** How far the venue reaches beyond the surface's box on its widest side, in feet: the ground the floor needs for it to stand on. 0 for none. */ reach: number; }
What the venue is made of: the things that stand, and the patterns they are drawn with (the contents of a defs).
type VenueBuild
interface VenueBuild extends VenueSettings { id: string; /** Leave the scoreboard hung over the middle out (a tournament hall has scoreboards of its own). */ noCentre?: boolean; /** The teams' colours the drawing has (a crowd's `home` and `away`, or a score's teams'): what a lighting's team colours are. */ team?: { home?: string; away?: string }; }
The settings a venue is built from: the asker's, and the prefix of the ids of what it draws, which the view gives.
type VenueSettings
interface VenueSettings { /** Roofs and canopies over the top tier of the stands: a canopy over the back of the top tier in the open, a lid over a hall. They give way to the eye as the walls do. Off by default. */ roof?: boolean; /** A retractable roof (a real venue's: BC Place's) drawn open, the fabric gathered into its pod, instead of closed over the opening. Closed by default. */ roofOpen?: boolean; /** The walls…
What can be asked of the venue.
const WASH
WASH: { readonly middle: 0.46; readonly edge: 0.26; }
The wash of light on the playing surface: a flat plane over the surface's box, a colour that is brighter over the middle and weaker at the edge, never so strong that the markings under it are lost (WASH says how much).
const ZOOM_MAX
ZOOM_MAX: 4
const ZOOM_MIN
ZOOM_MIN: 0.5
@johnmorrisdotca/kyogijo-stadiums/circuits
bindTower buildCircuitTurn carAt Circuit CIRCUIT_ATTRIBUTION CIRCUIT_IDS CIRCUIT_MARKER CIRCUIT_PLANES_MAX CIRCUIT_PRESETS CIRCUIT_WORDS CircuitBasis circuitById CircuitData circuitDrawing CircuitDrawing CircuitFact CircuitOptions CircuitOsm CircuitOsmPoint circuitPlan CircuitPlan CircuitRace CIRCUITS circuitTable circuitText circuitTurnMarkup circuitUprights CircuitWords cornerSpeed drawCircuit drawRace FEED_LIMITS FEED_MAX_BYTES feedAddress FeedFollower feedFromText FeedProblemKind FeedResult flatRaceShow FOLLOW_EVERY followModeOf followRaceFeed gapText KYOGIJO_CIRCUIT_STYLE KyogijoRace lapTime LEADER_CLEAR leaderMarkup lineLength loadRaceFeed looksLikeOpenF1Laps mountCircuitRace mountCircuitTurn OpenF1Driver openF1Feed OpenF1Lap OpenF1Location OpenF1Pit OpenF1Rows openF1Siblings paceProfile PaceProfile planBox PlanTurn podiumData PodiumData PodiumLine RACE_CARS_MAX RACE_DISTANCE RACE_DRIVERS RACE_FOLLOW_LIMITS RACE_PACE RACE_SPEEDS RACE_STYLE RACE_TEAMS RACE_WORDS raceAt raceBoard RaceCar raceClock raceDrawing RaceDrawing RaceDrawOptions RaceDriver RaceFeed RaceFeedCar RaceFeedError raceFollowInput raceFollowMode RaceFollowMode raceFromFeed raceLapMarks raceLaps raceLapStep raceLeaderMark RaceMoment RaceOptions racePoint raceStage RaceStanding RaceState RaceStatus RaceStop RaceTeam raceTimeText raceToFeed RaceViewOptions RaceViewSettings RaceWords readRaceFeed simulateRace speedAt standingGap TOWER_ROWS TOWER_STYLE TOWER_W towerData TowerData towerFrame towerHeight towerMarkup towerPlace TowerRow TowerView writeTower
function bindTower
bindTower(root: Element): TowerView
Find the elements of a tower made by towerMarkup inside root.
function buildCircuitTurn
buildCircuitTurn(options: CircuitOptions, settings?: TurnSettings): TurnModel
A circuit as a 3D model: its drawing as the floor, the pit building standing on it at its mapped height, and a marker with each turn's number on a post over its bend. settings.uprights: false is the floor alone. A TurnModel like any other: turnMarkupOf and mountCircuitTurn make a view of it.
function carAt
carAt(race: CircuitRace, index: number, t: number): { distance: number; pit: number; }
A car's race distance at a time (metres from the timing line), and its distance along the pit lane, or NaN on the track.
type Circuit
interface Circuit extends CircuitData { osm: CircuitOsm; }
A circuit: its facts and what OpenStreetMap maps of it.
const CIRCUIT_ATTRIBUTION
CIRCUIT_ATTRIBUTION: "(c) OpenStreetMap contributors, ODbL 1.0, openstreetmap.org/copyright"
The credit a drawing made from OpenStreetMap's data carries (the same words as the venues').
const CIRCUIT_IDS
CIRCUIT_IDS: readonly string[]
The keys of the circuits.
const CIRCUIT_MARKER
CIRCUIT_MARKER: Readonly<{ size: 30; post: 22; }>
The size of a turn's marker and the height of its post, in thousandths of the drawing's longer side (a marker, sized to be read: nothing of this size stands at a corner).
const CIRCUIT_PLANES_MAX
CIRCUIT_PLANES_MAX: 120
The most planes a circuit's 3D view may have: its markers (three planes each), its pit building and nothing else. A test holds every circuit to it.
const CIRCUIT_PRESETS
CIRCUIT_PRESETS: Readonly<Record<import("/home/runner/work/kyogijo-stadiums/kyogijo-stadiums/src/turn.camera").TurnPreset, import("/home/runner/work/kyogijo-stadiums/kyogijo-stadiums/src/turn.camera").TurnView>>
The four viewpoints of a circuit: straight down, the main camera high over the long side of the lap, the end-on view along it and the low corner. A lap is kilometres across and flat, so the eye is kept higher than a single surface's.
const CIRCUIT_WORDS
CIRCUIT_WORDS: Readonly<Record<Language, CircuitWords>>
type CircuitBasis
type CircuitBasis = "documented" | "plausible";
Whether a source says a fact (documented) or it is ours (plausible).
function circuitById
circuitById: (id: string) => Circuit | undefined
A circuit by its key, or undefined.
type CircuitData
interface CircuitData { /** The key: kebab case. */ id: string; /** The Wikidata item. */ wikidata: string; /** The articles and the revisions read. */ en: { title: string; revision: number }; ja: { title: string; revision: number }; /** The circuit's name: Wikidata's labels. */ names: { en: string; ja: string }; /** The country, as its two-letter code (Wikidata's P17). */ country: string; /** The day it opened, `yy…
A circuit's facts: scripts/circuits.data.json, checked against the raw answers by pnpm circuits.
function circuitDrawing
circuitDrawing(options: CircuitOptions): CircuitDrawing
A circuit's drawing and what was worked out to make it.
type CircuitDrawing
interface CircuitDrawing { svg: string; plan: CircuitPlan; /** The viewBox, in feet. */ viewBox: { x: number; y: number; w: number; h: number }; /** The size of the drawing's type and marks: a thousandth of its longer side, in feet. */ k: number; /** Where each turn's number is drawn (its badge's middle), in feet, or would be when `turns` is `false`. */ badges: { n: number; at: Pt; r: number }[]; title: string; desc…
A drawing of a circuit and what was worked out to make it.
type CircuitFact
interface CircuitFact<T> { value: T; basis: CircuitBasis; /** Where it was read: `wikidata` (CC0), `wikipedia` (the article and revision of the record, CC BY-SA 4.0, in our own words) or `openstreetmap` (ODbL); missing for one of ours. */ source?: "wikidata" | "wikipedia" | "openstreetmap"; /** What was read, in our own words. */ read: string; }
One fact, the source it was read from and in what words.
type CircuitOptions
interface CircuitOptions { /** The circuit's key: `las-vegas`. */ circuit: string; /** `en` (the default) or `ja`. */ language?: Language; /** `light` or `dark` forces a theme; left out, the drawing follows the page and the device. */ theme?: "light" | "dark"; /** The name and the line of facts in the top corner: `true` (the default) or `false`. */ label?: boolean; /** The turns' numbers: `true` (the default) or `fa…
The options of a circuit's drawing.
type CircuitOsm
interface CircuitOsm { /** The relation of the circuit, `relation/<id>`. */ source: string; /** The day the answer was read, and the base of the data it was read from. */ read: string; base: string; licence: "ODbL-1.0"; attribution: string; /** The lap: the relation's ways in the order and the direction it runs, joined into one ring, from the start, simplified to `tolerance` metres; longitude and latitude to six dec…
What OpenStreetMap maps of a circuit (ODbL 1.0): src/circuits.osm.data.ts, apart from every other file.
type CircuitOsmPoint
interface CircuitOsmPoint { /** The node, `node/<id>`. */ source: string; at: LonLat; }
A point of OpenStreetMap's that the drawing places: a turn, the start, the finish.
function circuitPlan
circuitPlan(circuit: Circuit): CircuitPlan
A circuit's plan: its lap, pit lane, ground, pit building, turns, start and finish in the drawing's frame.
type CircuitPlan
interface CircuitPlan { circuit: Circuit; /** The point of the map the frame is measured from (the middle of the lap's box), `[longitude, latitude]`. */ origin: LonLat; /** The heading of the lap's long side, degrees clockwise from north, and the way north points on the page, degrees clockwise from its top. */ heading: number; north: number; lap: Pt[]; /** The length of the lap measured along the drawn line, in metr…
A circuit's plan in the drawing's frame: feet, the long side of the lap along x, y down the page.
type CircuitRace
interface CircuitRace { circuit: Circuit; plan: CircuitPlan; seed: number; laps: number; cars: readonly RaceCar[]; /** The lap's length along the drawn line, in metres, and how far round it from the line's first point the timing line (the finish) is. */ lapLength: number; lineAlong: number; /** The pit lane: where it leaves the lap and joins it again (metres round the lap from the line's first point), and its length…
A race worked out: the cars, and each one's distance at every second, its laps, stops and finish.
const CIRCUITS
CIRCUITS: readonly Circuit[]
Every circuit, in the order of the data.
function circuitTable
circuitTable(options: CircuitOptions): string
A circuit's facts as a table, each with its basis (a source's, or ours) and the length the drawn line measures: for a reader who cannot see the drawing, and for a page that wants the data.
Example
import { circuitTable } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const table = circuitTable({ circuit: "las-vegas" });
console.log(table.startsWith("<table"), table.includes("6.201 km"));
// true true
function circuitText
circuitText(plan: CircuitPlan, language: Language, standing?: string): { title: string; description: string; }
The words of a circuit's drawing: its title and its description, sentence by sentence.
function circuitTurnMarkup
circuitTurnMarkup(options: CircuitOptions, settings?: TurnSettings): string
A circuit as the markup of a 3D view, still until a page's script makes it turn: pure, so a server can make it.
Example
import { circuitTurnMarkup } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const html = circuitTurnMarkup({ circuit: "las-vegas" }, { preset: "broadcast" });
console.log(html.includes('data-part="turn-17"'), html.includes("preserve-3d"));
// true false
function circuitUprights
circuitUprights(drawn: CircuitDrawing, thin: number, turns?: boolean): Upright[]
What stands up on a circuit's floor, in its plan's frame (feet): the pit building at its mapped height and each turn's number on a post over its badge's place beside the bend, the marker turned to face the eye and leaning back to be read square on. drawn is the circuit's drawing (its badges are where the markers stand), thin the width of a post and turns: false leaves the markers out (the pit building stays). The 3D view of the circuit stands these, and a district with the circuit stands them where it puts the circuit.
type CircuitWords
interface CircuitWords { /** The title: the circuit's name. */ title: string; /** The line under the name: the length and the number of turns. */ facts: string; /** The description, sentence by sentence. */ lap: string; counterclockwise: string; clockwise: string; turns: string; pit: string; building: string; width: string; /** What stands up in the 3D view. */ standing: string; standingNoBuilding: string; /** The c…
What a circuit's pictures say.
function cornerSpeed
cornerSpeed(r: number, pace?: Readonly<{ top: 94; grip: 22; downforce: 0.0036; brake: 34; launch: 17; step: 5; reach: 32; pitLimit: number; }>): number
The fastest speed a bend of radius r metres allows: v² = r × (grip + downforce × v²), and the top speed where the downforce holds it at any speed.
function drawCircuit
drawCircuit(options: CircuitOptions): string
A circuit as one SVG string: the lap as a ribbon of the track's width on the ways OpenStreetMap maps for it, the pit lane and the circuit's ground with its pit building, the start and the chequered finish across the track, arrows the way the lap runs, each turn's number beside its bend where OpenStreetMap numbers it, a north arrow, a scale bar and the credit of the map's data. Light and dark follow the page.
Example
import { drawCircuit } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const svg = drawCircuit({ circuit: "las-vegas" });
console.log(svg.startsWith("<svg"), svg.includes('data-turn="17"'), svg.includes("OpenStreetMap"));
// true true true
function drawRace
drawRace(options: RaceDrawOptions): string
A simulated race on a circuit at a moment, as one SVG string: the circuit's drawing with a dot for each made-up car where the race has it then, in its team's colour, with the position it holds written on it.
Example
import { drawRace } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const svg = drawRace({ circuit: "las-vegas", laps: 3, cars: 6, t: 120 });
console.log(svg.match(/class="ky-ci-car"/g)!.length, svg.includes("simulation"));
// 6 true
const FEED_LIMITS
FEED_LIMITS: Readonly<{ cars: 40; rows: 200000; laps: 200; }>
The most a feed may hold: cars, and rows of each list.
const FEED_MAX_BYTES
FEED_MAX_BYTES: 30000000
The most text a feed may be: 30 MB.
function feedAddress
feedAddress(text: string, base?: string): URL | undefined
An address the user typed, if it is one a page may read: http or https, nothing else.
type FeedFollower
interface FeedFollower { /** Stop asking. */ stop(): void; /** Whether it is still following. */ readonly following: boolean; }
What followRaceFeed gives back.
function feedFromText
feedFromText(text: string): FeedResult
Read a feed from text (pasted, or a file's): kyogijo's open race timeline, or the lap rows of an OpenF1-style API. The answer is a feed, or a sentence that says why not.
Example
import { feedFromText } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
console.log(feedFromText('{"kind":"kyogijo-race","version":1,"cars":[{"id":"a"}],"crossings":[{"car":"a","lap":1,"t":99}]}').ok, feedFromText("not json").ok);
// true false
type FeedProblemKind
type FeedProblemKind = "address" | "blocked" | "refused" | "busy" | "http" | "big" | "json" | "format";
Why a feed could not be read.
type FeedResult
type FeedResult = { ok: true; feed: RaceFeed } | { ok: false; error: string };
What reading a feed gives: the feed, or why it is not one, in words.
function flatRaceShow
flatRaceShow(svg: (): SVGSVGElement | null, box: () => FollowBox, maxZoom: number) => { show(shot: FollowShot | undefined): void; again(): void; }
Show a shot on a flat drawing: the part of it to show, by its viewBox (one attribute), and the whole drawing again for undefined. A drawing written again is a new element: it is shown whole until again. Returns what to call with a shot, and with a drawing that was just written.
const FOLLOW_EVERY
FOLLOW_EVERY: Readonly<{ least: 10000; normal: 15000; most: 120000; }>
How often a feed is asked again while it is followed: no faster than every 10 seconds, every 15 by default.
function followModeOf
followModeOf: (mode: RaceFollowMode) => FollowMode
The game camera's mode for a race's: the leader is the puck, the pack is the action.
function followRaceFeed
followRaceFeed(address: string, onFeed: (feed: RaceFeed): void, options?: { every?: number; fetch?: Fetch; doc?: Document; onError?: (error: RaceFeedError) => void; onStop?: (why: "over" | "refused" | "stopped") => void; }) => FeedFollower
Follow a race that is going on: ask the user's address again every 15 seconds (never faster than 10), only while the page is visible, and hand each new feed to onFeed. It stops by itself when the feed is no longer live (the race is over), when the source refuses (403) or says it is busy (429), and when stop is called; after any other failure it waits twice as long each time, up to two minutes. A hidden page asks nothing.
function gapText
gapText(seconds: number | undefined, laps: number, language: Language): string
A gap: +1.234, +1:02.345 past a minute, or the laps down in the words of the language.
const KYOGIJO_CIRCUIT_STYLE
KYOGIJO_CIRCUIT_STYLE: string
The rules of a circuit's drawing, and of the turn markers and the pit building of its 3D view (.ky-turn).
type KyogijoRace
interface KyogijoRace<O = RaceViewOptions, V = CircuitOptions> { /** The race it plays. */ readonly race: CircuitRace; /** The 3D view, when the race is on one. */ readonly turn: KyogijoTurn<V> | undefined; /** The places in the bar for the buttons of other features (the follow camera, the sound): empty elements that show only while they hold something. */ readonly slots: ReplayBarSlots; state(): RaceState; /** The …
What mountCircuitRace gives back (and mountDistrictRace, with a district's options and 3D view).
function lapTime
lapTime(seconds: number): string
A lap's time: 1:36.512.
const LEADER_CLEAR
LEADER_CLEAR: 1.5
How many metres clear of the car that holds the leader's mark the first car must be before the mark moves to it.
function leaderMarkup
leaderMarkup(line: RaceStanding, r: number, flag?: boolean): string
The leader's mark: a ring round the car's dot in a contrasting colour (amber, edged dark, so that it reads on a light or a dark ground) and a small "P1" tag above it, laid at the car's place. It is its own group, drawn after every car so that no dot lies over it, and it stays whatever the page does with the turn markers and the cars' numbers.
function lineLength
lineLength(points: readonly Pt[], closed: boolean): number
The length of a line, closed into a ring when closed.
function loadRaceFeed
loadRaceFeed(address: string, options?: { fetch?: Fetch; signal?: AbortSignal; base?: string; }): Promise<RaceFeed>
Read a race feed from an address the user gave, with the user's browser: kyogijo's open race timeline, or an OpenF1-style lap list (whose pit stops and drivers are then asked for from the same source and session, if it has them). It throws a RaceFeedError whose message says what went wrong in words: a source that does not let pages read it (CORS), a refusal (403), too many requests (429), not JSON, not a feed.
Example
``ts no-run import { loadRaceFeed, raceFromFeed } from "@johnmorrisdotca/kyogijo-stadiums/circuits"; const feed = await loadRaceFeed("https://example.org/my-race.json"); const race = raceFromFeed(feed, "las-vegas"); ``
function looksLikeOpenF1Laps
looksLikeOpenF1Laps: (input: unknown) => input is OpenF1Lap[]
Whether a list looks like OpenF1's lap rows: objects with a driver number and a lap number.
function mountCircuitRace
mountCircuitRace(host: HTMLElement, initial: RaceViewOptions, settings?: RaceViewSettings): KyogijoRace
Mount a simulated race on a circuit: the circuit flat (or in 3D) with a dot for each made-up car, the race clock, play and pause, the speeds 1×, 10× and 60×, a slider over the whole race and the timing board, moving together. It does nothing until it is played, and nothing while it is paused, hidden or out of sight.
Example
``ts no-run import { mountCircuitRace } from "@johnmorrisdotca/kyogijo-stadiums/circuits"; const race = mountCircuitRace(document.querySelector("#race")!, { circuit: "las-vegas" }, { speed: 10 }); race.play(); ``
function mountCircuitTurn
mountCircuitTurn(host: HTMLElement, options: CircuitOptions, settings?: TurnSettings): KyogijoTurn<CircuitOptions>
Mount a circuit as a 3D view in a container: the same view as mountKyogijoTurn's, with the controls, the pointer, the keys and the auto-turn of every 3D view, over the circuit's drawing with its pit building and the turns' numbers standing up. Where the browser cannot turn it, the flat drawing is shown.
Example
``ts no-run import { mountCircuitTurn } from "@johnmorrisdotca/kyogijo-stadiums/circuits"; const view = mountCircuitTurn(document.querySelector("#lap")!, { circuit: "las-vegas" }, { preset: "corner" }); view.set({ yaw: 40 }); ``
type OpenF1Driver
interface OpenF1Driver { driver_number: number; name_acronym?: string; broadcast_name?: string; last_name?: string; team_name?: string; team_colour?: string; }
A driver row: the code, the name and the team as the source gives them.
function openF1Feed
openF1Feed(rows: OpenF1Rows): RaceFeed
OpenF1-style rows as a race feed. The start is the earliest start of a first lap; a lap is completed at its start plus its duration (or, where the duration is missing, at the next lap's start). A pit stop runs from its row's time for its lane duration. Location rows, when given, become the feed's positions.
Example
import { openF1Feed } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const feed = openF1Feed({ laps: [
{ driver_number: 7, lap_number: 1, date_start: "2030-01-01T20:00:00Z", lap_duration: 101 },
{ driver_number: 7, lap_number: 2, date_start: "2030-01-01T20:01:41Z", lap_duration: 97.5 },
], drivers: [{ driver_number: 7, name_acronym: "ABC", team_name: "Made-up Team", team_colour: "3366CC" }] });
console.log(feed.cars[0].code, feed.cars[0].colour, feed.crossings.map((c) => c.t).join(" "));
// ABC #3366cc 101 198.5
type OpenF1Lap
interface OpenF1Lap { driver_number: number; lap_number: number; date_start?: string | null; lap_duration?: number | null; }
A lap row: who, which lap, when it started and how long it took.
type OpenF1Location
interface OpenF1Location { driver_number: number; date: string; x: number; y: number; }
A location row: where a car was, in the source's own frame.
type OpenF1Pit
interface OpenF1Pit { driver_number: number; lap_number?: number; date: string; pit_duration?: number | null; lane_duration?: number | null; stop_duration?: number | null; }
A pit row: who, on which lap, when it entered the pit lane and how long it was in it and standing.
type OpenF1Rows
interface OpenF1Rows { laps: readonly OpenF1Lap[]; pit?: readonly OpenF1Pit[]; drivers?: readonly OpenF1Driver[]; location?: readonly OpenF1Location[]; /** The laps of the race, if known. */ totalLaps?: number; /** True while the session is going on. */ live?: boolean; }
What the adapter is given: the rows of each answer the user's source gave. Only laps is needed.
function openF1Siblings
openF1Siblings(url: URL): { pit: string; drivers: string; } | undefined
For an OpenF1-style lap address (…/laps?session_key=…), the same source's pit and driver addresses for that session.
function paceProfile
paceProfile(plan: CircuitPlan, pace?: Readonly<{ top: 94; grip: 22; downforce: 0.0036; brake: 34; launch: 17; step: 5; reach: 32; pitLimit: number; }>): PaceProfile
A plan's speeds round its lap (circuitPlan), from its line alone: the bends' radii give each sample's fastest speed, and two passes round (twice, so that the lap closes on itself) hold it to the engine and the brakes. The same plan always gives the same profile.
Example
import { circuitById, circuitPlan, paceProfile } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const pace = paceProfile(circuitPlan(circuitById("las-vegas")!));
console.log(pace.lap > 90 && pace.lap < 105, Math.max(...pace.speed) * 3.6 > 300);
// true true
type PaceProfile
interface PaceProfile { /** Metres between two samples. */ step: number; /** The length of the line, in metres. */ length: number; /** The speed at each sample, metres a second, and the seconds from the line's first point to each (one more than the speeds: the last is the lap's time). */ speed: Float64Array; time: Float64Array; /** The time of a flying lap, in seconds. */ lap: number; }
A lap's speeds: one each step metres round the line from its first point, the time at each, and the lap's time and length.
function planBox
planBox: (plan: CircuitPlan) => FollowBox
The circuit's box as the follow camera's rectangle, in the plan's feet.
type PlanTurn
interface PlanTurn { n: number; at: Pt; along: number; dir: Pt; side: -1 | 0 | 1; }
A turn as the plan places it: its number, its point on the lap, how far round the lap it is, which way the lap runs there and the side the bend turns to (1 left, -1 right, 0 straight).
function podiumData
podiumData(race: CircuitRace, moment: RaceMoment, language: Language): PodiumData
The podium at a moment of a race: the first three as the board has them, a car that has taken the flag with its time or gap and one still racing as such. At the end of the race it is the finishing order.
type PodiumData
interface PodiumData { lines: PodiumLine[]; /** `Fastest lap: RTO Rautio, 1:37.996, lap 12`, or the empty string. */ fastest: string; final: boolean; }
What the podium card shows at a moment: the first three, the fastest lap, and whether the three have all taken the flag (so the order is final).
type PodiumLine
interface PodiumLine { id: string; position: number; /** The driver's name and the team's, made up. */ name: string; team: string; colour: string; ink: string; /** The race time for the winner, the gap for a car that has taken the flag behind, or `still racing`. */ time: string; finished: boolean; }
One line of the podium.
const RACE_CARS_MAX
RACE_CARS_MAX: number
The most cars a race can have, and the fewest.
const RACE_DISTANCE
RACE_DISTANCE: 305000
The distance of a race: the fewest laps that make more than 305 km, as a Grand Prix's is set.
const RACE_DRIVERS
RACE_DRIVERS: readonly RaceDriver[]
The drivers, two to a team in the order of RACE_TEAMS.
const RACE_FOLLOW_LIMITS
RACE_FOLLOW_LIMITS: Readonly<Partial<FollowLimits>>
How the race's camera frames and moves: it comes in much closer than a game's (a circuit is a long way across and a car a dot), up to six times at the leader and four on the leader alone, with a wider leash so that a leader at speed stays well inside the frame.
const RACE_PACE
RACE_PACE: Readonly<{ top: 94; grip: 22; downforce: 0.0036; brake: 34; launch: 17; step: 5; reach: 32; pitLimit: number; }>
The figures of the model, in metres and seconds.
const RACE_SPEEDS
RACE_SPEEDS: readonly number[]
The speeds the controls offer: real time, ten times and sixty times (a minute of the race a second).
const RACE_STYLE
RACE_STYLE: string
The rules of a race: the cars on the drawing, the clock, the controls and the board. Scoped to .ky-race and the cars of a circuit's or a district's drawing, in the page's own colours.
const RACE_TEAMS
RACE_TEAMS: readonly RaceTeam[]
The teams, from the quickest car to the slowest (RACE_FIELD gives the cars of the first n / 2).
const RACE_WORDS
RACE_WORDS: Readonly<Record<Language, RaceWords>>
function raceAt
raceAt(race: CircuitRace, time: number): RaceMoment
A moment of a race: each car's place on the drawing and its line of the timing board (position, laps, the gap to the leader and to the car in front, the last and best laps, the stops), the lap the leader is on and the fastest lap so far.
Example
import { raceAt, simulateRace } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const race = simulateRace({ circuit: "las-vegas", laps: 3, cars: 4 });
const now = raceAt(race, 150);
console.log(now.lap, now.standings.length, now.standings[0].position, now.flag);
// 2 4 1 false
function raceBoard
raceBoard(moment: RaceMoment, language?: Language): string
The timing board at a moment, as a table: position, driver and team, the gap to the leader and to the car in front, the last and best laps and the pit stops, the fastest lap marked. The colours of the teams are swatches beside their names, never the only way a car is told.
Example
import { raceAt, raceBoard, simulateRace } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const race = simulateRace({ circuit: "las-vegas", laps: 3, cars: 4 });
const table = raceBoard(raceAt(race, 200));
console.log(table.startsWith("<table"), (table.match(/<tr data-car/g) ?? []).length);
// true 4
type RaceCar
interface RaceCar { /** The driver's code in lower case: `hlv`. */ id: string; driver: RaceDriver; team: RaceTeam; /** Its place on the grid, 1 for pole. */ grid: number; }
A car of the race: its driver and team (made up) and where it started.
function raceClock
raceClock(seconds: number): string
A race clock: 23:45 or 1:23:45.
function raceDrawing
raceDrawing(options: RaceDrawOptions, given?: CircuitRace): RaceDrawing
The race, the drawing of its circuit and the moment, with the cars on it: the race the options make, or one given (from a feed).
type RaceDrawing
interface RaceDrawing extends CircuitDrawing { race: CircuitRace; moment: RaceMoment; }
A race's drawing at a moment, and what it was made from.
type RaceDrawOptions
interface RaceDrawOptions extends CircuitOptions, Omit<RaceOptions, "circuit"> { /** Seconds from the start: 0 (the grid) by default. */ t?: number; /** The timing tower standing beside the start and finish straight: `true` (the default) or `false`. */ tower?: boolean; }
What a race's drawing is made from: the circuit's options, the race's, and the moment.
type RaceDriver
interface RaceDriver { code: string; name: { en: string; ja: string }; team: string; }
A made-up driver: a three-letter code, as a timing board shows one, the name in both languages, and the team.
type RaceFeed
interface RaceFeed { kind: "kyogijo-race"; version: 1; /** The circuit's key (`las-vegas`). A page may draw a feed on another circuit; the lap's shape is then the page's. */ circuit?: string; /** The laps of the race, if the feed knows them; else the most any car has done. */ laps?: number; /** A line about where the race comes from, shown with it. */ title?: string; cars: RaceFeedCar[]; /** When each car completed …
kyogijo's open race timeline: any feed, file or program can write it. Times are seconds from the start (the lights going out).
type RaceFeedCar
interface RaceFeedCar { id: string; /** A short code, as a timing board shows one: three letters. Missing, the id is used. */ code?: string; name?: string; team?: string; /** The team's colour, `#rrggbb`. Missing, one of the package's is used. */ colour?: string; /** Its place on the grid, 1 for pole. Missing, the order of `cars`. */ grid?: number; }
A car of a feed: an id the rest of the feed uses, and what the board shows of it. Everything but id is optional.
const RaceFeedError
RaceFeedError: typeof RaceFeedError
A feed that could not be read: what kind of problem, the answer's status if there was one, and a sentence.
function raceFollowInput
raceFollowInput(plan: CircuitPlan, moment: RaceMoment, behind?: number): FollowInput
What the camera is told of a moment: the leader as the puck and the cars behind it as the players, in the plan's feet, and the circuit as the surface. A retired car is not part of the group.
Example
import { raceAt, raceFollowInput, simulateRace } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const race = simulateRace({ circuit: "las-vegas", laps: 3, cars: 8 });
const input = raceFollowInput(race.plan, raceAt(race, 100));
console.log(input.objects.filter((o) => o.team === "puck").length, input.box.w > 0);
// 1 true
function raceFollowMode
raceFollowMode: (value: unknown) => RaceFollowMode
A mode from anything: leader and pack are themselves, everything else is off.
type RaceFollowMode
type RaceFollowMode = "off" | "leader" | "pack";
What the race's camera follows: nothing (the whole circuit), the leader alone, or the leading group (the leader and the cars just behind it, the frame pulling back as they spread).
function raceFromFeed
raceFromFeed(feed: RaceFeed, circuitId?: string): CircuitRace
A feed as a race (CircuitRace): the same shape a simulation gives, so that raceAt, drawRace, raceBoard and mountCircuitRace play it. The circuit is the feed's, or the one named here (a page draws a feed on the circuit it shows). Between the moments a feed gives, the cars run at the lap's own speeds.
Example
import { raceAt, raceFromFeed } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const race = raceFromFeed({ kind: "kyogijo-race", version: 1, cars: [{ id: "a", code: "AAA" }, { id: "b", code: "BBB" }], crossings: [{ car: "a", lap: 1, t: 101 }, { car: "b", lap: 1, t: 102.5 }, { car: "a", lap: 2, t: 198 }, { car: "b", lap: 2, t: 200 }] }, "las-vegas");
const end = raceAt(race, race.duration);
console.log(race.laps, end.standings[0].car.driver.code, end.standings[1].gap);
// 2 AAA 2
function raceLapMarks
raceLapMarks(race: CircuitRace): readonly number[]
function raceLaps
raceLaps: (circuit: Pick<Circuit, "length">) => number
The laps of a full race distance on a circuit: 50 at Las Vegas.
function raceLapStep
raceLapStep(race: CircuitRace, t: number, direction: 1 | -1): number
Where one step of a race's bar goes from a time: on (1) to the next time the leader ends a lap, or the end of the race when none is left; back (-1) to the start of the lap in progress, or to the one before when the clock is within a second of it, or the start.
function raceLeaderMark
raceLeaderMark(moment: RaceMoment, held?: string): RaceStanding | undefined
The car that wears the leader's mark: the first car, except that two cars within a hair of each other do not hand it back and forth: the car that has it keeps it until the first is clear of it by LEADER_CLEAR metres, or it has retired or finished behind. held is the car that wore it a moment ago (none after a seek, which takes the first at once).
type RaceMoment
interface RaceMoment { /** Seconds since the start. */ t: number; /** The lap the leader is on (1 to `laps`), and the laps of the race. */ lap: number; laps: number; /** Whether the chequered flag has fallen, and whether the race is over (every car home). */ flag: boolean; over: boolean; /** The standings, leader first. */ standings: RaceStanding[]; /** The fastest lap so far: the car's place in `cars`, the lap and …
A moment of the race.
type RaceOptions
interface RaceOptions { /** The circuit's key: `las-vegas`. */ circuit: string; /** The seed every choice of the race is drawn from: a whole number, 1 by default. Another seed is another race. */ seed?: number; /** How many laps: by default a full race distance, the fewest laps that make 305 km (`raceLaps`). 1 to 200. */ laps?: number; /** How many cars: 2 to 20, 20 by default. */ cars?: number; }
What a race is made from: the circuit, and a seed, laps and cars of your own.
function racePoint
racePoint(race: CircuitRace, index: number, t: number): Pt
Where a car is on the drawing at a time, in the drawing's frame (feet): on the lap, or in the pit lane.
function raceStage
raceStage(moment: RaceMoment, language: Language): string
The race clock's line at a moment: the lap, the final lap, the flag or the grid.
type RaceStanding
interface RaceStanding { car: RaceCar; /** Its place in the race's `cars`. */ index: number; /** 1 for the leader. */ position: number; status: RaceStatus; /** Laps done. */ laps: number; /** Seconds behind the leader (undefined for the leader, and for a car a lap or more down), and laps down. */ gap?: number; lapsDown: number; /** The same to the car in front. */ interval?: number; intervalLaps: number; /** The las…
One line of the timing board.
type RaceState
interface RaceState { t: number; duration: number; playing: boolean; ended: boolean; speed: number; loop: boolean; markers: boolean; labels: boolean; tower: boolean; overlay: boolean; /** What the camera follows, and whether the reader's own turn or zoom of a 3D view holds it until it is resumed. */ follow: RaceFollowMode; followHeld: boolean; motion: "smooth" | "step"; }
What a race's view is doing.
type RaceStatus
type RaceStatus = "grid" | "running" | "pit" | "out" | "finished";
What a car is doing.
type RaceStop
interface RaceStop { lap: number; in: number; out: number; stop: number; }
A pit stop: the lap it ends, the time the car left the track and joined it again, and how long it stood still.
type RaceTeam
interface RaceTeam { id: string; name: { en: string; ja: string }; colour: string; ink: string; }
A made-up team: its name in both languages, and its colour and the colour of what is written on it.
function raceTimeText
raceTimeText(seconds: number): string
A time of a race that took the flag: 1:22:14.532, or 22:14.532 under an hour.
function raceToFeed
raceToFeed(race: CircuitRace, title?: string): RaceFeed
A race as the open race timeline: what a simulated race is, written as a feed (the demo's sample feed is one). Lap times are rounded to thousandths.
Example
import { raceToFeed, simulateRace } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const feed = raceToFeed(simulateRace({ circuit: "las-vegas", laps: 3, cars: 4 }));
console.log(feed.kind, feed.cars.length, feed.crossings.length);
// kyogijo-race 4 12
type RaceViewOptions
type RaceViewOptions = CircuitOptions & Omit<RaceOptions, "circuit">;
What a race's view is drawn from: the circuit's options and the race's.
type RaceViewSettings
interface RaceViewSettings { /** `flat` (the default) or `3d`: the circuit's 3D view, with the cars standing on it as discs that face the eye. */ view?: "flat" | "3d"; /** The 3D view's own settings (its viewpoint, its controls). */ turn?: TurnSettings; /** 1 (the default), 10 or 60; any speed from 1 to 600 is allowed. */ speed?: number; /** The turn numbers standing over the track (flat and in 3D): off by default, …
How a race is shown and played.
type RaceWords
interface RaceWords { /** The line that says what this is: a model, not a real race. */ simulated: string; /** The same line for a race from a feed the reader chose. */ feedNote: string; /** The race clock: the lap the leader is on, and the line under it once the flag has fallen. */ lap: string; finalLap: string; flag: string; grid: string; /** The time since the start, for a screen reader. */ elapsed: string; /** T…
What a race's pictures, controls and board say.
function readRaceFeed
readRaceFeed(input: unknown): FeedResult
Read a feed strictly: anything that is not the open race timeline is refused with a sentence that says why, and anything a feed carries that the format does not name is left behind. Text is kept as text (never markup).
Example
import { readRaceFeed } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const read = readRaceFeed({ kind: "kyogijo-race", version: 1, cars: [{ id: "a" }], crossings: [{ car: "a", lap: 1, t: 101 }] });
console.log(read.ok, readRaceFeed({ kind: "something" }).ok);
// true false
function simulateRace
simulateRace(options: RaceOptions): CircuitRace
A race on a circuit, worked out from a seed: made-up cars from the grid to the flag over a full race distance (50 laps of Las Vegas, about an hour and a half), with the gaps, overtakes, pit stops and retirements the model gives. The same options always give the same race; the last few asked for are kept.
Example
import { simulateRace } from "@johnmorrisdotca/kyogijo-stadiums/circuits";
const race = simulateRace({ circuit: "las-vegas", laps: 5, cars: 6, seed: 7 });
console.log(race.laps, race.cars.length, race.flag > 5 * 90 && race.flag < 5 * 110);
// 5 6 true
function speedAt
speedAt(profile: PaceProfile, along: number): number
The speed at along metres round the lap from the line's first point (wrapped), between the two samples either side.
function standingGap
standingGap(line: RaceStanding, language: Language, of?: "gap" | "interval"): string
What a line of the board shows in its gap column: the leader, a gap, laps down, the pit lane or out.
const TOWER_ROWS
TOWER_ROWS: 10
How many cars the tower lists; the rest go in the ticker under them.
const TOWER_STYLE
TOWER_STYLE: string
The tower's own rules: it is dark with light type on any ground, and the first row and the fastest lap are the accent. Scoped to where a tower can be (the plan view, the 3D view, the overlay).
const TOWER_W
TOWER_W: 220
The design's width, and the height of its head, of a row, and of the ticker and the fastest lap under the rows, in design units.
function towerData
towerData(race: CircuitRace, moment: RaceMoment, language: Language): TowerData
What the tower shows at a moment of a race. Pure: the same race, moment and language always give the same data.
type TowerData
interface TowerData { /** The clock's line: `Lap 10 / 50`, `On the grid`, `Chequered flag`. */ stage: string; flag: "grid" | "green" | "chequered"; rows: TowerRow[]; /** The codes of the cars after the listed ones, in order, or the empty string. */ rest: string; /** `FL RTO 1:37.996 L12`, or the empty string before a flying lap is done. */ fastest: string; }
What the tower shows at a moment.
function towerFrame
towerFrame(plan: CircuitPlan, k: number, cars: number): { rows: number; at: Pt; w: number; h: number; s: number; }
The tower's size and place in the plan, for a race of cars cars on a plan drawn with k (a thousandth of its longer side): its width is 17 of them.
function towerHeight
towerHeight: (rows: number) => number
The height of a tower of rows rows.
function towerMarkup
towerMarkup(data: TowerData, rows: number, language: Language): string
The tower at a moment as the inside of an SVG group of TOWER_W by towerHeight(rows) units: a head with the clock's line and the flag, a line for each of the first cars (its position, the team's colour, its code and its gap), the ticker for the rest and the fastest lap. Its texts carry data-t so that writeTower can change them in place.
function towerPlace
towerPlace(plan: CircuitPlan, w: number, h: number): { at: Pt; side: -1 | 1; }
Where the tower stands in the plan: its middle, beside the start and finish straight, on the side where its rectangle (and a margin the width of the track) is clear of the lap and the pit lane, as near the straight as that allows, and inside what the plan draws. In feet, like the plan.
type TowerRow
interface TowerRow { id: string; position: number; code: string; colour: string; /** What the gap column says: the leader's race time once it has taken the flag, otherwise the same words as the timing board (the pit lane is `PIT`). */ gap: string; status: RaceStatus; }
One line of the tower.
type TowerView
interface TowerView { root: Element; stage: Element | null; flag: Element | null; rest: Element | null; fast: Element | null; rows: { g: Element; pos: Element | null; sw: Element | null; code: Element | null; gap: Element | null }[]; /** What was last written, so that nothing is written twice. */ last: string; }
A tower that is in the page: the elements writeTower writes into.
function writeTower
writeTower(view: TowerView, data: TowerData): void
Write what the tower shows into a tower that is in the page: only what changed, and nothing at all when nothing did. Makes no element.