refactor: implement Pinia store for stylesheet management

- Add Pinia state management
- Create centralized stylesheet store with utility methods
- Extract CSS parsing utilities to src/utils/css-parsing.js
- Refactor ElementPopup to manage state independently via store
- Simplify App.vue by removing prop drilling
- Fix iframe rendering with srcdoc instead of document.write
- Improve API: updateProperty uses object parameter for clarity

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
isUnknown 2025-11-24 17:55:42 +01:00
parent a627a14fa1
commit e8298a9fbf
7 changed files with 307 additions and 75 deletions

View file

@ -4,20 +4,17 @@ import EditorPanel from './components/EditorPanel.vue';
import StylesheetViewer from './components/StylesheetViewer.vue';
import ElementPopup from './components/ElementPopup.vue';
import { onMounted, ref, watch } from 'vue';
import { useStylesheetStore } from './stores/stylesheet';
const stylesheetStore = useStylesheetStore();
// Main state
const previewFrame = ref(null);
const stylesheetContent = ref('');
const aboutFontSize = ref(2);
const aboutFontSizeUnit = ref('rem');
// Popup state
const popupVisible = ref(false);
const popupPosition = ref({ x: 0, y: 0 });
const popupSelector = ref('');
const popupElementCss = ref('');
const popupFontSize = ref(null);
const popupFontSizeUnit = ref('rem');
// PagedJS print rules
const printStyles = `
@ -35,25 +32,6 @@ h2 { break-before: page; }
.chapter > h2 { string-set: title content(text); }
`;
// CSS parsing utilities
const extractCssBlock = (css, selector) => {
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const match = css.match(new RegExp(`${escaped}\\s*{[^}]*}`, 'gi'));
return match ? match[0] : '';
};
const extractCssValue = (css, selector, property) => {
const regex = new RegExp(`${selector}\\s*{[^}]*${property}:\\s*([\\d.]+)(px|rem|em)`, 'i');
const match = css.match(regex);
return match ? { value: parseFloat(match[1]), unit: match[2] } : null;
};
const updateCssValue = (selector, property, value, unit) => {
const regex = new RegExp(`(${selector}\\s*{[^}]*${property}:\\s*)[\\d.]+(px|rem|em)`, 'gi');
stylesheetContent.value = stylesheetContent.value.replace(regex, `$1${value}${unit}`);
};
// Iframe style injection
const injectStylesToIframe = () => {
const iframe = previewFrame.value;
if (!iframe?.contentDocument) return;
@ -64,10 +42,9 @@ const injectStylesToIframe = () => {
styleElement.id = 'dynamic-styles';
iframe.contentDocument.head.appendChild(styleElement);
}
styleElement.textContent = stylesheetContent.value;
styleElement.textContent = stylesheetStore.content;
};
// Popup handlers
const handleIframeClick = (event) => {
const element = event.target;
@ -81,17 +58,12 @@ const handleIframeClick = (event) => {
: `.${element.className.split(' ')[0]}`;
popupSelector.value = selector;
popupElementCss.value = extractCssBlock(stylesheetContent.value, selector);
const fontSizeData = extractCssValue(stylesheetContent.value, selector, 'font-size');
popupFontSize.value = fontSizeData?.value ?? null;
popupFontSizeUnit.value = fontSizeData?.unit ?? 'rem';
const rect = element.getBoundingClientRect();
const iframeRect = previewFrame.value.getBoundingClientRect();
popupPosition.value = {
x: iframeRect.left + rect.left,
y: iframeRect.top + rect.bottom + 5
y: iframeRect.top + rect.bottom + 5,
};
popupVisible.value = true;
@ -101,50 +73,41 @@ const closePopup = () => {
popupVisible.value = false;
};
const updatePopupFontSize = (newValue) => {
updateCssValue(popupSelector.value, 'font-size', newValue, popupFontSizeUnit.value);
popupFontSize.value = newValue;
popupElementCss.value = extractCssBlock(stylesheetContent.value, popupSelector.value);
};
// Watchers
watch(aboutFontSize, (newVal) => {
updateCssValue('.about', 'font-size', newVal, aboutFontSizeUnit.value);
stylesheetStore.updateProperty(
'.about',
'font-size',
newVal,
aboutFontSizeUnit.value
);
});
watch(stylesheetContent, injectStylesToIframe);
watch(() => stylesheetStore.content, injectStylesToIframe);
// Initial render
const renderPreview = async () => {
const iframe = previewFrame.value;
if (!iframe) return;
const response = await fetch('/assets/css/stylesheet.css');
stylesheetContent.value = await response.text();
await stylesheetStore.loadStylesheet();
const initialFontSize = extractCssValue(stylesheetContent.value, '.about', 'font-size');
const initialFontSize = stylesheetStore.extractValue('.about', 'font-size');
if (initialFontSize) {
aboutFontSize.value = initialFontSize.value;
aboutFontSizeUnit.value = initialFontSize.unit;
}
const contentSource = document.getElementById('content-source');
const iframeDoc = iframe.contentDocument;
iframeDoc.open();
iframeDoc.write(`
iframe.srcdoc = `
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/assets/css/pagedjs-interface.css">
<style id="dynamic-styles">${stylesheetContent.value}</style>
<style id="dynamic-styles">${stylesheetStore.content}</style>
<style>${printStyles}</style>
<script src="https://unpkg.com/pagedjs/dist/paged.polyfill.js"><\/script>
</head>
<body>${contentSource.innerHTML}</body>
<body>${document.getElementById('content-source').innerHTML}</body>
</html>
`);
iframeDoc.close();
`;
iframe.onload = () => {
iframe.contentDocument.addEventListener('click', handleIframeClick);
@ -167,17 +130,13 @@ onMounted(renderPreview);
<iframe ref="previewFrame" id="preview-frame"></iframe>
<StylesheetViewer :stylesheet="stylesheetContent" />
<StylesheetViewer :stylesheet="stylesheetStore.content" />
<ElementPopup
:visible="popupVisible"
:position="popupPosition"
:selector="popupSelector"
:elementCss="popupElementCss"
:currentFontSize="popupFontSize"
:fontSizeUnit="popupFontSizeUnit"
@close="closePopup"
@update:fontSize="updatePopupFontSize"
/>
</template>

View file

@ -10,15 +10,15 @@
</div>
<div class="popup-body">
<div class="popup-controls">
<div class="control" v-if="currentFontSize !== null">
<div class="control" v-if="fontSizeData">
<label>font-size</label>
<input
type="number"
step="0.1"
:value="currentFontSize"
@input="$emit('update:fontSize', parseFloat($event.target.value))"
:value="fontSizeData.value"
@input="updateFontSize(parseFloat($event.target.value))"
/>
<span>{{ fontSizeUnit }}</span>
<span>{{ fontSizeData.unit }}</span>
</div>
<p v-else class="no-styles">Aucun style éditable</p>
</div>
@ -31,27 +31,47 @@
<script setup>
import { computed } from 'vue';
import { useStylesheetStore } from '../stores/stylesheet';
import hljs from 'highlight.js/lib/core';
import css from 'highlight.js/lib/languages/css';
import 'highlight.js/styles/github.css';
hljs.registerLanguage('css', css);
const stylesheetStore = useStylesheetStore();
const props = defineProps({
visible: Boolean,
position: Object,
selector: String,
elementCss: String,
currentFontSize: Number,
fontSizeUnit: String
selector: String
});
defineEmits(['close', 'update:fontSize']);
defineEmits(['close']);
const elementCss = computed(() => {
if (!props.selector) return '';
return stylesheetStore.extractBlock(props.selector);
});
const fontSizeData = computed(() => {
if (!props.selector) return null;
return stylesheetStore.extractValue(props.selector, 'font-size');
});
const highlightedCss = computed(() => {
if (!props.elementCss) return '<span class="no-css">Aucun style défini</span>';
return hljs.highlight(props.elementCss, { language: 'css' }).value;
if (!elementCss.value) return '<span class="no-css">Aucun style défini</span>';
return hljs.highlight(elementCss.value, { language: 'css' }).value;
});
const updateFontSize = (value) => {
if (!fontSizeData.value) return;
stylesheetStore.updateProperty(
props.selector,
'font-size',
value,
fontSizeData.value.unit
);
};
</script>
<style scoped>

View file

@ -1,5 +1,8 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import './style.css';
import App from './App.vue';
createApp(App).mount('#app')
const app = createApp(App);
app.use(createPinia());
app.mount('#app');

38
src/stores/stylesheet.js Normal file
View file

@ -0,0 +1,38 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import cssParsingUtils from '../utils/css-parsing';
export const useStylesheetStore = defineStore('stylesheet', () => {
const content = ref('');
const loadStylesheet = async () => {
const response = await fetch('/assets/css/stylesheet.css');
content.value = await response.text();
};
const updateProperty = (selector, property, value, unit) => {
content.value = cssParsingUtils.updateCssValue({
css: content.value,
selector,
property,
value,
unit
});
};
const extractValue = (selector, property) => {
return cssParsingUtils.extractCssValue(content.value, selector, property);
};
const extractBlock = (selector) => {
return cssParsingUtils.extractCssBlock(content.value, selector);
};
return {
content,
loadStylesheet,
updateProperty,
extractValue,
extractBlock
};
});

75
src/utils/css-parsing.js Normal file
View file

@ -0,0 +1,75 @@
/**
* CSS parsing utilities for extracting and manipulating CSS rules
* @module css-parsing
*/
/**
* Extracts a complete CSS block for a given selector
* @param {string} css - The CSS stylesheet content
* @param {string} selector - The CSS selector to find (e.g., '@page', '.my-class')
* @returns {string} The matched CSS block including selector and braces, or empty string if not found
* @example
* const css = '@page { margin: 20mm; }';
* extractCssBlock(css, '@page'); // '@page { margin: 20mm; }'
*/
const extractCssBlock = (css, selector) => {
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const match = css.match(new RegExp(`${escaped}\\s*{[^}]*}`, 'gi'));
return match ? match[0] : '';
};
/**
* Extracts a CSS property value and its unit from a stylesheet
* @param {string} css - The CSS stylesheet content
* @param {string} selector - The CSS selector to search within
* @param {string} property - The CSS property name to extract
* @returns {{value: number, unit: string}|null} Object with numeric value and unit, or null if not found
* @example
* const css = '@page { margin: 20mm; }';
* extractCssValue(css, '@page', 'margin'); // { value: 20, unit: 'mm' }
*/
const extractCssValue = (css, selector, property) => {
const regex = new RegExp(
`${selector}\\s*{[^}]*${property}:\\s*([\\d.]+)(px|rem|em|mm|cm|in)`,
'i'
);
const match = css.match(regex);
return match ? { value: parseFloat(match[1]), unit: match[2] } : null;
};
/**
* Updates a CSS property value in a stylesheet
* @param {Object} options - Configuration object
* @param {string} options.css - The CSS stylesheet content to modify
* @param {string} options.selector - The CSS selector to target
* @param {string} options.property - The CSS property to update
* @param {number} options.value - The new numeric value
* @param {string} options.unit - The CSS unit (px, rem, em, mm, cm, in, etc.)
* @returns {string} The modified CSS stylesheet content
* @example
* updateCssValue({
* css: '@page { margin: 20mm; }',
* selector: '@page',
* property: 'margin',
* value: 30,
* unit: 'mm'
* }); // '@page { margin: 30mm; }'
*/
const updateCssValue = ({ css, selector, property, value, unit }) => {
const regex = new RegExp(
`(${selector}\\s*{[^}]*${property}:\\s*)[\\d.]+(px|rem|em|mm|cm|in)`,
'gi'
);
return css.replace(regex, `$1${value}${unit}`);
};
/**
* Collection of CSS parsing utilities
* @type {Object}
* @property {Function} extractCssBlock - Extract a CSS block by selector
* @property {Function} extractCssValue - Extract a property value with unit
* @property {Function} updateCssValue - Update a property value in CSS
*/
const cssParsingUtils = { extractCssBlock, extractCssValue, updateCssValue };
export default cssParsingUtils;