@versatiles/svg-renderer 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +95 -47
  2. package/dist/index.d.ts +689 -50
  3. package/dist/index.js +15289 -11315
  4. package/package.json +4 -1
package/dist/index.d.ts CHANGED
@@ -2559,19 +2559,585 @@ type BackgroundLayerSpecification = {
2559
2559
  };
2560
2560
  };
2561
2561
  type LayerSpecification = FillLayerSpecification | LineLayerSpecification | SymbolLayerSpecification | CircleLayerSpecification | HeatmapLayerSpecification | FillExtrusionLayerSpecification | RasterLayerSpecification | HillshadeLayerSpecification | ColorReliefLayerSpecification | BackgroundLayerSpecification;
2562
+ //#endregion
2563
+ //#region src/expression/types/color_spaces.d.ts
2564
+ /**
2565
+ * @param r Red component 0..1
2566
+ * @param g Green component 0..1
2567
+ * @param b Blue component 0..1
2568
+ * @param alpha Alpha component 0..1
2569
+ */
2570
+ type RGBColor = [r: number, g: number, b: number, alpha: number];
2571
+ /**
2572
+ * @param h Hue as degrees 0..360
2573
+ * @param c Chroma 0..~230
2574
+ * @param l Lightness as percentage 0..100
2575
+ * @param alpha Alpha component 0..1
2576
+ */
2577
+ type HCLColor = [h: number, c: number, l: number, alpha: number];
2578
+ /**
2579
+ * @param l Lightness as percentage 0..100
2580
+ * @param a A axis value -125..125
2581
+ * @param b B axis value -125..125
2582
+ * @param alpha Alpha component 0..1
2583
+ */
2584
+ type LABColor = [l: number, a: number, b: number, alpha: number];
2585
+ //#endregion
2586
+ //#region src/expression/types/color.d.ts
2587
+ type InterpolationColorSpace = 'rgb' | 'hcl' | 'lab';
2588
+ /**
2589
+ * Color representation used by WebGL.
2590
+ * Defined in sRGB color space and pre-blended with alpha.
2591
+ * @private
2592
+ */
2593
+ declare class Color {
2594
+ readonly r: number;
2595
+ readonly g: number;
2596
+ readonly b: number;
2597
+ readonly a: number;
2598
+ /**
2599
+ * @param r Red component premultiplied by `alpha` 0..1
2600
+ * @param g Green component premultiplied by `alpha` 0..1
2601
+ * @param b Blue component premultiplied by `alpha` 0..1
2602
+ * @param [alpha=1] Alpha component 0..1
2603
+ * @param [premultiplied=true] Whether the `r`, `g` and `b` values have already
2604
+ * been multiplied by alpha. If `true` nothing happens if `false` then they will
2605
+ * be multiplied automatically.
2606
+ */
2607
+ constructor(r: number, g: number, b: number, alpha?: number, premultiplied?: boolean);
2608
+ static black: Color;
2609
+ static white: Color;
2610
+ static transparent: Color;
2611
+ static red: Color;
2612
+ /**
2613
+ * Parses CSS color strings and converts colors to sRGB color space if needed.
2614
+ * Officially supported color formats:
2615
+ * - keyword, e.g. 'aquamarine' or 'steelblue'
2616
+ * - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9'
2617
+ * - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)'
2618
+ * - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)'
2619
+ *
2620
+ * @param input CSS color string to parse.
2621
+ * @returns A `Color` instance, or `undefined` if the input is not a valid color string.
2622
+ */
2623
+ static parse(input: Color | string | undefined | null): Color | undefined;
2624
+ /**
2625
+ * Used in color interpolation and by 'to-rgba' expression.
2626
+ *
2627
+ * @returns Gien color, with reversed alpha blending, in sRGB color space.
2628
+ */
2629
+ get rgb(): RGBColor;
2630
+ /**
2631
+ * Used in color interpolation.
2632
+ *
2633
+ * @returns Gien color, with reversed alpha blending, in HCL color space.
2634
+ */
2635
+ get hcl(): HCLColor;
2636
+ /**
2637
+ * Used in color interpolation.
2638
+ *
2639
+ * @returns Gien color, with reversed alpha blending, in LAB color space.
2640
+ */
2641
+ get lab(): LABColor;
2642
+ /**
2643
+ * Lazy getter pattern. When getter is called for the first time lazy value
2644
+ * is calculated and then overwrites getter function in given object instance.
2645
+ *
2646
+ * @example:
2647
+ * const redColor = Color.parse('red');
2648
+ * let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate
2649
+ * // the value of red in HCL space and invoke this `overwriteGetter` function
2650
+ * // which in turn will set a field with a key 'hcl' in the `redColor` object.
2651
+ * // In other words it will override `get hcl()` from its `Color` prototype
2652
+ * // with its own property: hcl = [calculated red value in hcl].
2653
+ * let y = redColor.hcl; // next call will no longer invoke getter but simply
2654
+ * // return the previously calculated value
2655
+ * x === y; // true - `x` is exactly the same object as `y`
2656
+ *
2657
+ * @param getterKey Getter key
2658
+ * @param lazyValue Lazily calculated value to be memoized by current instance
2659
+ * @private
2660
+ */
2661
+ private overwriteGetter;
2662
+ /**
2663
+ * Used by 'to-string' expression.
2664
+ *
2665
+ * @returns Serialized color in format `rgba(r,g,b,a)`
2666
+ * where r,g,b are numbers within 0..255 and alpha is number within 1..0
2667
+ *
2668
+ * @example
2669
+ * var purple = new Color.parse('purple');
2670
+ * purple.toString; // = "rgba(128,0,128,1)"
2671
+ * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');
2672
+ * translucentGreen.toString(); // = "rgba(26,207,26,0.73)"
2673
+ */
2674
+ toString(): string;
2675
+ static interpolate(from: Color, to: Color, t: number, spaceKey?: InterpolationColorSpace): Color;
2676
+ }
2677
+ //#endregion
2678
+ //#region src/point2d.d.ts
2679
+ interface Point2D$1 {
2680
+ x: number;
2681
+ y: number;
2682
+ }
2683
+ //#endregion
2684
+ //#region src/expression/index.d.ts
2685
+ type Feature$1 = {
2686
+ readonly type: 0 | 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon';
2687
+ readonly id?: any;
2688
+ readonly properties: {
2689
+ [_: string]: any;
2690
+ };
2691
+ readonly patterns?: {
2692
+ [_: string]: {
2693
+ min: string;
2694
+ mid: string;
2695
+ max: string;
2696
+ };
2697
+ };
2698
+ readonly dashes?: {
2699
+ [_: string]: {
2700
+ min: string;
2701
+ mid: string;
2702
+ max: string;
2703
+ };
2704
+ };
2705
+ readonly geometry?: Array<Array<Point2D$1>>;
2706
+ };
2707
+
2708
+ /** Values of the style's global state, by name, as read by `global-state` expressions. */
2709
+ type GlobalState = Record<string, unknown>;
2710
+
2711
+ type Properties = Record<string, unknown>;
2712
+ type Patterns = Record<string, {
2713
+ min: string;
2714
+ mid: string;
2715
+ max: string;
2716
+ }>;
2717
+ type Geometry = Point2D[][];
2718
+ type Bbox = [number, number, number, number];
2719
+ declare class Point2D implements Point2D$1 {
2720
+ x: number;
2721
+ y: number;
2722
+ constructor(x: number, y: number);
2723
+ isZero(): boolean;
2724
+ scale(factor: number): this;
2725
+ translate(offset: Point2D): this;
2726
+ getProject2Pixel(): Point2D;
2727
+ }
2728
+ declare class Feature implements Feature$1 {
2729
+ #private;
2730
+ readonly type: 'LineString' | 'Point' | 'Polygon';
2731
+ readonly id: unknown;
2732
+ readonly properties: Properties;
2733
+ readonly patterns?: Patterns;
2734
+ readonly geometry: Geometry;
2735
+ /**
2736
+ * The boundary of a polygon for the fill-antialias outline, as open polylines — when it
2737
+ * differs from the polygon's rings, i.e. when the polygon was clipped to its tile: the
2738
+ * clipped edges along the tile border are not part of the outline.
2739
+ */
2740
+ readonly outline?: Geometry;
2741
+ constructor(opt: {
2742
+ type: 'LineString' | 'Point' | 'Polygon';
2743
+ id?: unknown;
2744
+ properties: Properties;
2745
+ patterns?: Patterns;
2746
+ geometry: Geometry;
2747
+ outline?: Geometry;
2748
+ });
2749
+ getBbox(): Bbox;
2750
+ doesOverlap(bbox: Bbox): boolean;
2751
+ }
2562
2752
 
