website

source code for the ttmaths.uk website
Log | Files | Refs | README

Label.jsx (1161B)


      1 import { useContext } from 'preact/hooks';
      2 import { PlotContext } from '../../scripts/contexts.js';
      3 import { getColourClass } from '../../scripts/graphUtils.js';
      4 
      5 function getPosition(position) {
      6   switch (position) {
      7     case 'central':
      8       return ['central', 'middle', 0, 0];
      9     case 'left':
     10       return ['central', 'end', -1, 0];
     11     case 'right':
     12       return ['central', 'start', 1, 0];
     13     case 'top':
     14       return ['auto', 'middle', 0, 1];
     15     case 'bottom':
     16       return ['hanging', 'middle', 0, -1];
     17     case 'bottom-left':
     18       return ['hanging', 'end', -1, -1];
     19   }
     20 }
     21 
     22 export default function Label({ point, position='central', spacing=1, weight="normal", colour='auto', children }) {
     23   const [x, y] = point;
     24   const [dominantBaseline, textAnchor, dx, dy] = getPosition(position);
     25   const scaledSpacing = spacing * useContext(PlotContext).strokeWidth;
     26   return (
     27     <text
     28       x={x} y={-y} dx={scaledSpacing * dx} dy={scaledSpacing * -dy} transform='scale(1 -1)'
     29       dominant-baseline={dominantBaseline}
     30       text-anchor={textAnchor}
     31       class={getColourClass(colour)}
     32       font-weight={weight}
     33     >
     34       {children}
     35     </text>
     36   );
     37 }