From ac5700f1347d58f1aa368c6dfc200d174ca606c8 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Tue, 17 Nov 2026 20:35:28 -0600 Subject: [PATCH 1/5] feat(flow-php/web): 404 page - missing urls no longer answer with the home page - search, documentation and examples links - site:not_found_view event --- .../Website/Controller/HomeController.php | 6 ++ .../templates/main/not_found.html.twig | 55 +++++++++++++++++++ .../Tests/Functional/HomeControllerTest.php | 21 +++++++ 3 files changed, 82 insertions(+) create mode 100644 web/landing/templates/main/not_found.html.twig diff --git a/web/landing/src/Flow/Website/Controller/HomeController.php b/web/landing/src/Flow/Website/Controller/HomeController.php index d88781bad3..048ef65717 100644 --- a/web/landing/src/Flow/Website/Controller/HomeController.php +++ b/web/landing/src/Flow/Website/Controller/HomeController.php @@ -23,6 +23,12 @@ public function home(): Response ]); } + #[Route('/404.html', name: 'not_found', options: ['sitemap' => false])] + public function notFound(): Response + { + return $this->render('main/not_found.html.twig', []); + } + #[Route('/sponsor', name: 'sponsor', options: ['sitemap' => false])] public function sponsor(): Response { diff --git a/web/landing/templates/main/not_found.html.twig b/web/landing/templates/main/not_found.html.twig new file mode 100644 index 0000000000..10f3b05055 --- /dev/null +++ b/web/landing/templates/main/not_found.html.twig @@ -0,0 +1,55 @@ +{% extends 'base.html.twig' %} + +{%- block title -%} + Page not found - Flow PHP - Data Processing Framework +{%- endblock -%} + +{%- block description -%} + The page you are looking for does not exist. Search the Flow PHP documentation or browse the examples. +{%- endblock -%} + +{% block stylesheets %} + {{ parent() }} + +{% endblock %} + +{%- block hero -%}{%- endblock -%} + +{%- block contributors -%}{%- endblock -%} + +{% block main %} +
+
+ + + 404 + +

+ Page not found. +

+

+ The page you are looking for does not exist, or it moved. + Search the documentation, or start from the docs or the examples. +

