prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
iddleware; use Illuminate\Foundation\Http\Middleware\TrimStrings; use Illuminate\Http\Request; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; class TrimStringsTest extends TestCase { public function testTrimStringsIgnoringExceptAttribute() { $middleware...
$this->assertSame('123', $request->get('abc')); $this->assertSame('456', $request->get('xyz')); $this->assertSame(' 789 ', $request->get('foo')); $this->assertSame(' 010 ', $request->get('bar')); })
'bar' => ' 010 ', ]); $symfonyRequest->server->set('REQUEST_METHOD', 'GET'); $request = Request::createFromBase($symfonyRequest); $middleware->handle($request, function (Request $request) {
{ "filepath": "tests/Foundation/Http/Middleware/TrimStringsTest.php", "language": "php", "file_size": 2332, "cut_index": 563, "middle_length": 229 }
tTrue($results->successful()); } public function testProcessPoolFailed() { $factory = new Factory; $factory->fake([ 'cat *' => $factory->result(exitCode: 1), ]); $pool = $factory->pool(function ($pool) { return [ $pool->path(__DIR__)...
actory->pool(function ($pool) { return [ $pool->path(__DIR__)->command($this->ls()), $pool->path(__DIR__)->command($this->ls()), ]; })->start(); $this->assertCount(2, $pool); }
->successful()); $this->assertTrue($results[1]->failed()); $this->assertTrue($results->failed()); } public function testInvokedProcessPoolCount() { $factory = new Factory; $pool = $f
{ "filepath": "tests/Process/ProcessTest.php", "language": "php", "file_size": 34038, "cut_index": 2151, "middle_length": 229 }
pace Illuminate\Tests\Cookie\Middleware; use Illuminate\Cookie\CookieJar; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\ResponseHeaderBag; class AddQueuedCookiesToResponseTest...
(Request $request) { return new Response; }; $this->assertEquals( [ '' => [ '/path' => [ 'foo' => $cookieOne, ], '/'
ieJar->make('foo', 'rab', 0, '/'); $cookieJar->queue($cookieOne); $cookieJar->queue($cookieTwo); $addQueueCookiesToResponseMiddleware = new AddQueuedCookiesToResponse($cookieJar); $next = function
{ "filepath": "tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php", "language": "php", "file_size": 1268, "cut_index": 524, "middle_length": 229 }
e\Cookie\CookieValuePrefix; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Cookie\Middleware\EncryptCookies; use Illuminate\Encryption\Encrypter; use Illuminate\Events\Dispatcher; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Routing\Controller; use Illuminate\Ro...
etUp(): void { parent::setUp(); $this->container = new Container; $this->container->singleton(EncrypterContract::class, function () { return new Encrypter(str_repeat('a', 16)); }); $this->router = n
*/ protected $container; /** * @var \Illuminate\Routing\Router */ protected $router; protected $setCookiePath = 'cookie/set'; protected $queueCookiePath = 'cookie/queue'; protected function s
{ "filepath": "tests/Cookie/Middleware/EncryptCookiesTest.php", "language": "php", "file_size": 7167, "cut_index": 716, "middle_length": 229 }
ception; use Illuminate\Database\Events\TransactionBeginning; use Illuminate\Database\Events\TransactionCommitted; use Illuminate\Database\Events\TransactionRolledBack; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Pipeline; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataP...
e string', $result); Event::assertDispatchedTimes(TransactionBeginning::class, 1); Event::assertDispatchedTimes(TransactionCommitted::class, 1); } public static function transactionConnectionDataProvider(): array { retu
->send('some string') ->through([ fn ($value, $next) => $next($value), fn ($value, $next) => $next($value), ]) ->thenReturn(); $this->assertSame('som
{ "filepath": "tests/Pipeline/PipelineTransactionTest.php", "language": "php", "file_size": 2939, "cut_index": 563, "middle_length": 229 }
minate\Container\Container; use Illuminate\Events\Dispatcher; use Mockery as m; use PHPUnit\Framework\TestCase; class EventsSubscriberTest extends TestCase { public function testEventSubscribers() { $this->expectNotToPerformAssertions(); $d = new Dispatcher($container = m::mock(Container::clas...
$subs = m::mock(ExampleSubscriber::class); $subs->shouldReceive('subscribe')->once()->with($d); $d->subscribe($subs); } public function testEventSubscribeCanReturnMappings() { $d = new Dispatcher; $d->subscrib
class)->andReturn($subs); $d->subscribe(ExampleSubscriber::class); } public function testEventSubscribeCanAcceptObject() { $this->expectNotToPerformAssertions(); $d = new Dispatcher;
{ "filepath": "tests/Events/EventsSubscriberTest.php", "language": "php", "file_size": 2041, "cut_index": 563, "middle_length": 229 }
minate\Contracts\Events\Dispatcher; use Illuminate\Notifications\Channels\BroadcastChannel; use Illuminate\Notifications\Events\BroadcastNotificationCreated; use Illuminate\Notifications\Messages\BroadcastMessage; use Illuminate\Notifications\Notification; use Mockery as m; use PHPUnit\Framework\TestCase; class Notifi...
$channel = new BroadcastChannel($events); $channel->send($notifiable, $notification); } public function testNotificationIsBroadcastedOnCustomChannels() { $notification = new CustomChannelsTestNotification; $notific
ification; $notification->id = 1; $notifiable = m::mock(); $events = m::mock(Dispatcher::class); $events->shouldReceive('dispatch')->once()->with(m::type(BroadcastNotificationCreated::class));
{ "filepath": "tests/Notifications/NotificationBroadcastChannelTest.php", "language": "php", "file_size": 4458, "cut_index": 614, "middle_length": 229 }
use Mockery as m; use PHPUnit\Framework\TestCase; class NotificationChannelManagerTest extends TestCase { protected function tearDown(): void { Container::setInstance(null); parent::tearDown(); } public function testNotificationCanBeDispatchedToDriver() { $container = new ...
$events->shouldReceive('listen')->once(); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $driver->shouldReceive('send')->once(); $events->shouldReceive('dispatch')->with(m::type
cher::class, $events = m::mock()); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); $manager->shouldReceive('driver')->andReturn($driver = m::mock());
{ "filepath": "tests/Notifications/NotificationChannelManagerTest.php", "language": "php", "file_size": 30159, "cut_index": 1331, "middle_length": 229 }
se Illuminate\Notifications\Channels\DatabaseChannel; use Illuminate\Notifications\Messages\DatabaseMessage; use Illuminate\Notifications\Notification; use Illuminate\Support\Carbon; use Mockery as m; use PHPUnit\Framework\TestCase; class NotificationDatabaseChannelTest extends TestCase { public function testDatab...
); $channel = new DatabaseChannel; $channel->send($notifiable, $notification); } public function testCorrectPayloadIsSentToDatabase() { $notification = new NotificationDatabaseChannelTestNotification; $notifica
$notifiable->shouldReceive('routeNotificationFor->create')->with([ 'id' => 1, 'type' => get_class($notification), 'data' => ['invoice_id' => 1], 'read_at' => null, ]
{ "filepath": "tests/Notifications/NotificationDatabaseChannelTest.php", "language": "php", "file_size": 2905, "cut_index": 563, "middle_length": 229 }
se Illuminate\Container\Container; use Illuminate\Contracts\Notifications\Dispatcher; use Illuminate\Notifications\RoutesNotifications; use Illuminate\Support\Facades\Notification; use InvalidArgumentException; use Mockery as m; use PHPUnit\Framework\TestCase; use stdClass; class NotificationRoutesNotificationsTest ex...
stdClass; $factory->shouldReceive('send')->with($notifiable, $instance); Container::setInstance($container); $notifiable->notify($instance); } public function testNotificationCanBeSentNow() { $container = new
{ $container = new Container; $factory = m::mock(Dispatcher::class); $container->instance(Dispatcher::class, $factory); $notifiable = new RoutesNotificationsTestInstance; $instance = new
{ "filepath": "tests/Notifications/NotificationRoutesNotificationsTest.php", "language": "php", "file_size": 2209, "cut_index": 563, "middle_length": 229 }
se Illuminate\Contracts\Database\ModelIdentifier; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Notifications\ChannelManager; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; use Illuminate\Notifications\SendQueuedNotification...
->once()->withArgs(function ($notifiables, $notification, $channels) { return $notifiables instanceof Collection && $notifiables->toArray() === ['notifiables'] && $notification instanceof TestNotification && $cha
nBeSent() { $notification = new TestNotification; $job = new SendQueuedNotifications('notifiables', $notification); $manager = m::mock(ChannelManager::class); $manager->shouldReceive('sendNow')
{ "filepath": "tests/Notifications/NotificationSendQueuedNotificationTest.php", "language": "php", "file_size": 2412, "cut_index": 563, "middle_length": 229 }
PaginatorTest extends TestCase { public function testReturnsRelevantContextInformation() { $p = new CursorPaginator($array = [['id' => 1], ['id' => 2], ['id' => 3]], 2, null, [ 'parameters' => ['id'], ]); $this->assertTrue($p->hasPages()); $this->assertTrue($p->hasMo...
]; $this->assertEquals($pageInfo, $p->toArray()); } public function testPaginatorRemovesTrailingSlashes() { $p = new CursorPaginator($array = [['id' => 4], ['id' => 5], ['id' => 6]], 2, null, ['path' => 'http:/
'per_page' => 2, 'next_cursor' => $this->getCursor(['id' => 2]), 'next_page_url' => '/?cursor='.$this->getCursor(['id' => 2]), 'prev_cursor' => null, 'prev_page_url' => null,
{ "filepath": "tests/Pagination/CursorPaginatorTest.php", "language": "php", "file_size": 5434, "cut_index": 716, "middle_length": 229 }
te\Tests\Pagination; use Illuminate\Pagination\Cursor; use Illuminate\Support\Carbon; use PHPUnit\Framework\TestCase; class CursorTest extends TestCase { public function testCanEncodeAndDecodeSuccessfully() { $cursor = new Cursor([ 'id' => 422, 'created_at' => Carbon::now()->to...
d(base64_encode('not-json'))); } public function testFromEncodedReturnsNullWhenDecodedPayloadIsNotAnArray() { $this->assertNull(Cursor::fromEncoded(base64_encode(json_encode('scalar')))); $this->assertNull(Cursor::fromEncoded(b
{ $this->assertNull(Cursor::fromEncoded(null)); $this->assertNull(Cursor::fromEncoded(123)); } public function testFromEncodedReturnsNullForInvalidJson() { $this->assertNull(Cursor::fromEncode
{ "filepath": "tests/Pagination/CursorTest.php", "language": "php", "file_size": 1832, "cut_index": 537, "middle_length": 229 }
te\Tests\Foundation\Http\Middleware; use Illuminate\Http\Exceptions\MalformedUrlException; use Illuminate\Http\Middleware\ValidatePathEncoding; use Illuminate\Http\Request; use Illuminate\Http\Response; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Requ...
$symfonyRequest->server->set('REQUEST_METHOD', 'GET'); $symfonyRequest->server->set('REQUEST_URI', $path); $request = Request::createFromBase($symfonyRequest); $response = $middleware->handle($request, fn () => new Response('O
TestWith(['%E6%B1%89%E5%AD%97%E5%AD%97%E7%AC%A6%E9%9B%86'])] public function testValidPathsArePassing(string $path): void { $middleware = new ValidatePathEncoding; $symfonyRequest = new SymfonyRequest;
{ "filepath": "tests/Foundation/Http/Middleware/ValidatePathEncodingTest.php", "language": "php", "file_size": 1896, "cut_index": 537, "middle_length": 229 }
($piped); }; $result = (new Pipeline(new Container)) ->send('foo') ->through([PipelineTestPipeOne::class, $pipeTwo]) ->then(function ($piped) { return $piped; }); $this->assertSame('foo', $result); $this->assertSame('foo',...
ed; }); $this->assertSame('foo', $result); $this->assertSame('foo', $_SERVER['__test.pipe.one']); unset($_SERVER['__test.pipe.one']); } public function testPipelineUsageWithInvokableObjects() { $re
on testPipelineUsageWithObjects() { $result = (new Pipeline(new Container)) ->send('foo') ->through([new PipelineTestPipeOne]) ->then(function ($piped) { return $pip
{ "filepath": "tests/Pipeline/PipelineTest.php", "language": "php", "file_size": 13419, "cut_index": 921, "middle_length": 229 }
']); $this->assertSame('barbar', $_SERVER['__event.test']); } public function testDeferEventExecution() { unset($_SERVER['__event.test']); $d = new Dispatcher; $d->listen('foo', function ($foo) { $_SERVER['__event.test'] = $foo; }); $result = $d-...
Dispatcher; $d->listen('foo', function ($value) { $_SERVER['__event.test'][] = $value; }); $d->listen('bar', function ($value) { $_SERVER['__event.test'][] = $value; }); $d->defer(function ()
$this->assertSame('callback_result', $result); $this->assertSame('bar', $_SERVER['__event.test']); } public function testDeferMultipleEvents() { $_SERVER['__event.test'] = []; $d = new
{ "filepath": "tests/Events/EventsDispatcherTest.php", "language": "php", "file_size": 25660, "cut_index": 1331, "middle_length": 229 }
e; use Illuminate\Foundation\Console\ServeCommand; use PHPUnit\Framework\TestCase; class ServeCommandLogParserTest extends TestCase { public function testExtractRequestPortWithValidLogLine() { $line = '[Mon Nov 19 10:30:45 2024] :8080 Info'; $this->assertEquals(8080, ServeCommand::getRequestP...
ServeCommand::getRequestPortFromLine($line)); } public function testExtractRequestPortWithMissingPort() { $line = '[Mon Nov 19 10:30:45 2024] Info'; $this->expectException(\InvalidArgumentException::class); $this->expe
->assertEquals(3000, ServeCommand::getRequestPortFromLine($line)); } public function testExtractRequestPortWithValidLogLineWithoutDate() { $line = ':5000 [Server Started]'; $this->assertEquals(5000,
{ "filepath": "tests/Foundation/Console/ServeCommandLogParserTest.php", "language": "php", "file_size": 2690, "cut_index": 563, "middle_length": 229 }
ications\Messages\SimpleMessage as Message; use PHPUnit\Framework\TestCase; class NotificationMessageTest extends TestCase { public function testLevelCanBeRetrieved() { $message = new Message; $this->assertSame('info', $message->level); $message = new Message; $message->level('...
'); $this->assertSame('This is a single line of text.', $message->introLines[0]); $message = new Message; $message->with([ 'This is a', 'single line of text.', ]); $this->assertSame('T
This is a single line of text.
{ "filepath": "tests/Notifications/NotificationMessageTest.php", "language": "php", "file_size": 956, "cut_index": 582, "middle_length": 52 }
HttpClient\ResponseInterface; class NotificationSenderTest extends TestCase { public function test_it_can_send_queued_notifications_with_a_string_via() { $notifiable = m::mock(Notifiable::class); $manager = m::mock(ChannelManager::class); $manager->shouldReceive('getContainer')->andRetu...
$events); $sender->send($notifiable, new DummyQueuedNotificationWithStringVia); } public function test_it_can_send_queued_notifications_with_an_array_via() { $notifiable = m::mock(Notifiable::class); $manager = m::moc
::mock(BusDispatcher::class); $bus->shouldReceive('dispatch'); $events = m::mock(EventDispatcher::class); $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus,
{ "filepath": "tests/Notifications/NotificationSenderTest.php", "language": "php", "file_size": 18285, "cut_index": 1331, "middle_length": 229 }
Mix; use Illuminate\Http\Exceptions\HttpResponseException; use Illuminate\Http\Request; use Illuminate\Support\Str; use Mockery as m; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; class FoundationHelpersTest extends TestCase { public function testCache() { ...
ull)->andReturn('bar'); $this->assertSame('bar', cache('foo')); // 4. cache('foo', null); $cache->shouldReceive('get')->once()->with('foo', null)->andReturn('bar'); $this->assertSame('bar', cache('foo', null)); //
// 2. cache(['foo' => 'bar'], 1); $cache->shouldReceive('put')->once()->with('foo', 'bar', 1); cache(['foo' => 'bar'], 1); // 3. cache('foo'); $cache->shouldReceive('get')->once()->with('foo', n
{ "filepath": "tests/Foundation/FoundationHelpersTest.php", "language": "php", "file_size": 9479, "cut_index": 921, "middle_length": 229 }
te\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Events\Dispatcher; use Mockery as m; use PHPUnit\Framework\TestCase; class BroadcastedEventsTest extends TestCase { public function testShouldBroadcastSuccess() { $d = m::mock(Dispatcher::class); $d->makePartial()->shouldAllowMockingPro...
broadcast = m::mock(BroadcastFactory::class); $broadcast->shouldReceive('queue')->once(); $container->shouldReceive('make')->once()->with(BroadcastFactory::class)->andReturn($broadcast); $d->listen(AlwaysBroadcastEvent::class, func
uldBroadcast([$event])); } public function testShouldBroadcastAsQueuedAndCallNormalListeners() { unset($_SERVER['__event.test']); $d = new Dispatcher($container = m::mock(Container::class)); $
{ "filepath": "tests/Events/BroadcastedEventsTest.php", "language": "php", "file_size": 6215, "cut_index": 716, "middle_length": 229 }
age; use PHPUnit\Framework\TestCase; class NotificationMailMessageTest extends TestCase { protected ?string $filesystemRoot = null; protected function tearDown(): void { if ($this->filesystemRoot !== null) { $this->deleteDirectory($this->filesystemRoot); $this->filesystemRo...
$this->assertNull($message->view); $this->assertSame([], $message->viewData); $message->view(['notifications::foo', 'notifications::bar'], [ 'foo' => 'bar', ]); $this->assertSame('notifications::foo', $m
e->markdown); $message->template('notifications::foo'); $this->assertSame('notifications::foo', $message->markdown); } public function testHtmlAndPlainView() { $message = new MailMessage;
{ "filepath": "tests/Notifications/NotificationMailMessageTest.php", "language": "php", "file_size": 15384, "cut_index": 921, "middle_length": 229 }
pace Illuminate\Tests\Foundation\Http\Middleware; use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull; use Illuminate\Http\Request; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; class ConvertEmptyStringsToNullTest extends TestCase { public function...
rtSame('bar', $request->get('foo')); $this->assertNull($request->get('baz')); }); } public function testSkipConvertsEmptyStringsToNull() { $middleware = new ConvertEmptyStringsToNull; ConvertEmptyStringsToNu
]); $symfonyRequest->server->set('REQUEST_METHOD', 'GET'); $request = Request::createFromBase($symfonyRequest); $middleware->handle($request, function (Request $request) { $this->asse
{ "filepath": "tests/Foundation/Http/Middleware/ConvertEmptyStringsToNullTest.php", "language": "php", "file_size": 1504, "cut_index": 524, "middle_length": 229 }
use PHPUnit\Framework\TestCase; class QueuedEventsTest extends TestCase { public function testQueuedEventHandlersAreQueued() { $d = new Dispatcher; $queue = m::mock(Queue::class); $queue->shouldReceive('connection')->once()->with(null)->andReturnSelf(); $queue->shouldReceive('...
ueue = new QueueFake(new Container); $d->setQueueResolver(function () use ($fakeQueue) { return $fakeQueue; }); $d->listen('some.event', TestDispatcherConnectionQueuedHandler::class.'@handle'); $d->dispatch('so
t', TestDispatcherQueuedHandler::class.'@someMethod'); $d->dispatch('some.event', ['foo', 'bar']); } public function testCustomizedQueuedEventHandlersAreQueued() { $d = new Dispatcher; $fakeQ
{ "filepath": "tests/Events/QueuedEventsTest.php", "language": "php", "file_size": 25938, "cut_index": 1331, "middle_length": 229 }
ain('foo', 'bar'); $c = $cookie->make('color', 'blue', 10, '/path', '/domain', true, false, false, 'lax'); $this->assertSame('blue', $c->getValue()); $this->assertFalse($c->isHttpOnly()); $this->assertTrue($c->isSecure()); $this->assertSame('/domain', $c->getDomain()); $t...
path', $c2->getPath()); $this->assertSame('strict', $c2->getSameSite()); $c3 = $cookie->forget('color'); $this->assertNull($c3->getValue()); $this->assertTrue($c3->getExpiresTime() < time()); } public function test
; $this->assertSame('blue', $c2->getValue()); $this->assertFalse($c2->isHttpOnly()); $this->assertTrue($c2->isSecure()); $this->assertSame('/domain', $c2->getDomain()); $this->assertSame('/
{ "filepath": "tests/Cookie/CookieTest.php", "language": "php", "file_size": 10100, "cut_index": 921, "middle_length": 229 }
ant to pass to Jest /** @type {import('jest').Config} */ const customJestConfig = { displayName: process.env.IS_WEBPACK_TEST ? 'webpack' : 'Turbopack', testMatch: ['**/*.test.js', '**/*.test.ts', '**/*.test.jsx', '**/*.test.tsx'], globalSetup: '<rootDir>/jest-global-setup.ts', setupFilesAfterEnv: ['<rootDir>/je...
ision: true, }, modulePathIgnorePatterns: [ '/\\.next/', // Prevents jest-haste-map warnings due to multiple versions of the same // package being vendored. Also means tests in `compiled` will be ignored. // Jest does not normalize/reso
kages/eslint-plugin-internal/', '<rootDir>/../packages/font/src/', '<rootDir>/../packages/next-routing/', ], haste: { // Throwing to avoid warnings creeping up over time polluting log output. throwOnModuleColl
{ "filepath": "jest.config.js", "language": "javascript", "file_size": 3176, "cut_index": 614, "middle_length": 229 }
* pnpm eval <eval-name> --dry preview without executing * pnpm eval --all run every eval (slow — normally only CI does this) * NEXT_SKIP_PACK=1 pnpm eval ... reuse tarball from last run * * Mirrors run-tests.js: pack once, hand paths to child via env, forward args. * * We only pac...
ne place instead of * maintaining N committed experiment files that only differ by one line. */ const path = require('path') const fs = require('fs') const { execFileSync, spawnSync } = require('child_process') const ROOT = __dirname const EVALS_DIR =
rc/build/swc/index.ts). * - @next/env etc: resolved from npm at the pinned canary version. * * The experiments/ dir is generated fresh on every run and gitignored. This * keeps the two variants (baseline vs. AGENTS.md) in o
{ "filepath": "run-evals.js", "language": "javascript", "file_size": 6587, "cut_index": 716, "middle_length": 229 }
ess.env.RSPACK_BINDING = require('node:path').dirname( require.resolve('@next/rspack-binding') ) const binding = require('@next/rspack-binding') // Register the plugins exported by `crates/binding/src/lib.rs`. binding.registerNextExternalsPlugin() binding.registerForceCompleteRuntimePlugin() const core = require('...
untimePlugin', function () { return {} } ) Object.defineProperty(core, 'NextExternalsPlugin', { value: NextExternalsPlugin, }) Object.defineProperty(core, 'ForceCompleteRuntimePlugin', { value: ForceCompleteRuntimePlugin, }) module.exports =
re.experiments.createNativePlugin( 'ForceCompleteR
{ "filepath": "rspack/lib/index.js", "language": "javascript", "file_size": 830, "cut_index": 516, "middle_length": 52 }
React from "react"; import { useForm, ValidationError } from "@formspree/react"; import formStyles from "../styles/form.module.css"; export default function ContactForm() { const [state, handleSubmit] = useForm(process.env.NEXT_PUBLIC_FORM); if (state.succeeded) { return <p>Thanks for your submission!</p>; }...
es.fieldErrors} /> <label htmlFor="message" className={formStyles.labels}> Your message: </label> <textarea id="message" name="message" className={`${formStyles.inputs} ${formStyles.textarea}`}
id="email" type="email" name="email" className={formStyles.inputs} /> <ValidationError prefix="Email" field="email" errors={state.errors} className={formStyl
{ "filepath": "examples/with-formspree/components/contact-form.js", "language": "javascript", "file_size": 1462, "cut_index": 524, "middle_length": 229 }
from "react-redux"; import Header from "../shared/components/header"; import { useRematchDispatch } from "../shared/utils"; const Home = () => { const counter = useSelector((state) => state.counter); const dispatch = useDispatch(); const { increment } = useRematchDispatch((dispatch) => ({ increment: dispatc...
ncrement(1)}> increment (using dispatch function) </button> <button onClick={() => increment(5)}>increment by 5</button> <button onClick={dispatch.counter.incrementAsync}> incrementAsync </button> <
>increment</button> <button onClick={() => i
{ "filepath": "examples/with-rematch/pages/index.js", "language": "javascript", "file_size": 913, "cut_index": 547, "middle_length": 52 }
StitchesLogo = () => ( <svg xmlns="http://www.w3.org/2000/svg" width="35" height="35" viewBox="0 0 35 35" fill="none" > <circle cx="17.5" cy="17.5" r="14.5" stroke="currentColor" strokeWidth="2" /> <path d="M12.8184 31.3218L31.8709 20.3218" stroke="curre...
lor" strokeLinecap="round" strokeLinejoin="round" /> <path d="M16.6973 12.2302L25.9736 19.1078" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" /> <path d="M9.21582 16.0815L19.045
strokeLinejoin="round" /> <path d="M9.21582 16.0815L26.5363 6.08154" stroke="currentColor" strokeLinecap="round" /> <path d="M13.2334 14.2297L22.5099 21.1077" stroke="currentCo
{ "filepath": "examples/with-stitches/app/_components/StitchesLogo.tsx", "language": "tsx", "file_size": 1148, "cut_index": 518, "middle_length": 229 }
WR from "swr"; import fetcher from "libs/fetcher"; import styles from "./Gallery.module.css"; import UImage from "components/UImage"; interface GalleryProps { id_collection?: number; } const Gallery = ({ id_collection }: GalleryProps) => { const { data, error } = useSWR( "/api/photo" + (id_collection ? `/${id...
ription }) => ( <UImage id={id} urls={urls} altDescription={alt_description ? alt_description : description} key={`${id}_uimage_component`} /> ))} </section> ); }; export default Gallery;
> {data.map(({ id, urls, alt_description, desc
{ "filepath": "examples/with-unsplash/components/Gallery/index.tsx", "language": "tsx", "file_size": 832, "cut_index": 523, "middle_length": 52 }
@type {import('tailwindcss').Config} */ module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", "./slices/**/*.{js,ts,jsx,tsx}", ], theme: { extend: { colors: { "accent-1": "#FAFAFA", "accent-2": "#EAEAEA", "accent-7": "#333"...
"5xl": "2.5rem", "6xl": "2.75rem", "7xl": "4.5rem", "8xl": "6.25rem", }, boxShadow: { small: "0 5px 10px rgba(0, 0, 0, 0.12)", medium: "0 8px 30px rgba(0, 0, 0, 0.12)", }, }, }, plugins: [],
tight: 1.2, }, fontSize: {
{ "filepath": "examples/cms-prismic/tailwind.config.js", "language": "javascript", "file_size": 828, "cut_index": 516, "middle_length": 52 }
from "next/head"; import { CMS_NAME, HOME_OG_IMAGE_URL } from "../lib/constants"; export default function Meta() { return ( <Head> <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" /> <link rel="icon" type="image/png" ...
n/favicon.ico" /> <meta name="msapplication-TileColor" content="#000000" /> <meta name="msapplication-config" content="/favicon/browserconfig.xml" /> <meta name="theme-color" content="#000" /> <link rel="alternate" type="application
/> <link rel="manifest" href="/favicon/site.webmanifest" /> <link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#000000" /> <link rel="shortcut icon" href="/favico
{ "filepath": "examples/cms-prismic/components/meta.tsx", "language": "tsx", "file_size": 1256, "cut_index": 524, "middle_length": 229 }
onst { promises: fs } = require("fs"); const path = require("path"); const RSS = require("rss"); const matter = require("gray-matter"); async function generate() { const feed = new RSS({ title: "Your Name", site_url: "https://yoursite.com", feed_url: "https://yoursite.com/feed.xml", }); const posts ...
?/, ""), date: frontmatter.data.date, description: frontmatter.data.description, categories: frontmatter.data.tag.split(", "), author: frontmatter.data.author, }); }), ); await fs.writeFile("./public/feed.xml"
t fs.readFile( path.join(__dirname, "..", "pages", "posts", name), ); const frontmatter = matter(content); feed.item({ title: frontmatter.data.title, url: "/posts/" + name.replace(/\.mdx
{ "filepath": "examples/blog/scripts/gen-rss.js", "language": "javascript", "file_size": 1044, "cut_index": 513, "middle_length": 229 }
ort { CSSTransition } from "react-transition-group"; import { gsap } from "gsap"; import Home from "../components/Home"; export default function HomePage() { const onEnter = (node: any) => { gsap.from( [node.children[0].firstElementChild, node.children[0].lastElementChild], 0.6, { y: 30...
( <> <div className="container"> <CSSTransition in={true} timeout={1200} classNames="page" onExit={onExit} onEntering={onEnter} unmountOnExit > <div className="
[node.children[0].firstElementChild, node.children[0].lastElementChild], 0.6, { y: -30, ease: "power3.InOut", stagger: { amount: 0.2, }, }, ); }; return
{ "filepath": "examples/with-gsap/pages/index.tsx", "language": "tsx", "file_size": 1098, "cut_index": 515, "middle_length": 229 }
': 'documentation', 'Example Changes': 'examples', } const fallbackSection = 'Misc Changes' // -------------------------------------------------- const prNumberRegex = /\(#([-0-9]+)\)$/ const getCommitPullRequest = async (commit, github) => { const match = prNumberRegex.exec(commit.title) if (!match) { r...
bel] of Object.entries(sectionLabelMap)) { if (labels.some((prLabel) => prLabel.name === label)) { return section } } return null } const groupByLabels = async (commits, github) => { // Initialize the sections object with empty arrays
repo: github.repoDetails.repo, number, }) return data } const getSectionForPullRequest = (pullRequest) => { const { labels } = pullRequest // sections defined first will take priority for (const [section, la
{ "filepath": "release.js", "language": "javascript", "file_size": 3695, "cut_index": 614, "middle_length": 229 }
tProfile { // Env vars that always affect test behavior (non-NEXT prefixed). static EXTRA_ENV_VARS = [ 'IS_WEBPACK_TEST', 'IS_TURBOPACK_TEST', 'TURBOPACK_DEV', 'TURBOPACK_BUILD', 'BROWSER_NAME', 'DEVICE_NAME', ] // NEXT_* / __NEXT* vars that are operational, not behavioral. static IGN...
ted once at construction // from a snapshot of process.env. The actual cache key for the workflow // is `input_step_key` (see `.github/workflows/build_reusable.yml`). entries // NEXT_*/__NEXT* vars that matched the pattern but were ignored. ignor
NEXT_TURBOPACK_IO_CONCURRENCY', 'NEXT_TEST_PASSED_FILE', 'TURBO_TASKS_AVAILABLE_PARALLELISM', ]) // All key=value pairs identifying this test profile, sorted by key. // Used for the diagnostic `log()` output. Compu
{ "filepath": "run-tests.js", "language": "javascript", "file_size": 32985, "cut_index": 1331, "middle_length": 229 }
wPackageName) { console.error('Usage: node change-npm-name.js <new-package-name>') console.error('Example: node change-npm-name.js @next/rspack-core') process.exit(1) } const bindingPackageName = newPackageName.replace(/core/g, 'binding') console.log(`Core package name: ${newPackageName}`) console.log(`Binding ...
ry URL to match current GitHub repo for provenance validation if (packageJson.repository && packageJson.repository.url) { const githubRepo = process.env.GITHUB_REPOSITORY if (githubRepo) { packageJson.repository.url = `git+https://g
xistsSync(filePath)) { console.warn(`Package.json not found: ${filePath}`) return } const packageJson = JSON.parse(fs.readFileSync(filePath, 'utf8')) packageJson.name = packageName // Update reposito
{ "filepath": "rspack/change-npm-name.js", "language": "javascript", "file_size": 3188, "cut_index": 614, "middle_length": 229 }
musl = isMuslFromReport() } if (musl === null) { musl = isMuslFromChildProcess() } } return musl } const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') const isMuslFromFilesystem = () => { try { return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') } cat...
sFileMusl)) { return true } } return false } const isMuslFromChildProcess = () => { try { return require('child_process') .execSync('ldd --version', { encoding: 'utf8' }) .includes('musl') } catch (e) { // If we reach
process.report.getReport() } if (!report) { return null } if (report.header && report.header.glibcVersionRuntime) { return false } if (Array.isArray(report.sharedObjects)) { if (report.sharedObjects.some(i
{ "filepath": "rspack/crates/binding/index.js", "language": "javascript", "file_size": 14433, "cut_index": 921, "middle_length": 229 }
Title, CardBody, } from "reactstrap"; export default function Home() { return ( <Container className="md-container"> <Head> <title>ReactJS with reactstrap</title> <link rel="icon" href="/favicon-32x32.png" /> </Head> <Container> <h1> Welcome to <a href="https...
PI. </CardText> <Button color="primary" href="https://nextjs.org/docs"> More &rarr; </Button> </CardBody> </Card> </Col> <Col sm
<Card className="my-3"> <CardBody> <CardTitle tag="h5">Documentation</CardTitle> <CardText> Find in-depth information about Next.js features and A
{ "filepath": "examples/with-reactstrap/pages/index.jsx", "language": "jsx", "file_size": 3262, "cut_index": 614, "middle_length": 229 }
"react"; import ClientOnlyPortal from "./ClientOnlyPortal"; export default function Modal() { const [open, setOpen] = useState(); return ( <> <button type="button" onClick={() => setOpen(true)}> Open Modal </button> {open && ( <ClientOnlyPortal selector="#modal"> <d...
tton type="button" onClick={() => setOpen(false)}> Close Modal </button> </div> <style jsx>{` :global(body) { overflow: hidden; } .backdrop {
ference/react-dom/createPortal" target="_blank" rel="noopener noreferrer" > portals </a> . </p> <bu
{ "filepath": "examples/with-portals/components/Modal.js", "language": "javascript", "file_size": 1575, "cut_index": 537, "middle_length": 229 }
ort { useMemo } from "react"; import { init } from "@rematch/core"; import { counter, github } from "./models"; let store; const exampleInitialState = { counter: 5, }; export const initStore = (initialState = exampleInitialState) => init({ models: { counter, github, }, redux: { init...
store = undefined; } // For SSG and SSR always create a new store if (typeof window === "undefined") return _store; // Create the store once in the client if (!store) store = _store; return _store; }; export function useStore(initialStat
rge that state // with the current state in the store, and create a new store if (preloadedState && store) { _store = initStore({ ...store.getState(), ...preloadedState, }); // Reset the current store
{ "filepath": "examples/with-rematch/shared/store.js", "language": "javascript", "file_size": 1101, "cut_index": 515, "middle_length": 229 }
om "react-redux"; import { useRematchDispatch } from "../shared/utils"; import { initializeStore } from "../shared/store"; import CounterDisplay from "../shared/components/counter-display"; import Header from "../shared/components/header"; const Github = (props) => { const github = useSelector((state) => state.githu...
<h1> Users passed as property from getStaticProps</h1> {usersList.map((user) => ( <div key={user.login}> <a href={user.html_url}> <img height="45" width="45" src={user.avatar_url} /> <span> Username - {user.
urn ( <div> <Header /> <h1> Github users </h1> <p> Server rendered github user list. You can also reload the users from the api by clicking the <b>Get users</b> button below. </p>
{ "filepath": "examples/with-rematch/pages/github-users.js", "language": "javascript", "file_size": 1839, "cut_index": 537, "middle_length": 229 }
nst github = { state: { users: [], isLoading: false, }, // initial state reducers: { requestUsers(state) { return { users: [], isLoading: true, }; }, receiveUsers(state, payload) { return { isLoading: false, users: payload, }; }, },...
ch("https://api.github.com/users"); const users = await response.json(); this.receiveUsers(users); return users; } catch (err) { console.log(err); this.receiveUsers([]); } }, }, }; export default g
se = await fet
{ "filepath": "examples/with-rematch/shared/models/github.js", "language": "javascript", "file_size": 791, "cut_index": 514, "middle_length": 14 }
from "@stitches/react"; import { createStitches } from "@stitches/react"; export const { config, createTheme, css, getCssText, globalCss, styled, theme, } = createStitches({ theme: { colors: { hiContrast: "hsl(206,10%,5%)", loContrast: "white", gray100: "hsl(206,22%,99%)", ...
1: "5px", 2: "10px", 3: "15px", 4: "20px", 5: "25px", 6: "35px", }, sizes: { 1: "5px", 2: "10px", 3: "15px", 4: "20px", 5: "25px", 6: "35px", }, fontSizes: { 1: "12px"
(252,100%,99%)", purple200: "hsl(252,100%,98%)", purple300: "hsl(252,100%,94%)", purple400: "hsl(252,75%,84%)", purple500: "hsl(252,78%,60%)", purple600: "hsl(252,80%,53%)", }, space: {
{ "filepath": "examples/with-stitches/stitches.config.ts", "language": "typescript", "file_size": 1754, "cut_index": 537, "middle_length": 229 }
} from "../stitches.config"; const Box = styled("div", {}); const Text = styled("p", { fontFamily: "$system", color: "$hiContrast", }); const Link = styled("a", { fontFamily: "$system", textDecoration: "none", color: "$purple600", }); const Container = styled("div", { marginX: "auto", paddingX: "$3",...
{ paddingY: "$6" }}> <Container size={{ "@initial": "1", "@bp1": "2" }}> <StitchesLogo /> <Text as="h1">Hello, from Stitches.</Text> <Text> For full documentation, visit{" "} <Link href="https://stitches.de
default function Home() { return ( <Box css={
{ "filepath": "examples/with-stitches/app/page.tsx", "language": "tsx", "file_size": 967, "cut_index": 582, "middle_length": 52 }
Head from "next/head"; import styles from "../styles/Home.module.css"; import ContactForm from "../components/contact-form"; export default function Home() { return ( <div className={styles.container}> <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </He...
h3> <ContactForm /> </div> </div> </main> <footer className={styles.footer}> <a href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
iption}> Get started by editing{" "} <code className={styles.code}>pages/index.js</code> </p> <div className={styles.grid}> <div className={styles.card}> <h3>Contact Us</
{ "filepath": "examples/with-formspree/pages/index.js", "language": "javascript", "file_size": 1221, "cut_index": 518, "middle_length": 229 }
import { useRouter } from "next/router"; import Link from "next/link"; import { format } from "url"; let counter = 0; export async function getServerSideProps() { counter++; return { props: { initialPropsCounter: counter } }; } export default function Index({ initialPropsCounter }) { const router = useRouter()...
Link> <button onClick={reload}>Reload</button> <button onClick={incrementCounter}>Change State Counter</button> <p>"getServerSideProps" ran for "{initialPropsCounter}" times.</p> <p>Counter: "{query.counter || 0}".</p> </div>
? parseInt(query.counter) : 0; const href = `/?counter=${currentCounter + 1}`; router.push(href, href, { shallow: true }); }; return ( <div> <h2>This is the Home Page</h2> <Link href="/about">About</
{ "filepath": "examples/with-shallow-routing/pages/index.js", "language": "javascript", "file_size": 1002, "cut_index": 512, "middle_length": 229 }
from "@apollo/server"; import { startServerAndCreateNextHandler } from "@as-integrations/next"; import { makeExecutableSchema } from "@graphql-tools/schema"; import { gql } from "graphql-tag"; const typeDefs = gql` type Query { users: [User!]! user(username: String): User } type User { name: String ...
{ return users.find((user) => user.username === username); }, }, }; export const schema = makeExecutableSchema({ typeDefs, resolvers }); const server = new ApolloServer({ schema, }); export default startServerAndCreateNextHandler(server);
return users; }, user(parent, { username })
{ "filepath": "examples/api-routes-apollo-server/pages/api/graphql.ts", "language": "typescript", "file_size": 844, "cut_index": 535, "middle_length": 52 }
SWR from "swr"; import fetcher from "libs/fetcher"; import Link from "next/link"; import styles from "./User.module.css"; import Social from "components/Social"; const User = () => { const { data, error } = useSWR("/api/user", fetcher); if (error) return <div>failed to load</div>; return ( <header classNam...
data.name} /> )} </Link> <h2 className={styles.headingLg}> <Link href="/">{data ? data.name : ""}</Link> </h2> {data ? <Social user={data} /> : ""} <p>{data ? data.bio : ""}</p> </header> ); }
alt={
{ "filepath": "examples/with-unsplash/components/User/index.tsx", "language": "tsx", "file_size": 816, "cut_index": 522, "middle_length": 14 }
ql from "../shared/query-graphql"; export default function UserProfile({ user }) { if (!user) { return <h1>User Not Found</h1>; } return ( <h1> {user.username} is {user.name} </h1> ); } export async function getStaticProps(context) { const { params } = context; const { username } = param...
on getStaticPaths() { const { users } = (await queryGraphql(` query { users { username } } `)) as { users: { username: string }[] }; return { paths: users.map(({ username }) => ({ params: { username }, })),
return { props: { user } }; } export async functi
{ "filepath": "examples/api-routes-apollo-server/pages/[username].tsx", "language": "tsx", "file_size": 864, "cut_index": 529, "middle_length": 52 }
useSWR from "swr"; import fetcher from "libs/fetcher"; import Link from "next/link"; import styles from "./Collections.module.css"; interface CollectionProps { id_collection?: number; } const Collections = ({ id_collection }: CollectionProps) => { const { data, error } = useSWR( "/api/collection" + (id_colle...
{styles.chip_remove} aria-label="Return to home" /> </Link> ) : ( <Link href={{ pathname: "/collection/[slug]", query: { id: id } }} as={`/collection/${slug}?id=${id}`}
{data.map(({ id, title, slug }) => id_collection ? ( <Link href="/" key={`collection_${slug}`} className={styles.chip}> {title} <Link href="/" className=
{ "filepath": "examples/with-unsplash/components/Collections/index.tsx", "language": "tsx", "file_size": 1187, "cut_index": 518, "middle_length": 229 }
{ GetStaticProps, GetStaticPaths, InferGetStaticPropsType, } from "next"; import Link from "next/link"; import { useRouter } from "next/router"; import LocaleSwitcher from "../../components/locale-switcher"; type GspPageProps = InferGetStaticPropsType<typeof getStaticProps>; export default function GspPage(prop...
itcher /> <Link href="/gsp">To getStaticProps page</Link> <br /> <Link href="/gssp">To getServerSideProps page</Link> <br /> <Link href="/">To index page</Link> <br /> </div> ); } type Props = { locale?: stri
ticProps page</h1> <p>Current slug: {query.slug}</p> <p>Current locale: {props.locale}</p> <p>Default locale: {defaultLocale}</p> <p>Configured locales: {JSON.stringify(props.locales)}</p> <LocaleSw
{ "filepath": "examples/i18n-routing-pages/pages/gsp/[slug].tsx", "language": "tsx", "file_size": 1490, "cut_index": 524, "middle_length": 229 }
ort type { GetServerSideProps, InferGetServerSidePropsType } from "next"; import Link from "next/link"; import { useRouter } from "next/router"; import LocaleSwitcher from "../components/locale-switcher"; type GsspPageProps = InferGetServerSidePropsType<typeof getServerSideProps>; export default function GsspPage(pr...
first">To dynamic getStaticProps page</Link> <br /> <Link href="/">To index page</Link> <br /> </div> ); } type Props = { locale?: string; locales?: string[]; }; export const getServerSideProps: GetServerSideProps<Props> = as
<p>Default locale: {defaultLocale}</p> <p>Configured locales: {JSON.stringify(props.locales)}</p> <LocaleSwitcher /> <Link href="/gsp">To getStaticProps page</Link> <br /> <Link href="/gsp/
{ "filepath": "examples/i18n-routing-pages/pages/gssp.tsx", "language": "tsx", "file_size": 1104, "cut_index": 515, "middle_length": 229 }
react"; import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client"; import { SchemaLink } from "@apollo/client/link/schema"; import { schema } from "../apollo/schema"; import merge from "deepmerge"; let apolloClient; function createIsomorphLink() { if (typeof window === "undefined") { return new Sch...
ient(); // If your page has Next.js data fetching methods that use Apollo Client, the initial state // gets hydrated here if (initialState) { // Get existing cache, loaded during client side data fetching const existingCache = _apolloClient.
{ ssrMode: typeof window === "undefined", link: createIsomorphLink(), cache: new InMemoryCache(), }); } export function initializeApollo(initialState = null) { const _apolloClient = apolloClient ?? createApolloCl
{ "filepath": "examples/api-routes-apollo-server-and-client/apollo/client.tsx", "language": "tsx", "file_size": 1646, "cut_index": 537, "middle_length": 229 }
ort type { GetStaticProps, InferGetStaticPropsType } from "next"; import Link from "next/link"; import { useRouter } from "next/router"; import LocaleSwitcher from "../../components/locale-switcher"; type GspPageProps = InferGetStaticPropsType<typeof getStaticProps>; export default function GspPage(props: GspPagePro...
etServerSideProps page</Link> <br /> <Link href="/">To index page</Link> <br /> </div> ); } type Props = { locale?: string; locales?: string[]; }; export const getStaticProps: GetStaticProps<Props> = async ({ locale, loca
cale: {defaultLocale}</p> <p>Configured locales: {JSON.stringify(props.locales)}</p> <LocaleSwitcher /> <Link href="/gsp/first">To dynamic getStaticProps page</Link> <br /> <Link href="/gssp">To g
{ "filepath": "examples/i18n-routing-pages/pages/gsp/index.tsx", "language": "tsx", "file_size": 1081, "cut_index": 515, "middle_length": 229 }
{ NextApiRequest, NextApiResponse } from "next"; import Unsplash, { toJson } from "unsplash-js"; import fetch from "node-fetch"; global.fetch = fetch; export default function download(req: NextApiRequest, res: NextApiResponse) { const { query: { id }, } = req; const u = new Unsplash({ accessKey: process.en...
.then((r) => r.buffer()) .then((buff) => { res.end(buff); resolve(); }) .catch((error) => { res.json(error); res.status(405).end(); resolve(); }); }
const filePath = json.links.download; const fileName = id + ".jpg"; res.setHeader( "content-disposition", "attachment; filename=" + fileName, ); fetch(filePath)
{ "filepath": "examples/with-unsplash/pages/api/photo/download/[id].tsx", "language": "tsx", "file_size": 1124, "cut_index": 518, "middle_length": 229 }
[KeyType]; }; /** Content for Author documents */ interface AuthorDocumentData { /** * Name field in *Author* * * - **Field Type**: Title * - **Placeholder**: Name of the author * - **API ID Path**: author.name * - **Tab**: Main * - **Documentation**: https://prismic.io/docs/core-concepts/rich-te...
rue` * - **Documentation**: https://prismic.io/docs/core-concepts/custom-types * * @typeParam Lang - Language API ID of the document. */ export type AuthorDocument<Lang extends string = string> = prismicT.PrismicDocumentWithoutUID< Simplify<Autho
* - **Tab**: Main * - **Documentation**: https://prismic.io/docs/core-concepts/image * */ picture: prismicT.ImageField<never>; } /** * Author document from Prismic * * - **API ID**: `author` * - **Repeatable**: `t
{ "filepath": "examples/cms-prismic/types.generated.ts", "language": "typescript", "file_size": 5818, "cut_index": 716, "middle_length": 229 }
ponent from "../../../../slices/Text"; export default { title: "slices/Text", }; export const _Default = () => ( <MyComponent slice={{ variation: "default", version: "sktwi1xtmkfgx8626", items: [{}], primary: { text: [ { type: "paragraph", text...
, }, { type: "paragraph", text: "Est consequat enim id quis consectetur exercitation reprehenderit. Nulla ut ut consequat ipsum nulla duis consequat nostrud eiusmod eiusmod ex incididunt consequat consequat minim
t: "Et nisi elit dolor pariatur pariatur nisi non est cillum aute.", spans: [], }, { type: "paragraph", text: "Officia deserunt sunt ad ut anim quis.", spans: []
{ "filepath": "examples/cms-prismic/.slicemachine/assets/slices/Text/index.stories.js", "language": "javascript", "file_size": 1257, "cut_index": 524, "middle_length": 229 }
ink"; import { PrismicNextImage } from "@prismicio/next"; import { ImageField } from "@prismicio/types"; import cn from "classnames"; type CoverImageProps = { title: string; image: ImageField; href?: string; }; export default function CoverImage({ title, image: imageField, href, }: CoverImageProps) { co...
-medium transition-shadow duration-200": href, })} /> ); return ( <div className="sm:mx-0"> {href ? ( <Link href={href} aria-label={title}> {image} </Link> ) : ( image )} </div> )
"hover:shadow
{ "filepath": "examples/cms-prismic/components/cover-image.tsx", "language": "tsx", "file_size": 810, "cut_index": 536, "middle_length": 14 }
nk"; import { DateField, ImageField, TitleField } from "@prismicio/types"; import { PrismicText } from "@prismicio/react"; import { asText, isFilled } from "@prismicio/helpers"; import { AuthorContentRelationshipField } from "../lib/types"; import Avatar from "../components/avatar"; import CoverImage from "../compone...
mage title={asText(title)} href={href} image={coverImage} /> </div> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28"> <div> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight"> <Lin
ationshipField; href: string; }; export default function HeroPost({ title, coverImage, date, excerpt, author, href, }: HeroPostProps) { return ( <section> <div className="mb-8 md:mb-16"> <CoverI
{ "filepath": "examples/cms-prismic/components/hero-post.tsx", "language": "tsx", "file_size": 1587, "cut_index": 537, "middle_length": 229 }
ic from "@prismicio/client"; import * as prismicNext from "@prismicio/next"; import sm from "../sm.json"; /** * The project's Prismic repository name. */ export const repositoryName = prismic.getRepositoryName(sm.apiEndpoint); /** * Route definitions for Prismic documents. */ const routes: prismic.Route[] = [ ...
ort const createClient = ({ previewData, req, ...config }: prismicNext.CreateClientConfig = {}) => { const client = prismic.createClient(sm.apiEndpoint, { routes, ...config, }); prismicNext.enableAutoPreviews({ client, previewData, req
nfig - Configuration for the Prismic client. */ exp
{ "filepath": "examples/cms-prismic/lib/prismic.ts", "language": "typescript", "file_size": 863, "cut_index": 529, "middle_length": 52 }
om "classnames"; import { EXAMPLE_PATH } from "../lib/constants"; import Container from "./container"; type AlertProps = { preview: boolean; }; export default function Alert({ preview }: AlertProps) { return ( <div className={cn("border-b", { "bg-accent-7 border-accent-7 text-white": preview, ...
>{" "} to exit preview mode. </> ) : ( <> The source code for this blog is{" "} <a href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
s page is a preview.{" "} <a href="/api/exit-preview" className="underline hover:text-cyan duration-200 transition-colors" > Click here </a
{ "filepath": "examples/cms-prismic/components/alert.tsx", "language": "tsx", "file_size": 1264, "cut_index": 524, "middle_length": 229 }
{ EXAMPLE_PATH } from "../lib/constants"; import Container from "./container"; export default function Footer() { return ( <footer className="bg-accent-1 border-t border-accent-2"> <Container> <div className="py-28 flex flex-col lg:flex-row items-center"> <h3 className="text-4xl lg:text...
der border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0" > Read Documentation </a> <a href={`https://github.com/vercel/next.js/tree/canary/examples
"flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2"> <a href="https://nextjs.org/docs/basic-features/pages" className="mx-3 bg-black hover:bg-white hover:text-black bor
{ "filepath": "examples/cms-prismic/components/footer.tsx", "language": "tsx", "file_size": 1211, "cut_index": 518, "middle_length": 229 }
"@prismicio/client"; import PostPreview from "../components/post-preview"; type MoreStoriesProps = { posts: Content.PostDocument[]; }; export default function MoreStories({ posts }: MoreStoriesProps) { return ( <section> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight...
st.url} title={post.data.title} coverImage={post.data.cover_image} date={post.data.date} author={post.data.author} excerpt={post.data.excerpt} /> ))} </div> </section>
view key={post.uid} href={po
{ "filepath": "examples/cms-prismic/components/more-stories.tsx", "language": "tsx", "file_size": 850, "cut_index": 535, "middle_length": 52 }
from "next/link"; import { DateField, ImageField, TitleField } from "@prismicio/types"; import { PrismicText } from "@prismicio/react"; import { asText, isFilled } from "@prismicio/helpers"; import { AuthorContentRelationshipField } from "../lib/types"; import Avatar from "../components/avatar"; import Date from "../...
ge title={asText(title)} href={href} image={coverImage} /> </div> <h3 className="text-3xl mb-3 leading-snug"> <Link href={href} className="hover:underline"> <PrismicText field={title} /> </Link> </h3> <div
ntRelationshipField; href: string; }; export default function PostPreview({ title, coverImage, date, excerpt, author, href, }: PostPreviewProps) { return ( <div> <div className="mb-5"> <CoverIma
{ "filepath": "examples/cms-prismic/components/post-preview.tsx", "language": "tsx", "file_size": 1303, "cut_index": 524, "middle_length": 229 }
rt { useRouter } from "next/router"; import { predicate } from "@prismicio/client"; import { asImageSrc, asText } from "@prismicio/helpers"; import { CMS_NAME } from "../../lib/constants"; import { PostDocumentWithAuthor } from "../../lib/types"; import { createClient } from "../../lib/prismic"; import Container from...
= { preview: boolean; post: PostDocumentWithAuthor; morePosts: PostDocumentWithAuthor[]; }; export default function Post({ post, morePosts, preview }: PostProps) { const router = useRouter(); return ( <Layout preview={preview}> <Cont
ody from "../../components/post-body"; import PostHeader from "../../components/post-header"; import PostTitle from "../../components/post-title"; import SectionSeparator from "../../components/section-separator"; type PostProps
{ "filepath": "examples/cms-prismic/pages/posts/[slug].tsx", "language": "tsx", "file_size": 3235, "cut_index": 614, "middle_length": 229 }
URL } from "../lib/constants"; export default function Intro() { return ( <section className="flex-col md:flex-row flex items-center md:justify-between mt-16 mb-16 md:mb-12"> <h1 className="text-6xl md:text-8xl font-bold tracking-tighter leading-tight md:pr-8"> Blog. </h1> <h4 className...
Next.js </a>{" "} and{" "} <a href={CMS_URL} className="underline hover:text-success duration-200 transition-colors" > {CMS_NAME} </a> . </h4> </section> )
xt-success duration-200 transition-colors" >
{ "filepath": "examples/cms-prismic/components/intro.tsx", "language": "tsx", "file_size": 847, "cut_index": 535, "middle_length": 52 }
ad"; import Container from "../components/container"; import MoreStories from "../components/more-stories"; import HeroPost from "../components/hero-post"; import Intro from "../components/intro"; import Layout from "../components/layout"; import { CMS_NAME } from "../lib/constants"; import { createClient } from "../li...
js Blog Example with ${CMS_NAME}`}</title> </Head> <Container> <Intro /> {heroPost && ( <HeroPost title={heroPost.data.title} href={heroPost.url} coverImage={heroPost
DocumentWithAuthor[]; }; export default function Index({ preview, allPosts }: IndexProps) { const [heroPost, ...morePosts] = allPosts; return ( <> <Layout preview={preview}> <Head> <title>{`Next.
{ "filepath": "examples/cms-prismic/pages/index.tsx", "language": "tsx", "file_size": 1743, "cut_index": 537, "middle_length": 229 }
onentProps } from "@prismicio/react"; import { Content } from "@prismicio/client"; type TextProps = SliceComponentProps<Content.TextSlice>; const Text = ({ slice }: TextProps) => { return ( <section className="text-lg leading-relaxed"> <PrismicRichText field={slice.primary.text} components...
</h2> ), paragraph: ({ children }) => <p className="my-6">{children}</p>, list: ({ children }) => <ul className="my-6">{children}</ul>, oList: ({ children }) => <ol className="my-6">{children}</ol>, }}
assName="text-2xl mt-8 mb-4 leading-snug">{children}
{ "filepath": "examples/cms-prismic/slices/Text/index.tsx", "language": "tsx", "file_size": 903, "cut_index": 547, "middle_length": 52 }
{ Html, Head, Main, NextScript } from "next/document"; export default function Document() { const meta = { title: "Next.js Blog Starter Kit", description: "Clone and deploy your own Next.js portfolio in minutes.", image: "https://assets.vercel.com/image/upload/q_auto/front/vercel/dps.png", }; retur...
e="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content="@yourname" /> <meta name="twitter:title" content={meta.title} /> <meta name="twitter:description" content={meta.description} /> <meta name=
" content={meta.title} /> <meta property="og:description" content={meta.description} /> <meta property="og:title" content={meta.title} /> <meta property="og:image" content={meta.image} /> <meta nam
{ "filepath": "examples/blog/pages/_document.tsx", "language": "tsx", "file_size": 1143, "cut_index": 518, "middle_length": 229 }
Post } from "@/interfaces/post"; import fs from "fs"; import matter from "gray-matter"; import { join } from "path"; const postsDirectory = join(process.cwd(), "_posts"); export function getPostSlugs() { return fs.readdirSync(postsDirectory); } export function getPostBySlug(slug: string) { const realSlug = slug...
; } export function getAllPosts(): Post[] { const slugs = getPostSlugs(); const posts = slugs .map((slug) => getPostBySlug(slug)) // sort posts by date in descending order .sort((post1, post2) => (post1.date > post2.date ? -1 : 1)); retu
return { ...data, slug: realSlug, content } as Post
{ "filepath": "examples/blog-starter/src/lib/api.ts", "language": "typescript", "file_size": 840, "cut_index": 520, "middle_length": 52 }
/_components/footer"; import { CMS_NAME, HOME_OG_IMAGE_URL } from "@/lib/constants"; import type { Metadata } from "next"; import { Inter } from "next/font/google"; import cn from "classnames"; import { ThemeSwitcher } from "./_components/theme-switcher"; import "./globals.css"; const inter = Inter({ subsets: ["latin...
rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png" />
{ images: [HOME_OG_IMAGE_URL], }, }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en" suppressHydrationWarning> <head> <link
{ "filepath": "examples/blog-starter/src/app/layout.tsx", "language": "tsx", "file_size": 1969, "cut_index": 537, "middle_length": 229 }
iner from "@/app/_components/container"; import { EXAMPLE_PATH } from "@/lib/constants"; export function Footer() { return ( <footer className="bg-neutral-50 border-t border-neutral-200 dark:bg-slate-800"> <Container> <div className="py-28 flex flex-col lg:flex-row items-center"> <h3 clas...
className="mx-3 bg-black hover:bg-white hover:text-black border border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0" > Read Documentation </a> <a
3> <div className="flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2"> <a href="https://nextjs.org/docs/app/building-your-application/routing/layouts-and-templates"
{ "filepath": "examples/blog-starter/src/app/_components/footer.tsx", "language": "tsx", "file_size": 1308, "cut_index": 524, "middle_length": 229 }
Avatar from "@/app/_components/avatar"; import CoverImage from "@/app/_components/cover-image"; import { type Author } from "@/interfaces/author"; import Link from "next/link"; import DateFormatter from "./date-formatter"; type Props = { title: string; coverImage: string; date: string; excerpt: string; auth...
l leading-tight"> <Link href={`/posts/${slug}`} className="hover:underline"> {title} </Link> </h3> <div className="mb-4 md:mb-0 text-lg"> <DateFormatter dateString={date} /> </
> <CoverImage title={title} src={coverImage} slug={slug} /> </div> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28"> <div> <h3 className="mb-4 text-4xl lg:text-5x
{ "filepath": "examples/blog-starter/src/app/_components/hero-post.tsx", "language": "tsx", "file_size": 1220, "cut_index": 518, "middle_length": 229 }
mport type { Config } from "tailwindcss"; const config: Config = { darkMode: "class", content: [ "./src/pages/**/*.{js,ts,jsx,tsx,mdx}", "./src/components/**/*.{js,ts,jsx,tsx,mdx}", "./src/app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { backgroundImage: { "gradient-radial": "...
}, fontSize: { "5xl": "2.5rem", "6xl": "2.75rem", "7xl": "4.5rem", "8xl": "6.25rem", }, boxShadow: { sm: "0 5px 10px rgba(0, 0, 0, 0.12)", md: "0 8px 30px rgba(0, 0, 0, 0.12)", }
"#FAFAFA", "accent-2": "#EAEAEA", "accent-7": "#333", success: "#0070f3", cyan: "#79FFE1", }, spacing: { 28: "7rem", }, letterSpacing: { tighter: "-.04em",
{ "filepath": "examples/blog-starter/tailwind.config.ts", "language": "typescript", "file_size": 1053, "cut_index": 513, "middle_length": 229 }
iner from "@/app/_components/container"; import { EXAMPLE_PATH } from "@/lib/constants"; import cn from "classnames"; type Props = { preview?: boolean; }; const Alert = ({ preview }: Props) => { return ( <div className={cn("border-b dark:bg-slate-800", { "bg-neutral-800 border-neutral-800 text-w...
here </a>{" "} to exit preview mode. </> ) : ( <> The source code for this blog is{" "} <a href={`https://github.com/vercel/next.js/tree/canary/exampl
This page is a preview.{" "} <a href="/api/exit-preview" className="underline hover:text-teal-300 duration-200 transition-colors" > Click
{ "filepath": "examples/blog-starter/src/app/_components/alert.tsx", "language": "tsx", "file_size": 1311, "cut_index": 524, "middle_length": 229 }
om "@prismicio/react"; import { asText, isFilled } from "@prismicio/helpers"; import { DateField, ImageField, TitleField } from "@prismicio/types"; import { AuthorContentRelationshipField } from "../lib/types"; import Avatar from "../components/avatar"; import Date from "../components/date"; import CoverImage from "....
assName="hidden md:block md:mb-12"> {isFilled.contentRelationship(author) && ( <Avatar name={asText(author.data.name)} picture={author.data.picture} /> )} </div> <div className="mb-8 m
RelationshipField; }; export default function PostHeader({ title, coverImage, date, author, }: PostHeaderProps) { return ( <> <PostTitle> <PrismicText field={title} /> </PostTitle> <div cl
{ "filepath": "examples/cms-prismic/components/post-header.tsx", "language": "tsx", "file_size": 1530, "cut_index": 537, "middle_length": 229 }
/app/_components/container"; import { HeroPost } from "@/app/_components/hero-post"; import { Intro } from "@/app/_components/intro"; import { MoreStories } from "@/app/_components/more-stories"; import { getAllPosts } from "@/lib/api"; export default function Index() { const allPosts = getAllPosts(); const heroP...
mage} date={heroPost.date} author={heroPost.author} slug={heroPost.slug} excerpt={heroPost.excerpt} /> {morePosts.length > 0 && <MoreStories posts={morePosts} />} </Container> </main> ); }
eroPost.coverI
{ "filepath": "examples/blog-starter/src/app/page.tsx", "language": "tsx", "file_size": 807, "cut_index": 536, "middle_length": 14 }
import DateFormatter from "./date-formatter"; import { PostTitle } from "@/app/_components/post-title"; import { type Author } from "@/interfaces/author"; type Props = { title: string; coverImage: string; date: string; author: Author; }; export function PostHeader({ title, coverImage, date, author }: Props) ...
age title={title} src={coverImage} /> </div> <div className="max-w-2xl mx-auto"> <div className="block md:hidden mb-6"> <Avatar name={author.name} picture={author.picture} /> </div> <div className="mb-6 text-lg
className="mb-8 md:mb-16 sm:mx-0"> <CoverIm
{ "filepath": "examples/blog-starter/src/app/_components/post-header.tsx", "language": "tsx", "file_size": 982, "cut_index": 582, "middle_length": 52 }
ext/link"; import Avatar from "./avatar"; import CoverImage from "./cover-image"; import DateFormatter from "./date-formatter"; type Props = { title: string; coverImage: string; date: string; excerpt: string; author: Author; slug: string; }; export function PostPreview({ title, coverImage, date, e...
/${slug}`} className="hover:underline"> {title} </Link> </h3> <div className="text-lg mb-4"> <DateFormatter dateString={date} /> </div> <p className="text-lg leading-relaxed mb-4">{excerpt}</p> <Avata
-3xl mb-3 leading-snug"> <Link href={`/posts
{ "filepath": "examples/blog-starter/src/app/_components/post-preview.tsx", "language": "tsx", "file_size": 957, "cut_index": 582, "middle_length": 52 }
"next"; import { notFound } from "next/navigation"; import { getAllPosts, getPostBySlug } from "@/lib/api"; import { CMS_NAME } from "@/lib/constants"; import markdownToHtml from "@/lib/markdownToHtml"; import Alert from "@/app/_components/alert"; import Container from "@/app/_components/container"; import Header from ...
iew={post.preview} /> <Container> <Header /> <article className="mb-32"> <PostHeader title={post.title} coverImage={post.coverImage} date={post.date} author={post.author}
s) { const params = await props.params; const post = getPostBySlug(params.slug); if (!post) { return notFound(); } const content = await markdownToHtml(post.content || ""); return ( <main> <Alert prev
{ "filepath": "examples/blog-starter/src/app/posts/[slug]/page.tsx", "language": "tsx", "file_size": 1708, "cut_index": 537, "middle_length": 229 }
nction Home() { return ( <div className="container"> <Head> <title>Next.js & HLS.js</title> <link rel="icon" href="/favicon.ico" /> </Head> <main> <h1 className="title"> Welcome to <a href="https://nextjs.org">Next.js!</a> </h1> <p className="d...
by{" "} <img src="/vercel.svg" alt="Vercel Logo" className="logo" /> </a> <div className="separator">.</div> <a href="https://mux.com?utm_source=create-next-app&utm_medium=with-hls-js&utm_campaign=create-next-ap
<footer> <a href="https://vercel.com?utm_source=create-next-app&utm_medium=with-hls-js&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > Powered
{ "filepath": "examples/with-hls-js/pages/index.js", "language": "javascript", "file_size": 4125, "cut_index": 614, "middle_length": 229 }
isFirst, isLast, isReleased, hasVoted, feature, pending, mutate, }: { isFirst: boolean; isLast: boolean; isReleased: boolean; hasVoted: boolean; feature: Feature; pending: boolean; mutate: any; }) { let upvoteWithId = upvote.bind(null, feature); // eslint-disable-next-line @typescript-esl...
ote(feature); }); }} className={clsx( "p-6 mx-8 flex items-center border-t border-l border-r", isFirst && "rounded-t-md", isLast && "border-b rounded-b-md", )} > <button className={clsx(
startTransition(async () => { mutate({ updatedFeature: { ...feature, score: Number(feature.score) + 1, }, pending: true, }); await upv
{ "filepath": "examples/with-redis/app/form.tsx", "language": "tsx", "file_size": 5428, "cut_index": 716, "middle_length": 229 }
act"; declare global { var updateDOM: () => void; } type ColorSchemePreference = "system" | "dark" | "light"; const STORAGE_KEY = "nextjs-blog-starter-theme"; const modes: ColorSchemePreference[] = ["system", "dark", "light"]; /** to reuse updateDOM function defined inside injected script */ /** function to be i...
teElement("style"); css.textContent = "*,*:after,*:before{transition:none !important;}"; document.head.appendChild(css); return () => { /* Force restyle */ getComputedStyle(document.body); /* Wait for next tick before removin
be injected in a different context */ const [SYSTEM, DARK, LIGHT] = ["system", "dark", "light"]; /** Modify transition globally to avoid patched transitions */ const modifyTransition = () => { const css = document.crea
{ "filepath": "examples/blog-starter/src/app/_components/theme-switcher.tsx", "language": "tsx", "file_size": 3183, "cut_index": 614, "middle_length": 229 }
erver"; import { kv } from "@vercel/kv"; import { revalidatePath } from "next/cache"; import { Feature } from "./types"; export async function saveFeature(feature: Feature, formData: FormData) { let newFeature = { ...feature, title: formData.get("feature") as string, }; await kv.hset(`item:${newFeature....
.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } if (email && validateEmail(email)) { await kv.sadd("emails", email); revalidatePath("/"); } } export async function upvote(feature: Feat
: FormData) { const email = formData.get("email"); function validateEmail(email: FormDataEntryValue) { const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\
{ "filepath": "examples/with-redis/app/actions.tsx", "language": "tsx", "file_size": 1242, "cut_index": 518, "middle_length": 229 }
t { useEffect, useRef } from "react"; import { gsap } from "gsap"; type TitleProps = { lineContent: string; lineContent2: string; }; export default function Title({ lineContent, lineContent2 }: TitleProps) { let line1 = useRef(null); let line2 = useRef(null); useEffect(() => { gsap.from([line1.current,...
<div className="line-wrap"> <div ref={line1} className="line"> {lineContent} </div> </div> <div className="line-wrap"> <div ref={line2} className="line"> {lineContent2} </div> </div>
ge-title">
{ "filepath": "examples/with-gsap/components/Title.tsx", "language": "tsx", "file_size": 804, "cut_index": 517, "middle_length": 14 }
VideoPlayer({ src }) { const videoRef = useRef(null); useEffect(() => { const video = videoRef.current; if (!video) return; video.controls = true; if (video.canPlayType("application/vnd.apple.mpegurl")) { // This will run in safari, where HLS is supported natively video.src = src; ...
s not support MSE https://developer.mozilla.org/docs/Web/API/Media_Source_Extensions_API", ); } }, [src, videoRef]); return ( <> <video ref={videoRef} /> <style jsx>{` video { max-width: 100%; }
sole.error( "This is an old browser that doe
{ "filepath": "examples/with-hls-js/components/video-player.js", "language": "javascript", "file_size": 942, "cut_index": 606, "middle_length": 52 }
m "./dotcms-image"; import Link from "next/link"; export const Bold = ({ children }) => <strong>{children}</strong>; export const Italic = ({ children }) => <em>{children}</em>; export const Strike = ({ children }) => <s>{children}</s>; export const Underline = ({ children }) => <u>{children}</u>; export const DotLink...
TextNode = (props) => { const { marks = [], text } = props; const mark = marks[0] || { type: "", attrs: {} }; const newProps = { ...props, marks: marks.slice(1) }; const Component = nodeMarks[mark?.type]; if (!Component) { return text; }
</a> ) : ( <Link href={href} target={target || "_self"}> {children} </Link> ); }; const nodeMarks = { link: DotLink, bold: Bold, underline: Underline, italic: Italic, strike: Strike, }; export const
{ "filepath": "examples/cms-dotcms/components/blocks.tsx", "language": "tsx", "file_size": 2316, "cut_index": 563, "middle_length": 229 }
below can be removed in production apps // Useful for getting started locally with SQLite async function findOrCreateTodosTable() { const result = await db.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name='todos'", ); if (!result || result?.rows?.length === 0) { await db.execute( ...
result.rows as unknown as TodoItem[]; if (!result || result?.rows?.length === 0) return null; return rows.map((row, index) => ( <Todo key={index} item={{ id: row.id, description: row.description, }} /> ));
it db.execute("SELECT * FROM todos"); const rows =
{ "filepath": "examples/with-turso/app/todo-list.tsx", "language": "tsx", "file_size": 917, "cut_index": 606, "middle_length": 52 }
iner from "../components/container"; import MoreStories from "../components/more-stories"; import HeroPost from "../components/hero-post"; import Intro from "../components/intro"; import Layout from "../components/layout"; import { getAllPostsFromCms } from "../lib/api"; import Head from "next/head"; import { CMS_NAME ...
&& ( <HeroPost title={heroPost.title} coverImage={heroPost.coverImage} date={heroPost.date} author={heroPost.author} slug={heroPost.slug} excerpt={heroPost.exce
const morePosts = allPosts.slice(1); return ( <> <Layout> <Head> <title>{`Next.js Blog Example with ${CMS_NAME}`}</title> </Head> <Container> <Intro /> {heroPost
{ "filepath": "examples/cms-sitefinity/pages/index.tsx", "language": "tsx", "file_size": 1301, "cut_index": 524, "middle_length": 229 }
URL } from "@/lib/constants"; export default function Intro() { return ( <section className="flex-col md:flex-row flex items-center md:justify-between mt-16 mb-16 md:mb-12"> <h1 className="text-6xl md:text-8xl font-bold tracking-tighter leading-tight md:pr-8"> Blog. </h1> <h4 className=...
Next.js </a>{" "} and{" "} <a href={CMS_URL} className="underline hover:text-success duration-200 transition-colors" > {CMS_NAME} </a> . </h4> </section> );
t-success duration-200 transition-colors" >
{ "filepath": "examples/cms-ghost/components/intro.js", "language": "javascript", "file_size": 846, "cut_index": 535, "middle_length": 52 }
* @type {import('tailwindcss').Config} */ module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", ], theme: { extend: { colors: { "accent-1": "#FAFAFA", "accent-2": "#EAEAEA", "accent-7": "#333", success: "#0070f3", ...
"5xl": "2.5rem", "6xl": "2.75rem", "7xl": "4.5rem", "8xl": "6.25rem", }, boxShadow: { small: "0 5px 10px rgba(0, 0, 0, 0.12)", medium: "0 8px 30px rgba(0, 0, 0, 0.12)", }, }, }, plugins:
tSize: {
{ "filepath": "examples/cms-datocms/tailwind.config.js", "language": "javascript", "file_size": 791, "cut_index": 514, "middle_length": 14 }
URL } from "@/lib/constants"; export default function Intro() { return ( <section className="flex-col md:flex-row flex items-center md:justify-between mt-16 mb-16 md:mb-12"> <h1 className="text-6xl md:text-8xl font-bold tracking-tighter leading-tight md:pr-8"> Blog. </h1> <h4 className=...
Next.js </a>{" "} and{" "} <a href={CMS_URL} className="underline hover:text-success duration-200 transition-colors" > {CMS_NAME} </a> . </h4> </section> );
t-success duration-200 transition-colors" >
{ "filepath": "examples/cms-datocms/components/intro.js", "language": "javascript", "file_size": 846, "cut_index": 535, "middle_length": 52 }
m"; import { Feature } from "./types"; export let metadata = { title: "Next.js and Redis Example", description: "Feature roadmap example with Next.js with Redis.", }; function VercelLogo(props: React.SVGProps<SVGSVGElement>) { return ( <svg aria-label="Vercel Logo" xmlns="http://www.w3.org/2000/...
ength) { return []; } let multi = kv.multi(); itemIds.forEach((id) => { multi.hgetall(`item:${id}`); }); let items: Feature[] = await multi.exec(); return items.map((item) => { return { ...item, s
venodd" stroke="#000" strokeWidth="1.5" /> </svg> ); } async function getFeatures() { try { let itemIds = await kv.zrange("items_by_score", 0, 100, { rev: true, }); if (!itemIds.l
{ "filepath": "examples/with-redis/app/page.tsx", "language": "tsx", "file_size": 4442, "cut_index": 614, "middle_length": 229 }
https://www.datocms.com/…udCBpZD0iYSIgeTE
2BZnVsbF9zbWFsbGVyPC90aXRsZT48cGF0aCBkPSJNMzkuMzQ0Ljg0NEgwVjgwLjAzN0gzOS4zNDRjMTkuNjc3LDAsMzkuMzQzLTE3LjcyOSwzOS4zNDMtMzkuNTkxUzU5LjAyMS44NDQsMzkuMzQ0Ljg0NFptMCw1Ny41ODlhMTcuOTkzLDE3Ljk5MywwLDEsMSwxOC0xNy45ODdBMTcuOTg2LDE3Ljk4NiwwLDAsMSwzOS4zNDQsNTguNDMzWi
9IjQwLjQ0IiB4Mj0iNzguNjg3IiB5Mj0iNDAuNDQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj48c3RvcCBvZmZzZXQ9IjAiIHN0b3AtY29sb3I9IiNmZjU5M2QiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNmZjc3NTEiLz48L2xpbmVhckdyYWRpZW50PjwvZGVmcz48dGl0bGU%
{ "filepath": "examples/cms-datocms/lib/constants.js", "language": "javascript", "file_size": 3341, "cut_index": 614, "middle_length": 229 }
Container from "./container"; import { EXAMPLE_PATH } from "@/lib/constants"; export default function Footer() { return ( <footer className="bg-accent-1 border-t border-accent-2"> <Container> <div className="py-28 flex flex-col lg:flex-row items-center"> <h3 className="text-4xl lg:text-5...
r border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0" > Read Documentation </a> <a href={`https://github.com/vercel/next.js/tree/canary/examples/$
lex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2"> <a href="https://nextjs.org/docs/basic-features/pages" className="mx-3 bg-black hover:bg-white hover:text-black borde
{ "filepath": "examples/cms-datocms/components/footer.js", "language": "javascript", "file_size": 1209, "cut_index": 518, "middle_length": 229 }
Container from "./container"; import cn from "classnames"; import { EXAMPLE_PATH } from "@/lib/constants"; export default function Alert({ preview }) { return ( <div className={cn("border-b", { "bg-accent-7 border-accent-7 text-white": preview, "bg-accent-1 border-accent-2": !preview, ...
</> ) : ( <> The source code for this blog is{" "} <a href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`} className="underline hover:text-succes
href="/api/exit-preview" className="underline hover:text-cyan duration-200 transition-colors" > Click here </a>{" "} to exit preview mode.
{ "filepath": "examples/cms-datocms/components/alert.js", "language": "javascript", "file_size": 1205, "cut_index": 518, "middle_length": 229 }
from "next/head"; import { CMS_NAME, HOME_OG_IMAGE_URL } from "@/lib/constants"; export default function Meta() { return ( <Head> <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" /> <link rel="icon" type="image/png" ...
favicon.ico" /> <meta name="msapplication-TileColor" content="#000000" /> <meta name="msapplication-config" content="/favicon/browserconfig.xml" /> <meta name="theme-color" content="#000" /> <link rel="alternate" type="application/r
/> <link rel="manifest" href="/favicon/site.webmanifest" /> <link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#000000" /> <link rel="shortcut icon" href="/favicon/
{ "filepath": "examples/cms-datocms/components/meta.js", "language": "javascript", "file_size": 1254, "cut_index": 524, "middle_length": 229 }