Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/playground-v2/src/exporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ export function configureExports(options: { project(): ExportProject; compile():
throw new Error(`Unknown export: ${action}`)
}
}

return { showLink: () => perform("link") }
}

function element<T extends HTMLElement>(id: string) {
Expand Down
1 change: 1 addition & 0 deletions packages/playground-v2/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ <h1><a href="/">TypeScript</a> Playground v2</h1>
<button id="clear-project-button" class="action-button" type="button" title="Start with an empty project">Clear</button>
<button id="settings-button" class="action-button" type="button">Settings</button>
<output id="status" class="status" hidden></output>
<output id="shortcut-toast" class="shortcut-toast" role="status" aria-live="polite" hidden></output>
</div>
</header>
<section class="workspace" aria-label="TypeScript playground">
Expand Down
56 changes: 49 additions & 7 deletions packages/playground-v2/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ const clearRunOutput = getElement<HTMLButtonElement>("clear-run-output")
const runOutput = getElement("run-output")
const runLog = getElement("run-log")
const status = getElement("status")
const shortcutToast = getElement("shortcut-toast")
const loader = getElement("loader")
const loadingAnimation = getElement("loading-animation")
const loadingCopy = getElement("loading-copy")
Expand Down Expand Up @@ -459,6 +460,33 @@ inputEditor.addAction({
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
run: runProject,
})
document.addEventListener(
"keydown",
event => {
if (!(event.ctrlKey || event.metaKey) || event.altKey || event.key.toLowerCase() !== "s") return
event.preventDefault()
if (event.repeat) return
void (async () => {
try {
const link = projectUrl(currentProjectState())
history.replaceState({}, "", link)
persistProjectState(true)
try {
await navigator.clipboard.writeText(link)
showShortcutToast("Playground link copied to clipboard.")
} catch {
await exportActions.showLink()
}
} catch (error) {
projectFailure = `Could not save the Playground link: ${error instanceof Error ? error.message : String(error)}`
console.error("Could not save the TypeScript Playground link", error)
renderStatus()
showShortcutToast("Could not save the Playground link.")
}
})()
},
{ capture: true }
)
const inlayEmitter = new monaco.Emitter<void>()
const typeQueries = new Map<string, TypeQuery[]>()
// Monaco subscribes to refresh events only after its first hint request completes.
Expand Down Expand Up @@ -820,12 +848,10 @@ monaco.languages.registerInlayHintsProvider("json", {
})

let updateTimer = 0
configureExports({
const exportActions = configureExports({
compile: () => compileActiveProject?.(),
project() {
const state = currentProjectState()
const url = new URL(location.href)
url.hash = `${projectHashPrefix.slice(1)}${LZString.compressToEncodedURIComponent(serializeProjectState(state))}`
return {
activeFile: relativeProjectPath(
state.activeFile && state.files[state.activeFile] !== undefined
Expand All @@ -843,7 +869,7 @@ configureExports({
symlinks: Object.fromEntries(
Object.entries(projectSymlinks).map(([path, target]) => [relativeProjectPath(path), target])
),
url: url.href,
url: projectUrl(state),
}
},
})
Expand Down Expand Up @@ -2593,6 +2619,16 @@ function restoreProjectSelection(state: ProjectState) {
inputEditor.revealRangeInCenter(inputEditor.getSelection()!, monaco.editor.ScrollType.Immediate)
}

let shortcutToastTimer = 0
function showShortcutToast(message: string) {
shortcutToast.textContent = message
shortcutToast.hidden = false
window.clearTimeout(shortcutToastTimer)
shortcutToastTimer = window.setTimeout(() => {
shortcutToast.hidden = true
}, 2000)
}

function renderStatus() {
const failure = compilerFailure ?? lspFailure
const error = failure ?? projectFailure ?? (typeAcquisitionFailure ? `Package types: ${typeAcquisitionFailure}` : "")
Expand Down Expand Up @@ -3137,7 +3173,13 @@ function currentProjectState(): ProjectState {
}
}

function persistProjectState() {
function projectUrl(state: ProjectState) {
const url = new URL(location.href)
url.hash = `${projectHashPrefix.slice(1)}${LZString.compressToEncodedURIComponent(serializeProjectState(state))}`
return url.href
}

function persistProjectState(forceUrl = false) {
window.clearTimeout(projectPersistTimer)
window.removeEventListener("beforeunload", flushProjectBeforeUnload)
if (!projectPersistenceEnabled) return
Expand All @@ -3147,8 +3189,8 @@ function persistProjectState() {
localStorage.setItem(storageKey, serialized)
lastStoredProject = serialized
}
if (!playgroundSettings.saveToUrl || legacyQuery !== undefined) return
if (serialized === lastUrlProject) return
if (!forceUrl && (!playgroundSettings.saveToUrl || legacyQuery !== undefined)) return
if (!forceUrl && serialized === lastUrlProject) return
const url = new URL(location.href)
url.hash = `${projectHashPrefix.slice(1)}${LZString.compressToEncodedURIComponent(serialized)}`
history.replaceState({}, "", url)
Expand Down
13 changes: 13 additions & 0 deletions packages/playground-v2/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,19 @@ body {
white-space: normal;
}

.shortcut-toast {
position: fixed;
z-index: 20;
right: 1rem;
bottom: 1rem;
padding: 0.6rem 0.85rem;
border: 1px solid var(--border);
border-radius: 0.35rem;
color: inherit;
background: var(--panel);
box-shadow: 0 0.25rem 1rem rgb(0 0 0 / 25%);
}

.form-dialog {
width: min(28rem, calc(100vw - 2rem));
padding: 0;
Expand Down
Loading