Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Add '3D Buildings' Example #80

Merged
merged 2 commits into from
Jan 17, 2025
Merged

docs: Add '3D Buildings' Example #80

merged 2 commits into from
Jan 17, 2025

Conversation

ciscorn
Copy link
Member

@ciscorn ciscorn commented Jan 17, 2025

No description provided.

@ciscorn ciscorn added documentation Improvements or additions to documentation example expand or improve examples labels Jan 17, 2025
@ciscorn ciscorn self-assigned this Jan 17, 2025
@ciscorn ciscorn changed the base branch from main to develop January 17, 2025 04:13
Copy link

Deploying svelte-maplibre-gl with  Cloudflare Pages  Cloudflare Pages

Latest commit: b14a4b6
Status: ✅  Deploy successful!
Preview URL: https://111ae8f3.svelte-maplibre-gl.pages.dev
Branch Preview URL: https://example-3d-buildings.svelte-maplibre-gl.pages.dev

View logs

Copy link

pkg-pr-new bot commented Jan 17, 2025

Open in Stackblitz

npm i https://pkg.pr.new/MIERUNE/svelte-maplibre-gl@80

commit: b14a4b6

Copy link

coderabbitai bot commented Jan 17, 2025

Walkthrough

This pull request encompasses a comprehensive update to the svelte-maplibre-gl project, focusing on enhancing documentation, example implementations, and dependency management. The changes span multiple areas, including package dependencies, component implementations, and documentation files.

Key modifications include updates to package.json with version upgrades for various dependencies, introduction of new example components like 3D Buildings and Globe with Atmosphere, and refinements to existing components such as Terrain and Custom Layer. Several markdown files were updated with metadata improvements, including adding original source links and adjusting descriptions.

The project also saw improvements in map component interfaces, with additions like new properties for MapLibre and Terrain components, and enhancements to custom layer implementations. The changes reflect ongoing development to improve the library's functionality, documentation, and user experience across different mapping scenarios.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 901317b and b14a4b6.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (51)
  • .prettierignore (1 hunks)
  • package.json (2 hunks)
  • src/content/CodeBlock.svelte (1 hunks)
  • src/content/docs/quickstart/content.svelte.md (1 hunks)
  • src/content/examples/3d-buildings/Buildings3D.svelte (1 hunks)
  • src/content/examples/3d-buildings/content.svelte.md (1 hunks)
  • src/content/examples/3d-extrusion-floorplan/Floorplan.svelte (1 hunks)
  • src/content/examples/3d-extrusion-floorplan/content.svelte.md (1 hunks)
  • src/content/examples/animate-images/content.svelte.md (1 hunks)
  • src/content/examples/basestyle/content.svelte.md (1 hunks)
  • src/content/examples/canvas-source/content.svelte.md (1 hunks)
  • src/content/examples/clusters/content.svelte.md (1 hunks)
  • src/content/examples/complex/Complex.svelte (0 hunks)
  • src/content/examples/contour/content.svelte.md (1 hunks)
  • src/content/examples/cursor/Cursor.svelte (3 hunks)
  • src/content/examples/custom-control/content.svelte.md (1 hunks)
  • src/content/examples/custom-layer/CustomLayer.svelte (2 hunks)
  • src/content/examples/custom-layer/content.svelte.md (1 hunks)
  • src/content/examples/custom-protocol/CustomProtocol.svelte (1 hunks)
  • src/content/examples/custom-protocol/content.svelte.md (1 hunks)
  • src/content/examples/deckgl-overlay/content.svelte.md (1 hunks)
  • src/content/examples/dynamic-image/content.svelte.md (1 hunks)
  • src/content/examples/fullscreen/content.svelte.md (1 hunks)
  • src/content/examples/geolocate/content.svelte.md (1 hunks)
  • src/content/examples/globe-atmosphere/Globe.svelte (1 hunks)
  • src/content/examples/globe-atmosphere/content.svelte.md (1 hunks)
  • src/content/examples/hover-styles/HoverStyles.svelte (2 hunks)
  • src/content/examples/hover-styles/content.svelte.md (1 hunks)
  • src/content/examples/image-loader/content.svelte.md (1 hunks)
  • src/content/examples/limit-interaction/content.svelte.md (1 hunks)
  • src/content/examples/marker-popup/MarkerAndPopup.svelte (0 hunks)
  • src/content/examples/pmtiles/PMTiles.svelte (3 hunks)
  • src/content/examples/pmtiles/content.svelte.md (1 hunks)
  • src/content/examples/query-features/Query.svelte (0 hunks)
  • src/content/examples/query-features/content.svelte.md (1 hunks)
  • src/content/examples/side-by-side/content.svelte.md (1 hunks)
  • src/content/examples/terrain/Terrain.svelte (2 hunks)
  • src/content/examples/terrain/content.svelte.md (1 hunks)
  • src/content/examples/threejs-model/CustomLayer.svelte (2 hunks)
  • src/content/examples/threejs-model/content.svelte.md (1 hunks)
  • src/content/examples/toc.ts (2 hunks)
  • src/content/examples/video-on-a-map/Video.svelte (1 hunks)
  • src/content/examples/video-on-a-map/content.svelte.md (1 hunks)
  • src/lib/components/Index.svelte (1 hunks)
  • src/lib/maplibre/map/MapLibre.svelte (2 hunks)
  • src/lib/maplibre/map/Terrain.svelte (1 hunks)
  • src/routes/docs/[slug]/+page.svelte (2 hunks)
  • src/routes/docs/components/[slug]/+page.svelte (2 hunks)
  • src/routes/docs/components/[slug]/+page.ts (2 hunks)
  • src/routes/examples/[slug]/+page.svelte (2 hunks)
  • src/routes/examples/[slug]/+page.ts (1 hunks)
