Skip to content
Merged
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
32 changes: 30 additions & 2 deletions messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
"tools": "Playground tools",
"noLanguages": "Languages unavailable",
"saveDraft": "Save draft",
"palette": "Command palette"
"palette": "Command palette",
"reference": "Reference"
},
"files": {
"tabs": "Open files",
Expand Down Expand Up @@ -344,7 +345,8 @@
"toggleTheme": "Switch light or dark theme",
"toggleFileTree": "Show or hide the file list",
"shortcuts": "Show keyboard shortcuts",
"clearOutput": "Clear output"
"clearOutput": "Clear output",
"toggleReference": "Show or hide the language reference"
},
"draft": {
"saved": "Draft saved {time}",
Expand All @@ -358,5 +360,31 @@
"hint": "Sent from the start on every run.",
"tooLarge": "Input is over 64 KB and cannot be sent.",
"lines": "{count, plural, one {# line} other {# lines}}"
},
"reference": {
"title": "Language reference",
"open": "Show or hide the language reference",
"search": "Search the reference",
"searchPlaceholder": "Keyword, function or English name",
"count": "{count, plural, one {# entry} other {# entries}}",
"noMatches": "Nothing matches \"{query}\". Try another word or an English name such as for or print.",
"clearSearch": "Clear search",
"insert": "Insert",
"insertLabel": "Insert the {title} example into the editor",
"inserted": "Example inserted",
"otherLanguage": "Examples are KingSejong code. Switch the language to KingSejong to insert them.",
"switchLanguage": "Switch to KingSejong",
"source": "Based on the KingSejong language docs (v0.6)",
"categories": {
"basics": "Basics",
"operators": "Operators",
"control": "Conditions and loops",
"functions": "Functions",
"arrays": "Arrays",
"josa": "Particles",
"errors": "Errors and async",
"builtins": "Built-in functions",
"modules": "Modules and standard library"
}
}
}
32 changes: 30 additions & 2 deletions messages/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
"tools": "플레이그라운드 도구",
"noLanguages": "언어 목록 없음",
"saveDraft": "임시 저장",
"palette": "명령 팔레트"
"palette": "명령 팔레트",
"reference": "문법 참고"
},
"files": {
"tabs": "열린 파일",
Expand Down Expand Up @@ -344,7 +345,8 @@
"toggleTheme": "밝은/어두운 테마 바꾸기",
"toggleFileTree": "파일 목록 열기/닫기",
"shortcuts": "단축키 보기",
"clearOutput": "출력 지우기"
"clearOutput": "출력 지우기",
"toggleReference": "문법 참고 열기/닫기"
},
"draft": {
"saved": "임시 저장됨 {time}",
Expand All @@ -358,5 +360,31 @@
"hint": "실행할 때마다 이 내용이 처음부터 프로그램에 전달돼요.",
"tooLarge": "입력이 64KB를 넘어서 보낼 수 없어요.",
"lines": "{count}줄"
},
"reference": {
"title": "문법 참고",
"open": "문법 참고 열기/닫기",
"search": "문법 검색",
"searchPlaceholder": "키워드, 함수, 영어 이름으로 찾기",
"count": "{count, plural, other {#개 항목}}",
"noMatches": "\"{query}\"에 맞는 항목이 없어요. 다른 낱말이나 영어 이름(예: for, print)으로 찾아보세요.",
"clearSearch": "검색어 지우기",
"insert": "넣기",
"insertLabel": "{title} 예제를 편집기에 넣기",
"inserted": "예제를 넣었어요",
"otherLanguage": "예제는 킹세종 코드예요. 편집기에 넣으려면 언어를 킹세종으로 바꾸세요.",
"switchLanguage": "킹세종으로 바꾸기",
"source": "킹세종 언어 문서(v0.6) 기준",
"categories": {
"basics": "기본",
"operators": "연산자",
"control": "조건과 반복",
"functions": "함수",
"arrays": "배열",
"josa": "조사 표현",
"errors": "오류와 비동기",
"builtins": "내장 함수",
"modules": "모듈과 표준 라이브러리"
}
}
}
33 changes: 31 additions & 2 deletions src/app/[locale]/PlaygroundClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
// Components
import OutputPanel from '@/features/execution/OutputPanel';
import FileTabs from '@/features/editor/FileTabs';
import { EditorSkeleton, type EditorCommand, type RevealRequest } from '@/features/editor/CodeEditor';
import { EditorSkeleton, type EditorCommand, type InsertRequest, type RevealRequest } from '@/features/editor/CodeEditor';
import { resolveEntryFile } from '@/features/editor/entry';
import { loadDraft, saveDraft } from '@/features/editor/drafts';
import { useDraft } from '@/features/editor/useDraft';
Expand All @@ -29,7 +29,10 @@ const CodeEditor = dynamicImport(() => import('@/features/editor/CodeEditor'), {
loading: () => <EditorSkeleton />,
ssr: false,
});
const FileTree = dynamicImport(() => import('@/features/editor/FileTree'));
// Lazily loaded panels need `loading`: without it the first open suspends the whole page,
// which tears down the Monaco editor and crashes when it is recreated.
const FileTree = dynamicImport(() => import('@/features/editor/FileTree'), { loading: () => null });
const ReferencePanel = dynamicImport(() => import('@/features/reference/ReferencePanel'), { loading: () => null });

