diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json deleted file mode 100644 index a857ad3b0..000000000 --- a/.config/dotnet-tools.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "version": 1, - "isRoot": true, - "tools": { - "docfx": { - "version": "2.78.4", - "commands": [ - "docfx" - ], - "rollForward": false - } - } -} \ No newline at end of file diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile deleted file mode 100644 index efd685114..000000000 --- a/.devcontainer/Dockerfile +++ /dev/null @@ -1,42 +0,0 @@ -# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.236.0/containers/dotnet/.devcontainer/base.Dockerfile - -# [Choice] .NET version: 6.0, 3.1, 6.0-bullseye, 3.1-bullseye, 6.0-focal, 3.1-focal -ARG VARIANT="6.0" -FROM mcr.microsoft.com/vscode/devcontainers/dotnet:0-${VARIANT} - -# [Choice] Node.js version: none, lts/*, 18, 16, 14 -ARG NODE_VERSION="lts/*" -RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi - -# Run Updates First -RUN apt-get update --fix-missing && apt-get install -y unzip mono-complete wget git - -# Fix for Yarn issue -RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - - -#FROM mono:latest - -ENV DOCFX_VER 2.56.7 - -RUN curl -sSL --output packages-microsoft-prod.deb https://packages.microsoft.com/config/debian/10/packages-microsoft-prod.deb -RUN dpkg -i packages-microsoft-prod.deb - -RUN wget -q -P /tmp https://github.com/dotnet/docfx/releases/download/v${DOCFX_VER}/docfx.zip && \ - mkdir -p /opt/docfx && \ - unzip /tmp/docfx.zip -d /opt/docfx && \ - echo '#!/bin/bash\nmono /opt/docfx/docfx.exe $@' > /usr/bin/docfx && \ - chmod +x /usr/bin/docfx - -WORKDIR /home/ -COPY . . - -COPY setup.sh / -RUN chmod +x /setup.sh -RUN bash /setup.sh - -# [Optional] Uncomment this section to install additional OS packages. -# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ -# && apt-get -y install --no-install-recommends - -# [Optional] Uncomment this line to install global node packages. -# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 \ No newline at end of file diff --git a/.devcontainer/README.md b/.devcontainer/README.md index 7ccfc46aa..0311c2670 100644 --- a/.devcontainer/README.md +++ b/.devcontainer/README.md @@ -1,10 +1,20 @@ -# Run Build Commands +# Work on the gallery in a dev container -## Build +Open the repository in a VS Code dev container or GitHub Codespaces. The container includes Node.js 22, PowerShell, GitHub CLI, and Azure CLI, and installs the gallery's locked dependencies. +From the repository root: + +```shell +npm --prefix site run dev ``` -docfx docfx.json --build + +Open the forwarded port at `/script-samples/`. To check your changes: + +```shell +npm --prefix site test +npm --prefix site run build ``` -## Server -http-server -c-1 \ No newline at end of file +Browser tests need Chromium installed once with `npx playwright install chromium` from the `site` directory. Run them with `npm --prefix site run test:e2e`. + +You do not need to build the gallery to contribute a script. Follow the [contribution guide](../docs/contributing/preparing-a-submission.md). diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 74f57955a..6ed28cff0 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,64 +1,17 @@ -// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: -// https://github.com/microsoft/vscode-dev-containers/tree/v0.236.0/containers/dotnet { - "name": "C# (.NET)", - "build": { - "dockerfile": "Dockerfile", - "args": { - // Update 'VARIANT' to pick a .NET Core version: 3.1, 6.0 - // Append -bullseye or -focal to pin to an OS version. - "VARIANT": "6.0", - // Options - "NODE_VERSION": "lts/*" - } - }, - - // Configure tool-specific properties. - "customizations": { - // Configure properties specific to VS Code. - "vscode": { - // Add the IDs of extensions you want installed when the container is created. - "extensions": [ - "ms-dotnettools.csharp" - ] - } - }, - - // Use 'forwardPorts' to make a list of ports inside the container available locally. - // "forwardPorts": [5000, 5001], - - // [Optional] To reuse of your local HTTPS dev cert: - // - // 1. Export it locally using this command: - // * Windows PowerShell: - // dotnet dev-certs https --trust; dotnet dev-certs https -ep "$env:USERPROFILE/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere" - // * macOS/Linux terminal: - // dotnet dev-certs https --trust; dotnet dev-certs https -ep "${HOME}/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere" - // - // 2. Uncomment these 'remoteEnv' lines: - // "remoteEnv": { - // "ASPNETCORE_Kestrel__Certificates__Default__Password": "SecurePwdGoesHere", - // "ASPNETCORE_Kestrel__Certificates__Default__Path": "/home/vscode/.aspnet/https/aspnetapp.pfx", - // }, - // - // 3. Do one of the following depending on your scenario: - // * When using GitHub Codespaces and/or Remote - Containers: - // 1. Start the container - // 2. Drag ~/.aspnet/https/aspnetapp.pfx into the root of the file explorer - // 3. Open a terminal in VS Code and run "mkdir -p /home/vscode/.aspnet/https && mv aspnetapp.pfx /home/vscode/.aspnet/https" - // - // * If only using Remote - Containers with a local container, uncomment this line instead: - // "mounts": [ "source=${env:HOME}${env:USERPROFILE}/.aspnet/https,target=/home/vscode/.aspnet/https,type=bind" ], - - // Use 'postCreateCommand' to run commands after the container is created. - // "postCreateCommand": "dotnet restore", - - // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. - "remoteUser": "vscode", - "features": { - "github-cli": "latest", - "azure-cli": "latest", - "powershell": "latest" - }, - "postCreateCommand": "/bin/bash ./.devcontainer/post-create.sh" + "name": "Community Script Samples", + "image": "mcr.microsoft.com/devcontainers/typescript-node:1-22-bookworm", + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {}, + "ghcr.io/devcontainers/features/powershell:1": {}, + "ghcr.io/devcontainers/features/azure-cli:1": {} + }, + "customizations": { + "vscode": { + "extensions": ["astro-build.astro-vscode", "ms-vscode.PowerShell"] + } + }, + "forwardPorts": [4321], + "postCreateCommand": "npm --prefix site ci", + "remoteUser": "node" } diff --git a/.devcontainer/post-create.sh b/.devcontainer/post-create.sh deleted file mode 100644 index 4ca13b048..000000000 --- a/.devcontainer/post-create.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash - -# copy directory of plugins -sudo cp -r /workspaces/script-samples/docfx/plugins /opt/docfx \ No newline at end of file diff --git a/.devcontainer/setup.sh b/.devcontainer/setup.sh deleted file mode 100644 index 5f84a65e8..000000000 --- a/.devcontainer/setup.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash - -# npm modules -npm install -g http-server diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..6e19e9c1d --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,18 @@ +## What does this change help someone do? + +Describe the scenario or improvement, and link to any related issue. + +## How did you test it? + +Include tool versions, the expected result, and any limitations. Do not include credentials, tenant IDs, or personal data. + +## For new or updated samples + +- [ ] The README explains prerequisites, permissions, and the expected result. +- [ ] Each advertised tool tab contains a complete, tested script. +- [ ] Destructive actions have a clear impact warning before the script. +- [ ] Metadata, author attribution, tested tool versions, and the preview are accurate. +- [ ] No template placeholders or private tenant details remain. +- [ ] The final README tracker points to this sample. + +Need a hand? See the [contribution guide](../docs/contributing/preparing-a-submission.md). Every sample contributor is eligible for the [contributor badge](../docs/contributing/recognition.md) after their first accepted sample and recognition-program opt-in. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 4dcc427ea..99d670976 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -19,4 +19,4 @@ - A sample requires `README.md`, `assets/sample.json`, and `assets/preview.png`. The README screenshot is optional; the template includes `assets/example.png`. If scaffolding manually, copy `assets/template.sample.json` to `assets/sample.json` and fill in its metadata. - Remove credentials, usernames, and tenant-specific details from sample scripts. For scripts that delete or remove data, add a clear warning describing the impact before the script. - The final line of every script-root `README.md` must be the visitor-tracking image. Set its `src` to `https://m365-visitor-stats.azurewebsites.net/script-samples/{script-path}`, replacing `{script-path}` with the repository-relative sample directory, for example `scripts/spo-get-list-items`. Preserve existing attributes such as `aria-hidden` when present. -- For the full submission workflow and requirements, see the [contribution guide](../docfx/contributing/preparing-a-submission.md). For scaffolding an existing script submission, follow the [sample-scaffolder skill](skills/sample-scaffolder/SKILL.md). +- For the full submission workflow and requirements, see the [contribution guide](../docs/contributing/preparing-a-submission.md). For scaffolding an existing script submission, follow the [sample-scaffolder skill](skills/sample-scaffolder/SKILL.md). diff --git a/.github/schemas/sample.schema.json b/.github/schemas/sample.schema.json new file mode 100644 index 000000000..cae32ac90 --- /dev/null +++ b/.github/schemas/sample.schema.json @@ -0,0 +1,87 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://pnp.github.io/script-samples/schemas/sample.schema.json", + "title": "Community Script Samples metadata", + "type": "array", + "minItems": 1, + "maxItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name", "source", "title", "shortDescription", "url", "longDescription", "creationDateTime", "updateDateTime", "products", "metadata", "categories", "tags", "thumbnails", "authors", "references"], + "properties": { + "schema": { "type": ["string", "null"] }, + "version": { "type": ["string", "null"] }, + "name": { "type": "string", "minLength": 1, "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$" }, + "source": { "const": "pnp" }, + "title": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "shortDescription": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "url": { "type": "string", "format": "uri" }, + "longDescription": { "type": "array", "items": { "type": "string" } }, + "creationDateTime": { "type": "string", "format": "date" }, + "updateDateTime": { "type": "string", "format": "date" }, + "products": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "type": "string", "minLength": 1 } }, + "metadata": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["key", "value"], + "properties": { + "key": { "enum": ["PNP-POWERSHELL", "CLI-FOR-MICROSOFT365", "GRAPH-POWERSHELL", "SPO-MANAGEMENT-SHELL", "POWERSHELL", "AZURE-CLI", "POWERAPPS-POWERSHELL", "MICROSOFTTEAMS-POWERSHELL", "MICROSOFTWHITEBOARDADMIN", "JAVASCRIPT", "BASH", "GITHUB", "PYTHON"] }, + "value": { "type": "string", "minLength": 1, "pattern": "\\S" } + } + } + }, + "categories": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "enum": ["Modernize", "Data", "Deploy", "Provision", "Configure", "Report", "Security", "AI", "Microsoft Copilot"] } }, + "tags": { "type": "array", "uniqueItems": true, "items": { "type": "string", "minLength": 1 } }, + "thumbnails": { + "type": "array", + "minItems": 1, + "contains": { "type": "object", "required": ["type"], "properties": { "type": { "const": "image" } } }, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["type", "order", "url", "alt"], + "properties": { + "name": { "type": "string" }, + "type": { "enum": ["image", "video"] }, + "order": { "type": "integer", "minimum": 0 }, + "url": { "type": "string", "format": "uri" }, + "alt": { "type": "string", "minLength": 1, "pattern": "\\S" } + } + } + }, + "authors": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["gitHubAccount", "name", "pictureUrl"], + "properties": { + "gitHubAccount": { "type": "string", "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$" }, + "name": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "pictureUrl": { "type": "string", "format": "uri" }, + "company": { "type": "string" }, + "twitter": { "type": "string" } + } + } + }, + "references": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name", "description", "url"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "description": { "type": "string" }, + "url": { "type": "string", "format": "uri" } + } + } + } + } + } +} diff --git a/.github/skills/sample-scaffolder/SKILL.md b/.github/skills/sample-scaffolder/SKILL.md index e77d473cb..f23e416fc 100644 --- a/.github/skills/sample-scaffolder/SKILL.md +++ b/.github/skills/sample-scaffolder/SKILL.md @@ -30,3 +30,4 @@ This skill should - Ensure the script-root README.md ends with the current tracking image and replace `{script-path}` with a path such as `scripts/my-sample`. - Copy the template.sample.json file to the assets folder and rename it to sample.json. It should then fill in the relevant information from the sample submission into the sample.json file. - Copy the sample image to the assets folder. +- Validate the completed submission with `npm --prefix site run validate:samples`. The Astro gallery uses the sample README and metadata directly; shared documentation includes live under `docs/includes`. diff --git a/.github/workflows/deploy-gallery.yml b/.github/workflows/deploy-gallery.yml new file mode 100644 index 000000000..2cad70f82 --- /dev/null +++ b/.github/workflows/deploy-gallery.yml @@ -0,0 +1,87 @@ +name: Deploy gallery + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: {} + +concurrency: + group: github-pages + cancel-in-progress: true + +jobs: + build: + if: github.repository == 'pnp/script-samples' + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + defaults: + run: + working-directory: site + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Set up Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: "22.19.0" + cache: npm + cache-dependency-path: site/package-lock.json + - name: Install dependencies + run: npm ci + - name: Test catalog and sample generator + run: npm test + - name: Test generator + shell: pwsh + run: ./tests/generator.ps1 + - name: Build and validate production gallery + run: npm run build + env: + PUBLIC_COMMIT_SHA: ${{ github.sha }} + PUBLIC_ENABLE_VIEW_TRACKING: "true" + - name: Install Chromium + run: npx playwright install --with-deps chromium + - name: Test release + run: npm run test:e2e + - name: Upload Pages artifact + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: site/dist + + deploy: + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy GitHub Pages + id: deployment + uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5.0.0 + - name: Verify published commit + shell: pwsh + env: + SITE_URL: ${{ steps.deployment.outputs.page_url }} + EXPECTED_COMMIT: ${{ github.sha }} + run: | + $ErrorActionPreference = 'Stop' + $baseUrl = $env:SITE_URL.TrimEnd('/') + for ($attempt = 1; $attempt -le 12; $attempt++) { + try { + $marker = Invoke-RestMethod "$baseUrl/deployment.json" + $home = Invoke-WebRequest "$baseUrl/" + if ($marker.commit -ne $env:EXPECTED_COMMIT) { throw 'Deployed commit does not match this workflow.' } + if ($home.Content -notmatch 'Community Script Samples') { throw 'The gallery home page was not deployed.' } + Write-Host "Verified $baseUrl at commit $env:EXPECTED_COMMIT with $($marker.sampleCount) samples." + exit 0 + } catch { + if ($attempt -eq 12) { throw } + Start-Sleep -Seconds 10 + } + } diff --git a/.github/workflows/docfx-generate.yml b/.github/workflows/docfx-generate.yml deleted file mode 100644 index 76db80af7..000000000 --- a/.github/workflows/docfx-generate.yml +++ /dev/null @@ -1,73 +0,0 @@ -name: Generate Site -on: - push: - branches: - # Only update docs for main branch pushes - - main -# A workflow run is made up of one or more jobs that can run sequentially or in parallel -jobs: - # This workflow contains a single job called "build" - docfx: - permissions: - contents: write - # The type of runner that the job will run on - # Note temporary patch - https://github.com/actions/runner-images/issues/10636 - runs-on: ubuntu-latest - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - # prevent parallel executions - - name: Wait for actions to finish - uses: softprops/turnstyle@v2 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Checks-out main branch - - name: Checkout main branch - uses: actions/checkout@v4 - with: - ref: main - path: main - # Checks-out gh-pages branch - - name: Checkout gh-pages branch - uses: actions/checkout@v4 - with: - ref: gh-pages - path: gh-pages - # Install .NET SDK (if not already available) and DocFx as a dotnet tool - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: '8.x' - - name: Install DocFx - run: | - cd main - dotnet tool restore - # Build docs - - name: Build docs - shell: pwsh - run: | - $ErrorActionPreference = "Stop" - Set-StrictMode -Version 2.0 - - cd main - - # Data Generated Content - ./docfx/report-matrix.ps1 -BaseDir "." -ReportFile "./docfx/matrix.md" - ./docfx/report-metadata.ps1 -BaseDir "." -ReportFile "./docfx/metadata.md" - ./docfx/report-cmdusage.ps1 -BaseDir "." -ReportFile "./docfx/cmdusage.md" - ./docfx/report-age.ps1 -BaseDir "." -ReportFile "./docfx/age.md" - ./docfx/generate-samplesJson.ps1 -BaseDir "." -OutputFile "./docfx/samples.json" - - # Main DocFX build - dotnet docfx build ./docfx/docfx.json --warningsAsErrors $args - - # Copy the created site to the gh-pages folder - copy-item -Force -Recurse ./docfx/_site/* -Destination "../gh-pages" - # Add, commit and push the changes - - name: Add & Commit & Push - uses: EndBug/add-and-commit@v6 - with: - # The directory where your repository is located. You should use actions/checkout first to set it up - cwd: ./gh-pages - branch: gh-pages - push: true - token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/update-cmdlet-help.yml b/.github/workflows/update-cmdlet-help.yml index 4a1d12748..e21a956ad 100644 --- a/.github/workflows/update-cmdlet-help.yml +++ b/.github/workflows/update-cmdlet-help.yml @@ -18,8 +18,8 @@ jobs: - name: Clone help repositories run: | - mkdir -p docfx/help-repos - cd docfx/help-repos + mkdir -p tooling/help-repos + cd tooling/help-repos # Clone PnP PowerShell documentation git clone --depth 1 https://github.com/pnp/powershell.git pnp-powershell @@ -33,13 +33,13 @@ jobs: - name: Run Get-HelpJson.ps1 shell: pwsh run: | - cd docfx + cd tooling ./Get-HelpJson.ps1 - name: Check for changes id: check_changes run: | - if git diff --quiet docfx/assets/help/*.help.json; then + if git diff --quiet docs/assets/help/*.help.json; then echo "has_changes=false" >> $GITHUB_OUTPUT else echo "has_changes=true" >> $GITHUB_OUTPUT @@ -61,9 +61,9 @@ jobs: - [MicrosoftDocs/OfficeDocs-SharePoint-PowerShell](https://github.com/MicrosoftDocs/OfficeDocs-SharePoint-PowerShell) The following help files have been updated: - - `docfx/assets/help/powershell.help.json` - PnP PowerShell cmdlets - - `docfx/assets/help/cli.help.json` - CLI for Microsoft 365 commands - - `docfx/assets/help/spoms.help.json` - SharePoint Online Management Shell cmdlets + - `docs/assets/help/powershell.help.json` - PnP PowerShell cmdlets + - `docs/assets/help/cli.help.json` - CLI for Microsoft 365 commands + - `docs/assets/help/spoms.help.json` - SharePoint Online Management Shell cmdlets Please review the changes and merge if everything looks correct. branch: automated/update-cmdlet-help diff --git a/.github/workflows/validate-gallery.yml b/.github/workflows/validate-gallery.yml new file mode 100644 index 000000000..d5534841d --- /dev/null +++ b/.github/workflows/validate-gallery.yml @@ -0,0 +1,82 @@ +name: Validate gallery + +on: + pull_request: + paths: + - "scripts/**" + - "docs/**" + - "site/**" + - "tooling/**" + - "New-Sample.ps1" + - ".github/schemas/**" + - ".github/workflows/validate-gallery.yml" + - ".github/workflows/deploy-gallery.yml" + - "README.md" + - "CONTRIBUTING.md" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: "${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}" + cancel-in-progress: true + +jobs: + validate: + name: Validate catalog, site, and accessibility + runs-on: ubuntu-latest + timeout-minutes: 15 + defaults: + run: + working-directory: site + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Set up Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: "22.19.0" + cache: npm + cache-dependency-path: site/package-lock.json + - name: Install locked dependencies + run: npm ci + - name: Validate all sample metadata, assets, and README trackers + run: npm run validate:samples + - name: Test catalog and Markdown compatibility + run: npm test + - name: Test sample generator + shell: pwsh + run: ./tests/generator.ps1 + - name: Check and build production gallery + run: npm run build + env: + PUBLIC_COMMIT_SHA: ${{ github.sha }} + PUBLIC_ENABLE_VIEW_TRACKING: "false" + - name: Install Chromium + run: npx playwright install --with-deps chromium + - name: Test desktop, mobile, accessibility, and redirects + run: npm run test:e2e + - name: Summarize validation + if: always() + shell: bash + run: | + { + echo "## Community Script Samples validation" + echo "- Read-only PR validation: schema, source assets, trackers, generator, Markdown, Astro, links, redirects, desktop/mobile, and accessibility." + if [ -f dist/catalog.json ]; then + node -e 'const fs=require("node:fs");const c=JSON.parse(fs.readFileSync("dist/catalog.json","utf8"));console.log(`- ${c.samples.length} samples and ${c.contributors.length} contributors.`)' + echo "- Static artifact: $(du -sh dist | cut -f1)" + fi + echo "- Production view tracking is disabled for this PR build." + } >> "$GITHUB_STEP_SUMMARY" + - name: Upload browser failure diagnostics + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: gallery-browser-failures-${{ github.run_id }} + path: | + site/playwright-report/ + site/test-results/ + if-no-files-found: ignore + retention-days: 7 diff --git a/.gitignore b/.gitignore index 2bd9a609b..a3a70a05d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,5 @@ staging -docfx/matrix.md -docfx/metadata.md -docfx/cmdusage.md -docfx/_site +tooling/help-repos/ # Mac files .DS_Store -docfx/samples.json -docfx/age.md -docfx/usage.md diff --git a/.tours/contributing.tour b/.tours/contributing.tour index 864396e3a..a2a08800d 100644 --- a/.tours/contributing.tour +++ b/.tours/contributing.tour @@ -1,166 +1,82 @@ { "$schema": "https://aka.ms/codetour-schema", - "title": "Contributing to PnP Script Samples", + "title": "Share a Community Script Sample", "steps": [ { - "title": "Getting Started with New-Sample.ps1", - "description": "# Getting Started with using New-Sample.ps1 script\r\n\r\nTo run New-Sample.ps1, this has no dependencies other than run in place when you download the repository to your development workspace.\r\nThis will help you to generate the sample quickly.\r\n\r\n**If you are submitting, either use this script OR manually use the provided sample template.**\r\n\r\n## Usage example\r\n\r\n.\\New-Sample.ps1 `\r\n -ScriptFolderName \"spo-enable-disable-search-crawling\" `\r\n -ScriptTitle \"Enable/Disable Search Crawling on Sites and Libraries\" `\r\n -ScriptShortDescription \"Control the sites and libraries that get crawled. Also useful for Copilot projects to chose which areas to include\" `\r\n -ScriptTool PnPPowerShell `\r\n -AuthorFullName \"Paul Bullock\" `\r\n -GitHubId \"pkbullock\"\r\n\r\n## What this produces\r\n\r\nUnder the hood, this uses the _template-script-submission folder to populate and replace the values above with your own sample details. Then it will create all the files needed for sample submission and populate as much as possible based on your inputs, leaving you with just the script itself to insert into the README.md file. \r\n\r\n## When you have finished\r\n\r\nWhen you have finished creating your sample, submit a PR to script samples, we will validate and in some cases tweak the metadata of the script to ensure DocFx (the tool we use for the site) can render the sample. " + "title": "Let the generator do the setup", + "description": "Open PowerShell 7 at the cloned repository root, where New-Sample.ps1 and scripts are located. Use a new, unused folder name; the generator rejects existing folders.\n\n```powershell\n.\\New-Sample.ps1 -ScriptFolderName \"spo-get-site-report\" `\n -ScriptTitle \"Report SharePoint sites\" `\n -ScriptShortDescription \"Export a SharePoint site inventory.\" `\n -ScriptTool PnPPowerShell `\n -AuthorFullName \"Your name\" `\n -GitHubId \"your-github-handle\"\n```\n\nThe generator creates a README, sample.json, placeholder images, selected tool tabs, author details, and the final view tracker. It does not write or run your script. You still need to finish the documentation, select relevant products/categories, and replace example tool versions with tested ones.\n\nFor several tools, use comma-separated values such as PnPPowerShell,CliForMicrosoft365. All creates all eight supported tabs; remove any you do not implement. Follow docs/contributing/preparing-a-submission.md for the full checklist." }, { "directory": "scripts/_template-script-submission", - "description": "# Using the sample template folder \r\n\r\nFind the folder \"scripts/_template-script-submission\" and **make a copy**, then please update the copied template location for the folder name.\r\n\r\nFor example, workload-sample-details e.g. spo-upload-file Please keep to lower case, no spaces hyphens instead and workload first. This is to ensure its a relatively nice URL and will go through the build system.\r\n\r\n**Note: use this method if you do not prefer to run the \"New-Sample.ps1\" script**\r\n\r\nThe folder contains key assets used for displaying the sample on the website:\r\n\r\n- **README.md** - This contains all the details of your sample that is shown to site visitors\r\n- **assets/example.png** - If you have a screenshot of the output or visual of the change the script makes please provide that, it helps those reading the sample to understand what the script is doing.\r\n- **assets/preview.png** - Typically, this is a smaller version of the example file or if you prefer to show a section of the visual, this is used on the homepage of the sites to display a small graphic in the cards. Ideally, max width 650px. \r\n- **assets/template.sample.json** - This is a metadata file, typically used by all samples to show the details on the cards of the homepage and this is used for submission (automatically) into the [Solution Sample Gallery](https://adoption.microsoft.com/en-us/sample-solution-gallery/) - when submitting this, please rename to \"sample.json\" but keep it in the assets folder.", - "title": "Using the sample template", - "selection": { - "start": { - "line": 3, - "character": 1 - }, - "end": { - "line": 3, - "character": 143 - } - } + "title": "Prefer a manual starting point?", + "description": "Copy this template into a new folder under scripts. Keep the template itself unchanged. Choose a descriptive lowercase name with a workload prefix and hyphens.\n\nRename assets/template.sample.json to assets/sample.json, fill in placeholders, and keep only the tools you implement. Replace assets/preview.png; the separate README screenshot assets/example.png is optional. No website build is needed to contribute." }, { "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## sample.json - Update Folder Name\r\n\r\nIf you find and replace the folder name, there are approx three entries here, with the foldername of your sample.\r\nFor preference, workload-sample-details e.g. spo-upload-file \r\nPlease keep to lower case, no spaces hyphens instead and workload first. This is to ensure its a relatively nice URL and will go through the build system.", "line": 3, - "selection": { - "start": { - "line": 1, - "character": 1 - }, - "end": { - "line": 5, - "character": 155 - } - } + "title": "Make the sample discoverable", + "description": "In your copied sample, use the folder name as name. Fill in title and shortDescription with the task and expected result, not just the tool name. Replace folder/title placeholders in the sample and preview URLs too. Keep the one-record JSON array." }, { "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update the title of your sample \r\n\r\nAgain, find and replace, this is also used on the preview for the alt text. The title is displayed on the cards and within the solution sample gallery.", - "line": 5 - }, - { - "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Describe your sample\r\n\r\nWrite a short description of your sample, as mulitple types of scripts can be run, best to describe what it does rather than specifically mention a tool used to run it e.g. avoid \"X script written with PnP PowerShell...\". Instead \"Script produces 5 documents and uploads to SharePoint\". ", - "line": 6, - "selection": { - "start": { - "line": 1, - "character": 1 - }, - "end": { - "line": 3, - "character": 288 - } - } - }, - { - "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update the Folder Name\r\n\r\nIf you haven't earlier replaced all the folder names, update this one to the folder of the sample, please let the rest of the path as is.\r\n\r\nFor preference, workload-sample-details e.g. spo-upload-file \r\nPlease keep to lower case, no spaces hyphens instead and workload first. This is to ensure its a relatively nice URL and will go through the build system.", - "line": 7, - "selection": { - "start": { - "line": 1, - "character": 1 - }, - "end": { - "line": 6, - "character": 155 - } - } - }, - { - "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update the sample creation date to submission date\r\n\r\nThe best date format is \"yyyy-mm-dd\". ", "line": 11, - "selection": { - "start": { - "line": 1, - "character": 1 - }, - "end": { - "line": 3, - "character": 39 - } - } + "title": "Use meaningful dates", + "description": "Use yyyy-MM-dd dates. The generator fills these in for a new sample. When improving an existing sample, preserve creationDateTime and update updateDateTime for your change." }, { "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update the sample update date to submission date\r\n\r\nThe best date format is \"yyyy-mm-dd\". ", - "line": 12 + "line": 13, + "title": "Choose relevant products", + "description": "Remove products that are not used by your sample; do not leave the whole template list. Use Microsoft Copilot as that product's name. Products describe the workload; tools and versions belong in metadata." }, { "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update products\r\n\r\nRemove the products that are not relevant to your sample.", - "line": 13 + "line": 24, + "title": "Record the tools you tested", + "description": "Keep metadata entries for the tools your sample actually supports. Replace example version numbers, including generator defaults, with the versions you tested. Keep matching reference links to each tool's documentation." }, { "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update Metadata\r\n\r\nRemove the key/value pair that is not relevant to the sample. Optionally, update the version you are using to aid the reader to understand the version used to get this working.", - "line": 24 + "line": 70, + "title": "Choose scenarios and commands", + "description": "Keep only relevant categories, such as Report, Configure, or Security. Add command names and useful topics to tags so someone can find the sample by the task or command they know." }, { "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update Categories\r\n\r\nRemove the categories that are not relevant to your sample", - "line": 62 + "line": 84, + "title": "Replace the preview", + "description": "Replace assets/preview.png with a readable image representing your scenario. Check the thumbnail URL and describe the image in alt text. Remove tenant and personal information from screenshots." }, { "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update the cmdlets used\r\n\r\nThis is part of the filtering features on the site, to find samples specific to a cmdlet.\r\nThis is optional, we have a script that can collate these from the sample itself.", - "line": 73 - }, - { - "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update the author\r\n\r\nThis is part of attributing you to the sample, especially on the sample cards on the homepage and solution sample gallery.\r\nGithub is only supported, however samples are only submitted through PRs in GitHub anyway. ", - "line": 84 - }, - { - "file": "scripts/_template-script-submission/assets/template.sample.json", - "description": "## Update References\r\n\r\nRemove the references that are specific to help documentation based on the tooling you have used e.g. PnP PowerShell. Remove all other references if you feel they are not relevant.", - "line": 92 - }, - { - "file": "scripts/_template-script-submission/README.md", - "description": "# README.md - Update plugin setting \r\n\r\nRemove the -preparation part of the plugin, should read ```plugin: add-to-gallery```", - "line": 2 - }, - { - "file": "scripts/_template-script-submission/README.md", - "description": "## Enter your title\r\n\r\nAdd your title here", - "line": 5 - }, - { - "file": "scripts/_template-script-submission/README.md", - "description": "## Remove note\r\n\r\nThis is guidance to point contributors to the guidance page if folks look at code first. We either remove or can you remove both > [!Note ] and the next line.", - "line": 8 - }, - { - "file": "scripts/_template-script-submission/README.md", - "description": "## Remove unneeded tabs\r\n\r\nWe provide a set of tabs to use, they have to be unique, so either remove any not needed or if you require more than one, say 2 x PnP PowerShell, append a number to the end of the tab fragment e.g. \"#tab/pnpps2\"", - "line": 19 + "line": 92, + "title": "Credit everyone who helped", + "description": "Verify your name, GitHub account, and picture URL. Add coauthors and keep the README contributor list consistent. A company or social account is not required." }, { "file": "scripts/_template-script-submission/README.md", - "description": "## Keep these includes\r\n\r\nKeep only the include statements where you have put a script within the markdown, this provides guidance to readers of your script to get to know more about the module that runs the script.", - "line": 26 + "line": 1, + "title": "Explain the scenario", + "description": "In your copied README, use a clear title and summary. Remove the helper note and template text. Describe prerequisites, permissions, and the expected result. The README screenshot is optional; remove its reference if you do not use it." }, { "file": "scripts/_template-script-submission/README.md", - "description": "## Optional Credit\r\n\r\nEither keep and reference a blog post you used to provide credit to, promote your own work e.g. Blog, or if unneeded, please remove.", - "line": 95 + "line": 15, + "title": "Add the tested script", + "description": "Replace each placeholder with a complete implementation. Keep only the tool tabs you support and their shared documentation includes. Use safe example values, not credentials or private tenant details. Put an explicit impact warning before destructive operations." }, { "file": "scripts/_template-script-submission/README.md", - "description": "## Credit yourself\r\n\r\nYou're awesome, you spent time writing this, credit yourself accordingly. If there are multiple contributors to the script, then just add your name to the end of the other authors.", - "line": 101 + "line": 89, + "title": "Preserve attribution and the disclaimer", + "description": "If adapting another project, keep source credit and replace the example link with the actual source. Otherwise remove the example section. Credit all authors and keep the disclaimer. The generator's -KeepSourceCredit switch retains this section but does not choose the right link for you." }, { "file": "scripts/_template-script-submission/README.md", - "description": "## Update the src\r\n\r\nPlease keep this and update \"template-script-submission\" to match your folder, it allows us to see how many folks have read this page.\r\n\r\nThis is the last step, if you have updated the image, and completed the sections in the tour, you are ready to submit your GitHub Pull Request.\r\n\r\n**Thank you, and look forward to reviewing and marging your sample.**", - "line": 105 + "line": 101, + "title": "Keep the tracker last, then share", + "description": "The README's final line must be the visitor-tracking image. Replace {script-path} with the repository-relative sample directory, for example scripts/spo-get-site-report, using / separators. Preserve existing accessibility attributes. The generator fills this URL for you.\n\nTest your sample and open a focused pull request with the scenario and test details. Maintainers can help with finishing touches. After your first accepted sample, opt in at https://pnp.github.io/recognitionprogram/ to earn your Script Samples contributor badge. See docs/contributing/recognition.md for claiming and sharing it." } ], "ref": "main" -} \ No newline at end of file +} diff --git a/.vscode/settings.json b/.vscode/settings.json index 2888a81d7..0b5532552 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,10 @@ { + "json.schemas": [ + { + "fileMatch": ["/scripts/*/assets/sample.json"], + "url": "./.github/schemas/sample.schema.json" + } + ], "chat.tools.terminal.autoApprove": { "cp": true } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..b4cc5cbd3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,23 @@ +# Contribute to Community Script Samples + +Share a useful script, add another tool implementation, improve the guidance, or report a reproducible problem. First-time contributors are welcome. + +- [Create a sample with the generator](docs/contributing/preparing-a-submission.md). +- [Explore other ways to contribute](docs/contributing/how-can-i-contribute.md). +- [Open a focused pull request](docs/contributing/submitting-pull-requests.md). +- [Earn your Script Samples contributor badge](docs/contributing/recognition.md). +- [Get friendly, hands-on GitHub help](https://pnp.github.io/sharing-is-caring/). + +The gallery is built with Astro, but you do not need to build the website to share a script. Sample content remains under `scripts/`, and shared guidance lives under `docs/`. + +For website changes, use Node.js 22.19 or later: + +```shell +npm --prefix site ci +npm --prefix site test +npm --prefix site run build +``` + +See the [maintainers guide](docs/contributing/maintainers-guidance.md) for browser tests, local development, deployment, and compatibility requirements. + +Please follow the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). diff --git a/New-Sample.ps1 b/New-Sample.ps1 index d6bd8fab5..e7cc47ba0 100644 --- a/New-Sample.ps1 +++ b/New-Sample.ps1 @@ -30,7 +30,7 @@ [CmdletBinding()] param ( - #[ValidatePattern("")] + [ValidatePattern('^[a-z0-9]+(?:-[a-z0-9]+)*$')] [Parameter(Mandatory, HelpMessage = "The folder name for the script e.g. spo-get-list-items or graph-export-teams")] [Alias("FolderName")] @@ -38,11 +38,13 @@ param ( [Parameter(Mandatory, HelpMessage = "The title for the script e.g. Generate a list of SharePoint Sites")] + [ValidateNotNullOrEmpty()] [Alias("Title")] [string] $ScriptTitle, [Parameter(Mandatory, HelpMessage = "The description for the script")] + [ValidateNotNullOrEmpty()] [Alias("Description")] [string] $ScriptShortDescription, @@ -55,11 +57,13 @@ param ( [Parameter(Mandatory, HelpMessage = "The name of the script author e.g. Paul Bullock")] + [ValidateNotNullOrEmpty()] [Alias("MyName", "Author")] [string] $AuthorFullName, [Parameter(Mandatory, HelpMessage = "Your GitHub ID, e.g. pkbullock, this is only for attribution on the sample")] + [ValidatePattern('^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$')] [Alias("GHID", "AuthorId")] [string] $GitHubId, @@ -71,7 +75,7 @@ begin{ # ------------------------------------------------------------------------------ # Global Variables # ------------------------------------------------------------------------------ - $mainScriptFolder = "scripts" + $mainScriptFolder = Join-Path $PSScriptRoot "scripts" $sampleTemplateFolder = "_template-script-submission" $sampleAssetsFolder = "assets" $jsonSample = "sample.json" @@ -117,7 +121,7 @@ begin{ $tabBlocks = @{ "PnPPowerShell" = [PSCustomObject]@{ Tab = "# [PnP PowerShell](#tab/pnpps)" - IncludeBlock = "[!INCLUDE [More about PnP PowerShell](../../docfx/includes/MORE-PNPPS.md)]" + IncludeBlock = "[!INCLUDE [More about PnP PowerShell](../../docs/includes/MORE-PNPPS.md)]" ScriptBlock = $psScriptBlock Reference = [PSCustomObject]@{ "name" = "Want to learn more about PnP PowerShell and the cmdlets" @@ -130,7 +134,7 @@ begin{ "CliForMicrosoft365" = [PSCustomObject]@{ Tab = "# [CLI for Microsoft 365 using PowerShell](#tab/cli-m365-ps)" - IncludeBlock = "[!INCLUDE [More about CLI for Microsoft 365](../../docfx/includes/MORE-CLIM365.md)]" + IncludeBlock = "[!INCLUDE [More about CLI for Microsoft 365](../../docs/includes/MORE-CLIM365.md)]" ScriptBlock = $psScriptBlock Reference = [PSCustomObject]@{ "name" = "Want to learn more about CLI for Microsoft 365 and the commands" @@ -142,7 +146,7 @@ begin{ } "SPOManagementShell" = [PSCustomObject]@{ Tab = "# [SPO Management Shell](#tab/spoms-ps)" - IncludeBlock = "[!INCLUDE [More about SPO Management Shell](../../docfx/includes/MORE-SPOMS.md)]" + IncludeBlock = "[!INCLUDE [More about SPO Management Shell](../../docs/includes/MORE-SPOMS.md)]" ScriptBlock = $psScriptBlock Reference = [PSCustomObject]@{ "name" = "Introduction to the SharePoint Online Management Shell" @@ -155,7 +159,7 @@ begin{ "CliForMicrosoft365Bash" = [PSCustomObject]@{ Tab = "# [CLI for Microsoft 365 using Bash](#tab/cli-m365-bash)" - IncludeBlock = "[!INCLUDE [More about CLI for Microsoft 365](../../docfx/includes/MORE-CLIM365.md)]" + IncludeBlock = "[!INCLUDE [More about CLI for Microsoft 365](../../docs/includes/MORE-CLIM365.md)]" ScriptBlock = $psScriptBlock Reference = [PSCustomObject]@{ "name" = "Want to learn more about CLI for Microsoft 365 and the commands" @@ -168,7 +172,7 @@ begin{ "MicrosoftGraphPowerShell" = [PSCustomObject]@{ Tab = "# [Microsoft Graph PowerShell](#tab/graphps)" - IncludeBlock = "[!INCLUDE [More about Microsoft Graph PowerShell SDK](../../docfx/includes/MORE-GRAPHSDK.md)]" + IncludeBlock = "[!INCLUDE [More about Microsoft Graph PowerShell SDK](../../docs/includes/MORE-GRAPHSDK.md)]" ScriptBlock = $psScriptBlock Reference = [PSCustomObject]@{ "name" = "Want to learn more about Microsoft Graph PowerShell SDK and the cmdlets" @@ -181,7 +185,7 @@ begin{ "AzureCli" = [PSCustomObject]@{ Tab = "# [Azure CLI](#tab/azure-cli)" - IncludeBlock = "[!INCLUDE [More about Azure CLI](../../docfx/includes/MORE-AZURECLI.md)]" + IncludeBlock = "[!INCLUDE [More about Azure CLI](../../docs/includes/MORE-AZURECLI.md)]" ScriptBlock = $psScriptBlock Reference = [PSCustomObject]@{ "name" = "Want to learn more about Azure CLI and the commands" @@ -194,7 +198,7 @@ begin{ "PowerAppsPowerShell" = [PSCustomObject]@{ Tab = "# [Power Apps PowerShell](#tab/powerapps-ps)" - IncludeBlock = "[!INCLUDE [More about Power Apps PowerShell](../../docfx/includes/MORE-POWERAPPS.md)]" + IncludeBlock = "[!INCLUDE [More about Power Apps PowerShell](../../docs/includes/MORE-POWERAPPS.md)]" ScriptBlock = $psScriptBlock Reference = [PSCustomObject]@{ "name" = "Want to learn more about Power Apps PowerShell and the cmdlets" @@ -207,7 +211,7 @@ begin{ "MicrosoftTeamsPowerShell" = [PSCustomObject]@{ Tab = "# [MicrosoftTeams PowerShell](#tab/teamsps)" - IncludeBlock = "[!INCLUDE [More about Microsoft Teams PowerShell](../../docfx/includes/MORE-TEAMSPS.md)]" + IncludeBlock = "[!INCLUDE [More about Microsoft Teams PowerShell](../../docs/includes/MORE-TEAMSPS.md)]" ScriptBlock = $psScriptBlock Reference = [PSCustomObject]@{ "name" = "Want to learn more about Microsoft Teams PowerShell and the cmdlets" @@ -237,7 +241,13 @@ begin{ |_| |_| "@ - Write-Host " Welcome to PnP Script Samples, this script will generate a new script sample" -ForegroundColor Green + Write-Host " Welcome to Community Script Samples, this script will generate a new script sample" -ForegroundColor Green + + if ($ScriptTool -contains 'All') { + $ScriptTool = @('PnPPowerShell', 'CliForMicrosoft365', 'CliForMicrosoft365Bash', + 'SPOManagementShell', 'MicrosoftGraphPowerShell', 'AzureCli', + 'PowerAppsPowerShell', 'MicrosoftTeamsPowerShell') + } # ------------------------------------------------------------------------------ @@ -254,6 +264,9 @@ process { # Copy the template to the script folder under the new name $templateSrc = Join-Path $mainScriptFolder -ChildPath $sampleTemplateFolder $targetFolder = Join-Path $mainScriptFolder -ChildPath $ScriptFolderName + if (Test-Path -LiteralPath $targetFolder) { + throw "The sample folder already exists: $targetFolder. Edit the existing sample directly or choose a new folder name." + } # Nesting Problem, need to test and create teh directory first then copy the contents @@ -498,6 +511,8 @@ process { Default {} } + $json[0].Metadata = @($json[0].Metadata | Sort-Object -Property key -Unique) + # Thumbnails $json[0].Thumbnails[0].Url = $json.Thumbnails[0].Url.Replace('', $ScriptFolderName) $json[0].Thumbnails[0].Alt = $json.Thumbnails[0].Alt.Replace('', $ScriptTitle) @@ -544,7 +559,7 @@ process { Write-Host " - Populated the sample.json file in $targetFolder/assets" - $finalPath = Join-Path -Path "$(Get-Location)" -ChildPath $targetFolder + $finalPath = (Resolve-Path -LiteralPath $targetFolder).Path Write-Host " Sample setup complete, please go to $finalPath " -ForegroundColor Cyan } diff --git a/README.md b/README.md index f75add113..444e1f9b8 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,64 @@ -# Welcome to PnP Script Samples +# Community Script Samples -This repository contains scripts for PnP PowerShell, CLI for Microsoft365, Graph SDK PowerShell, SPO PowerShell, and Azure CLI, that are based on real world examples of the scripts that you run to perform tasks. +[![Community Script Samples gallery redesign preview with search, product filters, and script cards](docs/assets/gallery-preview.png)](https://pnp.github.io/script-samples/) -If you are looking for all the scenario and scripts, we have over 300+, rather than view the repository, please visit: [https://pnp.github.io/script-samples](https://pnp.github.io/script-samples) as this has a navigation and filtering experience to help you better find the content you are seek. +**[Browse the script gallery](https://pnp.github.io/script-samples/)** | [Get started](docs/getting-started.md) | [Share a sample](docs/contributing/preparing-a-submission.md) -What is PnP Script Samples? Check out our YouTube Video for an overview: -[![Introducing Script Samples](https://img.youtube.com/vi/cB2aideuHlk/maxresdefault.jpg)](https://www.youtube.com/embed/cB2aideuHlk) +*Gallery preview. The published site updates after this change is reviewed, merged, and deployed.* -## Authors +A little script. A lot less work. Explore 400+ real-world scripts for Copilot, Microsoft 365, Power Platform and more, shared by the community. Find a starting point, choose your tool, and make it your own. -This repository's contributors are all community members who volunteered their time to share code samples. Work is done as an open source community project, which each sample contained in their own solution. +Find scripts for SharePoint, Microsoft Graph, Teams, Microsoft Copilot, Power Platform, Azure, and more. Choose the tools you already use: PnP PowerShell, CLI for Microsoft 365, Microsoft Graph PowerShell, SharePoint Online Management Shell, Azure CLI, and others. -## Contributions +## Find your next starting point -These samples are direct from the feature teams, PnP team (https://aka.ms/m365pnp) or shared by the community. We welcome your input on issues and suggestions for new and existing samples. We welcome community contributions for sample scripts. If you have any questions, just let us know. +1. **Find a task:** search the [gallery](https://pnp.github.io/script-samples/) for a scenario or command, or browse by product or tool. +2. **Choose an implementation:** many samples offer more than one tool. Read the README and select the matching code tab. +3. **Review, adapt, and test:** check prerequisites and permissions, replace placeholders, and test safely before using production data. Samples can modify or remove tenant data. -We are looking for contributions in the following areas: +The scripts and their documentation live together under [scripts/](scripts/). No need to install or build the gallery to use or contribute a sample. -* Create a new scenario with a script -* Update a scenario with an alternative script using another tool e.g. Adding a PnP PowerShell script to a scenario that only has CLI for Microsoft 365 as an example. -* Feedback on the usability of the site, we are always looking to improve the experience. +## Your everyday script could make someone's day -In this repo, we are created a template submission folder and files, complete the readme, add any screenshots and submit your GitHub Pull Request, please contact us via issues list to communicate what your planning. +New contributors are welcome. Share a useful scenario, add another tool to an existing sample, fix a bug, or improve the guidance. A focused contribution does not have to be a large one. -Check out our [Contribution Guidance](https://pnp.github.io/script-samples/contributing/index.html) before submitting your pull requests, so that we can get your contribution processed as fast as possible. +The [New-Sample.ps1 generator](New-Sample.ps1) creates a sample folder, README, metadata, tool tabs, and placeholder images. Run it from the cloned repository root in PowerShell 7, using your own name and GitHub handle: -If you need any support or want to know how to use GitHub then we have a great programme to [support new contributors | sharing is caring](https://pnp.github.io/sharing-is-caring/). +```powershell +.\New-Sample.ps1 -ScriptFolderName "spo-get-site-report" ` + -ScriptTitle "Report SharePoint sites" ` + -ScriptShortDescription "Export a SharePoint site inventory." ` + -ScriptTool PnPPowerShell ` + -AuthorFullName "Your name" ` + -GitHubId "your-github-handle" +``` -## Join the community calls +Replace the generated script placeholder, finish the metadata, and add your preview. The [step-by-step contribution guide](docs/contributing/preparing-a-submission.md) explains what the generator does and what to finish before opening a pull request. -Stay up to date with the latest Copilot, Microsoft 365, and Power Platform topics by joining our weekly community calls. Everyone is welcome. Come to learn, ask questions, and connect with the community. +Not ready to write a sample? [Report an issue](https://github.com/pnp/script-samples/issues/new), suggest a scenario, or help test an existing script. New to GitHub? [Sharing is caring](https://pnp.github.io/sharing-is-caring/) offers friendly, hands-on sessions. -[View the call schedule and download the recurring invites](https://aka.ms/community/calls) so you don't miss an upcoming call. +## Earn your Script Samples contributor badge + +[<img src="docs/assets/credly-badge.png" alt="Microsoft 365 and Power Platform Community Script Samples contributor badge" width="200" />](https://pnp.github.io/recognitionprogram/) + +Every sample contributor is eligible, including first-time contributors. After your first accepted sample, [opt in to the community recognition program](https://pnp.github.io/recognitionprogram/) to receive your badge. Issuance is processed in batches, so it is not immediate. + +Your contribution is credited in the sample. Share its gallery link with your team or community, and [request a community demo slot](https://aka.ms/community/request/demo) to show what you learned. See [contributor recognition](docs/contributing/recognition.md) for details. + +## Learn and share with the community + +- [Join the Microsoft 365 & Power Platform community](https://aka.ms/community/home). +- [View community calls and download recurring invites](https://aka.ms/community/calls). Everyone is welcome to learn, ask questions, and share ideas. +- [Explore ways to contribute](docs/contributing/how-can-i-contribute.md) or [help maintain the gallery](docs/contributing/maintainers-guidance.md). +- When sharing a sample, link to its gallery page, credit its authors, and explain the scenario it helped you solve. Remove tenant or personal information from screenshots. + +This is an open-source community project maintained by volunteers. Thank you to everyone who shares code, reports issues, and helps others get started. + +## Work on the gallery + +The site uses Astro and TypeScript. With Node.js 22.19 or later, run `npm --prefix site ci`, then `npm --prefix site run dev` and open `http://localhost:4321/script-samples/`. + +[Local development, validation, and deployment](docs/contributing/maintainers-guidance.md) | [Migration and GitHub Pages cutover notes](site/MIGRATION.md) ## Code of Conduct diff --git a/docfx/.gitignore b/docfx/.gitignore deleted file mode 100644 index 50454dbf5..000000000 --- a/docfx/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -############### -# folder # -############### -/**/DROP/ -/**/TEMP/ -/**/packages/ -/**/bin/ -/**/obj/ -_site -help-repos/ diff --git a/docfx/404.html b/docfx/404.html deleted file mode 100644 index f1c0ffa84..000000000 --- a/docfx/404.html +++ /dev/null @@ -1,131 +0,0 @@ -<!DOCTYPE html> -<!--[if IE]><![endif]--> -<html lang="en"> - - <head> - <meta charset="utf-8"> - <title>Sorry, these are not the scripts you are looking for | PnP Samples - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- -
- - -
- - - - - - - - - - - - \ No newline at end of file diff --git a/docfx/by-product.md b/docfx/by-product.md deleted file mode 100644 index d9cc60a91..000000000 --- a/docfx/by-product.md +++ /dev/null @@ -1,51 +0,0 @@ -# Scripts By Microsoft Product - -Find scripts by entering a keyword. You can filter by product. - -
- -
-
- All -
-
-
-
-
-
-
-
-
- - - -
-
-
-
- -
- -
-
- -
- -
- No results found. -
- - - \ No newline at end of file diff --git a/docfx/by-tool.md b/docfx/by-tool.md deleted file mode 100644 index c15abfa84..000000000 --- a/docfx/by-tool.md +++ /dev/null @@ -1,61 +0,0 @@ -# Scripts By Tool - -Find scripts by entering a keyword. You can filter by Tool. - -
- -
-
- All -
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -
-
-
-
- -
- -
-
- -
- -
- No results found. -
- - - diff --git a/docfx/compact-view.md b/docfx/compact-view.md deleted file mode 100644 index eea1e1d78..000000000 --- a/docfx/compact-view.md +++ /dev/null @@ -1,43 +0,0 @@ -# Script Samples - -Find scenarios and scripts here using tools such as ***PnP PowerShell, CLI for Microsoft 365, Graph PowerShell SDK*** and more. Are you looking for authoring tool then check out extensions -[PnP PowerShell](https://marketplace.visualstudio.com/items?itemName=adamwojcikit.pnp-powershell-extension) and [CLI for Microsoft 365](https://marketplace.visualstudio.com/items?itemName=adamwojcikit.cli-for-microsoft-365-extension) for Visual Studio Code - -
- -
-
All
-
Modernize
-
Data
-
Deploy
-
Provision
-
Configure
-
Report
-
Security
-
AI
-
Copilot
-
- - - -
-
-
- -
- -
-
-
- -
- No results found. -
- - - diff --git a/docfx/contributing/how-can-i-contribute.md b/docfx/contributing/how-can-i-contribute.md deleted file mode 100644 index 7e9e72346..000000000 --- a/docfx/contributing/how-can-i-contribute.md +++ /dev/null @@ -1,39 +0,0 @@ -# How Can I Contribute - -If you'd like to contribute to this repository, please read the following guidelines. Contributors are **more than welcome** to share their scripts with others in this centralized location. - -## How can I contribute - -There are ways to contribute: - -* Create a scenario e.g. Upload a document to SharePoint, then add your script to the scenario -* Extend an existing scenario that does NOT have an example for the tool e.g. a scenario containing only CLI for Microsoft 365 sample, you can submit an updated scenario with a PnP PowerShell equivalent -* Logging an [issue in GitHub](https://github.com/pnp/script-samples/issues) if you have feedback about the site or samples - -> [!div class="full-image-size"] -> ![Ways to contribute](../assets/contributing/ways-to-contribute.png) - -To get started quickly, check out the [Preparing a submission guide](preparing-a-submission.md) - -> *Please register your idea in the issue list and assign to yourself, there maybe others considering similar scripts.* - -### Script Quality - -In the PnP Script Samples, we do not place any specific quality requirements on the scripts themselves. To help guide you for suggested ways to present your scripts: - -- Indent the scripts when encapsulating blocks in curly braces - this make it easier to read the blocks and understand the script -- Use comments, if you feel the script isn't clear by itself what it is doing. However, do not overload the script with comments either. -- Use good naming for variables to understand what is being stored -- Check the script works as you would expect it to, preferably include a screenshot of the end result, to help guide the reader. -- Remove any lines that show details of **your** tenant, e.g. usernames, passwords, URLs (replace with Contoso). - -## Typos, Issues, Bugs and contributions - -Whenever you are submitting any changes to the SharePoint repositories, please follow these recommendations. - -* Always [fork the repository](https://docs.github.com/en/get-started/quickstart/fork-a-repo) to your own account before making your modifications -* Do not combine multiple changes to one [pull request](https://docs.github.com/en/pull-requests). For example, submit any samples and documentation updates using separate PRs. If you do no worries, this is a preference to help us organize the PRs. -* If your pull request shows merge conflicts, update your local `main` branch to match the upstream repository before making your modifications. In your fork, GitHub provides a sync option to update the branch. - - - \ No newline at end of file diff --git a/docfx/contributing/index.md b/docfx/contributing/index.md deleted file mode 100644 index b0e0b2b79..000000000 --- a/docfx/contributing/index.md +++ /dev/null @@ -1,37 +0,0 @@ -# Contributing - Getting Started - -PnP Script Samples is part of the wider [PnP](https://pnp.github.io/) community and is a place where you can find and share scripts that help you to automate your work with Microsoft 365. The repository is maintained by the community and we welcome contributions from everyone. - -Typically, we have support for the following types of scripts: - -* PnP PowerShell -* CLI for Microsoft 365 -* Microsoft Graph PowerShell SDK -* SPO Management Shell -* Azure CLI -* Power Apps PowerShell SDK -* Teams PowerShell SDK -* Microsoft Whiteboard PowerShell SDK - -We can add more, if there is script that is not in the above list. Please reach out and raise an [issue](https://github.com/pnp/script-samples/issues) with the details of the type of script sample you wish to submit. - -> [!NOTE] -> The repository can be found at [https://github.com/pnp/script-samples](https://github.com/pnp/script-samples) - -## Introductory video - -> [!Video https://www.youtube.com/embed/cB2aideuHlk] - -## Code of Conduct - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - -**Remember that this repository is maintained by community members who volunteer their time to help. Be courteous and patient.** - -## Repository Maintainers - -If you are interested in helping to maintain the repository please check out the [maintainers guidance](maintainers-guidance.md). - - - \ No newline at end of file diff --git a/docfx/contributing/maintainers-guidance.md b/docfx/contributing/maintainers-guidance.md deleted file mode 100644 index 507eca139..000000000 --- a/docfx/contributing/maintainers-guidance.md +++ /dev/null @@ -1,68 +0,0 @@ -# Maintainers Guidance - -This is the maintainers guide to provide a location to share knowledge about how the site works and some of the behaviors of the setup and underlying configuration. - -## Docfx - -The site uses the DocFx engine, this is the same tool that [learn.microsoft.com](https://learn.microsoft.com) uses (albeit a special version) in combination with the Material UI + UI tweaks we have made with the help and thanks for Hugo Bernier. - -- Install DocFx from GitHub [DocFx Releases](https://github.com/dotnet/docfx/releases). -- Ensure that ```docfx``` command can run from anywhere, add the installation location to my environment variables if it does not run. -- Clone the site with ```git clone https://github.com/pnp/script-samples.git``` -- Find a script called ```docfx-build-local.ps1``` running under the docfx folder will build the site. -- View the site locally, ```docfx docfx.json --serve```, alternatively, I use an npm module called ```http-server``` run that on the generated _site location to see it render. - -The main goal with DocFx builds must complete with **0 warnings and errors**. The site will not publish/update if there are warnings. - - -## Galleries - -Currently, there are 3 pages that galleries are used: - -* Index.md - default gallery page -* by-tool.md - By Library gallery page e.g. M365 CLI, PnP PS, Graph PS SDK etc. -* by-product.md - By Product e.g. Microsoft Product the script performs an action against - -The card style uses Isotope.js with CSS/HTML to show the card format, but it can adapt to screen resolution and adjust the number of cards accordingly. - -## Folder Structure for scripts - -We have worked to keep the folder structure lean and as simple as possible when submitting scripts: - -![Folder Structure](../assets/contributing/folder-structure.png) - -## Naming and casing - -DocFx is case sensitive with the markdown files and in compilation of the site, to make this easier, all sample file paths etc. should be in lowercase to avoid any issues with linking to files. - -Spaces should be replaced with hyphens as well. - -## Images and previews - -When creating images and previews, please follow this guidance: - -* Favor the product UI change, close up of the affect element if preferred, to reduce the updates -* If delete, show a before image and indicate what is being removed. -* Terminal is less favorable because it would only show output of 1 of the three types of script that could run. -* PNG format preferred, JPG can be submitted, though these will be converted to PNG. - -If only example images are shown, Paul Bullock has a tool to convert in bulk. - -## Recognizing contributors - -When samples are submitted it is important that contributors are recognized for their contributions as without them the library would not grow, this is done in the following ways: - -* Their name on the sample. If we as a maintainer also contributes to the article, they must be the primary or first name. -* The article must list their name, company and GitHub/LinkedIn/Twitter handle - we will encourage their complete this. -* Promotion to X, BlueSky, LinkedIn & Discord - their sample will get promoted in these locations for greater exposure. - -## Reports - -There are a series of reports that are generated to help with the maintenance of the site, these are: - -* [Matrix of Sample Distribution by Tool](https://pnp.github.io/script-samples/matrix.html) -* [Report of Samples Command Usage](https://pnp.github.io/script-samples/cmdusage.html) -* [Metadata Report of Samples](https://pnp.github.io/script-samples/metadata.html) -* [Age Report of Samples](https://pnp.github.io/script-samples/age.html) - - diff --git a/docfx/contributing/merging-existing-project.md b/docfx/contributing/merging-existing-project.md deleted file mode 100644 index 3850d01fd..000000000 --- a/docfx/contributing/merging-existing-project.md +++ /dev/null @@ -1,33 +0,0 @@ -# Merging your Existing GitHub Projects with this Repository - -If the sample you wish to contribute is stored in your own GitHub repository, you can use the following steps to merge it with this repository: - -* Fork the `script-samples` repository from GitHub -* Create a local git repository - - ```shell - md script-samples - cd script-samples - git init - ``` - -* Pull your forked copy of `script-samples` into your local repository - - ```shell - git remote add origin https://github.com/yourgitaccount/script-samples.git - git pull origin main - ``` - -* Pull your other project from GitHub into the `samples` folder of your local copy of `script-samples` - - ```shell - git subtree add --prefix=samples/projectname https://github.com/yourgitaccount/projectname.git main - ``` - -* Push the changes up to your forked repository - - ```shell - git push origin main - ``` - - \ No newline at end of file diff --git a/docfx/contributing/preparing-a-submission.md b/docfx/contributing/preparing-a-submission.md deleted file mode 100644 index 4c464b4d2..000000000 --- a/docfx/contributing/preparing-a-submission.md +++ /dev/null @@ -1,223 +0,0 @@ -# Preparing a submission - -Thank you for considering contributing to this repository. In order to help you get started, we have prepared this guide to provide you with the information you need to prepare your submission. - ->[!Note] -> If you miss anything on your submission, please don't worry, we will check and make the tweaks to the submission for you, we may reach out within the Pull Request to check some details with you. We do not want to put you off contributing, we want to make it as easy as possible for you to contribute. - -## Where Do I Start? - -First, you need to ensure you have a GitHub account. If you don't have one, you can create one for free. -Then find the repository at [https://github.com/pnp/script-samples](https://github.com/pnp/script-samples) and click the ["Fork"](https://docs.github.com/en/get-started/quickstart/fork-a-repo) button in the top right corner. - -Before you can submit, you need to make sure you are setup with a "fork" of the repository in your own account, please navigate to [Submitting Pull Requests](submitting-pull-requests.md) for setup information. - - -## Use a code tour - -We have added a code tour to help you create a sample from the template. In order to use, this, you will need to install the extension into Visual Studio Code called "CodeTour", details of how this works, see [CodeTour | Visual Studio Code Marketplace](https://marketplace.visualstudio.com/items?itemName=vsls-contrib.codetour) - - -### Submission Template Files - -There is a template submission folder called **"_template-script-submission"** in [_template-script-submission | GitHub - PnP Script Samples](https://github.com/pnp/script-samples/tree/main/scripts/_template-script-submission). - -The template submission folder contains: - -- **README.md** - Sample README with the required structure; remove the dummy text and update every section for your submission -- **assets/template.sample.json** - Gallery metadata template; rename it to `sample.json` and replace the placeholder values -- **assets/example.png** - Screenshot used in the README; replace it with an image of your sample -- **assets/preview.png** - Gallery preview image; replace the placeholder with an image that represents your sample - -> [!note] -> If you would like an example, please refer to the following script: [Generate Demo Events for SharePoint Events List | PnP Script Samples](https://pnp.github.io/script-samples/spo-generate-demo-events/README.html)
-> Please note: this isn't an expected sample style, quality or format, or a gold standard just an idea if you feel you need some ideas on how to present your script.

