move into sonardesk
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
return [
|
||||
'default_page_key' => 'home',
|
||||
'regions' => ['header', 'body', 'footer'],
|
||||
];
|
||||
@@ -0,0 +1,244 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Content\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\Content\Models\ContentDocument;
|
||||
use Modules\Content\Models\ContentType;
|
||||
use Modules\Content\Models\PageContent;
|
||||
use Modules\Menus\Models\Menu;
|
||||
use Modules\Settings\Services\SettingsRepository;
|
||||
|
||||
final class InstallSaaslandContent extends Command
|
||||
{
|
||||
protected $signature = 'content:install-saasland {--force : Replace the existing home composition}';
|
||||
protected $description = 'Install editable Saasland header, body and footer content documents.';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$requiredTables = ['content_types', 'content_documents', 'page_content'];
|
||||
$missingTables = array_values(array_filter($requiredTables, static fn (string $table): bool => ! Schema::hasTable($table)));
|
||||
|
||||
if ($missingTables !== []) {
|
||||
$this->components->error('Content composition tables are missing: '.implode(', ', $missingTables).'.');
|
||||
$this->components->info('Run php artisan migrate before installing the Saasland composition.');
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
DB::transaction(function (): void {
|
||||
$this->installSharedSettings();
|
||||
$this->installMenus();
|
||||
if ($this->option('force')) {
|
||||
PageContent::query()->where('page_key', 'home')->delete();
|
||||
}
|
||||
|
||||
$order = [
|
||||
'site-header' => ['header', 10], 'hero' => ['body', 10], 'feature-grid' => ['body', 20],
|
||||
'product-feed' => ['body', 30], 'testimonial-feed' => ['body', 40], 'team-feed' => ['body', 50],
|
||||
'blog-feed' => ['body', 60], 'news-feed' => ['body', 70], 'faq-feed' => ['body', 80],
|
||||
'newsletter-form' => ['body', 90], 'call-to-action' => ['body', 100], 'site-footer' => ['footer', 10],
|
||||
];
|
||||
|
||||
foreach ($this->definitions() as $key => $definition) {
|
||||
$type = ContentType::query()->updateOrCreate(['key' => $key], $definition['type']);
|
||||
$document = ContentDocument::query()->firstOrCreate(
|
||||
['slug' => 'saasland-'.$key],
|
||||
[
|
||||
'content_type_id' => $type->id,
|
||||
'title' => $definition['title'],
|
||||
'data' => $definition['data'],
|
||||
'status' => 'published',
|
||||
'published_at' => now(),
|
||||
]
|
||||
);
|
||||
|
||||
$currentData = is_array($document->data) ? $document->data : [];
|
||||
$mergedData = $this->mergeMissingDefaults($currentData, $definition['data']);
|
||||
|
||||
$document->forceFill([
|
||||
'content_type_id' => $type->id,
|
||||
'data' => $mergedData,
|
||||
])->save();
|
||||
[$region, $sort] = $order[$key];
|
||||
PageContent::query()->updateOrCreate(
|
||||
['page_key' => 'home', 'region' => $region, 'sort_order' => $sort],
|
||||
['content_document_id' => $document->id, 'is_enabled' => true]
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
$this->components->info('Saasland content composition installed with editable schemas.');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function installSharedSettings(): void
|
||||
{
|
||||
$settings = app(SettingsRepository::class);
|
||||
$legacy = [];
|
||||
|
||||
if (Schema::hasTable('stylist_theme_settings')) {
|
||||
$stored = DB::table('stylist_theme_settings')->where('theme_key', 'saasland')->value('settings');
|
||||
$legacy = is_string($stored) ? (json_decode($stored, true) ?: []) : [];
|
||||
}
|
||||
|
||||
$defaults = [
|
||||
'site_name' => $legacy['site_title'] ?? config('app.name'),
|
||||
'site_description' => $legacy['site_description'] ?? 'Modern software for modern companies.',
|
||||
'company_name' => $legacy['site_title'] ?? config('app.name'),
|
||||
'site_url' => url('/'),
|
||||
'logo_url' => $legacy['logo_url'] ?? '',
|
||||
'facebook_url' => $legacy['facebook_url'] ?? '',
|
||||
'x_url' => $legacy['x_url'] ?? '',
|
||||
'linkedin_url' => $legacy['linkedin_url'] ?? '',
|
||||
'dashboard_label' => 'Dashboard',
|
||||
'login_label' => 'Log in',
|
||||
'registration_label' => 'Get started',
|
||||
];
|
||||
|
||||
foreach ($defaults as $key => $value) {
|
||||
if ($settings->get($key, null, 'site') === null) {
|
||||
$settings->put($key, $value, 'site', 'string', true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function installMenus(): void
|
||||
{
|
||||
if (! Schema::hasTable('menus')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$menus = [
|
||||
'primary' => ['Primary navigation', [['enabled' => true, 'label' => 'Home', 'url' => '/'], ['enabled' => true, 'label' => 'Blog', 'url' => '/blog'], ['enabled' => true, 'label' => 'News', 'url' => '/news']]],
|
||||
'footer' => ['Footer — Explore', [['enabled' => true, 'label' => 'Home', 'url' => '/'], ['enabled' => true, 'label' => 'Blog', 'url' => '/blog'], ['enabled' => true, 'label' => 'News', 'url' => '/news']]],
|
||||
'footer_account' => ['Footer — Account', [['enabled' => true, 'label' => 'Dashboard', 'url' => '/dashboard'], ['enabled' => true, 'label' => 'Profile', 'url' => '/settings/profile']]],
|
||||
'footer_legal' => ['Footer — Legal', []],
|
||||
];
|
||||
|
||||
foreach ($menus as $location => [$name, $items]) {
|
||||
Menu::query()->firstOrCreate(['location' => $location], ['name' => $name, 'items' => $items, 'enabled' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
private function mergeMissingDefaults(array $current, array $defaults): array
|
||||
{
|
||||
foreach ($defaults as $key => $defaultValue) {
|
||||
if (! array_key_exists($key, $current)) {
|
||||
$current[$key] = $defaultValue;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
is_array($defaultValue)
|
||||
&& is_array($current[$key])
|
||||
&& ! array_is_list($defaultValue)
|
||||
&& ! array_is_list($current[$key])
|
||||
) {
|
||||
$current[$key] = $this->mergeMissingDefaults(
|
||||
$current[$key],
|
||||
$defaultValue
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $current;
|
||||
}
|
||||
|
||||
private function definitions(): array
|
||||
{
|
||||
$field = static fn (string $key, string $label, string $type = 'text', array $extra = []): array => array_merge(compact('key', 'label', 'type'), $extra);
|
||||
$type = static fn (string $name, string $renderer, array $regions, array $schema): array => [
|
||||
'name' => $name, 'renderer' => $renderer, 'allowed_regions' => $regions,
|
||||
'is_system' => true, 'is_active' => true, 'schema' => $schema,
|
||||
];
|
||||
$section = [$field('enabled', 'Show this section', 'boolean', ['default' => true])];
|
||||
$feed = array_merge($section, [
|
||||
$field('eyebrow', 'Eyebrow'), $field('heading', 'Heading'), $field('description', 'Description', 'textarea'),
|
||||
$field('limit', 'Maximum items', 'number', ['min' => 1, 'max' => 50]),
|
||||
$field('include_ids', 'Only show record IDs', 'csv', ['help' => 'Optional comma-separated IDs. Leave blank to use the latest records.']),
|
||||
$field('exclude_ids', 'Exclude record IDs', 'csv', ['help' => 'Optional comma-separated IDs to hide from this section.']),
|
||||
]);
|
||||
|
||||
return [
|
||||
'site-header' => [
|
||||
'title' => 'Main website header',
|
||||
'type' => $type('Site header', 'site-header', ['header'], [
|
||||
$field('enabled', 'Show header', 'boolean', ['default' => true]),
|
||||
$field('menu_location', 'Navigation menu location', 'text', ['help' => 'Usually primary. Edit links from Administration → Menus.']),
|
||||
$field('show_navigation', 'Show navigation', 'boolean', ['default' => true]),
|
||||
$field('show_dashboard', 'Show dashboard link', 'boolean', ['default' => true]),
|
||||
$field('show_user_name', 'Show signed-in user', 'boolean', ['default' => true]),
|
||||
$field('show_login', 'Show login', 'boolean', ['default' => true]),
|
||||
$field('show_registration', 'Show registration', 'boolean', ['default' => true]),
|
||||
$field('show_mobile_menu', 'Show mobile menu', 'boolean', ['default' => true]),
|
||||
]),
|
||||
'data' => ['enabled' => true, 'menu_location' => 'primary', 'show_navigation' => true, 'show_dashboard' => true, 'show_user_name' => true, 'show_login' => true, 'show_registration' => true, 'show_mobile_menu' => true],
|
||||
],
|
||||
'hero' => [
|
||||
'title' => 'Homepage hero',
|
||||
'type' => $type('Hero', 'hero', ['body'], [
|
||||
...$section, $field('eyebrow', 'Eyebrow'), $field('heading', 'Heading'), $field('description', 'Description', 'textarea'),
|
||||
$field('primary_label', 'Primary button label'), $field('primary_url', 'Primary button URL', 'url'),
|
||||
$field('secondary_label', 'Secondary button label'), $field('secondary_url', 'Secondary button URL', 'url'),
|
||||
$field('show_metrics', 'Show metrics panel', 'boolean', ['default' => true]),
|
||||
$field('metrics', 'Metrics', 'repeater', ['fields' => [
|
||||
$field('enabled', 'Show item', 'boolean', ['default' => true]), $field('label', 'Label'), $field('value', 'Value'), $field('change', 'Change'), $field('height', 'Chart height (%)', 'number', ['min' => 0, 'max' => 100]),
|
||||
]]),
|
||||
]),
|
||||
'data' => ['enabled' => true, 'eyebrow' => 'A better way to run your business', 'heading' => 'Transform Your Business With Our SaaS Solution', 'description' => 'Streamline operations, boost productivity, and improve customer satisfaction with one connected platform built for modern teams.', 'primary_label' => 'Get started free', 'primary_url' => '/register', 'secondary_label' => 'Book demo', 'secondary_url' => '#contact', 'show_metrics' => true, 'metrics' => [
|
||||
['enabled' => true, 'label' => 'Monthly revenue', 'value' => '£48,240', 'change' => '+18.4%', 'height' => 62],
|
||||
['enabled' => true, 'label' => 'Active users', 'value' => '12,842', 'change' => '+9.2%', 'height' => 78],
|
||||
['enabled' => true, 'label' => 'Conversion', 'value' => '7.8%', 'change' => '+2.1%', 'height' => 92],
|
||||
]],
|
||||
],
|
||||
'feature-grid' => [
|
||||
'title' => 'Core features',
|
||||
'type' => $type('Feature grid', 'feature-grid', ['body'], [
|
||||
...$section, $field('eyebrow', 'Eyebrow'), $field('heading', 'Heading'), $field('description', 'Description', 'textarea'),
|
||||
$field('items', 'Features', 'repeater', ['fields' => [$field('enabled', 'Show item', 'boolean', ['default' => true]), $field('title', 'Title'), $field('description', 'Description', 'textarea')]]),
|
||||
]),
|
||||
'data' => ['enabled' => true, 'eyebrow' => 'Powerful features', 'heading' => 'Everything your team needs to grow', 'description' => 'Planning, collaboration, reporting, publishing, commerce and customer insight in one extensible platform.', 'items' => [
|
||||
['enabled' => true, 'title' => 'Smart automation', 'description' => 'Remove repetitive work and delays.'],
|
||||
['enabled' => true, 'title' => 'Real-time analytics', 'description' => 'Turn activity into useful business insight.'],
|
||||
['enabled' => true, 'title' => 'Content operations', 'description' => 'Create, review and publish confidently.'],
|
||||
['enabled' => true, 'title' => 'Secure by design', 'description' => 'Protect users and data with dependable controls.'],
|
||||
['enabled' => true, 'title' => 'Flexible integrations', 'description' => 'Connect the tools your organisation already uses.'],
|
||||
['enabled' => true, 'title' => 'Modular architecture', 'description' => 'Activate only the capabilities each site needs.'],
|
||||
]],
|
||||
],
|
||||
'product-feed' => ['title' => 'Pricing plans', 'type' => $type('Product feed', 'product-feed', ['body'], $feed), 'data' => ['enabled' => true, 'eyebrow' => 'Simple pricing', 'heading' => 'Choose a plan that fits', 'description' => 'Plans are managed from Products & Pricing in the CMS.', 'limit' => 6, 'include_ids' => '', 'exclude_ids' => '']],
|
||||
'testimonial-feed' => ['title' => 'Customer stories', 'type' => $type('Testimonial feed', 'testimonial-feed', ['body'], $feed), 'data' => ['enabled' => true, 'eyebrow' => 'Customer stories', 'heading' => 'Trusted by ambitious teams', 'description' => '', 'limit' => 6, 'include_ids' => '', 'exclude_ids' => '']],
|
||||
'team-feed' => ['title' => 'Team', 'type' => $type('Team feed', 'team-feed', ['body'], $feed), 'data' => ['enabled' => true, 'eyebrow' => 'Our team', 'heading' => 'People behind the platform', 'description' => '', 'limit' => 8, 'include_ids' => '', 'exclude_ids' => '']],
|
||||
'blog-feed' => ['title' => 'Latest blog posts', 'type' => $type('Blog feed', 'blog-feed', ['body'], $feed), 'data' => ['enabled' => true, 'eyebrow' => 'Insights', 'heading' => 'Latest from the blog', 'description' => '', 'limit' => 3, 'include_ids' => '', 'exclude_ids' => '']],
|
||||
'news-feed' => ['title' => 'Latest news', 'type' => $type('News feed', 'news-feed', ['body'], $feed), 'data' => ['enabled' => true, 'eyebrow' => 'Newsroom', 'heading' => 'Latest news', 'description' => '', 'limit' => 3, 'include_ids' => '', 'exclude_ids' => '']],
|
||||
'faq-feed' => ['title' => 'Frequently asked questions', 'type' => $type('FAQ feed', 'faq-feed', ['body'], $feed), 'data' => ['enabled' => true, 'eyebrow' => 'FAQ', 'heading' => 'Answers before you begin', 'description' => '', 'limit' => 12, 'include_ids' => '', 'exclude_ids' => '']],
|
||||
'newsletter-form' => [
|
||||
'title' => 'Newsletter signup',
|
||||
'type' => $type('Newsletter form', 'newsletter-form', ['body'], [...$section, $field('eyebrow', 'Eyebrow'), $field('heading', 'Heading'), $field('description', 'Description', 'textarea'), $field('placeholder', 'Email placeholder'), $field('button_label', 'Button label')]),
|
||||
'data' => ['enabled' => true, 'eyebrow' => 'Newsletter', 'heading' => 'Useful updates, no noise', 'description' => 'Receive product news, publishing guidance, and practical platform updates.', 'placeholder' => 'you@example.com', 'button_label' => 'Subscribe'],
|
||||
],
|
||||
'call-to-action' => [
|
||||
'title' => 'Homepage final call to action',
|
||||
'type' => $type('Call to action', 'call-to-action', ['body'], [...$section, $field('anchor', 'Section anchor'), $field('heading', 'Heading'), $field('description', 'Description', 'textarea'), $field('button_label', 'Button label'), $field('button_url', 'Button URL', 'url')]),
|
||||
'data' => ['enabled' => true, 'anchor' => 'contact', 'heading' => 'Ready to transform your business?', 'description' => 'Start building a faster, more connected operation today.', 'button_label' => 'Get started free', 'button_url' => '/register'],
|
||||
],
|
||||
'site-footer' => [
|
||||
'title' => 'Main website footer',
|
||||
'type' => $type('Site footer', 'site-footer', ['footer'], [
|
||||
$field('enabled', 'Show footer', 'boolean', ['default' => true]),
|
||||
$field('explore_heading', 'Explore column heading'),
|
||||
$field('explore_menu_location', 'Explore menu location'),
|
||||
$field('account_heading', 'Account column heading'),
|
||||
$field('account_menu_location', 'Account menu location'),
|
||||
$field('legal_heading', 'Legal column heading'),
|
||||
$field('legal_menu_location', 'Legal menu location'),
|
||||
$field('show_back_to_top', 'Show back-to-top link', 'boolean', ['default' => true]),
|
||||
$field('back_to_top_label', 'Back-to-top label'),
|
||||
]),
|
||||
'data' => ['enabled' => true, 'explore_heading' => 'Explore', 'explore_menu_location' => 'footer', 'account_heading' => 'Account', 'account_menu_location' => 'footer_account', 'legal_heading' => 'Legal', 'legal_menu_location' => 'footer_legal', 'show_back_to_top' => true, 'back_to_top_label' => 'Back to top ↑'],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('content_types', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('name');
|
||||
$table->string('key')->unique();
|
||||
$table->text('description')->nullable();
|
||||
$table->json('schema')->nullable();
|
||||
$table->string('renderer');
|
||||
$table->json('allowed_regions')->nullable();
|
||||
$table->boolean('is_system')->default(false);
|
||||
$table->boolean('is_active')->default(true);
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('content_documents', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('content_type_id')->constrained('content_types')->cascadeOnDelete();
|
||||
$table->string('title');
|
||||
$table->string('slug')->unique();
|
||||
$table->json('data')->nullable();
|
||||
$table->string('status')->default('draft')->index();
|
||||
$table->timestamp('published_at')->nullable()->index();
|
||||
$table->timestamp('expires_at')->nullable();
|
||||
$table->string('language', 12)->nullable();
|
||||
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamps();
|
||||
$table->softDeletes();
|
||||
});
|
||||
|
||||
Schema::create('page_content', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('page_id')->nullable()->constrained('pages')->cascadeOnDelete();
|
||||
$table->string('page_key')->nullable()->index();
|
||||
$table->foreignId('content_document_id')->constrained('content_documents')->cascadeOnDelete();
|
||||
$table->string('region')->index();
|
||||
$table->unsignedInteger('sort_order')->default(0);
|
||||
$table->boolean('is_enabled')->default(true);
|
||||
$table->json('visibility_rules')->nullable();
|
||||
$table->json('presentation')->nullable();
|
||||
$table->timestamp('starts_at')->nullable();
|
||||
$table->timestamp('ends_at')->nullable();
|
||||
$table->timestamps();
|
||||
$table->unique(['page_key', 'region', 'sort_order'], 'page_content_key_region_order_unique');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('page_content');
|
||||
Schema::dropIfExists('content_documents');
|
||||
Schema::dropIfExists('content_types');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Content\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
use Modules\Content\Models\ContentDocument;
|
||||
use Modules\Content\Models\ContentType;
|
||||
|
||||
final class ContentDocumentController extends Controller
|
||||
{
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$documents = ContentDocument::query()
|
||||
->with('type')
|
||||
->withCount('placements')
|
||||
->when($request->string('type')->isNotEmpty(), fn ($query) => $query->whereHas('type', fn ($type) => $type->where('key', $request->string('type')->toString())))
|
||||
->when($request->string('status')->isNotEmpty(), fn ($query) => $query->where('status', $request->string('status')->toString()))
|
||||
->when($request->string('search')->isNotEmpty(), fn ($query) => $query->where('title', 'like', '%'.$request->string('search')->toString().'%'))
|
||||
->orderBy('title')
|
||||
->paginate(30)
|
||||
->withQueryString();
|
||||
|
||||
return view('content::admin.index', [
|
||||
'documents' => $documents,
|
||||
'types' => ContentType::query()->where('is_active', true)->orderBy('name')->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function create(Request $request): View
|
||||
{
|
||||
$types = ContentType::query()->where('is_active', true)->orderBy('name')->get();
|
||||
$selectedType = $types->firstWhere('id', (int) $request->integer('type')) ?? $types->first();
|
||||
|
||||
return view('content::admin.form', [
|
||||
'document' => new ContentDocument(['status' => 'draft', 'data' => []]),
|
||||
'types' => $types,
|
||||
'selectedType' => $selectedType,
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $this->validateDocument($request);
|
||||
$type = ContentType::query()->where('is_active', true)->findOrFail($validated['content_type_id']);
|
||||
|
||||
$document = ContentDocument::query()->create([
|
||||
'content_type_id' => $type->id,
|
||||
'title' => $validated['title'],
|
||||
'slug' => $this->uniqueSlug($validated['slug'] ?: $validated['title']),
|
||||
'status' => $validated['status'],
|
||||
'published_at' => $validated['status'] === 'published' ? ($validated['published_at'] ?? now()) : null,
|
||||
'expires_at' => $validated['expires_at'] ?? null,
|
||||
'data' => json_decode($validated['data_json'], true, 512, JSON_THROW_ON_ERROR),
|
||||
'created_by' => $request->user()?->id,
|
||||
'updated_by' => $request->user()?->id,
|
||||
]);
|
||||
|
||||
return redirect()->route('content.documents.edit', $document)->with('status', 'Content document created.');
|
||||
}
|
||||
|
||||
public function edit(ContentDocument $document): View
|
||||
{
|
||||
$document->load('type', 'placements');
|
||||
|
||||
return view('content::admin.form', [
|
||||
'document' => $document,
|
||||
'types' => ContentType::query()->where('is_active', true)->orderBy('name')->get(),
|
||||
'selectedType' => $document->type,
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, ContentDocument $document): RedirectResponse
|
||||
{
|
||||
$validated = $this->validateDocument($request, $document);
|
||||
|
||||
$document->update([
|
||||
'content_type_id' => $validated['content_type_id'],
|
||||
'title' => $validated['title'],
|
||||
'slug' => $this->uniqueSlug($validated['slug'] ?: $validated['title'], $document),
|
||||
'status' => $validated['status'],
|
||||
'published_at' => $validated['status'] === 'published' ? ($validated['published_at'] ?? $document->published_at ?? now()) : null,
|
||||
'expires_at' => $validated['expires_at'] ?? null,
|
||||
'data' => json_decode($validated['data_json'], true, 512, JSON_THROW_ON_ERROR),
|
||||
'updated_by' => $request->user()?->id,
|
||||
]);
|
||||
|
||||
return back()->with('status', 'Content document updated.');
|
||||
}
|
||||
|
||||
public function duplicate(Request $request, ContentDocument $document): RedirectResponse
|
||||
{
|
||||
$copy = $document->replicate(['slug', 'status', 'published_at', 'created_by', 'updated_by']);
|
||||
$copy->title = $document->title.' copy';
|
||||
$copy->slug = $this->uniqueSlug($copy->title);
|
||||
$copy->status = 'draft';
|
||||
$copy->published_at = null;
|
||||
$copy->created_by = $request->user()?->id;
|
||||
$copy->updated_by = $request->user()?->id;
|
||||
$copy->save();
|
||||
|
||||
return redirect()->route('content.documents.edit', $copy)->with('status', 'Independent draft copy created.');
|
||||
}
|
||||
|
||||
public function destroy(ContentDocument $document): RedirectResponse
|
||||
{
|
||||
if ($document->placements()->exists()) {
|
||||
return back()->withErrors(['document' => 'Remove this document from every page before deleting it.']);
|
||||
}
|
||||
|
||||
$document->delete();
|
||||
|
||||
return redirect()->route('content.index')->with('status', 'Content document deleted.');
|
||||
}
|
||||
|
||||
private function validateDocument(Request $request, ?ContentDocument $document = null): array
|
||||
{
|
||||
return $request->validate([
|
||||
'content_type_id' => ['required', 'integer', Rule::exists('content_types', 'id')->where('is_active', true)],
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
'slug' => ['nullable', 'string', 'max:255'],
|
||||
'status' => ['required', Rule::in(['draft', 'published'])],
|
||||
'published_at' => ['nullable', 'date'],
|
||||
'expires_at' => ['nullable', 'date', 'after:published_at'],
|
||||
'data_json' => ['required', 'json'],
|
||||
]);
|
||||
}
|
||||
|
||||
private function uniqueSlug(string $value, ?ContentDocument $except = null): string
|
||||
{
|
||||
$base = Str::slug($value) ?: 'content-document';
|
||||
$slug = $base;
|
||||
$suffix = 2;
|
||||
|
||||
while (ContentDocument::withTrashed()->where('slug', $slug)->when($except, fn ($query) => $query->whereKeyNot($except->getKey()))->exists()) {
|
||||
$slug = $base.'-'.$suffix++;
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Content\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
use Modules\Content\Models\ContentDocument;
|
||||
use Modules\Content\Models\PageContent;
|
||||
use Modules\Pages\Models\Page;
|
||||
|
||||
final class PageCompositionController extends Controller
|
||||
{
|
||||
private const REGIONS = ['header', 'body', 'footer'];
|
||||
|
||||
public function edit(string $pageKey): View
|
||||
{
|
||||
$placements = PageContent::query()
|
||||
->with('document.type')
|
||||
->where('page_key', $pageKey)
|
||||
->orderByRaw("CASE region WHEN 'header' THEN 1 WHEN 'body' THEN 2 ELSE 3 END")
|
||||
->orderBy('sort_order')
|
||||
->get()
|
||||
->groupBy('region');
|
||||
|
||||
$documents = ContentDocument::query()
|
||||
->with('type')
|
||||
->withCount('placements')
|
||||
->orderBy('title')
|
||||
->get();
|
||||
|
||||
return view('content::admin.composition', compact('pageKey', 'placements', 'documents'));
|
||||
}
|
||||
|
||||
|
||||
public function editPage(Page $page): View
|
||||
{
|
||||
$placements = PageContent::query()
|
||||
->with('document.type')
|
||||
->where(fn ($query) => $query->where('page_id', $page->id)->orWhere('page_key', $page->slug))
|
||||
->orderByRaw("CASE region WHEN 'header' THEN 1 WHEN 'body' THEN 2 ELSE 3 END")
|
||||
->orderBy('sort_order')
|
||||
->get();
|
||||
|
||||
PageContent::query()
|
||||
->whereNull('page_id')
|
||||
->where('page_key', $page->slug)
|
||||
->update(['page_id' => $page->id]);
|
||||
|
||||
$documents = ContentDocument::query()
|
||||
->with('type')
|
||||
->withCount('placements')
|
||||
->orderBy('title')
|
||||
->get();
|
||||
|
||||
return view('content::admin.composition', [
|
||||
'pageKey' => $page->slug,
|
||||
'page' => $page,
|
||||
'placements' => $placements->groupBy('region'),
|
||||
'documents' => $documents,
|
||||
]);
|
||||
}
|
||||
|
||||
public function preview(string $pageKey): View
|
||||
{
|
||||
abort_unless($pageKey === 'home', 404, 'This phase currently provides the Saasland homepage preview.');
|
||||
|
||||
return view('stylist-theme-saasland::home', ['pageKey' => $pageKey]);
|
||||
}
|
||||
|
||||
public function store(Request $request, string $pageKey): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'content_document_id' => ['required', 'integer', Rule::exists('content_documents', 'id')->whereNull('deleted_at')],
|
||||
'region' => ['required', Rule::in(self::REGIONS)],
|
||||
]);
|
||||
|
||||
$document = ContentDocument::query()->with('type')->findOrFail($validated['content_document_id']);
|
||||
abort_unless(in_array($validated['region'], $document->type?->allowed_regions ?? [], true), 422, 'This content type is not allowed in the selected region.');
|
||||
|
||||
$page = Page::query()->where('slug', $pageKey)->first();
|
||||
$nextOrder = ((int) PageContent::query()->where(fn ($query) => $query->where('page_key', $pageKey)->when($page, fn ($q) => $q->orWhere('page_id', $page->id)))->where('region', $validated['region'])->max('sort_order')) + 10;
|
||||
PageContent::query()->create([
|
||||
'page_id' => $page?->id,
|
||||
'page_key' => $pageKey,
|
||||
'content_document_id' => $document->id,
|
||||
'region' => $validated['region'],
|
||||
'sort_order' => $nextOrder,
|
||||
'is_enabled' => true,
|
||||
]);
|
||||
|
||||
return back()->with('status', 'Document added to the '.$validated['region'].' region.');
|
||||
}
|
||||
|
||||
public function update(Request $request, PageContent $placement): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'is_enabled' => ['nullable', 'boolean'],
|
||||
'starts_at' => ['nullable', 'date'],
|
||||
'ends_at' => ['nullable', 'date', 'after:starts_at'],
|
||||
]);
|
||||
|
||||
$placement->update([
|
||||
'is_enabled' => $request->boolean('is_enabled'),
|
||||
'starts_at' => $validated['starts_at'] ?? null,
|
||||
'ends_at' => $validated['ends_at'] ?? null,
|
||||
]);
|
||||
|
||||
return back()->with('status', 'Page placement updated.');
|
||||
}
|
||||
|
||||
public function destroy(PageContent $placement): RedirectResponse
|
||||
{
|
||||
$placement->delete();
|
||||
$this->normaliseRegion($placement->page_key, $placement->region);
|
||||
|
||||
return back()->with('status', 'Document removed from this page. The reusable document was not deleted.');
|
||||
}
|
||||
|
||||
public function duplicate(Request $request, PageContent $placement): RedirectResponse
|
||||
{
|
||||
$source = $placement->document()->firstOrFail();
|
||||
$copy = DB::transaction(function () use ($request, $placement, $source): ContentDocument {
|
||||
$copy = $source->replicate(['slug', 'status', 'published_at', 'created_by', 'updated_by']);
|
||||
$copy->title = $source->title.' copy';
|
||||
$copy->slug = $source->slug.'-copy-'.strtolower(str()->random(6));
|
||||
$copy->status = 'draft';
|
||||
$copy->published_at = null;
|
||||
$copy->created_by = $request->user()?->id;
|
||||
$copy->updated_by = $request->user()?->id;
|
||||
$copy->save();
|
||||
|
||||
PageContent::query()->create([
|
||||
'page_id' => $placement->page_id,
|
||||
'page_key' => $placement->page_key,
|
||||
'content_document_id' => $copy->id,
|
||||
'region' => $placement->region,
|
||||
'sort_order' => $placement->sort_order + 5,
|
||||
'is_enabled' => false,
|
||||
'visibility_rules' => $placement->visibility_rules,
|
||||
'presentation' => $placement->presentation,
|
||||
]);
|
||||
|
||||
return $copy;
|
||||
});
|
||||
|
||||
$this->normaliseRegion($placement->page_key, $placement->region);
|
||||
|
||||
return redirect()->route('content.documents.edit', $copy)->with('status', 'Page-specific draft copy created and added after the original.');
|
||||
}
|
||||
|
||||
public function reorder(Request $request, string $pageKey): JsonResponse|RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'region' => ['required', Rule::in(self::REGIONS)],
|
||||
'placements' => ['required', 'array'],
|
||||
'placements.*' => ['required', 'integer'],
|
||||
]);
|
||||
|
||||
$ids = array_values(array_unique(array_map('intval', $validated['placements'])));
|
||||
$owned = PageContent::query()->where('page_key', $pageKey)->where('region', $validated['region'])->whereIn('id', $ids)->pluck('id')->all();
|
||||
abort_unless(count($owned) === count($ids), 422, 'One or more placements do not belong to this page region.');
|
||||
|
||||
DB::transaction(function () use ($ids): void {
|
||||
PageContent::query()->whereIn('id', $ids)->increment('sort_order', 100000);
|
||||
foreach ($ids as $index => $id) {
|
||||
PageContent::query()->whereKey($id)->update(['sort_order' => ($index + 1) * 10]);
|
||||
}
|
||||
});
|
||||
|
||||
return $request->expectsJson()
|
||||
? response()->json(['message' => 'Order saved.'])
|
||||
: back()->with('status', 'Page order updated.');
|
||||
}
|
||||
|
||||
private function normaliseRegion(?string $pageKey, string $region): void
|
||||
{
|
||||
$ids = PageContent::query()->where('page_key', $pageKey)->where('region', $region)->orderBy('sort_order')->pluck('id');
|
||||
DB::transaction(function () use ($ids): void {
|
||||
foreach ($ids as $index => $id) {
|
||||
PageContent::query()->whereKey($id)->update(['sort_order' => ($index + 1) * 10]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
namespace Modules\Content\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
final class ContentDocument extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
protected $fillable = ['content_type_id','title','slug','data','status','published_at','expires_at','language','created_by','updated_by'];
|
||||
protected function casts(): array { return ['data'=>'array','published_at'=>'datetime','expires_at'=>'datetime']; }
|
||||
public function type(): BelongsTo { return $this->belongsTo(ContentType::class, 'content_type_id'); }
|
||||
public function placements(): HasMany { return $this->hasMany(PageContent::class); }
|
||||
public function scopePublished($query) { return $query->where('status','published')->where(fn($q) => $q->whereNull('published_at')->orWhere('published_at','<=',now()))->where(fn($q) => $q->whereNull('expires_at')->orWhere('expires_at','>',now())); }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
namespace Modules\Content\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
final class ContentType extends Model
|
||||
{
|
||||
protected $fillable = ['name','key','description','schema','renderer','allowed_regions','is_system','is_active'];
|
||||
protected function casts(): array { return ['schema'=>'array','allowed_regions'=>'array','is_system'=>'boolean','is_active'=>'boolean']; }
|
||||
public function documents(): HasMany { return $this->hasMany(ContentDocument::class); }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
namespace Modules\Content\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Pages\Models\Page;
|
||||
|
||||
final class PageContent extends Model
|
||||
{
|
||||
protected $table = 'page_content';
|
||||
protected $fillable = ['page_id','page_key','content_document_id','region','sort_order','is_enabled','visibility_rules','presentation','starts_at','ends_at'];
|
||||
protected function casts(): array { return ['is_enabled'=>'boolean','visibility_rules'=>'array','presentation'=>'array','starts_at'=>'datetime','ends_at'=>'datetime']; }
|
||||
public function document(): BelongsTo { return $this->belongsTo(ContentDocument::class, 'content_document_id'); }
|
||||
public function page(): BelongsTo { return $this->belongsTo(Page::class); }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
namespace Modules\Content\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Modules\Content\Console\InstallSaaslandContent;
|
||||
use Modules\Content\Services\PageRenderer;
|
||||
|
||||
final class ContentServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(module_path('Content','Config/config.php'),'content');
|
||||
$this->app->singleton(PageRenderer::class);
|
||||
}
|
||||
public function boot(): void
|
||||
{
|
||||
$this->loadMigrationsFrom(module_path('Content','Database/Migrations'));
|
||||
$this->loadViewsFrom(module_path('Content','Resources/views'),'content');
|
||||
$this->loadRoutesFrom(module_path('Content','Routes/web.php'));
|
||||
if ($this->app->runningInConsole()) $this->commands([InstallSaaslandContent::class]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
# Content Composer
|
||||
|
||||
The Content module provides reusable typed documents and ordered page regions.
|
||||
|
||||
## Phase 2 features
|
||||
|
||||
- Header, body and footer composition editor.
|
||||
- Drag-and-drop ordering with server-side ownership validation.
|
||||
- Add existing published or draft documents to a page.
|
||||
- Remove a placement without deleting the reusable document.
|
||||
- Create an independent page-specific draft copy.
|
||||
- Shared-use warnings and deletion protection.
|
||||
- Placement enable/disable and date scheduling.
|
||||
- Content document creation, duplication, filtering and publishing controls.
|
||||
- Authenticated Saasland homepage preview, including draft labels.
|
||||
- Content Composer entry in the administration sidebar.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
php artisan migrate
|
||||
php artisan content:install-saasland
|
||||
```
|
||||
|
||||
Reset the seeded homepage composition when required:
|
||||
|
||||
```bash
|
||||
php artisan content:install-saasland --force
|
||||
```
|
||||
|
||||
Administration:
|
||||
|
||||
- `/admin/content`
|
||||
- `/admin/content/pages/home`
|
||||
- `/admin/content/pages/home/preview`
|
||||
|
||||
The public theme remains backward-compatible: when no composition exists, the legacy Saasland homepage, header and footer are rendered.
|
||||
@@ -0,0 +1,147 @@
|
||||
<x-layouts.app :title="isset($page) ? 'Edit content: '.$page->title : 'Page composition: '.$pageKey">
|
||||
<div class="space-y-6" x-data="compositionEditor()">
|
||||
<div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div>
|
||||
<div class="flex items-center gap-2 text-sm text-zinc-500"><a href="{{ route('administration.pages.index') }}" class="hover:text-zinc-900 dark:hover:text-white">Pages</a><span>/</span><span>Content composer</span></div>
|
||||
<h1 class="mt-1 text-3xl font-semibold tracking-tight">{{ isset($page) ? $page->title : ucfirst($pageKey).' page' }}</h1>
|
||||
<p class="mt-1 text-sm text-zinc-500">Add sections, edit their content and drag them into the order visitors should see.</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
@isset($page)<flux:button :href="route('administration.pages.edit', $page)" variant="ghost">Page settings</flux:button>@endisset
|
||||
<flux:button :href="route('content.documents.create')">Create section</flux:button>
|
||||
@if(isset($page) && $page->status === 'published')<flux:button variant="primary" :href="route('pages.public.show', $page->slug)" target="_blank">Open live page</flux:button>@endif
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if(session('status'))<div class="rounded-xl border border-green-300 bg-green-50 p-4 text-sm text-green-800 dark:border-green-800 dark:bg-green-950 dark:text-green-200">{{ session('status') }}</div>@endif
|
||||
@if($errors->any())<div class="rounded-xl border border-red-300 bg-red-50 p-4 text-sm text-red-800"><ul class="list-disc pl-5">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>@endif
|
||||
|
||||
<div class="grid gap-6 2xl:grid-cols-[minmax(0,1fr)_25rem]">
|
||||
<div class="space-y-6">
|
||||
@foreach(['header', 'body', 'footer'] as $region)
|
||||
<section class="overflow-hidden rounded-2xl border border-zinc-200 bg-zinc-50 dark:border-zinc-700 dark:bg-zinc-950">
|
||||
<div class="flex items-center justify-between border-b border-zinc-200 bg-white px-5 py-4 dark:border-zinc-700 dark:bg-zinc-900">
|
||||
<div><h2 class="text-lg font-semibold">{{ ucfirst($region) }}</h2><p class="text-xs text-zinc-500">{{ $region === 'body' ? 'Ordered content sections' : 'Page-level '.$region.' document' }}</p></div>
|
||||
<span class="rounded-full bg-zinc-100 px-2 py-1 text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-300">{{ $placements->get($region, collect())->count() }} document{{ $placements->get($region, collect())->count() === 1 ? '' : 's' }}</span>
|
||||
</div>
|
||||
<div class="min-h-24 space-y-3 p-4" data-region="{{ $region }}" @dragover.prevent @drop="drop($event, '{{ $region }}')">
|
||||
@forelse($placements->get($region, collect()) as $placement)
|
||||
<article draggable="true" data-placement-id="{{ $placement->id }}" @dragstart="startDrag($event)" class="group rounded-xl border border-zinc-200 bg-white p-4 shadow-sm transition hover:border-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:hover:border-zinc-500 {{ $placement->is_enabled ? '' : 'opacity-60' }}">
|
||||
<div class="flex items-start gap-3">
|
||||
<button type="button" title="Drag to reorder" class="mt-1 cursor-grab select-none text-xl leading-none text-zinc-400 active:cursor-grabbing">⋮⋮</button>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<h3 class="font-semibold">{{ $placement->document?->title }}</h3>
|
||||
<span class="rounded bg-zinc-100 px-2 py-0.5 text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-300">{{ $placement->document?->type?->name }}</span>
|
||||
@if(($placement->document?->placements()->count() ?? 0) > 1)<span class="rounded bg-blue-100 px-2 py-0.5 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-200">Shared</span>@endif
|
||||
@unless($placement->is_enabled)<span class="rounded bg-amber-100 px-2 py-0.5 text-xs text-amber-700 dark:bg-amber-950 dark:text-amber-200">Disabled</span>@endunless
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-zinc-500">Order {{ $placement->sort_order }} · {{ $placement->document?->status === 'published' ? 'Published' : 'Draft — hidden from public rendering' }}</p>
|
||||
</div>
|
||||
<a href="{{ route('content.documents.edit', $placement->document) }}" class="text-sm font-medium underline">Edit</a>
|
||||
</div>
|
||||
|
||||
<details class="mt-4 border-t border-zinc-100 pt-3 dark:border-zinc-800">
|
||||
<summary class="cursor-pointer text-sm text-zinc-600 dark:text-zinc-300">Placement settings</summary>
|
||||
<div class="mt-4 grid gap-4 lg:grid-cols-[1fr_1fr_auto]">
|
||||
<form method="POST" action="{{ route('content.placements.update', $placement) }}" class="contents">
|
||||
@csrf @method('PUT')
|
||||
<flux:input type="datetime-local" name="starts_at" label="Show from" value="{{ $placement->starts_at?->format('Y-m-d\TH:i') }}" />
|
||||
<flux:input type="datetime-local" name="ends_at" label="Hide after" value="{{ $placement->ends_at?->format('Y-m-d\TH:i') }}" />
|
||||
<div class="flex items-end gap-2">
|
||||
<label class="mb-2 flex items-center gap-2 text-sm"><input type="checkbox" name="is_enabled" value="1" @checked($placement->is_enabled)> Enabled</label>
|
||||
<flux:button type="submit" size="sm">Save</flux:button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<form method="POST" action="{{ route('content.placements.duplicate', $placement) }}">@csrf<flux:button type="submit" size="sm">Create page-specific copy</flux:button></form>
|
||||
<form method="POST" action="{{ route('content.placements.destroy', $placement) }}" onsubmit="return confirm('Remove this document from the page? The reusable document itself will remain available.')">@csrf @method('DELETE')<flux:button type="submit" size="sm" variant="danger">Remove from page</flux:button></form>
|
||||
</div>
|
||||
</details>
|
||||
</article>
|
||||
@empty
|
||||
<div class="rounded-xl border-2 border-dashed border-zinc-300 p-8 text-center text-sm text-zinc-500 dark:border-zinc-700">No documents assigned to this region.</div>
|
||||
@endforelse
|
||||
</div>
|
||||
</section>
|
||||
@endforeach
|
||||
</div>
|
||||
|
||||
<aside class="space-y-6 2xl:sticky 2xl:top-6 2xl:self-start">
|
||||
<flux:card class="space-y-4">
|
||||
<div><h2 class="text-lg font-semibold">Add content section</h2><p class="text-sm text-zinc-500">Choose an existing section from the content library. Draft sections remain hidden from visitors.</p></div>
|
||||
<form method="POST" action="{{ route('content.placements.store', $pageKey) }}" class="space-y-4">
|
||||
@csrf
|
||||
<flux:select name="region" label="Region" required>
|
||||
<option value="header">Header</option><option value="body" selected>Body</option><option value="footer">Footer</option>
|
||||
</flux:select>
|
||||
<label class="block text-sm font-medium">Content section
|
||||
<select name="content_document_id" required class="mt-2 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 dark:border-zinc-700 dark:bg-zinc-950">
|
||||
<option value="">Select a content section</option>
|
||||
@foreach($documents as $document)
|
||||
<option value="{{ $document->id }}" data-regions="{{ implode(',', $document->type?->allowed_regions ?? []) }}">{{ $document->title }} — {{ $document->type?->name }}{{ $document->status === 'draft' ? ' (draft)' : '' }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
<flux:button type="submit" variant="primary" class="w-full">Add section</flux:button>
|
||||
</form>
|
||||
</flux:card>
|
||||
|
||||
<flux:card>
|
||||
<h2 class="text-lg font-semibold">Editing shared content</h2>
|
||||
<p class="mt-2 text-sm text-zinc-500">Editing a shared document changes every placement. “Create page-specific copy” makes a disabled draft copy beside the original so it can be reviewed before switching.</p>
|
||||
</flux:card>
|
||||
|
||||
<flux:card>
|
||||
<h2 class="text-lg font-semibold">Live order</h2>
|
||||
<p class="mt-2 text-sm text-zinc-500">Order is saved automatically after dropping a document. A confirmation appears here.</p>
|
||||
<p x-show="message" x-text="message" class="mt-3 rounded-lg bg-zinc-100 p-3 text-sm dark:bg-zinc-800"></p>
|
||||
</flux:card>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@push('scripts')
|
||||
<script>
|
||||
function compositionEditor() {
|
||||
return {
|
||||
dragged: null,
|
||||
message: '',
|
||||
startDrag(event) {
|
||||
this.dragged = event.currentTarget;
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
event.dataTransfer.setData('text/plain', this.dragged.dataset.placementId);
|
||||
},
|
||||
async drop(event, region) {
|
||||
if (!this.dragged) return;
|
||||
const container = event.currentTarget;
|
||||
const target = event.target.closest('[data-placement-id]');
|
||||
if (target && target !== this.dragged) {
|
||||
const rect = target.getBoundingClientRect();
|
||||
container.insertBefore(this.dragged, event.clientY < rect.top + rect.height / 2 ? target : target.nextSibling);
|
||||
} else if (!target) {
|
||||
container.appendChild(this.dragged);
|
||||
}
|
||||
const ids = [...container.querySelectorAll('[data-placement-id]')].map(item => Number(item.dataset.placementId));
|
||||
this.message = 'Saving order…';
|
||||
try {
|
||||
const response = await fetch(@js(route('content.placements.reorder', $pageKey)), {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content},
|
||||
body: JSON.stringify({region, placements: ids})
|
||||
});
|
||||
if (!response.ok) throw new Error((await response.json()).message || 'Unable to save order.');
|
||||
this.message = 'Order saved.';
|
||||
} catch (error) {
|
||||
this.message = error.message;
|
||||
window.setTimeout(() => window.location.reload(), 1200);
|
||||
} finally {
|
||||
this.dragged = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@endpush
|
||||
</x-layouts.app>
|
||||
@@ -0,0 +1,636 @@
|
||||
<x-layouts.app :title="$document->exists ? $document->title : __('Create content document')">
|
||||
<div class="mx-auto max-w-7xl space-y-6" id="content-editor">
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<a href="{{ route('content.index') }}" class="text-sm text-zinc-500 hover:underline">
|
||||
Content documents
|
||||
</a>
|
||||
<h1 class="mt-1 text-2xl font-semibold">
|
||||
{{ $document->exists ? $document->title : 'Create content document' }}
|
||||
</h1>
|
||||
<p class="mt-1 text-sm text-zinc-500">
|
||||
Edit every frontend field below. JSON is retained only as an emergency advanced tool.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@if ($document->exists)
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<form method="POST" action="{{ route('content.documents.duplicate', $document) }}">
|
||||
@csrf
|
||||
<flux:button type="submit" size="sm">Create independent copy</flux:button>
|
||||
</form>
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ route('content.documents.destroy', $document) }}"
|
||||
onsubmit="return confirm('Delete this unplaced document permanently?')"
|
||||
>
|
||||
@csrf
|
||||
@method('DELETE')
|
||||
<flux:button type="submit" size="sm" variant="danger">Delete</flux:button>
|
||||
</form>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
@if (session('status'))
|
||||
<div class="rounded-xl border border-green-300 bg-green-50 p-4 text-sm text-green-800">
|
||||
{{ session('status') }}
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($errors->any())
|
||||
<div class="rounded-xl border border-red-300 bg-red-50 p-4 text-sm text-red-800">
|
||||
<ul class="list-disc pl-5">
|
||||
@foreach ($errors->all() as $error)
|
||||
<li>{{ $error }}</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($document->exists && $document->placements->count() > 1)
|
||||
<div class="rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900">
|
||||
<strong>Shared document.</strong>
|
||||
Changes affect all {{ $document->placements->count() }} placements.
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ $document->exists ? route('content.documents.update', $document) : route('content.documents.store') }}"
|
||||
class="grid gap-6 xl:grid-cols-[minmax(0,1fr)_21rem]"
|
||||
id="document-form"
|
||||
>
|
||||
@csrf
|
||||
@if ($document->exists)
|
||||
@method('PUT')
|
||||
@endif
|
||||
|
||||
<div class="space-y-6">
|
||||
<flux:card class="space-y-5">
|
||||
<h2 class="text-lg font-semibold">Document</h2>
|
||||
<flux:input name="title" label="Internal title" value="{{ old('title', $document->title) }}" required />
|
||||
<flux:input name="slug" label="Slug" value="{{ old('slug', $document->slug) }}" />
|
||||
<flux:select name="content_type_id" label="Content type" id="content-type-select" required>
|
||||
@foreach ($types as $type)
|
||||
<option
|
||||
value="{{ $type->id }}"
|
||||
@selected((int) old('content_type_id', $selectedType?->id) === $type->id)
|
||||
>
|
||||
{{ $type->name }}
|
||||
</option>
|
||||
@endforeach
|
||||
</flux:select>
|
||||
</flux:card>
|
||||
|
||||
<flux:card class="space-y-5">
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold">Frontend content</h2>
|
||||
<p class="text-sm text-zinc-500">
|
||||
Switches take effect when this document is saved.
|
||||
</p>
|
||||
</div>
|
||||
<span id="schema-status" class="rounded-full bg-zinc-100 px-3 py-1 text-xs text-zinc-600"></span>
|
||||
</div>
|
||||
|
||||
<div id="schema-fields" class="space-y-5"></div>
|
||||
|
||||
<details class="rounded-xl border border-zinc-200 p-4 dark:border-zinc-700">
|
||||
<summary class="cursor-pointer text-sm font-medium">Advanced JSON (emergency use only)</summary>
|
||||
<p class="mt-2 text-xs text-zinc-500">
|
||||
Normal editing should be performed with the controls above.
|
||||
</p>
|
||||
<textarea
|
||||
id="data-json"
|
||||
class="mt-4 min-h-80 w-full rounded-xl border border-zinc-300 bg-white p-4 font-mono text-sm dark:border-zinc-700 dark:bg-zinc-950"
|
||||
name="data_json"
|
||||
spellcheck="false"
|
||||
>{{ old('data_json', json_encode($document->data ?: [], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) }}</textarea>
|
||||
</details>
|
||||
</flux:card>
|
||||
</div>
|
||||
|
||||
<aside class="space-y-6">
|
||||
<flux:card class="space-y-4">
|
||||
<h2 class="text-lg font-semibold">Publishing</h2>
|
||||
<flux:select name="status" label="Status">
|
||||
<option value="draft" @selected(old('status', $document->status ?: 'draft') === 'draft')>Draft</option>
|
||||
<option value="published" @selected(old('status', $document->status) === 'published')>Published</option>
|
||||
</flux:select>
|
||||
<flux:input
|
||||
type="datetime-local"
|
||||
name="published_at"
|
||||
label="Publish at"
|
||||
value="{{ old('published_at', $document->published_at?->format('Y-m-d\TH:i')) }}"
|
||||
/>
|
||||
<flux:input
|
||||
type="datetime-local"
|
||||
name="expires_at"
|
||||
label="Expire at"
|
||||
value="{{ old('expires_at', $document->expires_at?->format('Y-m-d\TH:i')) }}"
|
||||
/>
|
||||
<flux:button type="submit" variant="primary" class="w-full">Save document</flux:button>
|
||||
</flux:card>
|
||||
|
||||
@if ($document->exists)
|
||||
<flux:card>
|
||||
<h2 class="text-lg font-semibold">Usage</h2>
|
||||
<div class="mt-3 space-y-2">
|
||||
@forelse ($document->placements as $placement)
|
||||
<a
|
||||
class="block rounded-lg border p-3 text-sm"
|
||||
href="{{ route('content.pages.edit', $placement->page_key) }}"
|
||||
>
|
||||
<strong>{{ ucfirst($placement->page_key) }}</strong>
|
||||
<span class="block text-xs uppercase text-zinc-500">{{ $placement->region }}</span>
|
||||
</a>
|
||||
@empty
|
||||
<p class="text-sm text-zinc-500">Not placed on a page.</p>
|
||||
@endforelse
|
||||
</div>
|
||||
</flux:card>
|
||||
@endif
|
||||
</aside>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const rawSchemas = @json($types->mapWithKeys(fn ($type) => [(string) $type->id => $type->schema ?? []]));
|
||||
const dataField = document.getElementById('data-json');
|
||||
const host = document.getElementById('schema-fields');
|
||||
const typeSelect = document.getElementById('content-type-select');
|
||||
const status = document.getElementById('schema-status');
|
||||
const form = document.getElementById('document-form');
|
||||
|
||||
let data = parseObject(dataField.value);
|
||||
|
||||
function parseObject(value) {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(value || '{}');
|
||||
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||
? parsed
|
||||
: {};
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function normaliseSchema(raw) {
|
||||
if (typeof raw === 'string') {
|
||||
try {
|
||||
raw = JSON.parse(raw);
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(raw)) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
if (! raw || typeof raw !== 'object') {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (Array.isArray(raw.fields)) {
|
||||
return raw.fields;
|
||||
}
|
||||
|
||||
if (Array.isArray(raw.schema)) {
|
||||
return raw.schema;
|
||||
}
|
||||
|
||||
return Object.values(raw).filter(
|
||||
field => field && typeof field === 'object' && field.key
|
||||
);
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '').replace(/[&<>"']/g, character => ({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
})[character]);
|
||||
}
|
||||
|
||||
function pathParts(path) {
|
||||
return String(path || '')
|
||||
.split('.')
|
||||
.filter(part => part !== '');
|
||||
}
|
||||
|
||||
function getAtPath(path) {
|
||||
return pathParts(path).reduce((value, part) => {
|
||||
if (value === undefined || value === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return value[part];
|
||||
}, data);
|
||||
}
|
||||
|
||||
function setAtPath(path, value) {
|
||||
const parts = pathParts(path);
|
||||
|
||||
if (! parts.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
let target = data;
|
||||
|
||||
parts.forEach((part, index) => {
|
||||
const isLast = index === parts.length - 1;
|
||||
|
||||
if (isLast) {
|
||||
target[part] = value;
|
||||
return;
|
||||
}
|
||||
|
||||
const nextPart = parts[index + 1];
|
||||
const shouldBeArray = /^\d+$/.test(nextPart);
|
||||
|
||||
if (
|
||||
target[part] === undefined
|
||||
|| target[part] === null
|
||||
|| typeof target[part] !== 'object'
|
||||
) {
|
||||
target[part] = shouldBeArray ? [] : {};
|
||||
}
|
||||
|
||||
target = target[part];
|
||||
});
|
||||
|
||||
syncJson();
|
||||
}
|
||||
|
||||
function fieldForPath(schema, path) {
|
||||
const parts = pathParts(path);
|
||||
let fields = schema;
|
||||
let matched = null;
|
||||
|
||||
for (const part of parts) {
|
||||
if (/^\d+$/.test(part)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
matched = (fields || []).find(field => field.key === part) ?? null;
|
||||
|
||||
if (! matched) {
|
||||
return null;
|
||||
}
|
||||
|
||||
fields = matched.fields || [];
|
||||
}
|
||||
|
||||
return matched;
|
||||
}
|
||||
|
||||
function defaultValue(field) {
|
||||
if (Object.prototype.hasOwnProperty.call(field, 'default')) {
|
||||
return structuredClone(field.default);
|
||||
}
|
||||
|
||||
if (field.type === 'boolean') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (field.type === 'repeater') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
function newRepeaterItem(field) {
|
||||
const item = {};
|
||||
|
||||
(field.fields || []).forEach(child => {
|
||||
item[child.key] = defaultValue(child);
|
||||
});
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
function hydrateMissingFields(fields, target) {
|
||||
(fields || []).forEach(field => {
|
||||
if (! Object.prototype.hasOwnProperty.call(target, field.key)) {
|
||||
target[field.key] = defaultValue(field);
|
||||
}
|
||||
|
||||
if (field.type === 'repeater') {
|
||||
if (! Array.isArray(target[field.key])) {
|
||||
target[field.key] = [];
|
||||
}
|
||||
|
||||
target[field.key].forEach(item => {
|
||||
if (item && typeof item === 'object' && ! Array.isArray(item)) {
|
||||
hydrateMissingFields(field.fields || [], item);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function syncJson() {
|
||||
dataField.value = JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
function fieldMarkup(field, value, path) {
|
||||
const help = field.help
|
||||
? `<p class="mt-1 text-xs text-zinc-500">${escapeHtml(field.help)}</p>`
|
||||
: '';
|
||||
|
||||
if (field.type === 'boolean') {
|
||||
return `
|
||||
<label class="flex cursor-pointer items-center justify-between gap-4 rounded-xl border border-zinc-200 p-4 dark:border-zinc-700">
|
||||
<span>
|
||||
<strong class="block text-sm">${escapeHtml(field.label)}</strong>
|
||||
${help}
|
||||
</span>
|
||||
<input
|
||||
data-path="${escapeHtml(path)}"
|
||||
type="checkbox"
|
||||
value="1"
|
||||
${value === true || value === 1 || value === '1' ? 'checked' : ''}
|
||||
class="h-5 w-5 rounded border-zinc-400 text-orange-600 focus:ring-orange-500"
|
||||
>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
if (field.type === 'textarea' || field.type === 'richtext') {
|
||||
return `
|
||||
<label class="block text-sm font-medium">
|
||||
${escapeHtml(field.label)}
|
||||
<textarea
|
||||
data-path="${escapeHtml(path)}"
|
||||
class="mt-2 min-h-28 w-full rounded-lg border border-zinc-600 bg-zinc-950 p-3 text-zinc-100"
|
||||
>${escapeHtml(value)}</textarea>
|
||||
</label>
|
||||
${help}`;
|
||||
}
|
||||
|
||||
if (field.type === 'repeater') {
|
||||
return repeaterMarkup(
|
||||
field,
|
||||
Array.isArray(value) ? value : [],
|
||||
path
|
||||
) + help;
|
||||
}
|
||||
|
||||
let inputType = 'text';
|
||||
|
||||
if (field.type === 'number') {
|
||||
inputType = 'number';
|
||||
} else if (field.type === 'email') {
|
||||
inputType = 'email';
|
||||
} else if (field.type === 'url') {
|
||||
// Internal CMS links may be relative paths, anchors, mail links,
|
||||
// or complete external URLs. Browser type="url" rejects "/".
|
||||
inputType = 'text';
|
||||
}
|
||||
|
||||
const inputMode = field.type === 'url' ? 'url' : '';
|
||||
const placeholder = field.type === 'url'
|
||||
? '/, /blog, #section or https://example.com'
|
||||
: '';
|
||||
|
||||
return `
|
||||
<label class="block text-sm font-medium">
|
||||
${escapeHtml(field.label)}
|
||||
<input
|
||||
data-path="${escapeHtml(path)}"
|
||||
type="${inputType}"
|
||||
inputmode="${inputMode}"
|
||||
placeholder="${escapeHtml(placeholder)}"
|
||||
value="${escapeHtml(value)}"
|
||||
${field.min !== undefined ? `min="${escapeHtml(field.min)}"` : ''}
|
||||
${field.max !== undefined ? `max="${escapeHtml(field.max)}"` : ''}
|
||||
class="mt-2 w-full rounded-lg border border-zinc-600 bg-zinc-950 px-3 py-2 text-zinc-100"
|
||||
>
|
||||
</label>
|
||||
${help}`;
|
||||
}
|
||||
|
||||
function repeaterMarkup(field, items, path) {
|
||||
return `
|
||||
<section class="rounded-xl border border-zinc-600 p-4">
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 class="font-semibold">${escapeHtml(field.label)}</h3>
|
||||
<p class="text-xs text-zinc-500">
|
||||
Add, edit, reorder, hide or remove items.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
data-action="add"
|
||||
data-path="${escapeHtml(path)}"
|
||||
class="rounded-lg border border-zinc-500 px-3 py-1.5 text-sm hover:bg-zinc-800"
|
||||
>
|
||||
Add item
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3">
|
||||
${items.length
|
||||
? items.map((item, index) => `
|
||||
<article class="rounded-lg border border-zinc-700 bg-zinc-900 p-4">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-3">
|
||||
<strong class="text-sm">Item ${index + 1}</strong>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
data-action="up"
|
||||
data-path="${escapeHtml(path)}"
|
||||
data-index="${index}"
|
||||
class="rounded border border-zinc-600 px-2 py-1"
|
||||
aria-label="Move item up"
|
||||
>↑</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
data-action="down"
|
||||
data-path="${escapeHtml(path)}"
|
||||
data-index="${index}"
|
||||
class="rounded border border-zinc-600 px-2 py-1"
|
||||
aria-label="Move item down"
|
||||
>↓</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
data-action="remove"
|
||||
data-path="${escapeHtml(path)}"
|
||||
data-index="${index}"
|
||||
class="rounded border border-red-500 px-2 py-1 text-red-300"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
${(field.fields || []).map(child => `
|
||||
<div class="${['textarea', 'richtext', 'repeater'].includes(child.type) ? 'md:col-span-2' : ''}">
|
||||
${fieldMarkup(
|
||||
child,
|
||||
item?.[child.key] ?? defaultValue(child),
|
||||
`${path}.${index}.${child.key}`
|
||||
)}
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</article>
|
||||
`).join('')
|
||||
: `
|
||||
<p class="rounded-lg border border-dashed border-zinc-600 p-6 text-center text-sm text-zinc-500">
|
||||
No items. Select “Add item” to create one.
|
||||
</p>
|
||||
`}
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function currentSchema() {
|
||||
return normaliseSchema(rawSchemas[String(typeSelect.value)]);
|
||||
}
|
||||
|
||||
function render() {
|
||||
const schema = currentSchema();
|
||||
|
||||
status.textContent = schema.length
|
||||
? `${schema.length} editable field${schema.length === 1 ? '' : 's'}`
|
||||
: 'Schema unavailable';
|
||||
|
||||
if (! schema.length) {
|
||||
host.innerHTML = `
|
||||
<div class="rounded-xl border border-red-300 bg-red-50 p-4 text-sm text-red-800">
|
||||
This content type has no usable visual schema.
|
||||
Run <code>php artisan content:install-saasland</code> once.
|
||||
</div>`;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
hydrateMissingFields(schema, data);
|
||||
syncJson();
|
||||
|
||||
host.innerHTML = schema.map(field => fieldMarkup(
|
||||
field,
|
||||
data[field.key],
|
||||
field.key
|
||||
)).join('');
|
||||
}
|
||||
|
||||
host.addEventListener('input', event => {
|
||||
const element = event.target.closest('[data-path]');
|
||||
|
||||
if (! element || element.type === 'checkbox') {
|
||||
return;
|
||||
}
|
||||
|
||||
let value = element.value;
|
||||
|
||||
if (element.type === 'number') {
|
||||
value = element.value === '' ? null : Number(element.value);
|
||||
}
|
||||
|
||||
setAtPath(element.dataset.path, value);
|
||||
});
|
||||
|
||||
host.addEventListener('change', event => {
|
||||
const element = event.target.closest('[data-path]');
|
||||
|
||||
if (! element || element.type !== 'checkbox') {
|
||||
return;
|
||||
}
|
||||
|
||||
setAtPath(element.dataset.path, element.checked);
|
||||
});
|
||||
|
||||
host.addEventListener('click', event => {
|
||||
const button = event.target.closest('button[data-action]');
|
||||
|
||||
if (! button) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const schema = currentSchema();
|
||||
const action = button.dataset.action;
|
||||
const path = button.dataset.path;
|
||||
const field = fieldForPath(schema, path);
|
||||
const items = Array.isArray(getAtPath(path))
|
||||
? [...getAtPath(path)]
|
||||
: [];
|
||||
|
||||
if (action === 'add') {
|
||||
if (! field || field.type !== 'repeater') {
|
||||
return;
|
||||
}
|
||||
|
||||
items.push(newRepeaterItem(field));
|
||||
setAtPath(path, items);
|
||||
render();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const index = Number(button.dataset.index);
|
||||
|
||||
if (! Number.isInteger(index) || index < 0 || index >= items.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === 'remove') {
|
||||
if (! window.confirm('Remove this item?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
items.splice(index, 1);
|
||||
}
|
||||
|
||||
if (action === 'up' && index > 0) {
|
||||
[items[index - 1], items[index]] = [items[index], items[index - 1]];
|
||||
}
|
||||
|
||||
if (action === 'down' && index < items.length - 1) {
|
||||
[items[index], items[index + 1]] = [items[index + 1], items[index]];
|
||||
}
|
||||
|
||||
setAtPath(path, items);
|
||||
render();
|
||||
});
|
||||
|
||||
typeSelect.addEventListener('change', () => {
|
||||
data = {};
|
||||
hydrateMissingFields(currentSchema(), data);
|
||||
syncJson();
|
||||
render();
|
||||
});
|
||||
|
||||
dataField.addEventListener('change', () => {
|
||||
data = parseObject(dataField.value);
|
||||
render();
|
||||
});
|
||||
|
||||
form.addEventListener('submit', () => {
|
||||
syncJson();
|
||||
});
|
||||
|
||||
render();
|
||||
});
|
||||
</script>
|
||||
</x-layouts.app>
|
||||
@@ -0,0 +1,53 @@
|
||||
<x-layouts.app :title="__('Content documents')">
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<h1 class="text-2xl font-semibold">Content documents</h1>
|
||||
<p class="mt-1 text-sm text-zinc-500">Create and reuse typed content across page regions.</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<flux:button :href="route('content.pages.edit', 'home')">Compose homepage</flux:button>
|
||||
<flux:button variant="primary" :href="route('content.documents.create')">Create document</flux:button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if(session('status'))
|
||||
<div class="rounded-xl border border-green-300 bg-green-50 p-4 text-sm text-green-800 dark:border-green-800 dark:bg-green-950 dark:text-green-200">{{ session('status') }}</div>
|
||||
@endif
|
||||
@error('document')<div class="rounded-xl border border-red-300 bg-red-50 p-4 text-sm text-red-800">{{ $message }}</div>@enderror
|
||||
|
||||
<form method="GET" class="grid gap-3 rounded-xl border border-zinc-200 bg-white p-4 md:grid-cols-[minmax(12rem,1fr)_14rem_10rem_auto] dark:border-zinc-700 dark:bg-zinc-900">
|
||||
<flux:input name="search" label="Search" value="{{ request('search') }}" placeholder="Document title" />
|
||||
<flux:select name="type" label="Content type">
|
||||
<option value="">All types</option>
|
||||
@foreach($types as $type)<option value="{{ $type->key }}" @selected(request('type') === $type->key)>{{ $type->name }}</option>@endforeach
|
||||
</flux:select>
|
||||
<flux:select name="status" label="Status">
|
||||
<option value="">All statuses</option>
|
||||
<option value="draft" @selected(request('status') === 'draft')>Draft</option>
|
||||
<option value="published" @selected(request('status') === 'published')>Published</option>
|
||||
</flux:select>
|
||||
<div class="flex items-end gap-2"><flux:button type="submit">Filter</flux:button><flux:button :href="route('content.index')" variant="ghost">Reset</flux:button></div>
|
||||
</form>
|
||||
|
||||
<div class="overflow-hidden rounded-xl border border-zinc-200 bg-white dark:border-zinc-700 dark:bg-zinc-900">
|
||||
<table class="w-full text-sm">
|
||||
<thead class="bg-zinc-50 text-left text-xs uppercase text-zinc-500 dark:bg-zinc-950"><tr><th class="p-3">Document</th><th class="p-3">Type</th><th class="p-3">Status</th><th class="p-3">Uses</th><th class="p-3 text-right">Actions</th></tr></thead>
|
||||
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-800">
|
||||
@forelse($documents as $document)
|
||||
<tr>
|
||||
<td class="p-3"><div class="font-medium">{{ $document->title }}</div><div class="text-xs text-zinc-500">{{ $document->slug }}</div></td>
|
||||
<td class="p-3">{{ $document->type?->name }}</td>
|
||||
<td class="p-3"><span class="rounded-full px-2 py-1 text-xs {{ $document->status === 'published' ? 'bg-green-100 text-green-800 dark:bg-green-950 dark:text-green-200' : 'bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-200' }}">{{ ucfirst($document->status) }}</span></td>
|
||||
<td class="p-3">{{ $document->placements_count }}</td>
|
||||
<td class="p-3 text-right"><flux:button size="sm" :href="route('content.documents.edit', $document)">Edit</flux:button></td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr><td colspan="5" class="p-10 text-center text-zinc-500">No content documents match the current filters.</td></tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{{ $documents->links() }}
|
||||
</div>
|
||||
</x-layouts.app>
|
||||
@@ -0,0 +1,3 @@
|
||||
@if(app()->hasDebugModeEnabled())
|
||||
<!-- Unsupported content renderer: {{ $document->type?->renderer }} -->
|
||||
@endif
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Content\Http\Controllers\ContentDocumentController;
|
||||
use Modules\Content\Http\Controllers\PageCompositionController;
|
||||
|
||||
Route::middleware(['web', 'auth', 'verified'])->prefix('admin/content')->name('content.')->group(function (): void {
|
||||
Route::get('/', [ContentDocumentController::class, 'index'])->name('index');
|
||||
Route::get('/documents/create', [ContentDocumentController::class, 'create'])->name('documents.create');
|
||||
Route::post('/documents', [ContentDocumentController::class, 'store'])->name('documents.store');
|
||||
Route::get('/documents/{document}/edit', [ContentDocumentController::class, 'edit'])->name('documents.edit');
|
||||
Route::put('/documents/{document}', [ContentDocumentController::class, 'update'])->name('documents.update');
|
||||
Route::post('/documents/{document}/duplicate', [ContentDocumentController::class, 'duplicate'])->name('documents.duplicate');
|
||||
Route::delete('/documents/{document}', [ContentDocumentController::class, 'destroy'])->name('documents.destroy');
|
||||
|
||||
Route::get('/page/{page}/compose', [PageCompositionController::class, 'editPage'])->name('pages.page.edit');
|
||||
Route::get('/pages/{pageKey}', [PageCompositionController::class, 'edit'])->name('pages.edit');
|
||||
Route::get('/pages/{pageKey}/preview', [PageCompositionController::class, 'preview'])->name('pages.preview');
|
||||
Route::post('/pages/{pageKey}/placements', [PageCompositionController::class, 'store'])->name('placements.store');
|
||||
Route::put('/placements/{placement}', [PageCompositionController::class, 'update'])->name('placements.update');
|
||||
Route::delete('/placements/{placement}', [PageCompositionController::class, 'destroy'])->name('placements.destroy');
|
||||
Route::post('/placements/{placement}/duplicate', [PageCompositionController::class, 'duplicate'])->name('placements.duplicate');
|
||||
Route::post('/pages/{pageKey}/reorder', [PageCompositionController::class, 'reorder'])->name('placements.reorder');
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Content\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\View;
|
||||
use Modules\Content\Models\ContentDocument;
|
||||
use Modules\Content\Models\PageContent;
|
||||
use Throwable;
|
||||
|
||||
final class PageRenderer
|
||||
{
|
||||
public function hasComposition(string $pageKey): bool
|
||||
{
|
||||
try {
|
||||
return Schema::hasTable('page_content')
|
||||
&& PageContent::query()->where('page_key', $pageKey)->where('is_enabled', true)->exists();
|
||||
} catch (Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function renderRegion(string $pageKey, string $region): string
|
||||
{
|
||||
if (! $this->hasComposition($pageKey)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$preview = Route::currentRouteNamed('content.pages.preview');
|
||||
$placements = PageContent::query()
|
||||
->with('document.type')
|
||||
->where('page_key', $pageKey)
|
||||
->where('region', $region)
|
||||
->where('is_enabled', true)
|
||||
->where(fn ($query) => $query->whereNull('starts_at')->orWhere('starts_at', '<=', now()))
|
||||
->where(fn ($query) => $query->whereNull('ends_at')->orWhere('ends_at', '>', now()))
|
||||
->orderBy('sort_order')
|
||||
->get();
|
||||
|
||||
return $placements->map(function (PageContent $placement) use ($preview): string {
|
||||
$document = $placement->document;
|
||||
if (! $document || ! $document->type || ! $this->isRenderable($document, $preview)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$view = 'stylist-theme-saasland::documents.'.$document->type->renderer;
|
||||
if (! View::exists($view)) {
|
||||
$view = 'content::documents.unsupported';
|
||||
}
|
||||
|
||||
$rendered = View::make($view, [
|
||||
'document' => $document,
|
||||
'data' => $document->data ?? [],
|
||||
'placement' => $placement,
|
||||
'isCompositionPreview' => $preview,
|
||||
])->render();
|
||||
|
||||
if ($preview && $document->status !== 'published') {
|
||||
return '<div style="position:relative"><div style="position:absolute;z-index:1000;top:8px;right:8px;padding:5px 9px;border-radius:999px;background:#f59e0b;color:#111827;font:600 12px/1 sans-serif">Draft preview</div>'.$rendered.'</div>';
|
||||
}
|
||||
|
||||
return $rendered;
|
||||
})->implode("\n");
|
||||
}
|
||||
|
||||
private function isRenderable(ContentDocument $document, bool $preview): bool
|
||||
{
|
||||
if ($preview) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($document->status !== 'published') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($document->published_at?->isFuture()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! $document->expires_at?->isPast();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "Content",
|
||||
"alias": "content",
|
||||
"version": "1.0.0",
|
||||
"description": "Composable typed content documents and page regions.",
|
||||
"keywords": ["cms", "content", "regions", "composition"],
|
||||
"priority": 22,
|
||||
"providers": ["Modules\\Content\\Providers\\ContentServiceProvider"],
|
||||
"aliases": {},
|
||||
"files": [],
|
||||
"requires": ["Core", "Pages", "Stylist"]
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
<x-layouts.app :title="$document->exists ? $document->title : __('Create content document')">
|
||||
<div class="mx-auto max-w-7xl space-y-6" id="content-editor">
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<a href="{{ route('content.index') }}" class="text-sm text-zinc-500 hover:underline">
|
||||
Content documents
|
||||
</a>
|
||||
<h1 class="mt-1 text-2xl font-semibold">
|
||||
{{ $document->exists ? $document->title : 'Create content document' }}
|
||||
</h1>
|
||||
<p class="mt-1 text-sm text-zinc-500">
|
||||
Edit every frontend field below. JSON is retained only as an emergency advanced tool.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@if ($document->exists)
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<form method="POST" action="{{ route('content.documents.duplicate', $document) }}">
|
||||
@csrf
|
||||
<flux:button type="submit" size="sm">Create independent copy</flux:button>
|
||||
</form>
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ route('content.documents.destroy', $document) }}"
|
||||
onsubmit="return confirm('Delete this unplaced document permanently?')"
|
||||
>
|
||||
@csrf
|
||||
@method('DELETE')
|
||||
<flux:button type="submit" size="sm" variant="danger">Delete</flux:button>
|
||||
</form>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
@if (session('status'))
|
||||
<div class="rounded-xl border border-green-300 bg-green-50 p-4 text-sm text-green-800">
|
||||
{{ session('status') }}
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($errors->any())
|
||||
<div class="rounded-xl border border-red-300 bg-red-50 p-4 text-sm text-red-800">
|
||||
<ul class="list-disc pl-5">
|
||||
@foreach ($errors->all() as $error)
|
||||
<li>{{ $error }}</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($document->exists && $document->placements->count() > 1)
|
||||
<div class="rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900">
|
||||
<strong>Shared document.</strong>
|
||||
Changes affect all {{ $document->placements->count() }} placements.
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="{{ $document->exists ? route('content.documents.update', $document) : route('content.documents.store') }}"
|
||||
class="grid gap-6 xl:grid-cols-[minmax(0,1fr)_21rem]"
|
||||
id="document-form"
|
||||
>
|
||||
@csrf
|
||||
@if ($document->exists)
|
||||
@method('PUT')
|
||||
@endif
|
||||
|
||||
<div class="space-y-6">
|
||||
<flux:card class="space-y-5">
|
||||
<h2 class="text-lg font-semibold">Document</h2>
|
||||
<flux:input name="title" label="Internal title" value="{{ old('title', $document->title) }}" required />
|
||||
<flux:input name="slug" label="Slug" value="{{ old('slug', $document->slug) }}" />
|
||||
<flux:select name="content_type_id" label="Content type" id="content-type-select" required>
|
||||
@foreach ($types as $type)
|
||||
<option
|
||||
value="{{ $type->id }}"
|
||||
@selected((int) old('content_type_id', $selectedType?->id) === $type->id)
|
||||
>
|
||||
{{ $type->name }}
|
||||
</option>
|
||||
@endforeach
|
||||
</flux:select>
|
||||
</flux:card>
|
||||
|
||||
<flux:card class="space-y-5">
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold">Frontend content</h2>
|
||||
<p class="text-sm text-zinc-500">
|
||||
Switches take effect when this document is saved.
|
||||
</p>
|
||||
</div>
|
||||
<span id="schema-status" class="rounded-full bg-zinc-100 px-3 py-1 text-xs text-zinc-600"></span>
|
||||
</div>
|
||||
|
||||
<div id="schema-fields" class="space-y-5"></div>
|
||||
|
||||
<details class="rounded-xl border border-zinc-200 p-4 dark:border-zinc-700">
|
||||
<summary class="cursor-pointer text-sm font-medium">Advanced JSON (emergency use only)</summary>
|
||||
<p class="mt-2 text-xs text-zinc-500">
|
||||
Normal editing should be performed with the controls above.
|
||||
</p>
|
||||
<textarea
|
||||
id="data-json"
|
||||
class="mt-4 min-h-80 w-full rounded-xl border border-zinc-300 bg-white p-4 font-mono text-sm dark:border-zinc-700 dark:bg-zinc-950"
|
||||
name="data_json"
|
||||
spellcheck="false"
|
||||
>{{ old('data_json', json_encode($document->data ?: [], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) }}</textarea>
|
||||
</details>
|
||||
</flux:card>
|
||||
</div>
|
||||
|
||||
<aside class="space-y-6">
|
||||
<flux:card class="space-y-4">
|
||||
<h2 class="text-lg font-semibold">Publishing</h2>
|
||||
<flux:select name="status" label="Status">
|
||||
<option value="draft" @selected(old('status', $document->status ?: 'draft') === 'draft')>Draft</option>
|
||||
<option value="published" @selected(old('status', $document->status) === 'published')>Published</option>
|
||||
</flux:select>
|
||||
<flux:input
|
||||
type="datetime-local"
|
||||
name="published_at"
|
||||
label="Publish at"
|
||||
value="{{ old('published_at', $document->published_at?->format('Y-m-d\TH:i')) }}"
|
||||
/>
|
||||
<flux:input
|
||||
type="datetime-local"
|
||||
name="expires_at"
|
||||
label="Expire at"
|
||||
value="{{ old('expires_at', $document->expires_at?->format('Y-m-d\TH:i')) }}"
|
||||
/>
|
||||
<flux:button type="submit" variant="primary" class="w-full">Save document</flux:button>
|
||||
</flux:card>
|
||||
|
||||
@if ($document->exists)
|
||||
<flux:card>
|
||||
<h2 class="text-lg font-semibold">Usage</h2>
|
||||
<div class="mt-3 space-y-2">
|
||||
@forelse ($document->placements as $placement)
|
||||
<a
|
||||
class="block rounded-lg border p-3 text-sm"
|
||||
href="{{ route('content.pages.edit', $placement->page_key) }}"
|
||||
>
|
||||
<strong>{{ ucfirst($placement->page_key) }}</strong>
|
||||
<span class="block text-xs uppercase text-zinc-500">{{ $placement->region }}</span>
|
||||
</a>
|
||||
@empty
|
||||
<p class="text-sm text-zinc-500">Not placed on a page.</p>
|
||||
@endforelse
|
||||
</div>
|
||||
</flux:card>
|
||||
@endif
|
||||
</aside>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const rawSchemas = @json($types->mapWithKeys(fn ($type) => [(string) $type->id => $type->schema ?? []]));
|
||||
const dataField = document.getElementById('data-json');
|
||||
const host = document.getElementById('schema-fields');
|
||||
const typeSelect = document.getElementById('content-type-select');
|
||||
const status = document.getElementById('schema-status');
|
||||
const form = document.getElementById('document-form');
|
||||
|
||||
let data = parseObject(dataField.value);
|
||||
|
||||
function parseObject(value) {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) return value;
|
||||
try {
|
||||
const parsed = JSON.parse(value || '{}');
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function normaliseSchema(raw) {
|
||||
if (typeof raw === 'string') {
|
||||
try { raw = JSON.parse(raw); } catch (_) { return []; }
|
||||
}
|
||||
if (Array.isArray(raw)) return raw;
|
||||
if (!raw || typeof raw !== 'object') return [];
|
||||
if (Array.isArray(raw.fields)) return raw.fields;
|
||||
if (Array.isArray(raw.schema)) return raw.schema;
|
||||
return Object.values(raw).filter(field => field && typeof field === 'object' && field.key);
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '').replace(/[&<>"']/g, character => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
||||
})[character]);
|
||||
}
|
||||
|
||||
function get(path) {
|
||||
return path.split('.').reduce((value, key) => value?.[key], data);
|
||||
}
|
||||
|
||||
function set(path, value) {
|
||||
const parts = path.split('.');
|
||||
let target = data;
|
||||
parts.slice(0, -1).forEach(key => {
|
||||
if (target[key] === undefined || target[key] === null) {
|
||||
target[key] = /^\d+$/.test(parts[parts.indexOf(key) + 1] ?? '') ? [] : {};
|
||||
}
|
||||
target = target[key];
|
||||
});
|
||||
target[parts.at(-1)] = value;
|
||||
sync();
|
||||
}
|
||||
|
||||
function sync() {
|
||||
dataField.value = JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
function defaultValue(field) {
|
||||
if (Object.prototype.hasOwnProperty.call(field, 'default')) return field.default;
|
||||
if (field.type === 'boolean') return false;
|
||||
if (field.type === 'repeater') return [];
|
||||
return '';
|
||||
}
|
||||
|
||||
function fieldMarkup(field, value, path) {
|
||||
const help = field.help
|
||||
? `<p class="mt-1 text-xs text-zinc-500">${escapeHtml(field.help)}</p>`
|
||||
: '';
|
||||
|
||||
if (field.type === 'boolean') {
|
||||
return `
|
||||
<label class="flex items-center justify-between gap-4 rounded-xl border border-zinc-200 p-4 dark:border-zinc-700">
|
||||
<span>
|
||||
<strong class="block text-sm">${escapeHtml(field.label)}</strong>
|
||||
${help}
|
||||
</span>
|
||||
<span class="relative inline-flex h-6 w-11 shrink-0 items-center">
|
||||
<input class="peer sr-only" data-path="${escapeHtml(path)}" type="checkbox" ${value === true ? 'checked' : ''}>
|
||||
<span class="absolute inset-0 rounded-full bg-zinc-300 transition peer-checked:bg-blue-600"></span>
|
||||
<span class="absolute left-1 h-4 w-4 rounded-full bg-white transition peer-checked:translate-x-5"></span>
|
||||
</span>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
if (field.type === 'textarea' || field.type === 'richtext') {
|
||||
return `
|
||||
<label class="block text-sm font-medium">
|
||||
${escapeHtml(field.label)}
|
||||
<textarea data-path="${escapeHtml(path)}" class="mt-2 min-h-28 w-full rounded-lg border border-zinc-300 bg-white p-3 dark:border-zinc-700 dark:bg-zinc-950">${escapeHtml(value)}</textarea>
|
||||
</label>${help}`;
|
||||
}
|
||||
|
||||
if (field.type === 'repeater') {
|
||||
return repeaterMarkup(field, Array.isArray(value) ? value : [], path) + help;
|
||||
}
|
||||
|
||||
const type = field.type === 'number' ? 'number' : field.type === 'email' ? 'email' : 'text';
|
||||
return `
|
||||
<label class="block text-sm font-medium">
|
||||
${escapeHtml(field.label)}
|
||||
<input
|
||||
data-path="${escapeHtml(path)}"
|
||||
type="${type}"
|
||||
value="${escapeHtml(value)}"
|
||||
${field.min !== undefined ? `min="${escapeHtml(field.min)}"` : ''}
|
||||
${field.max !== undefined ? `max="${escapeHtml(field.max)}"` : ''}
|
||||
class="mt-2 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 dark:border-zinc-700 dark:bg-zinc-950"
|
||||
>
|
||||
</label>${help}`;
|
||||
}
|
||||
|
||||
function repeaterMarkup(field, items, path) {
|
||||
return `
|
||||
<section class="rounded-xl border border-zinc-200 p-4 dark:border-zinc-700">
|
||||
<div class="mb-4 flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 class="font-semibold">${escapeHtml(field.label)}</h3>
|
||||
<p class="text-xs text-zinc-500">Items can be reordered, hidden, or removed.</p>
|
||||
</div>
|
||||
<button type="button" data-add="${escapeHtml(path)}" class="rounded-lg border px-3 py-1.5 text-sm">Add item</button>
|
||||
</div>
|
||||
<div class="space-y-3">
|
||||
${items.length ? items.map((item, index) => `
|
||||
<article class="rounded-lg border border-zinc-200 bg-zinc-50 p-4 dark:border-zinc-700 dark:bg-zinc-900">
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<strong class="text-sm">Item ${index + 1}</strong>
|
||||
<div class="flex gap-2">
|
||||
<button type="button" data-up="${escapeHtml(path)}.${index}" class="rounded border px-2 py-1" title="Move up">↑</button>
|
||||
<button type="button" data-down="${escapeHtml(path)}.${index}" class="rounded border px-2 py-1" title="Move down">↓</button>
|
||||
<button type="button" data-remove="${escapeHtml(path)}.${index}" class="rounded border border-red-300 px-2 py-1 text-red-700">Remove</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
${(field.fields || []).map(child => `
|
||||
<div class="${child.type === 'textarea' || child.type === 'richtext' ? 'md:col-span-2' : ''}">
|
||||
${fieldMarkup(child, item?.[child.key] ?? defaultValue(child), `${path}.${index}.${child.key}`)}
|
||||
</div>`).join('')}
|
||||
</div>
|
||||
</article>`).join('') : '<p class="rounded-lg border border-dashed p-6 text-center text-sm text-zinc-500">No items. Select “Add item” to create one.</p>'}
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function render() {
|
||||
const schema = normaliseSchema(rawSchemas[String(typeSelect.value)]);
|
||||
status.textContent = schema.length ? `${schema.length} editable field${schema.length === 1 ? '' : 's'}` : 'Schema unavailable';
|
||||
|
||||
if (!schema.length) {
|
||||
host.innerHTML = `
|
||||
<div class="rounded-xl border border-red-300 bg-red-50 p-4 text-sm text-red-800">
|
||||
This content type has no usable visual schema. Run <code>php artisan content:install-saasland</code> once to refresh schemas without replacing content.
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
host.innerHTML = schema.map(field => fieldMarkup(
|
||||
field,
|
||||
Object.prototype.hasOwnProperty.call(data, field.key) ? data[field.key] : defaultValue(field),
|
||||
field.key
|
||||
)).join('');
|
||||
|
||||
bind();
|
||||
}
|
||||
|
||||
function bind() {
|
||||
host.querySelectorAll('[data-path]').forEach(element => {
|
||||
const eventName = element.type === 'checkbox' ? 'change' : 'input';
|
||||
element.addEventListener(eventName, () => {
|
||||
let value = element.type === 'checkbox' ? element.checked : element.value;
|
||||
if (element.type === 'number') value = element.value === '' ? null : Number(element.value);
|
||||
set(element.dataset.path, value);
|
||||
});
|
||||
});
|
||||
|
||||
host.querySelectorAll('[data-add]').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const schema = normaliseSchema(rawSchemas[String(typeSelect.value)]);
|
||||
const field = schema.find(candidate => candidate.key === button.dataset.add);
|
||||
const items = Array.isArray(get(button.dataset.add)) ? get(button.dataset.add) : [];
|
||||
const newItem = {};
|
||||
(field?.fields || []).forEach(child => newItem[child.key] = defaultValue(child));
|
||||
items.push(newItem);
|
||||
set(button.dataset.add, items);
|
||||
render();
|
||||
});
|
||||
});
|
||||
|
||||
host.querySelectorAll('[data-remove]').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
if (!confirm('Remove this item?')) return;
|
||||
const parts = button.dataset.remove.split('.');
|
||||
const index = Number(parts.pop());
|
||||
const path = parts.join('.');
|
||||
const items = Array.isArray(get(path)) ? get(path) : [];
|
||||
items.splice(index, 1);
|
||||
set(path, items);
|
||||
render();
|
||||
});
|
||||
});
|
||||
|
||||
host.querySelectorAll('[data-up], [data-down]').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const raw = button.dataset.up ?? button.dataset.down;
|
||||
const parts = raw.split('.');
|
||||
const index = Number(parts.pop());
|
||||
const path = parts.join('.');
|
||||
const items = Array.isArray(get(path)) ? get(path) : [];
|
||||
const destination = button.dataset.up !== undefined ? index - 1 : index + 1;
|
||||
if (destination < 0 || destination >= items.length) return;
|
||||
[items[index], items[destination]] = [items[destination], items[index]];
|
||||
set(path, items);
|
||||
render();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
typeSelect.addEventListener('change', () => {
|
||||
const schema = normaliseSchema(rawSchemas[String(typeSelect.value)]);
|
||||
const nextData = {};
|
||||
schema.forEach(field => nextData[field.key] = defaultValue(field));
|
||||
data = nextData;
|
||||
sync();
|
||||
render();
|
||||
});
|
||||
|
||||
dataField.addEventListener('change', () => {
|
||||
try {
|
||||
data = parseObject(dataField.value);
|
||||
render();
|
||||
} catch (error) {
|
||||
alert(`Invalid JSON: ${error.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
form.addEventListener('submit', sync);
|
||||
render();
|
||||
});
|
||||
</script>
|
||||
</x-layouts.app>
|
||||
Reference in New Issue
Block a user