2563
- /** Options for {@link renderToSVG}. */
2564
- interface RenderToSVGOptions {
2753
+ interface ClipCircle {
2754
+ x: number;
2755
+ y: number;
2756
+ radius: number;
2757
+ }
2758
+ type Triangle = [[number, number], [number, number], [number, number]];
2759
+ /** A triangle of a raster tile's mesh on the globe, drawn with its own affine transform. */
2760
+ interface RasterTriangle {
2761
+ /** Corners of the triangle within the tile image, in tile units (0..1). */
2762
+ source: Triangle;
2763
+ /** The same corners on screen, in pixels. */
2764
+ target: Triangle;
2765
+ }
2766
+ /** Space around the map's center, as MapLibre's `padding`, in pixels. */
2767
+ interface Padding {
2768
+ top?: number;
2769
+ right?: number;
2770
+ bottom?: number;
2771
+ left?: number;
2772
+ }
2773
+
2774
+ /**
2775
+ * A drawing surface the render pipeline paints a map onto. It only describes *how* to
2776
+ * draw; how the result is handed back is up to the backend, because those differ in
2777
+ * kind: the SVG backend serializes to a string ({@link StringRenderer}), while a raster
2778
+ * backend produces an encoded image buffer.
2779
+ */
2780
+ interface Renderer {
2781
+ readonly width: number;
2782
+ readonly height: number;
2783
+ /**
2784
+ * These two may be asynchronous, like {@link Renderer.drawIcons}: a pattern is a sprite
2785
+ * image, which a raster backend has to decode first.
2786
+ */
2787
+ drawBackgroundFill(style: BackgroundStyle): void | Promise<void>;
2788
+ drawPolygons(id: string, features: [Feature, FillStyle][]): void | Promise<void>;
2789
+ /** May be asynchronous, as a line pattern is a sprite image (see `drawPolygons`). */
2790
+ drawLineStrings(id: string, features: [Feature, LineStyle][]): void | Promise<void>;
2791
+ drawCircles(id: string, features: [Feature, CircleStyle][]): void;
2792
+ /**
2793
+ * Draws text labels, and (below) icons. Each feature is a single point: the pipeline
2794
+ * has already placed the symbol, one per point, line or polygon.
2795
+ */
2796
+ drawLabels(id: string, features: [Feature, SymbolStyle][]): void;
2797
+ /**
2798
+ * These two may be asynchronous. Their images arrive as data URIs, which a raster
2799
+ * backend has to decode before it can paint them, while the SVG backend simply embeds
2800
+ * the URI and stays synchronous. The pipeline awaits both, so layers keep their order
2801
+ * either way.
2802
+ */
2803
+ drawIcons(id: string, features: [Feature, IconStyle][], spriteAtlas: SpriteAtlas): void | Promise<void>;
2804
+ drawRasterTiles(id: string, tiles: RasterTile[], style: RasterStyle): void | Promise<void>;
2805
+ /** Restricts all drawing to a circle (the silhouette of the globe). */
2806
+ setClipCircle?(circle: ClipCircle): void;
2807
+ /**
2808
+ * Called once the map is complete: undoes any state set up for drawing it (such as the
2809
+ * clip circle), so that whoever gets the result can keep drawing on it.
2810
+ */
2811
+ finish?(): void;
2812
+ }
2813
+ /**
2814
+ * How labels and icons are drawn: not at all, as `<text>`, as the style's glyphs traced
2815
+ * into outlines, or as those with invisible text over them.
2816
+ */
2817
+ type LabelMode = 'none' | 'text' | 'glyphs' | 'glyphs-text';
2818
+ /**
2819
+ * A glyph's outline, in pixels at 24 per em (`GLYPH_EM`), as closed rings (to be filled
2820
+ * even-odd): x from the middle of its advance, y from the middle of its line of text.
2821
+ */
2822
+ interface GlyphOutline {
2823
+ /** Identifies the outline, for renderers that define each once. */
2824
+ key: string;
2825
+ rings: [number, number][][];
2826
+ /** The glyph's advance, in ems. */
2827
+ advance: number;
2828
+ }
2829
+ /** A glyph of a label drawn as glyphs: its outline, its middle on screen, angle and scale. */
2830
+ interface PlacedGlyph {
2831
+ outline: GlyphOutline;
2832
+ /** Where the middle of the glyph's advance lies, in the middle of its line of text. */
2833
+ x: number;
2834
+ y: number;
2835
+ /** Clockwise, in degrees. */
2836
+ angle: number;
2837
+ /** From the outline's units (24 per em) to pixels: the text size / 24. */
2838
+ scale: number;
2839
+ }
2840
+ interface BackgroundStyle {
2841
+ color: Color;
2842
+ opacity: number;
2843
+ /** `background-pattern`: drawn instead of `color`. */
2844
+ pattern?: FillPattern;
2845
+ }
2846
+ /**
2847
+ * A sprite image repeated over an area (`fill-pattern`, `background-pattern`), at its
2848
+ * display size (`width / pixelRatio`) and anchored to the world, as in MapLibre.
2849
+ */
2850
+ interface FillPattern {
2851
+ /** The image's name in the sprite. */
2852
+ name: string;
2853
+ sprite: SpriteEntry;
2854
+ /**
2855
+ * A screen point where one copy of the image has its top-left corner: one aligned with
2856
+ * the world's origin, so the pattern moves with the map.
2857
+ */
2858
+ origin: [number, number];
2859
+ /** How far the pattern turns around `origin`, clockwise in degrees: with the map's bearing. */
2860
+ angle?: number;
2861
+ /**
2862
+ * How much larger than its display size the image is drawn (1 if not given): MapLibre
2863
+ * scales patterns with the map from the zoom level's integer part, as its tiles are.
2864
+ */
2865
+ scale?: number;
2866
+ }
2867
+ interface FillStyle {
2868
+ color: Color;
2869
+ opacity: number;
2870
+ /** `fill-pattern`: drawn instead of `color`. */
2871
+ pattern?: FillPattern;
2872
+ translate: [number, number];
2873
+ /**
2874
+ * fill-outline-color. When omitted the fill `color` is used (MapLibre's
2875
+ * default: the antialias outline is drawn in the fill color).
2876
+ */
2877
+ outlineColor?: Color;
2878
+ /**
2879
+ * fill-antialias. When truthy, a ~1px edge outline in `outlineColor` is drawn
2880
+ * over all fills of the layer (a separate pass) so a lower feature's border
2881
+ * composites on top of later overlapping fills — matching MapLibre for
2882
+ * choropleths and stacked polygons.
2883
+ */
2884
+ antialias?: boolean;
2885
+ }
2886
+ interface LineStyle {
2887
+ blur: number;
2888
+ cap: 'butt' | 'round' | 'square';
2889
+ color: Color;
2890
+ dasharray?: number[];
2891
+ join: 'bevel' | 'miter' | 'round';
2892
+ miterLimit: number;
2893
+ offset: number;
2894
+ opacity: number;
2895
+ translate: [number, number];
2896
+ width: number;
2897
+ /** `line-pattern`: drawn instead of `color` and `dasharray`. */
2898
+ pattern?: LinePattern;
2899
+ }
2900
+ /**
2901
+ * A sprite image repeated along a line (`line-pattern`), spanning its width, as in MapLibre
2902
+ * (see `line_pattern.ts`).
2903
+ */
2904
+ interface LinePattern {
2905
+ /** The image's name in the sprite. */
2906
+ name: string;
2907
+ sprite: SpriteEntry;
2908
+ /** How far one copy of the image reaches along the line, in pixels. */
2909
+ period: number;
2910
+ }
2911
+ interface CircleStyle {
2912
+ color: Color;
2913
+ /** Opacity of the fill only; the stroke has its own, as in MapLibre. */
2914
+ opacity: number;
2915
+ radius: number;
2916
+ translate: [number, number];
2917
+ strokeWidth: number;
2918
+ strokeColor: Color;
2919
+ strokeOpacity: number;
2920
+ /** `circle-blur`: the share of the outer radius over which the circle fades out. */
2921
+ blur?: number;
2922
+ }
2923
+ interface RasterStyle {
2924
+ opacity: number;
2925
+ hueRotate: number;
2926
+ brightnessMin: number;
2927
+ brightnessMax: number;
2928
+ saturation: number;
2929
+ contrast: number;
2930
+ resampling: 'linear' | 'nearest';
2931
+ }
2932
+ /** One character of a label along a line: its center, and its angle in degrees. */
2933
+ interface GlyphPlacement {
2934
+ text: string;
2935
+ x: number;
2936
+ y: number;
2937
+ angle: number;
2938
+ }
2939
+ interface SymbolStyle {
2940
+ /**
2941
+ * For a label along a line: where each of its characters goes. The label is drawn glyph
2942
+ * by glyph there, centered on each position, instead of at the feature's point.
2943
+ */
2944
+ path?: GlyphPlacement[];
2945
+ /**
2946
+ * For a label drawn as the style's glyphs: each glyph's outline, where it goes and how
2947
+ * large. Drawn instead of the text.
2948
+ */
2949
+ glyphs?: PlacedGlyph[];
2950
+ /** With `glyphs`: also the text, invisible, so the label stays selectable and searchable. */
2951
+ textOverlay?: boolean;
2952
+ /**
2953
+ * For a label of several lines: each line, and the point its alignment (`justify`)
2954
+ * refers to, vertically at the middle of the line. The anchor and offset are applied
2955
+ * already; `text` is all lines.
2956
+ */
2957
+ lines?: {
2958
+ text: string;
2959
+ x: number;
2960
+ y: number;
2961
+ width?: number;
2962
+ }[];
2963
+ /** How the `lines` align at their points (`text-justify`). */
2964
+ justify?: 'left' | 'center' | 'right';
2965
+ /** `text-letter-spacing`, in ems. */
2966
+ letterSpacing?: number;
2967
+ text: string;
2968
+ size: number;
2969
+ font: string[];
2970
+ anchor: string;
2971
+ offset: [number, number];
2972
+ rotate: number;
2973
+ color: Color;
2974
+ opacity: number;
2975
+ haloColor: Color;
2976
+ haloWidth: number;
2977
+ }
2978
+ interface IconStyle {
2979
+ image: string;
2980
+ size: number;
2981
+ anchor: string;
2982
+ offset: [number, number];
2983
+ rotate: number;
2984
+ opacity: number;
2985
+ sdf: boolean;
2986
+ color: Color;
2987
+ haloColor: Color;
2988
+ haloWidth: number;
2989
+ /**
2990
+ * Fitted to its label (`icon-text-fit`): the box the icon spans, `[left, top, right,
2991
+ * bottom]` from its point, before `icon-size`; `anchor` and `offset` then do not apply.
2992
+ */
2993
+ fit?: [number, number, number, number];
2994
+ }
2995
+ interface RasterTile {
2996
+ x: number;
2997
+ y: number;
2998
+ width: number;
2999
+ height: number;
3000
+ dataUri: string;
3001
+ /**
3002
+ * On the globe a tile cannot be drawn as a rectangle. Instead it is split into a mesh of
3003
+ * triangles, each drawn with its own affine transform.
3004
+ */
3005
+ triangles?: RasterTriangle[];
3006
+ /**
3007
+ * An image on its own (an `image` source), with no neighbouring tiles to close seams
3008
+ * with: its triangles are drawn without the underlay that reaches beyond its border.
3009
+ */
3010
+ standalone?: boolean;
3011
+ }
3012
+ /** An image of the style's sprite: where it is on its sprite sheet, and how it stretches. */
3013
+ interface SpriteEntry {
3014
+ width: number;
3015
+ height: number;
3016
+ x: number;
3017
+ y: number;
3018
+ pixelRatio: number;
3019
+ sdf: boolean;
3020
+ sheetDataUri: string;
3021
+ sheetWidth: number;
3022
+ sheetHeight: number;
3023
+ /** The columns of the image that stretch with `icon-text-fit`, as `[from, to]` pixels. */
3024
+ stretchX?: [number, number][];
3025
+ /** The rows of the image that stretch with `icon-text-fit`, as `[from, to]` pixels. */
3026
+ stretchY?: [number, number][];
3027
+ /** The part of the image `icon-text-fit` fits to the label: `[left, top, right, bottom]` pixels. */
3028
+ content?: [number, number, number, number];
3029
+ /** Whether a fitted image keeps the content's aspect ratio, horizontally. */
3030
+ textFitWidth?: TextFit;
3031
+ /** Whether a fitted image keeps the content's aspect ratio, vertically. */
3032
+ textFitHeight?: TextFit;
3033
+ }
3034
+ type TextFit = 'stretchOrShrink' | 'stretchOnly' | 'proportional';
3035
+ type SpriteAtlas = Map<string, SpriteEntry>;
3036
+
3037
+ /**
3038
+ * The part of a `Response` the renderer uses. A real `Response` has all of it; the type
3039
+ * is spelled out so that using this package needs neither the DOM nor Node's type
3040
+ * definitions.
3041
+ */
3042
+ interface FetchResponse {
3043
+ readonly ok: boolean;
3044
+ readonly status: number;
3045
+ readonly headers: {
3046
+ get(name: string): string | null;
3047
+ };
3048
+ arrayBuffer(): Promise<ArrayBuffer>;
3049
+ json(): Promise<unknown>;
3050
+ }
3051
+ /**
3052
+ * Loads a URL, like `fetch`: the renderer loads tiles, sprites, TileJSON documents and GeoJSON data through it. It is called
3053
+ * with the URL only, and should resolve to a `Response`.
3054
+ */
3055
+ type FetchFunction = (url: string) => Promise<FetchResponse>;
3056
+
3057
+ /** Options for {@link SVGMapRenderer}: what stays the same for every view of the map. */
3058
+ interface SVGMapRendererOptions {
2565
3059
  /**
2566
3060
  * The MapLibre style to render.
2567
3061
  *
2568
- * Its sources must list their tile URLs directly (`tiles: [...]`). A style whose
2569
- * sources only point at a TileJSON document (`url: '.../tiles.json'`) renders as an
2570
- * **empty map without any error**, because the renderer does not fetch TileJSON. Styles
2571
- * built with `@versatiles/style` come in that form, so pass them through its
2572
- * `inlineSources()` first — see the examples on {@link renderToSVG}.
3062
+ * A source may list its tile URLs (`tiles: [...]`) or point at a TileJSON document
3063
+ * (`url: '.../tiles.json'`), which is fetched once, like the sprite, with
3064
+ * {@link SVGMapRendererOptions.fetch}. As in MapLibre GL JS, `tiles`, `minzoom`,
3065
+ * `maxzoom` and the like come from the document unless the style sets them, and
3066
+ * relative tile URLs are resolved against the document's URL. A GeoJSON source's `data`
3067
+ * may be a URL too. A source whose TileJSON or GeoJSON cannot be loaded is left out, and
3068
+ * the next render tries again.
2573
3069
  */
2574
3070
  style: StyleSpecification;
3071
+ /**
3072
+ * Whether and how to draw the style's symbol layers, its labels and icons:
3073
+ *
3074
+ * - `'none'`: neither labels nor icons.
3075
+ * - `'text'`: labels as `<text>` naming the style's fonts (`text-font`), which whatever
3076
+ * displays the SVG resolves, so they show in the intended typeface only where that font
3077
+ * is installed. In PNG output, with the fonts given by `fonts`.
3078
+ * - `'glyphs'`: labels as the style's own glyphs (`glyphs`), the letter shapes MapLibre
3079
+ * draws, traced into outlines: exact in every viewer and editor, but not text. Each
3080
+ * glyph is defined once and reused.
3081
+ * - `'glyphs-text'`: as `'glyphs'`, with the text laid invisibly over the outlines, so labels
3082
+ * stay selectable and searchable. (In PNG output, the same as `'glyphs'`.)
3083
+ *
3084
+ * Labels are placed as in MapLibre: at points, inside each polygon at the point farthest
3085
+ * from its edges, and along lines; labels and icons that would overlap one placed before
3086
+ * are left out, from the top layer down. With glyphs, they are laid out with MapLibre's
3087
+ * own metrics; as text, with the widths of Noto Sans. A style without `glyphs`, or glyphs
3088
+ * that cannot be loaded, fall back to `'text'`, reported through `onWarning`.
3089
+ * @defaultValue `'none'`, or as given by {@link SVGMapRendererOptions.renderLabels}
3090
+ */
3091
+ labels?: LabelMode;
3092
+ /**
3093
+ * Draw the style's labels and icons.
3094
+ * @deprecated Use {@link SVGMapRendererOptions.labels}: `true` is `'glyphs-text'`, `false`
3095
+ * is `'none'`.
3096
+ * @defaultValue `false`
3097
+ */
3098
+ renderLabels?: boolean;
3099
+ /**
3100
+ * How much memory the fetched tiles may take, in bytes. Tiles are kept so that
3101
+ * rendering an overlapping view does not fetch them again; beyond this size, the least
3102
+ * recently used ones are dropped. `0` keeps none.
3103
+ *
3104
+ * Tiles are kept for the lifetime of the instance, regardless of the HTTP caching
3105
+ * headers they were served with; see {@link SVGMapRenderer.clearCache}.
3106
+ * @defaultValue `134217728` (128 MB)
3107
+ */
3108
+ tileCacheSize?: number;
3109
+ /**
3110
+ * Loads tiles, sprites, TileJSON documents and GeoJSON data, like `fetch`, which is the default. Pass your own to send
3111
+ * headers, go through a proxy, or keep tiles in a cache on disk.
3112
+ *
3113
+ * It must return a real `Response`, and its status matters: a 404 or 204 means the
3114
+ * server has no such tile, which is remembered (see {@link SVGMapRendererOptions.tileCacheSize}); any other
3115
+ * error status, or a rejected promise, counts as failed, and the next render tries
3116
+ * again.
3117
+ * @defaultValue the global `fetch`
3118
+ */
3119
+ fetch?: FetchFunction;
3120
+ /**
3121
+ * Called with a message for each part of the style the renderer does not draw: a layer
3122
+ * type, a layer property, a source, or a TileJSON document that could not be loaded. Each
3123
+ * message is reported once per instance. Pass `() => {}` to silence them.
3124
+ *
3125
+ * Properties that make no difference to a flat, north-up map (e.g. `*-pitch-alignment`)
3126
+ * are not reported, nor are symbol layers unless {@link SVGMapRendererOptions.labels}
3127
+ * is set.
3128
+ * @defaultValue `console.warn`
3129
+ */
3130
+ onWarning?: (message: string) => void;
3131
+ /**
3132
+ * Values for the style's global state, read by `global-state` expressions, e.g. to
3133
+ * switch the language or a theme of a style. They override the defaults in the style's
3134
+ * `state`, like `map.setGlobalStateProperty(name, value)` in MapLibre GL JS.
3135
+ * @defaultValue the defaults of the style's `state`
3136
+ */
3137
+ globalState?: GlobalState;
3138
+ }
3139
+ /** The view to render: size, centre and zoom. */
3140
+ interface ViewOptions {
2575
3141
  /**
2576
3142
  * Width of the image in pixels.
2577
3143
  * @defaultValue `1024`
@@ -2584,34 +3150,127 @@ interface RenderToSVGOptions {
2584
3150
  height?: number;
2585
3151
  /**
2586
3152
  * Longitude of the map centre, in degrees.
2587
- * @defaultValue `0`
3153
+ * @defaultValue the longitude of the style's `center`, else `0`
2588
3154
  */
2589
3155
  lon?: number;
2590
3156
  /**
2591
3157
  * Latitude of the map centre, in degrees.
2592
- * @defaultValue `0`
3158
+ * @defaultValue the latitude of the style's `center`, else `0`
2593
3159
  */
2594
3160
  lat?: number;
2595
3161
  /**
2596
3162
  * Zoom level, as in MapLibre: each step doubles the scale. Fractional values are
2597
3163
  * allowed.
2598
- * @defaultValue `2`
3164
+ * @defaultValue the style's `zoom`, else `2`
2599
3165
  */
2600
3166
  zoom?: number;
2601
3167
  /**
2602
- * Draw the style's symbol layers: text labels and icons.
3168
+ * The compass direction that is up, in degrees, as in MapLibre: `90` puts east at the
3169
+ * top. The map turns around the image's center; labels stay upright.
3170
+ * @defaultValue the style's `bearing`, else `0`
3171
+ */
3172
+ bearing?: number;
3173
+ /**
3174
+ * Space around the map's center, in pixels, as MapLibre's `padding`: the center (`lon`,
3175
+ * `lat`) sits in the middle of the area inside it, e.g. to keep it clear of a panel laid
3176
+ * over the image. A number applies to all sides.
3177
+ * @defaultValue `0`
3178
+ */
3179
+ padding?: number | Padding;
3180
+ }
3181
+ /**
3182
+ * Renders many views of one MapLibre style as SVG.
3183
+ *
3184
+ * Does the work that depends only on the style once, when constructed or on the first
3185
+ * render, instead of on every call as {@link renderToSVG} does: the style is parsed once,
3186
+ * and the sprite (the icons, needed with `labels`) and the glyphs are fetched once. Tiles are kept
3187
+ * too (up to {@link SVGMapRendererOptions.tileCacheSize}), so overlapping views share
3188
+ * them. Use it to render a batch of views, e.g. thumbnails or a series of map sections.
3189
+ *
3190
+ * The style is read when the instance is created and is expected not to change
3191
+ * afterwards; to render a changed style, create a new instance. Renders may run
3192
+ * concurrently.
3193
+ *
3194
+ * @example Render several views of one style
3195
+ * ```ts
3196
+ * import { SVGMapRenderer } from '@versatiles/svg-renderer';
3197
+ *
3198
+ * const map = new SVGMapRenderer({ style });
3199
+ *
3200
+ * const berlin = await map.renderSVG({ lon: 13.4, lat: 52.52, zoom: 12 });
3201
+ * const potsdam = await map.renderSVG({ lon: 13.06, lat: 52.4, zoom: 12 });
3202
+ * ```
3203
+ */
3204
+ declare class SVGMapRenderer {
3205
+ #private;
3206
+ /**
3207
+ * @param options - The style, whether to draw labels, the tile cache size, how to load
3208
+ * tiles and sprites, and where to report unsupported parts of the style.
3209
+ * @throws If `tileCacheSize` is negative or not a number.
3210
+ */
3211
+ constructor(options: SVGMapRendererOptions);
3212
+ /**
3213
+ * Renders one view of the map as SVG. The result is a single self-contained SVG
3214
+ * document, as described on {@link renderToSVG}.
2603
3215
  *
2604
- * Off by default, because labels are the least faithful part of the output. They are
2605
- * drawn as horizontal text at the middle of their feature: labels that MapLibre curves
2606
- * along a line (`symbol-placement: "line"`, typically street names) come out straight,
2607
- * and there is no collision detection, so crowded label layers can overlap.
3216
+ * @param view - Size, centre and zoom. All optional.
3217
+ * @returns The SVG document, as a string beginning with `<svg`.
3218
+ * @throws If `width` or `height` is not positive.
3219
+ */
3220
+ renderSVG(view?: ViewOptions): Promise<string>;
3221
+ /**
3222
+ * Forgets the fetched tiles, sprite, TileJSON documents and GeoJSON data, so the next render fetches them again, e.g.
3223
+ * after they were updated on the server, or to free their memory.
3224
+ */
3225
+ clearCache(): void;
3226
+ /** Draws `view` onto `renderer`, which must already have the view's size. */
3227
+ protected draw<R extends Renderer>(renderer: R, view: ViewOptions): Promise<R>;
3228
+ /**
3229
+ * Where a coordinate lands in the image of `view`: its position in the units of
3230
+ * `width` and `height`, the same in the SVG and on the canvas of `renderCanvas`. Use
3231
+ * it to place your own drawing on the map.
2608
3232
  *
2609
- * The SVG names each label's font (`text-font`) and leaves resolving it to whatever
2610
- * displays the SVG, so labels use the intended typeface only where that font is
2611
- * installed or provided with `@font-face`.
2612
- * @defaultValue `false`
3233
+ * On the globe, a coordinate on its far side is hidden; then this returns `undefined`.
3234
+ * A position outside the image is returned as is, so it can lie beyond `width` and
3235
+ * `height`, or be negative. The map ends at about ±85.05° latitude, as in MapLibre: a
3236
+ * latitude beyond that, up to the poles, gives the position of the map's edge.
3237
+ *
3238
+ * @example Mark a place on a rendered canvas
3239
+ * ```ts
3240
+ * const view = { lon: 13.4, lat: 52.52, zoom: 12 };
3241
+ * const canvas = await map.renderCanvas(view);
3242
+ * const [x, y] = map.project(view, [13.3777, 52.5163])!; // Brandenburg Gate
3243
+ * const ctx = canvas.getContext('2d');
3244
+ * ctx.beginPath();
3245
+ * ctx.arc(x, y, 6, 0, 2 * Math.PI);
3246
+ * ctx.fill();
3247
+ * ```
3248
+ *
3249
+ * @param view - The view the image was rendered with.
3250
+ * @param lonLat - Longitude and latitude, in degrees.
3251
+ * @returns `[x, y]`, or `undefined` for a point hidden on the globe, and for a
3252
+ * longitude or latitude that is not a finite number.
3253
+ * @throws If `width` or `height` is not positive.
2613
3254
  */
2614
- renderLabels?: boolean;
3255
+ project(view: ViewOptions, lonLat: [number, number]): [number, number] | undefined;
3256
+ /**
3257
+ * The opposite of {@link SVGMapRenderer.project}: the coordinate shown at a position in
3258
+ * the image of `view`, e.g. where a user clicked on it.
3259
+ *
3260
+ * Where the image shows no map — next to the globe, or beyond the poles of the mercator
3261
+ * map (about ±85°) — this returns `undefined`. The longitude is between -180 and 180.
3262
+ *
3263
+ * @param view - The view the image was rendered with.
3264
+ * @param xy - A position in the units of `width` and `height`.
3265
+ * @returns `[lon, lat]` in degrees, or `undefined` where there is no map, and for a
3266
+ * position that is not a finite number.
3267
+ * @throws If `width` or `height` is not positive.
3268
+ */
3269
+ unproject(view: ViewOptions, xy: [number, number]): [number, number] | undefined;
3270
+ }
3271
+
3272
+ /** Options for {@link renderToSVG}: the style and the view, in one object. */
3273
+ interface RenderToSVGOptions extends Omit<SVGMapRendererOptions, 'tileCacheSize'>, ViewOptions {
2615
3274
  }
2616
3275
  /**
2617
3276
  * Renders a MapLibre style to an SVG image.
@@ -2625,43 +3284,23 @@ interface RenderToSVGOptions {
2625
3284
  * `@versatiles/svg-renderer`, `@versatiles/png-renderer` and
2626
3285
  * `@versatiles/maplibre-svg-export`; the examples import it from the first.
2627
3286
  *
2628
- * @example Render a map in Node.js
2629
- * ```ts
2630
- * import { renderToSVG } from '@versatiles/svg-renderer';
2631
- * import { inlineSources, osm } from '@versatiles/style';
2632
- * import { writeFile } from 'node:fs/promises';
2633
- *
2634
- * // inlineSources() resolves the style's TileJSON sources into tile URLs,
2635
- * // which the renderer needs. Without it the map comes out empty.
2636
- * const style = await inlineSources(osm({ theme: 'colorful' }));
2637
- *
2638
- * const svg = await renderToSVG({
2639
- * style,
2640
- * width: 800,
2641
- * height: 600,
2642
- * lon: 13.4, // Berlin
2643
- * lat: 52.52,
2644
- * zoom: 12,
2645
- * });
2646
- *
2647
- * await writeFile('berlin.svg', svg);
2648
- * ```
3287
+ * Each call starts from scratch: it parses the style and fetches the tiles and the
3288
+ * sprite again. To render many views of one style, use {@link SVGMapRenderer}, which
3289
+ * keeps them between renders.
2649
3290
  *
2650
- * @example Render a hosted style in the browser
3291
+ * @example Render a map
2651
3292
  * ```ts
2652
3293
  * import { renderToSVG } from '@versatiles/svg-renderer';
2653
3294
  *
2654
- * // This hosted style already lists its tile URLs, so it can be used directly.
2655
- * const style = await fetch(
2656
- * 'https://tiles.versatiles.org/assets/styles/colorful/style.json',
2657
- * ).then((response) => response.json());
3295
+ * const url = 'https://tiles.versatiles.org/assets/styles/colorful/style.json';
3296
+ * const style = await (await fetch(url)).json();
2658
3297
  *
2659
- * document.body.innerHTML = await renderToSVG({ style, width: 800, height: 600, zoom: 3 });
3298
+ * const svg = await renderToSVG({ style, lon: 13.4, lat: 52.52, zoom: 12 });
2660
3299
  * ```
2661
3300
  *
2662
3301
  * @example Include labels and icons
2663
3302
  * ```ts
2664
- * const svg = await renderToSVG({ style, lon: 13.4, lat: 52.52, zoom: 14, renderLabels: true });
3303
+ * const svg = await renderToSVG({ style, lon: 13.4, lat: 52.52, zoom: 14, labels: 'glyphs-text' });
2665
3304
  * ```
2666
3305
  *
2667
3306
  * @param options - What to render and how large. Only `style` is required.
@@ -2670,5 +3309,5 @@ interface RenderToSVGOptions {
2670
3309
  */
2671
3310
  declare function renderToSVG(options: RenderToSVGOptions): Promise<string>;
2672
3311
 
2673
- export { renderToSVG };
2674
- export type { RenderToSVGOptions };
3312
+ export { SVGMapRenderer, renderToSVG };
3313
+ export type { FetchFunction, FetchResponse, GlobalState, RenderToSVGOptions, SVGMapRendererOptions, ViewOptions };