💤 Files with no reviewable changes (3)
  • src/content/examples/complex/Complex.svelte
  • src/content/examples/marker-popup/MarkerAndPopup.svelte
  • src/content/examples/query-features/Query.svelte
✅ Files skipped from review due to trivial changes (29)
  • src/content/examples/deckgl-overlay/content.svelte.md
  • src/content/examples/pmtiles/content.svelte.md
  • src/content/examples/hover-styles/content.svelte.md
  • src/content/examples/video-on-a-map/Video.svelte
  • src/content/examples/fullscreen/content.svelte.md
  • src/content/examples/basestyle/content.svelte.md
  • src/content/examples/custom-control/content.svelte.md
  • src/content/examples/threejs-model/content.svelte.md
  • src/content/examples/image-loader/content.svelte.md
  • src/content/docs/quickstart/content.svelte.md
  • src/content/examples/canvas-source/content.svelte.md
  • src/lib/components/Index.svelte
  • src/routes/docs/components/[slug]/+page.svelte
  • src/content/examples/video-on-a-map/content.svelte.md
  • src/content/examples/dynamic-image/content.svelte.md
  • src/content/examples/clusters/content.svelte.md
  • src/content/examples/3d-extrusion-floorplan/content.svelte.md
  • src/content/examples/custom-protocol/CustomProtocol.svelte
  • src/content/examples/geolocate/content.svelte.md
  • src/content/examples/animate-images/content.svelte.md
  • src/content/examples/contour/content.svelte.md
  • src/content/examples/custom-protocol/content.svelte.md
  • src/content/examples/globe-atmosphere/content.svelte.md
  • src/content/examples/side-by-side/content.svelte.md
  • src/lib/maplibre/map/Terrain.svelte
  • src/content/examples/query-features/content.svelte.md
  • src/content/examples/pmtiles/PMTiles.svelte
  • src/content/examples/custom-layer/content.svelte.md
  • src/content/examples/limit-interaction/content.svelte.md
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (20)
src/content/examples/globe-atmosphere/Globe.svelte (1)

1-2: LGTM! Well-structured setup with TypeScript.

The component is properly configured with TypeScript and imports only the necessary components from svelte-maplibre-gl.

src/content/examples/3d-buildings/Buildings3D.svelte (1)

7-7: Verify the stability and security of the external CARTO basemap URL.