-> We fully understand that there any multiple styles and approaches, and __we are happy to accept the submission in your style__ 😊 - - -**Alternatively, you can use PowerShell...** - -We have added a PowerShell script to help you generate the scaffolding for a NEW sample, making it faster for you to submit. It does not add to an existing sample a new variation. - -In the root of the repo, you will find ```New-Sample.ps1``` this PowerShell script accepts the following parameters: - -| Property | Example | Description | -|----------|---------|-------------| -| -ScriptFolderName | "spo-dev-tenant-report-export" | Folder format for the sample itself. Lowercase, workload prefix | -| -ScriptTitle | "Report and Export Solutions from M365 Developer Tenant" | Title of your sample script | -| -ScriptShortDescription | "Expiring tenant or need..." | Short Description of what the sample does | -| -ScriptTool | PnPPowerShell | Multiple options supported here e.g. 'PnPPowerShell','CliForMicrosoft365', 'SPOManagementShell', 'CliForMicrosoft365Bash', 'MicrosoftGraphPowerShell', 'AzureCli', 'PowerAppsPowerShell', 'MicrosoftTeamsPowerShell', 'All' | -| -AuthorFullName | "Paul Bullock" | Your name, so we can credit you | -| -GitHubId | "pkbullock" | Your GitHub handle | - -Example: - -```powershell - .\New-Sample.ps1 -ScriptFolderName "spo-dev-tenant-report-export" ` - -ScriptTitle "Report and Export Solutions from M365 Developer Tenant" ` - -ScriptShortDescription "Expiring tenant or need to understand what you have created in the past, report and optionally export your projects and solutions" - -ScriptTool PnPPowerShell ` - -AuthorFullName "Paul Bullock" ` - -GitHubId "pkbullock" -``` - -![Example of output from parameters](../assets/contributing/new-sample-output.png) - -## Page Structure - -The page follows a standard format, we have created a graphic to explain the layout and the markdown for each section: - -> [!div class="full-image-size"] -> ![Page Layouts and Markdown](../assets/contributing/page-layouts.png) - -The minimum we need for the submission is: - -- **Article Title** - the title for your script -- **Summary** - for briefly describing what the script does -- **Image**, ideally named "example.png" in an assets folder, presenting the end result of the operation. The more visual the better. -- **Script** - minimum of at least one type. We support a wide range of script types, if this is not listed in the template file, we can add support for that type when you submit your PR. -- **Contributors** - your name, or if a joint submission those you have worked with - so that we can attribute credit for the submission. -- **Gallery metadata** - an `assets/sample.json` file with the sample name, description, products, categories, tools, author, and preview image details. -- **Gallery preview** - an `assets/preview.png` image referenced by `assets/sample.json`. - -Keep the disclaimer near the bottom and the required tracking image as the final line of the script-root `README.md`. - -### What is Markdown? - -This repository uses a text based markup called "Markdown" which allows you to write articles/pages quickly without having to worry about the presentation of the page. Even this page is written using this - we use a site generator to turn this into a page automatically. - -If you want to learn more about Markdown checkout this guide by Bob German on Tech Community - [What's up with Markdown?](https://techcommunity.microsoft.com/t5/microsoft-365-pnp-blog/what-s-up-with-markdown/ba-p/2323834) - -### Key elements of Markdown we use - -```markdown - -# Heading 1 -## Heading 2 -### Heading 3 - - -| Table Header | -|--------------| -| Table Data | - - -[Hyperlink](https://bing.co.uk) - -![Example Screenshot](assets/example.png) - -``` - -### Tabs containing scripts - -Each tab contains the sample for the scripts named under a specific tool. Use the following markdown to contain the script in the tab: - -```markdown - -# [PnP PowerShell](#tab/pnpps) -``powershell - Your-PowerShellScript -`` - -# [CLI for Microsoft 365 using PowerShell](#tab/cli-m365-ps) -`` powershell - Your-PowerShellScript -`` - -# [CLI for Microsoft 365 using Bash](#tab/cli-m365-bash) -``bash - echo "your bash script" -`` - -# [Microsoft Graph PowerShell](#tab/graphps) -``powershell - Your-PowerShellScript -`` - -``` - -> [!note] -> * Use three backticks around the script, not the two shown above -> * Delete the tabs you do not need - - -We add an additional block to provide guidance back to the tool guiding site: - -```markdown -[!INCLUDE [More about CLI for Microsoft 365](../../docfx/includes/MORE-CLIM365.md)] -``` - -## Gallery metadata and preview - -- **assets/sample.json** - Required metadata used to publish the sample in gallery views. `New-Sample.ps1` creates this file. If you copy the template manually, rename `assets/template.sample.json` to `assets/sample.json` and replace its placeholder values. -- **assets/preview.png** - Required preview image referenced by `assets/sample.json`. Replace the template image with a representative preview of your sample. - -## Folder Structure - -We have worked to keep the folder structure lean and as simple as possible when submitting scripts: - -```markdown - -+--- script-folder-title - *folder for the script based on the title of your sample, please all lowercase and spaces as hyphens* - |___ assets - *sub folder for any images or assets you need to support your sample* -``` -![Folder structure](../assets/contributing/folder-structure.png) - -## Sample Naming and Structure Guidelines - -When you are submitting a new sample, it has to follow up below guidelines - -### ReadMe File - -You will need to have a `README.md` file for your contribution, which is based on [the provided template](../../scripts/_template-script-submission/README.md) under the `scripts` folder. Please copy this template to your project and update it accordingly. Your `README.md` must be named exactly `README.md` -- with capital letters -- as this is the information we use to make your sample public. - -The final line of every script-root `README.md` must be the tracking image: - -```html - -``` - -Replace `{script-path}` with the sample folder's repository-relative path, using `/` separators and excluding the `README.md` filename. For example, `scripts/spo-get-list-items/README.md` must end with: - -```html - -``` - -We use this image for tracking your sample's usage and popularity. - -### Screenshot (optional) - -You will need to have a screenshot picture of your sample in action in the `README.md` file ("pics or it didn't happen"). The preview image must be located in the `/assets/` folder in the root your you solution. - -### Sample Updates - -You are free to submit updates to existing samples, if you find an issue or could benefit from improvements. - -When you update existing samples, please update also `README.md` file accordingly with information on provided changes and with your author details - -### Sample Folder Naming - -When submitting a new sample solution, please name the sample solution folder accordingly - -Do not use words such as `sample`, `script` or `ps` in the folder or sample name - -Do not use period/dot in the folder name of the provided sample - -### Remove environment or sensitive details - -Please be sure to remove all of your password, usernames and tenant addresses from the sample scripts - this is to maintain the security of your tenant. Examples include replacing the organisation name with Contoso e.g. https://contoso.sharepoint.com giving the details of the type of address but hiding the key information. - -### Destructive scripts - -We are happy to accept scripts that bulk delete or remove, delete an artefact but we will add a warning message to ensure that the reader is aware to ensure they understanding the implications of running the script. - -e.g. - -> [!Warning] -> Please be aware this script contains a command that will remove or delete an artefact, ensure you test and understanding the implications of running the script. - -### We Track the Samples Usage - -The `README` template ends with a transparent tracking image used to track viewership of individual samples in GitHub. Keep the tracking image as the final line and replace `{script-path}` with the repository-relative sample directory, for example `scripts/spo-get-list-items`. - - \ No newline at end of file diff --git a/docfx/contributing/recognition.md b/docfx/contributing/recognition.md deleted file mode 100644 index 82ea79010..000000000 --- a/docfx/contributing/recognition.md +++ /dev/null @@ -1,20 +0,0 @@ -# How you are recognized for your submissions - -In PnP, we are all about community and we want to recognize your contributions. We have a few ways to do this - - -## Community calls and demos - -Weekly Copilot, Microsoft 365, and Power Platform community calls are open to everyone. See the schedule and join at [https://aka.ms/community/calls](https://aka.ms/community/calls). - -You can also [request a community demo slot](https://aka.ms/community/request/demo) to share what you learned, show your solution, and provide input to the community. - -## Social Media - -We will share your submission on our social media channels, promotion to X, BlueSky, LinkedIn & Discord, when the samples have been processed by the team and is live. Typically, you will see a notification if there is a merge from Github. - -## Badges! - -Finally, as a Thank you for your contributions, we invite you to opt-in into the PnP Recognition Program. This will give you access to a badge that you can use on your social media profiles, blog posts, and other places to show that you are a PnP contributor. You can opt-in here: [https://pnp.github.io/recognitionprogram/](https://pnp.github.io/recognitionprogram/) - -You will receive a badge in a batch run (might be a few weeks) when you have submitted your first sample - that's it. \ No newline at end of file diff --git a/docfx/contributing/submitting-pull-requests.md b/docfx/contributing/submitting-pull-requests.md deleted file mode 100644 index cf03ecf58..000000000 --- a/docfx/contributing/submitting-pull-requests.md +++ /dev/null @@ -1,76 +0,0 @@ -# Submitting Pull Requests - -Welcome contributors, here is a guide to help you create a new sample or update an existing sample within PnP Script Samples site. - -## The process - -This is the process for submitting new samples or updates to existing samples to the repository. - - - Step 1 - Signing the CLA (One-time activity) - - Step 2 - Fork the repository (One-time activity) - - Step 3 - Preparing a submission - - Step 4 - Create a pull request - - Step 5 - What happens next, when the sample is submitted - - - -## Step 1 - Signing the CLA (One-time activity) - -Before we can accept your pull requests you will be asked to sign electronically Contributor License Agreement (CLA), which is a pre-requisite for any contributions all PnP repositories. This will be one-time process, so for any future contributions you will not be asked to re-sign anything. After the CLA has been signed, our PnP core team members will have a look at your submission for a final verification of the submission. **Please do not delete your development branch until the submission has been closed.** - -You can find Microsoft CLA from the following address - https://cla.microsoft.com. - -## Step 2 - Fork the repository (One-time activity) - -In GitHub here: https://github.com/pnp/script-samples - -Find the Fork button: - -![Fork the sample](../assets/contributing/fork-sample.png) - -This will make a copy of the site code within your account, this is where you will create the submission. - -We recommend you use [Visual Studio Code](https://code.visualstudio.com/), as your editor. - -### Want to practice the setup? - -If you feel insecure or would struggle to do this and are new to GitHub, please consider to attend the [Sharing Is Caring sessions from the PnP team](https://pnp.github.io/sharing-is-caring/#pnp-sic-events) in which the Microsoft 365 PnP team provides hands-on guidance for first time contributors -these are NOT recorded and completely safe space to ask questions. - -## Step 3 - Preparing a submission - -Please visit this page - [Preparing a submission](preparing-a-submission.md), to see the details of the submission, then return here to continue. - -## Step 4 - Create a pull request - -Commit your changes and push or sync the branch to your fork. - -![Commit Changes](../assets/contributing/commit-changes.png) - -When you are ready to submit your sample, open the branch on GitHub and select **Compare & pull request** or **Open a pull request**. - -![Open a Pull Request](../assets/contributing/open-pull-request.png) - -You will then be taken to a form, where you can complete: - -- Title of the Pull Request e.g. ```New Sample - Saving File to SharePoint``` -- Description - include some detail about the sample - -When you are happy with the pull request, select **Create pull request**. - -![Complete Pull Request](../assets/contributing/complete-pull-request-form.png) - -> Note: if you want to make additions or changes at this point, you can just edit and commit new changes, it will be included in the Pull Request up to the point we merge (Save into the Script Samples repository) the request. - -## Step 5 - What happens next, when the sample is submitted - -We will review the submission, make small tweaks if needed and provide feedback. The submission will get approved, we will merge it into the `main` branch and it will be published to the [PnP Script Samples](https://pnp.github.io/script-samples/) site within a few minutes via an automated process. - -Once published, we will begin to promote the sample on social media, see our details on [Recognizing Contributors](recognition.md). - -**THANK YOU! For reading this guide and taking the time to submit samples.** - -If you have any issues, please create an issue here in GitHub: [Issues in PnP Script Samples](https://github.com/pnp/script-samples/issues) we would be happy to help. - -Please be aware contributors and maintainers run this repository in their spare time and response may not be immediate, although we endevour to process your submission within a few days. - - diff --git a/docfx/contributing/toc.yml b/docfx/contributing/toc.yml deleted file mode 100644 index a760b36b1..000000000 --- a/docfx/contributing/toc.yml +++ /dev/null @@ -1,12 +0,0 @@ -- name: Getting Started - href: index.md -- name: How can I contribute - href: how-can-i-contribute.md -- name: Preparing a submission - href: preparing-a-submission.md -- name: Submitting pull requests - href: submitting-pull-requests.md -- name: How you are recognised - href: recognition.md -- name: First time contributor (navigates to PnP Site) - href: https://pnp.github.io/sharing-is-caring/#pnpsicsessions diff --git a/docfx/docfx-build-local.ps1 b/docfx/docfx-build-local.ps1 deleted file mode 100644 index 04afe797e..000000000 --- a/docfx/docfx-build-local.ps1 +++ /dev/null @@ -1,32 +0,0 @@ -$ErrorActionPreference = "Stop" -Set-StrictMode -Version 2.0 - -# Data Generated Content -$runLocation = Get-Location -#.\report-matrix.ps1 -BaseDir "$($runLocation)\..\" -ReportFile "matrix.md" -#.\report-metadata.ps1 -BaseDir "$($runLocation)\..\" -ReportFile "metadata.md" -#.\report-cmdusage.ps1 -BaseDir "$($runLocation)\..\" -ReportFile "usage.md" -#.\report-age.ps1 -BaseDir "$($runLocation)\..\" -ReportFile "age.md" - -Write-Host "Generating samples.json..." -ForegroundColor Cyan -$baseDir = (Resolve-Path (Join-Path $runLocation "..")).Path -./generate-samplesJson.ps1 -BaseDir $baseDir -ReportFile "samples.json" - -# Main DocFX build -Write-Host "Building docfx..." -ForegroundColor Cyan - -<# - DocFx is now installed as a .NET tool. To use it: - - 1. Ensure .NET SDK is installed (version 6.0 or higher) - - Download from: https://dotnet.microsoft.com/download - - 2. Restore the docfx tool (if not already done): - - Run: dotnet tool restore - - 3. Run docfx using: - - dotnet docfx build docfx.json -#> - -Write-Host "Running docfx using .NET tool..." -ForegroundColor Cyan -dotnet docfx build docfx.json --warningsAsErrors $args diff --git a/docfx/docfx.json b/docfx/docfx.json deleted file mode 100644 index a2e2a5dd7..000000000 --- a/docfx/docfx.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "build": { - "content": [ - { - "files": [ - "toc.yml", - "*.md", - "contributing/*.md", - "contributing/toc.yml" - ] - }, - { - "files":[ - "toc.yml", - "**.md", - "**/**.md" - ], - "src": "../scripts", - "dest": "" - } - ], - "resource": [ - { - "files": [ - "assets/**", - "404.html", - "samples.json", - "1b648b4546244e86bfb986feb97aa7ea.txt" - ] - }, - { - "files":[ - "**/assets/*.png", - "**/assets/*.jpg", - "**/assets/*.gif", - "**/assets/sample.json", - "**/assets/*.csv", - "**/assets/*.json", - "**/assets/*.html" - ], - "src": "../scripts", - "dest": "" - } - ], - "dest": "_site", - "globalMetadataFiles": [], - "fileMetadataFiles": [], - "template": [ - "default", - "templates/material" - ], - "sitemap": { - "baseUrl": "https://pnp.github.io/script-samples/", - "priority": 1.0, - "changefreq": "daily", - "fileOptions":{ - "../scripts/_template-script-submission/**.md": { - "baseUrl": "https://pnp.github.io/script-samples/", - "changefreq": "never", - "priority": 0.1 - } - } - }, - "postProcessors": [], - "markdownEngineName": "markdig", - "noLangKeyword": false, - "keepFileLink": false, - "cleanupCacheHistory": true, - "disableGitFeatures": false, - "globalMetadata": { - "_appTitle": "PnP Samples", - "_appFooter": "Script Samples
Generated by DocFX with Material UI
", - "_appFaviconPath": "https://c.s-microsoft.com/favicon.ico?v2", - "_appLogoPath": "assets/logo.svg", - "_description":"A sample gallery of scripts to manage all things Microsoft 365.", - "_enableSearch": false, - "_enableNewTab": true, - "_disableAffix": true, - "_disableBreadcrumb": true, - "_disableNavbar": false, - "_gitContribute": { - - } - } - } -} \ No newline at end of file diff --git a/docfx/generate-samplesJson.ps1 b/docfx/generate-samplesJson.ps1 deleted file mode 100644 index 3694cbfa6..000000000 --- a/docfx/generate-samplesJson.ps1 +++ /dev/null @@ -1,68 +0,0 @@ -# Script for reporting the information from the samples - -## Variables -param( - [string]$BaseDir = "D:\contrib\pkb-script-samples\", - [string]$ScriptFolder = "scripts", - [string]$OutputFile = "samples.json", - [string]$AssetsFolder = "assets" -) - -function GetJsonFromSampleJson{ - param( - [string]$SamplePath, - [string]$DefaultReturn - ) - - try{ - $assetsFolder = Join-Path -Path $SamplePath -ChildPath $AssetsFolder - $sampleFilePath = Join-Path -Path $assetsFolder -ChildPath "sample.json" - - $json = Get-Content $sampleFilePath | ConvertFrom-Json - - return $json - - }catch{ - # Swallow - this shouldnt happen - Write-Host "Warning cannot resolve json: $PSItem.Message" - } - - return $DefaultReturn -} - -$dir = Join-Path -Path $BaseDir -ChildPath $ScriptFolder -$files = Get-ChildItem -Path $dir -Recurse -Include README.md - -Write-Host "$($files.Length) found" - -$consolidatedSamplesFile = @() - -$files | Foreach-Object { - - # Skip these - if($_.Directory.Name -eq "scripts" -or - $_.Directory.Name -eq "_template-script-submission"){ - return - } - - $sampleJsonObj = GetJsonFromSampleJson -SamplePath $_.Directory -DefaultReturn $_.Directory.Name - - # Remove LongDescription and Description from the sampleJsonObj - $sampleJsonObj.PSObject.Properties.Remove("LongDescription") - $sampleJsonObj.PSObject.Properties.Remove("References") - $sampleJsonObj.PSObject.Properties.Remove("Source") - - # Update Sample Url - $sampleJsonObj.Url = $sampleJsonObj.Url.Replace("https://pnp.github.io/script-samples/", "") - - if($sampleJsonObj.thumbnails.length -gt 0){ - $sampleJsonObj.thumbnails | ForEach-Object { - $_.Url = $_.Url.Replace("https://raw.githubusercontent.com/pnp/script-samples/main/scripts/", "") - } - } - - $consolidatedSamplesFile += $sampleJsonObj -} - -# Output Report -$consolidatedSamplesFile | ConvertTo-Json -Depth 10 | Out-File $OutputFile -Force \ No newline at end of file diff --git a/docfx/get-scriptsfordownload.ps1 b/docfx/get-scriptsfordownload.ps1 deleted file mode 100644 index ecf460e2e..000000000 --- a/docfx/get-scriptsfordownload.ps1 +++ /dev/null @@ -1,19 +0,0 @@ -# Loop through all the samples -# Ensure the Downloads directory is in the GitIgnore file, we dont want to keep the files there - -# in each sample file create a download directory -# find the #tab/*** in the markdown files README.md -# then find the next row containing ```powershell/bash -# capture all lines until the next ``` -# save as file type .ps1 or .sh files -# naming convention is sample_name_tool_script.ps1 or sample_name_tool_script.sh like the sample directory - -# add info header for the files e.g. script title, description, credit, created and modified dates, -# using the sample.json metadata - -# move the file to the download directory - -# save all the individual files as a zip file -# naming convention is sample_name_all_scripts.zip like the sample directory - -# Update the sample.json file with the URL for the sample scripts \ No newline at end of file diff --git a/docfx/getting-started.md b/docfx/getting-started.md deleted file mode 100644 index c724ae324..000000000 --- a/docfx/getting-started.md +++ /dev/null @@ -1,3 +0,0 @@ -# Getting Started - -Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.Aenean nec lorem. In porttitor. Donec laoreet nonummy augue. \ No newline at end of file diff --git a/docfx/help-repos/OfficeDocs-SharePoint-PowerShell b/docfx/help-repos/OfficeDocs-SharePoint-PowerShell deleted file mode 160000 index fdc434ffe..000000000 --- a/docfx/help-repos/OfficeDocs-SharePoint-PowerShell +++ /dev/null @@ -1 +0,0 @@ -Subproject commit fdc434ffe4c32afe77ba78474d590966a9112e30 diff --git a/docfx/help-repos/README.md b/docfx/help-repos/README.md deleted file mode 100644 index f2e43b348..000000000 --- a/docfx/help-repos/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# Cmdlet Help Automation - -This directory contains automation for updating cmdlet help documentation from external repositories. - -## Overview - -The cmdlet help documentation is automatically synchronized from three upstream repositories using `git clone`: - -- **PnP PowerShell**: [pnp/powershell](https://github.com/pnp/powershell) -- **CLI for Microsoft 365**: [pnp/cli-microsoft365](https://github.com/pnp/cli-microsoft365) -- **SharePoint Online Management Shell**: [MicrosoftDocs/OfficeDocs-SharePoint-PowerShell](https://github.com/MicrosoftDocs/OfficeDocs-SharePoint-PowerShell) - -## Directory Structure - -The repositories are cloned into `docfx/help-repos/` directory during the GitHub Action workflow: - -``` -docfx/help-repos/ -├── pnp-powershell/ -├── cli-microsoft365/ -└── OfficeDocs-SharePoint-PowerShell/ -``` - -**Note:** The `help-repos/` directory is ignored by Git (via `.gitignore`) and is only created during the automated workflow or manual updates. - -## Automation - -### Monthly Updates - -A GitHub Action workflow (`.github/workflows/update-cmdlet-help.yml`) runs monthly on the 1st day of each month to: - -1. Clone the latest versions of all three documentation repositories -2. Run `Get-HelpJson.ps1` to regenerate help JSON files -3. Create a pull request if changes are detected - -### Manual Updates - -You can manually run the update process locally: - -```bash -# Create the help-repos directory -mkdir -p docfx/help-repos -cd docfx/help-repos - -# Clone the repositories -git clone --depth 1 https://github.com/pnp/powershell.git pnp-powershell -git clone --depth 1 https://github.com/pnp/cli-microsoft365.git cli-microsoft365 -git clone --depth 1 https://github.com/MicrosoftDocs/OfficeDocs-SharePoint-PowerShell.git OfficeDocs-SharePoint-PowerShell - -# Go back to docfx directory and run the script -cd .. -pwsh ./Get-HelpJson.ps1 -``` - -## Get-HelpJson.ps1 - -This PowerShell script processes the documentation from the cloned repositories and generates JSON files containing cmdlet names and their documentation URLs. - -### Generated Files - -The script generates the following files in `docfx/assets/help/`: - -- `powershell.help.json` - PnP PowerShell cmdlets -- `cli.help.json` - CLI for Microsoft 365 commands -- `spoms.help.json` - SharePoint Online Management Shell cmdlets - -These JSON files are used by the documentation website to provide quick links to cmdlet documentation. - -## Benefits - -- **Always up-to-date**: Monthly automatic updates ensure documentation links stay current -- **Human review**: All updates go through a PR review process -- **No local clutter**: Cloned repositories are not committed to the main repository -- **Simple approach**: Uses standard `git clone` instead of submodules -- **No manual maintenance**: Eliminates the need to manually sync documentation diff --git a/docfx/help-repos/cli-microsoft365 b/docfx/help-repos/cli-microsoft365 deleted file mode 160000 index 93e11fba9..000000000 --- a/docfx/help-repos/cli-microsoft365 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 93e11fba9ec37c772878ee0061a8cb94c3497224 diff --git a/docfx/help-repos/pnp-powershell b/docfx/help-repos/pnp-powershell deleted file mode 160000 index f5bbdff04..000000000 --- a/docfx/help-repos/pnp-powershell +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f5bbdff04da415650a479266cdc4082f0d4053fe diff --git a/docfx/index.md b/docfx/index.md deleted file mode 100644 index 7cb53ecc1..000000000 --- a/docfx/index.md +++ /dev/null @@ -1,42 +0,0 @@ -# Script Samples - -Find scenarios and scripts here using tools such as ***PnP PowerShell, CLI for Microsoft 365, Graph PowerShell SDK*** and more. Are you looking for authoring tool then check out extensions -[PnP PowerShell](https://marketplace.visualstudio.com/items?itemName=adamwojcikit.pnp-powershell-extension) and [CLI for Microsoft 365](https://marketplace.visualstudio.com/items?itemName=adamwojcikit.cli-for-microsoft-365-extension) for Visual Studio Code - -
- -
-
All
-
Modernize
-
Data
-
Deploy
-
Provision
-
Configure
-
Report
-
Security
-
AI
-
Copilot
-
- - - -
-
-
- -
- -
-
-
- -
- No results found. -
- - diff --git a/docfx/plugins/DocFx.Plugin.ExtractFrontMatter.dll b/docfx/plugins/DocFx.Plugin.ExtractFrontMatter.dll deleted file mode 100644 index 084fd778d..000000000 Binary files a/docfx/plugins/DocFx.Plugin.ExtractFrontMatter.dll and /dev/null differ diff --git a/docfx/plugins/DocFx.Plugin.ExtractFrontMatter.pdb b/docfx/plugins/DocFx.Plugin.ExtractFrontMatter.pdb deleted file mode 100644 index d923663e0..000000000 Binary files a/docfx/plugins/DocFx.Plugin.ExtractFrontMatter.pdb and /dev/null differ diff --git a/docfx/report-age.ps1 b/docfx/report-age.ps1 deleted file mode 100644 index 997f012d0..000000000 --- a/docfx/report-age.ps1 +++ /dev/null @@ -1,122 +0,0 @@ -# Script for reporting the information from the samples - -## Variables -param( - [string]$BaseDir = "d:\contrib\pkb-script-samples\", - [string]$ScriptFolder = "scripts", - [string]$ReportFile = "age.md", - [string]$AssetsFolder = "assets" -) - -function ResolveLink{ - param ( - [string] - $Link - ) - - $markdownLink = "../scripts/{0}/README.md" -f $Link - return $markdownLink -} - -function GetJsonFromSampleJson{ - param( - [string]$SamplePath, - [string]$DefaultReturn - ) - - try{ - $assetsFolder = Join-Path -Path $SamplePath -ChildPath $AssetsFolder - $sampleFilePath = Join-Path -Path $assetsFolder -ChildPath "sample.json" - - $json = Get-Content $sampleFilePath | ConvertFrom-Json - - return $json - - }catch{ - # Swallow - this shouldnt happen - Write-Host "Warning cannot resolve json: $PSItem.Message" - } - - return $DefaultReturn -} - -function ConvertToDateTime{ - param( - [string]$DateTimeString - ) - - try{ - $dateTime = [System.DateTime]::Parse($DateTimeString) - }catch{ - # Swallow - this shouldnt happen - Write-Host "Warning cannot convert to DateTime: $PSItem.Message" - return $null - } - - return $dateTime -} - -# Check all pages for tabs and three *** - -$dir = Join-Path -Path $BaseDir -ChildPath $ScriptFolder - -$files = Get-ChildItem -Path $dir -Recurse -Include README.md - -Write-Host "$($files.Length) found" - -"# Age Report of Samples" | Out-File $ReportFile -Force -"| Sample | Created | Modified (Latest) | " | Out-File $reportFile -Append -"|--------|:----:|:--------:|" | Out-File $reportFile -Append - -$matrixRows = @() -$sampleCount = 0 - -$files | Foreach-Object { - - # Skip these - if($_.Directory.Name -eq "scripts" -or - $_.Directory.Name -eq "_template-script-submission"){ - return - } - - $sampleJsonObj = GetJsonFromSampleJson -SamplePath $_.Directory -DefaultReturn $_.Directory.Name - - $title = $sampleJsonObj.title - $dirName = $_.Directory.Name - $sampleUrl = $sampleJsonObj.url - $created = $sampleJsonObj.creationDateTime - $modified = $sampleJsonObj.updateDateTime - $createdDt = ConvertToDateTime -DateTimeString $created - $modifiedDt = ConvertToDateTime -DateTimeString $modified - - $sampleCount++ - - $status = [PSCustomObject]@{ - Link = "[$($title)]($(ResolveLink $dirName))" - Description = $sampleJsonObj.shortDescription - Products = $($sampleJsonObj.products -join ', ') - Categories = $($sampleJsonObj.categories -join ', ') - Created = $created - Modified = $modified - CreatedDt = $createdDt - ModifiedDt = $modifiedDt - URL = $sampleUrl - } - - $matrixRows += $status -} - -# Output Report - - -$matrixRows | Sort-Object ModifiedDt -Descending | ForEach-Object{ - - $row = "| {0} | {1} | {2} | " -f $_.Link, $_.CreatedDt.ToString("dd MMM yyyy"), $_.ModifiedDt.ToString("dd MMM yyyy") - Write-Host $row - - $row | Out-File $reportFile -Append -} - -$summary = "`nThere are **{0}** script scenarios in the site | Generated: {1} `n`n" -f $sampleCount, [System.DateTime]::Now.ToString("dd MMM yyyy hh:mm:ss") -Write-Host $summary -$summary | Out-File $reportFile -Append diff --git a/docfx/report-cmdusage.ps1 b/docfx/report-cmdusage.ps1 deleted file mode 100644 index 35cd91a1a..000000000 --- a/docfx/report-cmdusage.ps1 +++ /dev/null @@ -1,268 +0,0 @@ -# Script for reporting the information from the samples - -## Variables -param( - [string]$BaseDir = "C:\Git\contrib\script-samples\", - [string]$ScriptFolder = "scripts", - [string]$ReportFile = "cmdusage.md", - [string]$AssetsFolder = "assets", - [string]$DocFxFolder = "docfx", - [string]$HelpFolder = "help", - [string]$IgnoreFile = "ignore.help.json" -) - -function ResolveLink{ - param ( - [string] - $Link - ) - - $markdownLink = Join-Path "../" "scripts" $Link "README.md" - return $markdownLink -} - -function GetTitleFromSampleJson{ - param( - [string]$SamplePath, - [string]$DefaultReturn - ) - - try{ - $assetsFolder = Join-Path -Path $SamplePath -ChildPath $AssetsFolder - $sampleFilePath = Join-Path -Path $assetsFolder -ChildPath "sample.json" - - $json = Get-Content $sampleFilePath | ConvertFrom-Json - - return $json.title - - }catch{ - # Swallow - this shouldnt happen - Write-Host "Warning cannot resolve title: $PSItem.Message" - } - - return $DefaultReturn -} - -function GetReadme{ - param( - [string]$SamplePath - ) - - try{ - - $readmeFilePath = Join-Path -Path $SamplePath -ChildPath "README.md" - - # On case-sensitive file systems (e.g. Linux), try a case-insensitive fallback - # if the exact path does not exist (e.g. readme.md instead of README.md) - if(-not (Test-Path -Path $readmeFilePath)){ - $readmeFile = Get-ChildItem -Path $SamplePath | Where-Object { $_.Name -ieq "README.md" } | Select-Object -First 1 - if($readmeFile){ - $readmeFilePath = $readmeFile.FullName - }else{ - Write-Host "Warning: README not found in $SamplePath" - return $null - } - } - - $content = Get-Content $readmeFilePath -Raw - - return $content - - }catch{ - # Swallow - this shouldnt happen - Write-Host "Warning cannot resolve readme: $PSItem.Message" - } -} - - -# Check all pages for tabs and three *** - -$dir = Join-Path $BaseDir $ScriptFolder - -$files = Get-ChildItem -Path $dir -Recurse -Include README.md - -Write-Host "$($files.Length) found" - -"# Report of Samples Command Usage" | Out-File $ReportFile -Force -"| Sample | Cmdlets | Detected Cmdlets |" | Out-File $reportFile -Append -"|--------|:--------:|:--------:|" | Out-File $reportFile -Append - -$matrixRows = @() -$helpCmds = @() -$cmdUsage = @() -$sampleCount = 0 - -# Get all help files in memory -$helpFolderPath = Join-Path $BaseDir $DocFxFolder $AssetsFolder $HelpFolder - -Write-Host "Help Path: $helpFolderPath" - -$helpFiles = Get-ChildItem -Path $helpFolderPath -Recurse -Include *.json -$helpFiles | ForEach-Object { - - $cmds = Get-Content -Path $_.FullName -Raw | ConvertFrom-Json - - $helpCmds += $cmds - - Write-Host "Help File: $_.Name Loaded" - - $cmdUsage += [PSCustomObject]@{ - File = $_.Name - Cmdlets = $cmds | ForEach-Object { - [PSCustomObject]@{ - Command = $_.cmd - UsageCount = 0 - } - } - } -} - -# Load the exceptions list -$ignoreFile = Join-Path $helpFolderPath $IgnoreFile -$ignoreHelpCmds = Get-Content -Path $ignoreFile -Raw | ConvertFrom-Json | ForEach-Object { "{0}," -f $_.cmd } - -Write-Host "Commands for Help Loaded: $($helpCmds.Length)" -Write-Host "Commands for Count Loaded: $($cmdUsage.Length)" -Write-Host "Commands Ignored: $($ignoreHelpCmds)" - -$files | Foreach-Object { - - # Skip these - if($_.Directory.Name -eq "scripts" -or - $_.Directory.Name -eq "_template-script-submission"){ - return - } - - $content = GetReadme -SamplePath $_.Directory - - if($null -eq $content){ - Write-Host "Warning: Skipping $($_.Directory.Name) - README.md could not be loaded" - return - } - - $title = GetTitleFromSampleJson -SamplePath $_.Directory -DefaultReturn $_.Directory.Name - $dirName = $_.Directory.Name - $cmdletsUsed = "" - $detectCmds = "" - - # TODO: This can be optimised to reduce the processing time - $helpCmds | foreach-Object { - if($content.Contains($_.cmd) -and $_.cmd -ne ""){ - $cmdletsUsed += "{0}, " -f $_.cmd - - $findCmd = $_.cmd - # Cmdlet Usage - $cmdUsage | ForEach-Object{ - - $existingCmd = $_.Cmdlets | Where-Object { $_.Command -eq $findCmd } - if($existingCmd){ - if($existingCmd.Length -eq 1){ - $existingCmd.UsageCount += 1 - } - if($existingCmd.Length -gt 1){ - Write-Host "Warning: more than one cmdlet found for {0}" -f $findCmd - } - } - } - } - } - - # Find all PowerShell commands beyond the help content - $results = $content | Select-String "\s[A-Za-z]+\-[A-Za-z]+\s" -AllMatches - $results.Matches | ForEach-Object { - [regex]::Escape($_.Value).Replace("\n","").Replace("\t","").Replace("\r","").replace("\ ","") - } | ForEach-Object { - - # Do not report on ignored cmdlets and already listed commands - if(!$ignoreHelpCmds.Contains( $_) -and !$cmdletsUsed.Contains($_)){ - - # De-deplicate - if(!$detectCmds.Contains($_)){ - $detectCmds += "{0}, " -f $_ - } - } - } - - $sampleCount++ - - $status = [PSCustomObject]@{ - Sample = "[$($title)]($(ResolveLink $dirName))" - Cmdlets = $cmdletsUsed.TrimEnd(", ") - DetectCmds = $detectCmds.TrimEnd(", ") - } - - $matrixRows += $status -} - -# Output Report -$matrixRows | ForEach-Object{ - - $row = "| {0} | {1} | {2} |" -f $_.Sample, $_.Cmdlets, $_.DetectCmds - Write-Host $row - - $row | Out-File $reportFile -Append -} - -# show cmdlets NOT used - -# PnP PowerShell -"## Overview of Sample Command Usage" | Out-File $ReportFile -Append - -$cmdUsage | ForEach-Object{ - - if($_.File -ne "ignore.help.json" -and $_.File -ne "archive.help.json"){ - - $friendlyName = "" - switch ($_.File) { - "cli.help.json" { $friendlyName = "CLI for Microsoft 365" } - "powershell.help.json" { $friendlyName = "PnP PowerShell" } - "spoms.help.json" { $friendlyName = "SharePoint Online Management Shell" } - Default {} - } - - - "### $($friendlyName) Usage" | Out-File $ReportFile -Append - - "| Used Cmdlets | Unused Cmdlets |" | Out-File $reportFile -Append - "|--------|--------|" | Out-File $reportFile -Append - - $usedCommands = $_.Cmdlets | Where-Object { $_.UsageCount -gt 0 } - $unUsedCommands = $_.Cmdlets | Where-Object { $_.UsageCount -eq 0 } - - $usedResult = "" - $usedCommands | ForEach-Object { - $usedResult += "{0}
" -f $_.Command - } - - $unUsedResult = "" - $unUsedCommands | ForEach-Object { - $UnUsedResult += "{0}
" -f $_.Command - } - - $row = "| {0} | {1} |" -f $usedResult, $UnUsedResult - Write-Host $row - - $row | Out-File $reportFile -Append - - $usedCmdCount = 0 - if($usedCommands){ - $usedCmdCount = $usedCommands.length - } - - $unUsedCmdCount = 0 - if($unUsedCommands){ - $unUsedCmdCount = $unUsedCommands.length - } - - - "| **Total Used** | **Total Unused** |" | Out-File $reportFile -Append - $counts = "| {0} | {1} |" -f $usedCmdCount, $unUsedCmdCount - $counts | Out-File $reportFile -Append - - } -} - - -$summary = "`nThere are **{0}** script scenarios with metadata in the site | Generated: {1} `n`n" -f $sampleCount, [System.DateTime]::Now.ToString("dd MMM yyyy hh:mm:ss") -Write-Host $summary -$summary | Out-File $reportFile -Append \ No newline at end of file diff --git a/docfx/report-matrix.ps1 b/docfx/report-matrix.ps1 deleted file mode 100644 index 77c482114..000000000 --- a/docfx/report-matrix.ps1 +++ /dev/null @@ -1,165 +0,0 @@ -# Script for reporting the information from the samples - -## Variables -param( - [string]$BaseDir = "D:\contrib\script-samples\", - [string]$ScriptFolder = "scripts", - [string]$ReportFile = "matrix.md", - [string]$AssetsFolder = "assets" -) - -function DispTick{ - [CmdletBinding()] - param ( - [Parameter()] - [bool] - $in - ) - - if($in -eq $true){ - return "`u{1F44D}" - } - - return "-" -} - -function ResolveLink{ - param ( - [string] - $Link - ) - - $markdownLink = "../scripts/{0}/README.md" -f $Link - return $markdownLink -} - -function GetTitleFromSampleJson{ - param( - [string]$SamplePath, - [string]$DefaultReturn - ) - - try{ - $assetsFolder = Join-Path -Path $SamplePath -ChildPath $AssetsFolder - $sampleFilePath = Join-Path -Path $assetsFolder -ChildPath "sample.json" - - $json = Get-Content $sampleFilePath | ConvertFrom-Json - - return $json.title - - }catch{ - # Swallow - this shouldnt happen - Write-Host "Warning cannot resolve title: $PSItem.Message" - } - - return $DefaultReturn -} - -# Check all pages for tabs and three *** - -$dir = Join-Path -Path $BaseDir -ChildPath $ScriptFolder - -$files = Get-ChildItem -Path $dir -Recurse -Include README.md - -Write-Host "$($files.Length) found" - -"# Matrix of Sample Distribution by Tool" | Out-File $ReportFile -Force - - -$matrixRows = @() -$sampleCount = 0 - -$PnPPSCount = 0 -$CLIPSCount = 0 -$CLIBashCount = 0 -$GraphSDKCount = 0 -$SPOMSCount = 0 -$AllTabs = 0 - -$files | Foreach-Object { - - # Skip these - if($_.Directory.Name -eq "scripts" -or - $_.Directory.Name -eq "_template-script-submission"){ - return - } - - $content = Get-Content -Path $_.FullName -Raw - $title = GetTitleFromSampleJson -SamplePath $_.Directory -DefaultReturn $_.Directory.Name - $dirName = $_.Directory.Name - $PnPPS = $false - $CLIPS = $false - $CLIBash = $false - $GraphSDK = $false - $SPOMS = $false - - #Write-Host $content - $matchResults = $content | Select-String "#tab/" -AllMatches - if($matchResults){ - $AllTabs += $matchResults.Matches.Count - } - - if($content.Contains("#tab/pnpps")){ - $PnPPS = $true - $sampleCount++ - $PnPPSCount++ - } - if($content.Contains("#tab/cli-m365-ps")){ - $CLIPS = $true - $sampleCount++ - $CLIPSCount++ - } - if($content.Contains("#tab/cli-m365-bash") -or - $content.Contains("#tab/m365cli-bash")){ - - $CLIBash = $true - $sampleCount++ - $CLIBashCount++ - } - - if($content.Contains("#tab/graphps")){ - $GraphSDK = $true - $sampleCount++ - $GraphSDKCount++ - } - if($content.Contains("#tab/spoms-ps")){ - $SPOMS = $true - $sampleCount++ - $SPOMSCount++ - } - - $status = [PSCustomObject]@{ - Link = "[$($title)]($(ResolveLink $dirName))" - PnPPS = $PnPPS - CLIPS = $CLIPS - CLIBash = $CLIBash - GraphSDK = $GraphSDK - SPOMS = $SPOMS - } - $matrixRows += $status -} - -# Output Report - -"`nThere are **{0}** scenarios and **{1}** scripts in the site | Generated: {2} `n`n" -f $matrixRows.Length, $sampleCount, [System.DateTime]::Now.ToString("dd MMM yyyy hh:mm:ss") ` - | Out-File $reportFile -Append - -"`rPnP PowerShell: {0}
Cli for Microsoft 365 PowerShell: {1}
Cli for Microsoft 365 Bash: {2}
Graph SDK: {3}
SPO Management SDK: {4}
All Tabs: {5}