// Hooks & Context
import { useAuth } from '@/features/auth/AuthContext';
Expand Down Expand Up @@ -125,6 +128,8 @@ function PlaygroundContent({ initialLanguages }: { initialLanguages: InitialLang
const [showTemplateGallery, setShowTemplateGallery] = useState(false);
const [showSnippetLibrary, setShowSnippetLibrary] = useState(false);
const [reveal, setReveal] = useState<RevealRequest | null>(null);
const [showReference, setShowReference] = useState(false);
const [insertRequest, setInsertRequest] = useState<InsertRequest | null>(null);
const [stdin, setStdin] = useState('');
const [showStdin, setShowStdin] = useState(false);
/** File that produced the current output; its diagnostics are drawn in the editor. */
Expand Down Expand Up @@ -254,6 +259,15 @@ function PlaygroundContent({ initialLanguages }: { initialLanguages: InitialLang
[replaceCode, setSelectedLanguage, t]
);

/** Inserts a reference example at the editor cursor (undo with the editor's undo). */
const handleInsertExample = useCallback(
(code: string) => {
setInsertRequest({ text: code, nonce: Date.now() });
toast.success(t('reference.inserted'));
},
[toast, t]
);

const handleAddFile = useCallback(() => {
const fileNumber = files.length + 1;
const newFileName = `file${fileNumber}.ksj`;
Expand Down Expand Up @@ -357,6 +371,7 @@ function PlaygroundContent({ initialLanguages }: { initialLanguages: InitialLang
{ id: 'share', label: t('commands.share'), run: handleShare },
{ id: 'settings', label: t('commands.settings'), run: () => setShowSettings(true) },
{ id: 'toggleFileTree', label: t('commands.toggleFileTree'), run: () => setShowFileTree((prev) => !prev) },
{ id: 'toggleReference', label: t('commands.toggleReference'), run: () => setShowReference((prev) => !prev) },
{ id: 'toggleLayout', label: t('commands.toggleLayout'), run: toggleOrientation },
{ id: 'toggleTheme', label: t('commands.toggleTheme'), run: toggleTheme },
{ id: 'clearOutput', label: t('commands.clearOutput'), run: resetExecution },
Expand All @@ -378,6 +393,7 @@ function PlaygroundContent({ initialLanguages }: { initialLanguages: InitialLang
? 'code-sanctuary-dark'
: 'code-sanctuary-light';
const direction = narrow ? 'vertical' : orientation;
const kingsejongId = languages.find((l) => l.id.startsWith('kingsejong'))?.id;
// Every file was sent, so a diagnostic belongs to the file its path names (no path: the entry file).
const runDiagnostics = output?.diagnostics.filter((d) => (d.path ? workspacePath(d.path) === activeFile?.name : runFileId === activeFileId));

Expand Down Expand Up @@ -407,6 +423,8 @@ function PlaygroundContent({ initialLanguages }: { initialLanguages: InitialLang
onOpenSnippets={() => setShowSnippetLibrary(true)}
onOpenHistory={() => setShowHistory(true)}
onToggleFileTree={() => setShowFileTree((prev) => !prev)}
onToggleReference={() => setShowReference((prev) => !prev)}
referenceOpen={showReference}
onFormat={handleFormatCode}
onSaveDraft={() => void saveDraftNow()}
onOpenShortcuts={() => setShowShortcutsHelp(true)}
Expand Down Expand Up @@ -467,6 +485,7 @@ function PlaygroundContent({ initialLanguages }: { initialLanguages: InitialLang
ariaLabel={`${t('editor.label')}: ${activeFile?.name ?? ''}`}
diagnostics={runDiagnostics}
reveal={reveal}
insert={insertRequest}
/>
</div>
{(!currentLanguage || currentLanguage.capabilities.includes(Language_Capability.STDIN)) && (
Expand Down Expand Up @@ -497,6 +516,16 @@ function PlaygroundContent({ initialLanguages }: { initialLanguages: InitialLang
/>
</Panel>
</PanelGroup>

{showReference && (
<ReferencePanel
isOpen={showReference}
onClose={() => setShowReference(false)}
onInsert={handleInsertExample}
canInsert={selectedLanguage.startsWith('kingsejong')}
onSwitchLanguage={kingsejongId ? () => handleLanguageChange(kingsejongId) : undefined}
/>
)}
</main>

<PlaygroundModals
Expand Down
13 changes: 13 additions & 0 deletions src/app/[locale]/components/PlaygroundHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { useRef } from 'react';
import { useTranslations } from 'next-intl';
import {
BookMarked,
BookOpenText,
FolderTree,
History,
Keyboard,
Expand All @@ -30,6 +31,7 @@ import {
Square,
Sun,
WandSparkles,
Check,
FileText,
} from 'lucide-react';
import LanguageSelector from '@/features/editor/LanguageSelector';
Expand Down Expand Up @@ -57,6 +59,8 @@ interface PlaygroundHeaderProps {
onOpenSnippets: () => void;
onOpenHistory: () => void;
onToggleFileTree: () => void;
onToggleReference: () => void;
referenceOpen: boolean;
onFormat: () => void;
onSaveDraft: () => void;
onOpenShortcuts: () => void;
Expand Down Expand Up @@ -88,6 +92,8 @@ export function PlaygroundHeader({
onOpenSnippets,
onOpenHistory,
onToggleFileTree,
onToggleReference,
referenceOpen,
onFormat,
onSaveDraft,
onOpenShortcuts,
Expand Down Expand Up @@ -141,6 +147,7 @@ export function PlaygroundHeader({
<nav className="flex items-center gap-1 max-lg:hidden" aria-label={t('header.tools')}>
<HeaderAction icon={<FileText />} label={t('header.templates')} onClick={onOpenTemplates} />
<HeaderAction icon={<History />} label={t('header.history')} onClick={onOpenHistory} />
<HeaderAction icon={<BookOpenText />} label={t('header.reference')} onClick={onToggleReference} aria-pressed={referenceOpen} />
<HeaderAction
icon={<Share2 />}
label={sharing ? t('header.sharing') : t('header.share')}
Expand Down Expand Up @@ -186,6 +193,7 @@ export function PlaygroundHeader({
<MenuDivider />
</div>
<MenuItem icon={<Save />} label={t('header.saveDraft')} hint={[runKeys[0], 'S']} onClick={fromMenu(onSaveDraft)} />
<MenuItem icon={<BookOpenText />} label={t('reference.title')} onClick={fromMenu(onToggleReference)} pressed={referenceOpen} />
<MenuItem icon={<BookMarked />} label={t('snippets.title')} onClick={fromMenu(onOpenSnippets)} />
<MenuItem icon={<FolderTree />} label={t('files.toggleTree')} onClick={fromMenu(onToggleFileTree)} />
<MenuItem icon={<WandSparkles />} label={t('commands.format')} onClick={fromMenu(onFormat)} />
Expand Down Expand Up @@ -258,25 +266,30 @@ function MenuItem({
hint,
onClick,
disabled,
pressed,
}: {
icon: React.ReactNode;
label: string;
hint?: string[];
onClick: () => void;
disabled?: boolean;
/** For toggles: shows a check and sets aria-pressed. */
pressed?: boolean;
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-pressed={pressed}
className="flex h-9 w-full items-center gap-3 rounded-md px-3 text-left text-sm text-fg-secondary hover:bg-hover hover:text-fg disabled:opacity-50"
>
<span className="inline-flex size-4 shrink-0 items-center justify-center text-fg-muted [&>svg]:size-4" aria-hidden="true">
{icon}
</span>
<span className="min-w-0 flex-1 truncate">{label}</span>
{hint && <KeyCombo keys={hint} className="shrink-0 max-sm:hidden" />}
{pressed && <Check className="size-4 shrink-0 text-accent-text" aria-hidden="true" />}
</button>
);
}
Expand Down
54 changes: 54 additions & 0 deletions src/features/editor/CodeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,31 @@ export interface RevealRequest {
nonce: number;
}

/** A request to insert text at the cursor; `nonce` makes repeated inserts of the same text work. */
export interface InsertRequest {
text: string;
nonce: number;
}

/**
* Where inserted text goes: a selection is replaced; on an empty line the text
* goes at the cursor; on a line with code it goes on a new line below.
*/
export function insertionEdit(
selection: { startLineNumber: number; startColumn: number; endLineNumber: number; endColumn: number; isEmpty: boolean },
lineText: string,
text: string
): { range: { startLineNumber: number; startColumn: number; endLineNumber: number; endColumn: number }; text: string } {
const body = text.endsWith('\n') ? text : `${text}\n`;
if (!selection.isEmpty || lineText.trim() === '') {
const { startLineNumber, startColumn, endLineNumber, endColumn } = selection;
return { range: { startLineNumber, startColumn, endLineNumber, endColumn }, text: body };
}
const end = lineText.length + 1;
const line = selection.startLineNumber;
return { range: { startLineNumber: line, startColumn: end, endLineNumber: line, endColumn: end }, text: `\n${body.replace(/\n$/, '')}` };
}

interface CodeEditorProps {
value: string;
onChange: (value: string) => void;
Expand All @@ -62,6 +87,8 @@ interface CodeEditorProps {
/** Diagnostics for this file, drawn as squiggles. */
diagnostics?: readonly DiagnosticView[];
reveal?: RevealRequest | null;
/** Text to insert at the cursor (see insertionEdit); undoable with the editor's undo. */
insert?: InsertRequest | null;
}

/*
Expand Down Expand Up @@ -167,6 +194,7 @@ export default function CodeEditor({
ariaLabel,
diagnostics,
reveal,
insert,
}: CodeEditorProps) {
const isKingsejongRegistered = useRef(false);
const editorRef = useRef<MonacoEditor.IStandaloneCodeEditor | null>(null);
Expand Down Expand Up @@ -259,6 +287,32 @@ export default function CodeEditor({
editor.focus();
}, [reveal]);

// Insert text at the cursor as one undoable edit.
useEffect(() => {
const editor = editorRef.current;
const monaco = monacoRef.current;
const model = editor?.getModel();
if (!editor || !monaco || !model || !insert) return;
const selection = editor.getSelection();
if (!selection) return;
const edit = insertionEdit(
{ ...selection, isEmpty: selection.isEmpty() },
model.getLineContent(selection.startLineNumber),
insert.text
);
// Leave the cursor at the end of the inserted text.
const lines = edit.text.split('\n');
const endLine = edit.range.startLineNumber + lines.length - 1;
const endColumn = (lines.length === 1 ? edit.range.startColumn : 1) + lines[lines.length - 1].length;
editor.pushUndoStop();
editor.executeEdits('playground-insert', [{ ...edit, forceMoveMarkers: true }], [
new monaco.Selection(endLine, endColumn, endLine, endColumn),
]);
editor.pushUndoStop();
editor.revealLineInCenterIfOutsideViewport(endLine);
editor.focus();
}, [insert]);

return (
<Editor
height="100%"
Expand Down
22 changes: 22 additions & 0 deletions src/features/editor/__tests__/insertionEdit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { insertionEdit } from '../CodeEditor';

const at = (line: number, column: number) => ({ startLineNumber: line, startColumn: column, endLineNumber: line, endColumn: column, isEmpty: true });

describe('insertionEdit', () => {
it('inserts at the cursor on an empty line, ending with a newline', () => {
expect(insertionEdit(at(3, 1), '', '출력(1)')).toEqual({ range: { startLineNumber: 3, startColumn: 1, endLineNumber: 3, endColumn: 1 }, text: '출력(1)\n' });
});

it('puts the text on a new line below a line with code', () => {
expect(insertionEdit(at(2, 3), 'x = 1', '출력(x)\n')).toEqual({
range: { startLineNumber: 2, startColumn: 6, endLineNumber: 2, endColumn: 6 },
text: '\n출력(x)',
});
});

it('replaces a selection', () => {
const selection = { startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 4, isEmpty: false };
expect(insertionEdit(selection, 'abc', 'y\n').text).toBe('y\n');
expect(insertionEdit(selection, 'abc', 'y\n').range).toEqual({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 4 });
});
});
Loading
Loading