The hardcoded CARTO basemap URL might be subject to changes or rate limiting. Consider:

  1. Adding error handling for failed map loads
  2. Documenting any rate limits or usage restrictions
  3. Moving the URL to a configuration file
✅ Verification successful

The CARTO basemap URL is verified as stable and secure.

The URL points to a standard CARTO basemap style that is widely used across the codebase and is part of CARTO's official basemap collection. The endpoint is accessible and returns valid data. While moving the URL to a configuration file could be considered, the current implementation follows the common MapLibre pattern of inline style URLs.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the CARTO basemap URL is accessible and returns valid JSON
curl -s "https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json" | jq . > /dev/null
echo $?

Length of output: 88


Script:

#!/bin/bash
# Search for CARTO URL patterns and error handling
echo "=== Searching for CARTO URLs ==="
rg -i "cartocdn" -A 2 -B 2

echo -e "\n=== Searching for error handling patterns ==="
ast-grep --pattern 'catch ($_) { $$$ }'

echo -e "\n=== Checking for config files ==="
fd -e json -e js -e ts "config|settings" --type f

Length of output: 11700

src/routes/docs/[slug]/+page.svelte (1)

8-8: LGTM! Layout adjustments improve visual hierarchy.

The margin and height adjustments create better spacing and alignment between components.

Also applies to: 29-29

src/content/examples/cursor/Cursor.svelte (2)

2-2: LGTM! Code organization improvements.

The consolidated imports and simplified GeoJSON structure improve code readability while maintaining functionality.

Also applies to: 25-25, 37-37


53-54: Consider adding error handling for undefined features.

The event handler assumes features will always be present. Consider adding a null check.

-			onmousemove={(e) => (cursor = e.features![0].properties.cursor)}
+			onmousemove={(e) => (cursor = e.features?.[0]?.properties?.cursor)}
src/routes/examples/[slug]/+page.svelte (2)

8-8: LGTM! Enhanced layout and attribution.

The adjusted margins improve visual hierarchy, and the added original source attribution enhances documentation transparency.

Also applies to: 20-30


36-36: Verify the impact of aside height change.

The aside height calculation has been modified. Ensure this doesn't cause layout issues on different viewport sizes.

✅ Verification successful

Height calculation follows established pattern

The height calculation matches the pattern used consistently across similar components in the codebase, with proper responsive design handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other instances of viewport height calculations
rg "calc\(100vh-\d+rem\)"

Length of output: 1104

src/content/examples/hover-styles/HoverStyles.svelte (1)

2-5: LGTM! Improved hover state management.

The switch to hoveredFeature and addition of cursor position tracking enhances the interaction model.

src/content/examples/toc.ts (2)

17-20: Well-organized additions to the Basic section!

The new entries for cursor handling and 3D buildings are appropriately placed in the Basic section, maintaining a logical progression of examples from simple to complex.


22-27: Good restructuring with the new Styles section!

The creation of a dedicated Styles section for visual customization examples improves the organization and discoverability of these features.

src/lib/maplibre/map/MapLibre.svelte (3)

14-18: Great documentation improvement!

The added JSDoc comment clearly explains the purpose and usage of the map property, which is essential for component consumers.


34-42: Well-documented debugging properties!

The new properties for debugging and visualization are thoroughly documented with clear descriptions of their purposes.


574-574: Type-safe children rendering!

The updated children rendering now properly passes the Map instance to child components, enabling type-safe access to the map instance.

.prettierignore (1)

5-10: Well-organized Prettier configuration!

The changes maintain clean separation between different ignore patterns and appropriately exclude the shadcn-svelte UI components, which are likely auto-generated.

src/content/examples/terrain/content.svelte.md (1)

2-4: Improved documentation clarity and attribution!

The updated title and description better reflect the example's functionality, and the addition of the original example reference properly attributes the source.

src/content/examples/3d-buildings/content.svelte.md (3)

1-5: LGTM! Well-structured frontmatter with clear metadata.

The frontmatter includes all essential information: title, description, and reference to the original example.


7-12: LGTM! Clean script setup with proper imports.