" ` - -f $PnPPSCount, $CLIPSCount, $CLIBashCount, $GraphSDKCount, $SPOMSCount, $AllTabs ` - | Out-File $reportFile -Append -"`n`n" | Out-File $reportFile -Append - -"| Sample | PnP
PowerShell | Cli for Microsoft 365
PowerShell | Cli for Microsoft 365
Bash | Graph
SDK | SPO Management
Shell |" | Out-File $reportFile -Append -"|--------|:--------:|:--------:|:----------:|:-----------:|:--------:|" | Out-File $reportFile -Append - -$matrixRows | ForEach-Object{ - - $row = "| {0} | {1} | {2} | {3} | {4} | {5} |" -f $_.Link, (DispTick $_.PnPPS), (DispTick $_.CLIPS), (DispTick $_.CLIBash), (DispTick $_.GraphSDK), (DispTick $_.SPOMS) - Write-Host $row - - $row | Out-File $reportFile -Append -} - -# Counts -$row = "| - | {0} | {1} | {2} | {3} | {4} |" -f $PnPPSCount, $CLIPSCount, $CLIBashCount, $GraphSDKCount, $SPOMSCount -$row | Out-File $reportFile -Append diff --git a/docfx/report-metadata.ps1 b/docfx/report-metadata.ps1 deleted file mode 100644 index e0569b762..000000000 --- a/docfx/report-metadata.ps1 +++ /dev/null @@ -1,146 +0,0 @@ -# Script for reporting the information from the samples - -## Variables -param( - [string]$BaseDir = "C:\Git\contrib\script-samples\", - [string]$ScriptFolder = "scripts", - [string]$ReportFile = "metadata.md", - [string]$AssetsFolder = "assets" -) - -function DispTick{ - return "`u{1F44D}" -} - -function DispNope{ - return "`u{1F937}" -} - -function ResolveLink{ - param ( - [string] - $Link - ) - - $markdownLink = "../scripts/{0}/README.md" -f $Link - return $markdownLink -} - -function GetJsonFromSampleJson{ - param( - [string]$SamplePath, - [string]$DefaultReturn - ) - - try{ - $assetsFolder = Join-Path -Path $SamplePath -ChildPath $AssetsFolder - $sampleFilePath = Join-Path -Path $assetsFolder -ChildPath "sample.json" - - $json = Get-Content $sampleFilePath | ConvertFrom-Json - - return $json - - }catch{ - # Swallow - this shouldnt happen - Write-Host "Warning cannot resolve json: $PSItem.Message" - } - - return $DefaultReturn -} - -# Check all pages for tabs and three *** - -$dir = Join-Path -Path $BaseDir -ChildPath $ScriptFolder - -$files = Get-ChildItem -Path $dir -Recurse -Include README.md - -Write-Host "$($files.Length) found" - -"# Metadata Report of Samples" | Out-File $ReportFile -Force -"| Sample | Products | Categories | Tags | Metadata | URL | Image URL | Source Credit | Reference Count |" | Out-File $reportFile -Append -"|--------|:--------:|:----------:|:----:|:--------:|:---------:|:---------:|:-------------:|:---------------:|" | Out-File $reportFile -Append - -$matrixRows = @() -$sampleCount = 0 - -$files | Foreach-Object { - - # Skip these - if($_.Directory.Name -eq "scripts" -or - $_.Directory.Name -eq "_template-script-submission"){ - return - } - - $sampleJsonObj = GetJsonFromSampleJson -SamplePath $_.Directory -DefaultReturn $_.Directory.Name - - $content = Get-Content -Path $_.FullName -Raw - $title = $sampleJsonObj.title - $dirName = $_.Directory.Name - $imgUrl = $sampleJsonObj.thumbnails[0].url - $sampleUrl = $sampleJsonObj.url - $imgStatus = "" - $sampleUrlStatus = "" - $sourceCreditReference = "-" - $referenceCount = 0 - $tags = "" - - if($imgUrl -like "https://raw.githubusercontent.com/pnp/script-samples/main/scripts/*"){ - $imgStatus = DispTick - }else{ - $imgStatus = DispNope - } - - if($sampleUrl -like "https://pnp.github.io/script-samples/*"){ - $sampleUrlStatus = DispTick - }else{ - $sampleUrlStatus = DispNope - } - - if($content.Contains("#tab/cli-m365-ps")){ - $sourceCreditReference = DispTick - } - - if($sampleJsonObj.PSobject.Properties.name -match "references"){ - if($sampleJsonObj.references){ - $referenceCount = $sampleJsonObj.references.length - } - } - - if($sampleJsonObj.PSobject.Properties.name -match "tags"){ - if($sampleJsonObj.tags){ - $tags = $sampleJsonObj.tags -join ', ' - } - } - - $sampleCount++ - - $status = [PSCustomObject]@{ - Link = "[$($title)]($(ResolveLink $dirName))" - Description = $sampleJsonObj.shortDescription - Products = $($sampleJsonObj.products -join ', ') - Categories = $($sampleJsonObj.categories -join ', ') - Tags = $tags - Metadata = $($sampleJsonObj.metadata.key -join ', ') - URL = $sampleUrlStatus - ImageStatus = $imgStatus - HasSourceCredit = $sourceCreditReference - ReferenceCount = $referenceCount - } - - $matrixRows += $status -} - -# Output Report - - -$matrixRows | ForEach-Object{ - - $row = "| {0} | {1} | {2} | {3} | {4} | {5} | {6} | {7} | {8} |" -f $_.Link, $_.Products, $_.Categories, $_.Tags, $_.Metadata, $_.URL, $_.ImageStatus, $_.HasSourceCredit, $_.ReferenceCount - Write-Host $row - - $row | Out-File $reportFile -Append -} - -$summary = "`nThere are **{0}** script scenarios with metadata in the site | Generated: {1} `n`n" -f $sampleCount, [System.DateTime]::Now.ToString("dd MMM yyyy hh:mm:ss") -Write-Host $summary -$summary | Out-File $reportFile -Append \ No newline at end of file diff --git a/docfx/templates/material/layout/_master.tmpl b/docfx/templates/material/layout/_master.tmpl deleted file mode 100644 index 5d38f5286..000000000 --- a/docfx/templates/material/layout/_master.tmpl +++ /dev/null @@ -1,58 +0,0 @@ -{{!Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.}} -{{!include(/^styles/.*/)}} -{{!include(/^fonts/.*/)}} -{{!include(favicon.ico)}} -{{!include(logo.svg)}} -{{!include(search-stopwords.json)}} - - - - {{>partials/head}} - -
-
- {{^_disableNavbar}} - {{>partials/navbar}} - {{/_disableNavbar}} - {{^_disableBreadcrumb}} - {{>partials/breadcrumb}} - {{/_disableBreadcrumb}} -
- {{#_enableSearch}} -
- {{>partials/searchResults}} -
- {{/_enableSearch}} - '); - } - - // Styling for alerts. - function renderAlerts() { - $('.NOTE, .TIP').addClass('alert alert-info'); - $('.WARNING').addClass('alert alert-warning'); - $('.IMPORTANT, .CAUTION').addClass('alert alert-danger'); - } - - // Enable anchors for headings. - (function () { - anchors.options = { - placement: 'left', - visible: 'touch' - }; - //anchors.add('article h2:not(.no-anchor), article h3:not(.no-anchor), article h4:not(.no-anchor)'); - })(); - - // Open links to different host in a new window. - function renderLinks() { - if ($("meta[property='docfx:newtab']").attr("content") === "true") { - $(document.links).filter(function () { - return this.hostname !== window.location.hostname; - }).attr('target', '_blank'); - } - } - - // Enable highlight.js - function highlight() { - $('pre code').each(function (i, block) { - hljs.highlightBlock(block); - }); - $('pre code[highlight-lines]').each(function (i, block) { - if (block.innerHTML === "") return; - var lines = block.innerHTML.split('\n'); - - queryString = block.getAttribute('highlight-lines'); - if (!queryString) return; - - var ranges = queryString.split(','); - for (var j = 0, range; range = ranges[j++];) { - var found = range.match(/^(\d+)\-(\d+)?$/); - if (found) { - // consider region as `{startlinenumber}-{endlinenumber}`, in which {endlinenumber} is optional - var start = +found[1]; - var end = +found[2]; - if (isNaN(end) || end > lines.length) { - end = lines.length; - } - } else { - // consider region as a sigine line number - if (isNaN(range)) continue; - var start = +range; - var end = start; - } - if (start <= 0 || end <= 0 || start > end || start > lines.length) { - // skip current region if invalid - continue; - } - lines[start - 1] = '' + lines[start - 1]; - lines[end - 1] = lines[end - 1] + ''; - } - - block.innerHTML = lines.join('\n'); - }); - } - - // Support full-text-search - function enableSearch() { - var query; - var relHref = $("meta[property='docfx\\:rel']").attr("content"); - if (typeof relHref === 'undefined') { - return; - } - try { - var worker = new Worker(relHref + 'styles/search-worker.js'); - if (!worker && !window.worker) { - localSearch(); - } else { - webWorkerSearch(); - } - - renderSearchBox(); - highlightKeywords(); - addSearchEvent(); - } catch (e) { - console.error(e); - } - - //Adjust the position of search box in navbar - function renderSearchBox() { - autoCollapse(); - $(window).on('resize', autoCollapse); - $(document).on('click', '.navbar-collapse.in', function (e) { - if ($(e.target).is('a')) { - $(this).collapse('hide'); - } - }); - - function autoCollapse() { - var navbar = $('#autocollapse'); - if (navbar.height() === null) { - setTimeout(autoCollapse, 300); - } - navbar.removeClass(collapsed); - if (navbar.height() > 60) { - navbar.addClass(collapsed); - } - } - } - - // Search factory - function localSearch() { - console.log("using local search"); - var lunrIndex = lunr(function () { - this.ref('href'); - this.field('title', { boost: 50 }); - this.field('keywords', { boost: 20 }); - }); - lunr.tokenizer.seperator = /[\s\-\.]+/; - var searchData = {}; - var searchDataRequest = new XMLHttpRequest(); - - var indexPath = relHref + "index.json"; - if (indexPath) { - searchDataRequest.open('GET', indexPath); - searchDataRequest.onload = function () { - if (this.status != 200) { - return; - } - searchData = JSON.parse(this.responseText); - for (var prop in searchData) { - if (searchData.hasOwnProperty(prop)) { - lunrIndex.add(searchData[prop]); - } - } - } - searchDataRequest.send(); - } - - $("body").bind("queryReady", function () { - var hits = lunrIndex.search(query); - var results = []; - hits.forEach(function (hit) { - var item = searchData[hit.ref]; - results.push({ 'href': item.href, 'title': item.title, 'keywords': item.keywords }); - }); - handleSearchResults(results); - }); - } - - function webWorkerSearch() { - console.log("using Web Worker"); - var indexReady = $.Deferred(); - - worker.onmessage = function (oEvent) { - switch (oEvent.data.e) { - case 'index-ready': - indexReady.resolve(); - break; - case 'query-ready': - var hits = oEvent.data.d; - handleSearchResults(hits); - break; - } - } - - indexReady.promise().done(function () { - $("body").bind("queryReady", function () { - worker.postMessage({ q: query }); - }); - if (query && (query.length >= 3)) { - worker.postMessage({ q: query }); - } - }); - } - - // Highlight the searching keywords - function highlightKeywords() { - var q = url('?q'); - if (q !== null) { - var keywords = q.split("%20"); - keywords.forEach(function (keyword) { - if (keyword !== "") { - $('.data-searchable *').mark(keyword); - $('article *').mark(keyword); - } - }); - } - } - - function addSearchEvent() { - $('body').bind("searchEvent", function () { - $('#search-query').keypress(function (e) { - return e.which !== 13; - }); - - $('#search-query').keyup(function () { - query = $(this).val(); - if (query.length < 3) { - flipContents("show"); - } else { - flipContents("hide"); - $("body").trigger("queryReady"); - $('#search-results>.search-list').text('Search Results for "' + query + '"'); - } - }).off("keydown"); - }); - } - - function flipContents(action) { - if (action === "show") { - $('.hide-when-search').show(); - $('#search-results').hide(); - } else { - $('.hide-when-search').hide(); - $('#search-results').show(); - } - } - - function relativeUrlToAbsoluteUrl(currentUrl, relativeUrl) { - var currentItems = currentUrl.split(/\/+/); - var relativeItems = relativeUrl.split(/\/+/); - var depth = currentItems.length - 1; - var items = []; - for (var i = 0; i < relativeItems.length; i++) { - if (relativeItems[i] === '..') { - depth--; - } else if (relativeItems[i] !== '.') { - items.push(relativeItems[i]); - } - } - return currentItems.slice(0, depth).concat(items).join('/'); - } - - function extractContentBrief(content) { - var briefOffset = 512; - var words = query.split(/\s+/g); - var queryIndex = content.indexOf(words[0]); - var briefContent; - if (queryIndex > briefOffset) { - return "..." + content.slice(queryIndex - briefOffset, queryIndex + briefOffset) + "..."; - } else if (queryIndex <= briefOffset) { - return content.slice(0, queryIndex + briefOffset) + "..."; - } - } - - function handleSearchResults(hits) { - var numPerPage = 10; - $('#pagination').empty(); - $('#pagination').removeData("twbs-pagination"); - if (hits.length === 0) { - $('#search-results>.sr-items').html('

No results found

'); - } else { - $('#pagination').twbsPagination({ - totalPages: Math.ceil(hits.length / numPerPage), - visiblePages: 5, - onPageClick: function (event, page) { - var start = (page - 1) * numPerPage; - var curHits = hits.slice(start, start + numPerPage); - $('#search-results>.sr-items').empty().append( - curHits.map(function (hit) { - var currentUrl = window.location.href; - var itemRawHref = relativeUrlToAbsoluteUrl(currentUrl, relHref + hit.href); - var itemHref = relHref + hit.href + "?q=" + query; - var itemTitle = hit.title; - var itemBrief = extractContentBrief(hit.keywords); - - var itemNode = $('
').attr('class', 'sr-item'); - var itemTitleNode = $('
').attr('class', 'item-title').append($('').attr('href', itemHref).attr("target", "_blank").text(itemTitle)); - var itemHrefNode = $('
').attr('class', 'item-href').text(itemRawHref); - var itemBriefNode = $('
').attr('class', 'item-brief').text(itemBrief); - itemNode.append(itemTitleNode).append(itemHrefNode).append(itemBriefNode); - return itemNode; - }) - ); - query.split(/\s+/).forEach(function (word) { - if (word !== '') { - $('#search-results>.sr-items *').mark(word); - } - }); - } - }); - } - } - }; - - // Update href in navbar - function renderNavbar() { - var navbar = $('#navbar ul')[0]; - if (typeof (navbar) === 'undefined') { - loadNavbar(); - } else { - $('#navbar ul a.active').parents('li').addClass(active); - renderBreadcrumb(); - showSearch(); - - // if window url is site root then set first item in navbar to active - if (window.location.pathname === '/' || window.location.pathname === '/script-samples/') { - $('#navbar ul li:first-child').addClass(active); - } - - } - - function showSearch() { - if ($('#search-results').length !== 0) { - $('#search').show(); - $('body').trigger("searchEvent"); - } - } - - function loadNavbar() { - var navbarPath = $("meta[property='docfx\\:navrel']").attr("content"); - if (!navbarPath) { - return; - } - navbarPath = navbarPath.replace(/\\/g, '/'); - var tocPath = $("meta[property='docfx\\:tocrel']").attr("content") || ''; - if (tocPath) tocPath = tocPath.replace(/\\/g, '/'); - $.get(navbarPath, function (data) { - $(data).find("#toc>ul").appendTo("#navbar"); - showSearch(); - var index = navbarPath.lastIndexOf('/'); - var navrel = ''; - if (index > -1) { - navrel = navbarPath.substr(0, index + 1); - } - $('#navbar>ul').addClass('navbar-nav'); - var currentAbsPath = util.getAbsolutePath(window.location.pathname); - // set active item - $('#navbar').find('a[href]').each(function (i, e) { - var href = $(e).attr("href"); - if (util.isRelativePath(href)) { - href = navrel + href; - $(e).attr("href", href); - - var isActive = false; - var originalHref = e.name; - if (originalHref) { - originalHref = navrel + originalHref; - if (util.getDirectory(util.getAbsolutePath(originalHref)) === util.getDirectory(util.getAbsolutePath(tocPath))) { - isActive = true; - } - } else { - if (util.getAbsolutePath(href) === currentAbsPath) { - var dropdown = $(e).attr('data-toggle') == "dropdown" - if (!dropdown) { - isActive = true; - } - } - } - if (isActive) { - $(e).addClass(active); - } - } - }); - renderNavbar(); - }); - } - } - - function renderSidebar() { - var sidetoc = $('#sidetoggle .sidetoc')[0]; - if (typeof (sidetoc) === 'undefined') { - loadToc(); - } else { - registerTocEvents(); - if ($('footer').is(':visible')) { - $('.sidetoc').addClass('shiftup'); - } - - // Scroll to active item - var top = 0; - $('#toc a.active').parents('li').each(function (i, e) { - $(e).addClass(active).addClass(expanded); - $(e).children('a').addClass(active); - }) - $('#toc a.active').parents('li').each(function (i, e) { - top += $(e).position().top; - }) - $('.sidetoc').scrollTop(top - 50); - - if ($('footer').is(':visible')) { - $('.sidetoc').addClass('shiftup'); - } - - renderBreadcrumb(); - } - - function registerTocEvents() { - var tocFilterInput = $('#toc_filter_input'); - var tocFilterClearButton = $('#toc_filter_clear'); - - $('.toc .nav > li > .expand-stub').click(function (e) { - $(e.target).parent().toggleClass(expanded); - }); - $('.toc .nav > li > .expand-stub + a:not([href])').click(function (e) { - $(e.target).parent().toggleClass(expanded); - }); - tocFilterInput.on('input', function (e) { - var val = this.value; - //Save filter string to local session storage - if (typeof(Storage) !== "undefined") { - try { - sessionStorage.filterString = val; - } - catch(e) - {} - } - if (val === '') { - // Clear 'filtered' class - $('#toc li').removeClass(filtered).removeClass(hide); - tocFilterClearButton.fadeOut(); - return; - } - tocFilterClearButton.fadeIn(); - - // set all parent nodes status - $('#toc li>a').filter(function (i, e) { - return $(e).siblings().length > 0 - }).each(function (i, anchor) { - var parent = $(anchor).parent(); - parent.addClass(hide); - parent.removeClass(show); - parent.removeClass(filtered); - }) - - // Get leaf nodes - $('#toc li>a').filter(function (i, e) { - return $(e).siblings().length === 0 - }).each(function (i, anchor) { - var text = $(anchor).attr('title'); - var parent = $(anchor).parent(); - var parentNodes = parent.parents('ul>li'); - for (var i = 0; i < parentNodes.length; i++) { - var parentText = $(parentNodes[i]).children('a').attr('title'); - if (parentText) text = parentText + '.' + text; - }; - if (filterNavItem(text, val)) { - parent.addClass(show); - parent.removeClass(hide); - } else { - parent.addClass(hide); - parent.removeClass(show); - } - }); - $('#toc li>a').filter(function (i, e) { - return $(e).siblings().length > 0 - }).each(function (i, anchor) { - var parent = $(anchor).parent(); - if (parent.find('li.show').length > 0) { - parent.addClass(show); - parent.addClass(filtered); - parent.removeClass(hide); - } else { - parent.addClass(hide); - parent.removeClass(show); - parent.removeClass(filtered); - } - }) - - function filterNavItem(name, text) { - if (!text) return true; - if (name && name.toLowerCase().indexOf(text.toLowerCase()) > -1) return true; - return false; - } - }); - - // toc filter clear button - tocFilterClearButton.hide(); - tocFilterClearButton.on("click", function(e){ - tocFilterInput.val(""); - tocFilterInput.trigger('input'); - if (typeof(Storage) !== "undefined") { - try { - sessionStorage.filterString = ""; - } - catch(e) - {} - } - }); - - //Set toc filter from local session storage on page load - if (typeof(Storage) !== "undefined") { - try { - tocFilterInput.val(sessionStorage.filterString); - tocFilterInput.trigger('input'); - } - catch(e) - {} - } - } - - function loadToc() { - var tocPath = $("meta[property='docfx\\:tocrel']").attr("content"); - if (!tocPath) { - return; - } - tocPath = tocPath.replace(/\\/g, '/'); - $('#sidetoc').load(tocPath + " #sidetoggle > div", function () { - var index = tocPath.lastIndexOf('/'); - var tocrel = ''; - if (index > -1) { - tocrel = tocPath.substr(0, index + 1); - } - var currentHref = util.getAbsolutePath(window.location.pathname); - $('#sidetoc').find('a[href]').each(function (i, e) { - var href = $(e).attr("href"); - if (util.isRelativePath(href)) { - href = tocrel + href; - $(e).attr("href", href); - } - - if (util.getAbsolutePath(e.href) === currentHref) { - $(e).addClass(active); - } - - $(e).breakWord(); - }); - - renderSidebar(); - }); - } - } - - function renderBreadcrumb() { - var breadcrumb = []; - $('#navbar a.active').each(function (i, e) { - breadcrumb.push({ - href: e.href, - name: e.innerHTML - }); - }) - $('#toc a.active').each(function (i, e) { - breadcrumb.push({ - href: e.href, - name: e.innerHTML - }); - }) - - var html = util.formList(breadcrumb, 'breadcrumb'); - $('#breadcrumb').html(html); - } - - //Setup Affix - function renderAffix() { - var hierarchy = getHierarchy(); - if (hierarchy && hierarchy.length > 0) { - var html = '
In This Article
' - html += util.formList(hierarchy, ['nav', 'bs-docs-sidenav']); - $("#affix").empty().append(html); - if ($('footer').is(':visible')) { - $(".sideaffix").css("bottom", "70px"); - } - $('#affix a').click(function(e) { - var scrollspy = $('[data-spy="scroll"]').data()['bs.scrollspy']; - var target = e.target.hash; - if (scrollspy && target) { - scrollspy.activate(target); - } - }); - } - - function getHierarchy() { - // supported headers are h1, h2, h3, and h4 - var $headers = $($.map(['h1', 'h2', 'h3', 'h4'], function (h) { return ".article article " + h; }).join(", ")); - - // a stack of hierarchy items that are currently being built - var stack = []; - $headers.each(function (i, e) { - if (!e.id) { - return; - } - - var item = { - name: htmlEncode($(e).text()), - href: "#" + e.id, - items: [] - }; - - if (!stack.length) { - stack.push({ type: e.tagName, siblings: [item] }); - return; - } - - var frame = stack[stack.length - 1]; - if (e.tagName === frame.type) { - frame.siblings.push(item); - } else if (e.tagName[1] > frame.type[1]) { - // we are looking at a child of the last element of frame.siblings. - // push a frame onto the stack. After we've finished building this item's children, - // we'll attach it as a child of the last element - stack.push({ type: e.tagName, siblings: [item] }); - } else { // e.tagName[1] < frame.type[1] - // we are looking at a sibling of an ancestor of the current item. - // pop frames from the stack, building items as we go, until we reach the correct level at which to attach this item. - while (e.tagName[1] < stack[stack.length - 1].type[1]) { - buildParent(); - } - if (e.tagName === stack[stack.length - 1].type) { - stack[stack.length - 1].siblings.push(item); - } else { - stack.push({ type: e.tagName, siblings: [item] }); - } - } - }); - while (stack.length > 1) { - buildParent(); - } - - function buildParent() { - var childrenToAttach = stack.pop(); - var parentFrame = stack[stack.length - 1]; - var parent = parentFrame.siblings[parentFrame.siblings.length - 1]; - $.each(childrenToAttach.siblings, function (i, child) { - parent.items.push(child); - }); - } - if (stack.length > 0) { - - var topLevel = stack.pop().siblings; - if (topLevel.length === 1) { // if there's only one topmost header, dump it - return topLevel[0].items; - } - return topLevel; - } - return undefined; - } - - function htmlEncode(str) { - if (!str) return str; - return str - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(/'/g, ''') - .replace(//g, '>'); - } - - function htmlDecode(value) { - if (!str) return str; - return value - .replace(/"/g, '"') - .replace(/'/g, "'") - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/&/g, '&'); - } - - function cssEscape(str) { - // see: http://stackoverflow.com/questions/2786538/need-to-escape-a-special-character-in-a-jquery-selector-string#answer-2837646 - if (!str) return str; - return str - .replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, "\\$&"); - } - } - - // Show footer - function renderFooter() { - initFooter(); - $(window).on("scroll", showFooterCore); - - function initFooter() { - if (needFooter()) { - shiftUpBottomCss(); - $("footer").show(); - } else { - resetBottomCss(); - $("footer").hide(); - } - } - - function showFooterCore() { - if (needFooter()) { - shiftUpBottomCss(); - $("footer").fadeIn(); - } else { - resetBottomCss(); - $("footer").fadeOut(); - } - } - - function needFooter() { - var scrollHeight = $(document).height(); - var scrollPosition = $(window).height() + $(window).scrollTop(); - return (scrollHeight - scrollPosition) < 1; - } - - function resetBottomCss() { - $(".sidetoc").removeClass("shiftup"); - $(".sideaffix").removeClass("shiftup"); - } - - function shiftUpBottomCss() { - $(".sidetoc").addClass("shiftup"); - $(".sideaffix").addClass("shiftup"); - } - } - - function renderLogo() { - // For LOGO SVG - // Replace SVG with inline SVG - // http://stackoverflow.com/questions/11978995/how-to-change-color-of-svg-image-using-css-jquery-svg-image-replacement - jQuery('img.svg').each(function () { - var $img = jQuery(this); - var imgID = $img.attr('id'); - var imgClass = $img.attr('class'); - var imgURL = $img.attr('src'); - - jQuery.get(imgURL, function (data) { - // Get the SVG tag, ignore the rest - var $svg = jQuery(data).find('svg'); - - // Add replaced image's ID to the new SVG - if (typeof imgID !== 'undefined') { - $svg = $svg.attr('id', imgID); - } - // Add replaced image's classes to the new SVG - if (typeof imgClass !== 'undefined') { - $svg = $svg.attr('class', imgClass + ' replaced-svg'); - } - - // Remove any invalid XML tags as per http://validator.w3.org - $svg = $svg.removeAttr('xmlns:a'); - - // Replace image with new SVG - $img.replaceWith($svg); - - }, 'xml'); - }); - } - - function renderTabs() { - var contentAttrs = { - id: 'data-bi-id', - name: 'data-bi-name', - type: 'data-bi-type' - }; - - var Tab = (function () { - function Tab(li, a, section) { - this.li = li; - this.a = a; - this.section = section; - } - Object.defineProperty(Tab.prototype, "tabIds", { - get: function () { return this.a.getAttribute('data-tab').split(' '); }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tab.prototype, "condition", { - get: function () { return this.a.getAttribute('data-condition'); }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tab.prototype, "visible", { - get: function () { return !this.li.hasAttribute('hidden'); }, - set: function (value) { - if (value) { - this.li.removeAttribute('hidden'); - this.li.removeAttribute('aria-hidden'); - } - else { - this.li.setAttribute('hidden', 'hidden'); - this.li.setAttribute('aria-hidden', 'true'); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tab.prototype, "selected", { - get: function () { return !this.section.hasAttribute('hidden'); }, - set: function (value) { - if (value) { - this.a.setAttribute('aria-selected', 'true'); - this.a.tabIndex = 0; - this.section.removeAttribute('hidden'); - this.section.removeAttribute('aria-hidden'); - } - else { - this.a.setAttribute('aria-selected', 'false'); - this.a.tabIndex = -1; - this.section.setAttribute('hidden', 'hidden'); - this.section.setAttribute('aria-hidden', 'true'); - } - }, - enumerable: true, - configurable: true - }); - Tab.prototype.focus = function () { - this.a.focus(); - }; - return Tab; - }()); - - initTabs(document.body); - - function initTabs(container) { - var queryStringTabs = readTabsQueryStringParam(); - var elements = container.querySelectorAll('.tabGroup'); - var state = { groups: [], selectedTabs: [] }; - for (var i = 0; i < elements.length; i++) { - var group = initTabGroup(elements.item(i)); - if (!group.independent) { - updateVisibilityAndSelection(group, state); - state.groups.push(group); - } - } - container.addEventListener('click', function (event) { return handleClick(event, state); }); - if (state.groups.length === 0) { - return state; - } - selectTabs(queryStringTabs, container); - updateTabsQueryStringParam(state); - notifyContentUpdated(); - return state; - } - - function initTabGroup(element) { - var group = { - independent: element.hasAttribute('data-tab-group-independent'), - tabs: [] - }; - var li = element.firstElementChild.firstElementChild; - while (li) { - var a = li.firstElementChild; - a.setAttribute(contentAttrs.name, 'tab'); - var dataTab = a.getAttribute('data-tab').replace(/\+/g, ' '); - a.setAttribute('data-tab', dataTab); - var section = element.querySelector("[id=\"" + a.getAttribute('aria-controls') + "\"]"); - var tab = new Tab(li, a, section); - group.tabs.push(tab); - li = li.nextElementSibling; - } - element.setAttribute(contentAttrs.name, 'tab-group'); - element.tabGroup = group; - return group; - } - - function updateVisibilityAndSelection(group, state) { - var anySelected = false; - var firstVisibleTab; - for (var _i = 0, _a = group.tabs; _i < _a.length; _i++) { - var tab = _a[_i]; - tab.visible = tab.condition === null || state.selectedTabs.indexOf(tab.condition) !== -1; - if (tab.visible) { - if (!firstVisibleTab) { - firstVisibleTab = tab; - } - } - tab.selected = tab.visible && arraysIntersect(state.selectedTabs, tab.tabIds); - anySelected = anySelected || tab.selected; - } - if (!anySelected) { - for (var _b = 0, _c = group.tabs; _b < _c.length; _b++) { - var tabIds = _c[_b].tabIds; - for (var _d = 0, tabIds_1 = tabIds; _d < tabIds_1.length; _d++) { - var tabId = tabIds_1[_d]; - var index = state.selectedTabs.indexOf(tabId); - if (index === -1) { - continue; - } - state.selectedTabs.splice(index, 1); - } - } - var tab = firstVisibleTab; - tab.selected = true; - state.selectedTabs.push(tab.tabIds[0]); - } - } - - function getTabInfoFromEvent(event) { - if (!(event.target instanceof HTMLElement)) { - return null; - } - var anchor = event.target.closest('a[data-tab]'); - if (anchor === null) { - return null; - } - var tabIds = anchor.getAttribute('data-tab').split(' '); - var group = anchor.parentElement.parentElement.parentElement.tabGroup; - if (group === undefined) { - return null; - } - return { tabIds: tabIds, group: group, anchor: anchor }; - } - - function handleClick(event, state) { - var info = getTabInfoFromEvent(event); - if (info === null) { - return; - } - event.preventDefault(); - info.anchor.href = 'javascript:'; - setTimeout(function () { return info.anchor.href = '#' + info.anchor.getAttribute('aria-controls'); }); - var tabIds = info.tabIds, group = info.group; - var originalTop = info.anchor.getBoundingClientRect().top; - if (group.independent) { - for (var _i = 0, _a = group.tabs; _i < _a.length; _i++) { - var tab = _a[_i]; - tab.selected = arraysIntersect(tab.tabIds, tabIds); - } - } - else { - if (arraysIntersect(state.selectedTabs, tabIds)) { - return; - } - var previousTabId = group.tabs.filter(function (t) { return t.selected; })[0].tabIds[0]; - state.selectedTabs.splice(state.selectedTabs.indexOf(previousTabId), 1, tabIds[0]); - for (var _b = 0, _c = state.groups; _b < _c.length; _b++) { - var group_1 = _c[_b]; - updateVisibilityAndSelection(group_1, state); - } - updateTabsQueryStringParam(state); - } - notifyContentUpdated(); - var top = info.anchor.getBoundingClientRect().top; - if (top !== originalTop && event instanceof MouseEvent) { - window.scrollTo(0, window.pageYOffset + top - originalTop); - } - } - - function selectTabs(tabIds) { - for (var _i = 0, tabIds_1 = tabIds; _i < tabIds_1.length; _i++) { - var tabId = tabIds_1[_i]; - var a = document.querySelector(".tabGroup > ul > li > a[data-tab=\"" + tabId + "\"]:not([hidden])"); - if (a === null) { - return; - } - a.dispatchEvent(new CustomEvent('click', { bubbles: true })); - } - } - - function readTabsQueryStringParam() { - var qs = parseQueryString(); - var t = qs.tabs; - if (t === undefined || t === '') { - return []; - } - return t.split(','); - } - - function updateTabsQueryStringParam(state) { - var qs = parseQueryString(); - qs.tabs = state.selectedTabs.join(); - var url = location.protocol + "//" + location.host + location.pathname + "?" + toQueryString(qs) + location.hash; - if (location.href === url) { - return; - } - history.replaceState({}, document.title, url); - } - - function toQueryString(args) { - var parts = []; - for (var name_1 in args) { - if (args.hasOwnProperty(name_1) && args[name_1] !== '' && args[name_1] !== null && args[name_1] !== undefined) { - parts.push(encodeURIComponent(name_1) + '=' + encodeURIComponent(args[name_1])); - } - } - return parts.join('&'); - } - - function parseQueryString(queryString) { - var match; - var pl = /\+/g; - var search = /([^&=]+)=?([^&]*)/g; - var decode = function (s) { return decodeURIComponent(s.replace(pl, ' ')); }; - if (queryString === undefined) { - queryString = ''; - } - queryString = queryString.substring(1); - var urlParams = {}; - while (match = search.exec(queryString)) { - urlParams[decode(match[1])] = decode(match[2]); - } - return urlParams; - } - - function arraysIntersect(a, b) { - for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { - var itemA = a_1[_i]; - for (var _a = 0, b_1 = b; _a < b_1.length; _a++) { - var itemB = b_1[_a]; - if (itemA === itemB) { - return true; - } - } - } - return false; - } - - function notifyContentUpdated() { - // Dispatch this event when needed - // window.dispatchEvent(new CustomEvent('content-update')); - } - } - - function utility() { - this.getAbsolutePath = getAbsolutePath; - this.isRelativePath = isRelativePath; - this.isAbsolutePath = isAbsolutePath; - this.getDirectory = getDirectory; - this.formList = formList; - - function getAbsolutePath(href) { - // Use anchor to normalize href - var anchor = $('
')[0]; - // Ignore protocal, remove search and query - return anchor.host + anchor.pathname; - } - - function isRelativePath(href) { - if (href === undefined || href === '' || href[0] === '/') { - return false; - } - return !isAbsolutePath(href); - } - - function isAbsolutePath(href) { - return (/^(?:[a-z]+:)?\/\//i).test(href); - } - - function getDirectory(href) { - if (!href) return ''; - var index = href.lastIndexOf('/'); - if (index == -1) return ''; - if (index > -1) { - return href.substr(0, index); - } - } - - function formList(item, classes) { - var level = 1; - var model = { - items: item - }; - var cls = [].concat(classes).join(" "); - return getList(model, cls); - - function getList(model, cls) { - if (!model || !model.items) return null; - var l = model.items.length; - if (l === 0) return null; - var html = '
    '; - level++; - for (var i = 0; i < l; i++) { - var item = model.items[i]; - var href = item.href; - var name = item.name; - if (!name) continue; - html += href ? '
  • ' + name + '' : '
  • ' + name; - html += getList(item, cls) || ''; - html += '
  • '; - } - html += '
'; - return html; - } - } - - /** - * Add into long word. - * @param {String} text - The word to break. It should be in plain text without HTML tags. - */ - function breakPlainText(text) { - if (!text) return text; - return text.replace(/([a-z])([A-Z])|(\.)(\w)/g, '$1$3$2$4') - } - - /** - * Add into long word. The jQuery element should contain no html tags. - * If the jQuery element contains tags, this function will not change the element. - */ - $.fn.breakWord = function () { - if (this.html() == this.text()) { - this.html(function (index, text) { - return breakPlainText(text); - }) - } - return this; - } - } - - // adjusted from https://stackoverflow.com/a/13067009/1523776 - function workAroundFixedHeaderForAnchors() { - var HISTORY_SUPPORT = !!(history && history.pushState); - var ANCHOR_REGEX = /^#[^ ]+$/; - - function getFixedOffset() { - return $('header').first().height(); - } - - /** - * If the provided href is an anchor which resolves to an element on the - * page, scroll to it. - * @param {String} href - * @return {Boolean} - Was the href an anchor. - */ - function scrollIfAnchor(href, pushToHistory) { - var match, rect, anchorOffset; - - if (!ANCHOR_REGEX.test(href)) { - return false; - } - - match = document.getElementById(href.slice(1)); - - if (match) { - rect = match.getBoundingClientRect(); - anchorOffset = window.pageYOffset + rect.top - getFixedOffset(); - window.scrollTo(window.pageXOffset, anchorOffset); - - // Add the state to history as-per normal anchor links - if (HISTORY_SUPPORT && pushToHistory) { - history.pushState({}, document.title, location.pathname + href); - } - } - - return !!match; - } - - /** - * Attempt to scroll to the current location's hash. - */ - function scrollToCurrent() { - scrollIfAnchor(window.location.hash); - } - - /** - * If the click event's target was an anchor, fix the scroll position. - */ - function delegateAnchors(e) { - var elem = e.target; - - if (scrollIfAnchor(elem.getAttribute('href'), true)) { - e.preventDefault(); - } - } - - $(window).on('hashchange', scrollToCurrent); - - $(window).on('load', function () { - // scroll to the anchor if present, offset by the header - scrollToCurrent(); - }); - - $(document).ready(function () { - // Exclude tabbed content case - $('a:not([data-tab])').click(function (e) { delegateAnchors(e); }); - }); - } - - // Hide the contribution panel on home page, by-tool, by-product pages - if (window.location.pathname === '/' || window.location.pathname === '/index.html' || window.location.pathname === '/by-tool.html' - || window.location.pathname === '/by-product.html' || window.location.pathname === '/compact-view.html' || - window.location.pathname === '/script-samples/' || window.location.pathname === '/script-samples/index.html' || window.location.pathname === '/script-samples/by-tool.html' - || window.location.pathname === '/script-samples/by-product.html' || window.location.pathname === '/script-samples/compact-view.html') { - $('.contribution-panel').hide(); - } - - // Note: THis will be redundant in newer versions of docfx, check and remove if not needed - // Add Clipboard Icon - var clipboardHtmlTemplate = ''; - - // Find all section[id^='tabpanel'] elements and add clipboard icon to them - $('section[id^="tabpanel"]').each(function() { - var targetElement = $(this).attr('data-tab'); - var targetId = "section[id^='tabpanel'][data-tab='" + targetElement + "'] pre"; - var clipboardScriptInstanceHtml = clipboardHtmlTemplate.replace(/{{targetElement}}/g, targetId); - $(this).prepend(clipboardScriptInstanceHtml); - }); - - - }); \ No newline at end of file diff --git a/docfx/templates/material/styles/extra.css b/docfx/templates/material/styles/extra.css deleted file mode 100644 index 251a8a4ee..000000000 --- a/docfx/templates/material/styles/extra.css +++ /dev/null @@ -1,1185 +0,0 @@ -@media screen and (max-width: 44.9375em) { - .md-footer__link--prev { - width: 25%; - } -} - -@media screen and (min-width: 45em) { - .md-footer__link { - width: 50%; - } -} - -@keyframes fadeIn { - 0% { - opacity:0; - } - 100% { - opacity:1; - } - } - - @-moz-keyframes fadeIn { - 0% { - opacity:0; - } - 100% { - opacity:1; - } - } - - @-webkit-keyframes fadeIn { - 0% { - opacity:0; - } - 100% { - opacity:1; - } - } - - @-o-keyframes fadeIn { - 0% { - opacity:0; - } - 100% { - opacity:1; - } - } - - @-ms-keyframes fadeIn { - 0% { - opacity:0; - } - 100% { - opacity:1; - } -} - -#noresults { - color:#797673; - animation: fadeIn ease 3s; - -webkit-animation: fadeIn ease 3s; - -moz-animation: fadeIn ease 3s; - -o-animation: fadeIn ease 3s; - -ms-animation: fadeIn ease 3s; -} - -.md-footer-nav__link--prev, .md-footer__link--prev { - float: left; -} - -.md-footer-nav__link--next, .md-footer__link--next { - float: right; - text-align: right; -} - -.md-footer__link { - display: flex; - padding-top: 1.4rem; - padding-bottom: .4rem; - transition: opacity 250ms; -} - -.md-footer__link:focus, .md-footer__link:hover { - opacity: .7; -} - -.md-footer__button { - margin: .2rem; - padding: .4rem; -} - -.md-footer__title { - position: relative; - flex-grow: 1; - max-width: calc(100% - 2.4rem); - padding: 0 1rem; - font-size: .9rem; - line-height: 2.4rem; -} - -.md-footer__direction { - position: absolute; - right: 0; - left: 0; - margin-top: -1rem; - padding: 0 1rem; - font-size: .64rem; - opacity: .7; -} - -.md-content { - background-color: #faf9f8; -} - -/* .md-sidebar--primary, .md-sidebar--primary .md-sidebar__scrollwrap { - background-color: #fff; -} */ - - -.md-main__inner { - margin-top: 0px; -} - -.md-main__inner.md-grid { - background: linear-gradient(90deg, #fff 50%, #faf9f8 50%); -} - -.md-content__inner { - font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif; - -webkit-font-smoothing: antialiased; - font-size: 16px; - font-weight: 400; - margin-bottom: 4px; -} - -.md-content__inner p, .md-content__inner pre, .md-content__inner iframe { - margin-top: 0; - margin-bottom: 1.2em; -} - -.md-content__inner p { - display: block; - margin-block-start: 1em; - margin-block-end: 1em; - margin-inline-start: 0px; - margin-inline-end: 0px; -} - -.md-content__inner a:link { - color: rgb(0, 120, 212); - font-weight: 600; -} - -.md-typeset h1 { - align-items: baseline; - color: rgb(50, 49, 48); - display: flex; - font-size: 32px; - font-weight: 600; - line-height: 1; - margin: 0px; -} - -.md-typeset p { - font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif; - -webkit-font-smoothing: antialiased; - font-size: 16px; - font-weight: 400; - margin-top: 0; - margin-bottom: 1.2em; -} - -.md-content section { - background: #fff; - padding: 28px; - margin-bottom: 28px; - border-radius: 2px; - background-clip: padding-box; - -webkit-box-shadow: 0 1.6px 3.6px 0 rgb(0 0 0 / 13%), 0 0.3px 0.9px 0 rgb(0 0 0 / 11%); - box-shadow: 0 1.6px 3.6px 0 rgb(0 0 0 / 13%), 0 0.3px 0.9px 0 rgb(0 0 0 / 11%); -} - -.content-header { - margin-bottom: 0px; - padding: 52px 0px; - min-height: 136px; -} - -h2.sub-heading { - font-size: 24px; - outline: 0; - text-align: left; - color: #323130; - font-weight: 600; - line-height: 1; - margin-top: 0; - margin-bottom: 0; -} - -.md-content h2 { - font-size: 24px; - outline: 0; - text-align: left; - color: #323130; - font-weight: 600; - line-height: 1; - margin: 32px 0px 8px; -} - -.md-content h3 { - font-size: 20px; - font-weight: 600; - padding: 0px; - /* margin: 32px 0px 8px; */ - margin: 0 0 0 0; - color: rgb(96, 94, 92); -} - -.md-logo { - width: 80px; -} - -.md-logo img { - width: 100% !important; - height: auto !important; - margin-top: -0.25em; -} - -.md-header-nav__topic { - margin-left: -16px; -} - -.md-nav__title { - font-size: 16px; - font-weight: 600; - padding: 0px 0px 0px 8px; - margin: 0px 0px 8px; - color: rgb(96, 94, 92); -} - -.md-nav--secondary .md-nav__title { - padding-top: 132px; -} - -ul.md-nav__list { - color: #323130; - font-size: 16px; - font-weight: 400; - margin-bottom: 8px; -} - -.md-nav__link { - margin-top: unset; -} - - -li.md-nav__item .md-nav__link:link { - font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif; - -webkit-font-smoothing: antialiased; - font-size: inherit; - font-weight: inherit; - color: rgb(50, 49, 48);; - outline: none; - text-decoration: none; - border-left: 2px solid transparent; - padding-left: 6px; -} - -li.md-nav__item { - display: block; - flex: 1 1 0%; - /* padding: 4px 8px; */ -} - -.md-nav--secondary li.md-nav__item .md-nav__link:link { - display: block; - flex: 1 1 0%; - padding: 4px 8px; -} - -.md-nav--secondary li.md-nav__item .md-nav__link:hover { - text-decoration: underline; -} - -.md-nav--secondary .md-nav__item { - padding: 0; -} - -.md-nav--secondary li.md-nav__item:hover { - background: rgb(237, 235, 233); -} - -.md-nav__icon::after { - display: none; -} - -@media screen and (min-width: 76.25em) { - .md-nav__icon { - float: left; - width: .9rem; - height: .9rem; - transition: transform 250ms; - } -} - -.md-nav__icon::before { - font-size: 16px; - color: #605e5c; - display: inline-block; - width: 100%; - height: 100%; - vertical-align: -0.1rem; - background-color: currentColor; - -webkit-mask-image: var(--md-nav-icon--next); - mask-image: var(--md-nav-icon--next); - -webkit-mask-repeat: no-repeat; - mask-repeat: no-repeat; - -webkit-mask-size: contain; - mask-size: contain; - content: ""; -} - - -li.md-nav__item .md-nav__link:active, li.md-nav__item .md-nav__link:hover -{ - text-decoration: underline; -} - -.md-nav__item .md-nav__item .md-nav__link:link, .md-nav__item .md-nav__item .md-nav__link:active, .md-nav__item .md-nav__item .md-nav__link:hover { - padding: 8px; - padding-left: 40px; - color: #323130; -} - -.md-nav__item .md-nav__item .md-nav__link:hover { - padding: 8px; - padding-left: 40px; - color: #323130; - background-color: #FAF9F8; -} - -label.md-nav__link, label.md-nav__link:hover { - color: #323130; - font-size: 14px; - font-weight: 600; - padding: 8px 0; -} - -li.md-nav__item .md-nav__link:active, li.md-nav__item .md-nav__link:hover { - text-decoration: none; -} - - -.md-nav__item .md-nav__item--active .md-nav__link--active { - background: #f3f2f1; - color: #323130; -} - -[data-md-color-primary=pnp] .md-header, [data-md-color-primary=pnp] .md-hero { - background-color: #0078d4; - box-shadow: 0 0 4px 2px rgb(0 0 0 / 20%); -} - -.md-tabs { - width: 100%; - -webkit-transition: background .25s; - transition: background .25s; - background-color: #0078d4; - color: #fff; - overflow: auto; -} - -/* Added for new filtering capability */ - -.filter-section { - margin: 0 0 0 0; - text-align: center; - padding: 45px 25px 0 0; - overflow: hidden; -} - -.filter-section .search-input-wrapper { - margin-top:25px; - margin-bottom: 20px; - margin-left: 20px; - - max-width: 320px; - min-width: 320px; -} - -.filter-section .icon-container { - display: flex; - flex-direction: column; - justify-content: center; - flex-shrink: 0; - font-size: 16px; - width: 32px; - text-align: center; - color: #0078d4; - cursor: text; - transition: width 0.167s ease 0s; - background: url(../assets/search-icon.svg) no-repeat left 8px center; - background-size: 16px 16px; -} - -.search-input-wrapper { - /* #0078D4 */ - font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif; - -webkit-font-smoothing: antialiased; - font-size: 14px; - font-weight: 400; - box-shadow: none; - margin: 0px; - padding: 1px 0px 1px 4px; - box-sizing: border-box; - color: rgb(50, 49, 48); - background-color: rgb(255, 255, 255); - display: flex; - flex-flow: row nowrap; - align-items: stretch; - border-radius: 2px; - border: 1px solid rgb(96, 94, 92); - height: 32px; - outline: 1px solid transparent; -} - -.search-input-wrapper:focus-within { - border: 1px solid #428e92; - outline: 1px solid #428e92; -} - -.search-input-wrapper:focus-within .icon-container { - width: 0px; -} - -.search-input-wrapper .search-input { - /* width: 100%; - padding: 10px 36px 10px 45px; - background: url(../img/search-icon.svg) no-repeat left 15px center; - border-bottom: 1px solid #EBEBF2; - transition: border 0.3s ease-in-out; */ - - box-shadow: none; - margin: 0px; - padding: 0px 0px 0.5px; - box-sizing: border-box; - background-color: transparent; - border: none; - outline: none; - font-weight: inherit; - font-family: inherit; - font-size: inherit; - color: rgb(50, 49, 48); - flex: 1 1 0px; - min-width: 0px; - overflow: hidden; - text-overflow: ellipsis; -} - -.primary-btn.dark { - border: 1px solid rgba(125, 122, 158, 0.5); - color: #7D7A9E; - background-color: #ffffff; -} - -.primary-btn { - display: inline-block; - max-width: 150px; - position: relative; - margin-left: 1%; -} - -.primary-btn { - border: 1px solid rgba(255, 255, 255, 0.5); - border-radius: 5px; - font-size: 14px; - padding: 11px 15px; - font-weight: bold; - width: 100%; - cursor: pointer; - transition: all 0.3s ease-in-out; - text-align: center; -} - -.float-l { - float: left; -} - -.float-r { - float: right; -} - -.tag-number { - color: #ffffff; - background-color: #0078d4; - font-size: 12px; - font-weight: bold; - border-radius: 25px; - position: absolute; - top: -11px; - right: -11px; - padding: 5px 9px; - box-shadow: 0 2px 8px 0 rgb(247 117 193 / 50%); - display: none; -} - -.sample-list { - display: inline-block; -} - -.producttype-item.active, .sampletype-item.active { - background-color: #428e92; - color: #ffffff; -} - -.producttype-item:hover, .sampletype-item:hover { - border: 1px solid #3b7d81; - background-color: #F7F7FC; - color: #34393e; -} - -.producttype-item, .sampletype-item { - min-width: 42px; - width: 42px; - height: 42px; - /* background-color: #f0feff; */ - border: 1px solid #f5f5f5; - border-radius: 25px; - transition: all 0.3s ease-in-out; - cursor: pointer; - display: inline-block; - vertical-align: middle; - text-align: center; - line-height: 42px; - font-size: 14px; - margin-left: 10px; - position: relative; -} - -.producttype-item:hover::after, .sampletype-item:hover::after { - opacity: 1; - bottom: 45px; -} - -.producttype-item::after, .sampletype-item::after { - content: attr(title); - background-color: #428e92; - color: #ffffff; - font-size: 14px; - border-radius: 2px; - box-shadow: rgb(0 0 0 / 13%) 0px 6.4px 14.4px 0px, rgb(0 0 0 / 11%) 0px 1.2px 3.6px 0px; - position: absolute; - bottom: 40px; - height: auto; - left: 50%; - transform: translateX(-50%); - padding: 0 15px; - opacity: 0; - transition: all 0.3s ease-in-out; - pointer-events: none; - white-space: nowrap; -} -/* -.sampletype-item::after { - content: attr(title); - background-color: #0078D4; - color: #ffffff; - font-size: 14px; - border-radius: 2px; - box-shadow: rgb(0 0 0 / 13%) 0px 6.4px 14.4px 0px, rgb(0 0 0 / 11%) 0px 1.2px 3.6px 0px; - position: absolute; - bottom: 40px; - height: auto; - left: 50%; - transform: translateX(-50%); - padding: 0 15px; - opacity: 0; - transition: all 0.3s ease-in-out; - pointer-events: none; - white-space: nowrap; -} */ - -.producttype-item, .sampletype-item { - background-size: 24px 24px; - background-repeat: no-repeat; - background-position: center; -} - -.tag-filter-panel { - right: -120%; - height: 110%; - width: 450px; - position: fixed; - top: 0; - background-color: #ffffff; - z-index: 10; - box-shadow: -8px 9px 25px 0 rgba(132, 128, 177, 0.28); - padding: 25px -} - -.tag-filter-panel.hidden { - right: -40% -} - -.tag-filter-panel .info-text-grey { - margin-top: 5px -} - -.tag-filter-panel .tag-filter-panel-header-text-wrapper { - width: calc(100% - 50px); - display: inline-block -} - -.tag-filter-panel .close-btn { - float: right; - display: inline-block -} - -.tag-filter-panel .selected-tags-counter { - clear: both; - width: 100%; - padding: 25px; - border-radius: 10px; - background: #F7F7FC; - margin-top: 30px -} - -.tag-filter-panel .selected-tags-counter.active .tag-counter-label-empty { - display: none; - font-size: 20px; - color: #7D7A9E -} - -.tag-filter-panel .selected-tags-counter.active .tag-counter-label { - display: inline-block -} - -.tag-filter-panel .selected-tags-counter.active .link-btn { - opacity: 1 -} - -.tag-filter-panel .tag-counter-label-empty { - font-size: 20px; - color: #7D7A9E; - display: inline-block; - width: calc(100% - 40px) -} - -.tag-filter-panel .tag-counter-label { - display: none; - font-size: 20px; - width: calc(100% - 40px) -} - -.tag-filter-panel .tag-counter-label span { - font-weight: bold -} - -.tag-filter-panel .link-btn { - float: right; - display: inline-block; - margin-top: 5px; - opacity: 0; - transition: opacity 0.3s ease-in-out -} - -.tag-filter-panel .tags-content-wrapper { - margin-top: 25px; - height: calc(100% - 300px); - width: 100%; - overflow-x: hidden -} - -.tag-filter-panel .tags-content { - margin-bottom: 15px -} - -.tag-filter-panel .grey { - margin-bottom: 5px; - text-transform: uppercase -} - -.tag-filter-panel .tag { - border-radius: 10px; - border: 1px solid #EBEBF2; - padding: 7px 10px; - display: inline-block; - margin-right: 10px; - margin-bottom: 10px; - color: #7D7A9E; - cursor: pointer; - background-color: #ffffff; - transition: all 0.3s ease-in-out -} - -.tag-filter-panel .tag:hover { - border: 1px solid #0078d4; - color: #0078D4 -} - -.tag-filter-panel .tag.active { - background-color: #0078d4; - border: 1px solid #0078d4; - color: #ffffff -} - -.tag-filter-panel .tag.active:hover { - background-color: #ea64a2 -} - -/* -TODO: Move styles -.samples-section { - clear: both; - padding: 15px 25px 50px; - max-width: 1450px; - height: auto; - margin: 0 auto 50px; - display: grid; - grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); - grid-auto-flow: row dense; - grid-gap: 25px; -} */ - -.sample-thumbnail { - /* transition: all 0.3s ease-in-out; */ - transition: background 0.4s, box-shadow 0.4s; - /* box-shadow: 0 20px 10px -15px rgb(197 192 249 / 20%); */ - /* background-color: rgba(255, 255, 255, 0.8); */ - text-align: center; - height: auto; - /* box-shadow: 0 0 4px 2px rgb(0 0 0 / 5%); */ - /* border-radius: 10px; */ - /* border: 1px solid rgb(237, 235, 233); */ - width: 33%; -} - -.sample-thumbnail:focus { - outline: none; -} - -.sample-thumbnail:focus .sample-inner { - outline: 1px solid #0078D4; -} - -.sample-inner { - transition: all 0.3s ease-in-out; - /* box-shadow: 0 20px 10px -15px rgb(197 192 249 / 20%); */ - background-color: rgba(255, 255, 255, 0.8); - text-align: center; - height: auto; - box-shadow: 0 0 4px 2px rgb(0 0 0 / 5%); - border-radius: 10px; - border: 1px solid rgb(237, 235, 233); - margin-left: 8px; - margin-right: 8px; - margin-bottom: 16px; - min-height: 325px; -} - - -.sample-thumbnail:hover .sample-inner { - box-shadow: 0 20px 20px -15px rgb(95 83 214 / 20%); - transform: scale(1.02); -} - -.sample-preview { - border-radius: 5px 5px 0 0; - height: 150px; - max-height: 150px; - background-color: #ededed; - width: 100%; - position: relative; - overflow: hidden; -} - -.sample-preview img { - - border-radius: 5px; - height: 100%; - width: 100%; - object-position: top; - object-fit: cover; - border: 0; - position: absolute; - top: -15px; - left: 65px; - -webkit-transform: rotate(-15deg); - -moz-transform: rotate(15deg); - -ms-transform: rotate(15deg); - -o-transform: rotate(15deg); - overflow: hidden; - box-shadow: 0px 0px 3px rgba(0,0,0,0.3); -} - -.sample-details { - background-color: #ffffff; - position: relative; - padding: 20px 12px; - border-radius: 0 0 5px 5px; - margin-top: -5px; - border-top: solid 1px #EDEBE9; -} - -.sample-title.sup { - width: 100%; -} - -.md-typeset p.sample-title { - font-size: 18px; - font-weight: 600; - margin-top: 10px; - margin-bottom: 5px; - color: #0078D4; - text-align: left; - white-space: nowrap; - text-overflow: ellipsis; - overflow: hidden; - /* width: calc(100% - 110px); */ -} - -.sample-date { - display: block; - font-size: 12px; - line-height: 15px; - height: 15px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - color: rgb(96, 94, 92); - text-align: left; -} - -.sample-author { - display: block; - font-size: 12px; - line-height: 15px; - height: 15px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - color: rgb(50, 49, 48); - font-weight: 600; - text-align: left; -} - -.activity-details { - padding-left: 8px; - display: table-cell; - vertical-align: middle; -} - -.activity-author-avatars { - display: table-cell; - vertical-align: middle; -} - -.author-image { - display: block; - opacity: 1; - width: 100%; - height: 100%; - object-fit: cover; - position: absolute; - left: 50%; - top: 50%; - transform: translate(-50%, -50%); -} - -.author-imagearea { - position: relative; - text-align: center; - flex: 0 0 auto; - height: 32px; - width: 32px; -} - -.image-400 { - font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif; - -webkit-font-smoothing: antialiased; - font-size: 14px; - font-weight: 400; - overflow: hidden; - animation-name: css-0; - animation-duration: 0.367s; - animation-timing-function: cubic-bezier(0.1, 0.25, 0.75, 0.9); - animation-fill-mode: both; - position: absolute; - margin-right: 10px; - top: 0px; - left: 0px; - width: 32px; - height: 32px; - border: 0px; - border-radius: 50%; - perspective: 1px; -} - -.sample-avatars { - margin-left: -2px; - height: 32px; -} - -.author-avatar { - display: inline-block; - vertical-align: top; - position: relative; - text-align: center; - width: 32px; - height: 32px; -} - -.author-avatar:nth-of-type(2), .author-avatar:nth-of-type(3), .author-avatar:nth-of-type(4), .author-avatar:nth-of-type(5) { - margin-left: -16px; -} - -.sample-activity { - padding-bottom: 12px; - padding-top: 0; - padding-right: 0; - padding-left: 0; - /* position: relative; */ - text-align: left; - display: table-row; - vertical-align: middle; -} - -.sample-description { - font-family: "Roboto", sans-serif, -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif; - -webkit-font-smoothing: antialiased; - font-size: 0.8em; - font-weight: 400; - /* padding: 8px 16px; - display: block; */ - text-overflow:ellipsis; - overflow:hidden; - display: -webkit-box !important; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; - white-space: normal; - /* height: 65px; - max-height: 65px; */ - line-height: 18px; - color: rgb(76, 74, 72); - text-align: left; -} - -.sample-details .producttype-item { - border: 1px solid #EBEBF2; - position: absolute; - left: 0; - top: -22px; - font-size: 0; -} - -.sample-details .producttype-item::after { - background-color: #0078D4; - color: #ffffff; - font-size: 14px; - border-radius: 5px; - box-shadow: 1px 14px 18px -15px #232e4c; - position: absolute; - bottom: 40px; - height: auto; - left: 50%; - transform: translateX(-50%); - padding: 0 15px; - opacity: 0; - transition: all 0.3s ease-in-out; -} - -.sample-details .producttype-item { - background-size: 24px 24px; - background-repeat: no-repeat; - background-position: center; -} - -.sample-details .producttype-item { - background-color: #fff; - background-size: 24px 24px; - background-repeat: no-repeat; - background-position: center; -} - -.sample-text{ - - height: 100px; - max-height: 100px; -} - -@media only screen and (max-width: 1175px) { - .sample-preview{ - height: 100px; - max-height: 100px; - } - .sample-text{ - - height: 150px; - max-height: 150px; - } -} - -@media only screen and (max-width: 1020px) { - .tag-filter-panel { - width: 35% - } - .tag-filter-panel.hidden { - right: -50% - } - - .sample-preview{ - height: 100px; - max-height: 100px; - } - - .sample-text{ - - height: 150px; - max-height: 150px; - } -} - -@media only screen and (max-width: 700px) { - .tag-filter-panel { - width: 100% - } - .tag-filter-panel.hidden { - right: -105% - } - .tag-filter-panel .tags-content-wrapper { - height: calc(100vh - 210px) - } - - .sample-preview{ - height: 100px; - max-height: 100px; - } - - .sample-text{ - - height: 120px; - max-height: 120px; - } - - .sample-inner{ - min-height: 300px; - } - -} - -/* ADDED FOR DIAGNOSIS */ - -/* clear fix */ - -.grid:after { - content: ''; - display: block; - clear: both; -} - -.producttype-item, .sampletype-item{ - width: fit-content; - padding: 0 10px; - height: 42px; -} - -.sample-details .producttype-item{ - width: 42px; - padding: 0 10px; - height: 42px; -} - -.filter-section{ - padding: 0; - box-shadow: 0 4px 2px rgb(0 0 0 / 5%); -} - -.filter-section .filter-list{ - margin: 20px 0; - margin-right: 20px; -} - -.well{ - /* background-color: inherit; */ - border: 0; - /* margin-bottom: 0; */ - padding: 0; - margin-top: 10px; - - --webkit-box-shadow: none; - box-shadow: none; - -} - -p.sample-title { - text-align: left; -} - -.filter-section { - overflow: unset; -} - -.compact-view .producttype-item { - right: 10px !important; - top: auto !important; - left: auto !important; -} - -.compact-view .producttype-item:nth-of-type(4) { - margin-right: 30px !important; - z-index: 20; -} - -.compact-view .producttype-item:nth-of-type(2), -.compact-view .producttype-item:not(:first-child){ - /* margin-right: 40px; */ - z-index: 40; -} - -.compact-view .sample-details{ - margin-top: 0; - border-left: 3px solid #0078D4; - border-radius: 5px; -} - -/* @media only screen and (max-width: 1020px) { - .compact-view .sample-details{ - padding: 5px 12px; - } -} */ - -.compact-view .content p{ - margin-bottom: 0.5rem; -} - -.compact-view .activity-details, -.compact-view .author-avatar{ - padding-top: 5px; -} - -/* Data driven backgrounds */ -.compact-view[data-products^="sharepoint"] .sample-details{ - border-left: 3px solid var(--sharepoint-product-color); - background: radial-gradient(circle at top left, color-mix(in srgb, var(--sharepoint-product-color) 10%, transparent) 0, white 65%) -} - -.compact-view[data-products^="teams"] .sample-details{ - border-left: 3px solid var(--teams-product-color); - background: radial-gradient(circle at top left, color-mix(in srgb, var(--teams-product-color) 10%, transparent) 0, white 65%) -} - -.compact-view[data-products^="graph"] .sample-details { - border-left: 3px solid var(--graph-product-color); - background: radial-gradient(circle at top left, color-mix(in srgb, var(--graph-product-color) 10%, transparent) 0, white 65%) -} - -.compact-view[data-products^="azure ad"] .sample-details, -.compact-view[data-products^="azuread"] .sample-details { - border-left: 3px solid var(--azuread-product-color); - background: radial-gradient(circle at top left, color-mix(in srgb, var(--azuread-product-color) 10%, transparent) 0, white 65%) -} - -.compact-view[data-products^="power automate"] .sample-details, -.compact-view[data-products^="powerautomate"] .sample-details { - border-left: 3px solid var(--powerautomate-product-color); - background: radial-gradient(circle at top left, color-mix(in srgb, var(--powerautomate-product-color) 10%, transparent) 0, white 65%) -} - -.compact-view[data-products^="office"] .sample-details { - border-left: 3px solid var(--office365-product-color); - background: radial-gradient(circle at top left, color-mix(in srgb, var(--office365-product-color) 10%, transparent) 0, white 65%) -} - -.compact-view[data-products^="microsoft todo"] .sample-details, -.compact-view[data-products^="microsoft to do"] .sample-details, -.compact-view[data-products^="todo"] .sample-details { - border-left: 3px solid var(--microsofttodo-product-color); - background: radial-gradient(circle at top left, color-mix(in srgb, var(--microsofttodo-product-color) 10%, transparent) 0, white 65%) -} - -.compact-view[data-products^="powerapps"] .sample-details, -.compact-view[data-products^="power apps"] .sample-details { - border-left: 3px solid var(--powerapps-product-color); - background: radial-gradient(circle at top left, color-mix(in srgb, var(--powerapps-product-color) 10%, transparent) 0, white 65%) -} \ No newline at end of file diff --git a/docfx/templates/material/styles/filter.css b/docfx/templates/material/styles/filter.css deleted file mode 100644 index f59147e4a..000000000 --- a/docfx/templates/material/styles/filter.css +++ /dev/null @@ -1,246 +0,0 @@ -* { - box-sizing: border-box; - } - - /* ---- button ---- */ - - .button { - display: inline-block; - padding: 10px 12px; - margin-bottom: 10px; - background: #EEE; - border: none; - /*border-radius: 7px; - background-image: linear-gradient( to bottom, hsla(0, 0%, 0%, 0), hsla(0, 0%, 0%, 0.2) );*/ - color: #222; - /*font-family: sans-serif;*/ - font-size: 14px; - /*text-shadow: 0 1px white;*/ - cursor: pointer; - transition: opacity 0.25s; - } - - .button:hover { - background-color: #2673ba; - color: white; - opacity:0.7; - } - - .button:active, - .button.is-checked { - background-color: #2673ba; - } - - .button.is-checked { - color: white; - } - - /* ---- button-group ---- */ - - .button-group:after { - content: ''; - display: block; - clear: both; - } - - .button-group .button { - float: left; - border-radius: 0; - margin-left: 2px; - margin-right: 2px; - - padding: 10px 12px; - border-radius: 7px; - } - - /*.button-group .button:first-child { - border-radius: 0.5em 0 0 0.5em; - } - - .button-group .button:last-child { - border-radius: 0 0.5em 0.5em 0; - }*/ - - /* ---- isotope ---- */ - - .grid { - /*border: 1px solid #333;*/ - } - - /* clear fix */ - .grid:after { - content: ''; - display: block; - clear: both; - } - - @media screen and (min-width: 768px) { - /* 5 columns for larger screens */ - .sample-thumbnail, - .grid-sizer { width: 33.333%; } - } - - @media screen and (max-width: 767px) { - /* 1 columns for small screens */ - .sample-thumbnail, - .grid-sizer { width: 100%; } - } - - - /* ---- .sample-item ---- */ - - .sample-item { - position: relative; - float: left; - width: 220px; - height: 280px; - margin-bottom: 30px; - margin-left: 15px; - margin-right: 15px; - margin-top: 0; - padding: 0; - background: #fff; - color: #262524; - /*border:1px solid rgb(50, 49, 48);*/ - box-shadow: rgba(0, 0, 0, 0.133) 0px 1.6px 3.6px 0px, rgba(0, 0, 0, 0.11) 0px 0.3px 0.9px 0px; - cursor: pointer; - border-radius: 2px; - border:1px solid #edebe9; - transition: box-shadow 0.5s ease 0s; - overflow: hidden; - } - - .sample-item:hover { - box-shadow: rgba(0, 0, 0, 0.133) 0px 3.2px 7.2px 0px, rgba(0, 0, 0, 0.11) 0px 0.6px 1.8px 0px; - } - - .sample-item>* { - margin: 0; - padding: 0; - } - - .sample-activity { - padding-bottom: 12px; - padding-top: 8px; - padding-right: 12px; - padding-left: 12px; - } - - .sample-item .author, - .sample-item .framework, - .sample-item .year, - .sample-item .modified, - .sample-item .drop, - .sample-item .status { - font-size: 12px; - color:#605e5c; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - display:block; - } - - .sample-item .location { - padding: 12px 12px 5px 12px; - overflow: hidden; - text-overflow: ellipsis; - color: #333333; - font-size: 12px; - } - - .sample-item .spfx img { - padding-top: 10px; - } - - .sample-item .author { - color:#323130; - font-size:12px; - font-weight: 600; - } - - .sample-item h2 { - /*max-height: 16px;*/ - margin: 0 0 0 0; - font-size: 14px; - font-weight: 400; - padding-top: 8px; - padding-right: 12px; - padding-bottom: 8px; - padding-left: 12px; - vertical-align: middle; - height: 38px; - line-height: 21px; - color: #323130; - width: 220px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } - - .sample-item h2 a, - .sample-item h2 a:link, - .sample-item h2 a:visited { - color: #333; - - } - - .sample-img { - min-height: 148px; - max-height: 148px; - overflow-y: hidden; - background-color: #FAF9F8; - border-bottom: 1px solid #edebe9;; - } - - #samplestable .sample-img { - min-height: unset; - max-height: unset; - - } - - .sample-video { - display: none; - position: absolute; - top:0px; - right:5px; - width: 24px; - height: 24px; - float: right; - text-shadow: 1px 1px #ffffff99; - color:#8a8886; - } - - .form-control { - display: block; - width: 100%; - padding: .375rem .75rem; - line-height: 1.5; - color: #495057; - background-color: #fff; - background-clip: padding-box; - border: 1px solid #ced4da; - border-radius: .25rem; - transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out; - } - - .ui-autocomplete { - cursor:pointer; - height:120px; - overflow-y:scroll; - } - - #samplestable th { - cursor: pointer; - } - - - .sample-item[data-thumbnail$='.gif'] .sample-video { - display: block; - } - - .sample:hover .sample-video { - display: none; - } - - - html { overflow-y: scroll; } diff --git a/docfx/templates/material/styles/filtersamples.js b/docfx/templates/material/styles/filtersamples.js deleted file mode 100644 index 723be5651..000000000 --- a/docfx/templates/material/styles/filtersamples.js +++ /dev/null @@ -1,170 +0,0 @@ -document.addEventListener('DOMContentLoaded', function () { - var sampleListing = document.getElementById('sample-listing'); - if (!sampleListing) return; - - var filterText = sampleListing.getAttribute('data-filter'); - var qsRegex; - var buttonFilter; - var viewMode = sampleListing.getAttribute('data-view') || 'grid'; // Default view mode - - // Check if Isotope is available - if (typeof Isotope === 'undefined') { - console.error('Isotope library is not loaded'); - return; - } - - // init Isotope - var grid = new Isotope('#sample-listing', { - itemSelector: '.sample-thumbnail', - layoutMode: 'fitRows', - sortBy: 'modified', - sortAscending: false, - getSortData: { - modified: '[data-modified]', - title: '.sample-title' - }, - filter: function (itemElem) { - // Isotope's filter function context: In jQuery mode, `this` refers to the element. - // In vanilla JS, the element may be passed as a parameter. Check if itemElem is a DOM node, - // otherwise fall back to `this` context for Isotope compatibility. - var element = itemElem.nodeType ? itemElem : this; - var keywords = element.getAttribute('data-keywords'); - var searchResult = qsRegex ? keywords.match(qsRegex) : true; - var buttonResult = buttonFilter ? element.matches(buttonFilter) : true; - return searchResult && buttonResult; - }, - fitRows: { - columnWidth: '.grid-sizer' - } - }); - - // Display/hide a message when there are no results - grid.on('arrangeComplete', function (filteredItems) { - var noResults = document.getElementById('noresults'); - if (noResults) { - if (filteredItems.length > 0) { - noResults.style.display = 'none'; - } else { - noResults.style.display = 'block'; - } - } - }); - - // Get the JSON - fetch(jsonPath) - .then(response => response.json()) - .then(data => { - var asc = true; - var prop = "updateDateTime"; - - // Sort data descending order - data = data.sort(function (a, b) { - try { - if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0); - else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0); - } catch (error) { - return 0; - } - }); - - data.forEach(function (sample) { - var item = loadSample(sample, filterText, viewMode); - if (item !== null) { - var tempDiv = document.createElement('div'); - tempDiv.innerHTML = item; - var element = tempDiv.firstElementChild; - sampleListing.appendChild(element); - grid.appended(element); - } - }); - - // Update the sort - grid.updateSortData(); - grid.arrange(); - }) - .catch(error => console.error('Error loading samples:', error)); - - // Get the list of filters to use - var filterChoices = document.querySelectorAll('#filters .filter-choice'); - - // Get the search box - var searchInput = document.getElementById('post-search-input'); - - var filterLists = document.querySelectorAll('.filter-list'); - filterLists.forEach(function (buttonGroup) { - buttonGroup.addEventListener('click', function (event) { - var target = event.target; - if (target.classList.contains('filter-choice')) { - var activeInGroup = buttonGroup.querySelector('.active'); - if (activeInGroup) { - activeInGroup.classList.remove('active'); - } - target.classList.add('active'); - - var filters = []; - var activeFilters = document.querySelectorAll('#filters .filter-choice.active'); - activeFilters.forEach(function (filter) { - filters.push(filter.getAttribute('data-filter')); - }); - - filters = filters.join(''); - buttonFilter = filters; - grid.arrange(); - } - }); - }); - - if (searchInput) { - // Create a single function for search handling - function handleSearch() { - qsRegex = new RegExp(searchInput.value, 'gi'); - grid.arrange(); - - // Update the URL - var url = window.location.href; - var urlParts = url.split("?"); - var searchVal = searchInput.value; - var newUrl = urlParts[0]; - - if (searchVal.length > 0) { - newUrl = urlParts[0] + "?query=" + searchVal; - } - - window.history.pushState({}, "", newUrl); - } - - // Attach the handler to all relevant events - searchInput.addEventListener('input', debounce(handleSearch, 200)); - searchInput.addEventListener('keyup', debounce(handleSearch, 200)); - searchInput.addEventListener('paste', debounce(handleSearch, 200)); - } - - // debounce so filtering doesn't happen every millisecond - function debounce(fn, threshold) { - var timeout; - return function debounced() { - if (timeout) { - clearTimeout(timeout); - } - function delayed() { - fn(); - timeout = null; - } - timeout = setTimeout(delayed, threshold || 100); - }; - } - - // See if there are any passed parameters - try { - grid.once('arrangeComplete', function () { - var urlParams = new URLSearchParams(window.location.search); - var query = urlParams.get('query'); - if (query !== "" && query !== null && searchInput) { - searchInput.value = query; - searchInput.dispatchEvent(new Event('input')); - } - }); - } catch (error) { - // Be vewy vewy quiet - } -}); \ No newline at end of file diff --git a/docfx/templates/material/styles/isotope.pkgd.min.js b/docfx/templates/material/styles/isotope.pkgd.min.js deleted file mode 100644 index 7ca671cbe..000000000 --- a/docfx/templates/material/styles/isotope.pkgd.min.js +++ /dev/null @@ -1,12 +0,0 @@ -/*! - * Isotope PACKAGED v3.0.6 - * - * Licensed GPLv3 for open source use - * or Isotope Commercial License for commercial use - * - * https://isotope.metafizzy.co - * Copyright 2010-2018 Metafizzy - */ - -!function(t,e){"function"==typeof define&&define.amd?define("jquery-bridget/jquery-bridget",["jquery"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("jquery")):t.jQueryBridget=e(t,t.jQuery)}(window,function(t,e){"use strict";function i(i,s,a){function u(t,e,o){var n,s="$()."+i+'("'+e+'")';return t.each(function(t,u){var h=a.data(u,i);if(!h)return void r(i+" not initialized. Cannot call methods, i.e. "+s);var d=h[e];if(!d||"_"==e.charAt(0))return void r(s+" is not a valid method");var l=d.apply(h,o);n=void 0===n?l:n}),void 0!==n?n:t}function h(t,e){t.each(function(t,o){var n=a.data(o,i);n?(n.option(e),n._init()):(n=new s(o,e),a.data(o,i,n))})}a=a||e||t.jQuery,a&&(s.prototype.option||(s.prototype.option=function(t){a.isPlainObject(t)&&(this.options=a.extend(!0,this.options,t))}),a.fn[i]=function(t){if("string"==typeof t){var e=n.call(arguments,1);return u(this,t,e)}return h(this,t),this},o(a))}function o(t){!t||t&&t.bridget||(t.bridget=i)}var n=Array.prototype.slice,s=t.console,r="undefined"==typeof s?function(){}:function(t){s.error(t)};return o(e||t.jQuery),i}),function(t,e){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",e):"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,function(){function t(){}var e=t.prototype;return e.on=function(t,e){if(t&&e){var i=this._events=this._events||{},o=i[t]=i[t]||[];return o.indexOf(e)==-1&&o.push(e),this}},e.once=function(t,e){if(t&&e){this.on(t,e);var i=this._onceEvents=this._onceEvents||{},o=i[t]=i[t]||{};return o[e]=!0,this}},e.off=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var o=i.indexOf(e);return o!=-1&&i.splice(o,1),this}},e.emitEvent=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){i=i.slice(0),e=e||[];for(var o=this._onceEvents&&this._onceEvents[t],n=0;n
`; + }; + renderer.heading = function ({ tokens: inlineTokens, depth }) { + const text = this.parser.parseInline(inlineTokens); + const baseId = text.replace(/<[^>]+>/g, "").toLowerCase().replace(/&[^;]+;/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-|-$/g, "") || "section"; + const count = headingIds.get(baseId) ?? 0; + headingIds.set(baseId, count + 1); + const level = Math.max(depth, 2); + return `${text}`; + }; + renderer.blockquote = function (token) { + const alert = /^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*/i.exec(token.text); + const div = /^\s*\[!div\b[^\]]*\]\s*/i.exec(token.text); + if (!alert && !div) return `
${this.parser.parse(token.tokens)}
`; + const type = alert?.[1].toLowerCase() ?? "note"; + const content = token.text.replace(/^\s*\[!(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION|div\b[^\]]*)\]\s*/gim, ""); + return ``; + }; + const options = { renderer, gfm: true }; + const output = []; + const panes = []; + let active; + let groupIndex = 0; + let scriptTabCount = 0; + const render = (items) => marked.parser(items, options); + function flush() { + if (!panes.length) return; + const prefix = `tools-${groupIndex++}`; + const used = new Set(); + for (const pane of panes) { + if (used.has(pane.id)) throw new Error(`${source}: duplicate tool tab #tab/${pane.id}`); + used.add(pane.id); + } + output.push(`
${panes.map((pane, index) => + ``).join("")}
${panes.map((pane, index) => + ``).join("")}
`); + scriptTabCount += panes.length; + panes.length = 0; + active = undefined; + } + let loose = []; + function flushLoose() { if (loose.length) { output.push(render(loose)); loose = []; } } + for (const token of tokens) { + const tab = token.type === "heading" ? /^\[([^\]]+)\]\(#tab\/([^)]+)\)$/.exec(token.text) : undefined; + if (tab) { + flushLoose(); + active = { title: tab[1], id: tab[2], tokens: [] }; + panes.push(active); + continue; + } + const sharedHeading = token.type === "heading" && (token.depth === 1 || /^(contributors?|authors?|source credit|references|disclaimer|acknowledg)/i.test(token.text)); + if (active && (token.type === "hr" || sharedHeading)) flush(); + if (active) active.tokens.push(token); + else loose.push(token); + } + flush(); + flushLoose(); + const html = sanitizeHtml(output.join("\n"), { + allowedTags: [...sanitizeHtml.defaults.allowedTags, "img", "button", "section", "aside", "details", "summary", "kbd", "del"], + allowedAttributes: { + "*": ["id", "class", "role", "aria-label", "aria-labelledby", "aria-controls", "aria-selected", "aria-hidden", "tabindex", "hidden"], + a: ["href", "title", "target", "rel"], + img: ["src", "alt", "title", "width", "height", "loading", "decoding"], + button: ["type", "data-copy-code", "data-tab-id"], + div: ["class", "data-tabs"], + pre: ["id", "class", "style", "tabindex", "aria-label"], + span: ["class", "style"], + code: ["class", "style"] + }, + allowedStyles: { + "*": { + color: [/^#[\da-f]{3,8}$/i, /^var\(--shiki-(light|dark)\)$/], + "--shiki-light": [/^#[\da-f]{3,8}$/i], + "--shiki-dark": [/^#[\da-f]{3,8}$/i], + "--shiki-light-bg": [/^#[\da-f]{3,8}$/i], + "--shiki-dark-bg": [/^#[\da-f]{3,8}$/i], + "font-style": [/^italic$/], + "font-weight": [/^bold$/], + "text-decoration": [/^underline$/] + } + }, + allowedSchemes: ["http", "https", "mailto"], + transformTags: { + a: (_tag, attributes) => ({ tagName: "a", attribs: { ...attributes, href: contentTarget(source, attributes.href ?? ""), ...(attributes.target === "_blank" ? { rel: "noopener noreferrer" } : {}) } }), + img: (_tag, attributes) => ({ tagName: "img", attribs: { ...attributes, src: contentTarget(source, attributes.src ?? "", true), alt: attributes.alt ?? "", loading: "lazy", decoding: "async" } }) + } + }); + return { html, scriptTabCount, codeBlockCount: codeIndex }; +} diff --git a/site/scripts/serve-test.mjs b/site/scripts/serve-test.mjs new file mode 100644 index 000000000..e19d9aa57 --- /dev/null +++ b/site/scripts/serve-test.mjs @@ -0,0 +1,46 @@ +import { createReadStream } from "node:fs"; +import { stat } from "node:fs/promises"; +import { createServer } from "node:http"; +import path from "node:path"; +import { BASE_PATH, SITE_ROOT } from "./config.mjs"; + +const dist = path.join(SITE_ROOT, "dist"); +const types = new Map([ + [".html", "text/html; charset=utf-8"], [".css", "text/css"], [".js", "text/javascript"], + [".json", "application/json"], [".png", "image/png"], [".jpg", "image/jpeg"], + [".jpeg", "image/jpeg"], [".gif", "image/gif"], [".webp", "image/webp"], + [".svg", "image/svg+xml"], [".woff2", "font/woff2"], [".xml", "application/xml"], + [".txt", "text/plain"], [".md", "text/plain"], [".ps1", "text/plain"] +]); +const server = createServer(async (request, response) => { + try { + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + const pathname = decodeURIComponent(url.pathname); + if (pathname !== BASE_PATH && !pathname.startsWith(`${BASE_PATH}/`)) { response.writeHead(404).end("Not found"); return; } + const file = path.resolve(dist, pathname.slice(BASE_PATH.length).replace(/^\//, "") || "index.html"); + if (!file.startsWith(`${dist}${path.sep}`)) { response.writeHead(400).end("Invalid path"); return; } + let target = file; + let status = 200; + try { + const details = await stat(target); + if (details.isDirectory()) { + if (!pathname.endsWith("/")) { response.writeHead(301, { Location: `${pathname}/${url.search}` }).end(); return; } + target = path.join(target, "index.html"); + } + await stat(target); + } catch (error) { + if (error.code !== "ENOENT") throw error; + target = path.join(dist, "404.html"); + status = 404; + } + response.writeHead(status, { "Content-Type": types.get(path.extname(target).toLowerCase()) ?? "application/octet-stream" }); + const stream = createReadStream(target); + stream.on("error", (error) => { console.error(error); response.destroy(error); }); + stream.pipe(response); + } catch (error) { + console.error("Test server request failed:", error); + response.writeHead(500).end("Request failed"); + } +}); +server.listen(4327, "127.0.0.1", () => console.log(`Gallery ready: http://127.0.0.1:4327${BASE_PATH}/`)); +for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => server.close()); diff --git a/site/scripts/source.mjs b/site/scripts/source.mjs new file mode 100644 index 000000000..fbed2f153 --- /dev/null +++ b/site/scripts/source.mjs @@ -0,0 +1,85 @@ +import { readFile, readdir, stat } from "node:fs/promises"; +import path from "node:path"; +import Ajv2020 from "ajv/dist/2020.js"; +import addFormats from "ajv-formats"; +import { marked } from "marked"; +import { REPOSITORY_ROOT, productIds, TRACKER_BASE } from "./config.mjs"; + +export async function readText(filename) { + const buffer = await readFile(filename); + const encoding = buffer[0] === 0xff && buffer[1] === 0xfe ? "utf-16le" + : buffer[0] === 0xfe && buffer[1] === 0xff ? "utf-16be" : "utf-8"; + return new TextDecoder(encoding, { fatal: true }).decode(buffer); +} + +export function validateTracker(slug, markdown) { + const expected = `${TRACKER_BASE}/scripts/${slug}`; + const line = markdown.trimEnd().split(/\r?\n/).at(-1)?.trim(); + const match = /^]*\bsrc=["']([^"']+)["'][^>]*\/?>$/.exec(line ?? ""); + if (match?.[1] !== expected) throw new Error(`scripts/${slug}/README.md: final line must be the tracking image with src="${expected}"`); + const count = (markdown.match(/m365-visitor-stats\.azurewebsites\.net/g) ?? []).length; + if (count !== 1) throw new Error(`scripts/${slug}/README.md: expected exactly one view tracker, found ${count}`); +} + +export async function localThumbnail(slug, url, root = REPOSITORY_ROOT) { + const parsed = new URL(url); + if (parsed.hostname !== "raw.githubusercontent.com") throw new Error(`${slug}: preview must use the repository's raw.githubusercontent.com URL`); + const prefix = `/pnp/script-samples/main/scripts/${slug}/`; + const decoded = decodeURIComponent(parsed.pathname); + if (!decoded.startsWith(prefix)) throw new Error(`${slug}: preview URL must refer to this sample, not another folder: ${url}`); + const relative = decoded.slice(prefix.length); + const directory = path.resolve(root, "scripts", slug); + const resolved = path.resolve(directory, relative); + if (!resolved.startsWith(`${directory}${path.sep}`)) throw new Error(`${slug}: unsafe preview path ${url}`); + let current = directory; + for (const segment of relative.split("/")) { + if (!(await readdir(current)).includes(segment)) throw new Error(`${slug}: preview filename or casing does not match the repository: ${relative}`); + current = path.join(current, segment); + } + if (!(await stat(resolved)).isFile()) throw new Error(`${slug}: preview is not a file: ${resolved}`); + return resolved; +} + +export async function loadSources({ root = REPOSITORY_ROOT, trackersOnly = false } = {}) { + const schema = JSON.parse(await readText(path.join(root, ".github", "schemas", "sample.schema.json"))); + const ajv = new Ajv2020({ allErrors: true }); + addFormats(ajv); + const validate = ajv.compile(schema); + const entries = (await readdir(path.join(root, "scripts"), { withFileTypes: true })) + .filter((entry) => entry.isDirectory() && !entry.name.startsWith("_")).sort((a, b) => a.name.localeCompare(b.name)); + const records = []; + const errors = []; + const identities = new Set(); + for (const entry of entries) { + const slug = entry.name; + const source = `scripts/${slug}/assets/sample.json`; + try { + const readme = await readText(path.join(root, "scripts", slug, "README.md")); + validateTracker(slug, readme); + if (trackersOnly) { records.push({ slug }); continue; } + const parsed = JSON.parse(await readText(path.join(root, ...source.split("/")))); + if (!validate(parsed)) throw new Error(`${source}: ${ajv.errorsText(validate.errors, { separator: "; " })}`); + const metadata = parsed[0]; + if (metadata.name !== slug) throw new Error(`${source}: name must match folder "${slug}"`); + if (identities.has(metadata.name.toLowerCase())) throw new Error(`${source}: duplicate sample identity`); + identities.add(metadata.name.toLowerCase()); + if (metadata.updateDateTime < metadata.creationDateTime) throw new Error(`${source}: updateDateTime must not precede creationDateTime`); + const expectedUrl = `https://pnp.github.io/script-samples/${slug}/README.html`; + if (metadata.url !== expectedUrl) throw new Error(`${source}: url must retain the legacy sample URL ${expectedUrl}`); + const products = productIds(metadata.products); + const authorIds = metadata.authors.map((author) => author.gitHubAccount.toLowerCase()); + if (new Set(authorIds).size !== authorIds.length) throw new Error(`${source}: duplicate author account`); + const keys = metadata.metadata.map((tool) => tool.key); + if (new Set(keys).size !== keys.length) throw new Error(`${source}: duplicate tool metadata key`); + const images = metadata.thumbnails.filter((thumbnail) => thumbnail.type === "image"); + for (const image of images) await localThumbnail(slug, image.url, root); + const prose = marked.lexer(readme).filter((token) => token.type !== "code").map((token) => token.raw).join(""); + if (/|Lorem ipsum|plugin:\s*add-to-gallery-preparation/.test(prose)) throw new Error(`scripts/${slug}/README.md: unfinished submission placeholder`); + records.push({ slug, metadata, readme, products }); + } catch (error) { + errors.push(`${source}: ${error.message}`); + } + } + if (errors.length) throw new Error(`Sample validation failed (${errors.length} files):\n${errors.join("\n")}`); + return records; +} diff --git a/site/scripts/validate-build.mjs b/site/scripts/validate-build.mjs new file mode 100644 index 000000000..41b6095d7 --- /dev/null +++ b/site/scripts/validate-build.mjs @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import { access, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { BASE_PATH, SITE_ORIGIN, SITE_ROOT, sitePath, trackerIdentity } from "./config.mjs"; + +const dist = path.join(SITE_ROOT, "dist"); +const routes = JSON.parse(await readFile(path.join(SITE_ROOT, "src", "generated", "routes.json"), "utf8")); +const views = ["", "contributors/", "reports/", "404.html", ...routes.guides, ...routes.samples.map((slug) => `samples/${slug}/`)]; +const files = new Map(); +async function htmlFile(relative) { + const file = path.join(dist, ...relative.split("/").filter(Boolean), ...(relative.endsWith(".html") ? [] : ["index.html"])); + if (!files.has(file)) files.set(file, await readFile(file, "utf8")); + return files.get(file); +} +const checked = new Set(); +const failures = []; +async function checkLink(source, href) { + if (!href || /^(data:|mailto:|tel:)/i.test(href)) return; + const url = new URL(href.replaceAll("&", "&"), `${SITE_ORIGIN}${sitePath(source)}`); + if (url.origin !== SITE_ORIGIN || !url.pathname.startsWith(`${BASE_PATH}/`)) return; + const identity = `${url.pathname}${url.hash}`; + if (checked.has(identity)) return; + checked.add(identity); + const relative = decodeURIComponent(url.pathname.slice(`${BASE_PATH}/`.length)); + const file = path.resolve(dist, ...relative.split("/").filter(Boolean), ...(url.pathname.endsWith("/") ? ["index.html"] : [])); + assert.ok(file.startsWith(`${dist}${path.sep}`), `Link escapes build directory: ${href}`); + try { await access(file); } + catch (error) { + if (error.code !== "ENOENT") throw error; + failures.push(`${source} -> missing ${url.pathname}`); + return; + } + if (url.hash && path.extname(file) === ".html") { + const html = await readFile(file, "utf8"); + if (!html.includes("data-legacy-redirect")) { + const fragment = decodeURIComponent(url.hash.slice(1)); + const escaped = fragment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const tab = fragment.replace(/^tab\//, ""); + if (!new RegExp(`\\bid=["']${escaped}["']`).test(html) && !html.includes(`data-tab-id="${tab}"`)) { + failures.push(`${source} -> missing fragment ${url.pathname}${url.hash}`); + } + } + } +} +for (const view of views) { + const html = await htmlFile(view); + const identity = trackerIdentity(view === "404.html" ? "404" : view); + const trackers = [...html.matchAll(/]*\bdata-visitor-stats\b[^>]*>/g)]; + assert.equal(trackers.length, 1, `${view}: expected one view tracker`); + assert.ok(trackers[0][0].includes(`data-tracker-src="${identity}"`), `${view}: wrong tracker identity`); + assert.ok(trackers[0][0].includes('src="data:image/gif;'), `${view}: local previews must not eagerly request production analytics`); + assert.equal((html.match(/]*(?:src|data-tracker-src)="https:\/\/m365-visitor-stats\.azurewebsites\.net\/[^>]*>/g) ?? []).length, 1, `${view}: duplicate tracker image from source Markdown`); + assert.match(html, /[^<]+<\/title>/); + assert.match(html, /<link rel="canonical" href="https:\/\/pnp\.github\.io\/script-samples\//); + assert.ok(!/\[!INCLUDE\s*\[/.test(html.replace(/<pre\b[\s\S]*?<\/pre>/g, "")), `${view}: unresolved shared include`); + for (const match of html.matchAll(/<(?:a|link|script|img)\b[^>]*?\b(?:href|src)="([^"]+)"[^>]*>/g)) await checkLink(view, match[1]); +} +for (const [legacy, target] of Object.entries(routes.redirects)) { + const html = await htmlFile(legacy); + assert.ok(html.includes("data-legacy-redirect"), `${legacy}: redirect missing`); + assert.ok(html.includes(`href="${target.replaceAll("&", "&")}"`), `${legacy}: wrong destination`); + assert.ok(!html.includes("data-visitor-stats"), `${legacy}: redirect must not double-count views`); + await checkLink(legacy, target); +} +for (const sample of routes.samples) await stat(path.join(dist, sample, "assets", "sample.json")); +const publicCatalog = JSON.parse(await readFile(path.join(dist, "catalog.json"), "utf8")); +assert.equal(publicCatalog.samples.length, routes.samples.length); +const legacyCatalog = JSON.parse(await readFile(path.join(dist, "samples.json"), "utf8")); +assert.equal(legacyCatalog.length, routes.samples.length); +for (const sample of legacyCatalog) { + assert.ok(sample.metadata.length && sample.authors[0].gitHubAccount, `${sample.name}: legacy catalog shape changed`); + assert.equal(sample.url, `${sample.name}/README.html`); +} +await access(path.join(dist, "sitemap-index.xml")); +await access(path.join(dist, "deployment.json")); +if (failures.length) throw new Error(`Built link validation failed (${failures.length}):\n${failures.join("\n")}`); +console.log(`[gallery] validated ${views.length} views, ${Object.keys(routes.redirects).length} redirects, ${checked.size} internal links/assets/fragments, catalog parity, canonical URLs, and exactly one tracker per view`); diff --git a/site/scripts/validate-samples.mjs b/site/scripts/validate-samples.mjs new file mode 100644 index 000000000..2efe204b0 --- /dev/null +++ b/site/scripts/validate-samples.mjs @@ -0,0 +1,5 @@ +import { loadSources } from "./source.mjs"; + +const trackersOnly = process.argv.includes("--trackers"); +const records = await loadSources({ trackersOnly }); +console.log(`[gallery] validated ${records.length} ${trackersOnly ? "README view trackers" : "sample records, assets, identities, dates, authors, taxonomy, and README trackers"}`); diff --git a/site/src/assets/fonts/pnp-pd-400.woff2 b/site/src/assets/fonts/pnp-pd-400.woff2 new file mode 100644 index 000000000..6f5a32375 Binary files /dev/null and b/site/src/assets/fonts/pnp-pd-400.woff2 differ diff --git a/site/src/assets/fonts/pnp-pd-600.woff2 b/site/src/assets/fonts/pnp-pd-600.woff2 new file mode 100644 index 000000000..e8179ac2a Binary files /dev/null and b/site/src/assets/fonts/pnp-pd-600.woff2 differ diff --git a/site/src/assets/fonts/pnp-pd-800.woff2 b/site/src/assets/fonts/pnp-pd-800.woff2 new file mode 100644 index 000000000..3ee5021cb Binary files /dev/null and b/site/src/assets/fonts/pnp-pd-800.woff2 differ diff --git a/site/src/components/ProductImage.astro b/site/src/components/ProductImage.astro new file mode 100644 index 000000000..fa5534dd1 --- /dev/null +++ b/site/src/components/ProductImage.astro @@ -0,0 +1,9 @@ +--- +import { sitePath } from "../lib/catalog"; +import type { Product } from "../lib/types"; +interface Props { product: Product; size?: number } +const { product, size = 34 } = Astro.props; +--- +{product.image + ? <img src={sitePath(`images/${product.image}`)} alt="" width={size} height={size} loading="lazy" decoding="async" /> + : <span class="product-monogram" aria-hidden="true">{product.monogram}</span>} diff --git a/site/src/components/Recognition.astro b/site/src/components/Recognition.astro new file mode 100644 index 000000000..5836feb1f --- /dev/null +++ b/site/src/components/Recognition.astro @@ -0,0 +1,14 @@ +--- +import { sitePath } from "../lib/catalog"; +--- +<aside class="recognition-band"> + <div> + <p class="eyebrow">Your contribution deserves recognition</p> + <h2>Share a sample. Earn your badge.</h2> + <p>The Script Samples contributor badge is for every sample contributor, including first-time contributors. After your first accepted sample, opt in to the community recognition program. Badges are issued in batches, not instantly.</p> + <a class="text-link" href="https://pnp.github.io/recognitionprogram/">Get your contributor badge <span aria-hidden="true">→</span></a> + </div> + <a href="https://pnp.github.io/recognitionprogram/" aria-label="Learn how to earn the Script Samples contributor badge"> + <img class="recognition-badge" src={sitePath("assets/credly-badge.png")} alt="Microsoft 365 and Power Platform Community Script Samples contributor badge" width="170" height="170" loading="lazy" decoding="async" /> + </a> +</aside> diff --git a/site/src/components/SampleCard.astro b/site/src/components/SampleCard.astro new file mode 100644 index 000000000..71791a78b --- /dev/null +++ b/site/src/components/SampleCard.astro @@ -0,0 +1,36 @@ +--- +import ProductImage from "./ProductImage.astro"; +import { formatDate, requireProduct, samplePath, sitePath } from "../lib/catalog"; +import type { Sample } from "../lib/types"; +interface Props { sample: Sample } +const { sample } = Astro.props; +const product = requireProduct(sample.products[0]); +const author = sample.authors[0]; +--- +<article class="sample-card" + data-sample-card data-slug={sample.slug} + data-search={sample.search} data-products={sample.products.join("|")} + data-tools={sample.tools.map((tool) => tool.id).join("|")} + data-categories={sample.categories.join("|")} + data-authors={sample.authors.map((candidate) => candidate.handle.toLowerCase()).join("|")} + data-title={sample.title} data-updated={sample.updated} data-created={sample.created}> + <a class="card-preview" href={samplePath(sample.slug)} tabindex="-1" aria-hidden="true"> + <ProductImage product={product} size={40} /><span>{product.label}</span><span class="preview-mark">>_</span> + </a> + <div class="card-body"> + <div class="card-meta"><span class="scenario-tag">{sample.categories[0]}</span><time class="card-date" datetime={sample.updated}>{formatDate(sample.updated)}</time></div> + <h3><a href={samplePath(sample.slug)}>{sample.title}</a></h3> + <p class="card-description">{sample.description}</p> + <div class="tool-tags"> + {sample.tools.slice(0, 2).map((tool) => <span class="tool-tag">{tool.label}</span>)} + {sample.tools.length > 2 && <span class="tool-tag" title={sample.tools.slice(2).map((tool) => tool.label).join(", ")}>+{sample.tools.length - 2} tools</span>} + </div> + </div> + <div class="card-footer"> + <a class="card-author" href={`${sitePath("")}?author=${encodeURIComponent(author.handle.toLowerCase())}`}> + <img class="avatar" src={author.pictureUrl} alt="" width="24" height="24" loading="lazy" decoding="async" data-avatar={author.name} /> + <span>{author.name}{sample.authors.length > 1 ? ` +${sample.authors.length - 1}` : ""}</span> + </a> + <a class="card-open" href={samplePath(sample.slug)} aria-label={`View script: ${sample.title}`}>View script <span aria-hidden="true">↗</span></a> + </div> +</article> diff --git a/site/src/layouts/Layout.astro b/site/src/layouts/Layout.astro new file mode 100644 index 000000000..5c776a007 --- /dev/null +++ b/site/src/layouts/Layout.astro @@ -0,0 +1,104 @@ +--- +import { ArrowUpRight, GitFork, Menu, Moon, Sun } from "@lucide/astro"; +import { basePath, sitePath, trackerUrl } from "../lib/catalog"; +import "../styles/global.css"; + +interface Props { title?: string; description?: string; route?: string; image?: string } +const { + title = "Community Script Samples", + description = "Real-world scripts for Copilot, Microsoft 365, Power Platform and more. Find a starting point, choose your tool, and make it your own.", + route = Astro.url.pathname.slice(basePath.length).replace(/^\/|\/$/g, ""), + image = sitePath("assets/gallery-preview.png") +} = Astro.props; +const pageTitle = title === "Community Script Samples" ? title : `${title} | Community Script Samples`; +const canonical = new URL(sitePath(route === "404" ? "404.html" : route ? `${route.replace(/\/$/, "")}/` : ""), Astro.site); +const nav = [ + { title: "Samples", path: "" }, + { title: "Getting started", path: "getting-started/" }, + { title: "Contributors", path: "contributors/" }, + { title: "Contributing", path: "contributing/" } +]; +const current = (value: string) => value ? route.startsWith(value.replace(/\/$/, "")) : !route || route.startsWith("samples/"); +const trackingEnabled = import.meta.env.PUBLIC_ENABLE_VIEW_TRACKING === "true"; +const structuredData = { "@context": "https://schema.org", "@type": "WebSite", name: "Community Script Samples", url: new URL(sitePath(""), Astro.site).href, description }; +--- +<!doctype html> +<html lang="en" data-theme="light"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <meta name="description" content={description} /> + <meta name="generator" content={Astro.generator} /> + <meta name="theme-color" id="theme-color" content="#f2f4f5" /> + <title>{pageTitle} + + + + + + + + + + + +
+ +

+ + + + diff --git a/site/src/lib/catalog.ts b/site/src/lib/catalog.ts new file mode 100644 index 000000000..07b3fbd20 --- /dev/null +++ b/site/src/lib/catalog.ts @@ -0,0 +1,18 @@ +import catalogData from "../generated/catalog.json"; +import type { Catalog } from "./types"; +import { BASE_PATH } from "./routes"; +export { sitePath, trackerUrl } from "./routes"; +import { sitePath } from "./routes"; + +export const catalog: Catalog = catalogData; +export const basePath = BASE_PATH; +export const samplePath = (slug: string): string => sitePath(`samples/${encodeURIComponent(slug)}/`); +export const formatDate = (value: string): string => new Intl.DateTimeFormat("en-US", { + year: "numeric", month: "short", day: "numeric", timeZone: "UTC" +}).format(new Date(`${value}T00:00:00Z`)); +export const productById = new Map(catalog.products.map((product) => [product.id, product])); +export const requireProduct = (id: string) => { + const product = productById.get(id); + if (!product) throw new Error(`Unknown catalog product: ${id}`); + return product; +}; diff --git a/site/src/lib/routes.ts b/site/src/lib/routes.ts new file mode 100644 index 000000000..407f689e0 --- /dev/null +++ b/site/src/lib/routes.ts @@ -0,0 +1,11 @@ +export const BASE_PATH = "/script-samples"; +export const SITE_ORIGIN = "https://pnp.github.io"; +export const TRACKER_BASE = "https://m365-visitor-stats.azurewebsites.net/script-samples"; +export const sitePath = (value = ""): string => `${BASE_PATH}/${value.replace(/^\/+/, "")}`; +export function trackerUrl(route: string): string { + const clean = route.replace(/^\/+|\/+$/g, ""); + if (!clean) return TRACKER_BASE; + if (clean.startsWith("samples/")) return `${TRACKER_BASE}/scripts/${clean.slice("samples/".length)}`; + if (clean === "contributing/how-can-i-contribute") return `${TRACKER_BASE}/how-can-i-contribute`; + return `${TRACKER_BASE}/${clean}`; +} diff --git a/site/src/lib/types.ts b/site/src/lib/types.ts new file mode 100644 index 000000000..6816f5dd9 --- /dev/null +++ b/site/src/lib/types.ts @@ -0,0 +1,65 @@ +export interface Product { + id: string; + label: string; + image: string; + monogram: string; + featured: boolean; + count: number; +} + +export interface Author { + handle: string; + name: string; + pictureUrl: string; +} + +export interface Contributor extends Author { + count: number; +} + +export interface Tool { + id: string; + label: string; + version: string; +} + +export interface Sample { + slug: string; + title: string; + description: string; + products: string[]; + categories: string[]; + tags: string[]; + tools: Tool[]; + created: string; + updated: string; + authors: Author[]; + references: { name: string; description: string; url: string }[]; + sourceUrl: string; + url: string; + legacyUrl: string; + previews: { src: string; alt: string }[]; + commandReferences: { name: string; url: string }[]; + search: string; + readmeHtml: string; + scriptTabCount: number; + codeBlockCount: number; +} + +export interface Guide { + source: string; + route: string; + title: string; + html: string; +} + +export interface Catalog { + version: number; + samples: Sample[]; + products: Product[]; + tools: { id: string; label: string; count: number }[]; + categories: string[]; + contributors: Contributor[]; + guides: Guide[]; + redirects: Record; +} diff --git a/site/src/pages/404.astro b/site/src/pages/404.astro new file mode 100644 index 000000000..7647f6048 --- /dev/null +++ b/site/src/pages/404.astro @@ -0,0 +1,11 @@ +--- +import Layout from "../layouts/Layout.astro"; +import { sitePath } from "../lib/catalog"; +--- + +
+

404 / A fresh starting point

That page isn't here.

The sample may have moved, or the link may be incomplete. Search the gallery to find the script you need.

+ Explore script samples → + Report a broken link +
+
diff --git a/site/src/pages/[...guide].astro b/site/src/pages/[...guide].astro new file mode 100644 index 000000000..b7dddf2fc --- /dev/null +++ b/site/src/pages/[...guide].astro @@ -0,0 +1,27 @@ +--- +import Layout from "../layouts/Layout.astro"; +import Recognition from "../components/Recognition.astro"; +import { catalog, sitePath } from "../lib/catalog"; +import type { Guide } from "../lib/types"; +export function getStaticPaths() { + return catalog.guides.map((guide) => ({ params: { guide: guide.route.replace(/\/$/, "") }, props: { guide } })); +} +interface Props { guide: Guide } +const { guide } = Astro.props; +const navigation = catalog.guides.filter((item) => item.route.startsWith("contributing/")); +const contributionGuide = guide.route.startsWith("contributing/"); +--- + +
+

{contributionGuide ? "Built together" : "From discovery to your first run"}

{guide.title}

+ {guide.route === "contributing/" && } +
+
+ +
+
+
diff --git a/site/src/pages/contributors.astro b/site/src/pages/contributors.astro new file mode 100644 index 000000000..70c81dacb --- /dev/null +++ b/site/src/pages/contributors.astro @@ -0,0 +1,61 @@ +--- +import Layout from "../layouts/Layout.astro"; +import Recognition from "../components/Recognition.astro"; +import { catalog, sitePath } from "../lib/catalog"; +--- + +
+

The people behind the scripts

Sharing is caring.

{catalog.contributors.length} community members. Hundreds of real-world starting points. Meet the people making everyday work a little easier for everyone.

+ +

Meet our contributors

Become a contributor →
+ +

{catalog.contributors.length} contributors

+
+ {catalog.contributors.map((author) => )} +
+ +
+
+ diff --git a/site/src/pages/deployment.json.ts b/site/src/pages/deployment.json.ts new file mode 100644 index 000000000..bf0c5d6a4 --- /dev/null +++ b/site/src/pages/deployment.json.ts @@ -0,0 +1,8 @@ +import { catalog } from "../lib/catalog"; +export function GET() { + return new Response(JSON.stringify({ + commit: import.meta.env.PUBLIC_COMMIT_SHA || "local", + sampleCount: catalog.samples.length, + contributorCount: catalog.contributors.length + }), { headers: { "Content-Type": "application/json" } }); +} diff --git a/site/src/pages/index.astro b/site/src/pages/index.astro new file mode 100644 index 000000000..009b8c70f --- /dev/null +++ b/site/src/pages/index.astro @@ -0,0 +1,74 @@ +--- +import { ArrowRight, CalendarDays, Grid2x2, List, Search } from "@lucide/astro"; +import Layout from "../layouts/Layout.astro"; +import SampleCard from "../components/SampleCard.astro"; +import ProductImage from "../components/ProductImage.astro"; +import { catalog, sitePath } from "../lib/catalog"; +const featured = catalog.products.filter((product) => product.featured); +const otherProducts = catalog.products.filter((product) => !product.featured); +--- + +
+
+

Microsoft 365 & Power Platform Community

+

Script Samples

+

A little script. A lot less work.

+

Real-world scripts for Copilot, Microsoft 365, Power Platform and more.
Find a starting point, choose your tool, and make it your own.

+
{catalog.samples.length} samples{catalog.contributors.length} contributorsOpen source. Community built.
+
+
+ + + Parker, the community porcupine + Small scripts. Big possibilities. +
+
+ +
+
+

The script library

What will you automate today?

+ New to scripts? Start here +
+
+
+ + {featured.map((product) => )} +
+ More products +
{otherProducts.map((product) => )}
+
+
+ +
+ +
+
+

Explore all {catalog.samples.length} community samples

+
+ + +
+
+
+ +
{catalog.samples.map((sample) => )}
+ +
+ +
+
+ diff --git a/site/src/pages/reports.astro b/site/src/pages/reports.astro new file mode 100644 index 000000000..332400d50 --- /dev/null +++ b/site/src/pages/reports.astro @@ -0,0 +1,25 @@ +--- +import Layout from "../layouts/Layout.astro"; +import { catalog, formatDate, samplePath } from "../lib/catalog"; +const commands = new Map(); +for (const sample of catalog.samples) for (const tag of sample.tags) commands.set(tag, (commands.get(tag) ?? 0) + 1); +const popular = [...commands].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); +const samplesByAge = [...catalog.samples].sort((a, b) => a.updated.localeCompare(b.updated) || a.title.localeCompare(b.title)); +--- + +
+

Keeping the gallery useful

Catalog reports

Build-time reports from the same validated catalog as the gallery. Dates describe content updates, not independent verification of a script.

+ +
+

Distribution by tool

+
{catalog.tools.map((tool) => )}
ToolSamples
{tool.label}{tool.count}
+

Catalog metadata

+

{catalog.samples.length} sample folders, {catalog.contributors.length} contributor accounts, {catalog.products.length} product groups. Every published record passes schema, identity, taxonomy, asset, date, and README-tracker checks. No samples are silently excluded.

+

Raw source values and tool versions come from authors. Product aliases are normalized for discovery; source metadata remains available in each sample.

+

Commands and topics

+
{popular.map(([command, count]) => )}
Command or topicSamples
{command}{count}
+

Content update dates

+
{samplesByAge.map((sample) => )}
SampleUpdated
{sample.title}
+
+
+
diff --git a/site/src/pages/robots.txt.ts b/site/src/pages/robots.txt.ts new file mode 100644 index 000000000..e45c30d29 --- /dev/null +++ b/site/src/pages/robots.txt.ts @@ -0,0 +1,3 @@ +export function GET() { + return new Response("User-agent: *\nAllow: /\nSitemap: https://pnp.github.io/script-samples/sitemap-index.xml\n", { headers: { "Content-Type": "text/plain" } }); +} diff --git a/site/src/pages/samples/[slug].astro b/site/src/pages/samples/[slug].astro new file mode 100644 index 000000000..cf1c71ef4 --- /dev/null +++ b/site/src/pages/samples/[slug].astro @@ -0,0 +1,67 @@ +--- +import { ArrowRight, ArrowUpRight } from "@lucide/astro"; +import Layout from "../../layouts/Layout.astro"; +import ProductImage from "../../components/ProductImage.astro"; +import { catalog, formatDate, requireProduct, samplePath, sitePath } from "../../lib/catalog"; +import type { Sample } from "../../lib/types"; +export function getStaticPaths() { + return catalog.samples.map((sample) => ({ params: { slug: sample.slug }, props: { sample } })); +} +interface Props { sample: Sample } +const { sample } = Astro.props; +const related = catalog.samples.filter((candidate) => candidate.slug !== sample.slug && candidate.products.some((product) => sample.products.includes(product))) + .sort((a, b) => Number(b.categories.some((category) => sample.categories.includes(category))) - Number(a.categories.some((category) => sample.categories.includes(category)))) + .slice(0, 3); +const tagsWithReferences = new Map(sample.commandReferences.map((reference) => [reference.name, reference.url])); +--- + +
+ +
+ {sample.categories.join(" / ")} +

{sample.title}

{sample.description}

+ +
+
+
+ +
+ {sample.references.length > 0 &&

Tool documentation & references

    {sample.references.map((reference) =>
  • {reference.name}{reference.description &&

    {reference.description}

    }
  • )}
} +

Keep exploring

+
+ +
+
+
+ diff --git a/site/src/scripts/catalog.ts b/site/src/scripts/catalog.ts new file mode 100644 index 000000000..ebe13b93c --- /dev/null +++ b/site/src/scripts/catalog.ts @@ -0,0 +1,186 @@ +export {}; + +type FilterKey = "q" | "product" | "tool" | "category" | "author"; +type Sort = "updated" | "newest" | "name"; +type Layout = "grid" | "list"; +interface State { q: string; product: string; tool: string; category: string; author: string; sort: Sort; layout: Layout; limit: number } +interface Card { element: HTMLElement; slug: string; search: string; products: string[]; tools: string[]; categories: string[]; authors: string[]; title: string; updated: string; created: string } +function required(selector: string): T { + const element = document.querySelector(selector); + if (!element) throw new Error(`Catalog control is missing: ${selector}`); + return element; +} +function data(element: HTMLElement, key: string): string { + const value = element.dataset[key]; + if (value === undefined) throw new Error(`Catalog card is missing data-${key}`); + return value; +} +const cards: Card[] = [...document.querySelectorAll("[data-sample-card]")].map((element) => ({ + element, slug: data(element, "slug"), search: data(element, "search"), + products: data(element, "products").split("|"), tools: data(element, "tools").split("|"), + categories: data(element, "categories").split("|"), authors: data(element, "authors").split("|"), + title: data(element, "title"), updated: data(element, "updated"), created: data(element, "created") +})); +const grid = required("#sample-grid"); +const form = required("#catalog-filters"); +const search = required("#sample-search"); +const tool = required("#tool-filter"); +const category = required("#category-filter"); +const author = required("#author-filter"); +const sort = required("#sort-samples"); +const count = required("#result-count"); +const empty = required("#empty-state"); +const loadMore = required("#load-more"); +const productGroup = required("#product-filters"); +const more = required(".more-products"); +const advanced = required("#advanced-filters"); +const active = required("#active-filters"); +const notice = required("#filter-notice"); +const productButtons = [...productGroup.querySelectorAll("[data-product]")]; +const productNames = new Map(productButtons.map((button) => [data(button, "product"), data(button, "productLabel")])); +const state: State = { q: "", product: "", tool: "", category: "", author: "", sort: "updated", layout: "grid", limit: 12 }; +const contextKey = "community-script-samples-gallery"; +const media = matchMedia("(max-width: 700px)"); +advanced.open = !media.matches; +media.addEventListener("change", () => { advanced.open = !media.matches; }); + +function selected(select: HTMLSelectElement, value: string): boolean { + return [...select.options].some((option) => option.value === value); +} +function readQuery() { + const query = new URLSearchParams(location.search); + const invalid: string[] = []; + state.q = query.get("q") ?? query.get("query") ?? ""; + const requestedProduct = query.get("product") ?? ""; + state.product = productNames.has(requestedProduct) ? requestedProduct : ""; + if (requestedProduct && !state.product) invalid.push("product"); + for (const [key, select] of [["tool", tool], ["category", category], ["author", author]] as const) { + const requested = query.get(key) ?? ""; + state[key] = selected(select, requested) ? requested : ""; + if (requested && !state[key]) invalid.push(key); + } + const requestedSort = query.get("sort"); + state.sort = requestedSort === "newest" || requestedSort === "name" ? requestedSort : "updated"; + const requestedLayout = query.get("layout"); + state.layout = requestedLayout === "list" ? "list" : "grid"; + const requestedLimit = Number(query.get("limit") ?? 12); + state.limit = Number.isInteger(requestedLimit) && requestedLimit >= 12 ? Math.min(requestedLimit, cards.length) : 12; + notice.hidden = !invalid.length; + notice.textContent = invalid.length ? `Some shared filters were not recognized (${invalid.join(", ")}). Those filters were cleared.` : ""; + if (state.tool || state.category || state.author || query.get("browse") === "tools") advanced.open = true; +} +function updateUrl() { + const query = new URLSearchParams(); + for (const key of ["q", "product", "tool", "category", "author"] as const) if (state[key]) query.set(key, state[key]); + if (state.sort !== "updated") query.set("sort", state.sort); + if (state.layout !== "grid") query.set("layout", state.layout); + if (state.limit > 12) query.set("limit", String(state.limit)); + history.replaceState(null, "", `${location.pathname}${query.size ? `?${query}` : ""}${location.hash}`); +} +function baseMatch(card: Card): boolean { + return state.q.trim().toLowerCase().split(/\s+/).filter(Boolean).every((term) => card.search.includes(term)) && + (!state.tool || card.tools.includes(state.tool)) && + (!state.category || card.categories.includes(state.category)) && + (!state.author || card.authors.includes(state.author)); +} +function chip(key: FilterKey, label: string) { + const button = document.createElement("button"); + button.type = "button"; + button.className = "filter-chip"; + button.textContent = `${label} \u00d7`; + button.setAttribute("aria-label", `Remove filter: ${label}`); + button.addEventListener("click", () => { state[key] = ""; apply(true); search.focus(); }); + return button; +} +function apply(reset = false) { + if (reset) state.limit = 12; + const baseMatches = cards.filter(baseMatch); + const matches = baseMatches.filter((card) => !state.product || card.products.includes(state.product)); + matches.sort((a, b) => state.sort === "name" ? a.title.localeCompare(b.title) + : (state.sort === "newest" ? b.created.localeCompare(a.created) : b.updated.localeCompare(a.updated)) || a.title.localeCompare(b.title)); + cards.forEach((card) => { card.element.hidden = true; }); + matches.forEach((card, index) => { card.element.hidden = index >= state.limit; grid.append(card.element); }); + grid.classList.toggle("is-list", state.layout === "list"); + grid.dataset.ready = "true"; + search.value = state.q; + tool.value = state.tool; + category.value = state.category; + author.value = state.author; + sort.value = state.sort; + count.textContent = matches.length === cards.length ? `Explore all ${cards.length} community samples` : `${matches.length} matching ${matches.length === 1 ? "sample" : "samples"} of ${cards.length}`; + empty.hidden = matches.length > 0; + loadMore.hidden = matches.length <= state.limit; + required("#page-count").textContent = matches.length ? `Showing ${Math.min(state.limit, matches.length)} of ${matches.length} samples` : ""; + productButtons.forEach((button) => { + const id = button.dataset.product ?? ""; + button.setAttribute("aria-pressed", String(id === state.product)); + const total = id ? baseMatches.filter((card) => card.products.includes(id)).length : baseMatches.length; + const label = productNames.get(id) || "All samples"; + button.setAttribute("aria-label", `${label}: ${total} matching samples`); + const span = button.querySelector("[data-product-count]"); + if (span) span.textContent = button.classList.contains("product-button") ? `${total} ${id ? "samples" : "scripts to explore"}` : String(total); + }); + const featured = productButtons.some((button) => button.parentElement === productGroup && button.dataset.product === state.product); + required("#more-product-label").textContent = state.product && !featured ? productNames.get(state.product) ?? "More products" : "More products"; + document.querySelectorAll("[data-layout]").forEach((button) => button.setAttribute("aria-pressed", String(button.dataset.layout === state.layout))); + active.replaceChildren(); + const labels: [FilterKey, string][] = [ + ["q", state.q ? `"${state.q}"` : ""], ["product", productNames.get(state.product) ?? ""], + ["tool", state.tool ? tool.selectedOptions[0].textContent?.replace(/\s+\(\d+\)$/, "") ?? state.tool : ""], + ["category", state.category], ["author", state.author ? author.selectedOptions[0].textContent ?? state.author : ""] + ]; + for (const [key, label] of labels) if (state[key] && label) active.append(chip(key, label)); + const advancedCount = [state.tool, state.category, state.author].filter(Boolean).length; + required("#advanced-filter-label").textContent = advancedCount ? `More filters (${advancedCount})` : "More filters"; + updateUrl(); +} +form.addEventListener("submit", (event) => event.preventDefault()); +search.addEventListener("input", () => { state.q = search.value; apply(true); }); +tool.addEventListener("change", () => { state.tool = tool.value; apply(true); }); +category.addEventListener("change", () => { state.category = category.value; apply(true); }); +author.addEventListener("change", () => { state.author = author.value; apply(true); }); +sort.addEventListener("change", () => { state.sort = sort.value === "newest" || sort.value === "name" ? sort.value : "updated"; apply(); }); +productButtons.forEach((button) => button.addEventListener("click", () => { state.product = button.dataset.product ?? ""; more.open = false; apply(true); })); +document.querySelectorAll("[data-layout]").forEach((button) => button.addEventListener("click", () => { state.layout = button.dataset.layout === "list" ? "list" : "grid"; apply(); })); +function clear() { + Object.assign(state, { q: "", product: "", tool: "", category: "", author: "", sort: "updated", limit: 12 }); + notice.hidden = true; + apply(); + search.focus(); +} +required("#clear-filters").addEventListener("click", clear); +required("#empty-clear").addEventListener("click", clear); +loadMore.addEventListener("click", () => { + const visible = cards.filter((card) => !card.element.hidden).length; + state.limit += 12; + apply(); + [...grid.querySelectorAll("[data-sample-card]")].filter((card) => !card.hidden)[visible]?.querySelector("h3 a")?.focus({ preventScroll: true }); +}); +document.addEventListener("keydown", (event) => { + if (event.key === "/" && !event.ctrlKey && !event.metaKey && !event.altKey && !(document.activeElement instanceof HTMLInputElement) && !(document.activeElement instanceof HTMLTextAreaElement) && !(document.activeElement instanceof HTMLSelectElement)) { + event.preventDefault(); search.focus(); + } +}); +function saveContext() { + try { sessionStorage.setItem(contextKey, JSON.stringify({ url: location.href, scroll: scrollY })); } + catch (error) { console.warn("The gallery scroll position could not be saved.", error); } +} +function restoreContext() { + try { + const stored = sessionStorage.getItem(contextKey); + if (!stored) return; + const parsed: unknown = JSON.parse(stored); + if (typeof parsed === "object" && parsed !== null && "url" in parsed && parsed.url === location.href && "scroll" in parsed && typeof parsed.scroll === "number") { + const position = parsed.scroll; + requestAnimationFrame(() => { window.scrollTo({ top: position, behavior: "instant" }); }); + } + } catch (error) { console.warn("The saved gallery context could not be restored.", error); } +} +history.scrollRestoration = "manual"; +grid.addEventListener("click", (event) => { if (event.target instanceof Element && event.target.closest("a")) saveContext(); }); +window.addEventListener("pagehide", saveContext); +window.addEventListener("pageshow", (event) => { if (event.persisted) restoreContext(); }); +window.addEventListener("popstate", () => { readQuery(); apply(); restoreContext(); }); +readQuery(); +apply(); +restoreContext(); diff --git a/site/src/scripts/site.ts b/site/src/scripts/site.ts new file mode 100644 index 000000000..2ea77d374 --- /dev/null +++ b/site/src/scripts/site.ts @@ -0,0 +1,112 @@ +export {}; + +const root = document.documentElement; +const toggle = document.querySelector("#theme-toggle"); +const status = document.querySelector("#site-status"); +const meta = document.querySelector("#theme-color"); + +function applyTheme(theme: "light" | "dark", persist: boolean) { + root.dataset.theme = theme; + root.style.colorScheme = theme; + const dark = theme === "dark"; + if (toggle) { + toggle.setAttribute("aria-checked", String(dark)); + toggle.setAttribute("aria-label", `Switch to ${dark ? "light" : "dark"} mode`); + toggle.title = toggle.getAttribute("aria-label") ?? ""; + } + if (meta) meta.content = dark ? "#0c131b" : "#f2f4f5"; + if (persist) { + try { localStorage.setItem("community-script-samples-theme", theme); } + catch (error) { + console.warn("Theme changed but the preference could not be saved.", error); + if (status) status.textContent = "Theme changed. This browser could not save your preference."; + } + } +} +applyTheme(root.dataset.theme === "dark" ? "dark" : "light", false); +toggle?.addEventListener("click", () => applyTheme(root.dataset.theme === "dark" ? "light" : "dark", true)); + +document.querySelectorAll("[data-avatar]").forEach((image) => { + image.addEventListener("error", () => { + const name = image.dataset.avatar ?? "Contributor"; + const fallback = document.createElement("span"); + fallback.className = "avatar avatar-fallback"; + fallback.style.width = `${image.width}px`; + fallback.style.height = `${image.height}px`; + fallback.textContent = name.split(/\s+/).slice(0, 2).map((part) => part[0]).join(""); + fallback.setAttribute("aria-label", `Profile image unavailable for ${name}`); + console.warn(`GitHub profile image unavailable for ${name}`); + image.replaceWith(fallback); + }, { once: true }); +}); + +document.querySelectorAll("[data-tabs]").forEach((group) => { + const buttons = [...group.querySelectorAll('[role="tab"]')]; + const panels = [...group.querySelectorAll('[role="tabpanel"]')]; + function activate(index: number, focus = false, updateHash = false) { + buttons.forEach((button, current) => { + const selected = index === current; + button.setAttribute("aria-selected", String(selected)); + button.tabIndex = selected ? 0 : -1; + if (selected && focus) button.focus(); + }); + panels.forEach((panel, current) => { panel.hidden = index !== current; }); + if (updateHash) { + const url = new URL(location.href); + url.hash = `tab/${buttons[index].dataset.tabId}`; + history.replaceState(null, "", url); + } + } + buttons.forEach((button, index) => { + button.addEventListener("click", () => activate(index, false, true)); + button.addEventListener("keydown", (event) => { + let next: number | undefined; + if (event.key === "ArrowRight") next = (index + 1) % buttons.length; + if (event.key === "ArrowLeft") next = (index - 1 + buttons.length) % buttons.length; + if (event.key === "Home") next = 0; + if (event.key === "End") next = buttons.length - 1; + if (next !== undefined) { event.preventDefault(); activate(next, true, true); } + }); + }); + function activateHash() { + const requested = location.hash.replace(/^#(?:tab\/)?/, ""); + const index = buttons.findIndex((button) => button.dataset.tabId === requested); + if (index >= 0) activate(index); + } + activateHash(); + window.addEventListener("hashchange", activateHash); +}); + +document.querySelectorAll("[data-copy-code]").forEach((button) => { + button.addEventListener("click", async () => { + const pre = document.getElementById(button.dataset.copyCode ?? ""); + const code = pre?.querySelector("code"); + if (!code) throw new Error(`Copy target is missing: ${button.dataset.copyCode}`); + try { + await navigator.clipboard.writeText(code.textContent ?? ""); + button.textContent = "Copied"; + if (status) status.textContent = "Complete code block copied to the clipboard."; + } catch (error) { + console.error("Could not copy the code block.", error); + const range = document.createRange(); + range.selectNodeContents(code); + const selection = window.getSelection(); + selection?.removeAllRanges(); + selection?.addRange(range); + pre?.focus(); + button.textContent = "Code selected"; + if (status) status.textContent = "Clipboard unavailable. The code is selected; use your browser's copy command."; + } + }); +}); + +const tracker = document.querySelector("[data-visitor-stats]"); +if (tracker?.dataset.trackingEnabled === "true" && location.hostname === "pnp.github.io" && location.pathname.startsWith("/script-samples/")) { + const source = tracker.dataset.trackerSrc; + if (!source) throw new Error("Page view tracker identity is missing."); + tracker.src = source; +} + +document.querySelectorAll(".mobile-nav").forEach((menu) => { + menu.querySelectorAll("a").forEach((link) => link.addEventListener("click", () => { menu.open = false; })); +}); diff --git a/site/src/styles/global.css b/site/src/styles/global.css new file mode 100644 index 000000000..cfc6769de --- /dev/null +++ b/site/src/styles/global.css @@ -0,0 +1,479 @@ +@font-face { font-family: Parker; src: url("../assets/fonts/pnp-pd-400.woff2") format("woff2"); font-weight: 400; font-display: swap; } +@font-face { font-family: Parker; src: url("../assets/fonts/pnp-pd-600.woff2") format("woff2"); font-weight: 600; font-display: swap; } +@font-face { font-family: Parker; src: url("../assets/fonts/pnp-pd-800.woff2") format("woff2"); font-weight: 800; font-display: swap; } +:root { + --ink: #171d22; --muted: #59656d; --brand-blue: #0078d4; --accent: #0067b8; --accent-hover: #005a9e; + --canvas: #f2f4f5; --surface: #fff; --soft: #f7f9fa; --border: #d7dfe2; + --selected: #e8f2fc; --selected-border: #98bcde; --header: rgba(255,255,255,.95); + --grid: rgba(0,120,212,.035); --shadow: 0 5px 20px rgba(20,40,47,.045); + --ribbon: #e9f1f8; --ribbon-border: #d0deec; --link: #095d9c; + --toggle-track: #dce7f5; --toggle-thumb: #fff; --focus: #086bcc; --code: #101c27; + --warm: #fff4e3; --warm-ink: #855104; --warm-border: #e9d3a9; + --footer: #20262c; --footer-ink: #e6eaed; --hero-halo: #d7e9f9; + color-scheme: light; color: var(--ink); background: var(--canvas); + font-family: Parker, Aptos, "Segoe UI", sans-serif; font-synthesis: none; +} +html[data-theme="dark"] { + --ink: #f0f5f8; --muted: #a9bac5; --brand-blue: #70b5ff; --accent: #8bc6ff; --accent-hover: #b7dcff; + --canvas: #0c131b; --surface: #141f2a; --soft: #101a24; --border: #2a3c4b; + --selected: #172f48; --selected-border: #416d97; --header: rgba(12,19,27,.95); + --grid: rgba(112,181,255,.045); --shadow: 0 8px 26px rgba(0,0,0,.2); + --ribbon: #122539; --ribbon-border: #2b425b; --link: #8cc9ff; + --toggle-track: #172b44; --toggle-thumb: #82bfff; --focus: #9acfff; --code: #080f17; + --warm: #302719; --warm-ink: #f2cc88; --warm-border: #695333; + --footer: #080e14; --footer-ink: #d9e3eb; --hero-halo: #15334e; + color-scheme: dark; +} +* { box-sizing: border-box; } +body { margin: 0; min-height: 100vh; background: linear-gradient(90deg,var(--grid) 1px,transparent 1px),linear-gradient(var(--grid) 1px,transparent 1px),var(--canvas); background-size: 48px 48px; font-size: 15px; line-height: 1.55; } +button,input,select { font: inherit; } +button,select { cursor: pointer; } +a { color: var(--link); text-underline-offset: 3px; } +a:hover { color: var(--accent); } +button { color: inherit; } +img { max-width: 100%; } +svg { flex-shrink: 0; } +h1,h2,h3,p { margin-top: 0; } +[hidden] { display: none !important; } +:focus-visible { outline: 3px solid var(--focus); outline-offset: 4px; } +.container { width: min(1360px,calc(100% - 48px)); margin-inline: auto; } +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; } +.skip-link { position: fixed; top: 8px; left: 8px; z-index: 100; padding: 12px; background: var(--surface); transform: translateY(-160%); } +.skip-link:focus { transform: none; } +.site-header { position: sticky; top: 0; z-index: 50; background: var(--header); border-bottom: 1px solid var(--border); backdrop-filter: blur(14px); box-shadow: var(--shadow); } +.spectrum { height: 4px; background: linear-gradient(90deg,#075fce 0 32%,#138a3d 32% 55%,#b32687 55% 78%,#d84f38 78%); } +.header-inner { min-height: 66px; display: flex; align-items: center; justify-content: space-between; gap: 20px; } +.brand { display: inline-flex; gap: 10px; align-items: center; text-decoration: none; color: var(--brand-blue); font-size: 20px; white-space: nowrap; } +.brand img { width: 35px; height: 45px; object-fit: contain; } +.brand strong { color: var(--brand-blue); font-weight: 800; } +.header-actions,.desktop-nav { display: flex; align-items: center; gap: 3px; } +.header-actions { gap: 12px; } +.desktop-nav a { display: inline-flex; align-items: center; gap: 7px; padding: 10px; border-radius: 5px; font-size: 14px; font-weight: 600; text-decoration: none; color: var(--ink); } +.desktop-nav a:hover,.desktop-nav a[aria-current="page"] { color: var(--accent); background: var(--selected); } +.theme-toggle { position: relative; width: 68px; height: 36px; border: 1px solid var(--border); border-radius: 99px; padding: 3px; background: var(--toggle-track); isolation: isolate; box-shadow: inset 0 1px 3px #0002; } +.theme-toggle::before { content: ""; position: absolute; top: 3px; left: 3px; width: 28px; height: 28px; border-radius: 50%; z-index: -1; background: var(--toggle-thumb); box-shadow: 0 2px 6px #0003; transition: transform 220ms; } +.theme-icons { display: grid; grid-template-columns: 28px 28px; gap: 4px; } +.theme-icons svg { width: 17px; height: 17px; margin: auto; color: #5d6878; } +.theme-icons svg:first-child { color: #8a5700; } +html[data-theme="dark"] .theme-toggle::before { transform: translateX(32px); } +html[data-theme="dark"] .theme-icons svg:first-child { color: #a7b4c5; } +html[data-theme="dark"] .theme-icons svg:last-child { color: #071525; } +.mobile-nav { display: none; position: relative; } +.mobile-nav summary { display: grid; place-items: center; width: 40px; height: 40px; border: 1px solid var(--border); border-radius: 5px; list-style: none; cursor: pointer; } +.mobile-nav summary::-webkit-details-marker { display: none; } +.mobile-nav nav { position: absolute; top: 48px; right: 0; width: 235px; padding: 8px; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; box-shadow: var(--shadow); } +.mobile-nav a { display: block; padding: 10px 12px; text-decoration: none; color: var(--ink); } +.hero { min-height: 292px; display: flex; align-items: center; justify-content: space-between; gap: 28px; padding-block: 34px 30px; } +.eyebrow { margin-bottom: 8px; color: var(--accent); font-size: 12px; font-weight: 800; text-transform: uppercase; letter-spacing: .045em; } +.hero h1 { font-size: clamp(42px,4.4vw,60px); line-height: 1.1; font-weight: 800; letter-spacing: -.025em; margin-bottom: 8px; } +.hero-descriptor { color: var(--accent); font-size: 22px; font-weight: 600; margin-bottom: 12px; } +.hero-description { font-size: 17px; color: var(--muted); line-height: 1.6; margin-bottom: 20px; } +.hero-meta { display: flex; gap: 22px; align-items: center; color: var(--muted); font-size: 13px; } +.hero-meta strong { color: var(--ink); font-weight: 800; } +.hero-meta > span + span { position: relative; } +.hero-meta > span + span::before { content: ""; position: absolute; left: -12px; top: 5px; height: 12px; border-left: 1px solid var(--border); } +.parker-scene { position: relative; display: flex; align-items: center; justify-content: center; width: 310px; height: 238px; flex-shrink: 0; } +.parker-scene::before { content: ""; position: absolute; width: 214px; height: 214px; border-radius: 50%; background: radial-gradient(circle,var(--hero-halo),transparent 72%); } +.parker-scene > img { position: relative; height: 218px; width: 170px; object-fit: contain; z-index: 1; } +.scene-orbit { position: absolute; width: 224px; height: 224px; border: 1px solid var(--selected-border); border-radius: 50%; opacity: .5; } +.orbit-two { width: 268px; height: 170px; transform: rotate(-24deg); border-style: dashed; opacity: .45; } +.scene-token { position: absolute; z-index: 2; display: grid; place-items: center; width: 46px; height: 42px; border: 1px solid var(--border); border-radius: 9px; background: var(--surface); font-family: Consolas,monospace; color: var(--accent); font-size: 20px; box-shadow: var(--shadow); transform: rotate(-10deg); } +.token-one { top: 38px; left: 16px; } +.token-two { right: 10px; bottom: 60px; transform: rotate(9deg); } +.scene-caption { position: absolute; bottom: -7px; font-size: 11px; color: var(--muted); } +.community-ribbon { background: var(--ribbon); border-block: 1px solid var(--ribbon-border); } +.ribbon-inner { display: flex; align-items: center; gap: 13px; min-height: 56px; padding-block: 12px; } +.ribbon-inner > svg { color: var(--link); } +.ribbon-inner p { margin: 0; font-size: 14px; } +.ribbon-inner a { margin-left: auto; font-size: 13px; font-weight: 600; white-space: nowrap; } +.ribbon-inner a span { margin-left: 10px; } +.catalog-section { padding-block: 32px 48px; } +.section-heading { display: flex; justify-content: space-between; align-items: end; gap: 16px; margin-bottom: 22px; } +.section-heading .eyebrow { margin-bottom: 4px; } +h2 { font-size: 28px; font-weight: 800; line-height: 1.25; letter-spacing: -.015em; margin-bottom: 0; } +.text-link { font-size: 13px; font-weight: 600; text-decoration: none; } +.text-link span { margin-left: 8px; } +.product-filters { display: grid; grid-template-columns: .9fr repeat(5,1.2fr) 1fr; gap: 9px; margin-bottom: 16px; } +.product-button { min-height: 68px; display: flex; align-items: center; justify-content: center; gap: 8px; background: var(--surface); border: 1px solid var(--border); border-radius: 7px; padding: 10px; color: var(--ink); font-size: 12px; font-weight: 600; box-shadow: var(--shadow); } +.product-button img { width: 34px; height: 34px; object-fit: contain; } +.product-button .product-number { display: block; font-size: 11px; color: var(--muted); font-weight: 400; text-align: left; } +.product-button[aria-pressed="true"] { border-color: var(--accent); background: var(--selected); box-shadow: inset 0 -2px var(--accent); } +.product-button:hover { border-color: var(--selected-border); } +.product-button .all-icon { font-family: Consolas,monospace; font-size: 25px; color: var(--accent); } +.more-products { position: relative; } +.more-products summary { height: 100%; list-style: none; cursor: pointer; } +.more-products summary::-webkit-details-marker { display: none; } +.more-product-options { position: absolute; top: calc(100% + 6px); right: 0; z-index: 5; width: 230px; padding: 6px; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; box-shadow: var(--shadow); } +.more-product-options button { width: 100%; min-height: 40px; display: flex; justify-content: space-between; gap: 10px; align-items: center; border: 0; background: transparent; padding: 8px 10px; border-radius: 5px; font-size: 13px; text-align: left; } +.more-product-options img { width: 23px; height: 23px; object-fit: contain; } +.more-product-options button > span:last-child { margin-left: auto; } +.more-product-options button:hover,.more-product-options button[aria-pressed="true"] { background: var(--selected); } +.catalog-toolbar { display: grid; grid-template-columns: minmax(240px,2.4fr) 1.25fr 1fr 1.15fr; align-items: center; gap: 10px; padding: 12px; background: var(--surface); border: 1px solid var(--border); border-radius: 7px; box-shadow: var(--shadow); } +input,select { min-width: 0; background: var(--surface); color: var(--ink); border: 1px solid var(--border); border-radius: 5px; padding: 10px 12px; font-size: 13px; min-height: 42px; } +select { width: 100%; } +.search-control { display: flex; align-items: center; gap: 10px; border: 1px solid var(--border); border-radius: 5px; padding-inline: 12px; } +.search-control svg { width: 18px; height: 18px; color: var(--muted); } +.search-control input { width: 100%; padding-inline: 0; border: 0; outline-offset: 0; } +.search-control kbd { border: 1px solid var(--border); border-radius: 4px; padding: 0 5px; color: var(--muted); font-size: 12px; } +.active-filters:empty { display: none; } +.active-filters { display: flex; flex-wrap: wrap; gap: 6px; padding-top: 12px; } +.filter-chip { display: inline-flex; gap: 10px; align-items: center; border-radius: 99px; background: var(--selected); border: 1px solid var(--selected-border); color: var(--accent); padding: 5px 12px; font-size: 12px; } +.results-bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-block: 18px 14px; } +.results-bar p { margin: 0; font-size: 13px; color: var(--muted); } +.results-actions { display: flex; align-items: center; gap: 16px; } +.results-actions select { border: 0; background: transparent; padding: 4px 20px 4px 4px; width: auto; min-height: 36px; font-size: 12px; } +.text-button { border: 0; background: transparent; color: var(--accent); padding: 4px 0; font-size: 12px; font-weight: 600; text-decoration: underline; text-underline-offset: 3px; } +.view-toggle { display: flex; padding: 3px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); } +.view-toggle button { width: 30px; height: 29px; padding: 5px; border: 0; border-radius: 4px; color: var(--muted); background: transparent; } +.view-toggle svg { width: 19px; height: 19px; } +.view-toggle button[aria-pressed="true"] { color: var(--accent); background: var(--selected); } +.sample-grid { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 18px; } +.sample-card { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); box-shadow: var(--shadow); transition: border-color 150ms,transform 150ms; } +.sample-card:hover { border-color: var(--selected-border); transform: translateY(-2px); } +.card-preview { display: flex; align-items: center; gap: 14px; min-height: 78px; padding: 16px 21px; border-bottom: 1px solid var(--border); background: linear-gradient(120deg,var(--selected),var(--soft)); text-decoration: none; color: var(--muted); } +.card-preview img { width: 40px; height: 40px; object-fit: contain; } +.card-preview .product-monogram { display: grid; place-items: center; width: 40px; height: 40px; border: 1px solid var(--border); border-radius: 10px; font-family: Consolas,monospace; font-size: 17px; font-weight: 600; background: var(--surface); color: var(--accent); } +.card-preview span:last-child { font-family: Consolas,monospace; font-size: 12px; } +.card-preview .preview-mark { margin-left: auto; color: var(--accent); opacity: .55; font-size: 23px !important; } +.card-body { padding: 20px 21px 16px; display: flex; flex-direction: column; flex: 1; } +.card-meta { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 11px; } +.scenario-tag { font-size: 10px; font-weight: 800; letter-spacing: .035em; color: var(--accent); text-transform: uppercase; background: var(--selected); border-radius: 99px; padding: 3px 8px; } +.card-date { font-size: 11px; color: var(--muted); } +.sample-card h3 { font-size: 19px; line-height: 1.3; font-weight: 800; margin-bottom: 10px; letter-spacing: -.01em; } +.sample-card h3 a { text-decoration: none; color: var(--ink); } +.sample-card h3 a:hover { color: var(--accent); } +.card-description { color: var(--muted); font-size: 13px; line-height: 1.65; margin-bottom: 16px; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; } +.tool-tags { display: flex; gap: 5px; flex-wrap: wrap; margin-top: auto; } +.tool-tag { display: inline-flex; padding: 3px 7px; border: 1px solid var(--border); border-radius: 4px; background: var(--soft); color: var(--muted); font-size: 10px; } +.card-footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 13px 21px; border-top: 1px solid var(--border); font-size: 11px; } +.card-author { display: inline-flex; gap: 7px; align-items: center; color: var(--muted); text-decoration: none; min-width: 0; } +.card-author > span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 200px; } +.avatar { flex-shrink: 0; width: 24px; height: 24px; border-radius: 50%; object-fit: cover; background: var(--selected); } +.avatar-fallback { display: inline-grid; place-items: center; background: var(--selected); color: var(--accent); font-size: 10px; font-weight: 600; } +.card-open { color: var(--accent); text-decoration: none; white-space: nowrap; font-weight: 600; } +.sample-grid.is-list { grid-template-columns: 1fr; gap: 10px; } +.is-list .sample-card { display: grid; grid-template-columns: 170px minmax(0,1fr) 200px; } +.is-list .card-preview { border-bottom: 0; border-right: 1px solid var(--border); padding: 16px; flex-wrap: wrap; gap: 8px; } +.is-list .card-preview .preview-mark { display: none; } +.is-list .card-body { padding: 14px 20px; } +.is-list .card-meta { margin-bottom: 6px; } +.is-list .card-description { -webkit-line-clamp: 1; margin-bottom: 10px; } +.is-list .sample-card h3 { font-size: 18px; margin-bottom: 5px; } +.is-list .card-footer { flex-direction: column; justify-content: center; align-items: start; border-top: 0; border-left: 1px solid var(--border); } +.load-more { display: flex; flex-direction: column; align-items: center; gap: 12px; padding-block: 30px 34px; } +.load-more > span { color: var(--muted); font-size: 12px; } +.button { display: inline-flex; align-items: center; justify-content: center; gap: 14px; min-height: 42px; padding: 10px 18px; border-radius: 5px; border: 1px solid var(--border); text-decoration: none; font-size: 13px; font-weight: 600; } +.button-primary { background: var(--accent); color: var(--surface); border-color: var(--accent); } +html[data-theme="dark"] .button-primary { color: #0b211f; } +.button-primary:hover { background: var(--accent-hover); color: var(--surface); } +html[data-theme="dark"] .button-primary:hover { color: #0b211f; } +.button-secondary { background: var(--surface); color: var(--ink); } +.button-secondary:hover { color: var(--accent); border-color: var(--accent); } +.contribution-banner { display: flex; align-items: center; gap: 20px; padding: 25px 28px; background: var(--selected); border: 1px solid var(--selected-border); border-radius: 8px; } +.contribution-badge { width: 88px; height: 88px; object-fit: contain; flex-shrink: 0; } +.code-symbol { display: grid; place-items: center; width: 54px; height: 54px; flex-shrink: 0; border-radius: 12px; background: var(--surface); color: var(--accent); font-family: Consolas,monospace; font-size: 22px; } +.contribution-banner h3 { font-size: 18px; margin-bottom: 4px; } +.contribution-banner p { color: var(--muted); font-size: 13px; margin: 0; } +.contribution-banner .button { margin-left: auto; white-space: nowrap; } +.empty-state { text-align: center; padding: 52px 20px; border: 1px dashed var(--border); border-radius: 8px; background: var(--surface); } +.empty-icon { display: inline-block; font: 30px Consolas,monospace; color: var(--accent); margin-bottom: 16px; } +.empty-state h3 { font-size: 24px; margin-bottom: 8px; } +.empty-state p { color: var(--muted); } +.site-footer { color: var(--footer-ink); background: var(--footer); border-top: 1px solid var(--border); padding: 30px 0 64px; } +.footer-inner { display: flex; justify-content: space-between; gap: 32px; align-items: center; } +.footer-inner strong { font-size: 14px; } +.footer-inner p { margin: 5px 0 0; font-size: 12px; color: #c1cbd2; } +.footer-inner nav { display: flex; gap: 22px; flex-wrap: wrap; } +.footer-inner a { color: #d9e5ed; font-size: 12px; text-decoration: none; } +.review-notice { position: fixed; z-index: 60; bottom: 0; width: 100%; min-height: 34px; display: flex; justify-content: space-between; gap: 16px; align-items: center; padding: 8px 24px; background: var(--surface); border-top: 1px solid var(--border); font-size: 11px; color: var(--muted); } +.review-notice a { color: var(--accent); font-weight: 600; text-decoration: none; } +.status-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: var(--accent); margin-right: 6px; } +.page-section { padding-block: 42px 60px; min-height: 70vh; } +.page-heading { max-width: 820px; margin-bottom: 28px; } +.page-heading h1,.detail-header h1 { font-size: 44px; line-height: 1.13; font-weight: 800; letter-spacing: -.025em; margin: 0 0 16px; } +.page-heading > p:last-child { color: var(--muted); font-size: 17px; } +.recognition-band { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 26px 30px; background: var(--selected); border: 1px solid var(--selected-border); border-radius: 8px; margin-bottom: 28px; } +.recognition-band h2 { font-size: 26px; margin-bottom: 8px; } +.recognition-band p { color: var(--muted); max-width: 720px; margin-bottom: 8px; } +.recognition-band .recognition-badge { width: 170px; height: 170px; object-fit: contain; flex-shrink: 0; } +.contributor-controls { display: grid; grid-template-columns: minmax(250px,1fr) 190px; gap: 12px; max-width: 730px; margin-bottom: 22px; } +.contributor-grid { display: grid; grid-template-columns: repeat(4,minmax(0,1fr)); gap: 16px; } +.contributor-card { padding: 23px 20px; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; box-shadow: var(--shadow); } +.contributor-card > .avatar { width: 60px; height: 60px; margin-bottom: 14px; font-size: 19px; } +.contributor-card h2 { font-size: 18px; margin-bottom: 3px; overflow-wrap: anywhere; } +.contributor-card .handle { font-size: 12px; } +.contributor-card p { color: var(--muted); font-size: 12px; margin: 12px 0; } +.contributor-card .text-link { font-size: 12px; } +.contributor-badge-link { display: flex; align-items: center; gap: 8px; margin-top: 16px; padding-top: 12px; border-top: 1px solid var(--border); color: var(--accent); font-size: 11px; text-decoration: none; } +.contributor-badge-link img { width: 32px; height: 32px; object-fit: contain; } +.detail-section { padding-block: 28px 60px; } +.breadcrumbs { display: flex; flex-wrap: wrap; gap: 10px; color: var(--muted); margin-bottom: 24px; font-size: 12px; } +.breadcrumbs a { text-decoration: none; color: var(--accent); } +.detail-header { max-width: 970px; margin-bottom: 24px; } +.detail-header h1 { font-size: 40px; margin-block: 12px; } +.detail-header > p { font-size: 17px; color: var(--muted); margin-bottom: 15px; } +.detail-byline { display: flex; flex-wrap: wrap; align-items: center; gap: 14px; font-size: 12px; color: var(--muted); } +.detail-byline .avatar { width: 30px; height: 30px; } +.detail-layout { display: grid; grid-template-columns: minmax(0,1fr) 290px; gap: 28px; } +.detail-main,.detail-sidebar { min-width: 0; } +.detail-main h2 { font-size: 24px; margin-block: 26px 14px; } +.detail-main > h2:first-child { margin-top: 0; } +.safety-note { padding: 14px 18px; border: 1px solid var(--warm-border); border-left: 3px solid var(--warm-ink); border-radius: 6px; background: var(--warm); color: var(--warm-ink); font-size: 13px; margin-bottom: 18px; } +.safety-note p { margin: 5px 0 0; } +.tool-tabs { display: flex; gap: 4px; flex-wrap: wrap; border-bottom: 1px solid var(--border); margin-bottom: 0; } +.tool-tabs button { padding: 12px 16px; border: 0; border-bottom: 3px solid transparent; background: transparent; font-size: 12px; color: var(--muted); } +.tool-tabs button[aria-selected="true"] { color: var(--accent); border-bottom-color: var(--accent); font-weight: 600; background: var(--selected); border-radius: 5px 5px 0 0; } +.code-frame { background: var(--code); border-radius: 0 0 7px 7px; overflow: hidden; color: #ddeaf4; } +.code-toolbar { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #ffffff20; padding: 10px 17px; color: #a2b9cb; font: 11px Consolas,monospace; } +.code-toolbar button { border: 1px solid #6b8190; background: transparent; color: #d5e5ee; border-radius: 4px; padding: 5px 10px; font-size: 11px; } +pre { margin: 0; padding: 19px; overflow-x: auto; max-height: 540px; font: 12px/1.85 Consolas,"Cascadia Code",monospace; tab-size: 2; } +.excerpt-notice { background: var(--surface); padding: 12px 16px; border: 1px solid var(--border); border-top: 0; border-radius: 0 0 6px 6px; color: var(--muted); font-size: 12px; } +.sidebar-panel { padding: 22px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); margin-bottom: 16px; } +.sidebar-panel h2 { font-size: 17px; margin-bottom: 16px; } +.sidebar-panel .button { width: 100%; margin-bottom: 10px; } +.sidebar-panel dl { margin-bottom: 0; } +.sidebar-panel dt { font-size: 11px; color: var(--muted); margin-top: 18px; } +.sidebar-panel dd { margin: 4px 0 0; font-size: 12px; } +.product-inline { display: inline-flex; align-items: center; gap: 8px; padding: 5px 0; margin-right: 14px; } +.product-inline img { width: 22px; height: 22px; object-fit: contain; } +.sidebar-panel .tag-list { display: flex; flex-wrap: wrap; gap: 5px; } +.sidebar-panel .tag-list span { padding: 3px 6px; background: var(--soft); border: 1px solid var(--border); border-radius: 4px; font-size: 10px; overflow-wrap: anywhere; } +.related-samples { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 12px; } +.related-samples a { background: var(--surface); padding: 16px; border: 1px solid var(--border); border-radius: 6px; color: var(--ink); text-decoration: none; font-size: 13px; } +.prose { max-width: 960px; } +.prose h2 { font-size: 25px; margin: 32px 0 16px; } +.prose h3 { margin: 20px 0 9px; font-size: 18px; } +.prose p,.prose li { color: var(--muted); } +.prose li { margin-bottom: 10px; } +.prose code { font: 12px Consolas,monospace; background: var(--selected); color: var(--accent); padding: 3px 5px; border-radius: 4px; overflow-wrap: anywhere; } +.prose .callout { padding: 20px 24px; background: var(--surface); border: 1px solid var(--border); border-radius: 7px; margin-block: 18px; } +.prose .callout h3 { margin-top: 0; } +.prose .callout p:last-child { margin-bottom: 0; } +.steps-grid { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 18px; margin-block: 28px; } +.step-card { padding: 25px; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; } +.step-number { color: var(--accent); font: 24px Consolas,monospace; } +.step-card h2 { font-size: 19px; margin: 18px 0 10px; } +.step-card p { color: var(--muted); font-size: 13px; } +.spec-table { width: 100%; border-collapse: collapse; background: var(--surface); font-size: 13px; margin-block: 18px; } +.spec-table th,.spec-table td { border: 1px solid var(--border); padding: 13px 16px; text-align: left; vertical-align: top; } +.spec-table th { background: var(--selected); font-weight: 600; } +.spec-table td { color: var(--muted); } +.color-swatches { display: flex; gap: 14px; margin: 22px 0; flex-wrap: wrap; } +.color-swatches span { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted); } +.color-swatches i { display: inline-block; width: 28px; height: 28px; border: 1px solid var(--border); border-radius: 6px; } +.table-wrap { overflow-x: auto; } +@media (min-width: 1600px) { .hero { min-height: 310px; } .catalog-section { padding-top: 38px; } } +@media (max-width: 1180px) { + .desktop-nav a { font-size: 12px; padding-inline: 7px; } + .brand { font-size: 18px; } + .header-actions { gap: 8px; } + .product-button { padding-inline: 8px; gap: 7px; font-size: 12px; } + .contributor-grid { grid-template-columns: repeat(3,minmax(0,1fr)); } +} +@media (max-width: 1000px) { + .desktop-nav { display: none; } .mobile-nav { display: block; } + .sample-grid { grid-template-columns: repeat(2,minmax(0,1fr)); } + .catalog-toolbar { grid-template-columns: repeat(3,minmax(0,1fr)); } + .catalog-toolbar .search-control { grid-column: 1 / -1; } + .product-filters { grid-template-columns: repeat(3,minmax(0,1fr)); } + .product-button { min-height: 62px; } + .detail-layout { grid-template-columns: minmax(0,1fr) 250px; gap: 20px; } + .contribution-banner { flex-wrap: wrap; } + .contribution-banner .button { margin-left: 74px; } + .is-list .sample-card { grid-template-columns: 120px minmax(0,1fr); } + .is-list .card-footer { grid-column: 2; flex-direction: row; justify-content: space-between; border: 0; padding-top: 0; } + .is-list .card-preview { grid-row: span 2; } + .footer-inner { flex-direction: column; align-items: start; } +} +@media (max-width: 700px) { + .container { width: calc(100% - 32px); } + .header-inner { min-height: 62px; gap: 12px; } + .brand { font-size: 16px; gap: 7px; } .brand img { width: 29px; height: 39px; } + .brand-name { display: flex; flex-direction: column; gap: 2px; line-height: 1.15; } + .brand-name > span { font-size: 10px; font-weight: 600; } + .brand-name > strong { font-size: 16px; } + .header-actions { gap: 8px; } + .theme-toggle { width: 60px; height: 34px; } + .theme-toggle::before { width: 26px; height: 26px; } + .theme-icons { grid-template-columns: 26px 26px; gap: 0; } + html[data-theme="dark"] .theme-toggle::before { transform: translateX(26px); } + .hero { position: relative; display: block; min-height: auto; padding-block: 25px 22px; } + .hero h1 { font-size: 38px; } + .hero-descriptor { font-size: 18px; } + .hero-description { max-width: calc(100% - 86px); font-size: 14px; margin-bottom: 16px; } + .hero-meta { gap: 20px; font-size: 11px; flex-wrap: wrap; } + .hero-meta > span:last-child { display: none; } + .hero .eyebrow { font-size: 10px; } + .desktop-break { display: none; } + .parker-scene { position: absolute; right: 0; top: 104px; width: 78px; height: 112px; } + .parker-scene > img { width: 78px; height: 112px; } + .scene-orbit,.scene-token,.scene-caption { display: none; } + .parker-scene::before { width: 100px; height: 100px; } + .ribbon-inner { gap: 10px; flex-wrap: wrap; padding-block: 12px; } + .ribbon-inner p { font-size: 12px; flex: 1 1 calc(100% - 40px); } + .ribbon-inner a { font-size: 11px; margin-left: 31px; } + .catalog-section { padding-top: 26px; } + h2 { font-size: 25px; } + .section-heading { align-items: start; flex-direction: column; gap: 10px; margin-bottom: 18px; } + .section-heading .text-link { font-size: 12px; } + .product-filters { gap: 7px; } + .product-button { flex-direction: column; gap: 5px; font-size: 11px; padding: 8px 5px; min-height: 72px; } + .product-button img { width: 28px; height: 28px; } + .product-button .all-icon { line-height: 28px; } + .product-button .product-number { display: none; } + .more-products { grid-column: 1 / -1; } + .more-products summary { flex-direction: row; min-height: 36px; } + .more-product-options { right: 0; width: 220px; } + .catalog-toolbar { grid-template-columns: 1fr 1fr; gap: 8px; padding: 9px; } + .catalog-toolbar #author-filter { grid-column: 1 / -1; } + .catalog-toolbar select { font-size: 12px; } + .search-control { gap: 7px; padding-inline: 9px; } + .search-control input { font-size: 12px; } + .search-control kbd { display: none; } + .results-bar { flex-wrap: wrap; gap: 8px; } + .results-bar p { font-size: 12px; } + .results-actions { gap: 10px; width: 100%; justify-content: space-between; } + .sample-grid { grid-template-columns: 1fr; gap: 15px; } + .sample-card h3 { font-size: 20px; } + .card-description { font-size: 14px; } + .card-preview { min-height: 68px; padding-block: 12px; } + .contribution-banner { padding: 22px; gap: 14px; } + .contribution-banner .contribution-badge { width: 64px; height: 64px; } + .contribution-banner > div:nth-child(2) { flex: 1; } + .contribution-banner h3 { font-size: 17px; } + .contribution-banner .button { margin-left: 0; width: 100%; } + .footer-inner nav { gap: 12px 20px; } + .footer-inner strong { font-size: 12px; } + .review-notice { font-size: 10px; padding-inline: 16px; } + .notice-secondary { display: none; } + .page-heading h1 { font-size: 35px; } + .page-heading > p:last-child { font-size: 15px; } + .contributor-grid { grid-template-columns: repeat(2,minmax(0,1fr)); gap: 10px; } + .contributor-card { padding: 18px 14px; } + .contributor-card h2 { font-size: 16px; } + .contributor-controls { grid-template-columns: 1fr; } + .recognition-band { padding: 22px; gap: 14px; } + .recognition-band h2 { font-size: 22px; } + .recognition-band p { font-size: 13px; } + .recognition-band .recognition-badge { width: 100px; height: 100px; } + .recognition-band { flex-wrap: wrap; } + .recognition-band > div { flex: 1 1 190px; } + .recognition-band > a { margin-inline: auto; } + .detail-header h1 { font-size: 31px; } + .detail-layout { grid-template-columns: 1fr; } + .detail-sidebar { display: grid; grid-template-columns: 1fr; } + .detail-header > p { font-size: 15px; } + .detail-byline { gap: 10px; } + .tool-tabs button { font-size: 11px; padding: 10px; } + .related-samples,.steps-grid { grid-template-columns: 1fr; } + .prose p,.prose li { font-size: 14px; } + .spec-table { font-size: 12px; } + .spec-table th,.spec-table td { padding: 10px; } + .is-list .sample-card { grid-template-columns: 64px minmax(0,1fr); } + .is-list .card-preview { padding: 12px; justify-content: center; align-content: center; } + .is-list .card-preview span:last-child { display: none; } + .is-list .card-preview img { width: 30px; height: 30px; } + .is-list .card-body { padding: 14px; } + .is-list .card-footer { padding-inline: 14px; } + .is-list .card-author > span:last-child { max-width: 140px; } +} +@media (max-width: 380px) { .parker-scene { display: none; } .hero-description { max-width: none; } .brand { font-size: 14px; } .header-actions { gap: 5px; } } +@media (prefers-reduced-motion: reduce) { *,*::before,*::after { transition: none !important; scroll-behavior: auto !important; } .sample-card:hover { transform: none; } } + +html { scroll-padding-top: 90px; } +.hero-copy { min-width: 0; } +.text-link, .card-open, .ribbon-inner a { display: inline-flex; align-items: center; gap: 7px; } +.ribbon-inner a { text-decoration: underline; } +.catalog-controls { display: flex; flex-direction: column; } +.catalog-toolbar { grid-template-columns: minmax(240px,2.4fr) minmax(0,3.4fr); } +.advanced-filters { min-width: 0; } +.advanced-filters > summary { display: none; } +.filter-selects { display: grid; grid-template-columns: 1.25fr 1fr 1.15fr; gap: 10px; } +.filter-notice { margin-top: 12px; padding: 10px 14px; border: 1px solid var(--warm-border); border-radius: 6px; background: var(--warm); color: var(--warm-ink); font-size: 13px; } +.js #sample-grid:not([data-ready]) > .sample-card:nth-child(n+13) { display: none; } +html:not(.js) .load-more, html:not(.js) .catalog-toolbar, html:not(.js) .view-toggle { display: none; } +html:not(.js) .readme-tabs > [role="tabpanel"][hidden] { display: block !important; } +.footer-inner nav { justify-content: flex-end; gap: 12px 20px; } +.site-footer { padding-bottom: 32px; } +.readme-content { min-width: 0; line-height: 1.75; overflow-wrap: anywhere; } +.readme-content > :first-child { margin-top: 0; } +.readme-content h2 { font-size: 25px; margin: 30px 0 16px; } +.readme-content h3 { font-size: 20px; margin: 25px 0 12px; } +.readme-content h4 { font-size: 17px; margin: 22px 0 10px; } +.readme-content p, .readme-content li { color: var(--muted); } +.readme-content ul, .readme-content ol { padding-left: 24px; } +.readme-content li { margin-bottom: 8px; } +.readme-content img { display: block; max-width: 100%; height: auto; margin-block: 18px; border-radius: 5px; } +.readme-content a > img { max-height: 520px; object-fit: contain; } +.readme-content p > a > img[src*="credly-badge"] { width: min(200px,100%); } +.readme-content hr { border: 0; border-top: 1px solid var(--border); margin-block: 24px; } +.readme-content :not(pre) > code { font: 13px/1.6 Consolas,monospace; padding: 3px 5px; background: var(--selected); color: var(--accent); border-radius: 4px; white-space: normal; } +.readme-content pre { max-width: 100%; white-space: pre; overflow-wrap: normal; } +.code-frame { margin-block: 16px 22px; } +.code-toolbar { font-family: inherit; } +.code-frame pre { background: var(--code); color: #e6edf3; max-height: 580px; font-size: 13px; } +.shiki, .shiki span { color: var(--shiki-dark, #e6edf3); } +.shiki .command-help { color: inherit; text-decoration: underline dotted; text-underline-offset: 3px; } +.readme-tabs { min-width: 0; margin-block: 20px; } +.readme-tabs .tool-tabs { overflow-x: auto; flex-wrap: nowrap; } +.readme-tabs .tool-tabs button { white-space: nowrap; flex-shrink: 0; } +.readme-tabs > [role="tabpanel"] { padding-top: 18px; } +.readme-tabs > [role="tabpanel"] > .code-frame:first-child { margin-top: 0; } +.table-wrap { max-width: 100%; margin-block: 18px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); } +.readme-content table { border-collapse: collapse; width: 100%; font-size: 13px; } +.readme-content th, .readme-content td { text-align: left; vertical-align: top; border: 1px solid var(--border); padding: 10px 14px; } +.readme-content th { background: var(--selected); color: var(--ink); } +.readme-content td { color: var(--muted); } +.readme-content blockquote { margin-inline: 0; padding: 12px 18px; border-left: 3px solid var(--selected-border); background: var(--soft); } +.callout { padding: 14px 18px; border: 1px solid var(--border); border-left: 3px solid var(--link); border-radius: 6px; background: var(--selected); margin-block: 18px; } +.callout p:last-child { margin-bottom: 0; } +.callout--warning, .callout--caution { background: var(--warm); border-color: var(--warm-border); border-left-color: var(--warm-ink); } +.callout--warning p, .callout--caution p { color: var(--warm-ink); } +.sidebar-panel .tag-list a { padding: 3px 6px; background: var(--soft); border: 1px solid var(--border); border-radius: 4px; font-size: 10px; text-decoration: none; overflow-wrap: anywhere; } +.sidebar-panel .product-inline { text-decoration: none; } +.detail-badge { display: block; margin-inline: auto; object-fit: contain; } +.reference-section li p { margin-top: 4px; font-size: 13px; } +.detail-main > section > h2 { margin-top: 30px; } +.guide-layout { display: grid; grid-template-columns: minmax(0,1fr) 260px; gap: 44px; } +.guide-content { max-width: 920px; } +.guide-sidebar { align-self: start; padding: 22px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); } +.guide-sidebar h2 { font-size: 18px; margin-bottom: 15px; } +.guide-sidebar nav { display: flex; flex-direction: column; gap: 4px; margin-bottom: 20px; } +.guide-sidebar nav a { text-decoration: none; font-size: 13px; padding: 8px; border-radius: 4px; } +.guide-sidebar nav a[aria-current="page"] { background: var(--selected); font-weight: 600; color: var(--accent); } +.guide-sidebar > a { font-size: 13px; } +.report-navigation { display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 28px; } +.more-product-options { max-height: min(480px,65vh); overflow-y: auto; } +@media (max-width: 1180px) { .catalog-toolbar { grid-template-columns: minmax(200px,1.3fr) minmax(0,2fr); } } +@media (max-width: 1000px) { + .catalog-toolbar { grid-template-columns: 1fr; } + .catalog-toolbar .search-control { grid-column: auto; } + .more-products { grid-column: 1 / -1; } + .more-products summary { min-height: 40px; } + .guide-layout { grid-template-columns: minmax(0,1fr) 220px; gap: 24px; } + .readme-tabs .tool-tabs { max-width: 100%; } +} +@media (max-width: 700px) { + .hero { padding-block: 23px 20px; } + .hero-instruction { display: none; } + .hero-description { margin-bottom: 14px; } + .parker-scene { top: 100px; } + .community-ribbon .ribbon-inner p { display: none; } + .community-ribbon .ribbon-inner { min-height: 44px; padding-block: 9px; gap: 10px; } + .community-ribbon .ribbon-inner a { margin-left: 0; } + .catalog-controls .catalog-toolbar { order: -1; margin-bottom: 14px; padding: 9px; } + .advanced-filters > summary { display: flex; justify-content: space-between; align-items: center; min-height: 36px; cursor: pointer; font-size: 12px; color: var(--accent); list-style: none; } + .advanced-filters > summary::-webkit-details-marker { display: none; } + .filter-selects { grid-template-columns: 1fr; gap: 8px; padding-top: 8px; } + .catalog-toolbar #author-filter { grid-column: auto; } + .product-filters { margin-bottom: 0; } + .section-heading .text-link { font-size: 12px; } + .results-bar { padding-top: 14px; } + .guide-layout { grid-template-columns: 1fr; } + .guide-sidebar { order: 2; } + .readme-content h2 { font-size: 23px; } + .readme-content pre { font-size: 12px; padding: 14px; } + .detail-layout { display: flex; flex-direction: column; } + .detail-sidebar { display: block; } + .footer-inner nav { justify-content: flex-start; } +} diff --git a/site/tests/catalog.test.mjs b/site/tests/catalog.test.mjs new file mode 100644 index 000000000..0db879c84 --- /dev/null +++ b/site/tests/catalog.test.mjs @@ -0,0 +1,59 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import Ajv2020 from "ajv/dist/2020.js"; +import addFormats from "ajv-formats"; +import { loadSources, localThumbnail, validateTracker } from "../scripts/source.mjs"; +import { BASE_PATH, REPOSITORY_ROOT, productIds, sitePath, trackerIdentity } from "../scripts/config.mjs"; + +const records = await loadSources(); +test("publishes every source sample without silently excluding records", () => { + assert.ok(records.length >= 419); + assert.equal(new Set(records.map((record) => record.slug.toLowerCase())).size, records.length); +}); +test("normalizes deliberate product aliases and rejects unknown products", () => { + assert.deepEqual(productIds(["AzureAD", "Entra ID", "Microsoft Entra"]), ["entra"]); + assert.deepEqual(productIds(["Teams", "Microsoft Teams", "Microsoft Copilot"]), ["teams", "copilot"]); + assert.deepEqual(productIds(["Graph"]), ["graph"]); + assert.throws(() => productIds(["Unregistered product"]), /Unknown product/); +}); +test("keeps historical tracker identities and canonical sample paths", () => { + assert.equal(sitePath("samples/example/"), `${BASE_PATH}/samples/example/`); + assert.equal(trackerIdentity(""), "https://m365-visitor-stats.azurewebsites.net/script-samples"); + assert.equal(trackerIdentity("samples/example/"), "https://m365-visitor-stats.azurewebsites.net/script-samples/scripts/example"); + assert.equal(trackerIdentity("contributing/how-can-i-contribute/"), "https://m365-visitor-stats.azurewebsites.net/script-samples/how-can-i-contribute"); + assert.equal(trackerIdentity("404"), "https://m365-visitor-stats.azurewebsites.net/script-samples/404"); +}); +test("requires exactly one final-line README tracker while preserving accessibility attributes", () => { + const image = ''; + assert.doesNotThrow(() => validateTracker("example", `# Sample\n${image}\n`)); + assert.throws(() => validateTracker("other", image), /final line/); + assert.throws(() => validateTracker("example", `${image}\nMore text`), /final line/); + assert.throws(() => validateTracker("example", `${image}\n${image}`), /exactly one/); +}); +test("schema rejects incomplete metadata, impossible dates, unknown tools, and duplicate categories", async () => { + const ajv = new Ajv2020({ allErrors: true }); + addFormats(ajv); + const validate = ajv.compile(JSON.parse(await readFile(path.join(REPOSITORY_ROOT, ".github", "schemas", "sample.schema.json"), "utf8"))); + const source = records[0].metadata; + assert.equal(validate([source]), true); + for (const edit of [ + (record) => { record.title = ""; }, + (record) => { record.shortDescription = ""; }, + (record) => { record.creationDateTime = "2026-02-31"; }, + (record) => { record.metadata[0].key = "UNREGISTERED"; }, + (record) => { record.categories.push(record.categories[0]); }, + (record) => { record.authors[0].gitHubAccount = "Not an account"; } + ]) { + const record = structuredClone(source); + edit(record); + assert.equal(validate([record]), false, JSON.stringify(record)); + } +}); +test("previews must belong to their sample and cannot traverse outside it", async () => { + const { slug, metadata } = records[0]; + assert.ok(await localThumbnail(slug, metadata.thumbnails[0].url)); + await assert.rejects(() => localThumbnail("other", metadata.thumbnails[0].url), /this sample/); + await assert.rejects(() => localThumbnail(slug, `https://raw.githubusercontent.com/pnp/script-samples/main/scripts/${slug}/../../secret.png`), /this sample/); +}); diff --git a/site/tests/gallery.spec.ts b/site/tests/gallery.spec.ts new file mode 100644 index 000000000..9ecda91bd --- /dev/null +++ b/site/tests/gallery.spec.ts @@ -0,0 +1,239 @@ +import { readFileSync } from "node:fs"; +import { expect, test } from "@playwright/test"; +import AxeBuilder from "@axe-core/playwright"; +import { marked, type Tokens } from "marked"; +import type { Product, Sample, Contributor } from "../src/lib/types"; + +const pageErrors = new WeakMap(); +test.beforeEach(async ({ page }) => { + const errors: string[] = []; + pageErrors.set(page, errors); + page.on("pageerror", (error) => errors.push(error.message)); +}); +test.afterEach(async ({ page }) => { + expect(pageErrors.get(page)).toEqual([]); +}); +async function openFilters(page: import("@playwright/test").Page) { + if (!(await page.locator("#tool-filter").isVisible())) await page.locator("#advanced-filters summary").click(); +} + +test("uses the approved brand, Graph imagery, ordered filters, and Community-first navigation", async ({ page, request }) => { + const catalog = await (await request.get("catalog.json")).json() as { samples: Sample[]; products: Product[]; contributors: Contributor[] }; + await page.goto("./"); + await expect(page.locator("#sample-grid")).toHaveAttribute("data-ready", "true"); + await expect(page.locator(".brand-name")).toHaveText(/Community\s+Script Samples/); + await expect(page.locator(".hero-description")).toContainText("Real-world scripts for Copilot, Microsoft 365, Power Platform and more."); + await expect(page.locator('#product-filters > [data-product="graph"] img')).toHaveAttribute("src", /images\/graph\.svg$/); + const featured = await page.locator("#product-filters > [data-product]").evaluateAll((buttons) => buttons.slice(1).map((button) => button.getAttribute("data-product"))); + expect(featured).toEqual(catalog.products.filter((product) => product.featured).map((product) => product.id)); + const counts = catalog.products.filter((product) => product.featured).map((product) => product.count); + expect(counts).toEqual([...counts].sort((a, b) => b - a)); + for (const route of ["./", "getting-started/", "contributors/", "contributing/", "samples/aad-add-app-permission/"]) { + await page.goto(route); + const mobile = await page.locator(".mobile-nav").isVisible(); + if (mobile) await page.locator(".mobile-nav summary").click(); + const nav = page.getByRole("navigation", { name: mobile ? "Mobile navigation" : "Primary navigation", exact: true }); + await expect(nav.getByRole("link").first()).toHaveAttribute("href", "https://aka.ms/community/home"); + await expect(nav.getByRole("link").first()).toHaveText("Community"); + await expect(nav.getByRole("link").first().locator("svg")).toHaveAttribute("aria-hidden", "true"); + } +}); + +test("combines filters, preserves deep links, sorts, and presents empty states", async ({ page, request }) => { + const catalog = await (await request.get("catalog.json")).json() as { samples: Sample[]; products: Product[] }; + await page.goto("./"); + await page.locator('[data-product="teams"]').click(); + await openFilters(page); + await page.locator("#tool-filter").selectOption("CLI-FOR-MICROSOFT365"); + const expected = catalog.samples.filter((sample) => sample.products.includes("teams") && sample.tools.some((tool) => tool.id === "CLI-FOR-MICROSOFT365")); + await expect(page.locator("#result-count")).toHaveText(`${expected.length} matching samples of ${catalog.samples.length}`); + await expect(page).toHaveURL(/product=teams.*tool=CLI-FOR-MICROSOFT365/); + await page.reload(); + await expect(page.locator("#tool-filter")).toHaveValue("CLI-FOR-MICROSOFT365"); + await expect(page.locator('[data-product="teams"]')).toHaveAttribute("aria-pressed", "true"); + await page.locator("#sample-search").fill("no-such-command-xyz-42"); + await expect(page.locator("#empty-state")).toBeVisible(); + await page.locator("#empty-clear").click(); + await expect(page.locator("#sample-search")).toBeFocused(); + await expect(page.locator(".sample-card:visible")).toHaveCount(12); + await page.locator("#sort-samples").selectOption("name"); + const titles = await page.locator(".sample-card:visible h3").allTextContents(); + expect(titles).toEqual([...titles].sort((a, b) => a.localeCompare(b))); + await page.goto("./?product=entra&q=AzureAD"); + const oldNameCount = await page.locator("#result-count").innerText(); + await page.locator("#sample-search").fill("Microsoft Entra"); + await expect(page.locator("#result-count")).toHaveText(oldNameCount); + await page.goto("./?product=invalid-product"); + await expect(page.locator("#filter-notice")).toBeVisible(); + await expect(page.locator("#result-count")).toHaveText(`Explore all ${catalog.samples.length} community samples`); +}); + +test("restores loaded results, list layout, filters, and scroll when returning from a sample", async ({ page }) => { + await page.goto("./?product=sharepoint"); + await page.locator("#load-more").click(); + await expect(page.locator(".sample-card:visible")).toHaveCount(24); + await page.locator('[data-layout="list"]').click(); + const link = page.locator(".sample-card:visible h3 a").nth(15); + await link.scrollIntoViewIfNeeded(); + const before = await page.evaluate(() => scrollY); + const title = await link.innerText(); + await link.click(); + await expect(page.locator("h1")).toHaveText(title); + await page.goBack(); + await expect(page.locator('[data-product="sharepoint"]')).toHaveAttribute("aria-pressed", "true"); + await expect(page.locator("#sample-grid")).toHaveClass("sample-grid is-list"); + await expect(page.locator(".sample-card:visible")).toHaveCount(24); + await expect.poll(async () => Math.abs((await page.evaluate(() => scrollY)) - before)).toBeLessThan(12); +}); + +test("shows full real tool implementations with keyboard tabs and exact code copying", async ({ page, context }) => { + const readme = readFileSync(new URL("../../scripts/aad-add-app-permission/README.md", import.meta.url), "utf8"); + const blocks = marked.lexer(readme).filter((token): token is Tokens.Code => token.type === "code"); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await page.goto("samples/aad-add-app-permission/"); + const tabs = page.locator('.readme-tabs [role="tab"]'); + await expect(tabs).toHaveCount(2); + const panel = page.locator('.readme-tabs [role="tabpanel"]:visible'); + expect((await panel.locator("pre code").innerText()).trim()).toBe(blocks[0].text.trim()); + await tabs.first().focus(); + await page.keyboard.press("ArrowRight"); + await expect(tabs.nth(1)).toHaveAttribute("aria-selected", "true"); + await expect(page).toHaveURL(/#tab\/graphps$/); + expect((await panel.locator("pre code").innerText()).trim()).toBe(blocks[1].text.trim()); + await panel.getByRole("button", { name: /Copy powershell code/ }).click(); + await expect(panel.getByRole("button", { name: /Copy powershell code/ })).toHaveText("Copied"); + const copied = await page.evaluate(() => navigator.clipboard.readText()); + expect(copied.replace(/\r\n/g, "\n").trim()).toBe(blocks[1].text.trim()); + await expect(page.locator(".safety-note")).toBeVisible(); + await expect(page.locator(".readme-content")).not.toContainText("[!INCLUDE"); + await expect(page.locator(".readme-content")).not.toContainText("Design preview"); +}); + +test("renders all contributor profiles, badge eligibility, and accurate author-filter links", async ({ page, request }) => { + const catalog = await (await request.get("catalog.json")).json() as { contributors: Contributor[]; samples: Sample[] }; + await page.goto("contributors/"); + await expect(page.locator(".contributor-card")).toHaveCount(catalog.contributors.length); + await expect(page.locator(".contributor-badge-link")).toHaveCount(catalog.contributors.length); + await expect(page.locator(".recognition-badge")).toHaveAttribute("src", /assets\/credly-badge\.png$/); + await page.locator("#contributor-search").fill("nelladath"); + await expect(page.locator(".contributor-card:visible")).toHaveCount(1); + const author = catalog.contributors.find((candidate) => candidate.handle.toLowerCase() === "nelladath"); + expect(author).toBeDefined(); + await page.locator(".contributor-card:visible .text-link").click(); + await expect(page.locator("#author-filter")).toHaveValue("nelladath"); + await expect(page.locator("#result-count")).toHaveText(`${author!.count} matching samples of ${catalog.samples.length}`); + await page.goto("contributing/"); + await expect(page.locator(".recognition-badge")).toBeVisible(); + await expect(page.locator(".guide-content")).toContainText("first accepted sample"); +}); + +test("retains old sample, guide, filter, and report links without redirect tracking", async ({ page, request }) => { + const legacy = await request.get("aad-add-app-permission/README.html"); + expect(legacy.status()).toBe(200); + expect(await legacy.text()).not.toContain("data-visitor-stats"); + await page.goto("aad-add-app-permission/README.html#tab/graphps"); + await expect(page).toHaveURL(/samples\/aad-add-app-permission\/#tab\/graphps$/); + await expect(page.locator('[data-tab-id="graphps"]')).toHaveAttribute("aria-selected", "true"); + await page.goto("by-tool.html?query=Get-PnPSite"); + await expect(page.locator("#sample-search")).toHaveValue("Get-PnPSite"); + await page.goto("compact-view.html"); + await expect(page.locator("#sample-grid")).toHaveClass("sample-grid is-list"); + await page.goto("contributing/preparing-a-submission.html"); + await expect(page).toHaveURL(/contributing\/preparing-a-submission\/$/); + await expect(page.locator("h1")).toHaveText("Share your first script sample"); + await page.goto("matrix.html"); + await expect(page).toHaveURL(/reports\/#matrix$/); +}); + +test("keeps local previews free of production analytics and maps every page tracker correctly", async ({ page }) => { + const requests: string[] = []; + page.on("request", (request) => { if (request.url().includes("m365-visitor-stats")) requests.push(request.url()); }); + const paths = [ + ["./", "script-samples"], + ["contributors/", "script-samples/contributors"], + ["contributing/", "script-samples/contributing"], + ["contributing/recognition/", "script-samples/contributing/recognition"], + ["samples/aad-add-app-permission/", "script-samples/scripts/aad-add-app-permission"] + ]; + for (const [url, identity] of paths) { + await page.goto(url); + await expect(page.locator("[data-visitor-stats]")).toHaveCount(1); + await expect(page.locator("[data-visitor-stats]")).toHaveAttribute("data-tracker-src", `https://m365-visitor-stats.azurewebsites.net/${identity}`); + await expect(page.locator("[data-visitor-stats]")).toHaveAttribute("src", /^data:image/); + } + const response = await page.goto("missing-example/"); + expect(response?.status()).toBe(404); + await expect(page.locator("[data-visitor-stats]")).toHaveAttribute("data-tracker-src", "https://m365-visitor-stats.azurewebsites.net/script-samples/404"); + expect(requests).toEqual([]); +}); + +test("activates exactly one production tracker without counting filter or theme interactions", async ({ page, request, baseURL }) => { + if (!baseURL) throw new Error("Browser tests require the local production server."); + const origin = new URL(baseURL).origin; + const tracked: string[] = []; + await page.route("https://m365-visitor-stats.azurewebsites.net/**", async (route) => { + tracked.push(route.request().url()); + await route.fulfill({ contentType: "image/gif", headers: { "Cache-Control": "no-store" }, body: Buffer.from("R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=", "base64") }); + }); + await page.route("https://pnp.github.io/script-samples/**", async (route) => { + const url = new URL(route.request().url()); + const response = await request.get(`${origin}${url.pathname}${url.search}`); + const headers = { ...response.headers() }; + delete headers["content-length"]; + const body = headers["content-type"]?.includes("text/html") + ? (await response.text()).replace('data-tracking-enabled="false"', 'data-tracking-enabled="true"') + : await response.body(); + await route.fulfill({ status: response.status(), headers, body }); + }); + await page.goto("https://pnp.github.io/script-samples/"); + await expect.poll(() => tracked.length).toBe(1); + expect(tracked[0]).toBe("https://m365-visitor-stats.azurewebsites.net/script-samples"); + await page.locator('[data-product="graph"]').click(); + await page.locator("#sample-search").fill("permissions"); + await page.locator("#theme-toggle").click(); + await page.evaluate(() => new Promise(requestAnimationFrame)); + expect(tracked).toHaveLength(1); +}); + +test("persists themes and has no WCAG violations on key views in either theme", async ({ page }) => { + test.setTimeout(120000); + const routes = ["./", "contributors/", "contributing/", "contributing/preparing-a-submission/", "samples/aad-add-app-permission/"]; + for (const theme of ["light", "dark"]) { + await page.goto("./"); + if ((await page.locator("html").getAttribute("data-theme")) !== theme) await page.locator("#theme-toggle").click(); + await page.reload(); + await expect(page.locator("html")).toHaveAttribute("data-theme", theme); + for (const route of routes) { + await page.goto(route); + const result = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]).analyze(); + expect(result.violations, `${theme}: ${route}`).toEqual([]); + const dimensions = await page.evaluate(() => ({ viewport: document.documentElement.clientWidth, content: document.documentElement.scrollWidth })); + expect(dimensions.content, `${theme}: ${route}`).toBeLessThanOrEqual(dimensions.viewport); + } + } +}); + +test("prioritizes search on mobile and renders the real local brand assets", async ({ page }, testInfo) => { + await page.goto("./"); + await expect(page.locator(".brand img")).toHaveJSProperty("complete", true); + await expect(page.locator(".brand img")).not.toHaveJSProperty("naturalWidth", 0); + await expect(page.locator('[data-product="graph"] img')).not.toHaveJSProperty("naturalWidth", 0); + if (testInfo.project.name === "mobile") { + const search = await page.locator("#sample-search").boundingBox(); + expect(search).not.toBeNull(); + expect(search!.y + search!.height).toBeLessThan(page.viewportSize()!.height); + await expect(page.locator("#advanced-filters")).not.toHaveAttribute("open"); + } +}); + +test.describe("without JavaScript", () => { + test.use({ javaScriptEnabled: false }); + test("still exposes all samples and full implementations", async ({ page, request }) => { + const catalog = await (await request.get("catalog.json")).json() as { samples: Sample[] }; + await page.goto("./"); + await expect(page.locator(".sample-card:visible")).toHaveCount(catalog.samples.length); + await page.goto("samples/aad-add-app-permission/"); + await expect(page.locator('.readme-tabs [role="tabpanel"]:visible')).toHaveCount(2); + await expect(page.locator("[data-visitor-stats]")).toHaveAttribute("src", /^data:image/); + }); +}); diff --git a/site/tests/generator.ps1 b/site/tests/generator.ps1 new file mode 100644 index 000000000..dee9aabfb --- /dev/null +++ b/site/tests/generator.ps1 @@ -0,0 +1,41 @@ +$ErrorActionPreference = 'Stop' +$repositoryRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$fixture = Join-Path ([System.IO.Path]::GetTempPath()) ("script-samples-generator-" + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path (Join-Path $fixture 'scripts') | Out-Null +try { + Copy-Item -LiteralPath (Join-Path $repositoryRoot 'New-Sample.ps1') -Destination $fixture + Copy-Item -LiteralPath (Join-Path $repositoryRoot 'scripts\_template-script-submission') -Destination (Join-Path $fixture 'scripts\_template-script-submission') -Recurse + $generator = Join-Path $fixture 'New-Sample.ps1' + $arguments = @{ + ScriptFolderName = 'spo-generator-check' + ScriptTitle = 'Generator check' + ScriptShortDescription = 'A temporary generator validation fixture.' + ScriptTool = 'All' + AuthorFullName = 'Example Contributor' + GitHubId = 'example-contributor' + } + & $generator @arguments + $sample = Join-Path $fixture 'scripts\spo-generator-check' + $readmePath = Join-Path $sample 'README.md' + $readme = Get-Content -LiteralPath $readmePath -Raw + $metadata = @(Get-Content -LiteralPath (Join-Path $sample 'assets\sample.json') -Raw | ConvertFrom-Json)[0] + if ([regex]::Matches($readme, '(?m)^# \[.+\]\(#tab/').Count -ne 8) { throw 'All must generate eight code tabs.' } + if (@($metadata.metadata).Count -ne 7) { throw 'All must generate seven unique tool keys, with CLI shared by PowerShell and Bash.' } + if ($readme -match '\.\./\.\./docfx/') { throw 'Generator must use the migrated shared include paths.' } + if ($readme.TrimEnd().Split("`n")[-1] -notmatch 'script-samples/scripts/spo-generator-check') { throw 'Incorrect final view tracker.' } + $original = Get-FileHash -LiteralPath $readmePath + $rejected = $false + try { & $generator @arguments } catch { $rejected = $_.Exception.Message -like '*already exists*' } + if (-not $rejected) { throw 'Generator must reject existing sample folders.' } + if ((Get-FileHash -LiteralPath $readmePath).Hash -ne $original.Hash) { throw 'An existing sample was modified.' } + $arguments.ScriptFolderName = 'spo-cli-check' + $arguments.ScriptTool = @('CliForMicrosoft365', 'CliForMicrosoft365Bash') + & $generator @arguments + $cli = @(Get-Content -LiteralPath (Join-Path $fixture 'scripts\spo-cli-check\assets\sample.json') -Raw | ConvertFrom-Json)[0] + if (@($cli.metadata).Count -ne 1) { throw 'CLI variants must not duplicate metadata keys.' } + Write-Host 'Generator checks passed: all tools, unique metadata, migrated includes, tracker, and overwrite protection.' +} finally { + Get-ChildItem -LiteralPath $fixture -Recurse -File | Remove-Item -Force + Get-ChildItem -LiteralPath $fixture -Recurse -Directory | Sort-Object { $_.FullName.Length } -Descending | Remove-Item -Force + Remove-Item -LiteralPath $fixture -Force +} diff --git a/site/tests/markdown.test.mjs b/site/tests/markdown.test.mjs new file mode 100644 index 000000000..95c5947e9 --- /dev/null +++ b/site/tests/markdown.test.mjs @@ -0,0 +1,63 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { expandIncludes, renderMarkdown, contentTarget } from "../scripts/markdown.mjs"; +import { readText } from "../scripts/source.mjs"; +import { REPOSITORY_ROOT } from "../scripts/config.mjs"; +import path from "node:path"; + +test("renders complete implementations rather than clipped preview excerpts", () => { + const lines = Array.from({ length: 160 }, (_, index) => `Write-Output "Line ${index}"`).join("\n"); + const { html, codeBlockCount } = renderMarkdown(`# Example\n\n\`\`\`powershell\n${lines}\n\`\`\``, "README.md"); + assert.equal(codeBlockCount, 1); + assert.match(html, /Line 159/); + assert.equal((html.match(/data-copy-code=/g) ?? []).length, 1); + assert.match(html, /tabindex="0"/); +}); +test("turns DocFX tool headings into accessible keyboard-ready tabs", () => { + const { html, scriptTabCount } = renderMarkdown("# Example\n\n# [PowerShell](#tab/ps)\n\n```powershell\nGet-Date\n```\n\n# [Bash](#tab/sh)\n\n```bash\necho hello\n```\n\n***\n\n## Contributors\n\nA person", "README.md"); + assert.equal(scriptTabCount, 2); + assert.equal((html.match(/role="tab"/g) ?? []).length, 2); + assert.equal((html.match(/role="tabpanel"/g) ?? []).length, 2); + assert.match(html, /aria-selected="true"/); + assert.match(html, /aria-controls="tools-0-panel-1"/); + assert.match(html, /hidden="hidden"/); + assert.ok(html.indexOf("Contributors") > html.lastIndexOf('role="tabpanel"')); +}); +test("keeps literal tracker examples inside code while removing actual tracker images", () => { + const image = ''; + const { html } = renderMarkdown(`# Example\n\n\`\`\`html\n${image}\n\`\`\`\n\n${image}`, "README.md"); + assert.match(html, /m365-visitor-stats/); + assert.ok(!/]*m365-visitor-stats/.test(html)); +}); +test("expands shared guidance, preserves example includes inside code, and strips duplicate trackers", () => { + const markdown = "# Sample\n\n[!INCLUDE [Disclaimer](../../docs/includes/DISCLAIMER.md)]\n\n```markdown\n[!INCLUDE [Example](../../docs/includes/DOES-NOT-EXIST.md)]\n```\n\n"; + const { html } = renderMarkdown(markdown, "scripts/example/README.md"); + assert.match(html, /WITHOUT WARRANTY/); + assert.ok(!html.includes("m365-visitor-stats")); + assert.match(html, /DOES-NOT-EXIST/); + assert.throws(() => expandIncludes("[!INCLUDE [Bad](../../README.md)]", "scripts/example/README.md"), /shared include/); +}); +test("renders warnings and sanitized HTML without changing code samples", () => { + const { html } = renderMarkdown('# Sample\n\n> [!WARNING]\n> This removes data.\n\n\n\n```html\n\n```', "README.md"); + assert.match(html, /callout--warning/); + assert.match(html, /This removes data/); + assert.ok(!html.includes("