+
+ + +
+ + {# Inline until the site has a shared tracking module. #} + +{% endblock %} diff --git a/web/landing/tests/Flow/Website/Tests/Functional/HomeControllerTest.php b/web/landing/tests/Flow/Website/Tests/Functional/HomeControllerTest.php index b3776a9956..82527cd9e6 100644 --- a/web/landing/tests/Flow/Website/Tests/Functional/HomeControllerTest.php +++ b/web/landing/tests/Flow/Website/Tests/Functional/HomeControllerTest.php @@ -7,6 +7,9 @@ use Flow\Website\Kernel; use Override; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; +use Symfony\Component\DomCrawler\Crawler; + +use function str_contains; final class HomeControllerTest extends WebTestCase { @@ -49,6 +52,24 @@ public function test_homepage_topic_link_works(): void self::assertResponseIsSuccessful(); } + public function test_not_found_page_links_to_docs_examples_and_search(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/404.html'); + + self::assertResponseIsSuccessful(); + static::assertGreaterThan(0, $crawler->filter('main a[href="/documentation"]')->count()); + static::assertGreaterThan(0, $crawler->filter('main a[href^="/reading/array/"]')->count()); + static::assertGreaterThan(0, $crawler->filter('main button[popovertarget="search-modal"]')->count()); + static::assertCount(1, $crawler + ->filter('script') + ->reduce(static fn(Crawler $script): bool => str_contains( + $script->text(), + "window.posthog.capture('site:not_found_view')", + ))); + static::assertSame(1, $crawler->filter('meta[name="robots"][content="noindex"]')->count()); + } + public function test_sponsor_page_sends_sponsors_to_the_work_shop(): void { $client = self::createClient(); From f6f390df544762c56fda3a6f874b87bcd01dec8e Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Tue, 17 Nov 2026 20:36:10 -0600 Subject: [PATCH 2/5] fix(flow-php/cli): phar build with a composer wrapper - box runs composer without the secrets wrapper - cli package restored on every exit --- bin/build-phar.sh | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/bin/build-phar.sh b/bin/build-phar.sh index 2d2f4354f8..2a9e7575c2 100755 --- a/bin/build-phar.sh +++ b/bin/build-phar.sh @@ -3,6 +3,13 @@ set -e CLI_DIR="src/cli" +restore_cli_package() { + composer config repositories --unset --working-dir="$CLI_DIR" + rm -rf "$CLI_DIR/vendor" +} + +trap restore_cli_package EXIT + composer config repositories.local-etl '{"type": "path", "url": "../core/etl", "options": {"symlink": false}}' --working-dir="$CLI_DIR" composer config repositories.local-adapter-csv '{"type": "path", "url": "../adapter/etl-adapter-csv", "options": {"symlink": false}}' --working-dir="$CLI_DIR" composer config repositories.local-adapter-parquet '{"type": "path", "url": "../adapter/etl-adapter-parquet", "options": {"symlink": false}}' --working-dir="$CLI_DIR" @@ -29,8 +36,5 @@ rm -rf "$CLI_DIR/vendor" composer update --no-dev --working-dir="$CLI_DIR" -tools/box/vendor/bin/box compile --config "$CLI_DIR/box.json" - -composer config repositories --unset --working-dir="$CLI_DIR" - -rm -rf "$CLI_DIR/vendor" +# Box runs composer in a temporary directory, where a composer wrapper that reads secrets finds no configuration +COMPOSER_AUTH="${COMPOSER_AUTH:-"{}"}" tools/box/vendor/bin/box compile --config "$CLI_DIR/box.json" From b0152956c0b84e79425a46c36dc93386aec69187 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Tue, 17 Nov 2026 20:48:12 -0600 Subject: [PATCH 3/5] fix(flow-php/web): playground file names rendered as text - workspace tree built with dom nodes, not an html string - a file name with markup no longer becomes markup in the page --- .../playground_workspace_controller.js | 54 ++++++++++--------- .../Functional/PlaygroundWorkspaceTest.php | 48 +++++++++++++++++ 2 files changed, 77 insertions(+), 25 deletions(-) diff --git a/web/landing/assets/controllers/playground_workspace_controller.js b/web/landing/assets/controllers/playground_workspace_controller.js index 34de26e743..4033ae9851 100644 --- a/web/landing/assets/controllers/playground_workspace_controller.js +++ b/web/landing/assets/controllers/playground_workspace_controller.js @@ -103,7 +103,7 @@ export default class extends Controller { return } - this.treeTarget.innerHTML = this.#renderFileTree(tree) + this.treeTarget.replaceChildren(this.#renderFileTree(tree)) this.#populateDropdown(tree) this.#treeRendered = true @@ -145,7 +145,8 @@ export default class extends Controller { } #renderFileTree(tree, level = 0) { - let html = '
    ' + const list = document.createElement('ul') + list.className = 'file-tree' const entries = Object.values(tree).sort((a, b) => { if (a.type === 'directory' && b.type !== 'directory') return -1 @@ -154,33 +155,36 @@ export default class extends Controller { }) for (const entry of entries) { - const indent = level * 16 + const isDirectory = entry.type === 'directory' - if (entry.type === 'directory') { - html += ` -
  • - - ${entry.name} -
  • - ` - - if (entry.children && Object.keys(entry.children).length > 0) { - html += this.#renderFileTree(entry.children, level + 1) - } - } else { - html += ` -
  • - - ${entry.name} -
  • - ` + const item = document.createElement('li') + item.className = isDirectory ? 'file-tree-item directory' : 'file-tree-item file clickable' + item.style.paddingLeft = `${level * 16}px` + + if (!isDirectory) { + item.dataset.action = 'click->playground-tabs#openFile' + item.dataset.filePath = entry.path + } + + const icon = document.createElement('img') + icon.src = isDirectory ? this.folderIconValue : this.fileIconValue + icon.className = 'icon' + icon.width = 16 + icon.height = 16 + icon.alt = '' + + const name = document.createElement('span') + name.textContent = entry.name + + item.append(icon, name) + list.append(item) + + if (isDirectory && entry.children && Object.keys(entry.children).length > 0) { + list.append(this.#renderFileTree(entry.children, level + 1)) } } - html += '
' - return html + return list } #updateSelectedState() { diff --git a/web/landing/tests/Flow/Website/Tests/Functional/PlaygroundWorkspaceTest.php b/web/landing/tests/Flow/Website/Tests/Functional/PlaygroundWorkspaceTest.php index ba27bdcd0d..46896481a9 100644 --- a/web/landing/tests/Flow/Website/Tests/Functional/PlaygroundWorkspaceTest.php +++ b/web/landing/tests/Flow/Website/Tests/Functional/PlaygroundWorkspaceTest.php @@ -4,6 +4,9 @@ namespace Flow\Website\Tests\Functional; +use function Flow\Types\DSL\type_list; +use function Flow\Types\DSL\type_string; + final class PlaygroundWorkspaceTest extends EndToEndTestCase { private const UPLOAD_INPUT = '[data-playground-upload-target="fileInput"]'; @@ -52,6 +55,51 @@ public function test_file_browser_updates_after_code_creates_files(): void ); } + public function test_names_with_markup_are_shown_as_text(): void + { + $browser = $this->openPlayground('/playground'); + $page = $this->pageOf($browser); + + $this->setPlaygroundCode($page, <<<'PHP' + x.txt', 'probe'); + mkdir('/workspace/output/d'); + file_put_contents('/workspace/output/d/inner.txt', 'probe'); + file_put_contents('/workspace/output/a" data-pwe-probe="1.txt', 'probe'); + echo 'Probe written'; + PHP); + + $page->evaluate('() => document.getElementById("action-run").click()'); + $browser->waitUntilSeeIn('[data-playground-output-target="container"]', 'Probe written'); + $page->evaluate( + '() => window.Stimulus.getControllerForElementAndIdentifier(document.getElementById("playground"), "playground-workspace").refreshTree()', + ); + + $tree = type_string()->assert($page->evaluate( + '() => document.querySelector(\'[data-playground-workspace-target="tree"]\').textContent', + )); + + static::assertTrue($page->evaluate('() => document.getElementById("pwe-file") === null'), 'file name'); + static::assertStringContainsString('x.txt', $tree); + static::assertTrue($page->evaluate('() => document.getElementById("pwe-dir") === null'), 'directory name'); + static::assertStringContainsString('d', $tree); + static::assertTrue($page->evaluate('() => document.querySelector("[data-pwe-probe]") === null'), 'file path'); + static::assertContains( + '/output/a" data-pwe-probe="1.txt', + type_list(type_string()) + ->assert($page->evaluate( + '() => [...document.querySelectorAll(".file-tree-item.file")].map(item => item.dataset.filePath)', + )), + ); + + $page->evaluate( + '(path) => [...document.querySelectorAll(".file-tree-item.file")].find(item => item.dataset.filePath === path).click()', + '/output/a" data-pwe-probe="1.txt', + ); + + $browser->waitUntilSeeIn('[data-playground-tabs-target="previewTabName"]', 'a" data-pwe-probe="1.txt'); + } + public function test_workspace_displays_default_structure(): void { $browser = $this->openPlayground('/playground'); From e40264551774eb2ce5e149c0089526347e6a5756 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Wed, 18 Nov 2026 09:52:59 -0600 Subject: [PATCH 4/5] feat(flow-php/web): site and playground analytics events - posthog loader served from /posthog.js, also on the api reference - site:code_copy event, copy button on documentation code blocks - playground events for runtime load, run, share, snippet open, upload - playground containers with user data masked from autocapture - link location and call to action attributes, packagist links - example page copy button copies the code again --- phpdoc/.phpdoc/template/layout.html.twig | 1 + .../controllers/clipboard_controller.js | 6 +- .../controllers/code_editor_controller.js | 11 ++- .../controllers/playground_controller.js | 12 +++ .../controllers/playground_run_controller.js | 11 ++- .../playground_share_controller.js | 51 +++++++----- .../playground_upload_controller.js | 23 ++++- .../assets/controllers/wasm_controller.js | 43 +++++++++- .../Website/Controller/HomeController.php | 6 ++ .../Service/Markdown/FlowCodeRenderer.php | 45 ++++++++-- .../LeagueCommonMarkConverterFactory.php | 2 +- web/landing/templates/base.html.twig | 12 +-- .../documentation/dsl/function.html.twig | 2 +- .../templates/documentation/example.html.twig | 4 +- web/landing/templates/example/index.html.twig | 7 +- web/landing/templates/main/_hero.html.twig | 10 ++- web/landing/templates/main/index.html.twig | 4 +- .../templates/main/not_found.html.twig | 3 +- web/landing/templates/main/posthog.js.twig | 9 ++ .../templates/partials/footer.html.twig | 3 +- .../templates/partials/header.html.twig | 4 +- .../playground/_playground.html.twig | 20 +++-- .../Website/Tests/Functional/CodeCopyTest.php | 37 +++++++++ .../Tests/Functional/EndToEndTestCase.php | 45 ++++++++++ .../Functional/ExamplePlaygroundTest.php | 42 ++++++++++ .../Functional/ExamplesControllerTest.php | 12 +++ .../Tests/Functional/HomeControllerTest.php | 54 +++++++++++- .../Functional/PlaygroundControllerTest.php | 37 +++++++++ .../Functional/PlaygroundRunCodeTest.php | 46 ++++++++++ .../Functional/PlaygroundSnippetTest.php | 17 +++- .../Tests/Functional/PlaygroundUploadTest.php | 37 +++++++++ .../Tests/Functional/PostHogRecordingTest.php | 26 ++++++ .../Integration/ApiReferenceLoaderTest.php | 22 +++++ .../Service/Markdown/FlowCodeRendererTest.php | 83 +++++++++++++++++++ 34 files changed, 668 insertions(+), 79 deletions(-) create mode 100644 web/landing/templates/main/posthog.js.twig create mode 100644 web/landing/tests/Flow/Website/Tests/Functional/CodeCopyTest.php create mode 100644 web/landing/tests/Flow/Website/Tests/Functional/PlaygroundControllerTest.php create mode 100644 web/landing/tests/Flow/Website/Tests/Functional/PostHogRecordingTest.php create mode 100644 web/landing/tests/Flow/Website/Tests/Integration/ApiReferenceLoaderTest.php create mode 100644 web/landing/tests/Flow/Website/Tests/Unit/Service/Markdown/FlowCodeRendererTest.php diff --git a/phpdoc/.phpdoc/template/layout.html.twig b/phpdoc/.phpdoc/template/layout.html.twig index 35a06e7d1c..2f42e2f30f 100644 --- a/phpdoc/.phpdoc/template/layout.html.twig +++ b/phpdoc/.phpdoc/template/layout.html.twig @@ -22,6 +22,7 @@ {% endblock %} {% block javascripts %} + diff --git a/web/landing/assets/controllers/clipboard_controller.js b/web/landing/assets/controllers/clipboard_controller.js index 7474526fa2..c0ca9e6c79 100644 --- a/web/landing/assets/controllers/clipboard_controller.js +++ b/web/landing/assets/controllers/clipboard_controller.js @@ -3,6 +3,8 @@ import ClipboardJS from 'clipboard'; export default class extends Controller { + static values = { kind: String } + connect() { if (!ClipboardJS.isSupported()) { @@ -18,6 +20,8 @@ export default class extends Controller this.element.classList.add('copied'); setTimeout(() => this.element.classList.remove('copied'), 2000); + + window.posthog?.capture('site:code_copy', { code_kind: this.kindValue }); }); } -} \ No newline at end of file +} diff --git a/web/landing/assets/controllers/code_editor_controller.js b/web/landing/assets/controllers/code_editor_controller.js index e4dd636a96..84f8ffc666 100644 --- a/web/landing/assets/controllers/code_editor_controller.js +++ b/web/landing/assets/controllers/code_editor_controller.js @@ -1,6 +1,6 @@ import { Controller } from "@hotwired/stimulus" import { EditorView, basicSetup } from "codemirror" -import { EditorState, StateField, StateEffect, Compartment, Prec } from "@codemirror/state" +import { EditorState, StateField, StateEffect, Compartment, Prec, Transaction } from "@codemirror/state" import { Decoration } from "@codemirror/view" import { keymap } from "@codemirror/view" import { php } from "@codemirror/lang-php" @@ -17,6 +17,7 @@ export default class extends Controller { #textarea #errorEffect #editorReady = false + #codeModified = false #themeCompartment = new Compartment() #onThemeChanged = null @@ -74,6 +75,10 @@ export default class extends Controller { flowTooltips, EditorView.updateListener.of((update) => { if (update.docChanged) { + if (update.transactions.some(transaction => transaction.annotation(Transaction.userEvent) !== undefined)) { + this.#codeModified = true + } + this.#textarea.value = update.state.doc.toString() this.dispatch('code-changed', { bubbles: true }) } @@ -143,6 +148,10 @@ export default class extends Controller { } } + isCodeModified() { + return this.#codeModified + } + getCode() { return this.#editor ? this.#editor.state.doc.toString() : '' } diff --git a/web/landing/assets/controllers/playground_controller.js b/web/landing/assets/controllers/playground_controller.js index 3456eea4bf..ecab1499bd 100644 --- a/web/landing/assets/controllers/playground_controller.js +++ b/web/landing/assets/controllers/playground_controller.js @@ -1,5 +1,13 @@ import { Controller } from "@hotwired/stimulus" +const POSTHOG_EVENTS = { + 'wasm:runtime-load': 'playground:runtime_load', + 'playground-run:code-run': 'playground:code_run', + 'playground-share:snippet-share': 'playground:snippet_share', + 'playground-share:snippet-open': 'playground:snippet_open', + 'playground-upload:file-upload': 'playground:file_upload', +} + export default class extends Controller { static outlets = ["wasm", "code-editor", "turnstile", "playground-output", "playground-tabs"] static targets = ["loadingMessage", "loadingBar", "loadingPercent", "navigation", "editor", "outputContainer", "storageIndicator", "actionSpinner"] @@ -13,6 +21,10 @@ export default class extends Controller { this.#log('Connecting playground controller') } + capture({ type, detail }) { + window.posthog?.capture(POSTHOG_EVENTS[type], detail) + } + onNotification(event) { const { message, type } = event.detail if (this.hasPlaygroundOutputOutlet) { diff --git a/web/landing/assets/controllers/playground_run_controller.js b/web/landing/assets/controllers/playground_run_controller.js index 708ecc4678..037b3ebb97 100644 --- a/web/landing/assets/controllers/playground_run_controller.js +++ b/web/landing/assets/controllers/playground_run_controller.js @@ -2,6 +2,7 @@ import { Controller } from "@hotwired/stimulus" export default class extends Controller { static outlets = ["code-editor", "wasm", "playground-output"] + static values = { isExample: { type: Boolean, default: false } } async run() { this.dispatch('action-started', { bubbles: true }) @@ -37,8 +38,14 @@ export default class extends Controller { } } - this.dispatch('executed', { - detail: { success: result.success, executionTime: result.executionTime }, + this.dispatch('code-run', { + detail: { + is_success: result.success, + duration_ms: result.executionTime, + failure_reason: result.failureReason, + is_example: this.isExampleValue, + is_code_modified: this.codeEditorOutlet.isCodeModified() + }, bubbles: true }) } finally { diff --git a/web/landing/assets/controllers/playground_share_controller.js b/web/landing/assets/controllers/playground_share_controller.js index caed0228d2..b6df965b13 100644 --- a/web/landing/assets/controllers/playground_share_controller.js +++ b/web/landing/assets/controllers/playground_share_controller.js @@ -14,8 +14,6 @@ export default class extends Controller { #wasmResourcesLoaded = false #pendingSnippetLoad = false #defaultFingerprint = null - #exampleCodeModified = false - #boundHandleExampleLoaded = null connect() { this.#debug = this.application.debug @@ -24,25 +22,12 @@ export default class extends Controller { this.#boundHandleCodeChanged = this.#handleCodeChanged.bind(this) this.element.addEventListener('code-editor:code-changed', this.#boundHandleCodeChanged) - - this.#boundHandleExampleLoaded = this.#handleExampleLoaded.bind(this) - this.element.addEventListener('playground-storage:loaded-from-example', this.#boundHandleExampleLoaded) } disconnect() { if (this.#boundHandleCodeChanged) { this.element.removeEventListener('code-editor:code-changed', this.#boundHandleCodeChanged) } - if (this.#boundHandleExampleLoaded) { - this.element.removeEventListener('playground-storage:loaded-from-example', this.#boundHandleExampleLoaded) - } - } - - #handleExampleLoaded() { - // Reset the modified flag when example is initially loaded - // This prevents the initial setCode() call from marking example as modified - this.#exampleCodeModified = false - this.#log('Example loaded, reset exampleCodeModified flag') } async onWasmResourcesLoaded() { @@ -130,6 +115,8 @@ export default class extends Controller { } async #loadSnippetFromR2(snippetId) { + let failureReason = 'other' + try { const snippetsBaseUrl = this.snippetsUrlValue const baseUrl = `${snippetsBaseUrl}/snippets/${snippetId}` @@ -139,6 +126,7 @@ export default class extends Controller { const metadataResponse = await fetch(metadataUrl) if (!metadataResponse.ok) { + failureReason = 'not_found' throw new Error(`Snippet not found (HTTP ${metadataResponse.status})`) } @@ -146,12 +134,14 @@ export default class extends Controller { const expiresAt = new Date(metadata.expires_at) if (Date.now() > expiresAt.getTime()) { + failureReason = 'expired' throw new Error('Snippet has expired') } const codeUrl = `${baseUrl}/code.php` const codeResponse = await fetch(codeUrl) if (!codeResponse.ok) { + failureReason = 'code_missing' throw new Error('Code file not found') } const code = await codeResponse.text() @@ -177,6 +167,7 @@ export default class extends Controller { if (!this.wasmOutlet.areResourcesLoaded()) { this.#showNotification('WASM resources failed to load, datasets not loaded', 'error') + this.#reportOpen(null) return } this.#log('WASM resources loaded, proceeding with dataset upload') @@ -233,8 +224,9 @@ export default class extends Controller { this.#showNotification('Snippet loaded successfully!', 'success') this.#snippetLoaded = true - + this.#reportOpen(null) } catch (error) { + this.#reportOpen(failureReason) console.error('[ShareCode] Failed to load snippet:', error) this.#showNotification(`Failed to load snippet: ${error.message}`, 'error') } @@ -243,6 +235,8 @@ export default class extends Controller { async share() { this.dispatch('action-started', { bubbles: true }) + let files = [] + try { // First, wait only for code-editor and wasm (NOT turnstile yet) await Promise.all([ @@ -250,13 +244,14 @@ export default class extends Controller { this.wasmOutlet.onLoad() ]) - const files = await this.#collectUploadedFiles() + files = await this.#collectUploadedFiles() // Check for unmodified example BEFORE requiring Turnstile - if (this.isExampleValue && !this.#exampleCodeModified && files.length === 0) { + if (this.isExampleValue && !this.codeEditorOutlet.isCodeModified() && files.length === 0) { const exampleUrl = `${window.location.origin}${window.location.pathname}` await this.#copyToClipboard(exampleUrl) this.#showNotification('Example link copied to clipboard!', 'success', exampleUrl) + this.#reportShare('example_link', files.length) return } @@ -275,6 +270,7 @@ export default class extends Controller { if (this.#defaultFingerprint && fingerprint === this.#defaultFingerprint) { this.#log('Code matches default, not uploading') this.#showNotification('You are trying to share default code. Please modify the code first.', 'info') + this.#reportShare('refused', files.length) return } @@ -293,11 +289,14 @@ export default class extends Controller { await this.#copyToClipboard(shareUrl) this.#showNotification('Snippet already exists! Link copied to clipboard.', 'success', shareUrl) + this.#reportShare('exists', files.length) return } await this.#uploadSnippetToAPI(code, fingerprint, files) + this.#reportShare('created', files.length) } catch (error) { + this.#reportShare('failed', files.length) console.error('[ShareCode] Share failed:', error) console.error('[ShareCode] Error stack:', error.stack) this.#logError('[ShareCode] Share failed:', error) @@ -378,12 +377,18 @@ export default class extends Controller { } } - #handleCodeChanged() { - // Mark example as modified when code changes - if (this.isExampleValue) { - this.#exampleCodeModified = true - } + #reportShare(outcome, fileCount) { + this.dispatch('snippet-share', { detail: { outcome, file_count: fileCount }, bubbles: true }) + } + #reportOpen(failureReason) { + this.dispatch('snippet-open', { + detail: { is_success: failureReason === null, failure_reason: failureReason }, + bubbles: true + }) + } + + #handleCodeChanged() { if (this.#snippetLoaded) { this.#log('Code changed, clearing snippet URL from browser') const cleanUrl = `${window.location.origin}${window.location.pathname}` diff --git a/web/landing/assets/controllers/playground_upload_controller.js b/web/landing/assets/controllers/playground_upload_controller.js index db2c61d6f3..2a99a94b6d 100644 --- a/web/landing/assets/controllers/playground_upload_controller.js +++ b/web/landing/assets/controllers/playground_upload_controller.js @@ -27,6 +27,7 @@ export default class extends Controller { const validation = this.#validate(file) if (!validation.valid) { this.playgroundOutputOutlet.show({ content: validation.error, type: 'error' }) + this.#reportUpload(file, validation.failureReason) return } @@ -42,6 +43,22 @@ export default class extends Controller { this.playgroundOutputOutlet.show({ content: `File uploaded: ${file.name}`, type: 'success' }) this.dispatch('file-uploaded', { detail: { filename: file.name, size: file.size }, bubbles: true }) } + + this.#reportUpload(file, result.success ? null : 'write') + } + + #reportUpload(file, failureReason) { + const extension = file.name.split('.').pop().toLowerCase() + + this.dispatch('file-upload', { + detail: { + is_success: failureReason === null, + file_extension: this.allowedExtensionsValue.includes(extension) ? extension : 'other', + file_size: file.size, + failure_reason: failureReason + }, + bubbles: true + }) } async handleFileUpload(event) { @@ -96,16 +113,16 @@ export default class extends Controller { #validate(file) { const filenameCheck = this.#validateFilename(file.name) if (!filenameCheck.valid) { - return filenameCheck + return { ...filenameCheck, failureReason: 'filename' } } if (file.size > this.maxFileSizeValue) { - return { valid: false, error: `File too large: ${file.name} (max 2MB)` } + return { valid: false, error: `File too large: ${file.name} (max 2MB)`, failureReason: 'size' } } const ext = file.name.split('.').pop().toLowerCase() if (!this.allowedExtensionsValue.includes(ext)) { - return { valid: false, error: `Invalid extension: ${ext}` } + return { valid: false, error: `Invalid extension: ${ext}`, failureReason: 'extension' } } return { valid: true } diff --git a/web/landing/assets/controllers/wasm_controller.js b/web/landing/assets/controllers/wasm_controller.js index 651bb7d43b..6199632e59 100644 --- a/web/landing/assets/controllers/wasm_controller.js +++ b/web/landing/assets/controllers/wasm_controller.js @@ -15,6 +15,7 @@ export default class extends Controller { #combinedOutput = '' #debug = false #recycleCount = 0 + #runtimeLoadReported = false connect() { this.#debug = this.application.debug @@ -66,10 +67,13 @@ export default class extends Controller { this.#combinedOutput = '' + const startedAt = performance.now() + try { this.#phpModule.FS.chdir('/workspace') const exitCode = this.#phpModule.ccall('pib_eval', 'number', ['string'], [code]) + const executionTime = Math.round(performance.now() - startedAt) const errorInfo = this.#parseErrorMessage(this.#combinedOutput) @@ -85,7 +89,8 @@ export default class extends Controller { }, output: this.#combinedOutput, exitCode, - executionTime: 0, + executionTime, + failureReason: this.#runFailureReason(this.#combinedOutput), memoryUsed: 0 } } @@ -94,7 +99,8 @@ export default class extends Controller { success: true, output: this.#combinedOutput || 'Code executed successfully (no output)', exitCode, - executionTime: 0, + executionTime, + failureReason: null, memoryUsed: 0 } } catch (e) { @@ -107,7 +113,8 @@ export default class extends Controller { }, output: this.#combinedOutput, exitCode: 1, - executionTime: 0, + executionTime: Math.round(performance.now() - startedAt), + failureReason: 'other', memoryUsed: 0 } } @@ -362,6 +369,7 @@ export default class extends Controller { return true } catch (error) { this.#logError('Failed to load resources:', error) + this.#reportRuntimeLoad('resources') this.#dispatchError('Failed to load resources: ' + error.message) return false } @@ -417,16 +425,19 @@ export default class extends Controller { await this.#loadResources() }).catch((err) => { this.#logError('Failed to initialize PHP module:', err) + this.#reportRuntimeLoad('instantiate') this.#dispatchError('Failed to initialize PHP: ' + err.message) }) } else { this.#logError('PHP function not available after script load') + this.#reportRuntimeLoad('runtime_missing') this.#dispatchError('Failed to load PHP module') } } script.onerror = (err) => { this.#logError('Failed to load PHP script:', err) + this.#reportRuntimeLoad('script') this.#dispatchError('Failed to load PHP WebAssembly module') } @@ -550,6 +561,32 @@ export default class extends Controller { #dispatchInitialized() { this.dispatch('initialized') + this.#reportRuntimeLoad(null) + } + + #reportRuntimeLoad(failureReason) { + if (this.#runtimeLoadReported) { + return + } + + this.#runtimeLoadReported = true + this.dispatch('runtime-load', { + detail: { + is_success: failureReason === null, + duration_ms: Math.round(performance.now()), + failure_reason: failureReason + } + }) + } + + #runFailureReason(output) { + const thrown = output.match(/Uncaught throwable '([^']+)'/) + + if (!thrown || thrown[1] === 'ParseError') { + return 'parse' + } + + return thrown[1].startsWith('Flow\\') ? 'flow' : 'php' } #dispatchResourcesLoaded() { diff --git a/web/landing/src/Flow/Website/Controller/HomeController.php b/web/landing/src/Flow/Website/Controller/HomeController.php index 048ef65717..3373fd6325 100644 --- a/web/landing/src/Flow/Website/Controller/HomeController.php +++ b/web/landing/src/Flow/Website/Controller/HomeController.php @@ -29,6 +29,12 @@ public function notFound(): Response return $this->render('main/not_found.html.twig', []); } + #[Route('/posthog.js', name: 'posthog_loader', options: ['sitemap' => false])] + public function posthogLoader(): Response + { + return $this->render('main/posthog.js.twig', [], new Response(headers: ['Content-Type' => 'text/javascript'])); + } + #[Route('/sponsor', name: 'sponsor', options: ['sitemap' => false])] public function sponsor(): Response { diff --git a/web/landing/src/Flow/Website/Service/Markdown/FlowCodeRenderer.php b/web/landing/src/Flow/Website/Service/Markdown/FlowCodeRenderer.php index 1f7b92ecdc..9b03fbf709 100644 --- a/web/landing/src/Flow/Website/Service/Markdown/FlowCodeRenderer.php +++ b/web/landing/src/Flow/Website/Service/Markdown/FlowCodeRenderer.php @@ -10,6 +10,7 @@ use League\CommonMark\Renderer\ChildNodeRendererInterface; use League\CommonMark\Renderer\NodeRendererInterface; use League\CommonMark\Util\HtmlElement; +use Symfony\Component\Asset\Packages; use function array_key_exists; use function Flow\Types\DSL\type_boolean; @@ -20,6 +21,10 @@ class FlowCodeRenderer implements NodeRendererInterface { + public function __construct( + private readonly Packages $packages, + ) {} + public function render(Node $node, ChildNodeRendererInterface $childRenderer) { if (!$node instanceof FencedCode) { @@ -39,13 +44,39 @@ public function render(Node $node, ChildNodeRendererInterface $childRenderer) ? type_string()->assert($attrs['class']) . ' ' . $class : $class; - // Escape the code content - $escapedContent = htmlspecialchars($node->getLiteral(), ENT_NOQUOTES, 'UTF-8'); - - // Render as
content
- $codeElement = new HtmlElement('code', $attrs, $escapedContent); + $codeId = 'code-' . substr(hash('xxh3', $node->getLiteral()), 0, 12); - // Render as
content
- return new HtmlElement('pre', array_merge($attrs, ['data-controller' => 'syntax-highlight']), $codeElement); + return new HtmlElement( + 'div', + ['class' => 'relative'], + [ + new HtmlElement( + 'button', + [ + 'class' => "absolute top-3 right-3 inline-flex items-center justify-center h-9 w-9 rounded-md border border-slate-300 bg-white hover:bg-slate-50 text-slate-700 [&.copied]:before:content-['Copied!'] before:absolute before:-translate-x-20 dark:border-white/10 dark:bg-black/60 dark:hover:bg-black/80 dark:text-white", + 'data-controller' => 'clipboard', + 'data-clipboard-kind-value' => 'documentation', + 'data-clipboard-target' => '#' . $codeId, + 'aria-label' => 'Copy code', + ], + new HtmlElement( + 'img', + [ + 'src' => $this->packages->getUrl('images/icons/copy.svg'), + 'alt' => '', + 'width' => '16', + 'height' => '16', + 'class' => 'dark:invert-0 invert', + ], + selfClosing: true, + ), + ), + new HtmlElement( + 'pre', + array_merge($attrs, ['id' => $codeId, 'data-controller' => 'syntax-highlight']), + new HtmlElement('code', $attrs, htmlspecialchars($node->getLiteral(), ENT_NOQUOTES, 'UTF-8')), + ), + ], + ); } } diff --git a/web/landing/src/Flow/Website/Service/Markdown/LeagueCommonMarkConverterFactory.php b/web/landing/src/Flow/Website/Service/Markdown/LeagueCommonMarkConverterFactory.php index 25d4fa3587..4c02ddfde5 100644 --- a/web/landing/src/Flow/Website/Service/Markdown/LeagueCommonMarkConverterFactory.php +++ b/web/landing/src/Flow/Website/Service/Markdown/LeagueCommonMarkConverterFactory.php @@ -78,7 +78,7 @@ public function __invoke(): CommonMarkConverter ->addExtension(new MentionExtension()) ->addExtension(new TableExtension()) ->addRenderer(FencedCode::class, new MermaidCodeRenderer($this->packages), 100) - ->addRenderer(FencedCode::class, new FlowCodeRenderer(), 0) + ->addRenderer(FencedCode::class, new FlowCodeRenderer($this->packages), 0) ->addRenderer(Link::class, new FlowLinkRenderer(), 0) ->addRenderer(TableOfContents::class, new TableOfContentsRenderer(), 10) ->addEventListener( diff --git a/web/landing/templates/base.html.twig b/web/landing/templates/base.html.twig index c68b3d373a..640304ecf1 100644 --- a/web/landing/templates/base.html.twig +++ b/web/landing/templates/base.html.twig @@ -58,17 +58,7 @@ {% endblock %} {% block tracking %} - {% if posthog_key|length %} - - {% endif %} + {% endblock %} {% block javascripts %} diff --git a/web/landing/templates/documentation/dsl/function.html.twig b/web/landing/templates/documentation/dsl/function.html.twig index 470c0383e7..6cf16edb32 100644 --- a/web/landing/templates/documentation/dsl/function.html.twig +++ b/web/landing/templates/documentation/dsl/function.html.twig @@ -92,7 +92,7 @@ title="copy code" aria-label="Copy code" data-clipboard-target="#example-code-{{ loop.index }}" - {{ stimulus_controller('clipboard') }}> + {{ stimulus_controller('clipboard', { kind: 'dsl_function' }) }}> diff --git a/web/landing/templates/documentation/example.html.twig b/web/landing/templates/documentation/example.html.twig index 5e82fa080e..113d7623ef 100644 --- a/web/landing/templates/documentation/example.html.twig +++ b/web/landing/templates/documentation/example.html.twig @@ -71,10 +71,10 @@ -
{{- code | escape('html') -}}
+
{{- code | escape('html') -}}
{% endapply %} diff --git a/web/landing/templates/example/index.html.twig b/web/landing/templates/example/index.html.twig index f442c7970d..09507e9b3b 100644 --- a/web/landing/templates/example/index.html.twig +++ b/web/landing/templates/example/index.html.twig @@ -98,6 +98,7 @@
-
-                        
+                    
+                        
                             {{- code | escape('html') -}}
                         
                     
diff --git a/web/landing/templates/main/_hero.html.twig b/web/landing/templates/main/_hero.html.twig index 264c2a9a84..fbb7f04004 100644 --- a/web/landing/templates/main/_hero.html.twig +++ b/web/landing/templates/main/_hero.html.twig @@ -1,4 +1,4 @@ -
+
@@ -19,11 +19,11 @@

- + Try Playground - + Read the docs @@ -38,10 +38,12 @@ title="copy command" aria-label="Copy install command" data-clipboard-target="#command" - {{ stimulus_controller('clipboard') }}> + {{ stimulus_controller('clipboard', { kind: 'install_command' }) }}>
+ View on Packagist

diff --git a/web/landing/templates/main/index.html.twig b/web/landing/templates/main/index.html.twig index 4d833fdb52..7f3b8c51a5 100644 --- a/web/landing/templates/main/index.html.twig +++ b/web/landing/templates/main/index.html.twig @@ -203,11 +203,11 @@ data_frame()

diff --git a/web/landing/templates/main/not_found.html.twig b/web/landing/templates/main/not_found.html.twig index 10f3b05055..f91dbe107c 100644 --- a/web/landing/templates/main/not_found.html.twig +++ b/web/landing/templates/main/not_found.html.twig @@ -50,6 +50,5 @@ - {# Inline until the site has a shared tracking module. #} - + {% endblock %} diff --git a/web/landing/templates/main/posthog.js.twig b/web/landing/templates/main/posthog.js.twig new file mode 100644 index 0000000000..e15f7fffc4 --- /dev/null +++ b/web/landing/templates/main/posthog.js.twig @@ -0,0 +1,9 @@ +{% if posthog_key|length %} +!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group identify setPersonProperties setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags resetGroups onFeatureFlags addFeatureFlagsHandler onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep".split(" "),n=0;n +