The script section correctly imports required components and uses TypeScript for type safety.


14-16: LGTM! Proper component usage.

The layout follows the documentation pattern of showing the demo followed by its source code.

package.json (2)

66-67: Verify compatibility with maplibre-gl and pmtiles version changes.

The peer dependency changes include:

  • Reordered maplibre-gl version constraints
  • Updated pmtiles to ^4.0.0

Please ensure these changes are compatible with the new 3D Buildings example.

✅ Verification successful

✓ MapLibre GL JS v5 and PMTiles v4 compatibility verified

The version constraints are compatible, and a previously reported globe projection issue with PMTiles has been resolved in MapLibre GL JS v5.0.0. The flexible version range ensures backward compatibility.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for breaking changes in maplibre-gl and pmtiles changelogs
gh api graphql -f query='
{
  repository(owner: "maplibre", name: "maplibre-gl-js") {
    releases(first: 5, orderBy: {field: CREATED_AT, direction: DESC}) {
      nodes {
        tagName
        description
      }
    }
  }
}'

curl -s https://raw.githubusercontent.com/protomaps/PMTiles/main/CHANGELOG.md

Length of output: 13856


Script:

#!/bin/bash
# Try to fetch PMTiles changelog and releases through GitHub API
gh api graphql -f query='
{
  repository(owner: "protomaps", name: "PMTiles") {
    releases(first: 5, orderBy: {field: CREATED_AT, direction: DESC}) {
      nodes {
        tagName
        description
      }
    }
  }
}'

# Also search for any PMTiles related issues in maplibre-gl-js
gh api graphql -f query='
{
  search(query: "repo:maplibre/maplibre-gl-js pmtiles", type: ISSUE, first: 5) {
    nodes {
      ... on Issue {
        title
        url
        state
      }
    }
  }
}'

Length of output: 1225


71-72: Verify compatibility of development dependency updates.

Several major version updates in devDependencies:

  • @sveltejs/adapter-auto: ^4.0.0
  • eslint-config-prettier: ^10.0.1
  • pmtiles: ^4.2.1

Please ensure:

  1. The build pipeline still works with these updates
  2. No breaking changes affect the documentation site

Also applies to: 76-77, 87-88, 91-91, 93-93, 96-96, 98-98, 100-103, 105-106, 113-114, 117-117

✅ Verification successful

Dependencies update appears safe to proceed

The codebase already uses compatible APIs and standard configurations for all updated packages:

  • pmtiles is already using v4.x.x compatible code
  • @sveltejs/adapter-auto has standard SvelteKit configuration
  • eslint-config-prettier is a development-only tooling update
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential breaking changes in major version updates
for pkg in "@sveltejs/adapter-auto" "eslint-config-prettier" "pmtiles"; do
  echo "Checking $pkg:"
  npm view $pkg versions --json | jq -r '.[]' | sort -V | tail -n 5
  echo "---"
done

Length of output: 794


Script:

#!/bin/bash
# Check for configuration files and usage
echo "=== Checking for config files ==="
fd -e js -e cjs -e json "svelte.config|.eslintrc" --exec cat {}

echo -e "\n=== Checking for pmtiles usage ==="
rg -n "pmtiles" -A 2 -B 2

Length of output: 7472

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🧹 Nitpick comments (12)
src/content/examples/globe-atmosphere/Globe.svelte (3)

4-17: Enhance code readability with documentation and better naming.

The mathematical calculations are complex and would benefit from:

  1. Documentation explaining the purpose and mathematical basis of each formula
  2. More descriptive variable names (e.g., thetaDegrees, phiDegrees instead of thetaDeg, phiDeg)
  3. Constants for magic numbers (e.g., 180, Math.PI)

Here's a suggested improvement:

-let thetaDeg = $state(135);
-let phiDeg = $state(0);
-let p = $derived(
-   (Math.acos(Math.cos((thetaDeg / 180 + 1) * Math.PI) * Math.cos((phiDeg / 180) * Math.PI)) / Math.PI) * 180
-);
-let a = $derived(
+// Constants for angle conversions
+const DEG_TO_RAD = Math.PI / 180;
+const RAD_TO_DEG = 180 / Math.PI;
+
+// Theta angle for light source position (horizontal rotation)
+let thetaDegrees = $state(135);
+
+// Phi angle for light source position (vertical rotation)
+let phiDegrees = $state(0);
+
+// Calculate polar angle (p) for spherical coordinates
+let polarAngle = $derived(
+   RAD_TO_DEG * Math.acos(
+     Math.cos((thetaDegrees * DEG_TO_RAD) + Math.PI) * 
+     Math.cos(phiDegrees * DEG_TO_RAD)
+   )
+);
+
+// Calculate azimuthal angle (a) for spherical coordinates
+let azimuthalAngle = $derived(

20-29: Consider externalizing configuration values.

The MapLibre setup is well-structured, but consider:

  1. Moving the style URL to a configuration constant or environment variable
  2. Extracting the atmosphere-blend interpolation array for better readability

Example refactor:

+const MAP_STYLE_URL = 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json';
+const ATMOSPHERE_BLEND = ['interpolate', ['linear'], ['zoom'], 0, 1, 5, 1, 7, 0];
+
 <MapLibre
   class="h-[55vh] min-h-[300px]"
-  style="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json"
+  style={MAP_STYLE_URL}
   zoom={1.5}
   center={{ lng: 155, lat: 45 }}
 >
   <Projection type="globe" />
   <Light anchor="map" position={[100, a, p]} />
-  <Sky atmosphere-blend={['interpolate', ['linear'], ['zoom'], 0, 1, 5, 1, 7, 0]} />
+  <Sky atmosphere-blend={ATMOSPHERE_BLEND} />

30-42: Well-implemented accessible controls with room for enhancement.

The control panel is well-structured with proper accessibility features. Consider adding:

  • title attributes to provide additional context when hovering over the controls
  • aria-valuemin, aria-valuemax, and aria-valuenow for better screen reader support

Example enhancement:

 <input 
   type="range" 
   id="theta" 
   bind:value={thetaDeg} 
   min={-180} 
   max={180}
+  title="Adjust horizontal rotation of the light source"
+  aria-valuemin="-180"
+  aria-valuemax="180"
+  aria-valuenow={thetaDeg}
 />
src/content/examples/threejs-model/CustomLayer.svelte (2)

12-12: Ensure 'this.map' is safely initialized before usage

The this.map property is initialized in the onAdd method and used in the render method with non-null assertions (this.map!). Ensure that onAdd is always called before render, and consider adding checks or assertions to guarantee that this.map is not null to prevent potential runtime errors.

Also applies to: 15-15


48-55: Consider externalizing model parameters for flexibility

The hardcoded modelOrigin, modelAltitude, and scaling values in the render method limit the ability to reuse CustomLayerImpl with different models or locations. Consider externalizing these parameters to allow dynamic configuration and enhance the reusability of the class.

Apply this diff to refactor the code:

 class CustomLayerImpl implements Omit<maplibregl.CustomLayerInterface, 'id' | 'type'> {
+   constructor(
+     private modelOrigin: [number, number],
+     private modelAltitude: number,
+     private scaling: number
+   ) {}

    // ...

    render(_gl: WebGL2RenderingContext | WebGLRenderingContext, args: maplibregl.CustomRenderMethodInput) {
-     const modelOrigin: [number, number] = [148.9819, -35.39847];
-     const modelAltitude = 0;
-     const scaling = 10_000.0;

      // ...

-     const modelMatrix = this.map!.transform.getMatrixForModel(modelOrigin, modelAltitude);
+     const modelMatrix = this.map!.transform.getMatrixForModel(this.modelOrigin, this.modelAltitude);
      // ...

-     const l = new THREE.Matrix4().fromArray(modelMatrix).scale(new THREE.Vector3(scaling, scaling, scaling));
+     const l = new THREE.Matrix4().fromArray(modelMatrix).scale(new THREE.Vector3(this.scaling, this.scaling, this.scaling));
      // ...
    }
 }

- const customLayerImpl = new CustomLayerImpl();
+ const customLayerImpl = new CustomLayerImpl([148.9819, -35.39847], 0, 10_000.0);
src/content/examples/terrain/Terrain.svelte (1)

17-19: Remove unused 'terrain' variable and UI controls

The terrain variable is declared and manipulated via the UI slider but is not utilized in the code. Since <TerrainControl /> provides interactive control over terrain exaggeration, the separate terrain variable and its associated UI elements are redundant. Consider removing them to streamline the code and avoid confusion.

Apply this diff to remove the unused terrain variable and UI elements:

 // Terrain
-let hillshade = $state(0.7);
-let terrain = $state(1.0);
+let hillshade = $state(0.7);

 // ...

   <Tabs.Content value="terrain" class="min-h-0 shrink overflow-scroll pt-1">
-    <div class="mb-4 flex flex-col items-center space-y-2 px-2">
-      <Label for="exaggeration" class="leading-none">Exaggeration</Label>
-      <Slider type="single" id="exaggeration" min={0} max={2} step={0.01} />
-    </div>
     <div class="mb-3 flex flex-col items-center space-y-2 px-2">
       <Label for="hillshade" class="leading-none">Hillshade ({hillshade.toFixed(2)})</Label>
       <Slider type="single" id="hillshade" bind:value={hillshade} min={0} max={1} step={0.01} />
     </div>
     <!-- Remaining content -->
   </Tabs.Content>

Also applies to: 96-98

src/content/examples/custom-layer/CustomLayer.svelte (1)

44-77: Add error handling for shader compilation and program linking

The current implementation lacks error checking after shader compilation and program linking. This can make debugging difficult if there are issues with the shaders. Consider adding error handling using gl.getShaderInfoLog and gl.getProgramInfoLog to capture and log errors, enhancing the robustness of the application.

Apply this diff to include error handling:

       gl.shaderSource(vertexShader, vertexSource);
       gl.compileShader(vertexShader);
+      if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
+        console.error('Vertex shader compilation error:', gl.getShaderInfoLog(vertexShader));
+      }

       // Create fragment shader
       const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)!;
       gl.shaderSource(fragmentShader, fragmentSource);
       gl.compileShader(fragmentShader);
+      if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
+        console.error('Fragment shader compilation error:', gl.getShaderInfoLog(fragmentShader));
+      }

       // Link the two shaders into a WebGL program
       const program = gl.createProgram();
       gl.attachShader(program, vertexShader);
       gl.attachShader(program, fragmentShader);
       gl.linkProgram(program);
+      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+        console.error('Program linking error:', gl.getProgramInfoLog(program));
+      }
src/routes/examples/[slug]/+page.ts (1)

23-24: Consider providing default values for optional metadata.

While making description optional and adding original improves flexibility, consider providing default values to maintain a consistent user experience when these fields are missing.

 metadata: {
   title: string;
-  description?: string;
-  original?: string;
+  description: string = '';
+  original: string = '';
 };
src/content/examples/3d-buildings/Buildings3D.svelte (1)

20-30: Consider color accessibility in the height-based color scheme.

The current color interpolation (#aaccbbroyalbluepurple) might not be easily distinguishable for colorblind users. Consider:

  1. Using a more accessible color palette
  2. Adding patterns or textures for better differentiation
  3. Documenting the color meaning in the UI
src/content/CodeBlock.svelte (1)

20-28: LGTM! Consider adding aria-label to links.

The layout changes look good and the added context about styling libraries is helpful. Consider adding aria-labels to the links for better accessibility.

-		<a href="https://tailwindcss.com/">Tailwind CSS</a> and
-		<a href="https://next.shadcn-svelte.com/">shadcn-svelte</a>.
+		<a href="https://tailwindcss.com/" aria-label="Visit Tailwind CSS website">Tailwind CSS</a> and
+		<a href="https://next.shadcn-svelte.com/" aria-label="Visit shadcn-svelte website">shadcn-svelte</a>.
src/content/examples/hover-styles/HoverStyles.svelte (2)

21-26: Consider debouncing mousemove events.

Frequent mousemove events might impact performance. Consider adding debounce.

+	function debounce<T extends (...args: any[]) => any>(
+		fn: T,
+		ms = 100
+	): (...args: Parameters<T>) => void {
+		let timeoutId: ReturnType<typeof setTimeout>;
+		return (...args: Parameters<T>) => {
+			clearTimeout(timeoutId);
+			timeoutId = setTimeout(() => fn(...args), ms);
+		};
+	}
+
+	const handleMouseMove = debounce((ev: any) => {
+		hoveredFeature = ev.features?.[0];
+		lnglat = ev.lngLat;
+	}, 50);

-			onmousemove={(ev) => {
-				hoveredFeature = ev.features?.[0];
-				lnglat = ev.lngLat;
-			}}
+			onmousemove={handleMouseMove}

36-40: Consider adding loading state for popup.

The popup might flash if the feature data is loading. Consider adding a loading state.

 		{#if hoveredFeature}
 			<FeatureState id={hoveredFeature.id} state={{ hover: true }} />
-			<Popup {lnglat} closeButton={false}>{hoveredFeature.properties.STATE_NAME}</Popup>
+			<Popup {lnglat} closeButton={false}>
+				{#if hoveredFeature.properties?.STATE_NAME}
+					{hoveredFeature.properties.STATE_NAME}
+				{:else}
+					Loading...
+				{/if}
+			</Popup>
 		{/if}
🛑 Comments failed to post (3)
src/content/examples/3d-extrusion-floorplan/Floorplan.svelte (2)

14-16: 🛠️ Refactor suggestion

Add error handling for OpenStreetMap tile loading.

The tile source should handle loading failures gracefully. Consider adding error handling and a fallback tile source.

 <RasterTileSource 
   tiles={['https://tile.openstreetmap.org/{z}/{x}/{y}.png']} 
   tileSize={256} 
   minzoom={0} 
   maxzoom={19}
+  on:error={(e) => {
+    console.error('Tile loading error:', e);
+    // TODO: Switch to fallback tile source
+  }}
 >

Committable suggestion skipped: line range outside the PR's diff.


17-30: 🛠️ Refactor suggestion

Add error handling and loading state for external GeoJSON data.

The GeoJSON source loads data from an external URL without error handling or loading indicators. Consider:

  1. Adding error handling for failed data loads
  2. Implementing a loading state
  3. Validating the GeoJSON data structure
+<script lang="ts">
+  let dataError = false;
+  let isLoading = true;
+
+  async function validateAndLoadData() {
+    try {
+      const response = await fetch("https://maplibre.org/maplibre-gl-js/docs/assets/indoor-3d-map.geojson");
+      if (!response.ok) throw new Error('Failed to load GeoJSON');
+      const data = await response.json();
+      isLoading = false;
+      return data;
+    } catch (error) {
+      console.error('Error loading GeoJSON:', error);
+      dataError = true;
+      isLoading = false;
+      return null;
+    }
+  }
+</script>

-<GeoJSONSource data="https://maplibre.org/maplibre-gl-js/docs/assets/indoor-3d-map.geojson">
+<GeoJSONSource data={validateAndLoadData()}>

Committable suggestion skipped: line range outside the PR's diff.

src/routes/docs/components/[slug]/+page.ts (1)

15-19: 🛠️ Refactor suggestion

Improve error handling flow.

The current error handling might throw after attempting to execute a non-existent loader. Consider this refactor for better flow:

-       const loader = loaders[slug]();
-       if (!loader) {
+       if (!loaders[slug]) {
            error(404, `Component '${slug}' not found`);
        }
+       const loader = loaders[slug]();
        const doc = (await loader).default;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if (!loaders[slug]) {
		error(404, `Component '${slug}' not found`);
	}
	const loader = loaders[slug]();
	const doc = (await loader).default;

@ciscorn ciscorn merged commit cfe7d21 into develop Jan 17, 2025
6 checks passed
@ciscorn ciscorn deleted the example-3d-buildings branch January 17, 2025 04:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation example expand or improve examples
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant